Compare commits

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

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

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

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 04:25:32 +03:00
Ateş b0b4f82f1d Merge pull request #712 from MacosPorters/track-a/run-diagnostics-input-asserts
[Boot] Scripted input and assert stepping for unattended target-build runs
2026-11-30 04:24:41 +03:00
ates 6e0b882691 Scripted input and assert stepping for unattended target-build runs
GameInput: BX_INPUT_SCRIPT presses gamepad buttons at given seconds,
without window focus, so an unattended run gets past screens that wait
for input. bx_runtime_veh: BX_CONTINUE_ASSERTS=1 steps over an int3 in
the title's own executable instead of letting it reach the crash
reporter, logging each address once and keeping the thread's last-error
value. Both are off unless set and documented with the other offline-run
diagnostics.

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 23:26:43 +01:00
ates 2dc58a3b25 Integrate main and address the DirectStorage remap guard review
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:58:28 +03:00
Bartosz Szczepański 8d7c3bf66c Merge remote-tracking branch 'origin/main' into track-c/get-frame-statistics-x
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 22:56:56 +01:00
Bartosz Szczepański 394525b8d0 Merge remote-tracking branch 'origin/main' into track-c/create-committed-resource-x
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 22:56:56 +01:00
Bartosz Szczepański 5acabd2f6e tests: D3DMetal capability checks for translated console shaders (#671)
test_d3dmetal_translator_caps measures, against the host D3D12 runtime: SM 6.6 descriptors fetched by index (runs correctly), a 64-lane wave emulated over a 64-thread group through groupshared memory and through merged host waves (workaround), and amplification and mesh shaders (runs correctly). With the 64-bit atomic results of test_d3dmetal_gpu_limits (workaround: native atomics are not run, the lock emulation is exact), no need is blocked. Results are recorded in docs/research/d3dmetal-gpu-limits.md.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 22:55:57 +01:00
Bartosz Szczepański 6957389fef tests: claim #671 D3DMetal capability checks for translated console shaders
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 22:49:49 +01:00
ates 147888c125 GameInput: expose a keyboard-backed gamepad
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:46:24 +03:00
ates d649610b7b Define the XMem remap guard contract
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:16:03 +03:00
ates 7f241ad170 Merge committed texture sizing into console profile fix
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:21 +03:00
ates 97947085bf Publish ConsoleMode before the guest starts
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:05 +03:00
ates f5aed211b5 Merge tested main into console profile registry fix
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:08:05 +03:00
Ateş 49e98cd684 Merge pull request #695 from 1Bartosz/track-c/console-texture-tile-size
[Boot] exit status 3 on the Series S path: committed render targets request host sizes, not console tile sizes
2026-11-30 00:07:24 +03:00
ates df7a83c734 Merge main into committed texture tile sizing
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:03:45 +03:00
Ateş 710103c70a Merge pull request #698 from MacosPorters/track-c/title-memory-geometry
[Picture] UI layer draws nothing: index and vertex data bound from plain title memory
2026-11-29 23:38:36 +03:00
ates bddd6f0030 Merge main into Track C title-memory geometry
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 23:35:14 +03:00
Ateş daca10b4fb Merge pull request #702 from MacosPorters/docs/own-translator
[Process] Roadmap: BetterXen writes its own shader translator
2026-11-29 23:29:09 +03:00
Ateş 441fec14c8 Merge pull request #697 from MacosPorters/track-c/rect-list
[Picture] half the screen missing: console rectangle lists
2026-11-29 23:28:51 +03:00
ates 9dd8f4f916 Merge remote-tracking branch 'origin/main' into track-c/rect-list
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 23:28:37 +03:00
Ateş c9388313e4 Merge pull request #694 from MacosPorters/track-a/clwb-flush-loop
[Boot] trap storm: CLWB range loop traps once per 64 bytes
2026-11-29 23:28:05 +03:00
ates 073aa40a97 Merge remote-tracking branch 'origin/main' into track-a/clwb-flush-loop
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 23:26:24 +03:00
ates 142fec28a2 Roadmap: BetterXen writes its own shader translator
The repository owner decided on 2026-11-29 not to use the upstream
emulator's translator. The Picture stage's translator step now
describes a translator of our own in shader-transpiler/: one rule per
instruction, registers as variables, control flow as numbered blocks in
a dispatch loop, each rule checked against the console compiler's
output for a shader of our own.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 23:25:53 +03:00
Bartosz Szczepański a1fcd96836 d3d12_xs: implement GetFrameStatisticsX
Slot 81 returned E_NOTIMPL. It now answers frame-event (ORIGIN) and present statistics per frame pipeline token for the last 17 frames, in QueryPerformanceCounter ticks, S_FALSE when nothing of the requested types is available and E_INVALIDARG for unknown tokens, invalid type sets and invalid list arrangements, as documented. Types with no host source are never reported.

Test: test_d3d12_frame_statistics_x; 14 of its checks fail on main.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 21:24:31 +01:00
Bartosz Szczepański 26003c37e2 d3d12_xs: claim: implement GetFrameStatisticsX
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 21:20:00 +01:00
Bartosz Szczepański 05b27f886f Merge origin/main into track-b/xmem-working-set-stats
CHANGELOG.md: keep both sides' Fixed entries, this branch's first.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 21:00:11 +01:00
ates 86ebd5c12c d3d12_xs: draw index and vertex data bound from plain title memory
On the console a GPU virtual address is the title's own address and the
GPU reads the memory when the commands execute. A title binds index and
vertex data it keeps in plain memory, with no Direct3D resource, and may
write it after recording the draw. Such bindings were left empty.

- bx_xbox_bind_title_memory (placed_x.cpp) finds the host buffer that
  holds the whole bound range, or creates a CPU-writable one for plain
  readable title memory, and records the range on the list.
- When a list is submitted, every range bound on it since its reset is
  copied from the title memory to its host buffer, before the host
  executes the list.
- Memory that is not readable still leaves the binding empty and is
  logged as unimplemented.

test_d3d12_title_memory_geometry draws an indexed triangle and a
non-indexed one (through a view that starts inside the same memory) from
VirtualAlloc memory written after the draws were recorded, then changes
the data and submits a second list: 26 of 26 checks by pixel readback,
twice in a row; against main's d3d12_xs the host never completes the
work. test_d3d12_unbacked_buffers now checks that plain memory is not
logged and that unreadable address space is, exactly once per binding.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 22:12:58 +03:00
Bartosz Szczepański 73cee37ee3 d3d12_xs: implement CreateCommittedResourceX
Slot 76 takes D3D12XBOX_RESOURCE_DESC, the PC resource description followed by DccOptions. It now creates the resource from the PC part through the CreateCommittedResource path, so console formats are translated and the XMemAlloc request is made; DccOptions has no host counterpart and is logged and ignored. The generator routes the slot; the regenerated table differs only in that slot.

Test: test_d3d12_committed_resource_x; it fails on main with E_NOTIMPL.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 20:03:48 +01:00
ates 10238c33b4 d3d12_xs: draw console rectangle lists as triangle strips
D3D_PRIMITIVE_TOPOLOGY_RECTLIST (17) and D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT
(19) are Xbox extensions: three vertices per rectangle, the fourth corner
v0 + v2 - v1. The host knows neither value; a title's full-screen passes
drew half a rectangle or nothing.

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 22:02:21 +03:00
Bartosz Szczepański 5a8aa63835 d3d12_xs: claim: implement CreateCommittedResourceX
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 20:00:39 +01:00
Bartosz Szczepański c0698e9fd4 Merge remote-tracking branch 'origin/main' into track-c/console-texture-tile-size
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 19:35:37 +01:00
Bartosz Szczepański 75f2ed8c3c Merge remote-tracking branch 'origin/main' into track-a/console-mode-registry
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 19:35:31 +01:00
Bartosz Szczepański 9f6fef064c Merge remote-tracking branch 'origin/main' into track-b/668-xmem-atomic-remap
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 19:35:24 +01:00
Bartosz Szczepański 94a22926d2 d3d12_xs: request console 64 KB tile sizes for committed render targets
The console lays out a 2D render-target or UAV texture with one mip and one sample in 64 KB tiles (64KB_R_X), and a title hooking XMemAlloc sizes its pool for those requests and asserts that less than 2 MB is left. The XMemAlloc request for those textures is now the tile size, from the title's format; other resources keep the host's size. Render-target compression metadata is not modelled.

Test: test_d3d12_committed_tile_size; three of its six cases fail on main.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:49:09 +01:00
Ateş f6bec97548 Merge pull request #693 from MacosPorters/track-c/unbacked-buffer-bindings
[Boot] null read in D3DMetal under IASetIndexBuffer: unbacked index and vertex bindings
2026-11-29 20:41:25 +03:00
ates 638673a173 Merge remote-tracking branch 'origin/main' into track-c/unbacked-buffer-bindings
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 20:41:08 +03:00
Bartosz Szczepański 1e0ffb642c Merge remote-tracking branch 'origin/main' into track-c/console-texture-tile-size
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:40:54 +01:00
Bartosz Szczepański b88fb86dbc d3d12_xs: claim: request console 64 KiB tile sizes for committed render targets
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:40:23 +01:00
Ateş 7feebe38f6 Merge pull request #690 from MacosPorters/track-c/console-only-formats
[Boot] Metal abort: console-only DXGI formats and depth-stencil unordered-access views
2026-11-29 20:40:14 +03:00
Bartosz Szczepański b8d709fed0 xmem: XMemGetWorkingSetStatistics follows the documented signature
The export took (out_stats, stats_size) and wrote BetterXen's own 32-byte
bx_xmem_stats_t. The authorized GDK header declares it as
(WorkingSetFlags, Statistics) with a 120-byte XMEM_WORKING_SET_STATISTICS,
so a title calling it as documented had its flags read as the output
address and the shim zeroed memory there.

The shim now takes the documented arguments and writes the whole
structure from xmem's own accounting: GameLimit is the title cap,
GameUsed everything the cap counts, GameUsedPeak its highest value and
GameAllocatedPhysicalPageCount the 64 KiB physical pages. Tools fields
are 0 since tools memory is unavailable; counters the host does not have
or xmem does not count are 0. A NULL structure or flags outside the five
XMEM_WORKING_SET_* values fail with ERROR_INVALID_PARAMETER.
bx_xmem_get_internal_stats keeps its contract for internal callers.

New test_xmem_working_set reads the structure between guard bands at
offsets written out from the header and fails against the previous
xmem.dll. test_xmem, test_xmem_physical, test_xmem_external_charge and
test_d3d12_placed use the documented form. test_xmem_physical reads its
two aliased page views through volatile, since the compiler cannot see
that they share a page and scheduled the read before the write.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:38:41 +01:00
ates f3eadff31c tests: conformance test for CLWB range loops
test_veh_clwb_loop runs its own machine-code loops (jbe with pointer
rcx and r9, jb with limit r10, an unaligned start with the limit inside
a line, a one-iteration range, a limit below the start, and a form with
a NOP that must keep the per-instruction path). It checks the final
pointer against the loop's definition, the number of illegal-instruction
exceptions, and that memory is unchanged.

Against main's handler the four loop cases take one exception per line
(1,000 to 12,345). 15 of 15 checks pass with the fix, twice in a row.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 20:32:18 +03:00
Bartosz Szczepański c4ceadc39e runtime_veh: publish the console type as ConsoleMode in the registry
A title can read the REG_DWORD ConsoleMode under HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM instead of calling XSystemGetDeviceType. Without it the title takes itself for a PC and sizes its memory for Series X, which does not fit the Lockhart budget. bx_runtime_veh.dll now writes 0x60 (Lockhart) or 0x64 (Anaconda) at attach, from the profile XSystemGetDeviceType answers from.

Test: test_console_mode; it fails on main because the key does not exist.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:20:18 +01:00
ates 00c270062b tests: conformance test for unbacked index and vertex bindings
test_d3d12_unbacked_buffers records into an Xbox-layout command list:
bindings inside a committed buffer (translated, not logged), an index
binding and the second of two vertex streams in plain title memory
(each left empty and logged as unimplemented exactly once), and null
bindings (unchanged, not logged). The list must still close.

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 20:19:39 +03:00
Bartosz Szczepański 00782e62e9 runtime_veh: claim: publish the console type in the registry
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 18:13:15 +01:00
Bartosz Szczepański 961cf7e26c xmem, xcrdapi: hold a remap guard while storing into a window that is being remapped (#668)
Windows and Wine cannot replace a mapped view in one step, so a thread storing into a neighbouring page while XMemMapPhysicalPages, XMemMapPhysicalPagesScatter or XMemFreePhysicalPages remaps a range faults in the gap. xmem.dll now exports bx_xmem_remap_guard_enter/_leave; the three calls wait for every open guard and XCRDAPI.dll holds it while it stores into a memory destination.

Tests: test_xmem_remap_guard and test_xcrdapi_remap_guard; both die in an access violation without the guard.
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-29 17:54:35 +01:00
ates 4389f74b2b d3d12_xs: leave index and vertex bindings empty when the address has no host buffer
A title binds index and vertex data by address in plain title memory,
with no Direct3D resource behind it. The address was passed to the host
unchanged and D3DMetal dereferenced the buffer it failed to find (a
null read under IASetIndexBuffer). Such a binding is now left empty and
logged as unimplemented. Supplying the data is separate work.

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

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

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

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

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 18:29:48 +03:00
ates 784e1ea439 runtime_veh: complete a CLWB range loop in one exception
A title flushes an address range with clwb [reg]; add reg, 0x40;
cmp reg, limit; jbe|jb. Each CLWB trapped, so a 6 MB range cost about
94,000 exception round trips. CLWB changes no register, flag or memory
content, so the handler now advances the pointer register to the last
value the loop would have used and lets the title's own add/cmp/jcc
leave the loop. Other forms keep the per-instruction path.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 13:00:39 +03:00
ates 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
Ateş b36e397681 Merge pull request #638 from MacosPorters/track-f/637-console-shader-abi
[M2-F17] docs: console compute shader entry ABI observed from the Series X|S compiler
2026-11-29 11:48:27 +03:00
ates 5bc4ff5cf4 Merge remote-tracking branch 'origin/main' into fix-638
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:48:08 +03:00
Ateş 5e204bd883 Merge pull request #662 from MacosPorters/docs/game-ladder-roadmap
[Process] Stage-based roadmap and the blocker queue: what an agent does when told "work"
2026-11-29 11:47:11 +03:00
ates 620019564b xgameruntime: restore the XUserDuplicateHandle implementation (#680)
The previous commit on this branch recorded main's com_dispatch.cpp and
xgameruntime.cpp by mistake (they had been restored into the index for
the negative-control run), which removed the fix and left only its
test. This puts the implementation back; it is the code the fixture was
built and run against.

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:38:36 +03:00
ates 29c8a29051 Merge remote-tracking branch 'origin/main' into track-e/680-xuser-duplicate 2026-11-29 11:37:55 +03:00
ates 6db66dc4a4 Merge remote-tracking branch 'origin/main' into track-a/665-clzero-loop 2026-11-29 11:36:35 +03:00
Ateş 5c2e2c9b63 Merge pull request #659 from MacosPorters/track-a/bringup-veh-diagnostics
[M2-A] runtime_veh: opt-in fault context, watches, breakpoints and sampler
2026-11-29 11:36:16 +03:00
ates 77dd9ffef3 Merge remote-tracking branch 'origin/main' into fix-659 2026-11-29 11:35:25 +03:00
Ateş abecde1c39 Merge pull request #635 from MacosPorters/track-a/634-veh-breakpoint
[M2-A16] runtime_veh: record breakpoints and assertion failures a guest crash reporter hides
2026-11-29 11:35:09 +03:00
ates e532fc56ba Merge remote-tracking branch 'origin/main' into fix-635
Signed-off-by: ates <ahmetrizaates@hotmail.com>

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

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

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

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

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

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 11:14:52 +03:00
ates 4c5cd55884 Merge remote-tracking branch 'origin/main' into docs/game-ladder-roadmap
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 11:11:08 +03:00
Ateş ec3dea9942 Merge pull request #661 from MacosPorters/track-f/bringup-review-process
[M2-F] docs: development cycle and review for target-build bring-up
2026-11-29 10:55:05 +03:00
ates 1fed04a80c Merge remote-tracking branch 'origin/main' into fix-661
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 10:51:45 +03:00
Ateş a9efeffc6f Merge pull request #658 from MacosPorters/track-e/bringup-xgameruntime
[M2-E] xgameruntime: offline XPackage installation monitor and enumeration
2026-11-29 10:51:22 +03:00
ates 365b411fed Merge remote-tracking branch 'origin/main' into fix-658
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 10:47:35 +03:00
Ateş 1b4b1bf7d7 Merge pull request #657 from MacosPorters/track-e/bringup-acphal
[M2-E] acphal: IAcpHal slot order and shape contexts
2026-11-29 10:47:06 +03:00
Ateş aeac1892c1 Merge pull request #656 from MacosPorters/track-c/bringup-xg-contract
[M2-C] xg_xs: the documented XG contract, replacing the clean-room interface
2026-11-29 10:46:44 +03:00
Ateş a9674bf9c7 Merge pull request #655 from MacosPorters/track-b/bringup-dstorage-queues
[M2-B] xcrdapi: zlib file requests and AutoSubmitDisabled on Xbox queues
2026-11-29 10:46:14 +03:00
ates eee9a4fcdc docs: how blockers are found once the target build runs
Working method: people play with recording on, agents replay short
routes through the input shim as ten-run regression tests, and picture
bugs are worked on from captured frames replayed offline. Lists the
signals a problem is recognised by and adds the three tools to the
starting queue.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:27:51 +03:00
ates fe28c5c2af docs: rework the proposal for an agent-driven team; stages replace milestone numbers
Collaborators work by telling a coding agent to "work", so the method
now answers what an agent does next without meetings or roles:
- AGENTS.md section 0 is rewritten as that instruction: preflight, then
  exactly one of own pull requests, review, one blocker of the current
  stage, or discovery; "work" authorizes commit, push and a pull request
  for the one item picked.
- docs/process/working-method.md: state lives in GitHub (a pinned ladder
  issue, one blocker issue per signature, claim comments, needs-human),
  the run protocol with per-session bottles and a machine-wide run lock,
  ranked sources of truth, the five-part pull request, and the starting
  queue.
- docs/roadmap.md: the ladder's rungs are named stages (Boot, Picture,
  Menus, World, Fidelity, Playable) instead of M3-M8.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:09:49 +03:00
ates e21f41ae24 docs: propose the game-ladder roadmap and the blocker-loop working method
docs/roadmap.md: M0-M2 become the foundation; M3-M8 are rungs the
project-authorized target build reaches (reliable boot, first correct
picture, front end, into the world, the world renders correctly,
playable), each judged on ten recorded runs on a 16 GB Mac, with
decision gates for the back end, reference images, memory and frame
rate, and a step-forward test for what belongs on main.

docs/process/working-method.md (proposed): the blocker loop, the run
protocol and run report, lanes beside tracks, ranked sources of truth,
one-blocker pull requests with a five-part description, the first two
weeks of work, and the AGENTS.md changes this needs. AGENTS.md itself
is not changed here.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 10:05:49 +03:00
ates 506defdd45 tests: AcpHal's 64 MB default APU heap in a fresh process
Review on #657: test_audio_input creates its own heap before allocating
shape contexts, so the default-heap branch never ran. The new fixture
allocates shape contexts with no ApuCreateHeap: 64 MiB + 64 bytes fails
with E_OUTOFMEMORY, exactly 64 MiB succeeds as an APU heap allocation,
a later ApuCreateHeap reports busy, and apu_default_heap is logged once.
A 32 MiB or 128 MiB default, or no default heap, each fail it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:15:33 +03:00
ates 64141e9ae6 Merge remote-tracking branch 'origin/main' into track-e/bringup-acphal
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:13:52 +03:00
ates 04148f77f8 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:06:54 +03:00
ates 5a6e786850 docs: console shader ABI review fixes: provenance, class U, NewBE scope
Review on #638:
- a Provenance section records the maintainer's statement that
  Microsoft's authorization covers publishing these derived observations,
  that the material is never committed, and that only a contributor with
  the same authorization can reproduce them;
- CLAIM-XBOX-CS-ENTRY-ABI moves from class A to U (no public source
  establishes it; not yet independently reproduced), names the NewBE
  backend, root buffer descriptors, and the exact host and tool versions;
- the page, changelog and index are scoped to the PIX/NewBE path; the ACO
  comparison cites #650, where it is recorded, instead of #647, and D2 is
  told the ABI is a candidate, not accepted;
- word 3 is decoded from the public GFX10 layout for both 0x11014fac and
  0x31016fac (FORMAT 20/22, OOB_SELECT 1/3), which also explains why the
  record count -1 disables the bounds check;
- eleven probes, not ten; table buffer descriptors 32 bytes apart;
  STRIDE bits 29:16; D3DMetal 4.0b3 named (3.0 not measured); wave64 as
  the default with no declared wave size; odd-SGPR alignment, the
  overflow threshold and ACCC-only output listed as open.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:06:54 +03:00
ates 34f744aa5d CHANGELOG: runtime_veh diagnostic hardening and fixture
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:04:44 +03:00
ates afc093ee54 Merge remote-tracking branch 'origin/track-a/634-veh-breakpoint' into track-a/bringup-veh-diagnostics 2026-11-29 07:03:55 +03:00
ates 224586917f runtime_veh, bx-cli trace: breakpoint record follow-ups from review
From the reviews on #635 (none blocking):
- log_breakpoint saves and restores the thread's last-error value, so a
  resumed first-chance exception leaves the guest's error state as it was
  (test_veh_breakpoint checks it; it fails without the restore);
- past the cap the counter is not advanced again, so it cannot wrap;
- bx-telemetry parses the record's address and bx-cli trace prints it,
  which locates a breakpoint outside any image (module ?);
- the cap note appears when any record reached the cap, not only the
  last line, since threads or processes can write records out of order.

Deduplicating repeated sites stays with #651.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:03:36 +03:00
ates 2af3e7d10a Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 07:02:00 +03:00
ates 17e2e2a835 runtime_veh: review fixes for the opt-in diagnostics; a fixture for them
Review on #659:
1. the AV context spec is scanned without strtok (no shared cursor
   across faulting threads);
2. every VirtualProtect is checked: a watch or range watch that cannot
   unprotect a page disarms, logs diagnostic_disarmed and passes the
   access violation on instead of looping; failed re-protection, code
   byte restores and int3 re-insertion are logged and disarm;
3. AV context and sampler lines use bounded appends (no length past the
   buffer), JSON-escape the spec and module names, and take module names
   through GetModuleFileNameW and UTF-8;
4. helper threads check a stop flag; detach disarms every diagnostic
   (pages, code bytes, TLS) without waiting, and keeps the log handle and
   lock alive while any helper was started;
5. BX_VEH_AV_CONTEXT/AV_ALL are read once at attach, so with them unset
   an access violation costs nothing;
6. bx-cli lets the named BX_VEH_* switches through its isolated guest
   environment (DIAGNOSTIC_ENV_ALLOWLIST), with a unit test that other
   variables and secrets still do not pass;
7. test_veh_diagnostics runs each mode in a child process (the switches
   are read at attach) and checks the log: no records when off; 16 capped
   av_context records from 4 threads, valid JSON with the spec escaped;
   a non-ASCII module name in UTF-8; one watched write with its value,
   and a failed protection change that disarms and reaches the guest; two
   code hits with a safe string argument; sampler records and a clean
   exit. 21 checks pass; the previous runtime_veh fails 6 of them.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 07:01:31 +03:00
ates 3ec40ba7fb docs: target-build review: recorded authorization, reproducible offline run
Review on #661:
- authorization is a recorded private note (build, evidence class,
  approving maintainer, lawful access, no circumvention); approval alone
  is not enough, and its ID goes into the PR template and every review;
- a reviewer needs their own recorded authorization for the same
  evidence class and re-derives from their own source;
- the ladder is renamed bring-up checkpoints and stated not to set
  milestone status, which only docs/roadmap.md defines;
- the offline run is copyable: wineserver restart, a curl probe that
  must print BLOCKED inside the profile, and the full bx-cli command
  with --exe, --profile and --inherit-env under env -i (and why);
  sandbox-exec's deprecation is noted;
- the diagnostics table lists only switches on main;
- the rules are cited from CONTRIBUTING.md and docs/legal.md, and the
  hash rule is narrowed to title-derived identifiers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:53:51 +03:00
ates b3aad0d948 Merge remote-tracking branch 'origin/main' into track-f/bringup-review-process
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:52:34 +03:00
ates 277edd592a Merge remote-tracking branch 'origin/main' into track-e/bringup-xgameruntime
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:51:07 +03:00
ates d4996ba9fd xgameruntime: installation monitors in the package state; enumerate this game
Review on #658:
- monitors move to package.cpp, into the mount handles' tagged table
  under mount_mutex: creation checks the runtime generation, rejects a
  null or foreign identifier, closing is idempotent, a closed or stale
  handle reports empty progress and registration on it fails with the
  stale-handle error, and the last uninitialize releases them;
- progress registration is logged as accepted and never fired, with a
  distinct token per registration; unregister reports whether the token
  existed;
- XPackageEnumeratePackages reports this game (its identifier, kind
  Game) for XPackageKind::Game, as documented for ThisOnly, and no
  packages for Content or PublisherContent; invalid kind/scope or a
  null callback is refused.

test_xgameruntime_saves covers slots 5-10 and 28/35/39 through the
public IXPackageImpl object: null and foreign arguments, the progress
values, tokens, double close, closed-handle behaviour, the registration
log record, enumeration per kind, and monitors made stale by
uninitialize.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:51:06 +03:00
ates ca2b48ef83 CHANGELOG: XG tiling per dimension and resource limits
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:45:39 +03:00
ates dc41f00cb3 Merge remote-tracking branch 'origin/main' into track-c/bringup-xg-contract 2026-11-29 06:45:31 +03:00
ates 1b04d6e237 xg_xs: review fixes: comments, 3D bounds, D3D12 limits, tiling per dimension
Review on #656:
- the header comments said other swizzle modes and multi-tile SW_64KB_S
  were refused; they are laid out linearly and reported as LINEAR;
- a 3D subresource past the mip count aliased onto mip 0 in
  CopyInto/FromSubresource; it is refused (E_INVALIDARG);
- XGCreateTextureComputer applies the public D3D12 limits (16384 for
  1D/2D, 2048 for 3D and array sizes) and a 64-bit bound for buffers,
  so widths are never truncated and pitches cannot overflow;
- GetResourceTiling uses the D3D12 standard 3D tile shapes (64x32x32
  one-byte elements down to 16x16x16) with depth tiles, a 64 KiB element
  row for 1D textures and 64 KiB for buffers, instead of 2D shapes.

test_xg_xbox (65 checks) adds hand-computed GetResourceTiling cases for a
2D array with a packed tail, a 3D texture and a 1D texture, the 3D copy
bound, the limits, AddRef/Release, IsTiledResource and the two E_NOTIMPL
methods. Each code fix is caught by the new checks when reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:45:31 +03:00
ates 9116c0a39e Merge remote-tracking branch 'origin/main' into track-b/bringup-dstorage-queues
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:41:34 +03:00
ates b96a9b5978 xcrdapi: a full AutoSubmitDisabled queue stalls until Submit
Review on #655: AutoSubmitDisabled only switched off the half-capacity
submit; a full blocking queue still submitted what was pending before
waiting, so commands ran before the title's Submit. A full queue now
submits by itself only when auto-submit is on. With it off, the enqueuer
waits until Submit is called on another thread and the drain frees a
slot, as DSTORAGE_QUEUE_OPTIONS documents.

test_xcrdapi_xbox fills a capacity-4 disabled queue from a worker
thread: the enqueue past its three slots waits, no destination changes
until Submit, Submit releases the waiter and every request then runs.
It fails with the old full-queue submit.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 06:41:34 +03:00
Ateş dcec248837 Merge pull request #660 from MacosPorters/track-c/bringup-xbox-first-frame
[M2-C] d3d12_xs: Xbox-layout objects through a target build's frame loop
2026-11-29 06:21:15 +03:00
ates 40b5ee7a8e Merge remote-tracking branch 'origin/main' into HEAD 2026-11-29 06:17:57 +03:00
Ateş b975e6335b Merge pull request #654 from MacosPorters/track-b/bringup-xmem-pages
[M2-B] xmem: page numbers in 4 KiB frames, run mapping, GPU-only windows
2026-11-29 06:17:51 +03:00
ates 8f4786e436 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-29 06:14:04 +03:00
Ateş 0c398214fa Merge pull request #645 from MacosPorters/track-c/644-xbox-device-tables
[M2-C14] d3d12_xs: Xbox-layout D3D12 objects, Phase 1 (ADR 0009)
2026-11-29 06:10:40 +03:00
ates 78b56747fb Merge remote-tracking branch 'origin/main' into HEAD 2026-11-29 06:06:38 +03:00
Ateş 63bd059182 Merge pull request #643 from MacosPorters/track-b/636-xmem-signatures
[M2-B6] xmem: follow the documented physical-page and XMemVirtualAlloc signatures
2026-11-29 06:06:24 +03:00
ates 24b124e144 Merge remote-tracking branch 'origin/main' into HEAD
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	tests/conformance/test_m2_first_frame/main.cpp
2026-11-29 06:05:20 +03:00
Ateş cff3e754a9 Merge pull request #640 from MacosPorters/track-c/639-xbox-create-device
[M2-C13] d3d12_xs: D3D12XboxCreateDevice takes the documented four parameters
2026-11-29 06:04:56 +03:00
ates 27bfa17cb1 xgameruntime: offline XPackage installation monitor and enumeration
The installation monitor reports the running package fully installed,
launchable and complete (progress never changes, so registered callbacks
are not called). XPackageEnumeratePackages succeeds offline and reports
no other packages. Both replace stubs a project-authorized target build
calls at startup. The save-container mount path ends with the drive-root
separator; test_xgameruntime_saves expects it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:45 +03:00
ates 261d71d8d1 docs: development cycle and review for target-build bring-up
How any number of contributors run a project-authorized target build
offline, turn each finding into a single-track PR with a conformance
test, and review it independently: roles, the cycle, a PR template,
what a reviewer re-derives, the offline-run procedure, the diagnostic
switches, and what never enters the repository.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:32 +03:00
ates 2cc64bd617 d3d12_xs: Xbox-layout objects through a target build's frame loop
On the Xbox-layout device: descriptor heaps with title-visible storage,
committed and placed resources in title memory with copy coherence,
samplers, page pools, pipelines through the shader gate, opt-in null
rendering (BX_NULL_RENDER=1), fences at GPU addresses, GPU value
writes, PresentX onto a DXGI swapchain, console page mappings
(CopyPageMappingsX/BatchX, ClearPageMappingsX) and the full 1384-byte
Xbox command-list area. BX_PRESENT_DUMP=<folder> dumps presented frames.

With the stacked xmem, XCRDAPI, XG, AcpHal and xgameruntime changes, a
project-authorized target build reaches its frame loop with null
rendering (thousands of frames). test_d3d12_xbox_layout checks the page
mappings (all four range types) and that writing every title-owned
command-list field leaves the list usable; each fails with its fix
reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:32 +03:00
ates d99e35ad42 acphal: IAcpHal slot order and shape contexts
IAcpHal is not COM (authorized GDK documentation): its slots are
Connect, Disconnect, SubmitCommand, PopMessage, GetNumMessages and
Release. AcpHalAllocateShapeContexts and AcpHalReleaseShapeContexts
allocate the documented SHAPE_CONTEXTS arrays from the APU heap, and a
second allocation fails with ACP_E_ALREADY_ALLOCATED; the default APU
heap is 64 MB. A project-authorized target build needs both to start.

test_audio_input checks the slots and the allocation lifecycle;
test_integration_boot releases IAcpHal through its sixth slot instead
of IUnknown::Release.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates f7748387da runtime_veh: opt-in fault context, watches, breakpoints and sampler
All off by default: BX_VEH_AV_CONTEXT / BX_VEH_AV_ALL log an access
violation's memory type, protection, allocation base and unwound stack;
BX_VEH_WATCH and BX_VEH_WATCH_RANGE watch writes to an address, a range
or a pointer chain; BX_VEH_HIT sets software code breakpoints that log
registers and string arguments; BX_VEH_SAMPLE samples every thread.
They were used to find the target build's startup blockers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 28a9c868e6 xg_xs: the documented XG contract, replacing the clean-room interface
xg_xs.dll now implements XGCreateTextureComputer and XGSuggestSwizzleMode
with the documented XG_RESOURCE_DESC and 14-method computer (authorized
GDK documentation): linear layouts by BetterXen's rule, single-tile
SW_64KB_S, other requested swizzles laid out linearly and reported as
LINEAR (refusing crashed a title that ignores the result), and
GetResourceTiling with standard tile shapes and a packed mip tail.

The clean-room xg_xs.cpp, xg_texture.h and test_xg_xs are removed.
test_xg_xbox (42 checks: 32 bpp offsets against the public D3D12
standard swizzle, 8- and 16-byte bijections, BC blocks, linear
fallbacks) replaces them; test_integration_boot stage 13 uses the
documented contract.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 6cfade83fe xcrdapi: zlib file requests and AutoSubmitDisabled on Xbox queues
Zlib requests now get the file handle (every compressed file request
failed), the Xbox request options are decoded and zlib streams inflated.
Xbox CreateQueueX honours DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled
(flags bit 0): such a queue runs nothing before Submit, so a title's
writes no longer land in pages it has not mapped yet; without the flag
the queue submits once half full. BX_DSTORAGE_TRACE=1 traces requests.

test_xcrdapi_xbox covers a file-source zlib request at an offset and
both queue behaviours; each check fails with its fix reverted.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates c963b9bc1a xmem: page numbers in 4 KiB frames, run mapping, GPU-only windows
Physical page numbers count 4 KiB frames (multiples of 16 for 64 KiB
pages, allocations aligned to 0x1000 frames): callers that keep
number >> 4 collapsed 16 consecutive numbers into one page. Pages are
mapped as runs, one view per run, which brought a project-authorized
target build's startup from 36 s to 6 s. Allocation goes through the
title's registered hooks; GPU-only large-page reservations become
mappable placeholders for console page mappings; BX_XMEM_TRACE=1 logs
allocations, frees and maps.

test_xmem_physical checks the page-number units (it fails with
kFramesPerPage = 1); test_xmem_hooks checks the hooks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:25:31 +03:00
ates 30197aa236 d3d12_xs: refuse Xbox-layout objects the host cannot back
bx_xbox_wrap returned the PC object when the host object lacked the
interface an Xbox table forwards to, and D3D12XboxCreateDevice then
logged device=xbox_function_tables and returned S_OK. On vkd3d, which
stops at ID3D12Device9, a title would have called Xbox slot numbers on
a PC table. The wrap now releases the object, logs xbox_wrap_refused and
fails with E_NOINTERFACE for every wrapped family; device creation and
QueryInterface pass that result on.

test_d3d12_xbox_layout verifies the refusal (E_NOINTERFACE, null out
pointer) on such a host and skips with exit 77; on D3DMetal it passes.
With the old fallback restored it fails on vkd3d.

ADR 0009 now states that the fixture's slot numbers come from the same
header as the generator, so it shows agreement, not correctness, and
records the frame-pacing limits (host Sleep, detached thread).

Addresses review points 2 and 4 on #645.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:11:02 +03:00
ates 957b8efb21 d3d12_xs: shadow resources for title-address placed resources (#644)
CreatePlacedResourceX and CreatePlacedResourceX1 place a resource at a
GPU address the title chose. D3DMetal cannot create a resource over
existing memory, so each gets a host shadow: buffers a committed buffer
in a CPU-visible write-back heap filled from the title's memory,
textures a committed texture (contents not filled, logged). The
resource reports the title's address from GetGPUVirtualAddress, and the
record is dropped when the resource is destroyed.

Ongoing synchronisation, GPU-to-CPU copies and address translation in
GPU calls are not implemented yet. test_d3d12_xbox_layout places a
buffer at a title address, checks the reported address and copies its
contents through the GPU.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates e04a3b3f62 d3d12_xs: Xbox-layout command lists and frame pacing, Phase 2 (#644)
Command lists become Xbox objects (ID3D12GraphicsCommandList8, 150
slots) created through CreateCommandListX or CreateCommandList. Their
Xbox field area (put buffer, CPU state, root packet headers) is zeroed,
so the inline fast paths fail their room checks and call through the
table. ResourceBarrier and CopyTextureRegion unwrap the interface
pointers inside their structures.

SetFrameIntervalX, ScheduleFrameEventX and WaitFrameEventX are
emulated from the recorded interval by a host timer that signals the
origin, vblank and flip events and hands out frame tokens.

The generator now handles CRLF lines, a table whose end the boundary
pattern ran past (it hid GraphicsCommandList1), nested SAL arguments and
FLOAT. test_d3d12_xbox_layout records a copy through Xbox command
objects, runs it on the GPU and checks frame pacing.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates ea29d3fc56 d3d12_xs: give titles Xbox-layout D3D12 objects, Phase 1 (#644)
A title built against the Xbox Series D3D12 header calls through
function tables whose slot order differs from PC D3D12, so the PC-layout
proxies sent its calls to the wrong methods. Titles (which set Version
in the device parameter block) now get BxXboxObjects: the Xbox object
layout with m_OutOfLineFlags set and Xbox-order tables that forward to
the existing PC proxies.

tools/gen_xbox_tables.py generates the tables from the Xbox header (slot
order, names, IIDs and types only; the header is not committed) and the
toolchain's <d3d12.h>: typed forwarders where the signatures match,
logged stubs otherwise. Phase 1 covers the device chain to Device11 and
the objects it creates, and implements CreateCommandQueueX. Command
lists follow in Phase 2.

ADR 0009 records the decision. test_d3d12_xbox_layout calls the Xbox
slots by number and fails against the previous DLL.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:08:07 +03:00
ates d724c6c013 xmem: accept MEM_64K_PAGES as the 64 KB physical-page flag
XMemAllocatePhysicalPages refused MEM_64K_PAGES, which Microsoft's
public samples pass for 64 KB pages: its MEM_PHYSICAL bit was outside
the accepted mask, and its MEM_2MB_PAGES bit reads as XMEM_2MB_CLUSTERS.
MEM_64K_PAGES is MEM_2MB_PAGES | MEM_PHYSICAL, so both bits together now
mean 64 KB pages; the 2 MB bit alone is still XMEM_2MB_CLUSTERS, which
stays unimplemented and logged.

test_xmem_physical adds the samples' shape: a MEM_64K_PAGES page mapped
into a mappable reservation made with PAGE_READWRITE |
PAGE_WRITECOMBINE | PAGE_GRAPHICS_READWRITE (0x2404). It passes on the
D3DMetal and vkd3d hosts and fails with the flag handling reverted.

Addresses review point 1 on #643; point 2 (graphics protection on
mapping) was fixed by the previous commit.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:07:21 +03:00
ates 43cb1aab54 xmem: title-managed placeholders and 32-bit graphics addresses (#636)
A title lays out its descriptor memory by reserving a placeholder with
XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
XMEM_GRAPHICS_32BIT_ADDRESS), splitting it with VirtualFree and
MEM_PRESERVE_PLACEHOLDER, and turning parts into mappable 64 KB ranges
with MEM_REPLACE_PLACEHOLDER | XMEM_MAPPABLE before mapping physical
pages in. All of that is documented; the shim stripped the placeholder
bits and made an ordinary reservation, so the split failed.

Placeholder reservations now honour the 32-bit address limit, a replaced
part is adopted as a mappable range if it is still a placeholder, and
PAGE_GRAPHICS_* protection bits are dropped for the host view. Replacing
a placeholder with committed memory stays a logged stub.
test_xmem_physical replays the sequence.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:05:28 +03:00
ates af869008a0 xmem: follow the documented physical-page and XMemVirtualAlloc signatures (#636)
The authorized GDK documentation gives XMemAllocatePhysicalPages(XMemFlags,
NumberOfPages, PageArray), XMemFreePhysicalPages(NumberOfPages, PageArray),
XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray),
XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)
and the five-argument XMemVirtualAlloc. A title calling them as documented
had its arguments misread, and its XMemAllocatePhysicalPages check broke
into its crash reporter.

Pages are 64 KB; the bandwidth values are accepted; 2 MB clusters and
2 MB-page mappings are stubs. XMEM_MAPPABLE reservations are placeholders
that pages map into, unmap back into, and can be remapped. Scatter
validates every entry before changing any. A NULL map address stays a
BetterXen extension for synthetic fixtures.

test_xmem_physical is rewritten against the documented contracts and
fails against the previous DLL; the other fixtures use the documented
signatures.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:05:28 +03:00
ates 8627285a59 tests: call D3D12XboxCreateDevice with its documented four parameters
test_d3d12_presentx, test_d3d12_vmem_xbox and test_m2_first_frame still
used the old three-argument form. They now pass a NULL adapter and a
zeroed parameter block (Version 0), which keeps the PC-layout proxy they
are written against (ADR 0009). All three pass on the D3DMetal backend.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:00:58 +03:00
ates aec6766b4d d3d12_xs: take the documented four D3D12XboxCreateDevice parameters (#639)
The documented form is (pAdapter, pParameters, riid, ppDevice); the shim
took (params, riid, ppv), so a documented call had its riid written
through as the out pointer. A NULL parameter block now fails with
E_INVALIDARG; a non-NULL adapter is logged and the default host adapter
used; only Version is read from the parameter block. Fixtures pass a
zeroed 80-byte block, and test_d3d12_xs checks the NULL refusal.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-29 05:00:40 +03:00
jelly013 84f4370227 Merge main into track-f/637-console-shader-abi
Resolve the CHANGELOG.md conflict under Added by keeping both sides.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-28 17:28:14 +01: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
ates 79e1906c27 docs: note that the console ABI probes describe the NewBE compiler path (#637)
The ACO compiler that emits ACCC containers generates different code for
the same HLSL; its root-buffer descriptor word 3 differs (#647).

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 19:01:10 +03:00
ates d65c12f6a9 Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 19:01:07 +03:00
Bartosz Szczepański b325320549 [M2-C10/C11] d3d12_xs: validate placement on every heap and all three CreatePlacedResource entry points (#554, #572)
CreatePlacedResource (slot 29) validated alignment, extent, buffer clear
value and the UPLOAD/READBACK initial state only on the backing heap.
CreatePlacedResource1 (ID3D12Device8 slot 70) and CreatePlacedResource2
(ID3D12Device10 slot 77) were generated pass-throughs with no validation
and no kPlacedResourceHeap retention, so the shim heap wrapper and its
xmem charge could be dropped while the placed resource was still alive.

All three now share create_placed_common in vmem.cpp. gen_proxy.py gains
a HANDOFF table so the generated slots 70/77 keep their trace and
null-host stub and pass the host interface and unmodified arguments to
vmem.cpp; proxy_generated.{h,cpp} are regenerated. No new vtable slot is
patched.

test_d3d12_placed adds misaligned, aligned-overhang, valid-offset and
UPLOAD-state cases on an ordinary heap for each entry point and runs the
heap-charge retention check through all three.

Closes #554
Closes #572

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 18:39:25 +03:00
atharvranjan 9f8b4c7f69 Merge pull request #646 from MacosPorters/track-e/xsystem-analytics-hdr
[M2-E7] xgameruntime: serve XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode
2026-11-28 09:17:40 -06:00
ates 2e5fbc70b1 xgameruntime: serve XSystemGetAnalyticsInfo and XDisplayTryEnableHdrMode through QueryApiImpl
A project-authorized target title requests both during System Init; they were logged as unsupported QueryApiImpl keys. The keys and vtable slots were derived from authorized GDK material; the function contracts follow the public XSystem.h and XDisplay.h documentation.

- XSystemGetAnalyticsInfo (slot 3, returns the 144-byte structure by value): family Xbox, a profile-dependent form, and a synthetic 10.0.26100.0 OS version.
- XDisplayTryEnableHdrMode (slot 4): Disabled, since BetterXen presents SDR. The optional luminance output is cleared.
- test_xgameruntime calls both through QueryApiImpl and checks the public contract.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 18:02:11 +03:00
ates 3f2f2732ed Merge origin/main into track-a/634-veh-breakpoint
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 17:49:29 +03:00
ates 7c807d8b3a runtime_veh: address jelly013's review of breakpoint logging
- Say precisely which guest handlers run after bx_veh_handler: the top-level filter and vectored handlers the guest registers last.
- Write module names as UTF-8 via GetModuleFileNameW and WideCharToMultiByte, so a non-ASCII name cannot make the JSONL line invalid.
- bx-telemetry parses record/limit, and bx-cli trace notes when the per-process cap was reached.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 17:49:28 +03:00
Ateş a2d153605d Merge pull request #534 from MacosPorters/track-c/465-presentx-timeout-budget
[M2-C2] Fix PresentX timeouts and post-present fence errors
2026-11-28 11:09:24 +03:00
ates 4a34ec3e50 Integrate main and fix PresentX timeout and recovery handling
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 11:04:23 +03:00
Ateş 2e96d93439 Merge pull request #592 from MacosPorters/track-c/vmem-xbox-config
d3d12_xs: add 32-byte Xbox decoder for D3D12ConfigureVirtualMemoryX
2026-11-28 10:47:39 +03:00
Ateş 30e666b86c Merge pull request #494 from MacosPorters/track-f/469-m2-first-frame-gate
Add end-to-end M2 first-frame conformance fixture
2026-11-28 10:46:04 +03:00
Ateş 41bc72887b Merge pull request #630 from MacosPorters/maint/finish-budget-hook
Finish the combined title budget hook and carry two reviewed PRs
2026-11-28 10:45:31 +03:00
ates c206a3f85d Merge current main into the virtual-memory integration
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:45:08 +03:00
ates c893436269 Combine the virtual memory decoder and shared budget logging
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:44:54 +03:00
Ateş 00b8344a40 Merge pull request #596 from MacosPorters/track-b/xcrdapi-xbox-dstorage
xcrdapi: add Xbox DirectStorage COM interfaces (IDStorage*X)
2026-11-28 10:43:23 +03:00
ates 451c6308c0 Preserve first-frame documentation while merging current main
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:42:40 +03:00
ates 4d69562b59 Merge current main into the combined budget hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:42:29 +03:00
Ateş 656eff8459 Merge pull request #628 from MacosPorters/track-a/627-xbox-drive-map
[M2-A15] bx-cli: map the Xbox title drives G: and T: before launch
2026-11-28 10:41:26 +03:00
Ateş 3ba0eb20d5 Merge pull request #626 from MacosPorters/maint/carry-reviewed-prs
Carry nine reviewed PRs whose head repositories were deleted
2026-11-28 10:41:13 +03:00
ates 8a00743d99 Leave unverified Xbox DirectStorage error output untouched
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:36:28 +03:00
ates ce1940d84c Merge current main into the virtual memory review update
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:35:34 +03:00
ates bd744727bd Validate BXVM inputs before read-only fallback
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:43 +03:00
ates b141c4b261 Count skipped graphics and xmem pairing checks
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:32 +03:00
ates c7a4b4cf19 Clarify conformance exit codes and evidence classes
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:31:32 +03:00
ates b88ea24a30 Guard the drive manifest temporary file and clarify fixture scope
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:29:37 +03:00
ates b2ae7a604e Merge current main and document the verified M2 pixel control
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 10:29:35 +03:00
Ateş 901b68ffba Merge pull request #471 from MacosPorters/track-c/465-d3d12-presentx
[M2-C2] Add D3D12 presentation bridge and verified frame conformance fixture
2026-11-28 09:59:09 +03:00
ates 3eb8900442 Merge origin/main into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	tests/conformance/test_audio_input/main.cpp
2026-11-28 09:39:15 +03:00
ates 335e3e4d60 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 09:38:48 +03:00
ates ca2ad143f9 docs: record the console compute shader entry ABI (#637)
Add the compute entry conventions observed from Microsoft's Series X|S
HLSL compiler, used under Microsoft's authorization, on eleven
project-authored probes: wave64 code, root data from s4 in parameter
order, the root-data address in s0:s1 on overflow, IDs after the root
data, inline root buffer descriptors without bounds, table descriptor
sizes and per-load binding metadata. Register roles are marked as
inferences. CLAIM-XBOX-CS-ENTRY-ABI (class A) records the measurement.
No compiler output, binary or documentation text is included.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:25:54 +03:00
Ateş c345ada8e9 Merge pull request #631 from elforeign/track-f/audio-input-log-required
[M2-F] test_audio_input: require BX_LOG_FILE instead of a temp log it can't fill
2026-11-28 09:24:57 +03:00
ates 3154497424 xcrdapi: address devil8blade's review of the Xbox DirectStorage adapters
- IDStorageFactoryX::SetStagingBufferSize logs that the size has no effect, as the public factory does, instead of 'accepted'.
- CreateQueueX documents that the queue priority is ignored on purpose: the Xbox range is not part of the inferred contract.
- test_xcrdapi_xbox requires BX_LOG_FILE and reads only what its own run appended.
- New error-path checks: a memory request on a file queue, a size mismatch, an out-of-range status index, and an enqueue after Close.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:22:06 +03:00
ates 6eaf8faa95 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:19:04 +03:00
ates 3c1ee93df5 Merge origin/main into track-a/627-xbox-drive-map
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:15:51 +03:00
ates 87a03d0421 bx-cli: write the drive manifest atomically and lock the prefix before staging
- write_manifest writes a temporary file and renames it over .bx-drives, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. New test: an interrupted write keeps the previous manifest, and the retry re-points g:.
- The prefix lock is taken before system32 staging, so a refused run has not touched the shared prefix. Runs sharing a prefix are serial, as the changelog now says.
- drives.rs and test_xbox_drives describe the G:/T: roles as an observation of one title plus an inference.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:15:51 +03:00
ates bf9dd7b383 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:11:25 +03:00
ates b59696975a Address devil8blade's review of the budget hook carry
- test_d3d12_placed: the 512 MiB pairing check prints SKIP with the command that runs it, instead of returning silently at other caps.
- vmem.cpp: the release_charge comment and the #552 changelog entry no longer claim the mirror check stops a double release while other heaps are alive. Each wrapper releasing once is what prevents that.
- vmem.cpp: the config log record's xmem_used= is renamed cap_used=, since it already includes graphics heaps.
- test_veh_clwb: parse record fields with a checked strtoull so a malformed record cannot throw.
- CHANGELOG: drop the stale overflow-guard and not-executed lines.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:11:25 +03:00
ates 43bb5636bf test_m2_first_frame: drain the GPU on failure, report the Present HRESULT, reject a malformed control value
- A GpuDrain guard declared just before ExecuteCommandLists signals the queue and waits (bounded) before the queue, back buffer and output resource are released after a failure.
- A failed PresentX reports its HRESULT instead of a fixed message.
- BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH must be unset or exactly 1. Any other value fails, so a mis-armed control cannot pass as an ordinary run, and an armed control is announced.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:05:28 +03:00
ates b7a660d4b9 Address devil8blade's review of the carried PRs
- test_win32_bridge: parse context= from the value, not the key, so the carried #520 round-trip check can pass (it read 0xc for every record).
- test_shader_gate: require every key before comparing positions; a missing hr= was npos and satisfied the order check.
- test_audio_input: a missing BX_LOG_FILE fails instead of printing SKIP and exiting 0.
- acphal: the zero-capacity comments no longer claim ApuAlloc accepted an allocation.
- bx-cli: tests/usage.rs runs the built binary and checks exit codes and output streams for the usage paths.
- CHANGELOG: getpgrp is Perl's built-in, and the new tests are recorded.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 09:04:11 +03:00
Eterna 10f78645cb win32_bridge: assert the PSM context pointer round-trips
context is observable in the JSONL. But the test only counted
callback_unfired records, so a dropped (context=0x0), swapped or
mis-tagged context would have passed unnoticed -- which makes the
storage decorative.

Parse context=0x<hex> out of the registration records (strtoull base
16; %llx prints lowercase with no leading zeros) and assert:

- every logged context on both families is non-zero and present in
  the set of &entry pointers the test passed;
- at least two distinct pointers appear per family, so one
  registration cannot overwrite another's stored context;
- each family's set covers the whole &entry set, which catches a
  swap or mis-tag between families;
- a record with a missing or malformed context= fails.

Limit, stated rather than asserted: the unregister records carry
only a detail string, so context-drop on unregister is not
observable in the log. The test documents that and prints a note if
a future shim starts logging context there.

Sits on #514, which introduces the context= field; rebases cleanly
once that merges. All existing checks kept and ANDed with the new
result. Cross-compiled and export-verified only; no live CrossOver
run.

Closes #519

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
(cherry picked from commit fa745d5211)
2026-11-28 09:01:48 +03:00
ates 8c4610b51c Merge origin/main into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:54:47 +03:00
ates 3b1d168de7 d3d12_xs: decode the documented Xbox virtual-memory configuration
Replace the inferred segment-count layout with
D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION as the authorized GDK
documentation describes it: flags, a GPU page-table size in 4 MB units
(clamped to 33), a frame-buffer preserve size (clamped to 64 MiB, -1
for the legacy size) and two output addresses. The decoder now writes
the outputs (minimum 2 GiB; maximum 159.375 GiB at the default size,
scaled linearly otherwise and logged as max_estimated=1) and fails with
E_FAIL once a device exists. It still only records the configuration
and keeps BX_STUB_LOG, since the host sizes no GPU page tables.

The fixture checks the documented values instead of the shim's own
constants and fails against the previous decoder.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:54:10 +03:00
Ateş 7a380bd3d7 Merge pull request #633 from EternaPeptix/track-f/632-heading-link-slugs
[M2-F17] docs_hygiene: slug a heading's rendered text, not its link URL
2026-11-28 08:51:26 +03:00
ates 931c09c6af xcrdapi: fill CommandType in the Xbox queue's error record
IDStorageQueueX::RetrieveErrorRecord left FirstFailure.CommandType zeroed. Share the public queue's command-kind mapping and fill it.

test_xcrdapi_xbox now asserts the error record for a rejected request and a rejected signal. DSTORAGE_COMMAND_TYPE_REQUEST is 0, so only the signal case tells a filled-in command kind from a zeroed one; it fails on the previous shim and passes now.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:39:49 +03:00
Eterna 186836e1d6 docs_hygiene: leave link syntax inside code spans literal
GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
the slug. Substituting links first changed `code-xy-span` to
`code-x-span`. Code spans are now set aside before the substitution
and restored afterwards.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:33:39 -07:00
ates 133ffd4c97 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:30:49 +03:00
atharvranjan 0d9997ce66 Merge origin/main into track-c/vmem-xbox-config
Resolve the CHANGELOG.md Added conflict by keeping both the #592
Xbox virtual-memory entry and main's #597 xcrdapi ABI entry. No
technical files changed in this merge.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:29:29 -06:00
ates bfbc84d251 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:27:31 +03:00
ates e96de7c455 Merge origin/main into track-a/627-xbox-drive-map
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:27:25 +03:00
atharvranjan 4b2985114a docs: clarify fixture skip and log evidence
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:26:25 -06:00
ates 0b474941f0 runtime_veh: record breakpoints a guest crash reporter hides (#634)
A guest with its own crash reporter replaces the top-level filter
installed at attach, so its assertions never reached
unhandled_exception. The vectored handler, which runs before any guest
handler, now records EXCEPTION_BREAKPOINT and STATUS_ASSERTION_FAILURE
as breakpoint_exception records with module name, base and RVA. They
are first-chance, handling is unchanged, and at most 16 are written per
process. bx-telemetry parses them and bx-cli trace lists them.

test_veh_breakpoint replaces the top-level filter, resumes from its own
vectored handler and checks the records against the RVA of a labelled
int3 site; it fails against the previous bx_runtime_veh.dll.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:26:19 +03:00
atharvranjan fe749b1436 fix(bx-cli): protect shared Xbox drive mappings
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:25:27 -06:00
Eterna b76066eafb docs_hygiene: slug a heading's rendered text, not its link URL
GitHub slugs the rendered heading, so an inline link contributes only
its text. Slugging the raw source appended the URL, which made a
heading with a link disagree with GitHub's anchor -- including
README.md:53 -- so the first real link to it would be reported as a
broken fragment.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:25:13 -07:00
atharvranjan b7bb7615d8 Merge origin/main into track-c/465-d3d12-presentx
Merge current main (2b2a9e15) with no manual conflict resolution; only
main's additions are brought in.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:20:46 -06:00
Ateş 2b2a9e15a6 Merge pull request #629 from EternaPeptix/track-b/597-xcrdapi-vtable-abi
validate: derive the xcrdapi public DirectStorage slot order and staged-copy fence lifetime (#597)
2026-11-28 08:18:03 +03:00
atharvranjan 3c65b393a4 Merge origin/main into track-c/465-d3d12-presentx
Resolve the proxy.cpp include conflict by keeping main's <vector> (stream
PSO gate) alongside this branch's <type_traits> and presentx.h.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:14:59 -06:00
Eterna 67f3b618ab test: verify xcrdapi public DirectStorage vtable ABI
Closes #597

Derives the public DirectStorage slot order from dstorage.h 1.4.0,
cross-checks it against Silk.NET, records the staged-copy lifetime
finding, and adds a test that calls every slot through a raw C vtable.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 22:13:07 -07:00
atharvranjan b0e40e29ea Merge remote-tracking branch 'origin/main' into pr592-technical-audit
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-27 23:12:23 -06:00
atharvranjan 90dc310b61 fix(d3d12): write VMEM output before applying config
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:11:05 -06:00
ates 4bf52b14a3 test_veh_clwb: require BX_LOG_FILE instead of a temp log it can't fill
The fixture imports bx_runtime_veh.dll, which reads BX_LOG_FILE once in DLL_PROCESS_ATTACH before main runs, so the temp-log fallback could never receive records. Fail with a clear message instead, as #631 does for test_audio_input.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:08:45 +03:00
ates bc7b622018 tmp
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:07:09 +03:00
atharvranjan d8fea7b351 Merge latest origin/main into Xbox drive mapping PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:06:48 -06:00
ates fe50a8edff Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:06:39 +03:00
atharvranjan d47eac809f test: avoid duplicate audio fixture log path
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:06:31 -06:00
atharvranjan 8db5552e32 Merge remote-tracking branch 'origin/main' into pr592-technical-audit
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-27 23:06:17 -06:00
Ateş 297251fb00 Merge pull request #611 from EternaPeptix/track-c/576-stream-pso-gate
[M2-C12] d3d12_xs: run stream pipeline states through the shader gate
2026-11-28 08:06:16 +03:00
atharvranjan 030c63f8c9 Merge origin/main into Xbox drive mapping PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:04:52 -06:00
atharvranjan 9a6f71abbc fix(bx-cli): record Xbox drive ownership before linking
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:04:35 -06:00
atharvranjan ad4bcc66b1 fix: correct carried PR claims and validate chunk offsets
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 23:03:56 -06:00
atharvranjan 3d244ddcb0 Merge remote-tracking branch 'origin/main' into maint/carry-reviewed-prs
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	launcher/crates/bx-cli/src/main.rs
#	tests/conformance/test_audio_input/main.cpp
2026-11-27 23:03:28 -06:00
ates b29ccc60e1 test_shader_gate: restore the wave64 refusal assertions from #609
The rebase onto main kept the pre-#609 assertions (wave64 PSO only printed, record expected as pass_dxil), so the fixture failed against main's shim. Restore #609's checks: the wave64 PSO returns E_NOTIMPL with no object, and the shader_gate record is reject_wave_wide. The stream PSO checks are unchanged.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 08:02:59 +03:00
ates 5f8235f607 Merge origin/main into track-c/576-stream-pso-gate
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 08:00:33 +03:00
Ateş c1b3edf9ba Merge pull request #621 from EternaPeptix/track-c/505-xg-sw64kb-s
[M3-C4] xg_xs: implement SW_64KB_S tiled layout from public AddrLib + D3D12 standard swizzle
2026-11-28 07:59:48 +03:00
Eterna 1eecf6a20c xg_xs: bound each copy offset by the buffer it belongs to
The CopyFromSubresource direction passes the caller's linear image as
`resource` and the tiled resource as `image`, so the old bounds check
compared the image offset against the tiled size. A short destination
with a wide row pitch passed and the copy wrote past the caller's
buffer. Bounds now follow the direction; test_xg_xs gains a
short-readback case that must return E_INVALIDARG.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:56:33 -07:00
elforeign ceaad9aee9 test_audio_input: require BX_LOG_FILE instead of a temp log it can't fill
When BX_LOG_FILE was unset, main created a temp file and set the
variable so the dispatcher log checks had something to read. That is too
late: AcpHal.dll imports bx_runtime_veh.dll, which reads BX_LOG_FILE once
in DLL_PROCESS_ATTACH before main runs. The temp file stayed empty and
the checks failed for the wrong reason.

Fail with a message naming the fix (run under bx-cli run --log) instead.
Also correct the comments that said the log checks catch a leaked
dispatcher: Release updates the counter before delete this, so a missing
delete this leaves the log unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-27 22:52:48 -06:00
ates 6bf2b9ab95 Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:50:24 +03:00
ates 527cd6208f Merge #540 into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:50:14 +03:00
Eterna 93a1f12bc6 docs_hygiene: detect the diff3 base marker and gate the unit tests
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
(cherry picked from commit ea9c883fcb)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:50:14 +03:00
Eterna 32b371e55f xg_xs: implement the SW_64KB_S BC family layout
Closes #505

Adds 8-byte (BC1/BC4) and 16-byte (BC2/3/5/6H/7) block addressing to the
SW_64KB_S tile math, and fixes the fixture that scaled every format by the
BC block dimension.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:49:59 -07:00
Eterna e48454bdd3 d3d12_xs: run stream pipeline states through the shader gate
Closes #576

Carries the ADR 0008 wording recording stream PSOs as covered
by the shader gate (#578).

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 21:49:06 -07:00
atharvranjan 55dfa39600 docs: document M2 pixel mismatch control
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 22:48:26 -06:00
ates c39d33821e xmem/d3d12_xs: apply review fixes to the external charge hook (#550, #552)
Apply the fixes 1Bartosz suggested on #551 and #553:

- Report external charges in XMemGetWorkingSetStatistics and
  bx_xmem_get_internal_stats so reported usage matches the cap.
- Refuse an over-release instead of zeroing other owners' charges.
- Log a failed bookkeeping refresh instead of reporting it as a budget
  rejection.
- Let the xmem hook alone admit graphics heaps; the local pre-check used a
  snapshot outside usage_lock and would count live heaps twice.
- Check the diagnostic mirror before crediting xmem on release.
- Add test_xmem_external_charge and correct the changelog entries.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:46:05 +03:00
Ateş e17a8281eb Merge pull request #609 from EternaPeptix/track-c/591-wave64-stance
[M3-D1b] d3d12_xs: refuse a wave wider than 32 lanes at PSO creation
2026-11-28 07:42:19 +03:00
ates 355197c4ac Merge origin/main into track-c/591-wave64-stance
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:40:24 +03:00
Ateş 01ef819910 Merge pull request #606 from EternaPeptix/track-a/590-trace-gap-detail
[M3-A1] bx-telemetry: group shader_d3dmetal_gap by (pso, stage)
2026-11-28 07:40:15 +03:00
ates 085e0d450e Merge origin/main into maint/finish-budget-hook
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:39:47 +03:00
ates 2d2ee990a7 Merge origin/main into track-a/590-trace-gap-detail
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:37:58 +03:00
Ateş 1f3e45eaf7 Merge pull request #622 from EternaPeptix/track-e/500-gameinput-dispatcher
[M2-E4] gameinput: implement IGameInput::CreateDispatcher and IGameInputDispatcher v0
2026-11-28 07:37:50 +03:00
ates a4742dd137 Merge origin/main into track-e/500-gameinput-dispatcher
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:35:13 +03:00
Ateş d5eb5ae97d Merge pull request #620 from EternaPeptix/track-a/507-bx-probe-hardening
[M2-A4] bx-probe: harden PE32+ parsing (wrapping offset, unvalidated section count) and add coverage
2026-11-28 07:35:05 +03:00
ates 2fc6c16f9d Merge origin/main into track-a/507-bx-probe-hardening
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:32:27 +03:00
Ateş cb6688c836 Merge pull request #619 from EternaPeptix/track-e/515-delayed-callback
[M2-E5] xgameruntime: XTaskQueueSubmitDelayedCallback ignores a non-zero delay and still returns S_OK
2026-11-28 07:32:19 +03:00
ates f1db93e2b4 Merge origin/main into track-e/515-delayed-callback
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:29:41 +03:00
Ateş 71fa30c29b Merge pull request #617 from EternaPeptix/track-f/527-bridge-export-check
[M2-F4] test_shim_exports: load bx_shader_bridge.dll so the fixture covers all 17 shipped DLLs
2026-11-28 07:29:33 +03:00
ates 050b0b279c Merge origin/main into track-f/527-bridge-export-check
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:27:17 +03:00
Ateş 162ed81eaf Merge pull request #616 from EternaPeptix/track-f/537-anchor-validation
[M2-F7] docs_hygiene: validate Markdown link fragments, not just the file they point at
2026-11-28 07:27:08 +03:00
ates dcd0a5127d Merge origin/main into track-f/537-anchor-validation
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:24:11 +03:00
Ateş f644569578 Merge pull request #613 from EternaPeptix/track-f/547-padded-vtable-slots
[M2-F11] test_d3d12_xs: check the padded vtable slot boundaries, the guard against console-only methods
2026-11-28 07:24:03 +03:00
ates 5b015a2b9e Merge origin/main into track-f/547-padded-vtable-slots
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:21:46 +03:00
Ateş 2549d724dd Merge pull request #624 from MacosPorters/fix/test-d3d12-placed-host-identity
Fix test_d3d12_placed device-host identity check
2026-11-28 07:14:42 +03:00
ates 9bcb121322 Merge origin/main into fix/test-d3d12-placed-host-identity
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:11:52 +03:00
ates 48378f8c35 bx-cli: map the Xbox title drives G: and T: before launch (#627)
An Xbox title opens its package on G: and writes crash logs to T:.
A Wine prefix has neither, so the title stops at startup. bx-cli run
now links dosdevices/g: to the executable's directory and t: to
drive_c/bx_temp. A .bx-drives manifest records the tool's own links;
a mapping it did not make is reported and left unchanged.

test_xbox_drives reads its own executable through G: and round-trips
a file on T:; it fails when G: is absent.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:06:03 +03:00
Ateş 88e6cf00b9 Merge pull request #602 from MacosPorters/track-d/dxbc-accc-nobc-header-only
[M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
2026-11-28 07:05:13 +03:00
ates 0521ea0c6c CHANGELOG: drop the duplicate #535 entry
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 07:01:52 +03:00
ates ce23d0b2b9 Merge #536 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates d17525c165 Merge #564 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 3cfb9ed690 Merge #556 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 51ac3bd766 Merge #522 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates e816c16495 Merge #514 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:52 +03:00
ates 076b354d61 Merge #533 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
#	launcher/crates/bx-cli/src/main.rs
2026-11-28 07:01:52 +03:00
ates 0bd188e602 Merge #510 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
ates b86be87576 Merge #581 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
ates 62290b2f21 Merge #560 into maint/carry-reviewed-prs
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 07:01:51 +03:00
Ateş 2d8685681b Merge pull request #610 from EternaPeptix/track-d/586-timeout-overflow
[M2-D6] d3dmetal-harness: saturate an overflowing timeout deadline
2026-11-28 06:56:41 +03:00
ates 25d5240dd0 Merge remote-tracking branch 'origin/main' into pr-610
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 06:52:58 +03:00
Ateş 97a2ad5d8b Merge pull request #612 from EternaPeptix/track-a/573-staging-manifest-orphan
[M2-A14] bx-cli: roll back a published shim when the manifest write fails
2026-11-28 06:52:33 +03:00
atharvranjan d93a3f3084 test(d3d12): fix placed host identity check
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 21:44:46 -06:00
atharvranjan 30c071845f Merge origin/main and enforce M2 first-frame gate
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 21:41:58 -06:00
atharvranjan 781f473ea3 fix(d3d12): safely probe virtual memory config
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 21:33:42 -06:00
Eterna 6b83bbbd8b gameinput: isolate the dispatcher log assertions (#504 review)
bx-cli run appends to the supplied BX_LOG_FILE, but the conformance
test read the ENTIRE file and only searched for the presence of
live_dispatchers=1/0 and the two modes. Re-running the fixture with
the same log could pass from stale lines even if this run emitted
none.

Capture the log's byte length before the run (log_file_size) and
assert only on the bytes appended by this run
(read_log_file_from(log_path, log_start)). The same offset-slicing
works whether the path came from the runner or from the temp file
the fixture creates when BX_LOG_FILE is unset.

Cross-compiled and export-verified only; live CrossOver execution
was not run on this host.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:10:26 -07:00
Eterna 9f81aadc49 gameinput: assert the dispatcher's live-reference count
devil8blade's review of #504 noted that removing `delete this` was
not caught by the tests: `Release` returning 0 proves the count
reached zero, not that the object was freed.

`dispatch_mode` already logs `mode=manual live_dispatchers=N` on
each transition, so the count IS observable -- the test just never
read it. It now reads the JSONL log and requires
live_dispatchers=1, live_dispatchers=0, mode=manual and
mode=automatic. A `delete this` removal that leaks the dispatcher
would leave live_dispatchers=1 behind and fail.

The fixture also creates its own temp BX_LOG_FILE at the top of
main() when the runner has not set one, so the assertions work
standalone instead of reading an empty file and failing for the
wrong reason.

Cross-compiled and export-verified only; no live CrossOver run on
this host.

Closes #500

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:07:14 -07:00
Eterna 724347fd98 gameinput: name the INFINITE-wait limit and soften the destruction claim (#504 review)
Two review findings on the dispatcher:

- OpenWaitHandle creates a non-signaled manual-reset event and this
  shim never signals it, since there is no background input work to
  make it ready. The code comment and the CHANGELOG now say that a
  caller waiting INFINITE blocks, and should poll with a timeout or
  call Dispatch instead. The request was to name the limits, not to
  change behaviour.
- The CHANGELOG claimed the test exercises 'dispatcher destruction at
  refcount zero'. The test asserts that the last Release returns 0,
  which is the refcount, not the deallocation. The wording now says
  exactly that.

No behaviour change; the shim still builds and GameInput.dll still
exports exactly GameInputCreate @1.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:07:04 -07:00
Eterna 6f588bc862 gameinput: implement IGameInput::CreateDispatcher and IGameInputDispatcher v0
Replace the E_NOTIMPL stub at IGameInput slot 14 with a real
IGameInputDispatcher object: IUnknown plus Dispatch and OpenWaitHandle
at slots 3 and 4, matching the public GameInput v0 contract on
Microsoft Learn (gdk-2610).

Dispatch returns false for every quota, including 0, because this
shim has no real background input work; the documented 'flush at
least one item even at quota 0' shape is honoured trivially and no
real work is implied. OpenWaitHandle returns a fresh manual-reset
event per call, caller-owned. QueryInterface serves only
IID_IUnknown: the v0 dispatcher IID is not published in the public
documentation, so no GUID was invented and other ids are logged.

A live dispatcher counter logs dispatch_mode on each manual and
automatic transition, matching the documented lifetime rule.

test_audio_input.exe now exercises slot 14 and the dispatcher slots.
GameInput.dll still exports exactly GameInputCreate @1.

Cross-compiled and export-verified only; the EXE was not run under
CrossOver on this host.

Closes #500

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 20:06:50 -07:00
ates 74fffaa350 Merge origin/main into track-b/xcrdapi-xbox-dstorage
Resolve the CHANGELOG conflict and reword the provenance of the Xbox
IDStorage*X contracts as inferences from call-site observation of a
project-authorized target build, pending maintainer review. No
behaviour change.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 05:56:04 +03:00
Eterna 23de596a23 bx-probe: validate the import data directory against its declared bounds
The import entry (data-directory index 1, an RVA/size pair) was read
without checking that it fits in SizeOfOptionalHeader, so a short
optional header made the read fall into the section table. The
descriptor walk was also only bounded by the containing section, so a
declared directory Size shorter than the section still reported
descriptors outside the directory.

Validate the index against NumberOfRvaAndSizes and the entry's 8 bytes
against SizeOfOptionalHeader before reading it. Bound the 20-byte
IMAGE_IMPORT_DESCRIPTOR walk by BOTH the declared Size and the
section's raw bytes, whichever ends first, stopping at a null
terminator or when the next descriptor would exceed the directory.

Add synthetic regressions for a short SizeOfOptionalHeader that puts
the entry out of range, NumberOfRvaAndSizes == 1, and a directory Size
shorter than the section.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:53:47 -07:00
Eterna 00e1b2fce9 xgameruntime: clamp Sleep chunks so INFINITE delays stay finite
delay_ms is a uint32_t, so 0xFFFFFFFF is a valid delay. When the
remaining time was exactly 0xFFFFFFFF, wait_until passed INFINITE to
Win32 Sleep, which waits forever: the loop never re-checked the
deadline and the callback never fired on the lanes that sleep out the
remainder themselves.

Factor the chunk calculation into finite_sleep_chunk_ms in
task_queue.h, which clamps every chunk to at most INFINITE - 1
(0xFFFFFFFE) and is always positive. The test asserts the clamp for a
0xFFFFFFFF remainder without waiting 49 days, and that a 0xFFFFFFFF
delay is accepted and its callback fires on the parallel and manual
lanes.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:53:40 -07:00
Eterna 846690befc docs: move the 17-DLL shim_exports claim to the unverified list
The reviewer's blocking evidence correction: the README placed the new
test_shim_exports.exe runtime claim under "Verified (local Apple M5,
... CrossOver 26.3)", but that fixture's 17-DLL / 28-check run was
never executed under CrossOver on this revision. Compiling and linking
the fixture, and scripts/build-shims.sh finding the bridge's three
exports, do not establish that LoadLibraryA/GetProcAddress passed for
bx_shader_bridge.dll.

The verified bullet now states only what was run: the 16 mingw-w64 C++
shim DLLs and their 25 runtime exports inside CrossOver/Wine. A new
"Not yet verified at runtime" bullet keeps the fixture description --
the added bridge entries, the 17-DLL / 28-check table, the counted
summary line -- and states plainly that the run is pending, that
compiling/linking/export agreement are not a runtime result, and that
the check would only show load-and-resolve, not that the bridge works
(test_shader_gate.exe covers that).

README only; no code, test or abi change.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:49:36 -07:00
atharvranjan 04ad81ee26 Merge branch 'track-c/465-d3d12-presentx' into track-c/465-presentx-timeout-budget
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:49:10 -06:00
atharvranjan e0f8b0e8f6 d3d12_xs: preserve device removal after Present and budget WaitForIdle before Signal
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:45:46 -06:00
atharvranjan 2fc82c4d58 d3d12_xs: distinguish post-present fence wait failures and require WaitForIdle
When wait_locked fails after a successful host Present and signal for a reason other than timeout, log the underlying wait HRESULT as present_next_buffer_wait_failed, require WaitForIdle to succeed before further Present calls (BX_PRESENT_E_NEEDS_IDLE), and return BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED (0x80040205) so callers can distinguish post-present wait failures from pre-present wait failures.

Update test_d3d12_presentx with test-side SetEventOnCompletion E_OUTOFMEMORY fault injection on both sides of host Present, verifying distinct return codes, host present counts, log records, and WaitForIdle recovery, plus a skip-wait-fault negative control in run_controls.sh.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 20:43:46 -06:00
Eterna c33199264a test_shim_exports: load bx_shader_bridge.dll, covering all 17 DLLs
The fixture that exists to prove every shipped shim loads and
resolves its exports covered 16 DLLs -- the mingw-w64 C++ shims --
and skipped bx_shader_bridge.dll, the Rust-built 17th DLL from
#484. That was the gap #526 documented.

Add the bridge's three frozen exports from
abi/defs/bx_shader_bridge.def: bx_shader_inspect,
bx_shader_prepare_for_d3dmetal and bx_shader_free_buffer. The
existing loop, failure counting and output format are untouched;
the table is simply extended, so all 25 previous checks stay.

The summary line now reports the DLL count as well as the check
count, computed from the table by a small DistinctDllCount helper
rather than hardcoded, so it cannot drift again. It prints
"PASS: test_shim_exports (28 checks verified across 17 shim DLLs)".

README updated to match: the fixture loads all 17 shipped DLLs and
resolves 28 runtime exports (25 + 3), keeping the distinction
between the 16 CMake-built shims and the 1 cargo-built bridge. It
also says plainly that this is a load-and-resolve check only and
does not show the bridge works -- test_shader_gate.exe exercises it
functionally.

abi/ unchanged. Verified on this revision: build-shims.sh ->
Verified 17 PE32+ shim DLLs (111 exact exports);
ls build-shims/bin/*.dll | wc -l -> 17; docs_hygiene 0 problems.
No live CrossOver run on this host.

Closes #527

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:40:03 -07:00
Eterna 82ec02e754 docs_hygiene: validate link fragments, not just the file
check_links() only confirmed that a relative link's target file was
tracked; a `#fragment` was never checked, so a link to a renamed or
reworded heading still passed the audit.

Add markdown_slugs(), which reproduces GitHub's heading-slug rules
(lowercase, drop punctuation, spaces to hyphens, underscore and hyphen
kept) and ignores headings inside fenced code blocks. Every link whose
target is a tracked Markdown file now has its fragment checked against
that file's headings; in-page `](#foo)` links are checked against the
same file. External URLs and bare `#` links are still not fetched.

Suffix generation tracks the set of slugs already emitted globally, not
just a count per base: for headings `Foo`, `Foo-1`, `Foo` the third
must be `foo-2`, because a literal `# Foo-1` heading already owns
`foo-1`. Counting identical bases alone handed the third heading
`foo-1` too, so the audit accepted a link to the wrong heading.

Covered by the new scripts/audit/test_docs_hygiene.py (23 tests), which
fails 3 tests against the previous counting-only suffix logic.

Closes #537

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:38:46 -07:00
Eterna 6cd94140b1 bx-probe: strengthen the defect tests so they discriminate
Two of the tests added in b15c33e passed against the ORIGINAL
parser, because their fixtures never reached the changed code. They
did not prove the fixes.

- bounds_unterminated_import_descriptor_walk now builds a
  two-section image: the descriptor section holds exactly two
  descriptors with no terminator, and a third valid descriptor sits
  just past the section boundary. The original parser imports
  THREE.DLL past the section; the fixed one stops at TWO.DLL.
- rejects_truncated_import_directory now truncates after two of the
  four data-directory bytes, which the original parser accepted as
  'no imports'. It also asserts the exact error variant.
- rejects_section_count_larger_than_file asserts the new
  'truncated section table' error rather than any error.

Verified by compiling the untouched original parser from
origin/main against the new test module: 4 of 10 tests fail
(wrap panic, section-table error mismatch, truncated import
accepted, THREE.DLL imported past the section). All 10 pass with
the fixes.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:23 -07:00
Eterna c08571ac74 bx-probe: bound the import descriptor walk by the section
The previous fix bounded the descriptor walk by the whole image size.
A section-bounded walk is more correct: an import directory that
starts inside a section must not read past that section's raw data,
even when the image has more bytes after it.

rva_to_off_bounded returns the mapped offset plus how many raw bytes
remain in the section, and the descriptor loop runs while at least 20
bytes remain. rva_to_off keeps its old signature for other callers.

Also drop the now-unneeded assert_eq! on the Result in the PE32
magic test (it compares the error variant directly), which removes
the PartialEq requirement the earlier test introduced.

All 10 bx-probe tests pass, and the wrap test still fails when the
u32 add is re-introduced.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:23 -07:00
Eterna d57aba26b9 bx-probe: harden PE32+ parsing and add real coverage
probe_pe32_plus parses attacker-controlled bytes and drives every
bx-cli import report and the system32 staging dependency walk, yet
it had no test at all (the crate's one test covered classify_dll).

Four defects fixed:

1. rva_to_off computed s.raw_ptr + delta as a u32 add, which wraps
   on a crafted image: 0xFFFFFFF0 + 0x20 -> 0x10, a byte offset near
   the start of the file instead of ~4 GiB. Now a checked 64-bit-safe
   add returning None on overflow.
2. Vec::with_capacity(section_count) allocated from an unvalidated
   u16 before the section table was bounds-checked. The table is now
   validated to fit first.
3. u32_le(...).unwrap_or(0) on the import data-directory read treated
   a truncated directory as 'no imports', indistinguishable from a
   genuine zero. Now a real error.
4. The import descriptor walk is bounded by the image size and by a
   checked desc_off increment, so a malformed table cannot run past
   the end of the image.

Nine new unit tests built from synthetic byte buffers: a minimal
valid PE32+, a two-DLL import table (one by name, one by ordinal),
truncation at every header boundary, a section whose raw_ptr would
wrap, section_count larger than the file, a PE32 image, and an import
directory outside all sections. The wrap test was confirmed to fail
when the u32 add is re-introduced and to pass with the fix.

PeSummary now derives PartialEq/Eq for the assertions. Every public
signature is unchanged for bx-cli; cargo test --locked --workspace
passes.

Closes #507

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:23 -07:00
Eterna de0d5bd7d9 xgameruntime: one queue per delay scenario, and assert no spin
The tests shared a single manual queue across scenarios. A 60 s
delayed task at the head then held the lane for every later case,
which made the FIFO and timeout assertions test the wrong thing.
Each scenario now creates and closes its own queue.

Also tightened while here: the finite-timeout case now submits a
2500 ms delay and asserts the 500 ms dispatch returns before the
deadline AND that the wall clock stayed under half the timeout, so
"did not spin" is checked rather than assumed. FIFO uses an explicit
OrderRecord so the order of the two callbacks is compared, not just
their counts. The context/cancelled case keeps the 0xA5 canary.

Margins are unchanged: 10 ms early / 250 ms late against a 100 ms
deadline.

Verified on a native harness that compiles the real task_queue.cpp
against a stub windows.h, since there is no CrossOver on this host:
all six scenarios pass, and a negative control with the delay
discarded fails exactly at the "not yet due" assert, so the tests
discriminate.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:16 -07:00
Eterna f48c42fd20 xgameruntime: gate every lane on the delay, not just dispatch
The first revision gated XTaskQueueDispatch only. Three other gateways
could still run a delayed callback early:

- the parallel/serialized threadpool worker, which popped and ran the
  head as soon as it was pushed;
- immediate mode, which ran the callback on the submitting thread
  without waiting out the deadline;
- a closed manual lane, which drains pending work on close.

All now wait out the deadline. schedule_serial() no longer requires
due() to schedule a worker: a delayed serial tail must still get a
worker that will wake for it, so the due check belongs in the worker,
not in the scheduling condition.

Every wait is saturating on due_ms - now, since the deadline can pass
between the check and the clock read and an unsigned wrap there would
block for ~584 million years.

The tests now cover what the first revision missed: context and
cancelled=true/false delivery checked with a canary, a dispatch
timeout shorter than the deadline ending on the timeout rather than
the deadline, FIFO (a later immediate task cannot overtake a delayed
head), close-before-due running the task as a cancel rather than a
normal run, and the pool path itself. Margins are 10 ms early /
250 ms late against a 100 ms deadline.

abi/defs/xgameruntime.def unchanged (49 exports). Cross-compiled and
export-verified only; no live CrossOver run.

Closes #515

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:16 -07:00
Eterna 2217eb83a1 xgameruntime: honour the delay in XTaskQueueSubmitDelayedCallback
core_tq_submit_delayed discarded delay_ms and fell through to
XTaskQueueSubmitCallback, which has no delay parameter, so the
callback ran on the next dispatch and the call still returned S_OK.
A caller scheduling a backoff or deferred teardown was told the delay
succeeded when it had not happened.

- Each queued task carries a GetTickCount64 deadline (Task::due_ms,
  zero meaning due now). XTaskQueueSubmitDelayedCallback sets it;
  XTaskQueueSubmitCallback forwards with delay_ms == 0, so the common
  immediate path is unchanged. Dispatch gates on the deadline: a
  delayed head holds FIFO order until it is due, and
  XTaskQueueDispatch waits exactly until that deadline (or the
  caller's timeout) rather than spinning.
- The log record now names the consequence ('queued delay_ms=N')
  instead of the old '(nonzero_delay)' text, which named only the
  symbol. It is emitted at INFO rather than as a stub warning, since
  the delay is now implemented.
- The wait computes due_ms - now, and the deadline can pass between
  the due check and the clock read; the subtraction is saturating,
  because an unsigned wrap there would block for ~584 million years.
- test_xgameruntime.exe reaches slot 19 through QueryApiImpl's
  IXGameRuntimeCore COM object (it is not an export) and checks that
  delay_ms == 0 still runs on the next dispatch, that a 100 ms delay
  does not run on a dispatch pass at ~0 ms or after a 10 ms sleep,
  and that it does run after a 250 ms sleep. Those margins are
  deliberately wide so a slow host is not flaky.

abi/defs/xgameruntime.def unchanged (49 exports); the delayed entry
point is a COM slot, not a new export. Cross-compiled and
export-verified only; no live CrossOver run.

Closes #515

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:37:16 -07:00
Eterna 63f5640a99 test_d3d12_xs: check the padded vtable slot boundaries
gen_proxy.py appends 32 BxBeyondPublicVtableNN stubs after each
generated proxy's public vtable (PAD_SLOTS = 32) so a caller
indexing past the interface it was handed lands on a logged
E_NOTIMPL stub instead of unrelated memory. That is the guard for
exactly the console-only-method case, and no fixture called one:
grepping the test for E_NOTIMPL, beyond_public or pad returned
nothing. So the E_NOTIMPL return, the log record, and the presence
of the 32 slots were all unverified -- the generator could have
stopped emitting them and no test would have noticed.

Indices derived from the generated code, not guessed: device 79,
queue 19, allocator 9, list 81. Cross-checked by parsing
proxy_generated.cpp for the BX_VTABLE_STUB_LOG("<leaf>", N u,
"beyond_public_vtable") calls: all four have exactly 32.

Coverage is boundary-only: for each of the four proxies the fixture
calls just the first (BxBeyondPublicVtable00) and last
(BxBeyondPublicVtable31) padded slot -- 8 calls in total, not all
128 -- and requires E_NOTIMPL without a crash, plus a BX_LOG_FILE
unimpl_vtable record naming the slot and beyond_public_vtable. If
BX_LOG_FILE is unset the log check skips, matching the fixture's
existing behaviour.

abi/ and gen_proxy.py unchanged. test_d3d12_xs.exe was NOT executed:
no CrossOver on this host.

Closes #547

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:35:23 -07:00
Ateş 4509911df0 Merge pull request #605 from MacosPorters/docs/trim-provenance-rules
docs: remove provenance-first and never-obtain bullets from AGENTS.md
2026-11-28 05:18:57 +03:00
Eterna 76c81468c7 d3dmetal-harness: give the probe no deadline when the timeout is unrepresentable
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:16:29 -07:00
Eterna f3976b24f4 d3dmetal-harness: saturate an overflowing timeout deadline
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:16:29 -07:00
Eterna 0f5a2ab6fd bx-cli trace: say kind/stage, not pipeline identity
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:14:18 -07:00
Eterna 987b404a4e bx-cli: snapshot the replaced file before publishing
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:13:16 -07:00
Eterna fa06be79b7 bx-cli: roll back a published shim when the manifest write fails
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:12:00 -07:00
ates 427f1b6cfa docs: remove remaining provenance and legal-boundary rules
Complete the policy trim started in baced397 by removing §4's third-party
licensing and proprietary-component rules, §6's Conditions for target
builds (including the unknown-condition stop rule), the Repository &
clean-tree boundary and Legal boundary. §4 is left as a placeholder
pending the replacement policy; the §6 authorized-evidence and §5
honesty rules remain. CHANGELOG records that other project documents
still describe the previous policy.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 05:11:52 +03:00
Eterna 56a27dfd80 d3d12_xs: keep the wave64 gap record shape and refresh the fixture
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:08:47 -07:00
Eterna 8d904a7f69 d3d12_xs: refuse a wave wider than 32 lanes at PSO creation
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:08:47 -07:00
Eterna 1300eb7892 bx-telemetry: make the (pso, stage) grouping test discriminate
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:07:52 -07:00
Eterna 1894ef23b7 bx-telemetry: group shader_d3dmetal_gap by (pso, stage) (#590)
Extend the bx-cli trace shader_d3dmetal_gap summary with an additive
grouped view: one entry per distinct (pso, stage) pair, in deterministic
first-seen order, reporting the group's count plus every distinct
(wave_lanes_min, atomic64_flags) constraint set. The #496 per-record
list and every existing summary line are unchanged.

A record with a missing or empty pso, stage, wave_lanes_min or
atomic64_flags is grouped under 'unknown' and counted (gaps w/o
pso/stage, gaps w/o constraints) rather than dropped or guessed; nothing
panics.

The summary only reflects records a run wrote; it adds no live run.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 19:07:52 -07:00
ates baced39764 docs: remove provenance-first and never-obtain bullets from AGENTS.md
Remove the "Provenance first" bullet from section 4 and the "Never
obtain or use" bullet from section 6. The section 6 conditions for
target builds and the repository clean-tree boundary are unchanged.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 04:57:54 +03:00
atharvranjan 989abbdc2c [M2-D] dxbc-accc: deduplicate DXIL state and add NOBC bounds tests
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:29:56 -06:00
atharvranjan 140dce0be1 Merge remote-tracking branch 'origin/main' into track-d/dxbc-accc-nobc-header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 19:27:40 -06:00
ates 1b25f3422b Merge origin/main into track-f/469-m2-first-frame-gate
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 03:47:21 +03:00
ates 766055e948 Merge origin/main into track-c/vmem-xbox-config
Signed-off-by: ates <ahmetrizaates@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 03:47:21 +03:00
Ateş 2faadeef7e Merge pull request #600 from MacosPorters/docs/merge-eligibility-policy
Clarify pull request merge eligibility
2026-11-28 03:32:26 +03:00
atharvranjan ce5968a2db Merge pull request #601 from 1Bartosz/track-d/599-fspx-layout-mismatch
[M3-D2] dxbc-accc: report an FSPX layout mismatch apart from out-of-bounds (#599)
2026-11-27 18:30:40 -06:00
atharvranjan 494e53b8fb [M2-D] dxbc-accc: treat NOBC DXIL chunks as header-only
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:29:50 -06:00
ates 54b87f613c test_m2_first_frame: fence the readback, name config fields, state limits
Wait on a queue fence before the CPU reads the backing map instead of
relying on WaitForIdle alone, assign the BXVM config by field name so a
reorder in vmem.h cannot compile silently, tie the expected pixel formula
to fill_cs66.hlsl, and record the fixture's limitations in its header.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:28:58 +03:00
ates bbd3b8a9d4 Merge origin/main into track-c/vmem-xbox-config
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:26:21 +03:00
ates 32d02efc33 d3d12_xs: record the Xbox vmem block without claiming it applied
Nothing consumes the decoded virtual-segment count yet, so the Xbox path
now logs vmem_config_recorded (applied=0 recorded_only=1), keeps
BX_STUB_LOG, and leaves the BXVM record and its cached backing heap
alone instead of evicting it.

Name the source of the layout as a project-authorized target build with
provenance pending review, and have the fixture read only the log bytes
appended by each step, so fixtures sharing one log cannot satisfy or
break its checks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 03:26:08 +03:00
atharvranjan ac82a55039 Keep PresentX test hook table alive on failure
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:19:39 -06:00
Bartosz Szczepański d6586b1fa3 docs: name FspxLayoutMismatch where ADR 0008 and the roadmap cite the FSPX scan (#599)
ADR 0008 and the roadmap (#588) say dxbc-accc rejects the 29 scanned
FSPX containers with FspxSectionOutOfBounds. The cause they record, a
descriptor offset inside the reserved header-plus-table region, is
FspxLayoutMismatch after this branch. Both now say which error the scan
saw, which one the same cause maps to now, and that the scan was not
re-run. The C ABI still returns BX_SHADER_ERR_INVALID_BLOB for both.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 01:10:37 +01:00
Bartosz Szczepański ceb1095139 Merge remote-tracking branch 'origin/main' into track-d/599-fspx-layout-mismatch
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-28 01:10:37 +01:00
atharvranjan e40d7293f8 Merge main into M2 first-frame fixture PR
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 18:09:56 -06:00
Ateşandatharvranjan 2ef175c0ce Roadmap: prioritize startup diagnosis and define first-frame acceptance (#588)
* docs: prioritize startup diagnosis and define first-frame acceptance

Signed-off-by: ates <ahmetrizaates@hotmail.com>

* docs: clarify roadmap verification and memory scope

Signed-off-by: ates <ahmetrizaates@hotmail.com>

* docs: record the target-workload shader corpus scan

Add the verified 2026-11-28 read-only container scan of an authorized
local test workload to the roadmap, ADR 0008 and the changelog: 52 DXIL
SM 6.5 compute containers with LLVM bitcode in the XboxBvhBuilder
component, 29 ACCC-only FSPX containers in the AMD FidelityFX upscaler
component, and 10 SM 6.6 DXIL containers whose DXIL chunks carry
four-byte NOBC payloads in the main executable. The packaged shader
archive remains unclassified. dxbc-accc accepts all 62 DXIL containers
(including the 10 NOBC programs) and rejects all 29 FSPX containers
because their section tables do not match the clean-room layout. The
roadmap keeps D1, gates D2 on runtime submission of an ACCC-only
container, and records both parser gaps as Track D prerequisites.
Build-specific details stay in a local evidence note; runtime use is
unmeasured.

Signed-off-by: ates <ahmetrizaates@hotmail.com>

---------

Signed-off-by: ates <ahmetrizaates@hotmail.com>
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
Co-authored-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:40:16 -06:00
atharvranjan e016cc1259 Add changelog entry for merge eligibility
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:40:07 -06:00
atharvranjan 083505ba1b Clarify pull request merge eligibility
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:39:56 -06:00
Bartosz Szczepański 1600d3f70f [M3-D2] dxbc-accc: report an FSPX layout mismatch apart from out-of-bounds (#599)
An FSPX descriptor whose offset lands inside the 16-byte header or the
descriptor table was reported as FspxSectionOutOfBounds, the same error as
a section that runs past the payload end. The reserved region cannot hold
section data under the synthetic layout, so such a table does not follow
that layout; it is not merely truncated or corrupt.

walk_sections now returns FspxError::LayoutMismatch for that case, surfaced
as ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }.
Both parse_fspx and scan_fspx share the walker, so inspect_dxbc and the C
ABI's summarize_dxbc classify it the same way. The container is still
refused: the C ABI is unchanged and returns BX_SHADER_ERR_INVALID_BLOB.

One existing case (offset 0 in a one-section table) now expects the new
variant. New tests cover the reserved-region boundary, the out-of-bounds
case, the unchanged C ABI refusal, and seeded random FSPX tables.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 00:28:47 +01:00
Jelly 9d4f7dffff Merge pull request #598 from MacosPorters/docs/agents-authorized-compatibility
docs: update AGENTS.md with 3-tier agent task priorities and authorized evidence rules
2026-11-28 00:14:59 +01:00
atharvranjan c126b94182 docs: tighten evidence conditions and add agent efficiency policy
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-27 17:08:29 -06:00
ates 257aa1651a docs: add 3-tier agent task priority order to AGENTS.md
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 02:06:49 +03:00
ates 6c243259d9 docs: permit project-authorized compatibility evidence in AGENTS.md
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:59:37 +03:00
ates 981bd3c64e xcrdapi: add Xbox DirectStorage COM interfaces (IDStorage*X)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:55:06 +03:00
Bartosz Szczepański 58b209a71b [M2-B2] xcrdapi: serve the public PC DirectStorage interfaces (#483)
DStorageGetFactory now accepts IDStorageFactory and IDStorageFactory1 and
logs any other requested IID with its value next to BX_STUB_LOG.

The public IDStorageFactory1, IDStorageFile, IDStorageQueue..4 and
IDStorageStatusArray objects wrap the existing queue engine. WorkQueue
gains an optional blocking enqueue, automatic submission and a failure
entry so the void enqueue methods report rejections in queue order. The
synthetic bx::storage behaviour is unchanged.

dstorage.h and dstorageerr.h from Microsoft.Direct3D.DirectStorage 1.4.0
(MIT per file) are vendored unmodified; dstorage_mingw.h restates their
IIDs for MinGW. Provenance is recorded in the upstream registry, the reuse
matrix and THIRD_PARTY_NOTICES.md. The Xbox IDStorage*X interfaces are
out of scope.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-28 01:49:18 +03:00
ates 63b5f5dac6 d3d12_xs: add 32-byte Xbox decoder for D3D12ConfigureVirtualMemoryX
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-28 01:28:00 +03:00
Eterna b96aa5c0b8 [M2-D5] judge reported shader model
Reviewed current head and checks; no remaining blockers.
2026-11-27 15:53:16 -06:00
Eterna 6484cb70a3 acphal: reject a zero-capacity APU heap
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:46:14 -07:00
Eterna 87da1752ad docs: keep the results table contiguous after the exit-code note
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 1bc42fcaec docs: move the exit-code note below the results table
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 25ceb05230 docs: define the conformance exit-77 skip protocol
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:35 -07:00
Eterna 2bc97a4f68 bx-cli: avoid ps in cleanup process-group test
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:34 -07:00
Eterna f2efeaf79d docs: define claims.toml evidence classes A/B/D/E/U (#549)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 14:44:33 -07:00
EternaandEterna 463169f72c [M2-A3] bx-cli trace: summarize shader_gate, D3DMetal-gap and bridge-missing records (#497)
* bx-cli trace: summarize shader-gate records

bx-telemetry now parses the shader_gate, shader_d3dmetal_gap and
shader_bridge_missing records that d3d12_xs.dll logs, aggregating
per-decision, per-kind and per-stage counts and keeping the
individual records. bx-cli trace renders the summary, and stays
byte-identical for logs with no gate records.

Closes the telemetry-summary gap ADR 0008 listed under 'Not covered
by the gate yet'. Summarizes records a run wrote; no live CrossOver
run was performed for this change.

Closes #496

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* bx-cli trace: address shader-gate review comments (#496)

From the #497 reviews:

- parse_key_values now takes a stop_at_free_text flag. Only the
  shader_d3dmetal_gap record appends free text, so a stray token ends
  the parse there; for shader_gate a stray token is skipped and
  parsing continues, so one unexpected word can no longer silently
  drop every later field.
- ShaderGateSummary gains missing_decision, counting parsed records
  that carry no decision. decision buckets + unparsed +
  missing_decision now reconcile against total, so the breakdown can
  never quietly add up to less than the total.
- bx-cli trace renders the individual non-pass decisions with pso,
  stage, decision and hr, so a rejected pipeline is named rather than
  only counted. This also makes ShaderGateSummary::records read
  outside tests.

Tests added for all three: a stray token keeping later fields, two
spaced atomic64 flags, a record with no decision, and a reconciliation
check over a mixed log.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* bx-cli: restore the doc comment on format_shader_gate_section

Arths17's re-verification of 93a309f noted that
format_non_pass_decisions was inserted between
format_shader_gate_section and its doc comment, so the comment
documented the wrong function. Split the two: the non-pass helper
keeps its own comment, and the section function gets its comment
back. No behaviour change; fmt, clippy and the 47 bx-cli tests pass.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* bx-telemetry: pin the two #497 review cases with tests and a note

devil8blade's review raised two parsing concerns. Both behaviour
changes were already in 796ed36; this adds the tests that name them
and the comment that explains why the two paths differ.

1. parse_key_values: a token without "=" stops the structured part
   when stop_at_free_text is set, and is skipped otherwise. The gate
   path passes false, so a value containing a space does not turn
   every later field into None. New test: a stray token does not
   drop later gate fields. Also documents that the emitter writes no
   spaces inside a value today, so this is robustness rather than a
   fix for current output.

2. A shader_gate record with fields but no decision is counted in
   missing_decision, so the decisions breakdown can be seen not to
   add up to the total. New test: a record without a decision is
   counted as missing. A third test pins the opposite free-text
   behaviour for the gap record.

cargo test -p bx-telemetry: 19 passed (was 17).

Closes #496

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

---------

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:43:04 -06:00
sahib453 a6dc3faf50 Never block on a --log path that is not a regular file (#503)
log_mark and read_log opened the --log path and read it to the end,
which waits forever on a FIFO nobody writes to (#502, from the review
of #475). The path is now opened with O_NONBLOCK and only a regular
file, checked on the open handle, is marked or summarized. Adds the
missing test for the file-identity half of the replaced-log check and
documents when a Ctrl-Z between supervised phases takes effect.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 15:39:30 -06:00
EternaandEterna 56650b91c2 bx-cli: propagate the guest numeric exit code (#566)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:37:54 -06:00
EternaandEterna 2505bc3a5b [M2-D3] docs: dxbc-accc README lists shipped ABI/staging/PSO-telemetry work as 'Not done' (#499)
* docs: dxbc-accc README lists shipped work as outstanding

The 'Not done here' section recorded the bx_shader_bridge.def
export list, scripts/build-shims.sh staging, and the d3d12_xs
PSO hook with JSONL telemetry as not yet done. All three shipped:
#445/#484 (.def + staging) and #466 (PSO hook + bx_log_emit
records). Replace the section with an accurate account of what
each one does and which issue delivered it.

The bx-cli trace summary of those records (#496, PR #497) is
NOT yet on main, so it is listed as the one item still open,
with the ADR 0008 telemetry note it leaves in place.

Documentation only; no code, ABI, test, or behavior change.

Closes #498

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* docs: decouple dxbc-accc README from PR state (#498 review)

Address review comments on #499:

- Drop the PR number, branch name and ADR-status sentence from the
  trace-summary bullet. It now points at #496 and says only what is
  true on main, so it cannot go stale in either merge order.
- Reword the intro: these are pieces around this crate, not pieces
  the crate depends on.
- Reword the closing line so it means this change rather than a
  claim about #445.
- Add #445 to the CHANGELOG citation to match the README.

Re-verified against main b8724bf: BxShaderGate::admit in proxy.cpp
covers VS/PS/DS/HS/GS and CS; build-shims.sh copies dxbc_accc.dll
to bx_shader_bridge.dll; the verifier checks the export directory
name against the .def.

Documentation only.

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

* dxbc-accc: drop the PR-state dependency from the README

devil8blade's review of #499 point 1: the last bullet said #497
was open and that bx-cli trace did not summarize the records. Once
#497 merges those sentences become wrong and nobody is assigned to
fix them.

Reworded to describe the split of responsibility only: the trace
summary work is tracked in #496, and the bullet no longer asserts
anything about that issue's status or about what bx-cli trace does
today. The crate's own behaviour is unaffected either way.

Also shortened the CHANGELOG entry to one sentence pointing at the
README, keeping #445 alongside #484 and #466 as the review asked.

Points 2, 3 and 5 were already addressed in 653e751: the intro says
"pieces around this crate", the closing line says "this change does
not touch the crate's code or tests", and the four factual claims
(proxy.cpp, shader_gate.cpp, BxShaderGate::admit, cargo naming the
built file dxbc_accc.dll) were verified against main before this
commit.

Documentation only; docs_hygiene.py 0 problems.

Closes #498

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>

---------

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:06:17 -06:00
EternaandEterna 01f5590e88 docs: correct the stale shim-DLL counts (16/102 -> 17/111) (#526)
scripts/build-shims.sh verifies 17 PE32+ DLLs with 111 exact exports,
but several documents still said 16 DLLs and 102 exports. The 17th is
bx_shader_bridge.dll, added by #484 so d3d12_xs's shader gate can
classify stages.

The wording now distinguishes the 16 mingw-w64 C++ shims built by the
CMake superbuild from the Rust bx_shader_bridge.dll built by cargo for
x86_64-pc-windows-gnu, rather than swapping 16 for 17 and calling all
seventeen "cross-compiled C++ shims", which would also be wrong.

Corrected: AGENTS.md (onboarding and the Section 8 comment),
README.md (abi row, build comment, verified-scope list, the
test_shim_exports claim, and the M0 roadmap-table row),
docs/roadmap.md (the diagram and the M0 exit gate) and
docs/architecture/parallel-tracks.md (M1).

test_shim_exports.exe still loads only the 16 C++ shims (25 checks)
and does NOT load the bridge; the README now says so and points at
test_shader_gate.exe, which does cover it. Extending the fixture is
named as a follow-up, not done here. Also dropped an unverified
"zero warnings" claim.

The docs/roadmap.md M0 exit-gate text is a stale-count correction to
a RECORDED gate (#406), not a re-opening of M0. Status stays Verified
complete.

Documentation only; no code, test or abi change. Verified on this
revision: build-shims.sh -> Verified 17 PE32+ shim DLLs (111 exact
exports); ls build-shims/bin/*.dll | wc -l -> 17;
grep -c bx_shader_bridge test_shim_exports -> 0; docs_hygiene 0
problems.

Closes #525

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:05:47 -06:00
EternaandEterna 21323cab80 docs: point ADR 0005 at the archived progress.md (#570)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
Co-authored-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 15:04:59 -06:00
Erkin Taş ab81b0beca d3d12_xs: distinguish fence wait failures after Present
Signed-off-by: Erkin Taş <erkinemreta@gmail.com>
2026-11-27 23:41:29 +03:00
Eterna b16797f576 test_d3d12_placed: exercise the graphics-first xmem pairing (#552)
Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 10:38:00 -07:00
Eterna 3409bf4ec0 d3d12_xs: charge graphics heaps through the xmem hook
After #550, xmem could see an external charge, but d3d12_xs still
kept its own private ledger and never registered one, so the
graphics-first overcommit remained. try_charge now calls
bx_xmem_try_charge_external and release_charge calls
bx_xmem_release_charge_external, so both allocation orders obey one
combined cap.

The overflow guards are kept, not traded away. try_charge still
rejects on bytes > cap, xmem_used > cap and
charged_private_bytes > cap - xmem_used before either unsigned
subtraction, and the comment now names which guard protects which
wrap and shows that the two additions cannot overflow given the
guards.

g_record.charged_private_bytes stays as a diagnostic mirror;
xmem's external_bytes is authoritative. release_charge releases
the xmem charge first, which logs and clamps on underflow, then
keeps the mirror in sync.

Lock order checked: try_charge and release_charge hold g_section
and then call into xmem, which takes usage_lock. xmem never calls
back into d3d12_xs (its only mention is a comment), so
g_section -> usage_lock is never inverted.

abi/, xmem.dll and d3d12_xs.dll export counts unchanged (17 / 4).
test_d3d12_placed.exe was NOT executed: no CrossOver on this host.
The two-order arithmetic was checked by simulation, not on host.

Closes #552

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 09:10:51 -07:00
Eterna 420c2329b7 abi: expose an xmem charge hook for the combined title budget
The combined Lockhart/Anaconda budget was one-way. try_charge in
shims/d3d12_xs/vmem.cpp read bx_xmem_get_internal_stats and
subtracted CPU usage before admitting a graphics heap, but
can_commit in shims/xmem/xmem.cpp summed only heap, virtual and
physical bytes and never saw the graphics charge. So graphics-first
(6 GiB) then CPU (3 GiB) admitted 9 GiB against an 8 GiB cap, while
xmem-first was rejected correctly. The header exposed no way for a
second owner to register a charge, so the fix could not live in one
shim; this is the [ABI] change that lands first.

Add bx_xmem_try_charge_external and bx_xmem_release_charge_external
to bx_xmem_internal.h, exported from xmem.dll (15 -> 17). Admission
is atomic under the same usage_lock can_commit takes, so two threads
cannot both pass, and it returns 0 rather than silently succeeding.
The new external_bytes counter is folded into can_commit and
update_peak, so both allocation orders now obey one cap. Release
clamps to zero and logs on underflow, mirroring release_charge.

bx_runtime_config_t is unchanged and there is no ABI version bump:
this is additive only.

shims/d3d12_xs/vmem.cpp still keeps its private
g_record.charged_private_bytes. Switching it to these functions is
the consumer change, a separate PR.

Verified: build-shims.sh reports Verified 17 PE32+ shim DLLs
(113 exact exports) with OK xmem.dll (17 exact exports verified);
fmt, clippy and test pass; docs_hygiene 0 problems; the header
compiles from both C and C++ with -Wall -Wextra -Werror. No live
CrossOver run: none on this host.

Closes #550

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 08:57:57 -07:00
Eterna ae869522ce test_veh_clwb: assert the decoded clwb length, not just the count
The fixture emitted six clwb forms and asserted only delta == 6.
But decode_clwb_length decides len, and the handler does
Rip += len: a wrong len lands the guest mid-instruction while the
trap count stays at 6. The log already carried len=%zu, and no test
read it.

log_sampled_trap logs only counts 1, 2, 4, 8, ..., so six traps
produce exactly three records with total_traps = 1, 2, 4. Assert on
those sampled records only (option (a)); forms 3, 5, 6 are NOT
covered by a len= assertion, and the comment and CHANGELOG say so.

Mapping, re-derived by assembling with x86_64-w64-mingw32-as and
disassembling with x86_64-w64-mingw32-objdump -d:

  total_traps=1 -> clwb (%rax)        -> len 4
  total_traps=2 -> clwb 0x40(%rax)    -> len 5
  total_traps=4 -> clwb (%r8)         -> len 5

clwb (%r8) is 66 41 0f ae 30, ModRM 0x30, confirmed from the
disassembly rather than guessed.

Add a BX_LOG_FILE reader (the fixture did not read it before),
creating a temp log when the variable is unset, initialized before
the clwb block. The AVX2/FMA block runs first but does not trap, so
the first clwb is trap #1. Also assert len >= 4 on every observed
record. The existing delta == 6 check is unchanged.

test_veh_clwb.exe was NOT executed: no CrossOver on this host. The
log-parsing logic was sanity-checked on the host against a synthetic
JSONL sample; a live CrossOver + Rosetta 2 pass is still required.

Closes #539

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 06:55:03 -07:00
Eterna 6e3ef5459b test_shader_gate: assert the log's shape, not a hand reading of it
The bx-cli trace fixtures were typed by hand from reading the
snprintf in shader_gate.cpp. A reviewer asked for a real log; one
was supplied in a PR comment and confirmed the parser, but that
confirmation lived nowhere in the repo, so the next fixture could
drift unnoticed.

This asserts the shape of the log the fixture itself writes:

- at least one shader_gate and one shader_d3dmetal_gap record exist;
- every gate record writes pso=, stage=, decision= and hr= in that
  order, which is the order the summarizer extracts them in;
- an *_unclassified record carries no kind=;
- every gap record has pso=, stage=, wave_lanes_min= and the colon
  that ends its structured part, which is the boundary
  parse_key_values(..., true) needs;
- no key=value value is split by a space, which is what
  parse_key_values(..., false) assumes for the gate records.

Shape, not counts: decision and kind totals vary by GPU. It is the
field order and token boundaries that a hand-typed fixture could get
wrong without any test noticing.

Verified: the assertions compile and link, and their logic was run
in a native harness against a sample log, including a negative
control where an atomic64 value containing a space correctly trips
the check. test_shader_gate.exe itself was not run here -- no
CrossOver on this host.

Closes #535

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 06:35:41 -07:00
Eterna bec15f43b6 bx-cli: test the usage paths in-process, not by spawning the binary
The previous test located the built bx-cli by guessing a path from
current_exe(). That worked locally but failed in CI with
"spawn bx-cli: No such file or directory", because cargo does not
guarantee the bin sits next to the test binary.

Replace it with a testable dispatch: Dispatch::classify(args) returns
Help / NoArgs / Unknown / Sub, plus usage_on_stdout() and
is_usage_error(). main() is now a thin shell over that, so the exit
and stream choices are asserted in-process with no binary lookup and
no dependency on the build layout.

usage_text() returns the string; main() prints it to the stream the
dispatch selects. The five real subcommands are asserted to be
neither usage errors nor usage-printing, and a second test checks
the usage text names every subcommand so the classifier is not
testing a table nothing prints.

Behaviour is unchanged from the intended fix: --help/-h/help exit 0
on stdout, a bare invocation exits 1 on stderr, an unknown
subcommand exits 1 on stderr.

Closes #532

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 05:59:40 -07:00
Erkin Taş 7dde71e2fd d3d12_xs: share the PresentX idle timeout budget
Signed-off-by: Erkin Taş <erkinemreta@gmail.com>
2026-11-27 15:54:54 +03:00
Eterna 33d439f828 bx-cli: fix the inverted help and usage exit codes
--help and -h were never matched, so they fell into the
unknown-subcommand arm: usage text on stderr and exit 1. Meanwhile a
bare bx-cli with no arguments printed usage and returned 0. Both
halves were wrong, and in opposite directions.

--help, -h and help now print usage on stdout and exit 0, so
`bx-cli --help | less` and `bx-cli --help && ...` both work. A bare
invocation is a usage error: text on stderr, exit 1. An unknown
subcommand still exits 1, unchanged.

print_usage takes a UsageStream so the caller chooses the stream
instead of the function hardcoding eprintln!. The subcommand
behaviour of doctor/probe/shader/trace/run is untouched.

Test help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error
runs the built binary and asserts exit code, stdout and stderr for
--help, -h, no arguments and a bogus subcommand. Mutation-checked:
restoring the old dispatch makes it fail at exactly
"--help must exit 0".

Closes #532

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 05:53:12 -07:00
Eterna a27284ab26 dxbc-accc: expose a bounds-checked chunk-lookup API
dxbc-accc already parsed the DXBC chunk table into
ChunkInfo { fourcc, offset, size }, but exposed no public lookup, so
shims/d3d12_xs/shader_gate.cpp:94 re-implements the same
bounds-checked walk in C++ (find_chunk), plus a second variant
has_chunk_tag that ignores the declared size. Two parsers for one
container is how a fix lands in one and not the other.

Add an additive API on ShaderInspection:

- chunk_payload(&container, &fourcc) returns the payload of the
  first chunk tagged fourcc. It reuses the already-parsed chunks
  vector rather than re-walking the raw table, and validates
  offset + 8 + size against BOTH container_size and container.len()
  with checked arithmetic, returning None instead of panicking.
  offset points at the 8-byte chunk header, so the payload begins
  at offset + 8. A zero-size chunk yields Some(&[]); callers needing
  a minimum size must check the returned length. When several chunks
  share a FourCC, the first in table order wins, matching the C++
  find_chunk.
- has_chunk_tag(&fourcc) answers presence WITHOUT trusting the
  declared size, mirroring the C++ has_chunk_tag.

Scope: the C++ gate is NOT migrated here -- find_chunk and
has_chunk_tag in shader_gate.cpp stay for now, and the PR names the
migration as a follow-up, since it is a larger change needing a live
run. abi/defs/bx_shader_bridge.def unchanged (3 exports).

Seven new unit tests: SFI0 and PSV0 payloads returned exactly; a
declared size past the container -> None; an absent FourCC -> None
and has_chunk_tag == false; a zero-size chunk -> Some(&[]); an
exact-fit chunk at the container end (no off-by-one); a truncated
container slice -> None; and duplicate FourCCs -> first wins.

Closes #521

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 04:53:52 -07:00
Eterna 311f4124fa win32_bridge: store the PSM callback and say it is never fired
register_notification validated callback for null and then dropped it:
nothing stored it, nothing ever invoked it, and the context pointer was
discarded as PVOID /*context*/. So ERROR_SUCCESS meant 'token
allocated', not 'you will be notified', and neither the code nor the
log said so.

- Each registration now keeps a (token, callback, context) record
  under the existing SRWLOCK, capped at a fixed kMaxRecords (256) so
  no allocator is needed. The exported wrappers thread context
  through. Unregistering drops the record, so no later event can
  reach a retired registration.
- A comment on register_notification and the JSONL detail (now
  'registered_offline callback_unfired') both state that the callbacks
  are accepted and currently never invoked, because this shim has no
  source of app-state or constrained-change events and the console
  firing contract is not publicly documented. No firing policy was
  invented: the callback is deliberately left unfired rather than
  called spuriously to look implemented.
- test_win32_bridge.exe now also asserts that no callback fires, and
  that every registration's detail carries callback_unfired, counted
  separately for state and constrained. The existing per-event JSONL
  counts still pass, since the detail grep is a substring match.

abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def and -l1-1-1.def are
unchanged at 2 exports each; all six API-set DLLs keep their original
export counts. Cross-compiled and export-verified only; no live
CrossOver run.

Closes #513

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 03:35:42 -07:00
Eterna 46a6a4baca acphal: stop reporting success for shape-context work not done
AcpHalAllocateShapeContexts and AcpHalReleaseShapeContexts logged a
stub and returned a bare S_OK. Allocate discarded its only argument
(unnamed) and Release takes no argument at all, so neither could be
held to anything: a caller was told the work succeeded when nothing
had happened. This is the silent-fallback case AGENTS.md section 5
names.

Both now return E_NOTIMPL and keep their BX_STUB_LOG record, so
bx-cli trace still surfaces the call while a caller is told to fall
back instead of being told the work happened. Release mutates no
state, so calling it twice is safe.

The public Microsoft Learn page for AcpHal is NDA-gated (HTTP 200
with only the membership gate), so the true signatures and the
context layout are unknown, including whether Release should take an
argument. E_NOTIMPL is therefore BetterXen's choice, not the
console's; no signature was invented and abi/defs/AcpHal.def is
unchanged at 9 exports.

test_audio_input.exe now calls both through the DLL: null and
sentinel pointers return E_NOTIMPL without crashing, a second
Release call returns E_NOTIMPL, and when BX_LOG_FILE is set it
asserts both symbols still appear on unimpl_api lines (printing an
explicit SKIP when the variable is unset rather than claiming a
pass).

Cross-compiled and export-verified only; no live CrossOver run.

Closes #509

Signed-off-by: Eterna <295740124+EternaPeptix@users.noreply.github.com>
2026-11-27 00:56:02 -07:00
atharvranjan 8245c30b56 d3d12_xs: keep Present from blocking and recover from a failed signal
Present no longer waits for the swapchain lock, which its holder may keep
across a host Present that depends on the caller's thread. It returns
BX_PRESENT_E_BUSY with nothing presented.

When the fence signal after a host Present fails, return
BX_PRESENT_E_COMPLETION_UNCONFIRMED and refuse further presents with
BX_PRESENT_E_NEEDS_IDLE until WaitForIdle succeeds, so a buffer is not
reported reusable on the strength of an older fence value.

The fixture injects both faults from the test side.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 22:27:19 -06:00
atharvranjan be647332cb Merge main into the PresentX branch
Keep both new d3d12_xs source files in CMakeLists.txt and both sets of CHANGELOG entries.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 22:27:19 -06:00
Ateş b8724bf04f Merge pull request #486 from devil8blade/track-c/464-d3d12-vmem-placed
[M2-C1] Back configured D3D12 regions with one WRITE_BACK heap (#464)
2026-11-27 06:35:00 +03:00
ates fbd2f8cf43 Gate the M2 fixture target on its provider headers
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 06:00:35 +03:00
ates 40a9cebb83 [M2-C1] Retain heap charges for live placed resources
Attach the charged heap to each base placed resource, describe the backing map lifetime, and serialize shared vtable installation before device publication. Exercise dependent heap charges and parallel device creation under the 512 MiB title cap.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 05:45:52 +03:00
ates 6a1451b265 Clarify M2 frame readback and test pixel mismatches
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 05:38:34 +03:00
ates 7056671c19 [M2-C1] Reject stale D3D12 backing heap publication
Validate the configuration generation at cache lookup and publication. Return a retry result and release any allocation if reconfiguration supersedes the request. Drop the extra fixture references so detached heaps are credited before the budget checks.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 05:31:32 +03:00
devil8blade bd546d8a39 [M2-C1] Address review: detach, unwrap, and one final release (#464)
A backing heap that leaves the cache drops its weak device pointer under
the same lock, so a caller who still holds it gets E_FAIL from GetDevice.
CreatePlacedResource1 and CreatePlacedResource2 unwrap that wrapper.
Weak GetDevice acquires a reference only when the count is non-zero, and
the 1-to-0 release clears weak pointers in that same critical section.
Handing out the cached heap checks the host and the size, retargets, and
takes the caller's reference before the lock is released.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 02:07:50 +00:00
devil8blade db193a3d16 Merge remote-tracking branch 'origin/main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 02:02:27 +00:00
Skakwy cd945ba749 Emulate AMD instruction traps in the Windows guest runtime (#470)
Closes #451.

Add AMD instruction emulation and conformance coverage using the
AMD Architecture Programmer's Manual, volumes 3 and 4. The final
decoder and fixture replace the earlier VIctory-macOS-derived work.
The earlier PR cited 64bitMango/VIctory-macOS at 841c1b8. The
maintainer's provenance decision accepts the AMD-manual replacement.

Verification on the PR head: both CI workflows passed, and the local
Apple Silicon CrossOver 26.3 run passed 28 AMD-instruction assertions.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 04:34:27 +03:00
devil8blade 8381f57204 [M2-C1] Address review: lock the weak heap GetDevice (#464)
The backing heap reads device_ and AddRefs the proxy while holding
g_section, the same lock that clears that pointer. An ordinary heap
still reads its owning pointer without the lock. If GetDevice AddRefs
after Release has observed zero, Release leaves the proxy alive.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:25:35 +00:00
devil8blade 0b48688c13 [M2-C1] Address review: retarget cached heap, own ordinary heaps (#464)
The cached backing heap keeps a weak device pointer. ensure_backing points
it at the proxy receiving the heap, and BxDeviceProxy::Release clears it
when that proxy is destroyed. Ordinary heaps AddRef the proxy and Release
it after the wrapper is destroyed, matching BxChildProxy.

The placed-resource test forces the second proxy onto the cached host device.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:22:54 +00:00
ates c64534fb21 Add end-to-end M2 first-frame conformance fixture
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 04:21:26 +03:00
devil8blade c878ad5875 [M2-C1] Address review: proxy GetDevice and per-device backing heap (#464)
BxChargedHeap::GetDevice returns the creating BxDeviceProxy and does not
AddRef it, so the cached backing heap cannot keep that device alive.
The cache is keyed by the host ID3D12Device. CreateHeap on a different
host device releases the old heap, its buffer, and that budget charge,
then builds a new one.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:17:10 +00:00
devil8blade 291047834a Merge branch 'main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 01:13:58 +00:00
jelly013 f07a24c28c xgameruntime: mount with UI through XAsync, answer IXError slot 3
Address the review of #492:

- XPackageMountWithUiAsync / XPackageMountWithUiResult (IXPackageImpl2
  slots 37-38) mount through the XAsync engine. The async call checks
  the package identity, and the result creates the same mount handle
  XPackageMount returns. A foreign identifier is reported as the
  operation status, ERROR_NOT_FOUND. The identity and path code is
  shared with XPackageMount.
- IXError slot 3 returns false instead of the E_NOTIMPL stub, whose
  low byte read as true. xgameruntime-docs lists the slot as unknown;
  the behaviour follows the review's interop observation. No
  parameters are read, and the first call is logged.
- test_xgameruntime_saves covers both mount slots through the public
  vtable, and slot 3's answer.
- Record xodus-gaming/xgameruntime-docs at 7090008 in the upstream
  registry and component reuse matrix, pending maintainer provenance
  acceptance.

Refs #468

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-27 03:07:49 +03:00
devil8blade aedd338980 [M2-E2] Wire XGameSave and XPackage into xgameruntime COM dispatch (#468)
QueryApiImpl now serves the offline XGameSave and XPackage objects from
#472 on the public COM class and interface ids, through const vtables in
com_dispatch.cpp. The ids, inheritance and slot order are facts from
xodus-gaming/xgameruntime-docs commit 7090008692569aa6081e30dfdd9de58237741e24
(GPL-3.0). Signatures follow the Microsoft Learn GDK reference.

Slots the existing save and package logic can answer call it, including
synchronous XGameSaveInitializeProvider, XGameSaveReadBlobData and
XGameSaveSubmitUpdate built on the async operations, and
XPackageIsPackagedProcess. Every other slot logs with BX_VTABLE_STUB_LOG.
The synthetic keys keep working. Storage stays under C:\bx_pls\<hash>\saves\.
abi/defs/xgameruntime.def is unchanged at 49 exports.

test_xgameruntime_saves gains a public-id round trip: QueryApiImpl and
QueryInterface across both interface chains, a save write and byte-exact
read back, enumeration, package identifier, kind and mount path, stubbed
slots and refused ids.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-27 03:07:49 +03:00
Ateş e61e27055f Merge pull request #491 from soggyramennoodle/track-c/450-direct3d-acceptance-failures
Document independent Direct3D acceptance results for #450
2026-11-27 02:15:40 +03:00
Ateş 0edb548e3d Merge pull request #485 from devil8blade/track-b/467-xcrdapi-gpu-batch
[M2-B1] Batch XCRDAPI transfers into D3D12 buffers (#467)
2026-11-27 02:15:02 +03:00
devil8blade c13f9c7665 Merge branch 'main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:51:11 +00:00
devil8blade c219636ae2 Merge branch 'main' into track-b/467-xcrdapi-gpu-batch
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:50:57 +00:00
atharvranjan 0bd385cf05 Merge pull request #478 from jelly013/track-d/466-shader-format-gate
[M2-D2] M2 Shader Format Gate: dxbc-accc in d3d12_xs PSO creation, ADR 0008 (#466)
2026-11-26 16:47:55 -06:00
devil8blade 38a21c2da1 Merge branch 'main' into track-b/467-xcrdapi-gpu-batch
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:46:08 +00:00
devil8blade c44ae4e221 Merge branch 'main' into track-c/464-d3d12-vmem-placed
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:45:52 +00:00
devil8blade af940476c6 [M2-C1] Address review: explicit backing heap, forwarded ordinary heaps (#464)
CreateHeap returns the backing heap only for an explicit request. The config
block must set BX_D3D12_VMEM_FLAG_BACKING_HEAP and the desc must be CUSTOM,
WRITE_BACK, L0, flags NONE, at the configured size. Every other CreateHeap and
CreatePlacedResource is forwarded unchanged to the host. Only the live-heap
budget wrapper remains, and it answers ID3D12Heap1 when the host heap does.

D3D12ConfigureVirtualMemoryX reads an 8-byte BXVM magic and size header
before anything else, copies the block, and never keeps the caller's pointer.
cpu_pointer is written only during the call. A second call with the same
region returns the map address once the backing heap exists.

test_d3d12_placed covers same-size UPLOAD and DEFAULT plus DENY_BUFFERS
heaps, a 100000-byte UPLOAD heap, 4 KiB small-resource placement,
ID3D12Heap1, and a config block that is gone before CreateHeap.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:45:26 +00:00
devil8blade 6eaa594ae4 [M2-B1] Address review: keep unconfirmed staged copies alive (#467)
After ExecuteCommandLists, a staged copy whose completion is not confirmed
no longer releases the upload buffer, command list, allocator, queue, fence,
or destination. It logs a warning and keeps them alive, unless the device was
removed or the fence already completed. test_xcrdapi forces that path with
BX_XCRDAPI_COPY_TIMEOUT_MS=0 and BX_XCRDAPI_DEFER_COPY=1.

WIDL_EXPLICIT_AGGREGATE_RETURNS is now a compile definition on the xcrdapi
and test_xcrdapi targets, because a define in synthetic_storage.h came after
windows.h had already set it.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 22:45:24 +00:00
Adeeb Rahman f0eb940504 Document Direct3D acceptance reproductions for #450
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-26 17:03:47 -05:00
jelly013 d30b676813 d3d12_xs: refuse ACCC-only shaders even without the bridge
Review of #478: with no bx_shader_bridge.dll, the gate passed every
shader through, and the structural check now accepts an ACCC chunk, so
an ACCC-only container reached D3DMetal, which crashed the process
(access violation) instead of returning an error.

- Without the bridge, a container with an ACCC chunk tag and no DXIL
  chunk that fits is refused with E_NOTIMPL. This uses a bounds-checked
  chunk scan and is logged as decision=reject_accc_only_unclassified.
  Other shaders still pass unclassified.
- Drop the bare-name LoadLibraryW fallback. The bridge is loaded only
  by full path beside d3d12_xs.dll, where build-shims.sh now stages it
  (#484), so the EXE directory and PATH cannot supply another copy.
- test_shader_gate reruns itself with --no-bridge from a scratch
  directory holding d3d12_xs.dll and its imports but no bridge. DXIL
  must still run there and ACCC-only must get E_NOTIMPL. Removing the
  new refusal brings back the crash, and the fixture reports it.
- ADR 0008 and the changelog describe the no-bridge behaviour and the
  build-shims staging.

Refs #466

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:33:07 +01:00
Ateş 4a585a79c6 Merge pull request #475 from sahib453/track-a/461-run-signal-cleanup
Closes #461

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 00:32:26 +03:00
ates b95b2c92a8 Merge current main and retain both changelog entries
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 00:29:39 +03:00
Ateş d38c5253c6 Merge pull request #490 from MacosPorters/track-d/479-harness-pid-path
[Track D] Handle apostrophes in the harness test PID path
2026-11-27 00:28:19 +03:00
jelly013 077e7d2f4e Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 22:27:42 +01:00
Ateş 6fb171b247 Merge pull request #489 from jelly013/track-a/484-bridge-staging
[ABI] + [M2-A] Build, stage and verify bx_shader_bridge.dll in build-shims (#484)
2026-11-27 00:26:55 +03:00
ates 482293fd35 Pass the harness PID file as a probe argument
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-27 00:25:28 +03:00
atharvranjan 993cd222a4 Merge pull request #480 from sahib453/track-d/479-harness-test-timing
[Track D] Stop d3dmetal-harness runner tests racing probe start-up (#479)
2026-11-26 15:24:29 -06:00
jelly013 54b295434e Merge remote-tracking branch 'upstream/main' into track-a/484-bridge-staging
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 22:09:36 +01:00
jelly013 8141b8e282 build-shims: build, stage and verify bx_shader_bridge.dll
scripts/build-shims.sh builds shader-transpiler/crates/dxbc-accc for
x86_64-pc-windows-gnu, linked with abi/defs/bx_shader_bridge.def, and
places it in build-shims/bin as bx_shader_bridge.dll. The existing
verifier then checks it like every shim: export directory name, exact
exports, ordinals, no forwarders, no MinGW runtime imports. It now
reports 17 DLLs and 111 exports.

cargo and rustc are resolved through rustup when present, and the
build always goes to <repo>/target. A rustc without std for the
Windows target stops the script with the rustup command to run; the
bridge is never skipped. The CI job installs that target with its
pinned toolchain.

d3d12_xs's shader format gate (#466) can then load the bridge from
build-shims/bin without a manual copy.

Closes #484

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:08:29 +01:00
jelly013 ba9a053b5c [ABI] Add the bx_shader_bridge.dll export list
abi/defs/bx_shader_bridge.def freezes the three entry points of
abi/include/bx_shader_bridge.h for bx_shader_bridge.dll, the x86-64
Windows build of shader-transpiler/crates/dxbc-accc (#445). Linking
with it also gives the DLL its export directory name. abi/README.md
notes that this is the one .def whose DLL is not under shims/.

build-shims.sh verifies every .def against a built DLL, so this
commit lands together with the next one, which builds the bridge.

Refs #484

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 22:08:29 +01:00
jelly013 f6e0afeab1 Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 22:07:58 +01:00
sahib453 f34b70dd45 Merge main and keep both changelog entries
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:34:37 +05:30
sahib453 e71fca720a Merge main and keep both changelog entries
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:34:27 +05:30
atharvranjan 83391f57be Merge pull request #487 from MacosPorters/track-e/481-gameinput-callbacks
[M2-E3] gameinput: implement IGameInput callback lifecycle and SetFocusPolicy (#481)
2026-11-26 15:04:06 -06:00
atharvranjan 8877bff9f2 Merge pull request #488 from MacosPorters/track-a/482-stage-gameinput
[M2-A2] bx-cli: stage GameInput.dll in system32 with safe Wine builtin stub replacement (#482)
2026-11-26 15:02:15 -06:00
sahib453 68d4b449f2 Merge main and combine the timeout and staging changes in cmd_run
Resolves the conflict with #477: staged names are still collected, the
guest's share of --timeout is computed from active (non-suspended) time
and still refuses to launch when initialization used all of it, and the
diagnostics #477 added after the signal handlers are installed go
through the non-panicking helper.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:27:52 +05:30
sahib453 daeeaeae34 Merge main; correct the changelog claim and clean up after a failed kill test
Addresses review of #480: the changelog no longer says the old kill
test passed with only the kill removed (it passed only with both the
kill and the wait removed). A PidFile guard removes the pid file and
kills the recorded process when the test fails.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:26:47 +05:30
sahib453 3b3e9f1c05 Record the CrossOver Preview confirmation in the changelog
Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:22:22 +05:30
ates f016960021 [M2-A2] bx-cli: stage GameInput.dll in system32 with Wine stub backup (#482)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 23:47:33 +03:00
devil8blade 6308fdc046 [M2-C1] Back configured D3D12 regions with one WRITE_BACK heap (#464)
The configured region is one shared WRITE_BACK/L0 heap with a persistent map. CreateHeap of that size returns it, and cpu_pointer in the config block publishes the address. An unrecognised parameter block stays a logged S_OK and is left unchanged.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 20:45:40 +00:00
devil8blade cf084e246b [M2-B1] Batch XCRDAPI transfers into D3D12 buffers (#467)
One Submit runs queued file reads in order into CPU memory, mapped upload
buffers, and default buffers. LZ, BCPack, and GDeflate complete as E_NOTIMPL.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-26 20:45:28 +00:00
jelly013 1571cf75c0 Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:44:27 +01:00
sahib453 01a7435d35 Address review: budget pauses across phases, detect replaced logs
A pause during wineboot is no longer charged to the guest's share of
--timeout: supervise reports total suspended time and cmd_run subtracts
it from the wall clock. The trace summary recognizes the pre-run log by
file identity and by the bytes before the old end instead of by size,
so a log replaced by an equal or larger file is summarized in full.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:04:08 +05:30
atharvranjan b096424f33 d3d12_xs: fix presentation timeout semantics and strengthen the frame test
Present now waits for the current buffer before calling the host, so
ERROR_TIMEOUT means nothing was presented. A timeout after the host
Present returns BX_PRESENT_E_NEXT_BUFFER_BUSY. WaitForIdle counts lock
acquisition against its timeout, and same-thread re-entry is refused. The
leak-on-timeout path now returns the queue proxy reference.

The fixture checks host buffer identity, per-frame present counts, both
timeout results, the leak path, rejection log records and the swapchain
release count against a host-only control. run_controls.sh checks each
negative control's failing stage.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 14:33:13 -06:00
sahib453 2cc44b8318 Stop d3dmetal-harness runner tests racing probe start-up
kills_a_probe_that_exceeds_the_timeout and
a_descendant_holding_the_pipes_cannot_outlast_the_deadline gave a
freshly written script 300 ms and 500 ms to start and print, and the
first failed intermittently with empty stdout (#479). Both now use a
2 s deadline. The kill test also checks that the probe ran until the
deadline and that its process is gone afterwards. Test-only change.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 02:00:21 +05:30
jelly013 ec65d79726 test_shader_gate: require the bridge from d3d12_xs.dll's directory
Check that bx_shader_bridge.dll was loaded from the directory of
d3d12_xs.dll rather than through the EXE's directory, so running the
fixture with the EXE outside the shim directory exercises the lookup
the shim is meant to use (review of #476).

Refs #466

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 21:28:43 +01:00
jelly013 77dde94aa8 Merge remote-tracking branch 'upstream/main' into track-d/466-shader-format-gate
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-26 21:23:19 +01:00
jelly013 884f5398e7 d3d12_xs: M2 shader format gate at pipeline creation
CreateComputePipelineState and CreateGraphicsPipelineState now pass
every stage through bx_shader_bridge.dll (#445) and log one
shader_gate JSONL record per stage: container kind, stage, shader
model, chunk sizes, SFI0 feature flags and PSV0 wave lane range.

DXIL and dual containers reach the host as the bridge's prepared
copy. ACCC-only containers are refused with E_NOTIMPL before the host
is called. Legacy DXBC and unclassifiable input pass unchanged. Stages
needing a wave wider than 32 lanes or 64-bit atomics also log
shader_d3dmetal_gap, the cases #453 measured as created but not run.
The bridge is loaded at run time; when it is missing, that is logged
once and shaders pass unclassified.

tests/conformance/test_shader_gate runs a real DXC SM 6.6 compute
shader through d3d12_xs with a full readback check, requires E_NOTIMPL
for ACCC-only compute and graphics shaders, and checks the logged
wave64 and 64-bit-atomic constraints.

docs/adr/0008 records the evidence and proposes Branch D1 for M3.

Closes #466

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-26 21:19:28 +01:00
sahib453 e75b4131a3 Make bx-cli run cleanup robust to signals and closed streams
Fixes the six points of #461: the environment's wineserver is stopped
before anything is reported, and stop-path diagnostics no longer use
panicking print macros; signals inherited as ignored stay ignored;
SIGQUIT stops the guest group and environment like SIGINT; SIGTSTP is
passed to the guest group and suspended time does not count against
--timeout; cleanup wineserver commands run in their own process group;
the trace summary covers only what this run appended; and
THIRD_PARTY_NOTICES.md names libc consistently and includes its MIT
text. Adds 7 unit tests with stub launchers and servers.

Signed-off-by: sahib453 <sahibsingh4533@gmail.com>
2026-11-27 01:11:47 +05:30
atharvranjan f2af367da6 [M2-C2] d3d12_xs: add a swapchain presentation bridge and frame conformance test
The proxied command queue answers a BetterXen-defined IID with a tear-off
that creates a flip-model swapchain on a Win32 window over the host's
IDXGISwapChain3. This is not the console's PresentX and claims no binary
compatibility with it. No export or abi/ file changes.

The bridge waits (bounded) for the next back buffer, waits for the GPU
before releasing, and refuses presents that D3DMetal 3.0 was observed to
accept with S_OK (sync interval above 4, any flag, destroyed window).

test_d3d12_presentx renders and presents 12 frames, checks every read-back
pixel against CPU-computed values, and compares swapchain lifetime with a
host-DXGI control.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 12:46:56 -06:00
259 changed files with 52135 additions and 2836 deletions

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
test "$(sysctl -n sysctl.proc_translated)" = 0
- name: Install Rust toolchain
run: |
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --target x86_64-pc-windows-gnu
rustc -vV
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
run: |
+2
View File
@@ -29,6 +29,8 @@ jobs:
fetch-depth: 0
- name: Install PyYAML
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
- name: Unit-test the hygiene checks
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
- name: Check documentation and workflow files
run: python3 scripts/audit/docs_hygiene.py --require-yaml
- name: Remind about the changelog (advisory)
+27
View File
@@ -0,0 +1,27 @@
name: Merge policy audit
# Detects a pull request merged by its own author (AGENTS.md §7, "Merge
# eligibility"). GitHub rulesets cannot block this, so the run fails after the
# merge. It is not a required check and never checks out pull request code.
on:
pull_request_target:
types: [closed]
branches: [main]
permissions: {}
jobs:
author-merge:
name: Author did not merge
if: github.event.pull_request.merged == true && github.event.pull_request.merged_by.login == github.event.pull_request.user.login
runs-on: ubuntu-24.04-arm
timeout-minutes: 2
steps:
- name: Report a self-merge
env:
PR: ${{ github.event.pull_request.number }}
AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
echo "::error::Pull request #$PR was merged by its own author, $AUTHOR. A maintainer other than the author must merge (AGENTS.md section 7)."
exit 1
+139 -45
View File
@@ -4,34 +4,103 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
---
## 0. First-Time Contributor Onboarding
## 0. What to Do When Told "Work"
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
1. **Preflight host & tools:**
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
2. **Discover & pick an unclaimed issue:**
- Query ready issues in the active milestone:
```sh
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
```
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
3. **Claim & isolate:**
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
4. **Implement strictly in scope:**
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
5. **Verify locally (including hosts without CrossOver):**
- Run every command in Section 8 and fix all warnings/failures before stopping.
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
6. **Review & submit PR:**
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
**"Work" authorizes, for the one item you pick:** opening a draft pull request, posting a review, committing with DCO sign-off, and pushing a branch. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
### Step 1 — Preflight: make the machine ready yourself
```sh
cargo build --locked -p bx-cli && target/debug/bx-cli preflight
```
`bx-cli preflight` must print `Ready to work.` It requires **all** of:
| Required | How it is found |
| --- | --- |
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
| **The Ghidra results of the target build** (the static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable | Found and saved by `bx-cli setup --find` |
| At least 10 GiB of free disk space | Measured |
**The target build, the GDK and the Ghidra results are a hard requirement.** An agent that lacks even one of them does not work on this repository at all: no code, tests, reviews, merges, issues or documentation.
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
| `MISSING` line | What you do |
| --- | --- |
| Target build, GDK, Ghidra results | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header, the build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three. |
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
**Stop only for what an agent cannot supply**, and say exactly which:
- the host is not an Apple Silicon Mac;
- CrossOver is not installed (it is licensed software; do not install it);
- `setup --find` reports that the target build, the GDK or the Ghidra results covering the build are not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
In those cases stop and do not work around it: no fixes, tests, reviews, merges or documentation "for someone else to verify". Work here is found by running the target build, located in the Ghidra results and checked against the GDK; an agent without all three is guessing.
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
`bx-cli setup` remembers the three locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE`, `BX_GDK_ROOT` and `BX_GHIDRA_RESULTS` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build, the GDK or the Ghidra results into a commit, issue or pull request (Section 6).
### Step 2 — Pick exactly one thing, in this order
Take the first that applies.
1. **Your person's pull requests that need attention.**
```sh
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,isDraft,reviewDecision,statusCheckRollup,mergeStateStatus
```
Requested changes, unresolved review comments, failing checks, conflicts, or a draft you opened and have not finished: do that. Resolve every review point, re-run Section 8, push, and reply to each point.
2. **Review someone else's pull request.**
```sh
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
```
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test **twice in a row**, confirm the test fails without the fix, and post an approval or a change request with what you ran. If it is approved, green and not your person's, merge it (Section 7).
3. **A handoff issue of the current stage.**
```sh
gh issue list --repo MacosPorters/betterxen --state open --label handoff --label "stage: <current>" --json number,title,labels
```
A handoff is something a collaborator found and could not finish. The current stage is named on the pinned issue labelled `ladder`. Take the lowest-numbered one that no open pull request mentions, and follow Step 3.
4. **Run the target build and fix the first thing it stops on.** Run it under the [run protocol](docs/process/working-method.md#run-protocol) and read `bx-cli report`. Take the first signature in the report that no open pull request is titled with or mentions, and follow Step 3. A blocker you can see and fix needs **no issue**: the pull request is the record.
5. **The run stops on nothing.** Make the stage's gate check (ten runs). If it passes, post the result on the ladder issue and label it `needs-human`; a person confirms the stage change. Then stop.
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
### Step 3 — Work one blocker
**Before touching any problem the game shows you, find out whether someone already has it.** This applies every time: to the blocker you picked, and to every further problem you meet along the way (a failed load, a refused request, an assert, a crash). Search by the log event, stub symbol, error code and the files you would change:
```sh
gh pr list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,headRefName
gh pr list --repo MacosPorters/betterxen --state merged --search "<event, symbol or file>" --limit 10 --json number,title,mergedAt
gh issue list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,labels
```
- **An open pull request covers it:** check out that branch (`gh pr checkout <n>`), run the build with it, and work there: report what you saw on the pull request, and push a fix to its branch or request changes. Do not write a second fix.
- **A merged pull request covers it:** sync with `origin/main` and run again before investigating.
- **An issue covers it:** take it up from the issue's notes, and link it from your pull request.
- **Nothing covers it:** carry on with step 1 below.
1. **Claim with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. Check the contract against the GDK where the GDK covers it.
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row. The test is what holds on every machine; your run is only why you looked.
5. **Verify:** every command in Section 8.
6. **Proof:** runs before and after on your machine, every run reported, with the machine and the `main` commit. Another collaborator's machine may never take the path yours took; say which path your runs took.
7. **Finish:** fill in the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof), sign off, no AI trailers, mark the pull request ready. Do not wait for CI before moving on.
8. **Stop.** The next "work" starts again at Step 2.
**If you cannot fix what you found** (too large, out of session, or it needs a decision): close your draft, file one **handoff issue** labelled `handoff` and `stage: <name>`, titled `[handoff] <signature>`, with what you saw, what you tried and what is still unknown. That is the only time a blocker gets an issue.
---
@@ -46,6 +115,7 @@ If the user asks to contribute, get started, or pick a task (even with a short p
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
- **GDK texture libraries (ADR 0010):** Console texture layouts (tiling) and BCPack decompression come from the GDK's own PC libraries, `xg_xs.dll` and `BCPack.dll`, which `bx-cli run` stages for the target build from the configured GDK. Do not reimplement them, and never commit or ship them.
---
@@ -64,8 +134,8 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
### Cross-Track `[ABI]` Rule
- Never edit another track's directory inside a feature PR.
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
- For issue-claimed contributor work, stay inside your issue's track directory; if your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first so provider and consumer tracks can implement in parallel.
- Maintainer-directed compatibility and startup-unblocking tasks may touch the required shim and `tests/conformance/` directories across tracks without a pre-existing issue claim. They must not overlap another contributor's active claim or open PR without that contributor's or a maintainer's recorded agreement, any new cross-DLL helper or export still goes through an `abi/`-only `[ABI]` PR first, and independent review (Section 5) still applies.
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
---
@@ -81,9 +151,7 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
## 4. Dependencies, Licensing & Provenance
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
_Reserved — policy migration in progress._
---
@@ -97,26 +165,34 @@ Every feature issue belongs to **one track** and defines an **exclusive file sco
---
## 6. Legal & Clean-Room Rules
## 6. Compatibility Evidence & Legal Boundaries
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
- **Authorized compatibility evidence:** Contributors and agents may use publicly accessible documentation, publicly licensed software, synthetic workloads, and **project-authorized target builds** (via local call-site inspection and runtime diagnostics) to establish undocumented Xbox OS, graphics, memory, storage, and runtime ABI contracts (struct layouts, flags, COM IIDs, vtable slot orders, and expected return/error semantics). Separate direct observations from inferences and verify every implemented contract with a synthetic conformance test under `tests/conformance/`. Such a test shows that a shim matches the recorded inference, not that the inference is correct.
---
## 7. Claiming, Git Safety & Changelog
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
3. **Isolate with branches or worktrees:**
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. Every problem met while running the game, not only the one picked, is searched for in open and merged pull requests and open issues before it is investigated; when a pull request covers it, check that branch out and work there (Section 0, Step 3). A draft with no push for 3 days may be taken over. Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
2. **Isolate with branches or worktrees:**
```sh
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
git worktree add ../wt-<slug> -b track-<a..f>/<slug> origin/main
```
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
### Merge eligibility
Four roles are separate: the **original author** (who opened the PR), **corrective contributors** (who later push to its branch), **independent approvers**, and the **merger**.
- The original author never merges their own PR. Any other maintainer may merge once required checks pass, at least one approval is current and blocking review conversations are resolved.
- Maintainers may resolve conflicts, correct defects, update documentation and push fixes to a contributor's PR branch where GitHub permissions allow. Doing so does not disqualify them from merging.
- Any push that changes the PR dismisses earlier approvals. After a **routine** push (conflict resolution that changes no behaviour, changelog correction, minor documentation fix), one new approval is enough and may come from the maintainer who pushed it, if they are not the original author. No further approval is required beyond the ruleset.
- **Substantive** implementation changes need independent review (Section 5): the approval must come from someone who did not write them. A maintainer who wrote substantive corrections may merge after another person has approved those corrections, but may not approve them. If in doubt, treat a change as substantive.
- A coding agent acts as the person it works for and merges only with that person's authorization.
The `Protect main` ruleset enforces pull requests, one approval, dismissal of stale approvals, resolved conversations, the required CI checks and no force push or deletion, with no bypass actors. GitHub cannot enforce two rules above: who may merge (`Merge policy audit` only fails after an author self-merge) and whether an approver wrote part of the change.
---
@@ -129,8 +205,9 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli # must print: arm64
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
# 2. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust bx_shader_bridge.dll, and
# build the auto-discovered conformance EXEs
# (strictly verifies all 17 .edata Export Directories: names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
scripts/build-shims.sh
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + Rosetta 2
@@ -141,3 +218,20 @@ target/debug/bx-cli trace /tmp/bx-test.jsonl
# 4. Repository Markdown link & hygiene check
python3 scripts/audit/docs_hygiene.py
```
---
## 9. AI Agent Efficiency & Resource Management
These rules apply to every coding agent, whatever its model, vendor or plan. Saving resources never justifies skipping necessary verification, fabricating or assuming results, weakening a security, legal or provenance safeguard, or bypassing independent review. Where this section and Sections 4–8 appear to conflict, Sections 4–8 win.
- **Spend in proportion:** Keep token consumption, API usage, reasoning effort and compute cost as low as correctness allows.
- **Reuse what is still valid:** Reuse conversation context, repository knowledge, review findings and verification evidence. Evidence is valid only for the revision and environment it was recorded on; re-run whatever a later change could affect.
- **Read narrowly:** Inspect relevant files and incremental diffs instead of rescanning the repository. Batch independent tool calls and GitHub API requests where practical.
- **Delegate sparingly:** Avoid unnecessary subagents, duplicate investigations and overlapping responsibilities. Independent review (Section 5) is not duplicate work.
- **Reasoning effort:** Default to low for routine tasks and for helper subagents; raise it only when technical complexity justifies it or the user asks.
- **Verify without redundancy:** Use targeted checks while iterating and for small changes. This does not replace Section 8 or required CI. Do not repeat builds, tests or CI runs when nothing relevant has changed, and do not poll workflows repeatedly.
- **Communicate concisely:** Report outcomes, blockers and what is needed next; skip lengthy status reports and repeated summaries.
- **Blocked work:** Do not re-review an unchanged PR that is waiting on an unresolved external blocker.
- **Finish authorized work:** Carry an authorized task through to completion, including a merge that is authorized and eligible (Section 7), instead of stopping at intermediate reports. This grants no permission beyond Section 7.
- **Escalate real uncertainty:** Raise genuine doubt about ABI compatibility, memory safety, concurrency, security, GPU synchronization, licensing or architecture with a maintainer rather than guessing.
+283
View File
@@ -9,7 +9,251 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Changed
- **Current stage: Picture** (`docs/roadmap.md`), by the repository owner's decision on 2026-11-30. Boot is marked as left without its ten-run gate having been run under the run protocol. The first frames and the menus are reached, and the open work is translation, textures and stability. The new pinned ladder issue carries the live status. The repository owner also accepted the LLVM-generated opcode table and test vectors of `gfx10-translate` (`docs/research/upstream-registry.md`).
- **`CONTRIBUTING.md` is a short entry point for new members, consistent with AGENTS.md.** It covers the hard requirements (the target build, the GDK and the Ghidra results, distributed among members), setup (`setup --find`, `preflight`), the current way of working (pick order, checking for existing work, draft pull request claims with the 3-day rule, tests, Section 8), and running the target build with its diagnostic switches. The outdated workflow is removed: issue-comment claims, the 7-day rule and the Wave 1 backlog. The licensing, sign-off and merge sections are unchanged.
- **Check for existing work before investigating any problem the game shows** (AGENTS.md Section 0 Step 3 and Section 7, `docs/process/working-method.md`). Every problem met while running the game, not only the picked blocker, is searched for in open and merged pull requests and open issues by its log event, stub symbol, error code and files. An open pull request that covers it is checked out and worked on, never duplicated. Prompted by a duplicate fix for physical-page DirectStorage requests made alongside #707.
- **The Ghidra results of the target build are required to work on the repository**, like the target build and the GDK (AGENTS.md Section 0, `docs/process/working-method.md`). An agent that lacks any of the three does not work on the repository. `bx-cli preflight` adds a `Ghidra results` row: present, and covering the configured target build's executable. `bx-cli setup --ghidra-results <dir>` saves them, and `setup --find` finds them by layout (`RUN_REPORT.md`, `decompiled/`, `exports/*/manifest.json` naming the program, `functions.csv`). `BX_GHIDRA_RESULTS` overrides the setting for one command. Unit tests cover an unset setting, a folder that isn't a results folder, results for another program, and results covering the target.
- **Roadmap, Picture stage: BetterXen writes its own shader translator** (repository owner's decision, 2026-11-29). The step that said to vendor the upstream GFX10-to-DXIL translator now describes a translator of our own in `shader-transpiler/`: one rule per instruction, control flow as numbered blocks, each rule checked against the console compiler.
- **A collaborator only has to say "work"** (AGENTS.md §0, step 1). When `bx-cli preflight` fails, the agent makes the machine ready itself: the new `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (a large PE32+ file that imports `d3d12_xs.dll`; never by name), ignores the GDK's own tools, treats byte-identical copies as one build and keeps the copy with its imported DLLs beside it, and saves both settings. The agent may install `mingw-w64`, `cmake` and `gh` with Homebrew and free disk space by removing its own scratch. It stops only for what it cannot supply: no Apple Silicon Mac, no CrossOver, the build or the GDK not on the machine, or more than one distinct build.
- **Working rules: the pull request is the unit of work, and the target build and the GDK are required** (AGENTS.md §0, [working method](docs/process/working-method.md)). An agent told to "work" first runs the new `bx-cli preflight`, which fails unless the host is an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`, the target build's executable and the GDK folder are known, and 10 GiB of disk is free. A collaborator records the two locations once with the new `bx-cli setup --target-exe <path> --gdk-root <folder>`, which checks them and keeps them in `~/.config/betterxen/local.conf`, outside the repository (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it). If preflight fails the agent stops and does no work. A blocker the agent can fix no longer gets an issue: it is claimed by a draft pull request titled with its run-report signature. Issues are kept for handoffs (label `handoff`), decisions for a person, and the ladder status. Claims by comment and the 7-day stale window are gone; an idle draft may be taken over after 3 days.
- **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.
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
### Added
- **`gfx10-translate`: integer, conversion and lane instructions** (#716).
- **Scalar:** `s_add_i32`, `s_sub_i32`, `s_min_i32`, `s_max_i32`.
- **Conversions:** `v_cvt_u32_f32`, with the ISA's clamping of NaN, negative and too-large values; `v_cvt_f32_ubyte0`–`3`; `v_rcp_iflag_f32`.
- **New three-source integer table (`VOP3_UINT3`):** `v_lshl_add_u32`, `v_add_lshl_u32`, `v_lshl_or_b32`, `v_and_or_b32`, `v_or3_b32`, `v_xor3_b32`, `v_add3_u32`, `v_bfi_b32` and `v_bfe_u32`.
- **Lanes:** `v_readfirstlane_b32` as `WaveReadLaneFirst`.
- **Measured locally:** 802 of the target build's 4,331 vertex and pixel shaders translate on their own, up from 703.
- **Tests:** `integer_conversion_and_lane_instructions`, with llvm-mc encodings and expected HLSL from the ISA definitions. The prototype goldens are unchanged.
- **`shader-transpiler/crates/gfx10-translate`: BetterXen's GFX10.3 shader translator on `main`** (roadmap, Picture stage). It replaces the experiment-branch Python prototype, which moves to `scripts/console-shader/translate.py` as the reference.
- **Pieces:** console container reader (zlib ported from `zlib_inflate.cpp`); a decoder for every encoding format, with SDWA/DPP extension words; HLSL translation of every prototype rule through family tables; and coverage. `bx-cli shader translate <vs> <ps> --out <dir>` and `bx-cli shader coverage <dir>` run it.
- **Opcode table:** generated from the public LLVM disassembler by `scripts/console-shader/gen_opcodes.py` (gfx1030, gaps from gfx1010, whose GFX10.1 multiply-adds the console compiler emits). Facts only; recorded in the upstream registry.
- **Tests:** 127 instructions decode to exactly the text `llvm-mc` prints (`tests/llvm_vectors.txt`). Three shader pairs of our own, assembled by `llvm-mc`, translate to exactly the prototype's HLSL and layout (`tests/goldens/`). Plus refusals, the multiply-add family, wave32 mask bookkeeping and half compressed exports, and FNV-1a against the published vectors.
- **Measured locally on the target build's 4,331 vertex and pixel shaders** (they stay local):
- every one decodes; the scan takes 3.6 s, against about 10 minutes through `llvm-mc`;
- 703 (16.2%) translate on their own, against 491 for the prototype's rules alone;
- all 214 pipeline pairs the prototype translated give identical HLSL and layout.
- **Differences from the prototype** are listed in the crate README. Among them: `s_movk_i32` sign-extends, and cache keys use standard FNV-1a (the prototype's offset basis is missing a digit).
- **Unattended runs get past input screens and continuable asserts** (`docs/testing/target-build-review.md`, Diagnostics).
- **`GameInput.dll`:** `BX_INPUT_SCRIPT=A@40,DOWN@50.5,...` presses gamepad buttons at given seconds after the first reading, each for 300 ms, without window focus. Each press, and each entry it cannot read, is logged (`input_script`).
- **`bx_runtime_veh.dll`:** `BX_CONTINUE_ASSERTS=1` steps over an `int3` in the title's own executable instead of letting it reach the crash reporter, and logs each address once (`assert_continued`). An `int3` anywhere else is left alone.
- **Tests:** `test_gameinput_script` (readings at fixed times carry exactly the scripted buttons, and unreadable entries are skipped) and `test_veh_continue_asserts` (the executable's `int3` is stepped over twice; one outside any module is not). Both fail on `main`'s shims and pass twice with these.
- **The GDK's texture libraries at run time (ADR 0010).** Console texture layouts and BCPack come from the GDK's own PC libraries instead of being reimplemented.
- **`bx-cli run`** stages the configured GDK's `xg_xs.dll` (in place of the `xg_xs` shim) and `BCPack.dll` (named to `XCRDAPI.dll` through `BX_BCPACK_DLL`) when the executable is the configured target build, or with `--gdk-libraries`; `--no-gdk-libraries` turns it off. The libraries are recognised by their exports (`gdk_libs.rs`), copied into a temporary shim folder for the run, and never committed. Conformance tests keep BetterXen's own shims.
- **`d3d12_xs.dll`** answers `GetResourceAllocationInfo`, `GetResourceAllocationInfo1` and `GetResourceAllocationInfo2` for console texture layouts (`Layout >= 0x100`) with the GDK's XG size and base alignment (`gdk_xg.cpp`), other descriptions with the host's answer, laid out in order at their alignments. It enables XG's exclusive locking at device creation, since the title and the shim both create XG texture computers. Without the GDK's XG, sizes stay as before and the run log says so (`gdk_xg`).
- **Tests:** `test_d3d12_gdk_xg_sizes` loads a stand-in XG library with answers the test computes (not Microsoft's code) and checks the sizes, alignments, the two-description layout and the locking. On the previous `d3d12_xs.dll` 6 checks fail; with this change it passes twice. `bx-cli` unit tests cover recognising the libraries by their exports and merging them beside the shims.
- **Measured** on the target build (Apple Silicon, CrossOver 26.3, offline, scripted input): the launcher staged both libraries; XG answered 48 console-layout size queries; with #709, 0 page-destination errors, 0 zlib failures and 0 refused BCPack requests. 14 partial reads of compressed blocks remain, so the allocation size is not the only place the title gets a short size (#708 stays open).
- `GameInput.dll` exposes one keyboard-backed gamepad through v0 blocking enumeration and current readings. Enter or Space maps to A, Escape or Backspace to B, arrow keys to the D-pad, WASD and IJKL to the two sticks, Q/E to shoulders, Z/C to triggers, F/H to stick clicks, X/Y to the matching face buttons, and P/Tab to Menu/View. Input returns to neutral when another application owns the foreground.
- **D3DMetal capability checks for translated console shaders** (#671). `test_d3dmetal_translator_caps` measures, against the host D3D12 runtime, the features a translator of console code needs: SM 6.6 descriptors fetched by index (UAV, raw and typed SRVs, texture and sampler) run correctly; a 64-lane wave emulated over a 64-thread group gives the 64-lane answers through groupshared memory and through merged 32-lane host waves; amplification and mesh shaders draw correctly. With the 64-bit atomic results of `test_d3dmetal_gpu_limits` (native 64-bit atomics are not run even though D3DMetal reports support; the lock emulation with a 1024 cap is exact), no need is blocked. Results are in [D3DMetal GPU limits](docs/research/d3dmetal-gpu-limits.md#capability-checks-for-translated-console-shaders-671).
- `xgameruntime.dll` serves `XGameSaveGetContainerInfo` (slot 13) and `XGameSaveEnumerateContainerInfoByName` (slot 15) on `IXGameSaveImpl` (#667). `XGameSaveGetContainerInfo` reads container metadata without loading blob payloads and, when the named container does not exist, succeeds without invoking the callback (source rank 3 inference). `XGameSaveEnumerateContainerInfoByName` filters containers by name prefix (treating `nullptr` or empty prefix as all containers), sorts by name, and stops early when the callback returns `false`. `test_xgameruntime_saves` checks both slots through `QueryApiImpl`.
- `xgameruntime.dll` serves `XAsyncRun`, `XTaskQueueCreateComposite`, `XTaskQueueGetPort` and `XTaskQueueDuplicateHandle` through `IXGameRuntimeCore` slots 6, 13, 14 and 15 (#666). `XAsyncRun` runs the title's work callback on the block's work port and completes the block with its result. A duplicated queue handle shares the queue, and only the last close shuts its lanes down. A composite queue forwards each port to the port it was made from, and an async block's completion returns through the queue the block named. A project-authorized target build uses these for its save-game work and exited when `XAsyncRun` was unimplemented. `test_xgameruntime` checks all four through `QueryApiImpl`.
- `bx-cli report <log.jsonl>...` (#664, part 1): a run report per log (one log is one run) and a summary across runs. Per run: how it ended, the frames presented (a lower bound), every unimplemented call with its count, faults whose innermost frame is in a BetterXen module, and pipelines by kind. The summary counts clean runs and lists each blocker signature with the number of runs that hit it; blocker issues are titled with those signatures. `bx-cli run` now appends a `run_end` record to its log (exited with a status, timeout, signal or launch failure), which the report reads. A log without it has an unknown outcome and is never counted as clean.
- `xgameruntime.dll` serves `XUserDuplicateHandle` through `IXUser` slot 3 (#680). A duplicate is a new handle to the one offline user; each handle is closed on its own, and `XUserCompare` returns 0 for any two valid handles of that user. A project-authorized target build duplicates its user handle after sign-in and waited when the slot was unimplemented. `test_xgameruntime` checks the slot through `QueryApiImpl`.
- Shader corpus, Phase 0 of the console shader translator (#649). `shader-transpiler/corpus/hlsl/` holds eight BetterXen-authored compute kernels covering integer and float ALU, divergent branches, loops, groupshared memory, wave operations, atomics and system values. `scripts/shader-corpus/build.sh` compiles each one locally with the console `xdxc` (a title-style container: `DXIL` plus `ACCC`/`FSPX`), the console PIX compiler (Microsoft's ISA listing) and the public PC DXC (DXIL for a D3DMetal reference run). `extract_code.py` then takes the code from the `FSPX` kind-6 section, skips the leading `v_nop_xbox_data` words and disassembles it with LLVM's public `gfx1030` decoder. All eight kernels build and decode cleanly. The extractor has nine unit tests on synthetic containers that need no GDK. Compiler outputs stay in the git-ignored `target/shader-corpus/`. One open question is recorded: a `v_cmp_class_f16` in the `wave` kernel's ballot sequence.
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
- `AcpHal.dll`:
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
- **The default APU heap** is 64 MB.
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
- **Samplers and page pools.**
- **Pipelines** through the shader gate.
- **Opt-in null rendering** (`BX_NULL_RENDER=1`): pipelines that cannot be built become null pipelines, and their draws and dispatches are skipped and logged.
- **Fences** at GPU addresses and GPU value writes.
- **`PresentX`** onto a DXGI swapchain.
- **Console page mappings:** `CopyPageMappingsX`, `CopyPageMappingsBatchX` and `ClearPageMappingsX`.
- **The full 1,384-byte Xbox command-list area.**
- **Opt-in dumps of presented frames** (`BX_PRESENT_DUMP`).
`test_d3d12_xbox_layout` checks the page mappings and the command-list area.
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
- `d3d12_xs.dll` gives titles Xbox-layout D3D12 objects ([ADR 0009](docs/adr/0009-xbox-layout-d3d12-objects.md)). A title built against the Xbox Series D3D12 header calls through function tables whose order differs from PC D3D12. `ID3D12Device` matches only up to slot 43, and `ID3D12Device11` has 139 slots. So before, every call past those slots reached the wrong PC method, and on a project-authorized target build the first such call jumped to address 0.
- **Objects and tables:** `BxXboxObject` (`shims/d3d12_xs/xbox_facade.{h,cpp}`) has the Xbox object layout and sets `m_OutOfLineFlags`. Its Xbox-order table forwards to the PC proxies. `shims/d3d12_xs/tools/gen_xbox_tables.py` generates the tables (`xbox_tables_generated.cpp`) from the Xbox header, used under Microsoft's authorization, and the toolchain's `<d3d12.h>`. It takes only slot order, names, IIDs and parameter types, and the header is not committed.
- **Slots:** a slot with an equivalent PC signature forwards with the PC types, unwrapping interface parameters and wrapping created objects. Every other slot logs `BX_VTABLE_STUB_LOG`.
- **Coverage:** the device chain up to `ID3D12Device11`, plus resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues. Command lists are not covered yet.
- **`CreateCommandQueueX`:** maps the Xbox queue description onto PC `CreateCommandQueue`.
- **Layout choice:** titles set `Version` in the device parameter block and get the Xbox layout. BetterXen's PC-layout fixtures pass a zeroed block and keep the PC proxy. The choice is logged as `xbox_layout`.
- **Phase 2:**
- **Command lists:** `ID3D12GraphicsCommandList8`, created through `CreateCommandListX` or `CreateCommandList`. Their zeroed put-buffer fields force the five inline fast paths through the table.
- **Embedded interface pointers:** `ResourceBarrier` and `CopyTextureRegion` unwrap the interface pointers inside their structures.
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` are emulated by a host timer (`frame_pacing.cpp`).
- **Generator fixes:** CRLF lines, a table-boundary overrun that hid `ID3D12GraphicsCommandList1`, nested SAL, and `FLOAT`.
- **Resources at title-chosen addresses:** `CreatePlacedResourceX`/`X1` create host shadow resources (`placed_x.cpp`), with buffer contents copied from the title's memory at creation. The resource reports the title's address from `GetGPUVirtualAddress`. Ongoing synchronisation, GPU-to-CPU copies, title-address translation in GPU calls and texture contents are not implemented yet.
- **Test:** `tests/conformance/test_d3d12_xbox_layout/` calls Xbox slots by number, with the slot numbers and offsets written out by hand from the header and the expected values taken from a PC-layout device. It also records a buffer copy through Xbox command objects, runs it on the GPU and reads the result back, and checks frame pacing. It fails against the previous DLL (8 checks against the Phase 1 build).
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
### Fixed
- **`XCRDAPI.dll`: physical-page destinations are mapped when the request runs, partial reads of compressed blocks are delivered, and BCPack requests can be decoded.**
- **Page array timing:** a title can fill the `DestinationPageArray` of a `DestinationIsPhysicalPages` request after `EnqueueRequest` returns. #707 read the array at enqueue, so such requests failed (in the target build, about 290 per run named page 0). The array is now read, and its pages mapped, when the request runs; they are unmapped once it is fulfilled.
- **Partial compressed reads:** a title may ask for only the first `DestinationSize` bytes of a zlib block (in the target build, 8 to 128 KiB blocks read 4 to 16 KiB at a time; 16 failures per run). The whole stream is decoded, its Adler-32 checked, and its first `DestinationSize` bytes delivered; a stream shorter than the destination is still an error. Logged as `dstorage_zlib_partial`.
- **BCPack:** a request with `BcpackMode` 1 to 7 is decoded with `BCPackDecompress` from the GDK's own `BCPack.dll` when `BX_BCPACK_DLL` names it (the collaborator's GDK; nothing from the GDK is shipped). Without it, or combined with zlib, BCPack stays refused with `E_NOTIMPL`. Logged as `bcpack_codec` and `dstorage_bcpack_failed`.
- **Tests:** `test_xcrdapi_page_destination` (24 checks) adds a page array filled after `EnqueueRequest` and a 4096-byte zlib destination from a 136000-byte stream (exact first part, nothing written past it). Both fail on the previous shim (4 checks) and pass twice with this one. BCPack needs the GDK's decoder, so it is not covered by a conformance test.
- **`GetFrameStatisticsX` is implemented** (#701). Slot 81 of the Xbox device table returned `E_NOTIMPL`, which the documented method never returns. It now answers as the authorized GDK documentation describes: frame-event (ORIGIN: wait call, signal and wait return) and present (PresentX call and return) statistics per frame pipeline token for the last 17 frames, in QueryPerformanceCounter ticks; `S_FALSE` when none of the requested types is available; `E_INVALIDARG` for unknown tokens, invalid type sets and invalid list arrangements. Interval, power-scaling, render, display and input statistics have no host source and are never reported; `GPUProcessTime` is 0 (not measured). Test: `test_d3d12_frame_statistics_x`.
- **`CreateCommittedResourceX` is implemented** (#696). Slot 76 of the Xbox device table takes a `D3D12XBOX_RESOURCE_DESC`, which is the PC resource description followed by `DccOptions` (authorized GDK header). It now creates the resource from the PC part through the same path as `CreateCommittedResource` (console format translation, the `XMemAlloc` request a title's hook sees); `DccOptions` (a struct of `CompressionLevel` and `ColorTransform`), console colour compression, has no host counterpart; both fields are logged for the first 8 calls and ignored. Until now the slot returned `E_NOTIMPL`, and the target build exited with status 99 about a second after it was refused. `tools/gen_xbox_tables.py` routes the slot to the new entry point; the regenerated table differs only there. Test: `test_d3d12_committed_resource_x`.
- `xmem.dll!XMemGetWorkingSetStatistics` takes the documented `(WorkingSetFlags, Statistics)` and fills the documented 120-byte `XMEM_WORKING_SET_STATISTICS` (source: the authorized GDK header). Before, it took `(out_stats, stats_size)` and wrote BetterXen's own 32-byte `bx_xmem_stats_t`. A title calling it as documented had its flags read as the output address and its structure pointer as the size, and the shim zeroed memory at the flags value. A project-authorized target build calls it on a tools-memory path with the tools and kernel-pool flags and treats `FALSE` as fatal; runs have not reached that path yet.
- **Values:** the whole structure is written, whatever the flags. `GameLimit` is the title cap, `GameUsed` everything the cap counts (XMem heap, virtual commits, physical pages and external charges), `GameUsedPeak` its highest value and `GameAllocatedPhysicalPageCount` the 64 KiB physical pages. The tools fields are 0, since `XMemIsToolsMemAvailable` is `FALSE`. The counters the host does not have or xmem does not count are 0 (stack, GPU-optimal bandwidth, kernel pool, DirectStorage, frame-preserve buffer, page tables), and so are the reserved words. These values are BetterXen's inference.
- **Refusals:** a NULL structure, or flags outside the five `XMEM_WORKING_SET_*` values, fails with `ERROR_INVALID_PARAMETER` and logs `working_set_statistics`. `bx_xmem_get_internal_stats` is unchanged for internal callers.
- **Tests:** new `test_xmem_working_set` reads the structure between guard bands at offsets written out from the header, with the tools and kernel-pool flags, `XMEM_WORKING_SET_TITLE` and `XMEM_WORKING_SET_ALL`. Against the previous `xmem.dll` it fails with an access violation inside the call. `test_xmem`, `test_xmem_physical`, `test_xmem_external_charge` and `test_d3d12_placed` use the documented form. `test_xmem_physical` now reads its two aliased page views through `volatile`: the compiler cannot see that they share a page, and after this change it scheduled the read before the write.
- **Not covered:** `XMemVirtualQuery` and `XMemTransferMemory` still differ from their documented signatures (#642).
- **`XCRDAPI.dll`: DirectStorage requests can write into physical pages** (#705). With `DestinationIsPhysicalPages` (bit 21 of `DSTORAGE_REQUEST_OPTIONS`), the destination of an Xbox request is an array of 64 KB page numbers from `XMemAllocatePhysicalPages` and a 16-bit offset into the first page, at +0x08 and +0x10 (authorized GDK header). `IDStorageQueueX::EnqueueRequest` refused such requests with `E_NOTIMPL`, and the target build stopped at a breakpoint about two milliseconds later (exit status 3). The request now maps its pages through `xmem.dll`'s `XMemMapPhysicalPages` with a NULL address (the existing BetterXen extension) into a span of its own, writes the destination there, file or memory source, plain or zlib, and unmaps the span once it is fulfilled; the pages are sections, so the title's views see the bytes. A physical-page source (`SourceIsPhysicalPages`) is still refused and logged as `EnqueueRequest_physical_page_source`. Test: `test_xcrdapi_page_destination` (19 checks: a zlib file request across three pages given out of order from an offset, an uncompressed memory request across a page boundary, an unallocated page number, the refused source form).
- **`d3d12_xs.dll`: index and vertex data bound from plain title memory are drawn.** A title keeps such data in its own memory with no Direct3D resource, and may write it after recording the draw. A bound range now gets a CPU-writable host buffer (once; later ranges inside it reuse it) and every range bound on a list is copied from the title memory when the list is submitted (`bx_xbox_bind_title_memory`, `placed_x.cpp`). This replaces leaving such bindings empty; only memory that is not readable is still left empty and logged as unimplemented. Tests: `test_d3d12_title_memory_geometry` (26 checks, pixel readback, data written after recording and changed between submissions); `test_d3d12_unbacked_buffers` now covers the unreadable case.
- **`d3d12_xs.dll`: console rectangle lists are drawn.** `D3D_PRIMITIVE_TOPOLOGY_RECTLIST` (17) and the pipeline topology type `D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT` (19) are Xbox extensions (GDK `d3d12_xs.h`): three vertices per rectangle, the fourth corner `v0 + v2 - v1`. The host knew neither value, so a title's full-screen passes drew half a rectangle or nothing. A rectangle list is now drawn as triangle strips (`rect_list.cpp`): the pipeline is created with the triangle type, and a non-indexed draw builds four vertices per rectangle from the title's vertex data and the pipeline's input layout. Indexed rectangle lists and quad lists are not emulated and are logged as unimplemented. Test: `test_d3d12_rect_list` (25 checks, pixel readback).
- **`bx_runtime_veh.dll`: a CLWB range loop completes in one exception.** A title flushes an address range with `clwb [reg]; add reg, 0x40; cmp reg, <reg64>; jbe|jb`; each CLWB trapped under Rosetta, about 94,000 exception round trips per 6 MiB buffer. CLWB changes no register, flag or memory, so the handler now advances the pointer register to the last value the loop would have used and the title's own add/cmp/jcc leaves the loop. Other forms keep the per-instruction path. Test: `test_veh_clwb_loop` (15 checks; without the fix the four loop cases take one exception per line).
- **Committed render targets request the console's size from XMemAlloc** (#695). The console lays out a 2D render-target or unordered-access texture with one mip and one sample in 64 KB tiles (64KB_R_X for every size: 128x128 elements at 4 bytes, 128x64 at 8, 64x64 at 16, 256x128 at 2, 256x256 at 1; authorized GDK XG library), and a title that hooks XMemAlloc sizes its pool for those requests and asserts that less than 2 MB is left over. `d3d12_xs.dll` requested the host's size instead, 1920x1080 RGBA8 as 128 pages where the console takes 135, and on the Series S path the target build stopped on that assertion. The XMemAlloc request for those textures is now the tile size, computed from the title's format; every other resource keeps the host's size, and XG's render-target compression metadata after the tiles (8 KB to 96 KB in the cases measured) is not modelled. `GetResourceAllocationInfo` still answers with the host's size. Test: `test_d3d12_committed_tile_size`.
- **The console type is published where a title reads it** (#692). A title can read the REG_DWORD `ConsoleMode` under `HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM` instead of calling `XSystemGetDeviceType`: 0x60 is Series S, 0x64 Series X and 0x68 the Scarlett devkit, and without the value the title takes itself for a PC and sizes its memory for Series X. Wine has no such value, so under the Lockhart profile the target build asked for its Series X memory set and stopped on the 8 GiB budget. `bx-cli run` writes the value in the selected Wine environment before launching the guest, using the same profile as `XSystemGetDeviceType` (0x60 for Lockhart, 0x64 for Anaconda). `--profile` is matched without regard to case, as the shims match `BX_PROFILE`, and a value other than `lockhart` or `anaconda` is refused, so the two cannot name different consoles. The test `test_console_mode` reads it the way the title does and checks it against the profile and `XSystemGetDeviceType`.
- **XCRDAPI holds an xmem guard while accessing title memory** (#668). Replacing a mapped view on Windows or Wine can temporarily make pages in that view inaccessible. DirectStorage reads and writes that can touch title memory now hold the shared guard while xmem mapping and freeing operations hold it exclusively. A loaded xmem DLL without both guard exports produces a warning. The guard covers DirectStorage accesses through BetterXen. `test_xcrdapi_remap_guard` exercises memory-to-memory stores into a window, zlib streams inflated into it and memory requests reading out of it while it is remapped; accesses by the title's own threads are not covered.
- **`d3d12_xs.dll`: an index or vertex binding at a title address without a host buffer no longer crashes the process.** A title binds index and vertex data by address in plain title memory, with no Direct3D resource behind it. The address reached D3DMetal unchanged and it read through a null buffer (`IASetIndexBuffer`). Such a binding is now left empty and logged as unimplemented (`IASetIndexBuffer(title memory without a host buffer)`, likewise `IASetVertexBuffers`); bindings inside resources BetterXen created are translated as before. Supplying the data is separate work. Test: `test_d3d12_unbacked_buffers` (13 checks; without the fix it dies with the same null read).
- **`d3d12_xs.dll`: console-only DXGI formats and depth-stencil unordered-access views no longer end the process.** The Xbox Series `DXGI_FORMAT` enumeration has values the PC one lacks (116-120, 189, 190; GDK `d3d12_xs.h`). D3DMetal turns one into an invalid Metal pixel format and Metal aborts, which a target build's crash reporter then turned into either "exit status 5" or a stall with every thread stopped.
- **Formats:** `console_formats.h` maps each to the nearest host format (a depth texture is created typeless, each view names the concrete format). The three `GetResourceAllocationInfo` forms, `CreatePlacedResource`, `CreateReservedResource`, the four view-creation methods, the committed-resource forms and the placed (X) resource and view forms translate before the host call.
- **Depth-stencil unordered-access views** (allowed on the console, forbidden on PC): the descriptor gets a null view and the call is logged as unimplemented (`CreateUnorderedAccessView(depth-stencil resource)`).
- **Limits:** sizes reported for a translated format are the host format's, `GetDesc` reports the host format, and pipeline-state formats are not translated yet.
- **Test:** `test_d3d12_console_formats` (21 checks; without the fix the process dies at the first console-only format).
- `bx_runtime_veh.dll` completes a `CLZERO` loop in one exception (#665). A title that zeroes memory with `clzero; add rax,0x40; cmp rax,<reg64>; jb` raised one illegal-instruction exception per 64 bytes under Rosetta 2, which stalled a project-authorized target build's frame loop for tens of seconds. When the trapped `CLZERO` is followed by exactly that form, the handler zeroes every remaining line below the limit and leaves `RAX` at the last one, so the title's own `add`/`cmp`/`jb` leaves the loop. The range is zeroed region by region and stops at memory that is not committed and writable, where the next `CLZERO` traps and faults as before. Other loop forms keep the per-instruction path. `test_veh_clzero_loop` checks the memory result and counts the exceptions; it fails on the old handler.
- `d3d12_xs.dll` no longer turns `DeserializeGraphicsPipelineStateX`, `DeserializeComputePipelineStateX`, `CreateDerivedGraphicsPipelineStateX` or `CreateDerivedComputePipelineStateX` into null pipelines in null-render mode (`BX_NULL_RENDER=1`) (#669). All four calls now always return `E_NOTIMPL`, clear `*ppv` and log `pipeline_refused` without `; null pipeline returned`, so a title falls back to creating pipelines from shader containers instead of silently receiving null pipelines. `test_d3d12_serialized_pipelines` checks all four slots and their refusal log lines with `BX_NULL_RENDER=1` active alongside a control shader-container null pipeline.
- `XCRDAPI.dll` Xbox DirectStorage fixes:
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
- `xmem.dll` follows the documented signatures of five exports (source: the authorized GDK documentation). Before, a title calling them as documented had its arguments misread: on a project-authorized target build, `XMemAllocatePhysicalPages` failed and the title's check broke into its crash reporter. `XMemAllocatePhysicalPages` accepts `MEM_64K_PAGES` (`MEM_2MB_PAGES | MEM_PHYSICAL`) as 64 KB pages, as Microsoft's public samples pass it; the `MEM_2MB_PAGES` bit alone is `XMEM_2MB_CLUSTERS`, still unimplemented and logged. `test_xmem_physical` adds the samples' shape: a `MEM_64K_PAGES` page mapped into a mappable reservation made with protection `0x2404`.
- **Signatures:** `XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray)`, `XMemFreePhysicalPages(NumberOfPages, PageArray)` (count by value), `XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray)` and `XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)` (parallel arrays, returns `BOOL`). `XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection)` takes five arguments, which supersedes the closed #518.
- **Pages and flags:** physical pages are always 64 KB. The four memory-bandwidth values are accepted. `XMEM_2MB_CLUSTERS` and mapping into `MEM_2MB_PAGES` reservations are not implemented: they log `BX_STUB_LOG` and fail with `ERROR_NOT_SUPPORTED`. Other flag bits fail with `ERROR_INVALID_PARAMETER`.
- **Mapping:** `XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)` reserves a placeholder, and `XMemMapPhysicalPages` maps into it. It replaces pages already mapped there, a NULL page array unmaps, and an unmapped range stays reserved and can be mapped again. Scatter checks every entry before changing any, and a 0 tag unmaps its slot. Mapping outside a mappable reservation is refused. A NULL address remains a BetterXen extension for synthetic fixtures: the shim picks the span, and unmapping it frees it.
- **Title-managed placeholders:**
- `XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)` reserves a placeholder the title splits itself with `VirtualFree(MEM_PRESERVE_PLACEHOLDER)`.
- `MEM_REPLACE_PLACEHOLDER` with `XMEM_MAPPABLE` turns a split part into a mappable range without a new reservation. It is refused unless the part is still a placeholder.
- `XMEM_GRAPHICS_32BIT_ADDRESS` keeps new reservations below 4 GB.
- The `PAGE_GRAPHICS_*` protection bits set a GPU view the host does not have, so mapped views use the low-byte CPU protection.
- Replacing a placeholder with committed memory is not implemented and logs `BX_STUB_LOG`.
- A project-authorized target build lays out its descriptor memory this way.
- **Tests:** `test_xmem_physical` is rewritten against the documented contracts, with constants written out from the documentation, and fails against the previous `xmem.dll`. `test_xmem`, `test_xmem_external_charge`, `test_d3d12_placed`, `test_d3d12_vmem_xbox`, `test_m2_first_frame` and `test_integration_boot` use the documented signatures.
- **Not covered:** `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` still differ from their documented signatures (#642).
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
- `d3d12_xs.dll!D3D12XboxCreateDevice` takes the documented four parameters `(pAdapter, pParameters, riid, ppDevice)`. Before, it took three `(params, riid, ppv)`, so a title calling it as documented had its interface ID treated as the out pointer, and the shim wrote through it. On a project-authorized target build that faulted on a write into read-only data. Source: the authorized GDK documentation of the function and of `D3D12XBOX_CREATE_DEVICE_PARAMETERS`. A NULL parameter block now fails with `E_INVALIDARG`, as documented. A non-NULL adapter is logged and the default host adapter is used, which is an inference, since BetterXen has no adapter objects. Of the parameter block only `Version` is read and logged. All fixtures that create a device pass a zeroed 80-byte parameter block. `test_d3d12_xs` checks the NULL-parameter refusal and that it clears the out pointer.
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
- `bx-cli`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
- `XCRDAPI.dll` completes a multi-request batch from one `Submit()` in queue order into CPU memory, mapped D3D12 upload buffers, and default buffers (a copy on the resource's device when the heap is not CPU-visible). If that copy has been submitted and its GPU completion is not confirmed, the shim keeps the destination and the copy's GPU objects alive and logs a warning, unless the device was removed or the fence already reached the waited value. The request still returns the failure HRESULT. LZ, BCPack, and GDeflate requests finish as `E_NOTIMPL` and log `BX_VTABLE_STUB_LOG`. `DStorageGetFactory` remains the only export (#467).
- M2 Shader Format Gate (#466). `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` classify every stage through `bx_shader_bridge.dll` (#445) and log one `shader_gate` JSONL record per stage: kind, stage, shader model, chunk sizes, `SFI0` feature flags and `PSV0` wave lane range.
- **Decisions:** DXIL and dual containers go to the host as the bridge's prepared copy. ACCC-only containers are refused with `E_NOTIMPL` before the host is called. Legacy DXBC and unclassifiable input pass unchanged. The bridge is loaded only by full path from `d3d12_xs.dll`'s directory. A missing bridge is logged once as `shader_bridge_missing`. Shaders then pass unclassified, but a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it.
- **D3DMetal gaps:** stages needing a wave wider than 32 lanes or 64-bit atomics also log `shader_d3dmetal_gap`, the cases #453 measured as created but not run. The structural check now counts an `ACCC` chunk as a shader chunk, so the gate decides it.
- **Test:** `tests/conformance/test_shader_gate/` runs a real DXC SM 6.6 compute shader through `d3d12_xs` and checks 256/256 output words. It requires `E_NOTIMPL` for an ACCC-only compute and graphics shader, and checks the logged wave64 and typed 64-bit-atomic constraints and every JSONL record. It then reruns itself from a directory without the bridge, which must still run DXIL and refuse ACCC-only. It passed on one Apple M5 Pro in a CrossOver 26.3 D3DMetal bottle. A bare prefix's vkd3d cannot load a DXIL converter, so the DXIL part needs the D3DMetal backend. `scripts/build-shims.sh` stages the bridge it needs (#484).
- **ADR:** [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) proposes Branch D1 for M3, with the evidence; it is pending maintainer acceptance.
- `scripts/build-shims.sh` now builds and verifies `bx_shader_bridge.dll` with the shims (#484). It builds the Windows version of `shader-transpiler/crates/dxbc-accc` (#445), linked with the new frozen export list `abi/defs/bx_shader_bridge.def`, so its export directory name is `bx_shader_bridge.dll`. It places the DLL in `build-shims/bin` and checks it with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. The script now reports 17 DLLs and 111 exports.
- **Toolchain:** `cargo` and `rustc` come from rustup when available. The build always uses `<repo>/target`, and a missing `x86_64-pc-windows-gnu` target stops the script with `rustup target add x86_64-pc-windows-gnu` (it is never skipped). The CI job installs that target with its pinned toolchain.
- **Effect:** `d3d12_xs`'s shader gate (#466) finds the bridge in `build-shims/bin` without a manual copy.
- Implemented the `IGameInput` v0 device-callback lifecycle (`RegisterDeviceCallback`, `StopCallback`, `UnregisterCallback`) and `SetFocusPolicy` in `shims/gameinput/gameinput.cpp` (#481). `RegisterDeviceCallback` validates `callbackFunc`, `inputKind`, `statusFilter`, and `enumerationKind` (`0..=2`), allocates unique monotonic `GameInputCallbackToken` handles under `SRWLOCK`, and supports optional null `callbackToken` output pointers; `StopCallback` marks active registrations stopped while keeping them unregisterable once via `UnregisterCallback`; `SetFocusPolicy` records focus-policy flags without stub noise. Expanded `test_audio_input.exe` to cover validation, token uniqueness, stop/unregister idempotence, and focus-policy calls.
- `dxbc-accc` now reaches Windows guests as `bx_shader_bridge.dll`, the x86-64 Windows build of the same crate (#445). It exports exactly the three `bx_shader_bridge.h` entry points and needs no MinGW runtime DLL. `shader-transpiler/crates/dxbc-accc/guest/build.sh` builds the DLL and checks its exports and imports. It also builds `check_bridge.exe`, a C guest program compiled against the frozen header, which sends a real DXC SM 6.6 blob and eight synthetic containers (DXIL with and without trailing bytes, `ACCC`/`FSPX` v1 and v0, dual, legacy `SHEX`, malformed) through the DLL loaded by full path. It checks classification (exact chunk sizes, root signature flag, header digest, declared size), prepare (only the declared container is copied), free, and prints a DXIL vs. `ACCC` count. The build script always uses `<repo>/target` and rustup's toolchain, and checks the whole Export Address Table and an import allowlist. On one Apple M5 Pro with CrossOver 26.3, in a prefix and a D3DMetal bottle, it reported `dxil=3 accc_only=2 dual=1 legacy=1 invalid=2` and passed. Synthetic containers only. Staging the DLL in `build-shims`, an `abi/defs` export list, and the `d3d12_xs` PSO hook (#466) are separate changes.
- `xgameruntime.dll!QueryApiImpl` now serves offline `XGameSave` and `XPackage` as COM `IUnknown` objects under BetterXen synthetic keys (#468, not yet closed). A title linked against Microsoft's `xgameruntime.lib` does not request these keys. Every synthetic key and COM slot order now lives in `shims/xgameruntime/synthetic_keys.h`, the single place to find or replace them. Signatures, structure layouts, `E_GS_*` values and container-name rules follow the public Microsoft Learn reference.
@@ -26,6 +270,7 @@ remains unsupported.
Each of eleven injected faults (non-atomic write, missing or per-process lock, ignored SCID, no-op close, lax parsing, uncounted names, retained results, stale work running, children kept after a provider close) makes it fail.
- **Not done:** validation against a caller linked to Microsoft's `xgameruntime.lib`, since these keys are BetterXen's own. `abi/defs/xgameruntime.def` is unchanged (49 exports).
- `QueryApiImpl` also serves offline XGameSave and XPackage on the public COM class and interface ids, with slot order from [xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) commit `7090008692569aa6081e30dfdd9de58237741e24` (#468). The ids and slot order come from that documentation; its provenance is recorded in `docs/research/upstream-registry.md` and the component reuse matrix, pending maintainer acceptance. `XPackageMountWithUiAsync` / `XPackageMountWithUiResult` (`IXPackageImpl2` slots 37–38) now mount through the XAsync engine, like `XPackageMount`. `IXError` slot 3 now returns `false`, following the #492 review's observation that the GDK's static library continues only on `false`; that source lists the slot as unknown.
- Added `docs/research/d3dmetal-gpu-limits.md` and `tests/conformance/test_d3dmetal_gpu_limits/` (#453). The fixture is an original D3D12 compute test that loads the host `d3d12.dll` directly, with four original HLSL kernels and committed DXC 1.9.2609 output (`shaders/compile.sh` regenerates them). It skips with exit 77 below shader model 6.6. Required checks:
- a kernel without `WaveSize` runs, and its lane indices form a permutation within each wave;
- a per-texel spin lock with acquire and release fences and a 1024-try cap emulates 64-bit add and max with no dropped update and exact values.
@@ -38,6 +283,17 @@ remains unsupported.
The note links only these measured items from the M2 and M3 roadmap rows. Observations reported from a commercial title are kept in a separate "not evidence" section, each with the synthetic workload that would verify it. This is a local implementer run, not on CrossOver 26.3 and not independently reproduced.
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
- `bx_runtime_veh.dll` handles illegal-instruction traps for CLZERO, MONITORX, MWAITX, RDPRU, EXTRQ and INSERTQ (#451). The decoder and fixture derive the encodings and expected results from the AMD Architecture Programmer’s Manual [volume 3](https://kib.kiev.ua/x86docs/AMD/AMD64/24594_APM_v3-r3.36.pdf) (24594, rev. 3.36) and [volume 4](https://kib.kiev.ua/x86docs/AMD/AMD64/26568_APM_v4-r3.25.pdf) (26568, rev. 3.25, EXTRQ pp. 139–140 and INSERTQ pp. 154–155).
- CLZERO clears a 64-byte cache line selected by RAX or, with the `67` prefix, EAX. An unwritable target is reported as a write access violation at the line address and the guest can repair the page and retry. One-shot Windows guard-page behavior is outside this emulation.
- MONITORX arms no host monitor. MWAITX yields once, so the EBX timer and ECX extensions have no effect. RDPRU approximates MPERF and APERF with the same timestamp rate and returns zero for unknown selectors. It clears the five flags specified by AMD and chooses zero for CF, whose value the manual leaves open.
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
@@ -76,11 +332,19 @@ remains unsupported.
- Added `tests/conformance/test_integration_boot/` (#420, M1-F1): an original synthetic x86-64 PE32+ boot fixture whose import directory names all 16 shim DLLs and which walks a startup-shaped sequence (AVX2 + FMA, three `clwb` forms, `xmem.dll`, `xgameruntime.dll`, PSM notifications, a hidden window pumped through the `ntuser` forwarders, `XCRDAPI.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, `GameInput.dll` ordinal 1, `xg_xs.dll`, `d3d12_xs.dll`) followed by reverse-order shutdown. Each of 21 stages prints a JSON checkpoint and a `bx_log_emit` record with status `pass`, `pending` or `fail`; `pending` marks an M0 stub's `E_NOTIMPL`/null answer or a host-answered import, is never counted as a pass, and becomes a failure with `--strict` or `BX_INTEGRATION_STRICT=1`. `scripts/build-shims.sh` builds it and still verifies all 16 DLLs. Run locally on an Apple M5 Pro (macOS 27.0, Rosetta 2) under CrossOver Preview build 20261006 by invoking its Wine loader directly with the same isolated environment `bx-cli run` sets: 13 pass, 8 pending, 0 fail, exit 0; `--strict` exits 1. It was not run through `bx-cli run` (the CLI only looks for `/Applications/CrossOver.app`) and not on CrossOver 26.3. That run found that this Wine build answers the two `api-ms-win-core-psm-appnotify-*` and four `ext-ms-win-rtcore-ntuser-*` import names itself instead of loading the BetterXen shims: the window stage still passes through `user32`, while PSM registration returns `ERROR_CALL_NOT_IMPLEMENTED` (reported as pending). The device, DirectStorage, AcpHal, GameInput and texture-computer stages are pending on their M0 stubs, and `D3D12XboxCreateDevice` and `XGCreateTextureComputer` are only probed with a null descriptor because no descriptor layout is defined in `abi/`.
### Removed
- Removed the repository-wide provenance, third-party licensing and legal-boundary rules from `AGENTS.md`: §4's per-file license audit and proprietary-component restrictions, §6's "Conditions for target builds" (including lawful acquisition, no leaked or unauthorized builds, no decryption or circumvention, and "If any condition is unknown, do not use the build"), the §6 "Repository & clean-tree boundary" and "Legal boundary" rules, plus the earlier removals of §4's "Provenance first" and §6's "Never obtain or use" bullets. §4 is left as a placeholder pending a replacement policy; the §6 "Authorized compatibility evidence" and §5 honesty rules stay. Nothing in `CONTRIBUTING.md`, `docs/legal.md`, `docs/claims.toml`, the ADRs or the research registry was changed, so those documents still describe the previous policy.
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
### Changed
- Updated the roadmap with the startup checkpoint, synthetic first-frame backing contract, and shared-budget correction. M3 and M6 memory work now has explicit eligibility and measurement criteria.
- Recorded the target-workload shader-corpus scan in the roadmap and [ADR 0008](docs/adr/0008-m2-shader-format-gate.md) (2026-11-28). A read-only container scan of an authorized local test workload — structure only, no run, no extraction, not redistributed — found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, and 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable; its packaged shader archive exposes no plaintext `DXBC` and remains unclassified. `dxbc-accc` accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers with `FspxSectionOutOfBounds` because their section tables do not match the clean-room layout. The roadmap keeps D1, treats the upscaler's ACCC-only containers as a concrete D2 candidate gated on runtime submission (first-frame blocker before the first presented frame, M4 upscaling if only upscaling needs them), and records both parser gaps as Track D prerequisites. Build-specific details stay in a local evidence note. Runtime use is unmeasured: the recorded startup run wrote no `shader_gate` records.
- `dxbc-accc` reports an `FSPX` descriptor whose offset lands inside the 16-byte header or the descriptor table as `ParseError::FspxLayoutMismatch { chunk, section_id, offset, table_end }`, not `FspxSectionOutOfBounds` (#599). The reserved region cannot hold section data under BetterXen's synthetic layout, so such a table does not follow that layout; it is not merely truncated. A section that runs past the payload end is still `FspxSectionOutOfBounds`. Both `inspect_dxbc` and the C ABI's `summarize_dxbc` path classify it the same way. The container is still refused: `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` keep returning `BX_SHADER_ERR_INVALID_BLOB` with output cleared, and the C ABI is unchanged, so the distinction does not yet reach `d3d12_xs` gate telemetry. One existing test case (offset 0 in a one-section table) now expects the new variant. New unit tests cover the reserved-region boundary, the out-of-bounds case, the unchanged C ABI refusal, and 4,096 seeded random `FSPX` tables without a panic. Synthetic bytes only; the `FSPX` layout itself is unchanged and remains synthetic (`CLAIM-XBOX-ISA-ABI`, class U).
- Added a model-agnostic "AI Agent Efficiency & Resource Management" section to `AGENTS.md` (§9), absorbing the earlier subagent reasoning rule: agents reuse valid evidence, read and verify narrowly and avoid redundant work, without weakening required verification, safeguards or independent review.
- Changed contributor and agent rules (`AGENTS.md`, `CONTRIBUTING.md`, `docs/legal.md`): agents now pick work in priority order (fix their own open PRs, then take an unclaimed issue, then review others' PRs); lawfully obtained, maintainer-approved target builds may be inspected locally as compatibility evidence where license terms and law permit, with no decryption or circumvention, and leaked or unauthorized material stays excluded; maintainer-directed tasks may cross track directories without a prior issue claim, while active claims, `[ABI]`-first changes and independent review still apply. Policy only; no compatibility claim.
- Corrected `shader-transpiler/crates/dxbc-accc/README.md` (#498): its "Not done here" section listed the export list, the `build-shims.sh` staging and the `d3d12_xs` PSO hook as outstanding, but those shipped (#445, #484, #466). The section now describes each one and credits the issue that delivered it. Documentation only.
- Documented independent Direct3D acceptance results on CrossOver 26.3 and CrossOver Preview 27, including D3D12 swapchain retention and Wine presentation stalls (#450).
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
@@ -110,6 +374,22 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
- `bx-cli`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
@@ -123,6 +403,9 @@ remains unsupported.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
- `bx-cli run` signal handling (#461). The environment's `wineserver` is now stopped before anything is reported on the stop path, and those reports and the trace summary no longer use panicking print macros, so Ctrl-C through `| tee` or a closed terminal can no longer skip cleanup. A signal inherited as ignored (`nohup`, a background job of a non-interactive shell) stays ignored. SIGQUIT (Ctrl-\\) stops the guest group and the environment like SIGINT. SIGTSTP (Ctrl-Z) is passed to the guest group, which is continued when `bx-cli` is, and suspended time does not count against `--timeout`. The cleanup `wineserver -k`/`-w` run in their own process group so a second Ctrl-C cannot kill them. The trace summary covers only what this run appended to the log; a log replaced or rewritten during the run (recognized by file identity and by the bytes before the old end, not by size) is summarized in full. A pause during prefix initialization is not charged to the guest's share of `--timeout` either. `THIRD_PARTY_NOTICES.md` no longer claims zero crates.io dependencies and now includes the `libc` MIT text. The stop messages changed from "stopping the environment" to "stopped the environment" because they are printed afterwards. Covered by 10 new unit tests with stub launchers and servers; each fix was removed in turn and its test failed. A reviewer confirmed Ctrl-C through `| tee` on a real terminal under CrossOver 26.3. The author then ran seven scenarios under CrossOver Preview build 20261006 (Ctrl-C through `tee`, an inherited-ignored SIGHUP, Ctrl-\\, Ctrl-Z and continue, repeated Ctrl-C during cleanup, a pause during prefix setup, a log replaced mid-run) with signals sent to the process group rather than typed, using a build that differs only in where it looks for CrossOver; each showed the old behaviour before the change and the fixed behaviour after. Not confirmed with real key presses, and not on CrossOver 26.3 for anything but the first. The same pattern in the unmerged #425 is not touched.
- `d3dmetal-harness` runner tests no longer give a freshly written script only 300–500 ms to start (#479); both use a 2 s deadline. The kill test now also checks that the probe ran until the deadline and that its process is gone, which catches a timeout path that neither kills nor waits for the probe. It passes the PID-file path as a script argument so temporary directory names containing apostrophes work. Test-only change. Slow script start-up as the cause of the earlier failures is inferred, not measured. `output_complete` is not asserted for the killed probe, because a child spawned by a parallel test may inherit its pipe.
- `bx-cli run` no longer blocks when `--log` names something other than a regular file (#502). The trace-log reads added for #461 opened the path and read it to the end, which waits forever on a FIFO nobody writes to; the log is now opened without waiting and only a regular file is summarized (anything else gets no summary). Also added the missing test for the file-identity half of the replaced-log check (a different file that begins with the old log's bytes), which a reviewer found untested, and documented that Ctrl-Z typed between supervised phases takes effect when the next phase starts. Covered by 2 new unit tests; three deliberate breakages each failed a test. Not run under CrossOver.
### Added
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
+53 -25
View File
@@ -1,47 +1,66 @@
# Contributing to BetterXen
BetterXen is a modular, CrossOver-based Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS. Contributions are organized into **6 parallel tracks** so 5–8+ human contributors and coding agents can work simultaneously without merge conflicts.
BetterXen runs a project-authorized Xbox Series title on Apple Silicon Macs, through CrossOver, Rosetta 2 and D3DMetal plus BetterXen's own shims. Members work by pointing a coding agent at this repository and saying **"work"**; the agent follows [AGENTS.md](AGENTS.md). This page is the short version for a person joining.
## Active Work & Track Ownership
## What you need
The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones M0–M6), supported by [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and the ready-to-claim Wave 1 issues in [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md). The earlier native-first workspace was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently at Git tag `native-first-final`.
These are a **hard requirement**. Without every one of them you, and your agent, do not work on the repository:
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
- an Apple Silicon Mac with CrossOver 26.3+ (licensed separately, never bundled), D3DMetal, and at least 10 GiB free;
- **the project-authorized target build**;
- **the GDK**, under the project's authorization;
- **the Ghidra results of the target build** (its static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`).
## Development & Verification
The target build, the GDK and the Ghidra results are distributed among members. Ask a maintainer for them; never get them anywhere else, and never commit, upload or post anything from them (paths, file names, hashes or bytes).
Requirements on Apple Silicon macOS: Rust 1.85+ (`aarch64-apple-darwin`), `mingw-w64` & `cmake` (`brew install mingw-w64 cmake`), Python 3.11+, Rosetta 2, and CrossOver 26.3+ (externally installed, never bundled).
Run these checks before opening a PR:
## Getting started
```sh
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli
scripts/build-shims.sh
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
python3 scripts/audit/docs_hygiene.py
git clone https://github.com/MacosPorters/betterxen.git && cd betterxen
brew install mingw-w64 cmake gh # Rust 1.85+ and Python 3.11+ are also needed
cargo build --locked -p bx-cli
target/debug/bx-cli setup --find # finds the build, the GDK and the Ghidra results in your home folder
target/debug/bx-cli preflight # must print: Ready to work.
```
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
`setup` saves the three locations in `~/.config/betterxen/local.conf`, outside the repository, once per machine. If `--find` finds more than one distinct build, choose with `bx-cli setup --target-exe <path>`.
## Clean-Room, Licensing & Provenance Policy
Then tell your agent **"work"**. If you work by hand, follow the same steps yourself: [AGENTS.md](AGENTS.md) Section 0.
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. 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.
## How work is organised
The full process is [AGENTS.md](AGENTS.md) Section 0 and [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md). In short:
1. **Pick one thing**, in this order: your own pull requests that need attention; a review of someone else's; a `handoff` issue of the current stage (named on the pinned `ladder` issue); or the first thing the target build stops on.
2. **Check for existing work first.** Before investigating any problem the game shows, search open and merged pull requests and open issues for it. If an open pull request covers it, check that branch out and work there.
3. **Claim it with a draft pull request** titled `[<Stage>] <signature>`, before writing the fix. A draft with no push for 3 days may be taken over.
4. **Evidence, smallest fix, test.** Every contract the fix introduces gets a conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row with it.
5. **Verify** with [AGENTS.md](AGENTS.md) Section 8, fill in the five-part description (Blocker, Contract, Fix, Test, Proof), and mark it ready.
Something you can't finish goes into a `handoff` issue instead, with what you saw, tried and still don't know.
## Running the target build
Runs are made offline, inside a sandbox that blocks outbound network: [docs/testing/target-build-review.md](docs/testing/target-build-review.md) has the procedure and the diagnostic switches. Three switches matter for getting through the title unattended:
- `BX_INPUT_SCRIPT=A@40,A@50` presses buttons;
- `BX_CONTINUE_ASSERTS=1` steps over the title's continuable asserts;
- `BX_PRESENT_DUMP=<folder>` saves frames.
`bx-cli run` stages the GDK's texture libraries for the target build automatically ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)). `bx-cli report <log.jsonl>...` turns run logs into the report and the blocker signatures that pull requests are titled with.
## Licensing & Provenance Policy
- 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.
- 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).
## Pull Requests & DCO Sign-Off
- Branch from `main`, keep changes focused inside your track scope, link the issue with `Closes #<number>`, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Branch from `main`, keep changes focused inside your track scope, link any related issue (`Closes #<number>` for a handoff it finishes), update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Disclose material AI assistance and personally review generated changes. Never include secrets, personal paths, or credentials in patches or logs.
- Sign off every commit under the [Developer Certificate of Origin](https://developercertificate.org/):
@@ -49,4 +68,13 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
git commit -s -m "Describe the change"
```
## Review and Merging
- A PR needs at least one current approval, passing required checks and resolved blocking conversations. Any later push that changes the PR dismisses earlier approvals.
- You do not merge your own PR. A maintainer other than the original author merges it.
- Please leave **Allow edits by maintainers** enabled on fork PRs (GitHub does not offer it for organization-owned forks). Maintainers may then resolve conflicts and push fixes to your branch, and may still merge it.
- A maintainer may re-approve after their own routine fix (conflicts, changelog, minor docs). Substantive changes need approval from someone who did not write them.
The full rule, including what GitHub does not enforce, is in [AGENTS.md](AGENTS.md) §7, "Merge eligibility".
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
Generated
+5
View File
@@ -9,6 +9,7 @@ dependencies = [
"bx-probe",
"bx-telemetry",
"dxbc-accc",
"gfx10-translate",
"libc",
]
@@ -31,6 +32,10 @@ dependencies = [
name = "dxbc-accc"
version = "0.2.0"
[[package]]
name = "gfx10-translate"
version = "0.2.0"
[[package]]
name = "libc"
version = "0.2.191"
+1
View File
@@ -5,6 +5,7 @@ members = [
"launcher/crates/bx-telemetry",
"shader-transpiler/crates/d3dmetal-harness",
"shader-transpiler/crates/dxbc-accc",
"shader-transpiler/crates/gfx10-translate",
]
exclude = ["legacy-native"]
resolver = "3"
+10 -7
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.
---
@@ -67,7 +67,7 @@ Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
| Milestone | Scope | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
@@ -129,7 +129,7 @@ The repository is organized into disjoint track directories around a single froz
| Directory | Track | Stack | Contents |
| --- | --- | --- | --- |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
@@ -165,8 +165,9 @@ cargo build -p bx-cli
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
target/debug/bx-cli doctor
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
# bx_shader_bridge.dll with cargo, and build the conformance binaries
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
scripts/build-shims.sh
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
@@ -208,9 +209,11 @@ See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architectu
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
- **Not yet implemented (M1–M6):**
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
+64 -2
View File
@@ -1,8 +1,14 @@
# Third-party notices
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `GPL-3.0-or-later` source with **one external crates.io dependency**: `libc`, used only by `bx-cli`.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. Preserve the Rust Project Developers notice and permission text.
`bx-cli` links the unmodified `libc` 0.2.191 crate (`ccc2ff4aaab962f7fde7b8edda7379c045b1ca12`) for POSIX process groups and signals, under its MIT option. The crate is licensed `MIT OR Apache-2.0`; its notice and permission text (`LICENSE-MIT` in the 0.2.191 crate) are reproduced under [libc MIT license text](#libc-mit-license-text) below.
## Vendored source files
| Files | Origin | License |
| --- | --- | --- |
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
## External Host Tools & Runtime Dependencies (Never Bundled)
@@ -13,3 +19,59 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
## libc MIT license text
```text
Copyright (c) The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
```
## DirectStorage headers MIT license text
```text
Copyright (c) Microsoft Corporation.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+1 -1
View File
@@ -7,4 +7,4 @@ This directory holds the **only shared interface boundary** across BetterXen's s
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files. One entry is not under `shims/`: `bx_shader_bridge.def` is the export list of `bx_shader_bridge.dll`, the x86-64 Windows build of `shader-transpiler/crates/dxbc-accc` (#445). `scripts/build-shims.sh` links it into that build and verifies it with the shims (#484).
+5
View File
@@ -0,0 +1,5 @@
LIBRARY bx_shader_bridge.dll
EXPORTS
bx_shader_inspect
bx_shader_prepare_for_d3dmetal
bx_shader_free_buffer
+4
View File
@@ -15,3 +15,7 @@ EXPORTS
XMemVirtualQuery
bx_xmem_query_region
bx_xmem_get_internal_stats
bx_xmem_try_charge_external
bx_xmem_release_charge_external
bx_xmem_remap_guard_enter @18
bx_xmem_remap_guard_leave @19
+28 -1
View File
@@ -33,9 +33,36 @@ typedef struct bx_xmem_stats {
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
* committed_virtual_bytes includes bytes admitted through
* bx_xmem_try_charge_external(), so committed + physical is everything the
* cap counts and peak_committed_bytes never exceeds what was reported. */
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
/* Admit `bytes` against the combined title cap, counting every owner.
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
* bookkeeping could not be refreshed (logged as external_charge). On success the
* caller owns the charge and must release it exactly once with
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
int bx_xmem_try_charge_external(uint64_t bytes);
/* Release a charge previously admitted by bx_xmem_try_charge_external().
* Releasing more than is outstanding is refused: the counter is left
* unchanged and an external_charge error is logged. */
void bx_xmem_release_charge_external(uint64_t bytes);
/* The remap guard protects BetterXen reads and writes to title memory while
* XMemMapPhysicalPages, XMemMapPhysicalPagesScatter or XMemFreePhysicalPages
* replaces mapped views. Those operations wait for active guards and block
* new guards until the remap completes.
*
* Pair each enter with one leave on the same thread. Keep the guard short,
* avoid nesting it, and release it before calling an XMem function.
* Consumers that resolve the helpers dynamically must resolve both or
* call neither. */
void bx_xmem_remap_guard_enter(void);
void bx_xmem_remap_guard_leave(void);
#ifdef __cplusplus
}
#endif
+12 -4
View File
@@ -3,7 +3,8 @@
## Getting Started & Architecture
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
- [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.
- [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/`).
@@ -15,21 +16,28 @@
- [ADR 0005: CrossOver-based hybrid direction](adr/0005-crossover-hybrid-direction.md) — Pivot to CrossOver + Rosetta 2 + D3DMetal as the external foundation.
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
- [ADR 0010: The GDK's texture libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), staged by `bx-cli run` for the target build from each machine's GDK; never reimplemented, committed or shipped.
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
## Research, Testing & Licensing
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
- [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) — One-host observation to check before M2 presentation work.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [gfx10-translate](../shader-transpiler/crates/gfx10-translate/README.md) — BetterXen's GFX10.3 console shader translator: container reader, decoder with an LLVM-generated opcode table, HLSL translation ported from the Python prototype, coverage over local shaders, and how to add an instruction.
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
- [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.
## 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.
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
- [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.
+1 -1
View File
@@ -26,7 +26,7 @@ BetterXen provides integration, configuration, environment management, diagnosti
## Verified implementation capabilities
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md`.
None for the hybrid architecture. Verified native-research capabilities (synthetic evidence only) are unchanged and listed in `docs/progress.md` at tag `native-first-final`, the archive ADR 0006 makes canonical; the file is retired from `main`.
## Planning consequence
+78
View File
@@ -0,0 +1,78 @@
# ADR 0008: M2 Shader Format Gate — Branch D1 (DXIL normalization) for M3
Status: **Proposed** (2026-11-26, issue #466). The choice for M3 is the maintainers' to accept. The evidence below is from local Apple Silicon runs by the implementer and has not been independently reproduced.
## Context
The roadmap's M2 gate asks which shader path M3 builds:
- **Branch D1, DXIL normalization:** shaders reach D3DMetal as DXIL, and BetterXen rewrites only what D3DMetal cannot run.
- **Branch D2, `ACCC`/`FSPX` translation:** console-compiled RDNA 2 code in `ACCC` chunks is translated to DXIL or MSL.
The gate needs a classifier that guest pipeline creation actually reaches, plus measurements of what D3DMetal does with each form.
## What M2 built
- **Bridge (#445):** `bx_shader_bridge.dll` is the x86-64 Windows build of `dxbc-accc`, so guest code can call the inspector.
- **Gate (#466):** `d3d12_xs.dll`'s `CreateComputePipelineState` and `CreateGraphicsPipelineState` pass every stage through `bx_shader_inspect`. One `shader_gate` JSONL record per stage gives:
- the container kind, stage, shader model and chunk sizes;
- the `SFI0` feature flags (`D3D_SHADER_FEATURE_*` values from DirectX-Headers `d3dcommon.h`);
- the `PSV0` wave lane range.
- **Decisions:**
- **DXIL and dual containers:** go to the host as the bridge's prepared copy (`bx_shader_prepare_for_d3dmetal`).
- **ACCC-only containers:** are refused with `E_NOTIMPL` before the host device is called.
- **Legacy DXBC and unclassifiable input:** pass unchanged.
- **A missing bridge:** is logged once (`shader_bridge_missing`). Shaders then pass unclassified, except that a container with an `ACCC` chunk and no `DXIL` chunk is still refused with `E_NOTIMPL`, found by a bounds-checked chunk scan, because D3DMetal crashes on it. The bridge is loaded only by full path from `d3d12_xs.dll`'s own directory.
- **Known D3DMetal gaps:** a stage that needs a wave wider than 32 lanes, or 64-bit atomics, also gets a `shader_d3dmetal_gap` record.
`tests/conformance/test_shader_gate` exercises all of this.
## Evidence
| Observation | Source | Host and class |
| --- | --- | --- |
| A real DXC 1.9.2609 SM 6.6 compute shader (`fill_cs66`) creates a PSO through `d3d12_xs`, runs, and all 256 output words match the CPU reference. | `test_shader_gate` | Apple M5 Pro, macOS 27.2.1, CrossOver 26.3 (`26.3.0.39832`) bottle with `CX_GRAPHICS_BACKEND=d3dmetal`; class A, this host only |
| The same shader, run outside Wine through `d3dmetal-native` against CrossOver's D3DMetal 3.0, matches 256/256. | [d3dmetal-harness](../../shader-transpiler/crates/d3dmetal-harness/README.md) (#417) | Same host; class A |
| An ACCC-only container is refused with `E_NOTIMPL` for compute and graphics, no host object is created, and the device stays usable. | `test_shader_gate` | Same bottle; class A |
| In a bare CrossOver 26.3 prefix (vkd3d), SM 6.6 DXIL PSOs fail with `E_FAIL`. vkd3d reports `Cannot load DXIL conversion library`. | `test_shader_gate`, same host | Class A; DXIL needs the D3DMetal backend under CrossOver |
| `[WaveSize(64)]` kernels and kernels with SM 6.6 64-bit atomics are created but never run on D3DMetal. | [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints) (#453) | Apple M3 Pro, Wine 11.0 source build, D3DMetal 4.0b3; class A for that host |
| DXC records `[WaveSize(64)]` as `PSV0` lanes 64/64, and 64-bit atomics on typed resources as `SFI0` `0x400000`. 64-bit atomics on raw buffers set only `INT64_OPS` (`0x8000`), the same as other 64-bit integer use. | The #453 blobs, read by the gate and by a script | Class A |
| Public sources do not establish a console-native shader container layout. BetterXen's `FSPX` is a clean-room synthetic layout, not a description of a console compiler's format. | `CLAIM-XBOX-ISA-ABI` (class U) in [claims.toml](../claims.toml); `shader-transpiler/crates/dxbc-accc/src/fspx.rs` | Source review |
| A serialized console pipeline path exists for Series X\|S, with no public version-independent format. | `CLAIM-XBOX-ACO-SAMPLE` (class D) | Source review |
| A read-only structural scan of an authorized local test workload (2026-11-28) found 52 DXIL SM 6.5 compute containers with LLVM bitcode in its `XboxBvhBuilder` component, 29 ACCC-only `FSPX` containers in its AMD FidelityFX upscaler component, 10 SM 6.6 DXIL containers with four-byte `NOBC` payloads (nine pixel, one vertex) in its main executable, and no plaintext `DXBC` in its packaged shader archive. | Static container scan on this host, re-run through `dxbc-accc`; private evidence note, workload not redistributed | This host; structure only, runtime use unmeasured |
Runtime gate telemetry still covers only synthetic programs; no target-workload run has reached pipeline creation, so what a run submits remains unmeasured. One static measurement now exists (2026-11-28): a read-only container scan of an authorized local test workload, re-run through `dxbc-accc`, with the counts in the table above. The scan measures what shipped components contain, not what any run submits, and the workload is not redistributed. Wherever the gate runs, its `shader_gate` records count it.
## Decision
Branch **D1** is proposed for M3:
1. **Pass DXIL through the gate to D3DMetal.** This is the only path with measured, end-to-end execution evidence.
2. **Spend M3 shader work on the two measured gaps,** within the [D3DMetal GPU limits](../research/d3dmetal-gpu-limits.md#measured-constraints):
- lower `WaveSize(64)` programs to 32-lane code;
- lower SM 6.6 64-bit atomics to 32-bit operations or bounded lock emulation.
The gate's `shader_d3dmetal_gap` records show which pipelines need this.
3. **Keep refusing ACCC-only containers** with `E_NOTIMPL` and a structured log.
Branch **D2** is deferred. It needs a documented, lawfully available description of console-compiled containers and their RDNA 2 code, and none exists (`CLAIM-XBOX-ISA-ABI`). A translator built against the synthetic `FSPX` layout would prove nothing about real inputs.
Revisit this ADR in any of these cases:
- an authorized public source for that format appears;
- gate telemetry shows a required pipeline-creation path refusing an ACCC-only container at runtime — a static scan already established that the target workload's upscaler component embeds 29, so the open question is submission, not existence;
- D3DMetal starts running the gap cases.
## Consequences
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
- **Not covered by the gate yet:**
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
- **`NOBC` programs:** the classifier validates the `DXIL` program header's sizes but not the LLVM bitcode signature, so a container whose bitcode payload is the four-byte placeholder `NOBC` still classifies as executable DXIL and is prepared for the host unchanged. The target workload's main executable embeds 10 such containers (nine pixel, one vertex, SM 6.6). They carry no bitcode, so D1 cannot run them as-is; their signature and validation chunks are intact.
- **Wave size:** the gate logs constraints but changes no shader. A pipeline that D3DMetal creates but does not run still behaves that way.
## Not claimed
Nothing here describes any Xbox title's shaders, behaviour on Xbox hardware, or D3DMetal versions other than those named. Evidence class: local Apple Silicon runs, one local static container scan of an authorized test workload, and public-source review. The scan counts containers embedded in shipped components on this host; it does not establish what any run submits, and it documents no console-compiled format layout beyond the stated mismatch.
@@ -0,0 +1,59 @@
# ADR 0009: Xbox-layout D3D12 objects in d3d12_xs
Status: **Proposed** (2026-11-28). Phase 1 is implemented with this ADR; the maintainers decide whether the direction stands. The evidence is from local Apple Silicon runs by the implementer and has not been independently reproduced.
## Context
`d3d12_xs.dll` handed titles PC D3D12 objects: C++ proxies (`proxy.h`, `proxy_generated.cpp`) whose vtables follow the PC `<d3d12.h>` order. A title built against the Xbox Series D3D12 header (`d3d12_xs.h`, part of the GDK material Microsoft authorized the project to use) calls through each object's **function table**, and that order is different:
| Interface | Xbox slots | PC slots | Orders agree up to |
| --- | --- | --- | --- |
| `ID3D12Device` | 83 | 44 | slot 43. Xbox then adds 39 methods (`CreatePlacedResourceX`, `CreateCommandQueueX`, ...) before `ID3D12Device1`. |
| `ID3D12Device11` (chain) | 139 | — | `ID3D12Device11` is the interface a project-authorized target build asks for. |
| `ID3D12GraphicsCommandList` | 107 | 60 | slot 27 |
| `ID3D12CommandQueue` | 38 | 19 | slot 13 |
So every call past those slots reached the wrong PC method. On the target build, the first call on the device after `QueryInterface(ID3D12Device11)` jumped to address 0.
From the same header:
- **Base layout:** every object starts with the table pointer, a 32-bit flags word and `m_RefCount`, 16 bytes in all.
- **`ID3D12Device` fields:** a 64-bit null constant-buffer address at +16 and a 64-byte union at +24. The union's first byte, `m_OutOfLineFlags`, makes the two inline device helpers (`CopyDescriptorsSimple`, `CreateConstantBufferView`) call out through the table when it is non-zero. That holds unless a title is compiled with `D3DCOMPILE_NO_DEBUG`, in which case they write descriptors inline.
- **Command lists:** they add a put buffer and CPU state. Of their 76 inline methods, 71 call the table. The other five write command packets directly when the next write fits below `m_Putter`'s limits, and call the table otherwise.
- **IIDs:** the interface IDs of shared interfaces are the PC ones (`ID3D12Device` `189819f1-…`, `ID3D12Resource` `696442be-…`).
## Decision
1. **Xbox-layout objects:** titles get `BxXboxObject`s (`xbox_facade.h`). They have the Xbox object layout, with `m_OutOfLineFlags` set, and an Xbox-order function table. Each object hosts a PC object, normally one of the existing proxies, so their logging, shader gate, heap hooks and wrapping stay in force.
2. **Generated tables:** `tools/gen_xbox_tables.py` reads the Xbox header locally and the toolchain's `<d3d12.h>`, and writes `xbox_tables_generated.cpp`. It takes only slot order, names, IIDs and parameter types from the Xbox header. The header is never committed.
- **Forwarders:** a slot whose Xbox and PC signatures are equivalent gets a typed forwarder written with the PC types. That includes the free-function versus member struct-return difference, so the compiler produces the right calling convention. Interface pointers passed in are unwrapped, and `(REFIID, void**)` results are wrapped.
- **Stubs:** every other slot is a `BX_VTABLE_STUB_LOG` stub.
- **Hand-written slots:** Xbox-only methods are implemented in `xbox_facade.cpp` as titles need them.
3. **Who gets which layout:** titles set `Version` in the `D3D12XBOX_CREATE_DEVICE_PARAMETERS` block they pass to `D3D12XboxCreateDevice`, and the documentation requires it. Those calls get the Xbox layout. BetterXen's synthetic fixtures are PC-layout clients built against `<d3d12.h>`, pass a zeroed block, and keep the PC proxy. The log records which layout was chosen (`xbox_layout`).
4. **Command lists (Phase 2):** command lists get an Xbox object whose zeroed put-buffer pointers fail every inline room check, so every call reaches the table.
## Consequences
- **Phase 1 (this change):**
- The device chain up to `ID3D12Device11` is covered: 139 slots, 75 forwarded, 4 shared or hand-written, 60 stubs.
- So are the objects it creates: resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues.
- `CreateCommandQueueX` maps the Xbox queue description onto PC `CreateCommandQueue`. The engine and queue indices are logged and not used.
- On the target build, the title now creates its device and four compute queues, and stops at `CreateCommandListX`, which is Phase 2.
- **Phase 2:**
- **Command lists:** `ID3D12GraphicsCommandList8`, 150 slots: 75 forwarded, 6 shared or hand-written, 69 stubs. They are created through `CreateCommandListX` and the PC `CreateCommandList`, and their Xbox field area is zeroed, so the five inline fast paths call through the table.
- **Interface pointers inside structures:** `ResourceBarrier` and `CopyTextureRegion` unwrap them before the host call. The Xbox `ResourceBarrier` returns 0 actions.
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` (`frame_pacing.cpp`) are emulated from the recorded interval by a host timer. It signals the origin, vblank and flip events and their ancillary handles, and gives out frame-pipeline tokens as documented.
- **Generator fixes:** CRLF lines in parts of the header, a table definition whose end the boundary pattern ran past (it hid `ID3D12GraphicsCommandList1`), SAL annotations with nested parentheses, and `FLOAT`/`float`.
- **Resources at title-chosen addresses** (`placed_x.cpp`), translation by copy:
- `CreatePlacedResourceX` and `CreatePlacedResourceX1` create a host shadow resource. A buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's memory at creation; a texture gets a committed texture whose contents are not filled, which is logged.
- The resource reports the title's address from `GetGPUVirtualAddress`.
- Not yet done: keeping shadows in step with later CPU writes (planned: page-protection dirty tracking, copying at submit), copying GPU writes back, and translating title addresses in GPU calls.
- **On the target build:** the title creates 581 command lists, sets a 30 Hz interval and schedules its origin and flip events. It then lays out its own descriptor memory with `xmem` placeholders (#643) and creates a 174 MB buffer at a title-chosen address through `CreatePlacedResourceX1`, now served by a shadow.
- **Where it stops:** the title creates a descriptor heap and requires `GetCPUDescriptorHandleForHeapStart` to equal an address in its own descriptor memory. D3DMetal returns an opaque handle.
- **What that needs:** BetterXen-owned descriptor heaps whose handles are addresses, translated to host descriptors when used. That is the descriptor-heap item under Consequences.
- **Fixtures:** the existing fixtures are unaffected, since they use the PC layout. `tests/conformance/test_d3d12_xbox_layout` calls Xbox slots by number, with the expected results taken from a PC-layout device. It fails against the previous `d3d12_xs.dll`.
- **What the fixture can and cannot show:** its slot numbers and object offsets are written by hand, but from the same header the generator reads. It shows that the generator and the fixture agree. It cannot show that either read the header correctly; only an independent re-derivation from the header, or a title running further, can.
- **On a host without the forwarded interface** (vkd3d stops at `ID3D12Device9`): the Xbox-layout device is refused with `E_NOINTERFACE` and logged. The fixture verifies the refusal and skips (exit 77). `bx_xbox_wrap` refuses the same way for every wrapped family, so a title never gets a PC object where it expects an Xbox one.
- **Frame pacing:** the emulated frame interval follows host `Sleep` and is not synchronised to the display. The pacing thread is detached and never exits, which is safe only while `d3d12_xs.dll` stays loaded for the life of the process.
- **Descriptor heaps:** a title compiled with `D3DCOMPILE_NO_DEBUG` writes console-format descriptors straight into descriptor-heap memory and computes handles with Xbox descriptor sizes. Supporting that needs BetterXen-owned descriptor heaps translated at bind time, which is not part of this ADR.
- **Identity:** QueryInterface on an Xbox object for another wrapped family returns that family's Xbox object over the same host. A host reached through another path, such as `GetDevice` returning the raw host device, may get a second Xbox object.
- **Replacing the PC proxy:** this ADR supersedes the PC proxy for titles. Whether the PC proxy is eventually removed in favour of fixtures that use the Xbox layout is left open.
+29
View File
@@ -0,0 +1,29 @@
# ADR 0010: The GDK's texture libraries at run time
Status: **Accepted** (2026-11-30, by the repository owner). The evidence is from local Apple Silicon runs by the implementer.
## Context
Console textures differ from PC textures in two ways that BetterXen had no answer for:
- **Tiled layouts.** A console texture carries a swizzle layout (`D3D12XBOX_TEXTURE_LAYOUT`, `0x100 | XG_SWIZZLE_MODE`; most of the target build's textures use the 4 KB "S" mode). A title sizes its placements and loads from the layout, and the bytes arrive tiled. BetterXen's `xg_xs` shim answers every layout as linear, so sizes were too small (#708) and textures could not be uploaded.
- **BCPack.** Texture data in the target build's archives is BCPack-compressed (`DSTORAGE_BCPACK_MODE` 1 to 7). There is no public specification of the format. `XCRDAPI.dll` refused those requests (34 per run).
The GDK the project is authorized to use contains Microsoft's **PC builds** of both: the XG library (`xg_xs.dll`, which computes layouts and copies between tiled and linear data) and the BCPack decoder (`BCPack.dll`). Both are pure computation, with only standard Windows imports, and load under CrossOver. Measured on the target build with them in place: the GDK's XG answers the device's console-layout size queries, detiling through it produced the first real image of the title's menu artwork, and BCPack requests decode.
Reimplementing either would mean deriving the console's tiling rules and the BCPack format from observation, with the result only ever approximating Microsoft's.
## Decision
1. **Use Microsoft's libraries at run time; do not reimplement them.** `bx-cli run` stages the GDK's `xg_xs.dll` in place of BetterXen's shim and `BCPack.dll` beside it, and names the decoder to `XCRDAPI.dll` through `BX_BCPACK_DLL` (`launcher/crates/bx-cli/src/gdk_libs.rs`). `d3d12_xs` uses the XG library when it is the loaded `xg_xs.dll` (`shims/d3d12_xs/gdk_xg.cpp`).
2. **From each machine's own GDK.** The libraries come from the GDK configured by `bx-cli setup`, which preflight already requires. They are found by their exports, not their place in the GDK.
3. **Never committed or shipped**, unless the project records an authorization that covers redistributing them. Commits name only the documented interfaces (`XGCreateTextureComputer`, `BCPackDecompress`, ...), as with every other GDK contract.
4. **Only for the target build.** Conformance tests check BetterXen's own shims, so the GDK's libraries are staged only when the executable is the configured target build, or with `--gdk-libraries`. `--no-gdk-libraries` turns them off.
5. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
## Consequences
- Correct console layouts and BCPack decoding now, without a reverse-engineering effort for either.
- Running the title needs the GDK on the machine. Preflight already requires it.
- Conformance tests cannot call Microsoft's libraries in CI. Tests cover BetterXen's side of the contract with stand-ins whose answers the test computes (`test_d3d12_gdk_xg_sizes`). Microsoft's results are exercised on machines with the GDK.
- Agents need no special knowledge: the target build's run protocol stages the libraries automatically, and `CLAUDE.md` Section 1 says not to reimplement them.
+1 -1
View File
@@ -25,7 +25,7 @@ BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-bas
## Milestones (M0 → M6)
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 16 shim DLLs load cleanly; auto-logging COM proxy captures startup call traces.
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
+36
View File
@@ -1,4 +1,30 @@
# Source review is distinct from a Xenora test run.
#
# Evidence classes (derived from existing usage; claim classes are unchanged):
# A — Executed measurement on a named Apple Silicon host, with an independent
# CPU/reference expectation. Valid only for the named host/software versions;
# implementer-run unless independently reproduced. Never Xbox verification.
# B — Source-derived semantics from a public vendor specification, scoped to the
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
# exercised by synthetic tests, but does not establish console applicability.
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
# without console execution. Establishes only what the reviewed source states.
# E — Public tool/format documentation or observed behavior of a public
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
# Documentation review and execution are distinct; the claim's test field
# records which one applies.
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
# about the evidence reviewed, not proof that no authorized source exists.
#
# Use B for semantics from a specification, D for a claim about what a public
# document or sample says, and E for a claim about a tool or its format support.
# The current registry does not assign class C.
#
# These are the repository's evidence classes. AGENTS.md §5 refers to this
# file and does not define a second vocabulary; the longer VERIFIED /
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
# present in the in-tree AGENTS.md, so no mapping is invented here.
schema_version = 1
[[claim]]
@@ -242,3 +268,13 @@ retrieved = "2026-11-22"
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
test = "Read slides 12 and 13. No console execution."
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
[[claim]]
id = "CLAIM-XBOX-CS-ENTRY-ABI"
class = "U"
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
sources = ["docs/research/console-shader-abi.md"]
retrieved = "2026-11-28"
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
+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.
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
+206
View File
@@ -0,0 +1,206 @@
# Working Method: Run, Fix, Pull Request
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
BetterXen is built by collaborators who each have the project-authorized target build, the GDK and the target build's Ghidra results, and who work by pointing a coding agent at this repository and saying **"work"**. This document answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
The short answer: run the build, fix the first thing it stops on, and open a pull request. The pull request is the unit of work. There are no meetings, no rotating roles and no backlog to interpret.
## What you must have
No agent works without all of these. `bx-cli preflight` checks them and fails if one is missing:
- an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`;
- **the project-authorized target build**;
- **the GDK**, headers and compilers, under the project's authorization;
- **the Ghidra results of the target build**: the static-analysis run (`RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable;
- at least 10 GiB of free disk space.
The target build, the GDK and the Ghidra results are a hard requirement: an agent that lacks even one of them does not work on the repository at all.
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header, the target build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
Work here is found by running the build, located in the Ghidra results and checked against the GDK. Without all three an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build, the GDK or the Ghidra results are not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
## Why this shape
What the first target-build runs taught us:
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
## The stages
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
## Where the state lives
| What | Where |
| --- | --- |
| A blocker someone is fixing | An open pull request titled with its signature (a draft while in progress) |
| A blocker someone found and could not finish | A **handoff issue** (label `handoff`, plus `stage: <name>`) |
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) |
| What needs a person | Label `needs-human` |
| Rules | AGENTS.md and this document, changed by pull request |
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
### Why a blocker gets a pull request and not an issue
An agent that runs the build and sees what it stops on usually knows the fix a few minutes later. Writing an issue, claiming it and then opening a pull request that closes it is three steps where one does the job. And an issue of the form "the build stops at X" is a fact about one run on one machine: the build takes different start-up paths from run to run, so another collaborator may never see it.
What holds on every machine is the **test**: "the console does X for this call, and this test fails without the fix". The run is why you looked; the test is the proof.
So:
- **You can fix it:** open a draft pull request titled with the signature, before writing the fix. The draft is the claim.
- **You cannot fix it** (too large, out of session, needs a decision): file one handoff issue with what you saw, what you tried and what is unknown.
### Signatures
A signature is the fixed string `bx-cli report` prints for something a run stopped on: `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll`, `exit status 5`. Pull requests and handoff issues are titled with it (`[Boot] unimplemented IXUser slot 3`), so searching open pull requests for a signature tells you whether someone is already on it.
## What an agent does when told "work"
AGENTS.md §0 has the binding version. In short, in strict order:
1. **Preflight.** `bx-cli preflight` must pass. If it does not, stop.
2. **Your own pull requests first.** Requested changes, failing checks, conflicts, or a draft you have not finished.
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
4. **Then a handoff issue** of the current stage that no pull request covers.
5. **Then run the build** and fix the first thing it stops on that no open pull request covers.
6. **If the run stops on nothing,** make the stage's ten-run gate check and post it on the ladder issue with `needs-human`.
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
## Working one blocker
```text
run → signature → draft pull request (the claim) → evidence → smallest fix + test → runs before and after → ready → someone else reviews and merges
```
1. **Claim with a draft pull request.** Check open pull requests for the signature. If nobody has it, branch from `origin/main`, push, and open a draft titled `[<Stage>] <signature>`. A draft with no push for 3 days may be taken over.
2. **Is it already someone's?** Before investigating any problem the game shows (the picked blocker or one met along the way), search open and merged pull requests and open issues for its log event, stub symbol, error code and the files a fix would touch. If an open pull request covers it, check that branch out, run with it and work there. If a merged one does, sync and run again. On 2026-11-30 a session fixed physical-page DirectStorage requests in parallel with an open pull request for the same problem (#707), and found the overlap only afterwards.
3. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
4. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
5. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
6. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
7. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
If the blocker turns out to be more than you can finish, close the draft and file a handoff issue.
### Pull-request description
Five parts and nothing else:
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
2. **Contract:** what the console does, and which source says so (ranks below).
3. **Fix:** what changed.
4. **Test:** the conformance test, and that it fails without the fix.
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
### Review
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
- a change under `abi/`;
- a new or changed translator instruction class;
- a contract from source rank 4 or 5;
- anything touching the sandbox, security or licensing.
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
## Run protocol
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
- **Build:** current `main`, or `main` plus exactly the one branch under test.
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
**The run report** is generated, not written. Per run:
- outcome: frames presented, clean timeout, early exit with its status, or hang;
- the start-up path taken;
- every unimplemented call reached, counted;
- every fault inside a BetterXen module;
- pipelines drawn with: translated, passed through, skipped;
- on a stall: every thread's stack.
It ends with a ten-run summary and a list of **signatures**, the strings pull requests and handoff issues are titled with.
**What exists today** (#664): `bx-cli report <log.jsonl>...` produces the per-run report and the summary with signatures from run logs, and `bx-cli run` records how each run ended. Not yet in the launcher: the offline runner, per-session bottles, the machine-wide lock, thread stacks on a stall, and stall detection itself (frames are logged at powers of two, so a log cannot yet tell a stall from slow presentation).
## Sources of truth
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
| Rank | Source | Notes |
| --- | --- | --- |
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
## Evidence and references
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
## Finding blockers once the game runs
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
**How a problem is recognised,** from most to least reliable without a person:
| Signal | Catches | Needs a person |
| --- | --- | --- |
| Crash, hang, early exit | Stability | No |
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
| Frame compared with the last good capture of the same route | Regressions | No |
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
Findings become pull requests (or handoff issues, when they cannot be fixed at once) with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
## What people do
People are needed for exactly four things, each marked `needs-human`:
1. confirming a stage change after a gate passes;
2. deciding a decision gate (for example the graphics back end);
3. licence, provenance and legal questions;
4. changing these rules.
Everything else is the queue.
## The first handoffs
When this method started, the first target-build runs had already found more than could be fixed at once. Those were filed as issues #664–#680. The ones that were only "a blocker with a fix on the way" close as their pull requests merge; the ones that remain open as handoffs are the larger pieces: the run tooling, the D3DMetal capability checks, the translator, the reference images and the record-and-replay tools.
+3
View File
@@ -21,5 +21,8 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| Test and diagnostics methodology | BetterXen existing audits, benchmark harness, claims registry | **Reuse** | Existing evidence classes, claims audit and benchmark gating apply to hybrid work (Phase 1 onward). |
| Configuration, diagnostics, benchmarking around CrossOver | BetterXen | **Build** (Phase 2, provisional) | Only after Phase 1 shows what CrossOver does not already provide (#351). |
| Process groups and signals for `bx-cli run` | rust-lang/libc 0.2.191 (MIT) | **Reuse** | Unmodified crates.io dependency (#408). |
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
+75
View File
@@ -0,0 +1,75 @@
# Console compute shader entry ABI (probe results)
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
What this is:
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
## Method
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
| Probe | Root signature | Shader |
| --- | --- | --- |
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
## Observations
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
- A root constant takes one SGPR (p01: `s4`–`s7`).
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
**Descriptor tables.** Descriptors are loaded from the table address:
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
## Consequences
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
## Open
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
- **`s0`–`s3`:** what they hold when root data fits in registers.
- **One compiler build, one host:** a different GDK version may differ.
## Provenance
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
+27 -1
View File
@@ -108,7 +108,7 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
| Check | Outcome |
| --- | --- |
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
| `device.shader_model` | 6.6 |
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
| `wave.wavesize64` | created but not run (output still sentinel) |
@@ -118,9 +118,35 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
(D3DMetal 3.0) by another contributor.
## Capability checks for translated console shaders (#671)
A translator of console code needs four things from D3DMetal. Each has a synthetic check with
one of three results: *runs correctly*, *workaround* (the translator can get the console's
answer another way) or *blocked*. The checks talk to the host `d3d12.dll` directly, so they
measure D3DMetal, not BetterXen. Expected values are computed on the CPU.
Machine: Apple M5 (32 GB), macOS 27.2.1, CrossOver 26.3, D3DMetal; each check run twice in a
row with the same result.
| Need | Check | Result | What was measured |
| --- | --- | --- | --- |
| Descriptors fetched by index (SM 6.6 dynamic resources) | `test_d3dmetal_translator_caps` `heap_index` | **runs correctly** | Resource binding tier 3. A UAV, a raw SRV, a typed SRV, a texture and a sampler, all taken from the descriptor heaps by index (`ResourceDescriptorHeap`, `SamplerDescriptorHeap`, root signature flags `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED`): all 65 values correct. |
| 64-lane waves | `test_d3dmetal_translator_caps` `wave64`, with `test_d3dmetal_gpu_limits` `wave` | **workaround** | The host runs 32-lane waves (`WaveLaneCountMin = Max = 32`), and a `[WaveSize(64)]` kernel is created but not run (above). A 64-thread group standing for one 64-lane wave gives the 64-lane ballot, exclusive prefix sum, read-lane and sum on all 64 lanes, both through groupshared memory and through the host's own wave operations merged across its two waves. |
| 64-bit atomics on typed resources | `test_d3dmetal_gpu_limits` `atomic64`, `lock64` | **workaround** | D3DMetal reports `AtomicInt64OnTypedResourceSupported = 1` and `AtomicInt64OnDescriptorHeapResourceSupported = 1`, but kernels using 64-bit atomics, on typed and on raw resources, are created and not run: even their plain stores are missing. The per-texel lock over 32-bit words with a retry cap of 1024 is exact (0 of 512 updates dropped); with a cap of 64 it drops updates. A translator must not trust the reported support. |
| Amplification and mesh shaders | `test_d3dmetal_translator_caps` `mesh` | **runs correctly** | `D3D12_MESH_SHADER_TIER_1` (enum value 10). An amplification shader passes a payload to two mesh groups through `DispatchMesh`; each draws half of a 4x4 target with a pixel shader: all 16 pixels correct. |
No need is *blocked*, so no ADR is required by #671. The shaders are regenerated with
`tests/conformance/test_d3dmetal_translator_caps/shaders/compile.sh` (same DXC release as below).
## Unverified reports (not evidence)
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
+70 -2
View File
@@ -1,8 +1,7 @@
# D3D12 swapchain references under D3DMetal
An observation to check before M2 builds presentation on `IDXGISwapChain3`. One Apple M4,
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. Not independently reproduced, and not an
Xbox hardware result.
macOS 27, CrossOver 26.3.0 (26.3.0.39832), 2026-11-26. See the independent Apple M2 Pro run below.
| | D3DMetal | Wine `vkd3d` path |
| --- | --- | --- |
@@ -18,3 +17,72 @@ is explained.
The probe is
[`lifetime.c` at `7c512af`](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_lifetime/lifetime.c)
on the branch of #425; it is not part of this branch. Tracked in #450.
## Independent run on Apple M2 Pro
On 2026-11-26, an Apple M2 Pro (16 GiB, macOS 27.3 build 26C5035r) reproduced
the swapchain retention in CrossOver 26.3.0.39832 with D3DMetal 3.0. The
same x86-64 probe under Rosetta 2 released all swapchains in CrossOver
Preview 27.0.0.41303. Each CrossOver build used a fresh Windows 11
64-bit bottle. The Direct3D 12 workload loaded the `apple_gptk` D3D12
and DXGI modules in both builds. The bundled framework in the Preview
build's `apple_gptk` directory reports version 4.0b3.
| Swapchain lifetime probe | Initial reference count | Application release returned | Witnesses retained |
| --- | ---: | ---: | ---: |
| 26.3 D3DMetal | 2 | 1 | 12 of 12 |
| 26.3 Wine D3D12 | 1 | 0 | 0 of 12 |
| Preview D3DMetal | 1 | 0 | 0 of 12 |
| Preview Wine D3D12 | 1 | 0 | 0 of 12 |
Destroying the window before releasing the swapchain and calling
`ResizeBuffers` before teardown each left 3 of 3 witnesses retained on
26.3 D3DMetal. Explicitly detaching the witness released the probe's
private data, while the swapchain's release still returned 1. The
deliberately retained witness control failed as expected. An extra
application-side `Release` would drop a reference the application
does not own.
The separate D3D12 integrated workload presented 600 frames and verified
eight readbacks with zero mismatches on both D3DMetal builds. It failed
only the shutdown gate on 26.3, where the final device release returned
2. Preview passed shutdown with a final device release of 0. These runs
used the direct host D3D12 path without BetterXen's D3D12 shim. The
comparison establishes behavior for these two CrossOver builds on this
host. The underlying ownership change is unknown.
Build the probe from the pinned source linked above with
`x86_64-w64-mingw32-clang -std=c11 -O2 -Wall -Wextra -Werror lifetime.c -o d3d12-lifetime.exe -ld3d12 -ldxgi -ldxguid -luser32`
(LLVM-MinGW 20261117 in this run). Run in a clean bottle using
`ROSETTA_ADVERTISE_AVX=1 CX_GRAPHICS_BACKEND=d3dmetal wine --bottle <bottle> <absolute-path-to-exe> --cycles 12`
and repeat with `CX_GRAPHICS_BACKEND=wined3d`. The two witness controls
use `--cycles 3 --detach-witness` with and without `--retain-app-reference`.
## Related Direct3D acceptance failures
The [integrated D3D12 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d12_integrated/integrated12.c)
also reproduced the presentation slowdown on the Wine D3D12 path on
26.3. With `CX_GRAPHICS_BACKEND=wined3d` and a 600-frame target, the
workload logged approximately 2,000 ms inside `Present` on frames
12–38, then exited 3 after a 10-second GPU completion wait failed. The
previous M4 report saw the slowdown around frame 437. This run exited
before reaching normal teardown. Preview completed the same 600-frame
workload on the Wine path with eight verified readbacks, no mismatches
and clean shutdown. A 600-frame repeat on 26.3 passed with `--vsync`
enabled. A subsequent 600-frame repeat also passed with the flag off,
so the slowdown remains intermittent and the successful vsync run
does not establish a workaround.
The [integrated D3D11 workload](https://github.com/MacosPorters/betterxen/blob/7c512af/tests/conformance/test_d3d11_integrated/integrated.c)
completed the 20,000-frame soak on 26.3 with 46 verified readbacks,
zero mismatches and a clean shutdown. The intermittent GPU event
stall did not recur in this run. Preview also completed all 20,000
frames and all 46 readbacks, then failed the shutdown gate with one
device reference remaining. A separate 600-frame Preview run
reproduced that shutdown result.
The 26.3 keyboard check delivered five macOS events to the workload and
reached the expected offset (16, 32). The negative control delivered
two Up events and reached (0, -32), which the input gate rejected as
expected. These were isolated runs, so they do not reproduce the
intermittent failure observed inside the full acceptance suite.
+94
View File
@@ -84,3 +84,97 @@ Identification is not execution. `xenora shaders coverage` reports forms
discovered in metadata against forms the semantic decoder accepts
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
per form remains in `docs/status.toml`.
## 64 KiB swizzle (`SW_64KB_S`) — public sources (#505)
`xg_xs.dll` implements `SW_64KB_S` tile addressing for `TEXTURE2D`, one array
slice and one mip, over the element sizes the RB+ tables specify: 32-bpp RGBA8
(4-byte elements) and the BC family — BC1/BC4 with 8-byte blocks and
BC2/3/5/6H/7 with 16-byte blocks, where one "texel" element is a 4x4 block and
`elemLog2 = log2(block_bytes)`. At 32 bpp the two public sources below agree
bit-for-bit, which is why this is the mode implemented first; the 8- and 16-byte
rows come from AddrLib alone.
**Microsoft, `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE`** (public, no NDA):
<https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout>.
The page gives the 32-bpp masks `xBytesMask = 0xAA8F` and `yMask = 0x5570`,
combined with `_pdep_u32`. It states that tail-mip packing is **adapter-specific**,
which is why only the single-mip case is implemented. It has no `D` or `R` variant.
**AMD AddrLib (MIT)** — the authoritative public implementation, in both
[Mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib)
and [AMD PAL](https://github.com/GPUOpen-Drivers/pal/tree/dev/src/core/imported/addrlib)
(`SPDX-License-Identifier: MIT`, AMD copyright; PAL `LICENSE.txt` is MIT):
- `src/amd/addrlib/inc/addrtypes.h` — `AddrSwizzleMode`: `ADDR_SW_64KB_S` = 9,
`_D` = 10, `_R` = 11 (Reserved on GFX10).
- `src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h` — `GFX10_SW_64K_S_PATINFO`
and `GFX10_SW_64K_S_RBPLUS_PATINFO`, plus the `GFX10_SW_PATTERN_NIBBLE01/2/3/4`
tables. The RB+ variant is used because `gfx1030` is Navi2x.
- `src/amd/addrlib/src/gfx10/gfx10addrlib.h` — `GetSwizzlePatternFromPatternInfo`,
`IsInMipTail`.
- `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp` — `GetSwizzlePatternInfo`,
`HwlComputeSurfaceAddrFromCoordTiled`, `ComputeSurfaceAddrFromCoordMacroTiled`.
- `src/amd/addrlib/src/core/addrlib2.cpp` — `ComputeThinBlockDimension`,
`Block256_2d`.
There is **no** standalone GPUOpen `addrlib` repository (404). The public
[RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf)
only names a 5-bit "SW mode" field in the T# descriptor (bits 120:116) and does
not define the patterns.
### S versus D versus R
- **S and D are not interchangeable.** At 32 bpp RB+, D uses nibble01 index 39
(`[0,0,X0,X1,Y0,Y1,X2,Y2]`) while S uses index 2
(`[0,0,X0,X1,Y0,Y1,Y2,X2]`) — address bits 6 and 7 swapped.
- **`SW_64KB_R` has no public GFX10 form.** Mesa's `SwizzleModeTable` marks
`ADDR_SW_64KB_R` (enum 11) as Reserved; the render-target mode is
`ADDR_SW_64KB_R_X`, whose pipe/packer XOR depends on the console
`GB_ADDR_CONFIG`, which is not public.
### Xbox `XG` tile modes are NDA
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
interface have been retired: `xg_xs.dll` now follows the documented XG contract
titles call, with values from the authorized GDK documentation recorded as derived
facts in `shims/xg_xs/xg_xbox.cpp`.
### Element sizes and the derived masks
For a 64 KiB tile the intra-tile byte offset of element (x, y) is
`pdep(x, x_mask) | pdep(y, y_mask)`, where x and y are **block** indices (one
4x4 block for BC, one texel for 32 bpp). The masks were expanded by hand from
`GFX10_SW_PATTERN_NIBBLE01/2/3` at the patinfo indices
`GFX10_SW_64K_S_RBPLUS_PATINFO` selects for each `elemLog2`:
| block bytes | formats | `elemLog2` | x mask | y mask | tile (blocks) |
| --- | --- | --- | --- | --- | --- |
| 4 | R8G8B8A8_* | 2 | `0xAA8C` | `0x5570` | 128 x 128 |
| 8 | BC1, BC4 | 3 | `0xAAC8` | `0x5530` | 128 x 64 |
| 16 | BC2, BC3, BC5, BC6H, BC7 | 4 | `0xAAC0` | `0x5530` | 64 x 64 |
At 32 bpp the x mask `0xAA8C` is Microsoft's public `xBytesMask` `0xAA8F` with
the two intra-texel byte bits cleared (`0xAA8F & ~0x3`), and the y mask matches
`0x5570` exactly. The 8- and 16-byte rows have no D3D12 page to cross-check
against; they are AddrLib-only, which is stated in the PR risks. All three rows
were checked to be bijections over their 64 KiB tile (16384 / 8192 / 4096
distinct offsets, each block-aligned and inside the tile).
### Verification
The three masks above were expanded and their bijectivity checked against an
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
back from the shim:
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
the offsets are a bijection of aligned slots inside the 64 KiB tile;
- it checks that the 16 texels of a BC block share one byte offset.
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
Xbox-hardware claim.
+17
View File
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
| LLVM (AMDGPU target) | [llvm/llvm-project](https://github.com/llvm/llvm-project) | Homebrew LLVM 23.1.6 (`llvm-mc`) | Apache-2.0 WITH LLVM-exception | Source of the generated GFX10.3 opcode table and decoder test vectors (`shader-transpiler/crates/gfx10-translate`) | Run locally by `scripts/console-shader/gen_opcodes.py` and `gen_llvm_vectors.py`. Only facts are committed (opcode number to mnemonic, instruction words to text); no LLVM code or tables are copied. Accepted by the repository owner on 2026-11-30 (AGENTS.md Section 4). |
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
## Built and run for M1-D2 (#417)
@@ -26,6 +27,22 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
| directx-native | [osy/directx-native](https://github.com/osy/directx-native) | `7258be1c56cdbf1e55c56b1bc4a866169c8ca0da` (pinned by d3dmetal-native's `subprojects/directx-native.wrap`) | Apache-2.0: repository `LICENSE`, plus `SPDX-License-Identifier: Apache-2.0` in 22 of its 25 files | Build dependency of d3dmetal-native, statically linked into the dylib; nothing is copied into BetterXen | Supplies the shared-resource and embedder headers that `d3dmetal_native.h` includes. Apache-2.0 is compatible with GPL-3.0, not GPL-2.0. |
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The package ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
## Interface facts for XGameSave and XPackage (#468, #492)
Facts only, no text or code copied. **Pending maintainer provenance acceptance** under AGENTS.md §4.
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| xgameruntime-docs | [xodus-gaming/xgameruntime-docs](https://github.com/xodus-gaming/xgameruntime-docs) | `7090008692569aa6081e30dfdd9de58237741e24` | Repository `LICENSE` is the unmodified GNU GPL version 3 text. No project copyright holder is named, nothing states "only" or "or later", and the documentation files checked (`README.md`, `COM/XErrorImpl/IXErrorImpl.md`, `COM/XPackageImpl/IXPackageImpl.md`, `IXPackageImpl2.md`, `XErrorReport.md`) carry no licence or copyright header. | Source of the interface facts behind the public `QueryApiImpl` entries in `shims/xgameruntime/com_dispatch.cpp`: class and interface ids, interface inheritance, and vtable slot order for `IXGameSaveImpl`–`IXGameSaveImpl3` and `IXPackageImpl`–`IXPackageImpl4`. | Its README says the information "was found using black box reverse engineering" following Wine's clean-room guidelines. It states no use of Microsoft binaries, leaked material or the GDK EULA either way, and the COM notes say the listing is incomplete. It lists `IXErrorImpl` slot 3 only as unknown. BetterXen's answer for that slot (return `false`) instead follows an interop observation in the #492 review (2026-11-26), not this repository. Function signatures come from Microsoft Learn. |
## Vendored for the public PC DirectStorage interfaces (#483)
Checked on 2026-11-26 by reading the package files, not just its metadata. Not legal advice. Details and file hashes: [`shims/xcrdapi/dstorage/README.md`](../../shims/xcrdapi/dstorage/README.md).
| Project | Source | Pin | License (per file) | Role for BetterXen | Findings |
| --- | --- | --- | --- | --- | --- |
| DirectStorage SDK headers | NuGet [`Microsoft.Direct3D.DirectStorage`](https://www.nuget.org/packages/Microsoft.Direct3D.DirectStorage/1.4.0) | `1.4.0`, package SHA-256 `0838e7f71b14acfbd1ac7ecc5e943f6c95e4f4e679e8a67f8ff6e7c102414321` | `native/include/dstorage.h` and `dstorageerr.h` each carry `Copyright (c) Microsoft Corporation` / `Licensed under the MIT license`; the package's `LICENSE-CODE.txt` is the MIT text. The package as a whole is under the proprietary *Microsoft DirectStorage SDK* terms, whose distributables are only `dstorage.dll` and `dstoragecore.dll`. | The two headers are vendored unmodified in `shims/xcrdapi/dstorage/` for the public `IDStorage*` interfaces in `XCRDAPI.dll` and `test_xcrdapi`. No DLL or other package file is used or redistributed. | The headers are not in the MIT `microsoft/DirectStorage` repository; they ship only in this package. Microsoft Learn documents the same API but gives neither IIDs nor vtable order. The Xbox `IDStorage*X` interfaces (`dstorage_xs.h`) ship only in the GDK with Xbox Extensions, "only available to licensed partners", so they are excluded. |
## Additional candidates found by search (not reviewed)
Found by GitHub search on 2026-11-25. Only repository metadata was read; none was evaluated, installed or run, and none is a recommendation. Licenses are what GitHub reported.
+91 -13
View File
@@ -1,6 +1,6 @@
# BetterXen Roadmap
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
## Direction
@@ -9,7 +9,8 @@ BetterXen builds a modular **Xbox Series (`Scarlett`) compatibility layer for Ap
```text
BetterXen (in-tree):
launcher/ (ARM64 CLI, probe, telemetry) + abi/ (frozen contracts)
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs)
shims/ (16 cross-compiled x86-64 PE32+ Xbox Game OS DLLs
+ the Rust-built bx_shader_bridge.dll)
shader-transpiler/ (DXBC / DXIL / ACCC / FSPX classifier & RDNA 2 pipeline)
|
External Foundation (user-installed, never bundled):
@@ -18,34 +19,111 @@ External Foundation (user-installed, never bundled):
Apple Silicon: ARM64, Metal, unified memory
```
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
---
## Completed Research Inputs (Carried Forward)
## Research Inputs
- **Licensing & redistribution boundaries:** [docs/research/crossover-licensing.md](research/crossover-licensing.md) and [docs/licenses.md](licenses.md) (#354). CrossOver, D3DMetal, and Rosetta 2 stay strictly external and unbundled.
- **Primary-source verification & upstream registry:** [docs/research/primary-source-verification-2026-11-25.md](research/primary-source-verification-2026-11-25.md), [docs/research/upstream-registry.md](research/upstream-registry.md), and [docs/research/component-reuse-matrix.md](research/component-reuse-matrix.md).
- **Hybrid measurement protocol:** [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) (#353).
- **Buffer ownership on CrossOver 26.3.0.39832 and D3DMetal 3.0 (#473).** On the tested M4 (24 GiB) and M5 (16 GiB), the two existing-memory heap imports returned `E_NOTIMPL`. A D3D12-owned persistent buffer mapping supported fence-separated CPU/GPU access and ordered virtual aliasing (BASE-2, BASE-4, A-8). The actual CPU address could miss 64 KiB alignment (A-6). Inside the timed small-copy window, no serialized copy cost as much as the explicit full copy to READBACK. The other workstream accepted 13 of 29 register entries within stated scopes, mostly through same-source reruns. #473 remains open. Physical page identity, hidden copies, workload memory savings and speedups remain open. [Report 001](https://github.com/MacosPorters/betterxen/blob/0aaa81ab81309d64432d97d3005284c8b13cd285/docs/research/publications/001-unified-memory/technical-findings.md) · [Evidence register](https://github.com/MacosPorters/betterxen/blob/f8810a48af384d13c594b9fba954200bfdb944f1/docs/research/d3dmetal-zero-copy/allocation-profiling/consolidation-draft/evidence-register.md) · [Review corrections](https://github.com/MacosPorters/betterxen/discussions/493)
- **Target-workload shader corpus (static scan, 2026-11-28).** A read-only container scan of an authorized local test workload measured what its shipped components embed — structure only, no run, no extraction, and the workload is not redistributed. Its `XboxBvhBuilder` component carries **52 DXIL compute containers, all Shader Model 6.5, with valid LLVM bitcode**; its AMD FidelityFX upscaler component carries **29 ACCC-only containers** whose payloads start with `FSPX`, none with a `DXIL` chunk; its main executable carries **10 DXIL containers (nine pixel, one vertex, Shader Model 6.6) whose `DXIL` chunks hold four-byte `NOBC` payloads** — valid program headers, no executable bitcode. Its packaged shader archive exposes no plaintext `DXBC` signatures and remains unclassified. BetterXen's classifier accepts all 62 DXIL containers, so it currently labels the 10 `NOBC` programs as executable DXIL, and it rejects all 29 `FSPX` containers because their section tables do not match the clean-room `FSPX` layout (`FspxSectionOutOfBounds` at the time of the scan; that cause is `FspxLayoutMismatch` since #599, not re-measured). Runtime use is unmeasured: the recorded startup run stopped before pipeline creation and wrote no `shader_gate` records. [ADR 0008](adr/0008-m2-shader-format-gate.md)
---
## Milestones (M0 → M6)
## Foundation and stages
| Milestone | Objective | Exit Gate | Status |
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
### Foundation (history)
| Milestone | What it established | Status |
| --- | --- | --- |
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
### The stages
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
| Stage | The target build… | Exit gate | Status |
| --- | --- | --- | --- |
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; 16/16 PE32+ DLLs pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), placed resources over `xmem`, bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **Left** (repository owner's decision, 2026-11-30; the gate was not run under the run protocol) |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | **Current** (since 2026-11-30) |
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
### Boot
**Known work, all found by running the target build:**
| Blocker | Effect | State |
| --- | --- | --- |
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
**Not needed for the gate:** audio output, correct pictures, performance.
### Picture
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
2. **The translator.** BetterXen writes its own GFX10-to-DXIL translator in `shader-transpiler/` and exposes it through `bx_shader_bridge.dll`; the upstream emulator's translator is not used (repository owner's decision, 2026-11-29). The design is mechanical: one rule per instruction, registers as variables, and control flow as numbered blocks in a dispatch loop, so no structure has to be reconstructed. Each rule is checked against the console compiler's output for a shader of our own (source rank 2). A prototype on branch `experiment/visible-frame` translates the four pipelines of the build's first screen and is the reference for that screen.
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
### Menus to Playable — known work and unknowns
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
| Stage | Known work | Main unknown |
| --- | --- | --- |
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
### Decision gates
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
| Gate | When | Question | If the answer is no |
| --- | --- | --- | --- |
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
### What counts as progress
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
1. remove a blocker of the current stage (shown by the run report before and after);
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
4. retire a risk at a decision gate.
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
---
## How Progress Is Reported
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
+139
View File
@@ -0,0 +1,139 @@
# Target-Build Bring-Up: Development Cycle and Review
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
## Authorization is recorded, not assumed
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
- the build;
- the evidence class: target-build observation, or authorized SDK documentation;
- the maintainer who approved it;
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
- **The note's ID goes into every PR and every review** that relies on that evidence.
## Roles
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
- **Author.** Turns one finding into one single-track PR.
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
## Cycle
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
2. **Record the evidence privately,** under an evidence note ID.
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
6. **Review independently** (see "What a reviewer does").
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
### Bring-up checkpoints
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
1. **Starts:** reaches its first graphics device.
2. **Presents:** presents its first frame, whatever it contains.
3. **Frame loop:** keeps presenting for a recorded duration.
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
5. **Interactive:** reaches a menu that accepts input.
Each PR states which checkpoint it affects, and the measured result before and after.
## PR description template
```text
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
Source: "authorized SDK documentation" and/or "target-build observation";
never quote header or documentation text, never name the title or build
Authorization: authorization note ID
Evidence: evidence note ID(s)
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
Test: the conformance test that asserts the contract, and how its expected
values were derived independently of the implementation
Checkpoint: the checkpoint this affects, with the measured result before and after
```
## What a reviewer does
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
## Offline-run procedure
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
```sh
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
BOTTLE=<bottle name>
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
# serve the title outside it.
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
&& echo REACHABLE || echo BLOCKED
# 3. Run the title inside the same profile. Every process it starts, including the new
# wineserver, inherits the sandbox.
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 BX_PRESENT_DUMP='Z:\<frames folder>' BX_INPUT_SCRIPT=A@40,A@50 \
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
```
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
## Diagnostics
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
| Switch | Where | Effect |
| --- | --- | --- |
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
| `BX_INPUT_SCRIPT=<presses>` | `GameInput` | Scripted gamepad presses for unattended runs, without window focus: comma-separated `BUTTON@SECONDS` (`A@40,DOWN@50.5,A@52`), each held 300 ms, timed from the first gamepad reading. Buttons `MENU VIEW A B X Y UP DOWN LEFT RIGHT`. Each press is logged (`input_script`), and so is each entry that cannot be read |
| `BX_CONTINUE_ASSERTS=1` | `bx_runtime_veh` | Steps over an `int3` in the title's own executable (a continuable assert) instead of letting it reach the title's crash reporter. Each address is logged once (`assert_continued`), so the report still lists every assert. Use it to get past a known assert to the next blocker, and say so in the evidence |
Their output can contain title addresses and file names, so it goes only into the private evidence store.
## Evidence
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
## What never enters the repository
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
- SDK header or documentation text;
- the title's name or file names;
- identifiers derived from the title or build: its hashes, addresses or raw logs;
- decompiled code or disassembly;
- screenshots of the title;
- personal paths.
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
+1
View File
@@ -13,6 +13,7 @@ path = "src/main.rs"
bx-probe = { path = "../bx-probe" }
bx-telemetry = { path = "../bx-telemetry" }
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
gfx10-translate = { path = "../../../shader-transpiler/crates/gfx10-translate" }
# POSIX signals and process groups for `run` supervision.
libc = "=0.2.191"
+548
View File
@@ -0,0 +1,548 @@
//! Xbox title drive letters, linked in the prefix's `dosdevices` before launch.
//!
//! The project-authorized target title we traced reads its package from `G:` and writes
//! temporary files such as crash logs to `T:`. That is an observation of one title at startup;
//! that `G:` is the package root and `T:` temporary storage for Xbox titles in general is an
//! inference. A Wine prefix has neither drive, so that title's first `G:\...` open fails with
//! `STATUS_OBJECT_PATH_NOT_FOUND`. `bx-cli run` links `g:` to the executable's directory and
//! `t:` to `drive_c/bx_temp`.
//!
//! As with system32 staging (#474), a drive letter the prefix already uses is not ours. A
//! `.bx-drives` manifest in `dosdevices` records each link this tool made, and only a link that
//! is listed and still points where it was pointed is replaced. Any other mapping to a
//! different target is reported and left unchanged.
use std::collections::BTreeMap;
use std::fs;
use std::io::{self, Write};
use std::os::fd::AsRawFd;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::{OpenOptionsExt, symlink};
use std::path::{Path, PathBuf};
const MANIFEST: &str = ".bx-drives";
const LOCK_FILE: &str = ".bx-drive-mapping.lock";
/// The prefix-relative target of `t:`, in the form Wine itself uses for `c:`.
pub const TEMP_TARGET: &str = "../drive_c/bx_temp";
#[derive(Debug)]
pub struct DriveMappingLock {
_file: fs::File,
}
/// Holds the prefix's drive mappings stable until the returned lock is dropped.
pub fn lock_drive_mappings(prefix: &Path) -> Result<DriveMappingLock, String> {
fs::create_dir_all(prefix).map_err(|e| {
format!(
"cannot prepare prefix {} for drive lock: {e}",
prefix.display()
)
})?;
let prefix = fs::canonicalize(prefix).map_err(|e| {
format!(
"cannot resolve prefix {} for drive lock: {e}",
prefix.display()
)
})?;
let path = prefix.join(LOCK_FILE);
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.custom_flags(libc::O_NOFOLLOW)
.open(&path)
.map_err(|e| format!("cannot open drive lock {}: {e}", path.display()))?;
loop {
// The open file descriptor stays alive in DriveMappingLock for the full launch.
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if result == 0 {
return Ok(DriveMappingLock { _file: file });
}
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted {
continue;
}
if error.kind() == io::ErrorKind::WouldBlock {
return Err(format!(
"another bx-cli run is active for prefix {}; refusing to launch with shared Xbox drive mappings",
prefix.display()
));
}
return Err(format!("cannot lock {}: {error}", path.display()));
}
}
#[derive(Debug)]
pub enum Mapping {
Created(char, PathBuf),
/// A link this tool made earlier, pointed at a new target.
Retargeted(char, PathBuf),
Unchanged(char, PathBuf),
/// A mapping this tool did not make, to a different target; left as it is.
Foreign {
letter: char,
existing: String,
wanted: PathBuf,
},
}
impl Mapping {
pub fn describe(&self) -> String {
match self {
Mapping::Created(l, t) => {
format!("mapped {}: to {}", l.to_ascii_uppercase(), t.display())
}
Mapping::Retargeted(l, t) => {
format!(
"remapped own {}: to {}",
l.to_ascii_uppercase(),
t.display()
)
}
Mapping::Unchanged(l, t) => {
format!(
"{}: already maps to {}",
l.to_ascii_uppercase(),
t.display()
)
}
Mapping::Foreign {
letter,
existing,
wanted,
} => format!(
"warning: {}: already maps to {existing}, not {}; left unchanged, so the guest \
may not find its files there",
letter.to_ascii_uppercase(),
wanted.display()
),
}
}
}
fn read_manifest(dosdevices: &Path) -> Result<BTreeMap<char, PathBuf>, String> {
let path = dosdevices.join(MANIFEST);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
};
let mut owned = BTreeMap::new();
for line in text.lines().filter(|l| !l.is_empty()) {
let mut chars = line.chars();
match (chars.next(), chars.next()) {
(Some(letter), Some('\t')) if letter.is_ascii_lowercase() => {
let encoded = chars.as_str();
let target = match encoded.strip_prefix('@') {
Some(hex) => decode_path(hex)
.ok_or_else(|| format!("malformed path in {}: {line:?}", path.display()))?,
None => PathBuf::from(encoded),
};
owned.insert(letter, target);
}
_ => return Err(format!("malformed line in {}: {line:?}", path.display())),
}
}
Ok(owned)
}
fn write_manifest(dosdevices: &Path, owned: &BTreeMap<char, PathBuf>) -> Result<(), String> {
let path = dosdevices.join(MANIFEST);
let mut text = String::new();
for (letter, target) in owned {
text.push_str(&format!("{letter}\t@{}\n", encode_path(target)));
}
// Written to a temporary file and renamed over the manifest, like `relink`, so an
// interrupted write can never leave a truncated manifest that later runs refuse to parse.
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)
.map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
let written = file.write_all(text.as_bytes()).and_then(|()| {
drop(file);
fs::rename(&tmp, &path)
});
if written.is_err() {
let _ = fs::remove_file(&tmp);
}
written.map_err(|e| format!("cannot write {}: {e}", path.display()))
}
fn encode_path(path: &Path) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let bytes = path.as_os_str().as_bytes();
let mut encoded = String::with_capacity(bytes.len() * 2);
for &byte in bytes {
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
encoded
}
fn decode_path(hex: &str) -> Option<PathBuf> {
fn nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
let bytes = hex.as_bytes();
if bytes.len() % 2 != 0 {
return None;
}
let mut decoded = Vec::with_capacity(bytes.len() / 2);
for pair in bytes.chunks_exact(2) {
decoded.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
}
Some(PathBuf::from(std::ffi::OsString::from_vec(decoded)))
}
/// Points `link` at `target`, replacing what is there through a rename so the link never
/// disappears in between.
fn relink(dosdevices: &Path, link: &Path, target: &Path) -> io::Result<()> {
let tmp = dosdevices.join(format!(".bx-drive-tmp.{}", std::process::id()));
let _ = fs::remove_file(&tmp);
symlink(target, &tmp)?;
let result = fs::rename(&tmp, link);
if result.is_err() {
let _ = fs::remove_file(&tmp);
}
result
}
/// Links `g:` to `package_dir` and `t:` to [`TEMP_TARGET`] in `prefix`'s `dosdevices`.
pub fn map_xbox_drives(prefix: &Path, package_dir: &Path) -> Result<Vec<Mapping>, String> {
let dosdevices = prefix.join("dosdevices");
if !dosdevices.is_dir() {
return Err(format!(
"{} does not exist (start the prefix once so Wine creates it)",
dosdevices.display()
));
}
let temp_dir = prefix.join("drive_c/bx_temp");
fs::create_dir_all(&temp_dir)
.map_err(|e| format!("cannot create {}: {e}", temp_dir.display()))?;
let mut owned = read_manifest(&dosdevices)?;
let mut mappings = Vec::new();
for (letter, target) in [
('g', package_dir.to_path_buf()),
('t', PathBuf::from(TEMP_TARGET)),
] {
let link = dosdevices.join(format!("{letter}:"));
let current = match fs::symlink_metadata(&link) {
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(format!("cannot inspect {}: {e}", link.display())),
Ok(meta) if meta.file_type().is_symlink() => Some(
fs::read_link(&link).map_err(|e| format!("cannot read {}: {e}", link.display()))?,
),
Ok(_) => {
mappings.push(Mapping::Foreign {
letter,
existing: format!("a non-link entry {}", link.display()),
wanted: target,
});
continue;
}
};
let mapping = match current {
None => {
owned.insert(letter, target.clone());
write_manifest(&dosdevices, &owned)?;
relink(&dosdevices, &link, &target)
.map_err(|e| format!("cannot create {}: {e}", link.display()))?;
Mapping::Created(letter, target.clone())
}
Some(current) if current == target => Mapping::Unchanged(letter, target.clone()),
Some(current) if owned.get(&letter) == Some(&current) => {
owned.insert(letter, target.clone());
write_manifest(&dosdevices, &owned)?;
if let Err(error) = relink(&dosdevices, &link, &target) {
owned.insert(letter, current);
let restore = write_manifest(&dosdevices, &owned);
let detail = restore
.err()
.map(|e| format!("; also could not restore the drive manifest: {e}"))
.unwrap_or_default();
return Err(format!(
"cannot replace {}: {error}{detail}",
link.display()
));
}
Mapping::Retargeted(letter, target.clone())
}
Some(current) => {
mappings.push(Mapping::Foreign {
letter,
existing: current.display().to_string(),
wanted: target,
});
continue;
}
};
mappings.push(mapping);
}
Ok(mappings)
}
#[cfg(test)]
mod tests {
use super::*;
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let p = std::env::temp_dir().join(format!(
"bx-drives-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = fs::remove_dir_all(&p);
fs::create_dir_all(p.join("prefix/dosdevices")).unwrap();
fs::create_dir_all(p.join("game")).unwrap();
TempDir(p)
}
fn prefix(&self) -> PathBuf {
self.0.join("prefix")
}
fn game(&self) -> PathBuf {
self.0.join("game")
}
fn link(&self, letter: char) -> PathBuf {
self.0.join(format!("prefix/dosdevices/{letter}:"))
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn missing_drives_are_created_and_resolve() {
let t = TempDir::new("create");
fs::write(t.game().join("package.bin"), b"pkg").unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(
mappings[..],
[Mapping::Created('g', _), Mapping::Created('t', _)]
));
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
assert_eq!(
fs::read_link(t.link('t')).unwrap(),
PathBuf::from(TEMP_TARGET)
);
// Both links resolve the way Wine resolves them, from inside dosdevices.
assert_eq!(fs::read(t.link('g').join("package.bin")).unwrap(), b"pkg");
assert!(t.link('t').is_dir());
}
#[test]
fn a_second_run_changes_nothing() {
let t = TempDir::new("rerun");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(
mappings[..],
[Mapping::Unchanged('g', _), Mapping::Unchanged('t', _)]
));
}
#[test]
fn an_own_link_follows_a_new_package_directory() {
let t = TempDir::new("retarget");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(mappings[0], Mapping::Retargeted('g', _)));
assert_eq!(fs::read_link(t.link('g')).unwrap(), other);
}
#[test]
fn a_foreign_mapping_is_reported_and_kept() {
let t = TempDir::new("foreign");
let elsewhere = t.0.join("elsewhere");
symlink(&elsewhere, t.link('g')).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
assert!(mappings[0].describe().starts_with("warning: G:"));
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
// A link this tool did not record is never treated as its own on a later run.
let again = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&again[0], Mapping::Foreign { letter: 'g', .. }));
}
#[test]
fn an_own_link_changed_by_someone_else_becomes_foreign() {
let t = TempDir::new("changed");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
fs::remove_file(t.link('g')).unwrap();
let elsewhere = t.0.join("elsewhere");
symlink(&elsewhere, t.link('g')).unwrap();
let other = t.0.join("other-game");
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
}
#[test]
fn a_non_link_entry_is_never_touched() {
let t = TempDir::new("nonlink");
fs::create_dir_all(t.link('t')).unwrap();
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
assert!(matches!(&mappings[1], Mapping::Foreign { letter: 't', .. }));
assert!(t.link('t').is_dir() && !fs::symlink_metadata(t.link('t')).unwrap().is_symlink());
}
#[test]
fn a_prefix_without_dosdevices_is_an_error() {
let t = TempDir::new("nodos");
fs::remove_dir_all(t.prefix().join("dosdevices")).unwrap();
let e = map_xbox_drives(&t.prefix(), &t.game()).unwrap_err();
assert!(e.contains("dosdevices"), "{e}");
}
#[test]
fn a_malformed_manifest_is_an_error_not_an_ownership_claim() {
let t = TempDir::new("badmanifest");
fs::write(t.prefix().join("dosdevices").join(MANIFEST), "g /x\n").unwrap();
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
}
#[test]
fn a_failed_manifest_write_leaves_no_unrecorded_link() {
let t = TempDir::new("orphan");
// A directory where the manifest's temporary file goes makes the write fail.
let tmp = t
.prefix()
.join("dosdevices")
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
fs::create_dir(&tmp).unwrap();
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
assert!(
fs::symlink_metadata(t.link('g')).is_err(),
"g: must not be created before ownership is recorded"
);
fs::remove_dir(&tmp).unwrap();
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
}
#[test]
fn an_interrupted_manifest_write_keeps_the_previous_manifest() {
let t = TempDir::new("atomic");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let manifest = t.prefix().join("dosdevices").join(MANIFEST);
let before = fs::read(&manifest).unwrap();
// Fail the next write after the new contents would have been produced: the old
// manifest must survive whole, never truncated or half written.
let tmp = t
.prefix()
.join("dosdevices")
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
fs::create_dir(&tmp).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
assert_eq!(
fs::read(&manifest).unwrap(),
before,
"previous manifest kept intact"
);
fs::remove_dir(&tmp).unwrap();
// The intact manifest still proves ownership, so the retry re-points g:.
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
assert!(
fs::read_dir(t.prefix().join("dosdevices"))
.unwrap()
.all(|e| !e.unwrap().file_name().to_string_lossy().contains(".tmp."))
);
}
#[test]
fn manifest_temp_does_not_follow_an_existing_symlink() {
let t = TempDir::new("manifest-symlink");
let dosdevices = t.prefix().join("dosdevices");
let target = t.0.join("outside-manifest");
fs::write(&target, b"unchanged").unwrap();
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
symlink(&target, &tmp).unwrap();
assert!(write_manifest(&dosdevices, &BTreeMap::new()).is_err());
assert_eq!(fs::read(&target).unwrap(), b"unchanged");
assert_eq!(fs::read_link(&tmp).unwrap(), target);
}
#[test]
fn a_failed_retarget_restores_the_previous_manifest_and_link() {
let t = TempDir::new("retarget-failure");
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
let other = t.0.join("other-game");
fs::create_dir_all(&other).unwrap();
let temp_link = t
.prefix()
.join("dosdevices")
.join(format!(".bx-drive-tmp.{}", std::process::id()));
fs::create_dir(&temp_link).unwrap();
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
t.game()
);
}
#[test]
fn a_prefix_lock_rejects_another_launcher_until_released() {
let t = TempDir::new("lock");
let lock = lock_drive_mappings(&t.prefix()).unwrap();
let error = lock_drive_mappings(&t.prefix()).unwrap_err();
assert!(error.contains("another bx-cli run"), "{error}");
drop(lock);
assert!(lock_drive_mappings(&t.prefix()).is_ok());
}
#[test]
fn a_non_utf8_target_round_trips_through_the_manifest() {
let t = TempDir::new("non-utf8");
let mut game_bytes = t.0.as_os_str().as_bytes().to_vec();
game_bytes.extend_from_slice(b"/game-\xff");
let game = PathBuf::from(std::ffi::OsString::from_vec(game_bytes));
let owned = BTreeMap::from([('g', game.clone())]);
write_manifest(&t.prefix().join("dosdevices"), &owned).unwrap();
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
game
);
}
#[test]
fn a_legacy_plain_text_target_still_reads() {
let t = TempDir::new("legacy-manifest");
let legacy_target = t.0.join("old-game");
fs::write(
t.prefix().join("dosdevices").join(MANIFEST),
format!("g\t{}\n", legacy_target.display()),
)
.unwrap();
assert_eq!(
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
legacy_target
);
}
}
+184
View File
@@ -0,0 +1,184 @@
//! The GDK's own texture libraries, staged for runs of the target build (ADR 0010).
//!
//! Console textures use tiled layouts and BCPack compression. BetterXen does not reimplement
//! either: a run of the target build loads Microsoft's PC builds of the GDK's XG library
//! (`xg_xs.dll`, in place of BetterXen's `xg_xs` shim) and BCPack decoder (`BCPack.dll`, named to
//! `XCRDAPI.dll` through `BX_BCPACK_DLL`) from the GDK configured on this machine. Nothing from
//! the GDK is committed or shipped.
//!
//! The libraries are recognised by what they export, never by their place in the GDK: an
//! x86-64 PE32+ file named `xg_xs.dll` that exports `XGComputeTexture2DLayout` and does not
//! import `xmem.dll` (the console build does), and one named `BCPack.dll` that exports
//! `BCPackDecompress`. Conformance tests keep BetterXen's own shim: the GDK's are staged only
//! for the configured target build, or with `--gdk-libraries`.
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use bx_probe::probe_pe32_plus;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct GdkLibraries {
pub xg: Option<PathBuf>,
pub bcpack: Option<PathBuf>,
}
fn contains(bytes: &[u8], needle: &[u8]) -> bool {
bytes.windows(needle.len()).any(|w| w == needle)
}
/// Whether `bytes` are the PC build of the GDK's XG library.
pub fn is_pc_xg(bytes: &[u8]) -> bool {
let Ok(summary) = probe_pe32_plus(bytes) else {
return false;
};
contains(bytes, b"XGComputeTexture2DLayout\0")
&& contains(bytes, b"XGCreateTextureComputer\0")
&& !summary
.imports
.keys()
.any(|dll| dll.eq_ignore_ascii_case("xmem.dll"))
}
/// Whether `bytes` are the GDK's BCPack decoder.
pub fn is_bcpack(bytes: &[u8]) -> bool {
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"BCPackDecompress\0")
}
/// Finds the two libraries under `root` (bounded depth). When the GDK holds several builds,
/// the first by path order is used, so the choice is the same on every run.
pub fn find(root: &Path) -> GdkLibraries {
let mut xg = Vec::new();
let mut bcpack = Vec::new();
let mut stack = vec![(root.to_path_buf(), 0usize)];
while let Some((dir, depth)) = stack.pop() {
let Ok(entries) = fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(kind) = entry.file_type() else {
continue;
};
if kind.is_dir() {
if depth < 14 {
stack.push((path, depth + 1));
}
continue;
}
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
if name != "xg_xs.dll" && name != "bcpack.dll" {
continue;
}
let Ok(bytes) = fs::read(&path) else {
continue;
};
if name == "xg_xs.dll" && is_pc_xg(&bytes) {
xg.push(path);
} else if name == "bcpack.dll" && is_bcpack(&bytes) {
bcpack.push(path);
}
}
}
xg.sort();
bcpack.sort();
GdkLibraries {
xg: xg.into_iter().next(),
bcpack: bcpack.into_iter().next(),
}
}
/// Builds `out` as a copy of the shim folder's files with the GDK's libraries added: its
/// `xg_xs.dll` replaces BetterXen's shim, and `BCPack.dll` sits beside it. Returns the path of
/// the staged `BCPack.dll`, when there is one.
pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<Option<PathBuf>> {
fs::create_dir_all(out)?;
for entry in fs::read_dir(shims)? {
let entry = entry?;
if entry.file_type()?.is_file() {
fs::copy(entry.path(), out.join(entry.file_name()))?;
}
}
if let Some(xg) = &libs.xg {
fs::copy(xg, out.join("xg_xs.dll"))?;
}
match &libs.bcpack {
Some(bcpack) => {
let staged = out.join("BCPack.dll");
fs::copy(bcpack, &staged)?;
Ok(Some(staged))
}
None => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A minimal x86-64 PE32+ image with no sections, followed by `tail`. Import tables are
/// not modelled, so "imports xmem.dll" is covered by `is_pc_xg` on a real probe only.
fn pe(tail: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 0x200];
b[0..2].copy_from_slice(b"MZ");
b[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
b[0x40..0x44].copy_from_slice(b"PE\0\0");
b[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes()); // machine
b[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // SizeOfOptionalHeader
b[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes()); // PE32+
b[0x58 + 108..0x58 + 112].copy_from_slice(&16u32.to_le_bytes()); // NumberOfRvaAndSizes
b.extend_from_slice(tail);
b
}
#[test]
fn recognises_the_libraries_by_their_exports() {
assert!(is_pc_xg(&pe(
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
)));
// BetterXen's own shim exports only what titles import.
assert!(!is_pc_xg(&pe(
b"XGCreateTextureComputer\0XGSuggestSwizzleMode\0"
)));
assert!(!is_pc_xg(
b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"
));
assert!(is_bcpack(&pe(b"BCPackCompress\0BCPackDecompress\0")));
assert!(!is_bcpack(&pe(b"BCPackCompress\0")));
}
#[test]
fn finds_by_content_and_merges_beside_the_shims() {
let root = std::env::temp_dir().join(format!("bx-gdk-libs-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let gdk = root.join("gdk");
fs::create_dir_all(gdk.join("a/b")).unwrap();
fs::create_dir_all(gdk.join("c")).unwrap();
fs::write(
gdk.join("a/b/xg_xs.dll"),
pe(b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"),
)
.unwrap();
fs::write(gdk.join("c/xg_xs.dll"), pe(b"XGCreateTextureComputer\0")).unwrap(); // not the PC library
fs::write(gdk.join("c/BCPack.dll"), pe(b"BCPackDecompress\0")).unwrap();
let libs = find(&gdk);
assert_eq!(libs.xg, Some(gdk.join("a/b/xg_xs.dll")));
assert_eq!(libs.bcpack, Some(gdk.join("c/BCPack.dll")));
let shims = root.join("shims");
fs::create_dir_all(&shims).unwrap();
fs::write(shims.join("xg_xs.dll"), b"shim").unwrap();
fs::write(shims.join("d3d12_xs.dll"), b"d3d12").unwrap();
let out = root.join("out");
let staged = merge_shims(&shims, &libs, &out).unwrap();
assert_eq!(staged, Some(out.join("BCPack.dll")));
assert_eq!(fs::read(out.join("d3d12_xs.dll")).unwrap(), b"d3d12");
assert_eq!(
fs::read(out.join("xg_xs.dll")).unwrap(),
fs::read(gdk.join("a/b/xg_xs.dll")).unwrap()
);
assert_eq!(fs::read(shims.join("xg_xs.dll")).unwrap(), b"shim");
let _ = fs::remove_dir_all(&root);
}
}
File diff suppressed because it is too large. Load diff
+223 -6
View File
@@ -19,8 +19,32 @@ use std::fs;
use std::io;
use std::path::{Path, PathBuf};
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`.
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll"];
/// Shims loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32` (or shadowed by Wine builtin stubs in
/// `system32`, which Windows searches before `WINEPATH`).
pub const SYSTEM32_SHIMS: &[&str] = &["xgameruntime.dll", "GameInput.dll"];
/// Returns true when `bytes` is a Wine `winebuild` fake-DLL placeholder stub in `system32`
/// (`"MZ"` header, `"Wine builtin DLL\0"` at DOS offset `0x40`, and `"PE\0\0"` at `e_lfanew`).
///
/// Wine populates `drive_c/windows/system32/` with fake PE stubs for built-in modules such as
/// `gameinput.dll`. Unlike user- or installer-provided native DLLs (#474), these placeholders are
/// created by Wine itself and would otherwise shadow BetterXen shims on `LOAD_LIBRARY_SEARCH_SYSTEM32`
/// loads (`fixme:ginput:GameInputCreate ... stub!`).
pub fn is_wine_builtin_dll(bytes: &[u8]) -> bool {
const WINE_SIG_OFFSET: usize = 0x40;
const WINE_SIG: &[u8] = b"Wine builtin DLL\0";
if bytes.len() < WINE_SIG_OFFSET + WINE_SIG.len() + 4 {
return false;
}
if &bytes[0..2] != b"MZ" {
return false;
}
if &bytes[WINE_SIG_OFFSET..WINE_SIG_OFFSET + WINE_SIG.len()] != WINE_SIG {
return false;
}
let pe_off = u32::from_le_bytes([bytes[0x3c], bytes[0x3d], bytes[0x3e], bytes[0x3f]]) as usize;
pe_off >= WINE_SIG_OFFSET + WINE_SIG.len() && bytes.get(pe_off..pe_off + 4) == Some(b"PE\0\0")
}
/// `roots` plus, transitively, every import that is itself a file in the shim folder
/// (`is_shim`). Names are compared case-insensitively, as the Windows loader does, and returned
@@ -220,6 +244,8 @@ pub enum Staged {
Copied(PathBuf),
/// An earlier copy staged by this tool, refreshed because the shim changed.
Replaced(PathBuf),
/// A Wine `"Wine builtin DLL"` placeholder stub in `system32`, backed up once and replaced.
ReplacedWineStub(PathBuf),
Unchanged(PathBuf),
/// A [`SYSTEM32_SHIMS`] file the shim folder does not have.
Absent(PathBuf),
@@ -230,6 +256,9 @@ impl Staged {
match self {
Staged::Copied(p) => format!("staged {}", p.display()),
Staged::Replaced(p) => format!("refreshed own earlier copy {}", p.display()),
Staged::ReplacedWineStub(p) => {
format!("replaced Wine builtin stub {} (backup saved)", p.display())
}
Staged::Unchanged(p) => format!("already current {}", p.display()),
Staged::Absent(p) => format!("not staged, {} not found", p.display()),
}
@@ -365,6 +394,8 @@ where
));
} else if existing.as_deref().map(sha256_hex).as_ref() == owned.get(name) {
Staged::Replaced(dst.clone())
} else if existing.as_deref().is_some_and(is_wine_builtin_dll) {
Staged::ReplacedWineStub(dst.clone())
} else {
return Err(foreign(
&dst,
@@ -402,6 +433,12 @@ where
for (name, bytes, dst, result) in plan {
if !matches!(result, Staged::Unchanged(_)) {
let tmp = tmp_of(name);
// Snapshot what the target holds now, before the rename, so a failed manifest
// write can put the *old* bytes back (not the bytes just written).
let previous: Option<Vec<u8>> = match result {
Staged::Copied(_) => None,
_ => fs::read(&dst).ok(),
};
let published = before_publish(name).and_then(|()| match result {
// Nothing was there at step 1; refuse to replace whatever appeared since.
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
@@ -415,6 +452,41 @@ where
format!("cannot install {}: {e}", dst.display())
}
}),
// Wine fake-DLL placeholder stub: verify it is still a regular Wine builtin stub,
// preserve a one-time backup `.<name>.wine-builtin.bak`, then atomically replace.
Staged::ReplacedWineStub(_) => match fs::symlink_metadata(&dst) {
Ok(meta) if meta.is_file() => match fs::read(&dst) {
Ok(now) if is_wine_builtin_dll(&now) => {
let bak = system32.join(format!(".{name}.wine-builtin.bak"));
if fs::symlink_metadata(&bak).is_err() {
let bak_tmp = system32.join(format!(
".{name}.wine-builtin.bak.{}.bx-staging",
std::process::id()
));
fs::write(&bak_tmp, &now).map_err(|e| {
let _ = fs::remove_file(&bak_tmp);
format!("cannot write backup {}: {e}", bak_tmp.display())
})?;
let bak_res = install_new(&bak_tmp, &bak, &now);
let _ = fs::remove_file(&bak_tmp);
match bak_res {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
Err(e) => {
return Err(format!(
"cannot save Wine stub backup {}: {e}",
bak.display()
));
}
}
}
fs::rename(&tmp, &dst)
.map_err(|e| format!("cannot replace {}: {e}", dst.display()))
}
_ => Err(foreign(&dst, name, "changed while staging")),
},
_ => Err(foreign(&dst, name, "changed while staging")),
},
// Still our own earlier copy? Then the rename replaces it in one step.
_ => match fs::read(&dst) {
Ok(now) if owned.get(name) == Some(&sha256_hex(&now)) => fs::rename(&tmp, &dst)
@@ -429,6 +501,19 @@ where
let _ = fs::remove_file(&tmp);
owned.insert(name.clone(), sha256_hex(&bytes));
if let Err(e) = write_manifest(system32, &owned) {
// The file is installed but the manifest on disk does not name it, so the
// next run would call bx-cli's own copy foreign (#573). Roll the publish
// back: a Copied file is removed, a Replaced one is restored from the bytes
// it had before. The manifest is left exactly as it was, so the retry sees
// the same state it would have seen had the publish never happened.
match previous {
None => {
let _ = fs::remove_file(&dst);
}
Some(before) => {
let _ = fs::write(&dst, before);
}
}
discard(&pending);
return Err(e);
}
@@ -511,11 +596,12 @@ mod tests {
let (_t, shims, prefix) = setup("deps");
let sys = system32_dir(&prefix);
let staged = stage(&shims, &sys).unwrap();
assert_eq!(staged.len(), 2, "{staged:?}");
assert_eq!(staged.len(), 3, "{staged:?}");
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v1");
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
assert!(
!sys.join("unrelated.dll").exists(),
"only imported shims are staged"
"only SYSTEM32_SHIMS and imported shims are staged"
);
}
@@ -808,6 +894,67 @@ mod tests {
);
}
#[test]
fn a_manifest_write_failure_leaves_no_unowned_file() {
let (_t, shims, prefix) = setup("manifest");
let sys = system32_dir(&prefix);
// A directory where the manifest's temporary file has to go makes
// `write_manifest` fail after the first shim has already been published.
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::create_dir(&obstacle).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("cannot write"), "{err}");
assert!(
!sys.join("bx_runtime_veh.dll").exists(),
"the published file was rolled back, so the retry is not refused as foreign"
);
assert!(!sys.join(MANIFEST_NAME).exists());
// Only the obstacle itself is left: no staged copy, no temporary file.
let entries: Vec<String> = fs::read_dir(&sys)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(
entries,
vec![obstacle.file_name().unwrap().to_string_lossy().into_owned()],
"system32 holds nothing but the obstacle that failed the manifest write"
);
fs::remove_dir(&obstacle).unwrap();
// The retry installs everything fresh; nothing is reported as foreign.
let retry = stage(&shims, &sys).unwrap();
assert!(
retry.iter().all(|s| matches!(s, Staged::Copied(_))),
"{retry:?}"
);
// And a shim rebuilt later refreshes bx-cli's own copy rather than failing.
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let update = stage(&shims, &sys).unwrap();
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
}
#[test]
fn a_manifest_write_failure_restores_the_previous_bytes() {
let (_t, shims, prefix) = setup("restore");
let sys = system32_dir(&prefix);
stage(&shims, &sys).unwrap();
// Rebuild the shim, then make the manifest write fail after the rename.
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
fs::create_dir(&obstacle).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(
fs::read(sys.join("bx_runtime_veh.dll")).unwrap(),
b"veh v1",
"the replaced file must be restored to the bytes it had before the rename"
);
// The manifest still names the old copy, so the retry refreshes it rather than
// calling it foreign.
fs::remove_dir(&obstacle).unwrap();
let retry = stage(&shims, &sys).unwrap();
assert!(retry.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
}
#[test]
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
let (t, shims, prefix) = setup("visible");
@@ -867,10 +1014,15 @@ mod tests {
#[test]
fn missing_shim_is_reported_and_nothing_is_staged() {
let (t, shims, prefix) = setup("missing");
fs::remove_file(shims.join("xgameruntime.dll")).unwrap();
for name in SYSTEM32_SHIMS {
fs::remove_file(shims.join(name)).unwrap();
}
assert!(!has_system32_shims(&shims));
let sys = system32_dir(&prefix);
let expected = vec![Staged::Absent(shims.join("xgameruntime.dll"))];
let expected: Vec<Staged> = SYSTEM32_SHIMS
.iter()
.map(|name| Staged::Absent(shims.join(name)))
.collect();
assert_eq!(stage(&shims, &sys).unwrap(), expected);
assert_eq!(fs::read_dir(&sys).unwrap().count(), 0);
// With nothing to stage, a prefix without system32 is not an error either.
@@ -879,6 +1031,71 @@ mod tests {
assert!(!fresh.exists());
}
fn make_fake_wine_builtin_pe() -> Vec<u8> {
let mut pe = vec![0u8; 0x100];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3c..0x40].copy_from_slice(&(0x80u32).to_le_bytes());
pe[0x40..0x51].copy_from_slice(b"Wine builtin DLL\0");
pe[0x80..0x84].copy_from_slice(b"PE\0\0");
pe
}
#[test]
fn replaces_a_wine_builtin_stub_after_saving_a_backup() {
let (_t, shims, prefix) = setup("wine-stub");
let sys = system32_dir(&prefix);
let wine_stub = make_fake_wine_builtin_pe();
assert!(is_wine_builtin_dll(&wine_stub));
fs::write(sys.join("gameinput.dll"), &wine_stub).unwrap();
let first = stage(&shims, &sys).unwrap();
assert!(first.contains(&Staged::ReplacedWineStub(sys.join("gameinput.dll"))));
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v1");
assert_eq!(
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
wine_stub
);
let owned = read_manifest(&sys).unwrap();
assert_eq!(owned.get("gameinput.dll"), Some(&sha256_hex(b"shim v1")));
// Subsequent rebuilds refresh our owned copy while keeping the original Wine backup intact.
fs::write(shims.join("GameInput.dll"), b"shim v2").unwrap();
let second = stage(&shims, &sys).unwrap();
assert!(second.contains(&Staged::Replaced(sys.join("gameinput.dll"))));
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), b"shim v2");
assert_eq!(
fs::read(sys.join(".gameinput.dll.wine-builtin.bak")).unwrap(),
wine_stub
);
}
#[test]
fn non_wine_pe_and_symlinks_to_wine_stubs_are_still_refused() {
let (t, shims, prefix) = setup("non-wine-pe");
let sys = system32_dir(&prefix);
// A regular native PE (standard DOS stub, no "Wine builtin DLL" marker) is foreign.
let mut native_pe = make_fake_wine_builtin_pe();
native_pe[0x40..0x51].copy_from_slice(b"This program can!");
assert!(!is_wine_builtin_dll(&native_pe));
fs::write(sys.join("gameinput.dll"), &native_pe).unwrap();
assert!(stage(&shims, &sys).is_err());
assert_eq!(fs::read(sys.join("gameinput.dll")).unwrap(), native_pe);
// A symlink pointing to a real Wine builtin stub is ALSO refused (never follow links).
fs::remove_file(sys.join("gameinput.dll")).unwrap();
let wine_target = t.0.join("wine_gameinput.dll");
fs::write(&wine_target, make_fake_wine_builtin_pe()).unwrap();
std::os::unix::fs::symlink(&wine_target, sys.join("gameinput.dll")).unwrap();
let err = stage(&shims, &sys).unwrap_err();
assert!(err.contains("symbolic link"), "{err}");
assert!(
fs::symlink_metadata(sys.join("gameinput.dll"))
.unwrap()
.file_type()
.is_symlink()
);
}
#[test]
fn uninitialized_prefix_is_an_error_not_a_skip() {
let (t, shims, _prefix) = setup("uninit");
+262 -15
View File
@@ -8,7 +8,7 @@ use std::io::IsTerminal;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use std::time::{Duration, Instant};
const POLL: Duration = Duration::from_millis(50);
@@ -16,29 +16,81 @@ const POLL: Duration = Duration::from_millis(50);
const GRACE: Duration = Duration::from_secs(5);
const SERVER_WAIT: Duration = Duration::from_secs(15);
/// Signals that stop the run: the guest group is terminated and the environment cleaned up.
/// SIGQUIT (Ctrl-\) is included so it cannot kill `bx-cli` and leave the guest running (#461).
const STOP_SIGNALS: [libc::c_int; 4] = [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGQUIT];
static SIGNAL: AtomicI32 = AtomicI32::new(0);
static SUSPEND: AtomicBool = AtomicBool::new(false);
/// Total time this process has spent suspended inside [`supervise`], in nanoseconds.
static SUSPENDED_NANOS: AtomicU64 = AtomicU64::new(0);
extern "C" fn note_signal(signal: libc::c_int) {
SIGNAL.store(signal, Ordering::SeqCst);
}
/// Records SIGINT, SIGTERM and SIGHUP instead of dying, so the run can be cleaned up.
pub fn install_signal_handlers() {
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
// SAFETY: the handler only stores to an atomic, which is async-signal-safe.
unsafe {
libc::signal(
signal,
note_signal as extern "C" fn(libc::c_int) as libc::sighandler_t,
);
extern "C" fn note_suspend(_signal: libc::c_int) {
SUSPEND.store(true, Ordering::SeqCst);
}
/// Installs `handler` for `signal` unless the disposition this process inherited is `SIG_IGN`.
/// Returns whether the handler was installed.
///
/// A signal the caller chose to ignore (`nohup`, or a `&` job of a non-interactive shell) stays
/// ignored, so it cannot stop the run or the bottle (#461).
fn install_unless_ignored(signal: libc::c_int, handler: extern "C" fn(libc::c_int)) -> bool {
// SAFETY: `current` is a valid, writable sigaction; a null new action only queries. The
// handlers passed here only store to an atomic, which is async-signal-safe.
unsafe {
let mut current: libc::sigaction = std::mem::zeroed();
if libc::sigaction(signal, std::ptr::null(), &mut current) == 0
&& current.sa_sigaction == libc::SIG_IGN
{
return false;
}
libc::signal(signal, handler as libc::sighandler_t) != libc::SIG_ERR
}
}
/// Records SIGINT, SIGTERM, SIGHUP and SIGQUIT instead of dying, so the run can be cleaned up,
/// and records SIGTSTP (Ctrl-Z) so the guest group can be suspended together with `bx-cli`.
/// Signals that were inherited as ignored are left ignored.
///
/// SIGTSTP is only acted on inside [`supervise`]. A Ctrl-Z typed while nothing is being
/// supervised (for example while shims are copied) has no visible effect until the next
/// supervised phase starts, which is then suspended at once.
pub fn install_signal_handlers() {
for signal in STOP_SIGNALS {
install_unless_ignored(signal, note_signal);
}
install_unless_ignored(libc::SIGTSTP, note_suspend);
}
pub fn received_signal() -> i32 {
SIGNAL.load(Ordering::SeqCst)
}
/// Total time spent suspended (Ctrl-Z until continued) across every [`supervise`] call so far.
///
/// A caller that budgets one `--timeout` over several supervised phases subtracts this from its
/// own wall-clock measurement, so a pause during an earlier phase is not charged to a later one.
pub fn suspended_time() -> Duration {
Duration::from_nanos(SUSPENDED_NANOS.load(Ordering::SeqCst))
}
/// True once per SIGTSTP received since the last call.
fn take_suspend_request() -> bool {
SUSPEND.swap(false, Ordering::SeqCst)
}
/// Stops this process the way the terminal's Ctrl-Z would; returns when it is continued.
fn suspend_self(_guest: libc::pid_t) {
// SAFETY: raise takes no pointers. SIGSTOP cannot be caught, so this stops the process.
unsafe {
libc::raise(libc::SIGSTOP);
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Stop {
TimedOut,
@@ -52,11 +104,14 @@ pub enum Outcome {
}
impl Outcome {
/// 0 or 1 for the guest's own result, 124 for a timeout (as `timeout(1)`), 128 + N for a
/// signal.
/// The guest's own numeric exit code (so a conformance fixture's documented exit-77 skip
/// stays distinguishable from a failure, #565), 124 for a timeout (as `timeout(1)`),
/// 128 + N for a signal.
pub fn exit_code(&self) -> u8 {
match self {
Outcome::Exited(status) => u8::from(!status.success()),
// Unix guest codes are already 0-255; a signalled guest has no code, which is a
// failure. `code.max(1)` at the call sites still turns a failed cleanup into 1.
Outcome::Exited(status) => status.code().map_or(1, |code| code.clamp(0, 255) as u8),
Outcome::Stopped(Stop::TimedOut) => 124,
Outcome::Stopped(Stop::Signalled(signal)) => 128u8.saturating_add(*signal as u8),
}
@@ -85,10 +140,27 @@ fn wait_until(child: &mut Child, deadline: Instant) -> std::io::Result<Option<Ex
/// Runs `command` in a new process group until it exits, `timeout` passes, or `signal`
/// returns non-zero. On a stop the whole group is terminated before this returns.
///
/// The guest is not in the terminal's foreground group, so Ctrl-Z reaches only `bx-cli`. It is
/// passed on: the guest group gets SIGTSTP, `bx-cli` stops itself, and when `bx-cli` is continued
/// the guest group gets SIGCONT. Time spent suspended does not count against `timeout`.
pub fn supervise(
command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
) -> std::io::Result<Outcome> {
supervise_with(command, timeout, signal, take_suspend_request, suspend_self)
}
/// [`supervise`] with the suspend request and the self-stop injected, so tests can exercise the
/// job-control path without stopping the test process. `suspend` is called with the guest
/// group's id after that group was sent SIGTSTP and returns when the launcher may continue.
fn supervise_with(
mut command: Command,
timeout: Option<Duration>,
signal: impl Fn() -> i32,
suspend_requested: impl Fn() -> bool,
mut suspend: impl FnMut(libc::pid_t),
) -> std::io::Result<Outcome> {
// A background process group is stopped by SIGTTIN if it reads the terminal, so a terminal
// is replaced by end-of-file. Piped and redirected input is passed through.
@@ -97,6 +169,7 @@ pub fn supervise(
}
let mut child = command.process_group(0).spawn()?;
let started = Instant::now();
let mut suspended = Duration::ZERO;
let stop = loop {
if let Some(status) = child.try_wait()? {
return Ok(Outcome::Exited(status));
@@ -105,7 +178,20 @@ pub fn supervise(
if received != 0 {
break Stop::Signalled(received);
}
if timeout.is_some_and(|limit| started.elapsed() >= limit) {
if suspend_requested() {
let paused = Instant::now();
signal_group(&child, libc::SIGTSTP);
suspend(child.id() as libc::pid_t);
signal_group(&child, libc::SIGCONT);
let pause = paused.elapsed();
suspended += pause;
SUSPENDED_NANOS.fetch_add(
u64::try_from(pause.as_nanos()).unwrap_or(u64::MAX),
Ordering::SeqCst,
);
continue;
}
if timeout.is_some_and(|limit| started.elapsed().saturating_sub(suspended) >= limit) {
break Stop::TimedOut;
}
std::thread::sleep(POLL);
@@ -141,6 +227,10 @@ fn group_leader_running(child: &Child) -> bool {
///
/// `-k` exits 1 when no server is running (observed on CrossOver 26.3), so 1 is accepted
/// there; `-w` must still succeed, which a surviving server prevents.
///
/// Each `wineserver` runs in its own process group with no terminal input, so a second Ctrl-C
/// typed while cleanup is running reaches only `bx-cli` (which records it) and cannot kill the
/// cleanup itself (#461).
pub fn stop_server(
wineserver: &Path,
prefix: &Path,
@@ -152,8 +242,10 @@ pub fn stop_server(
.env_clear()
.envs(environment.iter().map(|(k, v)| (k, v)))
.env("WINEPREFIX", prefix)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0)
.spawn()
.map_err(|e| format!("cannot start wineserver {flag}: {e}"))?;
match wait_until(&mut child, Instant::now() + SERVER_WAIT) {
@@ -191,7 +283,11 @@ mod tests {
let ok = supervise(shell("exit 0"), None, || 0).unwrap();
assert_eq!(ok.exit_code(), 0);
let failed = supervise(shell("exit 7"), Some(Duration::from_secs(10)), || 0).unwrap();
assert_eq!(failed.exit_code(), 1);
assert_eq!(failed.exit_code(), 7);
// A conformance fixture's documented skip must stay distinguishable from a failure
// through `bx-cli run` (#565); the old `!status.success()` collapsed it to 1.
let skipped = supervise(shell("exit 77"), Some(Duration::from_secs(10)), || 0).unwrap();
assert_eq!(skipped.exit_code(), 77);
let slow = supervise(shell("sleep 30"), Some(Duration::from_millis(200)), || 0).unwrap();
assert!(matches!(slow, Outcome::Stopped(Stop::TimedOut)));
assert_eq!(slow.exit_code(), 124);
@@ -222,6 +318,157 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// Signal dispositions and the recorded signal are process-wide: tests that touch them run
/// one at a time and use signals no other test raises.
static SIGNAL_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn set_disposition(signal: libc::c_int, action: libc::sighandler_t) {
// SAFETY: SIG_DFL and SIG_IGN are valid dispositions for these signals.
unsafe {
libc::signal(signal, action);
}
}
fn disposition(signal: libc::c_int) -> libc::sighandler_t {
// SAFETY: a null new action only queries; `current` is valid and writable.
unsafe {
let mut current: libc::sigaction = std::mem::zeroed();
assert_eq!(libc::sigaction(signal, std::ptr::null(), &mut current), 0);
current.sa_sigaction
}
}
fn raise(signal: libc::c_int) {
// SAFETY: raise takes no pointers.
unsafe {
libc::raise(signal);
}
}
#[test]
fn an_inherited_ignored_signal_stays_ignored() {
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
// As under nohup: the signal arrives already ignored.
set_disposition(libc::SIGUSR2, libc::SIG_IGN);
SIGNAL.store(0, Ordering::SeqCst);
assert!(!install_unless_ignored(libc::SIGUSR2, note_signal));
assert_eq!(disposition(libc::SIGUSR2), libc::SIG_IGN);
raise(libc::SIGUSR2);
assert_eq!(
received_signal(),
0,
"an ignored signal must not stop the run"
);
// Control: the same signal with the default disposition is recorded.
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
assert!(install_unless_ignored(libc::SIGUSR2, note_signal));
raise(libc::SIGUSR2);
assert_eq!(received_signal(), libc::SIGUSR2);
set_disposition(libc::SIGUSR2, libc::SIG_DFL);
SIGNAL.store(0, Ordering::SeqCst);
}
#[test]
fn sigquit_is_recorded_and_stops_the_guest_group() {
let _guard = SIGNAL_TESTS.lock().unwrap_or_else(|e| e.into_inner());
assert!(STOP_SIGNALS.contains(&libc::SIGQUIT));
let before = disposition(libc::SIGQUIT);
set_disposition(libc::SIGQUIT, libc::SIG_DFL);
SIGNAL.store(0, Ordering::SeqCst);
assert!(install_unless_ignored(libc::SIGQUIT, note_signal));
// Without the handler this would kill the test process, as it killed bx-cli.
raise(libc::SIGQUIT);
assert_eq!(received_signal(), libc::SIGQUIT);
set_disposition(libc::SIGQUIT, before);
SIGNAL.store(0, Ordering::SeqCst);
let stopped = supervise(shell("sleep 30"), None, || libc::SIGQUIT).unwrap();
assert!(matches!(
stopped,
Outcome::Stopped(Stop::Signalled(libc::SIGQUIT))
));
assert_eq!(stopped.exit_code(), 128 + libc::SIGQUIT as u8);
}
/// True once `pid` is reported stopped; leaves the status in place.
fn is_stopped(pid: libc::pid_t) -> bool {
(0..100).any(|_| {
// SAFETY: `info` is valid and writable; WNOWAIT leaves the child's state in place.
let stopped = unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WSTOPPED | libc::WNOHANG | libc::WNOWAIT,
) == 0
&& info.si_pid() == pid
};
if !stopped {
std::thread::sleep(POLL);
}
stopped
})
}
#[test]
fn a_suspend_request_stops_and_resumes_the_guest_without_using_up_the_timeout() {
let requested = std::cell::Cell::new(false);
let guest_was_stopped = std::cell::Cell::new(false);
let suspended_before = suspended_time();
let outcome = supervise_with(
shell("sleep 0.4; exit 0"),
// Shorter than the suspension below: only running time may count.
Some(Duration::from_millis(1500)),
|| 0,
|| !requested.replace(true),
|guest| {
guest_was_stopped.set(is_stopped(guest));
std::thread::sleep(Duration::from_millis(2000));
},
)
.unwrap();
assert!(guest_was_stopped.get(), "the guest group was not stopped");
// The pause is also reported to callers that budget a timeout across several phases.
let reported = suspended_time() - suspended_before;
assert!(reported >= Duration::from_millis(2000), "{reported:?}");
match outcome {
Outcome::Exited(status) => assert!(status.success(), "{status}"),
other => panic!("the resumed guest should have finished on its own: {other:?}"),
}
}
#[test]
fn cleanup_runs_outside_the_callers_process_group() {
let dir = scratch("cleanup-group");
let server = dir.join("wineserver");
let seen = dir.join("pgid");
std::fs::write(
&server,
format!(
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
seen.display()
),
)
.unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_server(&server, &dir, &[]).unwrap();
// SAFETY: getpgrp takes no arguments and cannot fail.
let ours = unsafe { libc::getpgrp() };
let groups: Vec<libc::pid_t> = std::fs::read_to_string(&seen)
.unwrap()
.lines()
.map(|line| line.trim().parse().unwrap())
.collect();
assert_eq!(groups.len(), 2, "-k and -w should both have run");
for group in groups {
// A terminal signal goes to the foreground group, which these are not part of.
assert_ne!(group, ours, "cleanup shares the caller's process group");
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn an_idle_server_is_accepted_only_when_the_wait_succeeds() {
let dir = scratch("server");
+43
View File
@@ -0,0 +1,43 @@
//! Runs the built `bx-cli` binary to check what `main` prints and returns for the
//! usage paths (#532). The unit tests cover `Dispatch::classify`; these cover the
//! mapping from that classification to the real exit code and output stream.
use std::process::Command;
fn run(args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_bx-cli"))
.args(args)
.env_clear()
.output()
.expect("bx-cli must start")
}
#[test]
fn help_prints_usage_on_stdout_and_succeeds() {
for flag in ["--help", "-h", "help"] {
let out = run(&[flag]);
assert!(out.status.success(), "{flag}: {:?}", out.status);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("bx-cli run --exe"),
"{flag}: usage on stdout: {stdout}"
);
assert!(out.stderr.is_empty(), "{flag}: nothing on stderr");
}
}
#[test]
fn a_bare_invocation_is_a_usage_error_on_stderr() {
let out = run(&[]);
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "nothing on stdout");
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
}
#[test]
fn an_unknown_subcommand_is_a_usage_error_on_stderr() {
let out = run(&["frobnicate"]);
assert_eq!(out.status.code(), Some(1));
assert!(out.stdout.is_empty(), "nothing on stdout");
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
}
+349 -11
View File
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
}
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PeSummary {
pub image_base: u64,
pub size_of_image: u32,
@@ -128,12 +128,21 @@ struct Section {
}
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
}
/// Map an RVA to a file offset and report how many raw bytes remain in that
/// section from the mapped offset. The bound lets callers walk a table without
/// leaving the section that contains it.
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
for s in sections {
let span = s.vsize.max(s.raw_size);
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
let delta = rva - s.vaddr;
if delta < s.raw_size {
return Some((s.raw_ptr + delta) as usize);
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
return Some((off, remaining));
}
}
}
@@ -167,8 +176,36 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
let mut sections = Vec::with_capacity(section_count as usize);
// The import data directory is entry index 1, an 8-byte RVA/size pair at
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
// validated while the optional header is read: a short optional header must
// not let the read fall through into the section table.
const IMPORT_DIR_INDEX: u32 = 1;
const IMPORT_DIR_OFF: usize = 112 + 8;
let mut import_dir: Option<(u32, u32)> = None;
if num_rvas > IMPORT_DIR_INDEX {
let entry = bytes
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
if IMPORT_DIR_OFF + 8 > opt_size {
return Err(ProbeError::NotPe32Plus(
"import directory outside SizeOfOptionalHeader",
));
}
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
import_dir = Some((rva, size));
}
let sec_base = opt + opt_size;
let section_table_size = (section_count as usize)
.checked_mul(40)
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
bytes
.get(sec_base..sec_base + section_table_size)
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
let mut sections = Vec::with_capacity(section_count as usize);
for i in 0..section_count as usize {
let so = sec_base + i * 40;
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
@@ -184,16 +221,22 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
}
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
if num_rvas > 1 {
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
if let Some((imp_rva, imp_size)) = import_dir {
if imp_rva != 0
&& let Some(mut desc_off) = rva_to_off(&sections, imp_rva)
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(&sections, imp_rva)
{
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) {
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
// declared directory Size and the section's raw bytes, whichever
// ends first, so descriptors past the directory are not reported.
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
while desc_bytes_left >= 20 {
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
u32_le(bytes, desc_off),
u32_le(bytes, desc_off + 12),
u32_le(bytes, desc_off + 16),
) else {
break;
};
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
break;
}
@@ -225,6 +268,7 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
imports.entry(dll).or_default().extend(syms);
}
desc_off += 20;
desc_bytes_left -= 20;
}
}
}
@@ -242,6 +286,129 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
mod tests {
use super::*;
const PE_OFF: usize = 0x80;
const COFF: usize = PE_OFF + 4;
const OPT: usize = COFF + 20;
const OPT_SIZE: usize = 0xF0;
const SEC: usize = OPT + OPT_SIZE;
const SECTION_RVA: u32 = 0x1000;
const RAW_PTR: u32 = 0x200;
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
}
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
}
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
}
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
put_u32(bytes, base + 8, raw_size);
put_u32(bytes, base + 12, rva);
put_u32(bytes, base + 16, raw_size);
put_u32(bytes, base + 20, raw_ptr);
}
fn minimal_pe32_plus() -> Vec<u8> {
let mut bytes = vec![0u8; 0x400];
bytes[0..2].copy_from_slice(b"MZ");
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
put_u16(&mut bytes, COFF, 0x8664);
put_u16(&mut bytes, COFF + 2, 1);
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
put_u16(&mut bytes, OPT, 0x020B);
put_u32(&mut bytes, OPT + 16, 0x1234);
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
put_u32(&mut bytes, OPT + 56, 0x2000);
put_u32(&mut bytes, OPT + 108, 16);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
bytes
}
fn two_import_pe32_plus() -> Vec<u8> {
let mut bytes = minimal_pe32_plus();
let import_rva = SECTION_RVA;
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
// Two descriptors followed by the required all-zero terminator.
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
put_u64(
&mut bytes,
RAW_PTR as usize + 0x80,
u64::from(SECTION_RVA + 0x60),
);
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
bytes
}
/// Two sections: an import-descriptor section holding exactly two
/// descriptors and no terminator, and a data section for names and thunks.
/// Ellipsis bytes just past the descriptor section spell a third valid
/// descriptor, so an unbounded walk reports a DLL that is not imported.
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
const DATA_PTR: u32 = 0x300;
let mut bytes = minimal_pe32_plus();
put_u16(&mut bytes, COFF + 2, 2);
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
// Declare the directory to cover the whole descriptor section, so the
// section bound (not the Size) is what this fixture exercises.
put_u32(&mut bytes, OPT + 112 + 12, 40);
for (base, dll_rva, thunk_rva) in [
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
] {
put_u32(&mut bytes, base, thunk_rva);
put_u32(&mut bytes, base + 12, dll_rva);
put_u32(&mut bytes, base + 16, thunk_rva);
}
// A third, entirely valid descriptor just past the section boundary.
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
for (delta, name) in [
(0x00, &b"ONE.DLL\0"[..]),
(0x20, &b"TWO.DLL\0"[..]),
(0x40, &b"THREE.DLL\0"[..]),
] {
let off = DATA_PTR as usize + delta;
bytes[off..off + name.len()].copy_from_slice(name);
}
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
let off = DATA_PTR as usize + delta;
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
put_u64(&mut bytes, off + 8, 0);
}
bytes
}
#[test]
fn classifies_tracks_accurately() {
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
@@ -263,4 +430,175 @@ mod tests {
);
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
}
#[test]
fn parses_minimal_pe32_plus_without_imports() {
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
assert_eq!(summary.entry_point_rva, 0x1234);
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
assert_eq!(summary.size_of_image, 0x2000);
assert_eq!(summary.section_count, 1);
assert!(summary.imports.is_empty());
}
#[test]
fn parses_named_and_ordinal_imports_from_two_dlls() {
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
#[test]
fn rejects_truncation_at_every_header_boundary() {
let image = minimal_pe32_plus();
for len in 0..=0x100 {
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
}
}
#[test]
fn rejects_section_rva_mapping_that_would_wrap_u32() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
put_u32(&mut image, SEC + 20, u32::MAX);
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
assert!(result.is_ok(), "raw pointer addition panicked");
assert!(result.unwrap().unwrap().imports.is_empty());
}
#[test]
fn rejects_section_count_larger_than_file() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, COFF + 2, u16::MAX);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated section table")
);
}
#[test]
fn rejects_pe32_magic() {
let mut image = minimal_pe32_plus();
put_u16(&mut image, OPT, 0x010B);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
);
}
#[test]
fn import_directory_outside_all_sections_is_safe() {
let mut image = minimal_pe32_plus();
put_u32(&mut image, OPT + 112 + 8, 0x8000);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
#[test]
fn rejects_truncated_import_directory() {
let mut image = minimal_pe32_plus();
// An empty section table that fits, an optional header long enough to
// declare the import entry, and a file cut after two of the entry's
// RVA bytes.
put_u16(&mut image, COFF + 2, 0);
put_u16(&mut image, COFF + 16, 0xE0);
image.truncate(OPT + 112 + 8 + 2);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("truncated import directory")
);
}
#[test]
fn bounds_unterminated_import_descriptor_walk() {
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
}
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
/// past the end of the optional header, so its 8 bytes would otherwise be
/// read from the section table. The entry index is still within
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
#[test]
fn rejects_import_directory_outside_short_optional_header() {
let mut image = two_import_pe32_plus();
// Import entry spans optional-header offsets 120..128; declare the
// optional header to end at 120, inside the entry.
put_u16(&mut image, COFF + 16, 120);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// One byte short of the full 8-byte entry is still out of range.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 127);
assert_eq!(
probe_pe32_plus(&image).unwrap_err(),
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
);
// Exactly 128 bytes covers the whole entry, so the import directory is
// read normally. The section table now starts at OPT + 128, so write it
// there for this size.
let mut image = two_import_pe32_plus();
put_u16(&mut image, COFF + 16, 128);
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.contains_key("ALPHA.DLL"));
assert!(summary.imports.contains_key("BETA.DLL"));
}
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
/// import entry (index 1) must not be probed even though its bytes are
/// present and inside SizeOfOptionalHeader.
#[test]
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
let mut image = two_import_pe32_plus();
put_u32(&mut image, OPT + 108, 1);
let summary = probe_pe32_plus(&image).unwrap();
assert!(summary.imports.is_empty());
}
/// (b) The declared import directory Size is shorter than the containing
/// section, so descriptors past the declared size must not be reported even
/// though they are valid and inside the section's raw bytes.
#[test]
fn bounds_import_descriptor_walk_by_declared_directory_size() {
// Size 40 covers exactly the two real descriptors; the third valid
// descriptor at +40 lies outside the directory but inside the section.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 40);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
]);
assert_eq!(summary.imports, expected);
assert!(!summary.imports.contains_key("THREE.DLL"));
// Size 20 reports only the first descriptor.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 20);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
// A size that is not a multiple of 20 stops before the next descriptor
// would exceed the directory.
let mut image = import_table_without_terminator_pe32_plus();
put_u32(&mut image, OPT + 112 + 12, 39);
let summary = probe_pe32_plus(&image).unwrap();
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
assert_eq!(summary.imports, expected);
}
}
+751 -5
View File
@@ -6,6 +6,8 @@
use std::collections::BTreeMap;
pub mod report;
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TraceSummary {
pub total_lines: usize,
@@ -13,10 +15,168 @@ pub struct TraceSummary {
pub clwb_events: usize,
/// Highest cumulative counter in the sampled CLWB records, if available.
pub clwb_trap_lower_bound: Option<u64>,
/// Sampled `<kind>_trapped` records for the other AMD-only instructions the
/// VEH emulates (`clzero`, `monitorx`, `mwaitx`, `rdpru`, `extrq`, `insertq`).
pub amd_traps: BTreeMap<String, TrapCount>,
pub adx_errors: usize,
pub unhandled_exceptions: Vec<UnhandledException>,
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
pub breakpoint_exceptions: Vec<BreakpointException>,
pub unimpl_apis: BTreeMap<String, usize>,
pub unimpl_vtables: BTreeMap<String, usize>,
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
pub shader_gate: ShaderGateSummary,
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
pub shader_gaps: Vec<ShaderGap>,
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
pub shader_gap_groups: Vec<ShaderGapGroup>,
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
/// they are grouped under `unknown`. Counted here so the group counts reconcile
/// with [`TraceSummary::shader_gaps`].
pub shader_gaps_missing_identity: usize,
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
/// value for one). Counted here rather than dropped or assumed.
pub shader_gaps_missing_constraints: usize,
/// `shader_bridge_missing` messages, in log order.
pub shader_bridge_missing: Vec<String>,
}
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapGroup {
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
/// `unknown`).
pub pso: Option<String>,
/// The emitted `stage=` value, or `None` when the record carried none.
pub stage: Option<String>,
/// How many gap records this `(pso, stage)` pair covers.
pub count: usize,
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
/// first-seen order. Two pipelines of the same kind and stage can need different
/// wave widths or atomic features, so a group keeps each constraint set rather than
/// reporting only the first and losing the rest.
pub variants: Vec<ShaderGapVariant>,
}
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGapVariant {
pub wave_lanes_min: Option<String>,
pub atomic64_flags: Option<String>,
/// How many records in the group carried exactly these constraints.
pub count: usize,
}
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
/// their emitted string so unknown values are counted rather than dropped.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGateSummary {
pub total: usize,
/// Gate records whose `detail` could not be parsed as `key=value` pairs.
pub unparsed: usize,
/// Parsed gate records that carry no `decision` field, so they appear in no
/// `decisions` bucket. Counted here so the decision counts can be
/// reconciled against `total` (#497 review). `kind` is legitimately absent
/// on unclassified records and is not counted here.
pub missing_decision: usize,
pub decisions: BTreeMap<String, usize>,
pub kinds: BTreeMap<String, usize>,
pub stages: BTreeMap<String, usize>,
/// Individual gate records, in log order.
pub records: Vec<ShaderGateRecord>,
}
/// One `shader_gate` record. Fields absent from the emitted `detail` (for
/// example on unclassified records) are `None`; `atomic64` may be `Some("")`.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGateRecord {
pub pso: Option<String>,
pub stage: Option<String>,
pub decision: Option<String>,
pub hr: Option<String>,
pub kind: Option<String>,
pub shader_stage: Option<String>,
pub sm: Option<String>,
pub bytes: Option<String>,
pub dxil: Option<String>,
pub accc: Option<String>,
pub sfi0: Option<String>,
pub wave_ops: Option<String>,
pub int64_ops: Option<String>,
pub atomic64: Option<String>,
pub wave_lanes: Option<String>,
}
/// One `shader_d3dmetal_gap` record.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct ShaderGap {
pub pso: Option<String>,
pub stage: Option<String>,
pub wave_lanes_min: Option<String>,
pub atomic64_flags: Option<String>,
}
/// Tokenize a `detail` string of space-separated `key=value` pairs.
///
/// Only the `shader_d3dmetal_gap` record appends free text after its pairs
/// (`... atomic64_flags=0x400000: D3DMetal ...`), so `stop_at_free_text`
/// selects how a token without `=` is treated:
///
/// - `true` (gap records): the token ends the key=value section.
/// - `false` (`shader_gate` records): a stray token is skipped and parsing
/// continues, so one unexpected word cannot silently drop every later
/// field (#497 review).
///
/// Values never contain spaces, so `atomic64=` followed by a space yields an
/// empty value.
/// Splits a log detail string into `key=value` pairs.
///
/// `stop_at_free_text` exists for records that end with prose after their
/// fields (`shader_d3dmetal_gap` ends in a sentence), where the first token
/// without `=` marks the end of the structured part.
///
/// For `shader_gate` the whole string is structured, so a token without `=`
/// is skipped rather than treated as the end. Stopping there would silently
/// drop every later field while the record still counted as parsed: with
/// `atomic64=typed, raw, wave_lanes=64-64`, a `break` loses `wave_lanes`,
/// whereas a `continue` keeps it. The emitter writes no spaces inside a value
/// today, so this is robustness against a future value containing one, not a
/// fix for current output.
fn parse_key_values(detail: &str, stop_at_free_text: bool) -> Vec<(&str, &str)> {
let mut pairs = Vec::new();
for token in detail.split_ascii_whitespace() {
match token.split_once('=') {
Some((key, value)) if !key.is_empty() => pairs.push((key, value)),
_ if stop_at_free_text => break,
_ => continue,
}
}
pairs
}
/// Sampled trap records of one instruction kind.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TrapCount {
pub events: usize,
/// Highest cumulative counter in the sampled records, if available.
pub lower_bound: Option<u64>,
}
const AMD_TRAP_EVENTS: [(&str, &str); 6] = [
("clzero_trapped", "clzero"),
("monitorx_trapped", "monitorx"),
("mwaitx_trapped", "mwaitx"),
("rdpru_trapped", "rdpru"),
("extrq_trapped", "extrq"),
("insertq_trapped", "insertq"),
];
fn sampled_counter(detail: &str) -> Option<u64> {
detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok())
}
#[derive(Debug, PartialEq, Eq)]
@@ -27,6 +187,30 @@ pub struct UnhandledException {
pub rip: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
pub struct BreakpointException {
pub exception_code: Option<String>,
pub module: Option<String>,
pub module_base: Option<String>,
pub rva: Option<String>,
/// The faulting address, which locates a breakpoint outside any image (module `?`).
pub address: Option<String>,
/// 1-based index of this record and the per-process cap, so a reader can tell a run
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
pub record: Option<u32>,
pub limit: Option<u32>,
}
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
let needle = format!("\"{key}\":");
let start = line.find(&needle)? + needle.len();
let digits: &str = &line[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
@@ -35,6 +219,124 @@ fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
Some(&rest[..end])
}
fn get_field<'a>(pairs: &[(&'a str, &'a str)], key: &str) -> Option<String> {
pairs
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| (*v).to_owned())
}
fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
let gate = &mut summary.shader_gate;
gate.total += 1;
let pairs = parse_key_values(detail, false);
if pairs.is_empty() {
gate.unparsed += 1;
return;
}
let record = ShaderGateRecord {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
decision: get_field(&pairs, "decision"),
hr: get_field(&pairs, "hr"),
kind: get_field(&pairs, "kind"),
shader_stage: get_field(&pairs, "shader_stage"),
sm: get_field(&pairs, "sm"),
bytes: get_field(&pairs, "bytes"),
dxil: get_field(&pairs, "dxil"),
accc: get_field(&pairs, "accc"),
sfi0: get_field(&pairs, "sfi0"),
wave_ops: get_field(&pairs, "wave_ops"),
int64_ops: get_field(&pairs, "int64_ops"),
atomic64: get_field(&pairs, "atomic64"),
wave_lanes: get_field(&pairs, "wave_lanes"),
};
match &record.decision {
Some(decision) => *gate.decisions.entry(decision.clone()).or_insert(0) += 1,
None => gate.missing_decision += 1,
}
if let Some(kind) = &record.kind {
*gate.kinds.entry(kind.clone()).or_insert(0) += 1;
}
if let Some(stage) = &record.stage {
*gate.stages.entry(stage.clone()).or_insert(0) += 1;
}
gate.records.push(record);
}
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
/// always writes a value, so an empty one means the record is malformed, not that the
/// pipeline is named "".
fn non_empty(value: Option<String>) -> Option<String> {
value.filter(|v| !v.is_empty())
}
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
///
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
let pso = non_empty(gap.pso.clone());
let stage = non_empty(gap.stage.clone());
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
if pso.is_none() || stage.is_none() {
groups.shader_gaps_missing_identity += 1;
}
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
groups.shader_gaps_missing_constraints += 1;
}
// The group list is small (one entry per affected pipeline stage), so a linear scan
// keeps first-seen order without a second index to keep in sync.
let group_index = match groups
.shader_gap_groups
.iter()
.position(|g| g.pso == pso && g.stage == stage)
{
Some(index) => index,
None => {
groups.shader_gap_groups.push(ShaderGapGroup {
pso,
stage,
count: 0,
variants: Vec::new(),
});
groups.shader_gap_groups.len() - 1
}
};
let group = &mut groups.shader_gap_groups[group_index];
group.count += 1;
match group
.variants
.iter()
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
{
Some(index) => group.variants[index].count += 1,
None => group.variants.push(ShaderGapVariant {
wave_lanes_min,
atomic64_flags,
count: 1,
}),
}
}
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
let pairs = parse_key_values(detail, true);
// The emitter appends `: D3DMetal creates such pipelines ...` directly
// after the flags value, so strip the trailing colon.
let atomic64_flags = get_field(&pairs, "atomic64_flags")
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
let gap = ShaderGap {
pso: get_field(&pairs, "pso"),
stage: get_field(&pairs, "stage"),
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
atomic64_flags,
};
record_shader_gap_group(summary, &gap);
summary.shader_gaps.push(gap);
}
pub fn summarize_jsonl(input: &str) -> TraceSummary {
let mut summary = TraceSummary::default();
for line in input.lines() {
@@ -48,11 +350,19 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
match event {
"clwb_trapped" => {
summary.clwb_events += 1;
let sample = detail
.split_ascii_whitespace()
.find_map(|field| field.strip_prefix("total_traps="))
.and_then(|count| count.parse::<u64>().ok());
summary.clwb_trap_lower_bound = summary.clwb_trap_lower_bound.max(sample);
summary.clwb_trap_lower_bound =
summary.clwb_trap_lower_bound.max(sampled_counter(detail));
}
_ if AMD_TRAP_EVENTS.iter().any(|(e, _)| *e == event) => {
let name = AMD_TRAP_EVENTS.iter().find(|(e, _)| *e == event).unwrap().1;
let entry = summary.amd_traps.entry(name.to_string()).or_default();
entry.events += 1;
entry.lower_bound = entry.lower_bound.max(sampled_counter(detail));
}
"shader_gate" => record_shader_gate(&mut summary, detail),
"shader_d3dmetal_gap" => record_shader_gap(&mut summary, detail),
"shader_bridge_missing" => {
summary.shader_bridge_missing.push(detail.to_owned());
}
"adx_illegal_instruction" => summary.adx_errors += 1,
"unhandled_exception" => {
@@ -63,6 +373,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
});
}
"breakpoint_exception" => {
summary.breakpoint_exceptions.push(BreakpointException {
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
module: extract_json_str(trimmed, "module").map(str::to_owned),
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
address: extract_json_str(trimmed, "address").map(str::to_owned),
record: extract_json_u32(trimmed, "record"),
limit: extract_json_u32(trimmed, "limit"),
});
}
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
"unimpl_vtable" => {
*summary
@@ -139,6 +460,39 @@ mod tests {
assert_eq!(summary.clwb_trap_lower_bound, None);
}
#[test]
fn collects_breakpoint_exceptions_in_log_order() {
let log = r#"
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
"#;
let summary = summarize_jsonl(log);
assert!(summary.unhandled_exceptions.is_empty());
assert_eq!(
summary.breakpoint_exceptions,
[
BreakpointException {
exception_code: Some("0x80000003".into()),
module: Some("title.exe".into()),
module_base: Some("0x0000000140000000".into()),
rva: Some("0x0000000002236178".into()),
address: Some("0x0000000142236178".into()),
record: Some(1),
limit: Some(16),
},
BreakpointException {
exception_code: Some("0xc0000420".into()),
module: Some("?".into()),
module_base: Some("0x0000000000000000".into()),
rva: Some("0x0000000000000000".into()),
address: Some("0x0000000000410000".into()),
record: Some(2),
limit: Some(16),
},
]
);
}
#[test]
fn collects_unhandled_exceptions_in_log_order() {
let log = r#"
@@ -165,4 +519,396 @@ mod tests {
]
);
}
#[test]
fn counts_amd_only_traps_per_kind() {
let summary = summarize_jsonl(
r#"{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=1"}
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=2"}
{"event":"clzero_trapped","detail":"rip=0x1000 len=3 total_traps=4"}
{"event":"extrq_trapped","detail":"rip=0x2000 len=5 total_traps=1"}
{"event":"rdpru_trapped","detail":"rip=0x3000 len=3"}"#,
);
assert_eq!(
summary.amd_traps["clzero"],
TrapCount {
events: 3,
lower_bound: Some(4)
}
);
assert_eq!(
summary.amd_traps["extrq"],
TrapCount {
events: 1,
lower_bound: Some(1)
}
);
assert_eq!(
summary.amd_traps["rdpru"],
TrapCount {
events: 1,
lower_bound: None
}
);
assert!(!summary.amd_traps.contains_key("mwaitx"));
assert_eq!(summary.clwb_events, 0);
}
#[test]
fn summarizes_full_pass_dxil_gate_record() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.unparsed, 0);
assert_eq!(summary.shader_gate.decisions["pass_dxil"], 1);
assert_eq!(summary.shader_gate.kinds["dxil"], 1);
assert_eq!(summary.shader_gate.stages["CS"], 1);
assert_eq!(summary.shader_gate.records.len(), 1);
let r = &summary.shader_gate.records[0];
assert_eq!(r.pso.as_deref(), Some("compute"));
assert_eq!(r.stage.as_deref(), Some("CS"));
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
assert_eq!(r.hr.as_deref(), Some("0x00000000"));
assert_eq!(r.kind.as_deref(), Some("dxil"));
assert_eq!(r.shader_stage.as_deref(), Some("5"));
assert_eq!(r.sm.as_deref(), Some("6.6"));
assert_eq!(r.bytes.as_deref(), Some("1234"));
assert_eq!(r.dxil.as_deref(), Some("800"));
assert_eq!(r.accc.as_deref(), Some("0"));
assert_eq!(r.sfi0.as_deref(), Some("0x4000"));
assert_eq!(r.wave_ops.as_deref(), Some("1"));
assert_eq!(r.int64_ops.as_deref(), Some("0"));
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
}
#[test]
fn summarizes_reject_accc_only_gate_record() {
let log = r#"{"ts_ms":12,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_gate","detail":"pso=graphics stage=VS decision=reject_accc_only hr=0x80004001 kind=accc_only shader_stage=0 sm=6.0 bytes=2048 dxil=0 accc=512 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=none"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.decisions["reject_accc_only"], 1);
assert_eq!(summary.shader_gate.kinds["accc_only"], 1);
assert_eq!(summary.shader_gate.stages["VS"], 1);
let r = &summary.shader_gate.records[0];
assert_eq!(r.hr.as_deref(), Some("0x80004001"));
assert_eq!(r.sm.as_deref(), Some("6.0"));
assert_eq!(r.accc.as_deref(), Some("512"));
assert_eq!(r.atomic64.as_deref(), Some(""));
assert_eq!(r.wave_lanes.as_deref(), Some("none"));
}
#[test]
fn summarizes_unclassified_gate_record_without_kind() {
let log = r#"{"ts_ms":14,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_unclassified hr=0x00000000 bytes=4096"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.decisions["pass_unclassified"], 1);
assert_eq!(summary.shader_gate.stages["CS"], 1);
assert!(summary.shader_gate.kinds.is_empty());
let r = &summary.shader_gate.records[0];
assert_eq!(r.bytes.as_deref(), Some("4096"));
assert_eq!(r.kind, None);
assert_eq!(r.sm, None);
assert_eq!(r.dxil, None);
assert_eq!(r.atomic64, None);
assert_eq!(r.wave_lanes, None);
}
#[test]
fn summarizes_d3dmetal_gap_with_free_text_suffix() {
let log = r#"{"ts_ms":16,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gaps.len(), 1);
let gap = &summary.shader_gaps[0];
assert_eq!(gap.pso.as_deref(), Some("compute"));
assert_eq!(gap.stage.as_deref(), Some("CS"));
assert_eq!(gap.wave_lanes_min.as_deref(), Some("64"));
assert_eq!(gap.atomic64_flags.as_deref(), Some("0x400000"));
}
#[test]
fn collects_shader_bridge_missing_messages() {
let log = r#"{"ts_ms":18,"tid":1,"level":"WARN","sub":"d3d12_xs","event":"shader_bridge_missing","detail":"bx_shader_bridge.dll not found beside d3d12_xs.dll; shaders pass unclassified, ACCC-only refused"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_bridge_missing.len(), 1);
assert!(summary.shader_bridge_missing[0].contains("not found beside d3d12_xs.dll"));
}
#[test]
fn malformed_shader_gate_detail_is_counted_not_dropped() {
for detail in ["", "garbage", "=value", " "] {
let log = format!(
"{{\"ts_ms\":20,\"tid\":1,\"level\":\"INFO\",\"sub\":\"d3d12_xs\",\"event\":\"shader_gate\",\"detail\":\"{detail}\"}}"
);
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gate.total, 1, "detail={detail:?}");
assert_eq!(summary.shader_gate.unparsed, 1, "detail={detail:?}");
assert!(summary.shader_gate.records.is_empty(), "detail={detail:?}");
}
}
#[test]
fn empty_atomic64_value_is_preserved() {
let log = r#"{"ts_ms":22,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=100 dxil=64 accc=0 sfi0=0x0 wave_ops=0 int64_ops=0 atomic64= wave_lanes=0-4294967295"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.atomic64.as_deref(), Some(""));
assert_eq!(r.wave_lanes.as_deref(), Some("0-4294967295"));
}
#[test]
fn a_stray_token_does_not_drop_later_gate_fields() {
// #497 review point 1: one value containing a space must not turn every
// later field into None.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil atomic64=typed, raw wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.decision.as_deref(), Some("pass_dxil"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
assert_eq!(summary.shader_gate.unparsed, 0);
}
#[test]
fn two_atomic64_flags_are_parsed() {
// #497 review point 1: the emitter concatenates flags with no separator,
// but two flags must round-trip if they ever are spaced.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil kind=dxil atomic64=typed, groupshared, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
let r = &summary.shader_gate.records[0];
assert_eq!(r.atomic64.as_deref(), Some("typed,"));
assert_eq!(r.wave_lanes.as_deref(), Some("64-64"));
}
#[test]
fn a_gate_record_without_a_decision_is_counted_as_missing() {
// #497 review point 2: decision counts must reconcile against total.
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert_eq!(summary.shader_gate.missing_decision, 1);
assert_eq!(summary.shader_gate.unparsed, 0);
assert!(summary.shader_gate.decisions.is_empty());
assert_eq!(summary.shader_gate.stages["CS"], 1);
}
#[test]
fn decision_buckets_plus_missing_reconcile_with_total() {
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil bytes=1"}
{"event":"shader_gate","detail":"pso=compute stage=CS"}
{"event":"shader_gate","detail":"garbage"}"#;
let summary = summarize_jsonl(log);
let gate = &summary.shader_gate;
let bucketed: usize = gate.decisions.values().sum();
assert_eq!(gate.total, 3);
assert_eq!(gate.unparsed, 1);
assert_eq!(gate.missing_decision, 1);
assert_eq!(bucketed + gate.unparsed + gate.missing_decision, gate.total);
}
#[test]
fn unknown_decisions_and_kinds_are_counted() {
let log = r#"{"event":"shader_gate","detail":"pso=compute stage=CS decision=some_future_decision hr=0x00000000 kind=some_future_kind bytes=1"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.decisions["some_future_decision"], 1);
assert_eq!(summary.shader_gate.kinds["some_future_kind"], 1);
}
/// A stray token must not end the structured part of a `shader_gate`
/// record: if it did, every later field would silently become `None`
/// while the record still counted as parsed.
#[test]
fn a_record_without_a_decision_is_counted_as_missing() {
let mut summary = TraceSummary::default();
record_shader_gate(&mut summary, "pso=graphics stage=pixel");
let gate = &summary.shader_gate;
assert_eq!(gate.total, 1);
assert_eq!(gate.unparsed, 0);
assert_eq!(gate.missing_decision, 1);
assert!(gate.decisions.is_empty());
}
/// The free-text path is the opposite: `shader_d3dmetal_gap` ends in a
/// sentence, so the first token without `=` ends the structured part.
#[test]
fn free_text_ends_the_structured_part_of_a_gap_record() {
let pairs = parse_key_values("pso=graphics stage=pixel and then some prose", true);
assert_eq!(pairs.len(), 2);
assert_eq!(pairs[1], ("stage", "pixel"));
}
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
/// with its own wave width and 64-bit-atomic flags.
#[test]
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
// Same pso, different stages: grouping on pso alone would collapse these, so the
// test discriminates the (pso, stage) key rather than only the pso.
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
assert_eq!(summary.shader_gap_groups.len(), 3);
let first = &summary.shader_gap_groups[0];
assert_eq!(first.pso.as_deref(), Some("graphics"));
assert_eq!(first.stage.as_deref(), Some("VS"));
assert_eq!(first.count, 1);
assert_eq!(
first.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 1,
}]
);
let second = &summary.shader_gap_groups[1];
assert_eq!(second.pso.as_deref(), Some("compute"));
assert_eq!(second.stage.as_deref(), Some("CS"));
assert_eq!(second.count, 1);
// A second stage of the *same* pso stays its own group, which is what separates a
// (pso, stage) key from a pso-only key.
let third = &summary.shader_gap_groups[2];
assert_eq!(third.pso.as_deref(), Some("graphics"));
assert_eq!(third.stage.as_deref(), Some("PS"));
assert_eq!(third.count, 1);
}
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
/// identical records are not adjacent.
#[test]
fn groups_identical_gaps_together() {
let record = r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let log = format!("{record}\n{other}\n{record}\n");
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 3);
assert_eq!(summary.shader_gap_groups.len(), 2);
let compute = &summary.shader_gap_groups[0];
assert_eq!(compute.stage.as_deref(), Some("CS"));
assert_eq!(compute.count, 2);
assert_eq!(
compute.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 2,
}]
);
assert_eq!(summary.shader_gap_groups[1].count, 1);
// Every record is in exactly one group.
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
assert_eq!(grouped, summary.shader_gaps.len());
}
/// #590: one pipeline kind and stage can need different wave widths or atomic
/// features, so a group keeps every distinct constraint set, not only the first.
#[test]
fn one_group_keeps_each_distinct_constraint_set() {
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gap_groups.len(), 1);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 3);
assert_eq!(
group.variants,
[
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x0".into()),
count: 2,
},
ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: Some("0x400000".into()),
count: 1,
},
]
);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
/// #590: a gap record with a missing or empty field must not panic. It is grouped
/// under `unknown` and counted, never dropped or guessed.
#[test]
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
for (detail, missing_identity, missing_constraints) in [
("", 1, 1),
("garbage", 1, 1),
("pso=compute", 1, 1),
("stage=CS", 1, 1),
(
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
1,
0,
),
("pso=compute stage=CS", 0, 1),
(
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
0,
1,
),
] {
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
let summary = summarize_jsonl(&log);
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
assert_eq!(
summary.shader_gap_groups.len(),
1,
"detail={detail:?} lost its record"
);
assert_eq!(
summary.shader_gaps_missing_identity, missing_identity,
"detail={detail:?}"
);
assert_eq!(
summary.shader_gaps_missing_constraints, missing_constraints,
"detail={detail:?}"
);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.count, 1, "detail={detail:?}");
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
assert_eq!(recorded, 1, "detail={detail:?}");
}
}
/// #590: the fields a malformed record does carry are still reported.
#[test]
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
let log =
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
let summary = summarize_jsonl(log);
let group = &summary.shader_gap_groups[0];
assert_eq!(group.pso.as_deref(), Some("compute"));
assert_eq!(group.stage.as_deref(), Some("CS"));
assert_eq!(
group.variants,
[ShaderGapVariant {
wave_lanes_min: Some("64".into()),
atomic64_flags: None,
count: 1,
}]
);
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 1);
}
/// #590: a run with no gap records produces no groups and no missing-field counts, so
/// the trace renders as it did before the grouping existed.
#[test]
fn a_run_with_no_gaps_has_no_groups() {
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
let summary = summarize_jsonl(log);
assert_eq!(summary.shader_gate.total, 1);
assert!(summary.shader_gaps.is_empty());
assert!(summary.shader_gap_groups.is_empty());
assert_eq!(summary.shader_gaps_missing_identity, 0);
assert_eq!(summary.shader_gaps_missing_constraints, 0);
}
}
+582
View File
@@ -0,0 +1,582 @@
//! Run reports for the blocker queue (docs/process/working-method.md, "Run protocol").
//!
//! One JSONL log is one run. [`report_run`] reduces it to what decides the next task: how the
//! run ended, how far it got, and everything it stopped on. [`RunReport::signatures`] turns
//! those into the fixed strings blocker issues are titled with, so two people who hit the
//! same thing file the same issue. [`render_summary`] puts several runs side by side.
//!
//! What a log cannot show is said, not guessed: a run with no `run_end` record has an unknown
//! outcome, and a stall cannot be told from slow presentation because frames are logged at
//! powers of two.
use std::collections::BTreeMap;
use std::fmt::Write as _;
/// BetterXen's own guest modules. A fault whose innermost frame is in one of them is ours.
const BETTERXEN_MODULES: &[&str] = &[
"d3d12_xs.dll",
"xmem.dll",
"xcrdapi.dll",
"xgameruntime.dll",
"xg_xs.dll",
"acphal.dll",
"xapu.dll",
"chad.dll",
"gameinput.dll",
"bx_runtime_veh.dll",
"bx_shader_bridge.dll",
"ffx_bvh_hooks.dll",
];
/// How a run ended, from the launcher's `run_end` record.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum RunEnd {
/// No `run_end` record: the launcher was killed, or the log predates the record.
#[default]
Unknown,
/// The guest exited by itself with this status.
Exited(i32),
/// The launcher's `--timeout` stopped it: the run lasted as long as it was allowed to.
TimedOut,
/// A signal stopped the launcher.
Signalled(i32),
/// CrossOver could not be started.
LaunchFailed,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunReport {
pub events: u64,
/// Guest clock span of the log, in milliseconds.
pub span_ms: u64,
pub end: RunEnd,
/// The last power-of-two frame count logged: at least this many frames were presented.
pub frames_at_least: Option<u64>,
/// Unimplemented calls reached, by signature, with how often.
pub unimplemented: BTreeMap<String, u64>,
/// Faults whose innermost frame is in a BetterXen module, by module.
pub faults: BTreeMap<String, u64>,
/// Exceptions nothing handled.
pub unhandled_exceptions: u64,
/// Pipeline stages that reached the shader gate, by "kind decision" (for example
/// "stream reject_unclassified_dxil").
pub shader_gate: BTreeMap<String, u64>,
/// Refused pipeline creations by kind.
pub pipelines_refused: BTreeMap<String, u64>,
/// Draws and dispatches skipped with a null pipeline bound (a lower bound).
pub skipped_work_at_least: Option<u64>,
}
fn json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let needle = format!("\"{key}\":\"");
let start = line.find(&needle)? + needle.len();
let rest = &line[start..];
// Details do not contain escaped quotes in practice; stop at the first unescaped one.
let mut end = 0;
let bytes = rest.as_bytes();
while end < bytes.len() {
if bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\') {
return Some(&rest[..end]);
}
end += 1;
}
None
}
fn json_u64(line: &str, key: &str) -> Option<u64> {
let needle = format!("\"{key}\":");
let start = line.find(&needle)? + needle.len();
let digits = &line[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
fn number_after(detail: &str, key: &str) -> Option<u64> {
let start = detail.find(key)? + key.len();
let digits = &detail[start..];
let end = digits
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(digits.len());
digits[..end].parse().ok()
}
/// `IXUser[3]::slot_3` -> `unimplemented IXUser slot 3`;
/// `XboxDevice[81]::GetFrameStatisticsX` -> `unimplemented XboxDevice slot 81 (GetFrameStatisticsX)`.
fn vtable_signature(detail: &str) -> String {
let parsed = (|| {
let open = detail.find('[')?;
let close = detail[open..].find(']')? + open;
let slot: u32 = detail[open + 1..close].parse().ok()?;
let method = detail[close + 1..].strip_prefix("::")?;
Some((&detail[..open], slot, method))
})();
match parsed {
Some((interface, slot, method)) if method.starts_with("slot_") || method.is_empty() => {
format!("unimplemented {interface} slot {slot}")
}
Some((interface, slot, method)) => {
format!("unimplemented {interface} slot {slot} ({method})")
}
None => format!("unimplemented {detail}"),
}
}
/// The module of the innermost stack frame in an `av_context` detail (`... | stack: A.dll+12 B.dll+34`).
fn fault_module(detail: &str) -> Option<&str> {
let stack = detail.split("stack: ").nth(1)?;
let frame = stack.split_whitespace().next()?;
Some(frame.split('+').next().unwrap_or(frame))
}
fn is_betterxen_module(module: &str) -> bool {
BETTERXEN_MODULES
.iter()
.any(|m| m.eq_ignore_ascii_case(module))
}
/// Reduces one run's JSONL log to its report.
pub fn report_run(input: &str) -> RunReport {
let mut report = RunReport::default();
let mut first_ts = None;
let mut last_ts = 0;
for line in input.lines() {
let line = line.trim();
if !line.starts_with('{') {
continue;
}
report.events += 1;
let event = json_str(line, "event").unwrap_or("");
let detail = json_str(line, "detail").unwrap_or("");
if event == "run_end" {
report.end = match detail {
d if d.starts_with("outcome=exited") => {
let status = d
.split("status=")
.nth(1)
.and_then(|s| s.trim().parse().ok());
status.map_or(RunEnd::Unknown, RunEnd::Exited)
}
"outcome=timeout" => RunEnd::TimedOut,
d if d.starts_with("outcome=signal") => {
RunEnd::Signalled(number_after(d, "signal=").unwrap_or(0) as i32)
}
"outcome=launch_failed" => RunEnd::LaunchFailed,
_ => RunEnd::Unknown,
};
continue; // the launcher's record carries no guest timestamp
}
if let Some(ts) = json_u64(line, "ts_ms") {
first_ts.get_or_insert(ts);
last_ts = last_ts.max(ts);
}
match event {
"presentx_frames" => {
if let Some(n) = number_after(detail, "presented=") {
report.frames_at_least = Some(report.frames_at_least.unwrap_or(0).max(n));
}
}
"unimpl_vtable" => {
*report
.unimplemented
.entry(vtable_signature(detail))
.or_default() += 1
}
"unimpl_api" => {
*report
.unimplemented
.entry(format!("unimplemented {detail}"))
.or_default() += 1
}
"av_context" => {
if let Some(module) = fault_module(detail).filter(|m| is_betterxen_module(m)) {
*report.faults.entry(module.to_owned()).or_default() += 1;
}
}
"unhandled_exception" => report.unhandled_exceptions += 1,
"shader_gate" => {
let kind = detail
.split("pso=")
.nth(1)
.and_then(|s| s.split_whitespace().next());
let decision = detail
.split("decision=")
.nth(1)
.and_then(|s| s.split_whitespace().next());
if let (Some(kind), Some(decision)) = (kind, decision) {
*report
.shader_gate
.entry(format!("{kind} {decision}"))
.or_default() += 1;
}
}
"pipeline_refused" => {
let kind = detail.split(" pipeline refused").next().unwrap_or(detail);
*report.pipelines_refused.entry(kind.to_owned()).or_default() += 1;
}
"null_render_skip" => {
if let Some(n) = number_after(detail, "total skipped=") {
report.skipped_work_at_least =
Some(report.skipped_work_at_least.unwrap_or(0).max(n));
}
}
_ => {}
}
}
report.span_ms = first_ts.map_or(0, |first| last_ts.saturating_sub(first));
report
}
impl RunReport {
/// The strings blocker issues are titled with (`[blocker] <signature>`), most severe first.
pub fn signatures(&self) -> Vec<String> {
let mut out = Vec::new();
match self.end {
RunEnd::Exited(status) if status != 0 => out.push(format!("exit status {status}")),
RunEnd::LaunchFailed => out.push("launch failed".to_owned()),
_ => {}
}
if self.unhandled_exceptions > 0 {
out.push("unhandled exception".to_owned());
}
out.extend(
self.faults
.keys()
.map(|module| format!("fault in {module}")),
);
out.extend(self.unimplemented.keys().cloned());
if self.skipped_work_at_least.is_some() {
out.push("draws or dispatches skipped with a null pipeline".to_owned());
}
out
}
/// True when the run reached the frame loop and stopped on nothing: the Boot gate's
/// per-run condition, except for its length, which the caller sets with `--timeout`.
pub fn clean_boot(&self) -> bool {
self.end == RunEnd::TimedOut
&& self.frames_at_least.is_some()
&& self.unimplemented.is_empty()
&& self.faults.is_empty()
&& self.unhandled_exceptions == 0
}
}
fn end_text(end: &RunEnd) -> String {
match end {
RunEnd::Unknown => "unknown (no run_end record)".to_owned(),
RunEnd::Exited(status) => format!("exited by itself, status {status}"),
RunEnd::TimedOut => "ran until the timeout".to_owned(),
RunEnd::Signalled(signal) => format!("stopped by signal {signal}"),
RunEnd::LaunchFailed => "launch failed".to_owned(),
}
}
/// The report of one run, as text.
pub fn render_run(name: &str, report: &RunReport) -> String {
let mut out = String::new();
let _ = writeln!(out, "Run {name}");
let _ = writeln!(out, " outcome : {}", end_text(&report.end));
let _ = writeln!(
out,
" frames presented : {}",
report
.frames_at_least
.map_or("none".to_owned(), |n| format!("at least {n}"))
);
let _ = writeln!(
out,
" log span : {:.1} s, {} events",
report.span_ms as f64 / 1000.0,
report.events
);
if !report.unimplemented.is_empty() {
let _ = writeln!(out, " unimplemented calls:");
for (signature, count) in &report.unimplemented {
let _ = writeln!(out, " {count:>7}x {signature}");
}
}
if !report.faults.is_empty() || report.unhandled_exceptions > 0 {
let _ = writeln!(out, " faults:");
for (module, count) in &report.faults {
let _ = writeln!(out, " {count:>7}x fault in {module}");
}
if report.unhandled_exceptions > 0 {
let _ = writeln!(
out,
" {:>7}x unhandled exception",
report.unhandled_exceptions
);
}
}
if !report.shader_gate.is_empty() || !report.pipelines_refused.is_empty() {
let _ = writeln!(out, " pipelines:");
for (kind, count) in &report.shader_gate {
let _ = writeln!(out, " {count:>7}x shader stage: {kind}");
}
for (kind, count) in &report.pipelines_refused {
let _ = writeln!(out, " {count:>7}x refused: {kind}");
}
if let Some(skipped) = report.skipped_work_at_least {
let _ = writeln!(
out,
" at least {skipped} draws or dispatches skipped (null pipeline)"
);
}
}
out
}
/// Several runs side by side, then every signature with the number of runs that hit it.
pub fn render_summary(runs: &[(String, RunReport)]) -> String {
let mut out = String::new();
let total = runs.len();
let _ = writeln!(out, "Summary of {total} run(s)");
for (name, report) in runs {
let _ = writeln!(
out,
" {name}: {}; frames {}; {}",
end_text(&report.end),
report
.frames_at_least
.map_or("none".to_owned(), |n| format!(">= {n}")),
if report.clean_boot() {
"clean"
} else {
"not clean"
}
);
}
let clean = runs.iter().filter(|(_, r)| r.clean_boot()).count();
let _ = writeln!(
out,
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): {clean} of {total}"
);
let mut hits: BTreeMap<String, usize> = BTreeMap::new();
for (_, report) in runs {
for signature in report.signatures() {
*hits.entry(signature).or_default() += 1;
}
}
if hits.is_empty() {
let _ = writeln!(out, "Signatures: none");
} else {
let _ = writeln!(out, "Signatures (runs that hit each):");
let mut ordered: Vec<_> = hits.into_iter().collect();
ordered.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
for (signature, count) in ordered {
let _ = writeln!(out, " {count} of {total} {signature}");
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn line(ts: u64, sub: &str, event: &str, detail: &str) -> String {
format!(
"{{\"ts_ms\":{ts},\"tid\":1,\"level\":\"INFO\",\"sub\":\"{sub}\",\"event\":\"{event}\",\"detail\":\"{detail}\"}}\n"
)
}
#[test]
fn a_clean_run_reports_frames_span_and_no_signatures() {
let log = line(
1000,
"d3d12_xs",
"presentx_frames",
"frames presented=1 last hr=0x00000000",
) + &line(
4000,
"d3d12_xs",
"presentx_frames",
"frames presented=64 last hr=0x00000000",
) + &line(0, "bx_cli", "run_end", "outcome=timeout");
let report = report_run(&log);
assert_eq!(report.frames_at_least, Some(64));
assert_eq!(
report.span_ms, 3000,
"the launcher's record must not stretch the guest span"
);
assert_eq!(report.end, RunEnd::TimedOut);
assert!(report.clean_boot());
assert!(report.signatures().is_empty());
}
#[test]
fn unimplemented_calls_become_stable_signatures() {
let log = line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
+ &line(
2,
"com_vtable",
"unimpl_vtable",
"XboxDevice[81]::GetFrameStatisticsX",
)
+ &line(
3,
"com_vtable",
"unimpl_vtable",
"XboxDevice[81]::GetFrameStatisticsX",
)
+ &line(
4,
"stub",
"unimpl_api",
"d3d12_xs.dll!CreatePlacedResourceX(texture contents)",
);
let report = report_run(&log);
assert_eq!(
report.unimplemented.get("unimplemented IXUser slot 3"),
Some(&1)
);
assert_eq!(
report
.unimplemented
.get("unimplemented XboxDevice slot 81 (GetFrameStatisticsX)"),
Some(&2)
);
assert!(report.signatures().contains(
&"unimplemented d3d12_xs.dll!CreatePlacedResourceX(texture contents)".to_owned()
));
assert!(
!report.clean_boot(),
"an unimplemented call is not a clean run"
);
}
#[test]
fn a_fault_counts_only_when_its_innermost_frame_is_a_betterxen_module() {
let ours = line(
1,
"runtime_veh",
"av_context",
"rip=1 fault=2 | stack: XCRDAPI.dll+9a51 ntdll.dll+10",
);
let theirs = line(
2,
"runtime_veh",
"av_context",
"rip=1 fault=2 | stack: title.exe+10 XCRDAPI.dll+9a51",
);
let report = report_run(&(ours + &theirs));
assert_eq!(report.faults.get("XCRDAPI.dll"), Some(&1));
assert_eq!(report.faults.len(), 1);
assert_eq!(report.signatures(), vec!["fault in XCRDAPI.dll".to_owned()]);
}
#[test]
fn the_end_of_a_run_is_read_from_the_launcher_record() {
let exited = report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=5"));
assert_eq!(exited.end, RunEnd::Exited(5));
assert_eq!(exited.signatures(), vec!["exit status 5".to_owned()]);
assert_eq!(
report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=0")).signatures(),
Vec::<String>::new()
);
assert_eq!(
report_run(&line(0, "bx_cli", "run_end", "outcome=signal signal=15")).end,
RunEnd::Signalled(15)
);
assert_eq!(
report_run(&line(0, "bx_cli", "run_end", "outcome=launch_failed")).end,
RunEnd::LaunchFailed
);
// No record: unknown, and never "clean".
let unknown = report_run(&line(
1,
"d3d12_xs",
"presentx_frames",
"frames presented=8 last hr=0x0",
));
assert_eq!(unknown.end, RunEnd::Unknown);
assert!(!unknown.clean_boot());
}
#[test]
fn pipelines_are_counted_by_kind() {
let log = line(
1,
"d3d12_xs",
"shader_gate",
"pso=stream stage=VS decision=reject_unclassified_dxil hr=0x80004001",
) + &line(
2,
"d3d12_xs",
"shader_gate",
"pso=compute stage=CS decision=pass_dxil hr=0x00000000",
) + &line(
3,
"d3d12_xs",
"pipeline_refused",
"deserialized graphics (console code) pipeline refused hr=0x80004001",
) + &line(
4,
"d3d12_xs",
"null_render_skip",
"DrawInstanced with a null pipeline bound; total skipped=4",
) + &line(
5,
"d3d12_xs",
"null_render_skip",
"DrawInstanced with a null pipeline bound; total skipped=8",
);
let report = report_run(&log);
assert_eq!(
report.shader_gate.get("stream reject_unclassified_dxil"),
Some(&1)
);
assert_eq!(report.shader_gate.get("compute pass_dxil"), Some(&1));
assert_eq!(
report
.pipelines_refused
.get("deserialized graphics (console code)"),
Some(&1)
);
assert_eq!(report.skipped_work_at_least, Some(8));
}
#[test]
fn the_summary_counts_runs_per_signature_and_clean_runs() {
let clean = report_run(
&(line(
1,
"d3d12_xs",
"presentx_frames",
"frames presented=16 last hr=0x0",
) + &line(0, "bx_cli", "run_end", "outcome=timeout")),
);
let stopped = report_run(
&(line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
+ &line(0, "bx_cli", "run_end", "outcome=exited status=1")),
);
let text = render_summary(&[
("a".to_owned(), clean),
("b".to_owned(), stopped.clone()),
("c".to_owned(), stopped),
]);
assert!(
text.contains(
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): 1 of 3"
),
"{text}"
);
assert!(text.contains(" 2 of 3 exit status 1\n"), "{text}");
assert!(
text.contains(" 2 of 3 unimplemented IXUser slot 3\n"),
"{text}"
);
}
#[test]
fn lines_that_are_not_json_records_are_ignored() {
let report = report_run("warning: not a record\n\n{\"broken\n");
assert_eq!(
report.events, 1,
"a line starting with a brace is counted even when malformed"
);
assert!(report.signatures().is_empty());
}
}
+117 -21
View File
@@ -4,11 +4,15 @@
Checks only tracked files:
1. no merge-conflict markers in tracked text files;
2. every relative Markdown link points at a tracked file or directory;
3. every workflow file under .github/workflows parses as YAML.
3. every fragment (``#heading``) in a Markdown link resolves to a real
heading in the target Markdown file, including in-page ``](#foo)``
links validated against the same file's headings;
4. every workflow file under .github/workflows parses as YAML.
External URLs and in-page anchors are not fetched or validated, so the result
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
when PyYAML is missing.
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
fetched or validated, so the result does not depend on the network.
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
not skip, when PyYAML is missing.
"""
import re
import subprocess
@@ -17,9 +21,16 @@ from pathlib import Path, PurePosixPath
from urllib.parse import unquote
ROOT = Path(__file__).resolve().parents[2]
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
MARKER = re.compile(r"^(<{7}( |$)|\|{7}( |$)|={7}$|>{7}( |$))")
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
FENCE = re.compile(r"^\s*(```|~~~)")
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
# GitHub slugs the rendered heading, so an inline link contributes only its
# text: ``## See [ADR](x.md)`` slugs as ``see-adr``, not ``see-adrxmd``.
# Link syntax inside a code span stays literal, so those spans are set aside
# before substituting and put back afterwards.
INLINE_LINK = re.compile(r"(?<!\!)\[([^\]]*)\]\([^)]*\)")
CODE_SPAN = re.compile(r"(`+)(.+?)\1")
def tracked():
@@ -35,6 +46,63 @@ def text(path):
return data.decode("utf-8", "replace")
def _slug(text):
"""GitHub-style slug: lowercase, strip non-alnum/-/_/space, spaces -> -."""
text = text.lower()
text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE)
return text.replace(" ", "-")
def _heading_text(text):
"""Rendered text of a heading: link text in, code spans left literal."""
spans = []
def stash(match):
spans.append(match.group(0))
return "\x00%d\x00" % (len(spans) - 1)
stashed = CODE_SPAN.sub(stash, text)
substituted = INLINE_LINK.sub(r"\1", stashed)
for index, span in enumerate(spans):
substituted = substituted.replace("\x00%d\x00" % index, span)
return substituted
def markdown_slugs(body):
"""Return the set of GitHub-style heading slugs in a Markdown document.
Duplicate headings get ``-1``, ``-2``, ... suffixes. Headings inside
fenced code blocks are ignored.
"""
slugs = set()
seen = {}
in_fence = False
for line in body.splitlines():
if FENCE.match(line):
in_fence = not in_fence
continue
if in_fence:
continue
m = HEADING.match(line)
if not m:
continue
base = _slug(_heading_text(m.group(2)))
if not base:
continue
# Advance the numeric suffix until we find a slug that has not
# already been emitted. Counting only identical bases is not
# enough: a literal heading such as ``Foo-1`` may already own
# ``foo-1``, so the next ``Foo`` must become ``foo-2``.
count = seen.get(base, 0)
slug = base if count == 0 else f"{base}-{count}"
while slug in slugs:
count += 1
slug = f"{base}-{count}"
seen[base] = count + 1
slugs.add(slug)
return slugs
def check_markers(files, problems):
for path in files:
if path.endswith((".patch", ".diff")):
@@ -47,9 +115,30 @@ def check_markers(files, problems):
problems.append(f"{path}:{number}: merge conflict marker")
def _resolve_link(path, target):
"""Resolve a relative link target to a repo-root-relative POSIX path."""
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
return "/".join(parts)
def check_links(files, problems):
known = set(files)
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
slug_cache = {}
def slugs_for(md_path):
if md_path not in slug_cache:
slug_cache[md_path] = markdown_slugs(text(md_path) or "")
return slug_cache[md_path]
for path in files:
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
continue
@@ -61,24 +150,31 @@ def check_links(files, problems):
if in_fence:
continue
line = re.sub(r"`[^`]*`", "", line)
for target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
for raw_target in LINK.findall(line):
if re.match(r"^([a-z][a-z0-9+.-]*:|//)", raw_target, re.I):
continue
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
if not target:
if raw_target == "#":
continue
base = PurePosixPath(path).parent
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
parts = []
for part in resolved.parts:
if part == "..":
if parts:
parts.pop()
elif part != ".":
parts.append(part)
norm = "/".join(parts)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
fragment = ""
if "#" in raw_target:
fragment = unquote(raw_target.split("#", 1)[1])
target = unquote(raw_target.split("#", 1)[0].split("?", 1)[0])
if not target and not fragment:
continue
if target:
norm = _resolve_link(path, target)
if norm and norm not in known and norm not in dirs:
problems.append(f"{path}:{number}: broken relative link '{target}'")
continue
else:
norm = path
if fragment and norm.endswith(".md") and norm in known:
if fragment not in slugs_for(norm):
shown = raw_target
problems.append(
f"{path}:{number}: broken fragment '#{fragment}' "
f"in link '{shown}' (heading not found)"
)
def check_workflows(files, problems, require_yaml):
+296
View File
@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
Run with:
python3 -m unittest scripts/audit/test_docs_hygiene.py
"""
import importlib.util
import sys
import unittest
from pathlib import Path
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
docs_hygiene = importlib.util.module_from_spec(_spec)
sys.modules["docs_hygiene"] = docs_hygiene
_spec.loader.exec_module(docs_hygiene)
class SlugTests(unittest.TestCase):
def test_basic_slug(self):
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
self.assertIn("hello-world", slugs)
def test_strips_punctuation(self):
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
self.assertIn("whats-new-2024", slugs)
def test_keeps_underscore_and_hyphen(self):
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
self.assertIn("foo_bar-baz", slugs)
def test_duplicate_headings(self):
body = "# Setup\n\n# Setup\n\n# Setup\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("setup", slugs)
self.assertIn("setup-1", slugs)
self.assertIn("setup-2", slugs)
def test_suffix_skips_literal_heading_slug(self):
# Regression: counting identical bases alone lets a generated
# suffix collide with a literal heading slug, so the third `Foo`
# also became `foo-1` and a link to the wrong heading validated.
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_suffix_skips_multiple_literal_heading_slugs(self):
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
def test_three_identical_headings(self):
body = "# Foo\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
def test_literal_slug_before_duplicates(self):
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
def test_heading_link_contributes_only_its_text(self):
# GitHub slugs the rendered heading, where the link's URL is gone.
# Slugging the raw source appended the URL and made the first real
# link to the anchor look broken.
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
self.assertEqual(slugs, {"setup-guide-notes"})
def test_heading_link_matches_github_for_the_readme_heading(self):
# The exact heading at README.md:53; GitHub renders
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
def test_heading_link_duplicate_still_gets_a_suffix(self):
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
def test_heading_link_inside_a_code_span_stays_literal(self):
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
# the slug. Substituting links first made this `code-x-span`.
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
self.assertEqual(slugs, {"code-xy-span"})
def test_heading_mixes_a_code_span_and_a_link(self):
# Only the real link loses its URL; the code span keeps its text.
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
self.assertEqual(slugs, {"see-a-and-b"})
def test_heading_double_backtick_code_span(self):
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
# the inner single-backtick run closes the outer span early, so the
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
# observed GitHub anchor keeps this honest rather than assuming the
# "obvious" answer.
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
def test_heading_image_is_not_treated_as_a_link(self):
# An image contributes its alt text through GitHub's rendering, but
# the `(?<!\!)` guard must keep this path unchanged for now.
slugs = docs_hygiene.markdown_slugs("## ![img](a.png) caption\n")
self.assertEqual(len(slugs), 1)
def test_fenced_code_block_ignored(self):
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertIn("real-heading", slugs)
self.assertNotIn("not-a-heading", slugs)
def test_tilde_fence_ignored(self):
body = "~~~\n# Not A Heading\n~~~\n"
slugs = docs_hygiene.markdown_slugs(body)
self.assertNotIn("not-a-heading", slugs)
def test_atx_levels(self):
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
slugs = docs_hygiene.markdown_slugs(body)
for s in ("one", "two", "three", "four", "five", "six"):
self.assertIn(s, slugs)
class CheckLinksTests(unittest.TestCase):
"""Exercise check_links with a synthetic in-memory file set."""
def _run(self, files):
"""files: dict mapping repo-relative path -> Markdown body."""
problems = []
original_text = docs_hygiene.text
def fake_text(path):
return files.get(path)
docs_hygiene.text = fake_text
try:
docs_hygiene.check_links(list(files), problems)
finally:
docs_hygiene.text = original_text
return problems
def test_existing_heading_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(problems, [])
def test_in_page_anchor_passes(self):
problems = self._run({
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
})
self.assertEqual(problems, [])
def test_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "[link](b.md#no-such-heading)\n",
"docs/b.md": "# Hello World\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#no-such-heading", problems[0])
self.assertIn("heading not found", problems[0])
def test_in_page_nonexistent_heading_fails(self):
problems = self._run({
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#this-heading-does-not-exist", problems[0])
def test_duplicate_heading_addressable(self):
problems = self._run({
"docs/a.md": "[link](b.md#setup-1)\n",
"docs/b.md": "# Setup\n\n# Setup\n",
})
self.assertEqual(problems, [])
def test_fenced_heading_not_a_slug(self):
problems = self._run({
"docs/a.md": "[link](b.md#not-a-heading)\n",
"docs/b.md": "```\n# Not A Heading\n```\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("#not-a-heading", problems[0])
def test_external_url_with_fragment_not_checked(self):
problems = self._run({
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
})
self.assertEqual(problems, [])
def test_mailto_not_checked(self):
problems = self._run({
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
})
self.assertEqual(problems, [])
def test_protocol_relative_not_checked(self):
problems = self._run({
"docs/a.md": "[link](//example.com/page#frag)\n",
})
self.assertEqual(problems, [])
def test_bare_hash_skipped(self):
problems = self._run({
"docs/a.md": "[link](#)\n",
})
self.assertEqual(problems, [])
def test_missing_file_still_reported(self):
problems = self._run({
"docs/a.md": "[link](nonexistent.md#foo)\n",
})
self.assertEqual(len(problems), 1)
self.assertIn("broken relative link", problems[0])
def test_fragment_on_non_markdown_not_checked(self):
problems = self._run({
"docs/a.md": "[link](image.png#foo)\n",
"docs/image.png": None,
})
# image.png is binary (text returns None) but it exists in the
# file list, so the link itself resolves; fragment is not checked.
self.assertEqual(problems, [])
class MarkerTests(unittest.TestCase):
"""The conflict-marker check must catch all four markers, including the diff3 one."""
def _markers(self, text):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "f.md").write_text(text, encoding="utf-8")
previous = docs_hygiene.ROOT
docs_hygiene.ROOT = root
try:
problems = []
docs_hygiene.check_markers({"f.md": text}, problems)
return problems
finally:
docs_hygiene.ROOT = previous
def test_every_marker_kind_is_reported(self):
for line in ["<<<<<<< HEAD", "||||||| merged common ancestors", "=======", ">>>>>>> topic"]:
problems = self._markers(line + "\n")
self.assertEqual(len(problems), 1, f"{line!r} was not reported: {problems}")
self.assertIn("f.md:1", problems[0])
def test_diff3_base_marker_is_reported(self):
base = self._markers("||||||| merged common ancestors\n")
self.assertEqual(len(base), 1, "the diff3 base marker must be reported")
self.assertIn("conflict marker", base[0])
def test_a_diff3_block_reports_all_four_lines(self):
block = "<<<<<<< HEAD\na\n||||||| merged common ancestors\nb\n=======\nc\n>>>>>>> topic\n"
problems = self._markers(block)
self.assertEqual(len(problems), 4, problems)
def test_ordinary_content_is_not_a_marker(self):
for text in ["| a | b |\n", "||||||\n", "======\n", "prose with | pipes\n", "---\n"]:
self.assertEqual(self._markers(text), [], f"{text!r} was wrongly reported")
class WorkflowTests(unittest.TestCase):
"""check_workflows must reject unparseable YAML."""
def _check(self, text):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / ".github" / "workflows").mkdir(parents=True)
(root / ".github" / "workflows" / "a.yml").write_text(text, encoding="utf-8")
previous = docs_hygiene.ROOT
docs_hygiene.ROOT = root
try:
problems = []
docs_hygiene.check_workflows({".github/workflows/a.yml": text}, problems, require_yaml=True)
return problems
finally:
docs_hygiene.ROOT = previous
def test_parses_a_valid_workflow(self):
self.assertEqual(self._check("on: push\njobs:\n b:\n runs-on: ubuntu-latest\n"), [])
def test_reports_invalid_yaml(self):
problems = self._check("on: [push\n")
self.assertEqual(len(problems), 1, problems)
self.assertIn("a.yml", problems[0])
if __name__ == "__main__":
unittest.main()
+31
View File
@@ -18,6 +18,37 @@ cmake -S "$ROOT_DIR/shims" -B "$BUILD_DIR" \
cmake --build "$BUILD_DIR" --parallel "$JOBS"
# bx_shader_bridge.dll (#445, #484): shader-transpiler/crates/dxbc-accc built for x86-64
# Windows guests, linked with abi/defs/bx_shader_bridge.def so its export list and internal
# name are the frozen ones. The verifier below then checks it like every other shim.
# Cargo and rustc are resolved through rustup when present (a cargo earlier on PATH may have
# no Windows std), and the build always goes to <repo>/target so no stale DLL is staged.
BRIDGE_TARGET=x86_64-pc-windows-gnu
if command -v rustup >/dev/null 2>&1; then
BRIDGE_CARGO="$(cd "$ROOT_DIR" && rustup which cargo)"
BRIDGE_RUSTC="$(cd "$ROOT_DIR" && rustup which rustc)"
else
BRIDGE_CARGO="$(command -v cargo || true)"
BRIDGE_RUSTC="$(command -v rustc || true)"
fi
if [ -z "$BRIDGE_CARGO" ] || [ -z "$BRIDGE_RUSTC" ]; then
echo "error: cargo/rustc not found; bx_shader_bridge.dll needs the Rust toolchain" >&2
exit 1
fi
BRIDGE_LIBDIR="$("$BRIDGE_RUSTC" --print target-libdir --target "$BRIDGE_TARGET" 2>/dev/null || true)"
if [ -z "$BRIDGE_LIBDIR" ] || ! ls "$BRIDGE_LIBDIR"/libstd-*.rlib >/dev/null 2>&1; then
echo "error: $("$BRIDGE_RUSTC" --version) has no std for $BRIDGE_TARGET, needed for bx_shader_bridge.dll" >&2
echo "error: install it with: rustup target add $BRIDGE_TARGET" >&2
exit 1
fi
echo "=== Building bx_shader_bridge.dll with $("$BRIDGE_RUSTC" --version) ==="
RUSTC="$BRIDGE_RUSTC" CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc \
"$BRIDGE_CARGO" rustc --locked --release -j "$JOBS" --manifest-path "$ROOT_DIR/Cargo.toml" \
-p dxbc-accc --lib --crate-type cdylib --target "$BRIDGE_TARGET" --target-dir "$ROOT_DIR/target" \
-- -C link-arg="$ROOT_DIR/abi/defs/bx_shader_bridge.def"
mkdir -p "$BUILD_DIR/bin"
cp "$ROOT_DIR/target/$BRIDGE_TARGET/release/dxbc_accc.dll" "$BUILD_DIR/bin/bx_shader_bridge.dll"
echo "=== Verifying built PE32+ DLL Export Directories against abi/defs/*.def ==="
python3 - "$ROOT_DIR/abi/defs" "$BUILD_DIR/bin" <<'PY'
import os
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env python3
"""Generates shader-transpiler/crates/gfx10-translate/tests/llvm_vectors.txt: instruction
encodings and their canonical text from the public LLVM AMDGPU assembler (llvm-mc, gfx1030).
Each line is `<hex words> | <text>`. The decoder test decodes the words and requires the same
text, so the decoder is checked against an implementation independent of BetterXen.
usage: gen_llvm_vectors.py [--llvm-mc PATH] > shader-transpiler/crates/gfx10-translate/tests/llvm_vectors.txt
"""
import argparse
import os
import subprocess
# Every shape the translator handles, and common instructions of each format.
INSTRUCTIONS = """
s_add_u32 s0, s1, s2
s_add_u32 s3, s1, 0x12345678
s_or_b32 s0, s1, 7
s_and_b32 s4, s5, -1
s_xor_b32 s0, s1, s2
s_mul_i32 s0, s1, s2
s_sub_u32 s0, s1, 64
s_lshr_b32 s0, s1, 4
s_lshl_b32 s0, s1, 2
s_min_u32 s0, s1, s2
s_max_u32 s0, s1, s2
s_bfe_u32 s0, s1, 0x100000
s_mov_b32 s0, s1
s_mov_b32 s0, 0x3f800000
s_mov_b32 m0, s1
s_mov_b64 s[0:1], s[2:3]
s_mov_b64 s[0:1], exec
s_and_b64 exec, exec, s[2:3]
s_wqm_b64 exec, exec
s_brev_b32 s0, s1
s_swappc_b64 s[4:5], s[4:5]
s_movk_i32 s0, 0x1234
s_cmp_eq_u32 s0, s1
s_cbranch_scc0 4
s_endpgm
s_load_dwordx4 s[0:3], s[4:5], 0x10
s_load_dwordx8 s[8:15], s[4:5], 0x20
s_load_dwordx4 s[0:3], s[4:5], 0x0
s_buffer_load_dword s0, s[4:7], 0x0
s_buffer_load_dwordx2 s[0:1], s[4:7], 0x8
s_buffer_load_dwordx4 s[8:11], s[4:7], 0x10
s_buffer_load_dwordx8 s[8:15], s[4:7], 0x20
s_buffer_load_dwordx16 s[16:31], s[4:7], 0x40
v_mov_b32_e32 v0, v1
v_mov_b32_e32 v0, s2
v_mov_b32_e32 v0, 0x40490fdb
v_mov_b32_e32 v0, 1.0
v_mov_b32_e32 v0, -4.0
v_mov_b32_e32 v0, 0.15915494
v_mov_b32_e32 v0, 17
v_mov_b32_e32 v0, -3
v_add_f32_e32 v0, v1, v2
v_add_f32_e32 v0, 0.5, v1
v_mul_f32_e32 v0, 0x3e800000, v1
v_sub_f32_e32 v0, v1, v2
v_subrev_f32_e32 v0, v1, v2
v_max_f32_e32 v0, v1, v2
v_min_f32_e32 v0, v1, v2
v_fmac_f32_e32 v0, v1, v2
v_mul_legacy_f32_e32 v0, v1, v2
v_cvt_pkrtz_f16_f32_e32 v0, v1, v2
v_lshlrev_b32_e32 v0, 2, v1
v_lshrrev_b32_e32 v0, 16, v1
v_ashrrev_i32_e32 v0, 16, v1
v_and_b32_e32 v0, 0xff, v1
v_or_b32_e32 v0, v1, v2
v_xor_b32_e32 v0, v1, v2
v_sub_nc_u32_e32 v0, v1, v2
v_subrev_nc_u32_e32 v0, v1, v2
v_add_nc_u32_e32 v0, s2, v1
v_mul_u32_u24_e32 v0, v1, v2
v_min_u32_e32 v0, v1, v2
v_max_u32_e32 v0, v1, v2
v_rcp_f32_e32 v0, v1
v_rsq_f32_e32 v0, v1
v_sqrt_f32_e32 v0, v1
v_floor_f32_e32 v0, v1
v_fract_f32_e32 v0, v1
v_exp_f32_e32 v0, v1
v_log_f32_e32 v0, v1
v_trunc_f32_e32 v0, v1
v_rndne_f32_e32 v0, v1
v_ceil_f32_e32 v0, v1
v_cvt_f32_u32_e32 v0, v1
v_cvt_f32_i32_e32 v0, v1
v_cvt_i32_f32_e32 v0, v1
v_sin_f32_e32 v0, v1
v_cos_f32_e32 v0, v1
v_add_f32_e64 v0, v1, v2
v_mul_f32_e64 v0, -v1, v2
v_mul_f32_e64 v0, v1, -v2
v_mul_f32_e64 v0, -v1, |v2|
v_add_f32_e64 v0, v1, v2 clamp
v_mul_f32_e64 v0, v1, v2 mul:2
v_max_f32_e64 v0, v1, s2
v_sub_f32_e64 v0, v1, v2
v_rcp_f32_e64 v0, -v1
v_lshlrev_b32_e64 v0, s2, v1
v_mul_lo_u32 v0, v1, v2
v_mul_hi_u32 v0, v1, v2
v_fma_f32 v0, v1, v2, v3
v_fma_f32 v0, -v1, v2, 1.0
v_med3_f32 v0, v1, 0, 1.0
v_bfe_u32 v0, v1, 8, 8
v_cmp_lt_f32_e32 vcc_lo, v1, v2
v_cmpx_eq_u32_e32 v1, v2
v_cndmask_b32_e32 v0, v1, v2, vcc_lo
v_interp_p1_f32_e32 v2, v0, attr0.x
v_interp_p2_f32_e32 v2, v1, attr0.x
v_interp_p2_f32_e32 v3, v1, attr3.w
v_interp_mov_f32_e32 v0, p0, attr2.y
v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]
v_fma_mixhi_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]
buffer_load_dword v0, v1, s[4:7], 0 idxen
buffer_load_dword v0, v1, s[4:7], 0 idxen offset:12
buffer_load_dwordx2 v[0:1], v2, s[4:7], 0 idxen
buffer_load_dwordx3 v[0:2], v3, s[4:7], 0 idxen offset:4
buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 idxen
buffer_load_dword v0, v1, s[4:7], 0 offen
buffer_load_dword v0, off, s[4:7], s2 offset:16
tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen
tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] idxen offset:8
image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
exp pos0, v0, v1, v2, v3 done
exp mrt0, v0, v1, v2, v3 done vm
exp mrt0, v0, off, off, off
exp param3, v4, v5, v6, v7
exp mrt0, v0, v0, v1, v1 done compr vm
v_fmaak_f32 v0, v1, v2, 0x3f800000
v_fmamk_f32 v0, v1, 0x40000000, v2
gfx1010 v_mac_f32_e32 v0, v1, v2
gfx1010 v_mac_f32_e64 v0, -v1, v2
gfx1010 v_mad_f32 v0, v1, v2, v3
gfx1010 v_madak_f32 v0, v1, v2, 0x3f800000
gfx1010 v_madmk_f32 v0, v1, 0x40000000, v2
"""
# Lines starting with a target name are assembled for that target: the console compiler emits a
# few GFX10.1 instructions (v_mac_f32, v_mad_f32, v_madak/madmk_f32) that LLVM knows only there.
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
a = ap.parse_args()
lines = [l.strip() for l in INSTRUCTIONS.strip().splitlines() if l.strip()]
version = subprocess.run([a.llvm_mc, "--version"], capture_output=True, text=True).stdout.split("\n")
version = next((v.strip() for v in version if "version" in v.lower()), "unknown")
print("# @generated by scripts/console-shader/gen_llvm_vectors.py from %s (gfx1030)." % version)
print("# <instruction words> | <llvm-mc's text for them>")
for line in lines:
mcpu = "gfx1030"
if line.startswith("gfx"):
mcpu, line = line.split(" ", 1)
r = subprocess.run([a.llvm_mc, "-arch=amdgcn", "-mcpu=" + mcpu, "-show-encoding"], input=line,
capture_output=True, text=True)
enc = next(l for l in r.stdout.splitlines() if "encoding:" in l)
data = bytes(int(b, 16) for b in enc.split("encoding:")[1].strip().strip("[]").split(","))
words = " ".join("%08x" % int.from_bytes(data[i:i + 4], "little") for i in range(0, len(data), 4))
# The canonical text is what the disassembler prints for these bytes.
d = subprocess.run([a.llvm_mc, "--disassemble", "-arch=amdgcn", "-mcpu=" + mcpu],
input=" ".join("0x%02x" % b for b in data), capture_output=True, text=True)
text = next(l.strip() for l in d.stdout.splitlines() if l.strip() and not l.strip().startswith("."))
print("%s | %s" % (words, text))
if __name__ == "__main__":
main()
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Generates shader-transpiler/crates/gfx10-translate/src/opcodes.rs: the GFX10.3 (gfx1030)
instruction names for every opcode value of every encoding format the decoder handles.
The names come from the public LLVM AMDGPU disassembler (llvm-mc, Apache-2.0 WITH
LLVM-exception): for each format, an instruction word is built with each opcode value and
fixed, valid operand fields, and llvm-mc names it or rejects it. Only the resulting facts (opcode
number -> mnemonic) are committed; LLVM itself is not.
usage: gen_opcodes.py [--llvm-mc PATH] > shader-transpiler/crates/gfx10-translate/src/opcodes.rs
"""
import argparse
import concurrent.futures
import os
import subprocess
import sys
# (name, opcode bits, word builder, mask of word 0's format and opcode bits) per format.
# Builders place `op` in the format's opcode field; the other fields hold valid registers.
# Layouts: AMD "RDNA 2" instruction set reference.
FORMATS = [
# SOP2 opcodes from 0x60 and VOP2 opcodes from 0x3E are the prefixes of other formats.
("SOP2", 7, lambda op: [0x80000000 | (op << 23) | (2 << 8) | 1] if op < 0x60 else None, 0xFF800000),
("SOPK", 5, lambda op: [[0xB0000000 | (op << 23) | 0x10], [0xB0000000 | (op << 23) | 0x1801, 0x1]], 0xFF800000),
("SOP1", 8, lambda op: [0xBE800000 | (op << 8) | 2], 0xFF80FF00),
("SOPC", 7, lambda op: [0xBF000000 | (op << 16) | (2 << 8) | 1], 0xFFFF0000),
("SOPP", 7, lambda op: [0xBF800000 | (op << 16)], 0xFFFF0000),
("SMEM", 8, lambda op: [0xF4000000 | (op << 18) | 2, 0xFA000010], 0xFFFC0000),
# v_madmk/madak/fmamk/fmaak carry a literal constant after the instruction word.
("VOP2", 6, lambda op: [[(op << 25) | (2 << 9) | 0x101], [(op << 25) | (2 << 9) | 0x101, 0x3F800000]] if op < 0x3E else None,
0xFE000000),
("VOP1", 8, lambda op: [0x7E000000 | (op << 9) | 0x101], 0xFE01FE00),
("VOPC", 8, lambda op: [0x7C000000 | (op << 17) | (2 << 9) | 0x101], 0xFFFE0000),
("VOP3", 10, lambda op: [0xD4000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFFFF0000),
("VOP3P", 7, lambda op: [0xCC000000 | (op << 16), (0x103 << 18) | (0x102 << 9) | 0x101], 0xFC7F0000),
("VINTRP", 2, lambda op: [0xC8000000 | (op << 16) | 1], 0xFC030000),
("DS", 8, lambda op: [[0xD8000000 | (op << 18), w] for w in (0x00000201, 0x00000001, 0x00030201)], 0xFFFC0000),
("MUBUF", 7, lambda op: [0xE0000000 | ((op & 0x7F) << 18) | 0x2000, 0x80010001], 0xFDFC0000),
("MTBUF", 4, lambda op: [0xE8000000 | (op & 7) << 16 | (22 << 19) | 0x2000, 0x80010001 | ((op >> 3) << 21)], 0xFC070000),
("MIMG", 8, lambda op: [[0xF0000000 | ((op & 0x7F) << 18) | ((op >> 7) << 0) | (1 << 3) | (0xF << 8), w]
for w in (0x00820004, 0x00020004)], 0xFDFC0001),
("FLAT", 7, lambda op: [0xDC000000 | (op << 18), 0x007D0001], 0xFDFCC000),
("GLOBAL", 7, lambda op: [0xDC008000 | (op << 18), 0x007D0001], 0xFDFCC000),
]
def name_of(llvm_mc, words, mask, mcpu):
"""The mnemonic llvm-mc gives `words`, or None. A name counts only when llvm-mc reports no
invalid encoding and its first instruction is as long as `words` with the same format and
opcode bits (`mask`): for an invalid opcode, llvm-mc skips a word and decodes the next one as
an instruction of its own. Operand fields may be re-encoded, so they are not compared."""
data = b"".join(w.to_bytes(4, "little") for w in words)
text = " ".join("0x%02x" % b for b in data)
r = subprocess.run([llvm_mc, "--disassemble", "-show-encoding", "-arch=amdgcn", "-mcpu=" + mcpu], input=text,
capture_output=True, text=True)
if "invalid instruction encoding" in r.stderr:
return None
for line in r.stdout.splitlines():
if "encoding:" not in line:
continue
asm, enc = line.split("; encoding:")
encoded = bytes(int(b, 16) for b in enc.strip().strip("[]").split(","))
same = len(encoded) == len(data) and (int.from_bytes(encoded[:4], "little") & mask) == (words[0] & mask)
return asm.split()[0] if same else None
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
a = ap.parse_args()
version = subprocess.run([a.llvm_mc, "--version"], capture_output=True, text=True).stdout.split("\n")
version = next((v.strip() for v in version if "version" in v.lower()), "unknown")
jobs = [(fmt, op, build(op), mask) for fmt, bits, build, mask in FORMATS for op in range(1 << bits)]
def first_name(job):
# A builder gives one word list, or several variants of the operand fields to try in turn
# (llvm-mc rejects some opcodes unless their unused fields are zero).
if job[2] is None:
return None
variants = job[2] if isinstance(job[2][0], list) else [job[2]]
# gfx1030 first; the console compiler also emits a few GFX10.1 instructions that LLVM
# knows only for gfx1010 (v_mac_f32), so gaps are filled from there.
for mcpu in ("gfx1030", "gfx1010"):
for v in variants:
n = name_of(a.llvm_mc, v, job[3], mcpu)
if n:
return n
return None
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
names = list(pool.map(first_name, jobs))
out = ["// @generated by scripts/console-shader/gen_opcodes.py from %s (gfx1030, gaps from gfx1010)." % version,
"// Do not edit. Facts only: opcode number -> mnemonic, per encoding format, as named by the",
"// public LLVM AMDGPU disassembler (Apache-2.0 WITH LLVM-exception).", "",
"/// (opcode, mnemonic) pairs of one encoding format, sorted by opcode.", "pub type Table = &'static [(u16, &'static str)];", ""]
for fmt, _, _, _ in FORMATS:
rows = [(op, n) for (f, op, _, _), n in zip(jobs, names) if f == fmt and n]
out.append("pub static %s: Table = &[" % fmt)
for op, n in rows:
out.append(" (%d, \"%s\")," % (op, n))
out.append("];")
out.append("")
print("%s: %d opcodes" % (fmt, len(rows)), file=sys.stderr)
# MTBUF unified buffer formats (word 0 bits 25:19), named by the disassembler as format:[NAME].
def format_name(value):
words = [0xE8000000 | (value << 19) | (3 << 16) | 0x2000, 0x80000000]
text = " ".join("0x%02x" % b for w in words for b in w.to_bytes(4, "little"))
r = subprocess.run([a.llvm_mc, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
capture_output=True, text=True)
if "invalid instruction encoding" in r.stderr or "format:[" not in r.stdout:
return None
return r.stdout.split("format:[")[1].split("]")[0]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
formats = list(pool.map(format_name, range(128)))
out.append("/// MTBUF unified buffer formats: (value, name), as `format:[NAME]` prints them.")
out.append("pub static BUF_FORMATS: Table = &[")
for value, name in enumerate(formats):
if name and not name.isdigit():
out.append(" (%d, \"%s\")," % (value, name))
out.append("];")
out.append("")
print("BUF_FORMATS: %d" % sum(1 for f in formats if f and not f.isdigit()), file=sys.stderr)
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
main()
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Generates the translator's golden files: small VS/PS pairs written in GFX10.3 assembly,
assembled by the public LLVM assembler (llvm-mc), and translated by the Python prototype
(translate.py, the reference). The Rust translator must produce the same HLSL and layout.
Writes shader-transpiler/crates/gfx10-translate/tests/goldens/<case>.{vs,ps}.hex (instruction
words), .vs.hlsl, .ps.hlsl and .il. The programs are BetterXen's own, written for these tests.
usage: gen_translate_goldens.py [--llvm-mc PATH]
"""
import argparse
import os
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import translate # noqa: E402 (the prototype)
OUT = os.path.join(HERE, "..", "..", "shader-transpiler", "crates", "gfx10-translate", "tests", "goldens")
# VS reading a fetch-subroutine input and a constant buffer; PS sampling a texture.
TEXTURED_VS = """
s_swappc_b64 s[4:5], s[4:5]
s_load_dwordx4 s[12:15], s[8:9], 0x0
s_waitcnt lgkmcnt(0)
s_buffer_load_dwordx4 s[16:19], s[12:15], 0x0
s_waitcnt lgkmcnt(0)
v_mul_f32_e32 v0, s16, v4
v_fma_f32 v1, s17, v5, s19
v_mov_b32_e32 v2, 0
v_mov_b32_e32 v3, 1.0
exp pos0, v0, v1, v2, v3 done
exp param0, v6, v7, v2, v3
s_endpgm
"""
TEXTURED_PS = """
s_mov_b64 s[10:11], exec
s_wqm_b64 exec, exec
s_mov_b32 m0, s2
v_interp_p1_f32_e32 v2, v0, attr0.x
v_interp_p2_f32_e32 v2, v1, attr0.x
v_interp_p1_f32_e32 v3, v0, attr0.y
v_interp_p2_f32_e32 v3, v1, attr0.y
s_load_dwordx8 s[0:7], s[8:9], 0x20
s_load_dwordx4 s[12:15], s[20:21], 0x0
s_and_b64 exec, exec, s[10:11]
s_waitcnt lgkmcnt(0)
image_sample v[4:7], v[2:3], s[0:7], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D
s_waitcnt vmcnt(0)
v_mul_f32_e32 v4, v4, v4
exp mrt0, v4, v5, v6, v7 done vm
s_endpgm
"""
# The ALU families and single rules, in a PS.
ALU_VS = """
s_swappc_b64 s[4:5], s[4:5]
exp pos0, v4, v5, v6, v7 done
exp param0, v8, v9, v10, v11
s_endpgm
"""
ALU_PS = """
v_interp_p1_f32_e32 v2, v0, attr0.x
v_interp_p2_f32_e32 v2, v1, attr0.x
v_interp_mov_f32_e32 v3, p0, attr0.y
s_movk_i32 s20, 0x1234
s_mov_b32 s21, 0x3f800000
s_lshl_b32 s22, s20, 2
s_or_b32 s23, s22, 7
s_and_b32 s23, s23, s21
s_xor_b32 s23, s23, s20
s_mul_i32 s23, s23, s22
s_add_u32 s23, s23, 64
s_sub_u32 s23, s23, s20
s_lshr_b32 s23, s23, 4
s_min_u32 s24, s23, s22
s_max_u32 s24, s24, s20
s_brev_b32 s25, s24
s_bfe_u32 s26, s25, 0x100000
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 3
v_lshlrev_b32_e32 v4, 2, v2
v_lshrrev_b32_e32 v4, 16, v4
v_ashrrev_i32_e32 v4, 1, v4
v_and_b32_e32 v4, 0xff, v4
v_or_b32_e32 v4, v4, v3
v_xor_b32_e32 v4, v4, v2
v_sub_nc_u32_e32 v4, v4, v3
v_subrev_nc_u32_e32 v4, v4, v2
v_mul_u32_u24_e32 v4, v4, v3
v_min_u32_e32 v4, v4, v2
v_max_u32_e32 v4, v4, v3
v_mul_lo_u32 v4, v4, v2
v_mul_hi_u32 v4, v4, s25
v_lshlrev_b32_e64 v4, s24, v4
v_add_f32_e32 v5, 0.5, v2
v_mul_f32_e32 v5, 0x3e800000, v5
v_sub_f32_e32 v5, v5, v3
v_subrev_f32_e32 v5, v5, v3
v_max_f32_e32 v5, v5, v2
v_min_f32_e32 v5, v5, v3
v_add_f32_e64 v5, v5, -v2
v_mul_f32_e64 v5, -v5, v3
v_sub_f32_e64 v5, v5, v2
v_max_f32_e64 v5, v5, s21
v_fmac_f32_e32 v5, v2, v3
v_rcp_f32_e32 v6, v5
v_rsq_f32_e32 v6, v6
v_sqrt_f32_e32 v6, v6
v_floor_f32_e32 v6, v6
v_fract_f32_e32 v6, v6
v_exp_f32_e32 v6, v6
v_log_f32_e32 v6, v6
v_trunc_f32_e32 v6, v6
v_rndne_f32_e32 v6, v6
v_ceil_f32_e32 v6, v6
v_sin_f32_e32 v6, v6
v_cos_f32_e32 v6, v6
v_rcp_f32_e64 v6, -v6
v_cvt_f32_u32_e32 v7, v4
v_cvt_f32_i32_e32 v7, v4
v_cvt_i32_f32_e32 v8, v7
v_med3_f32 v7, v7, 0, 1.0
v_fma_f32 v7, -v7, v2, 1.0
v_mul_legacy_f32_e32 v7, v7, v3
v_cvt_pkrtz_f16_f32_e32 v9, v7, v6
v_fma_mixlo_f16 v10, v9, v2, v3 op_sel_hi:[1,0,0]
v_fma_mixhi_f16 v10, v9, v9, v10 op_sel_hi:[1,1,1]
v_mov_b32_e32 v11, s23
v_add_nc_u32_e32 v11, v11, v8
exp mrt0, v9, v9, v10, v10 done compr vm
s_endpgm
"""
# A VS without the fetch subroutine: vertex buffers through s[0:1], typed buffer loads, and an
# indexed load from a buffer bound through the root table.
BUFFERS_VS = """
s_load_dwordx4 s[12:15], s[0:1], 0x0
s_load_dwordx4 s[16:19], s[0:1], 0x10
s_load_dwordx4 s[20:23], s[8:9], 0x20
v_add_nc_u32_e32 v1, s2, v0
s_waitcnt lgkmcnt(0)
buffer_load_dwordx2 v[2:3], v1, s[12:15], 0 idxen
tbuffer_load_format_xyzw v[4:7], v1, s[16:19], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen offset:8
buffer_load_dwordx3 v[8:10], v1, s[12:15], 0 idxen offset:8
buffer_load_dwordx4 v[12:15], v0, s[20:23], 0 idxen
s_waitcnt vmcnt(0)
v_mov_b32_e32 v11, 1.0
exp pos0, v2, v3, v8, v11 done
exp param0, v4, v5, v6, v7
exp param1, v12, v13, v14, v15
s_endpgm
"""
BUFFERS_PS = """
v_interp_mov_f32_e32 v2, p0, attr1.x
v_interp_mov_f32_e32 v3, p0, attr1.w
v_interp_p1_f32_e32 v4, v0, attr0.z
v_interp_p2_f32_e32 v4, v1, attr0.z
exp mrt0, v2, v3, v4, off done vm
s_endpgm
"""
CASES = [("textured", TEXTURED_VS, TEXTURED_PS), ("alu", ALU_VS, ALU_PS), ("buffers", BUFFERS_VS, BUFFERS_PS)]
def assemble(llvm_mc, text):
r = subprocess.run([llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "-show-encoding"], input=text,
capture_output=True, text=True)
if r.returncode != 0:
sys.exit("llvm-mc failed:\n" + r.stderr)
data = bytearray()
for line in r.stdout.splitlines():
if "encoding:" in line:
data += bytes(int(b, 16) for b in line.split("encoding:")[1].strip().strip("[]").split(","))
return bytes(data)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc"))
a = ap.parse_args()
translate.LLVM_MC = a.llvm_mc
os.makedirs(OUT, exist_ok=True)
for name, vs_asm, ps_asm in CASES:
vs, ps = assemble(a.llvm_mc, vs_asm), assemble(a.llvm_mc, ps_asm)
vt, pt = translate.Translator("vs"), translate.Translator("ps")
vt.run(translate.disassemble(vs))
pt.run(translate.disassemble(ps))
vs_src, params = translate.build_vs(vt)
ps_src = translate.build_ps(pt, params)
il = ""
if vt.fetch_call:
il += "FETCH %d\n" % (max(vt.fetch_attrs) + 1 if vt.fetch_attrs else 0)
for sem, fmt, slot, off, n, kind in vt.inputs:
il += "ATTR %d %d %d %d\n" % (sem, translate.DXGI[fmt], slot, off)
for cb in sorted(vt.cbs | pt.cbs):
il += "USE CB %d\n" % cb
for tex in sorted(vt.textures | pt.textures):
il += "USE TEX %d\n" % tex
base = os.path.join(OUT, name)
for suffix, blob in ((".vs.hex", vs), (".ps.hex", ps)):
words = [int.from_bytes(blob[i:i + 4], "little") for i in range(0, len(blob), 4)]
open(base + suffix, "w").write(" ".join("%08x" % w for w in words) + "\n")
open(base + ".vs.hlsl", "w").write(vs_src)
open(base + ".ps.hlsl", "w").write(ps_src)
open(base + ".il", "w").write(il)
print("%s: VS %d words, PS %d words" % (name, len(vs) // 4, len(ps) // 4))
if __name__ == "__main__":
main()
+930
View File
@@ -0,0 +1,930 @@
#!/usr/bin/env python3
"""Experimental RDNA 2 (gfx1030) -> HLSL translator for straight-line console VS/PS pairs.
Input: the VS and PS of a console graphics pipeline, each either a raw GPU instruction blob
(from a deserialized pipeline) or a console shader container (DXBC with an XBCH record).
Output, in --out: <vs>_<ps>.vs.hlsl / .ps.hlsl, compiled .vs.dxil / .ps.dxil (when --dxc is
given), and <vs>_<ps>.il, the input layout the shim creates the host pipeline with.
Reference implementation for shader-transpiler/crates/gfx10-translate, which replaces it: the
crate's golden tests compare against this script's output (see that crate's README).
Model (inferences from the console compiler's listings and the target build's code, AGENTS.md
section 6):
* Code starts after a header of 12-byte `v_nop` + literal records (VOP3 word top half 0xD580).
* VS user data: s[0:1] = vertex-buffer descriptor table (16-byte V#s), s2 = base vertex.
Both stages: s8 = 32-bit pointer to root parameter 0's descriptor table (32-byte entries).
* A buffer V# loaded from the root table is a constant buffer; an 8-dword T# is a texture.
* PS v0:v1 are barycentrics; `v_interp_p1/p2 ... attrN.c` is attribute N, component c.
* VS `exp paramN` pairs with PS `attrN`; `exp pos0` is the position.
HLSL resources use register space 100 (+ root parameter index); the shim widens each title root
signature with overlapping ranges in that space so table entry k is register k.
Only straight-line code with the instructions below is accepted; anything else fails loudly.
"""
import argparse
import json
import os
import re
import struct
import zlib
import subprocess
import sys
LLVM_MC = os.environ.get("LLVM_MC", "/opt/homebrew/opt/llvm/bin/llvm-mc")
DXGI = {"R32_UINT": 42, "R32G32_UINT": 17, "R32G32B32_UINT": 7, "R32G32B32A32_UINT": 3,
"R8G8B8A8_UNORM": 28, "R16G16_FLOAT": 34, "R16G16B16A16_FLOAT": 10, "R32G32_FLOAT": 16}
TBUF_FMT = {"BUF_FMT_8_8_8_8_UNORM": ("R8G8B8A8_UNORM", 4, "float"),
"BUF_FMT_16_16_FLOAT": ("R16G16_FLOAT", 2, "float"),
"BUF_FMT_16_16_16_16_FLOAT": ("R16G16B16A16_FLOAT", 4, "float"),
"BUF_FMT_32_32_FLOAT": ("R32G32_FLOAT", 2, "float")}
class Unsupported(Exception):
pass
def container_code(blob):
"""The GPU code of one stage from a console shader container.
A container is a DXBC file whose DXIL part carries no bitcode; the console code is in an
`XBCH` record: magic, version, compressed size (u64), uncompressed size (u64), then a zlib
stream. It inflates to an `FSSM` block: a 16-byte header (magic, version, size), then
offsets relative to the end of that header. One of the per-stage slots at 0x18..0x78 is not
0xDEADBEEF filler and locates the stage record, whose first two u64 fields are the code
offset and the code size. (Layout inferred from containers of a project-authorized build.)
"""
at = blob.find(b"XBCH")
if at < 0:
raise Unsupported("container has no XBCH record")
csize, usize = struct.unpack_from("<QQ", blob, at + 8)
fssm = zlib.decompress(blob[at + 24:at + 24 + csize])
if len(fssm) != usize or fssm[:4] != b"FSSM":
raise Unsupported("XBCH record does not inflate to an FSSM block")
base = 16
record = None
for slot in range(0x18, 0x78, 8):
(v,) = struct.unpack_from("<Q", fssm, slot)
if v != 0xDEADBEEFDEADBEEF:
record = base + v
break
if record is None:
raise Unsupported("FSSM block has no stage record")
code_off, code_size = struct.unpack_from("<QQ", fssm, record)
code = fssm[base + code_off:base + code_off + code_size]
if len(code) < 12 or struct.unpack_from("<I", code, 0)[0] >> 16 != 0xD580:
raise Unsupported("stage code does not start with the expected header records")
return code
def code_words(blob):
if blob[:4] == b"DXBC":
blob = container_code(blob)
off = 0
while off + 12 <= len(blob) and struct.unpack_from("<I", blob, off)[0] >> 16 == 0xD580:
off += 12
return blob[off:]
def disassemble(blob):
body = code_words(blob)
text = " ".join("0x%02x" % b for b in body)
r = subprocess.run([LLVM_MC, "--disassemble", "-arch=amdgcn", "-mcpu=gfx1030"], input=text,
capture_output=True, text=True)
out = []
for line in r.stdout.splitlines():
line = line.split(";")[0].strip()
if not line or line.startswith("."):
continue
out.append(line)
if line == "s_endpgm":
break
if "s_endpgm" not in out:
raise Unsupported("no s_endpgm in decoded code")
return out
def split_ops(rest):
ops, depth, cur = [], 0, ""
for ch in rest:
if ch in "[(":
depth += 1
elif ch in "])":
depth -= 1
if ch == "," and depth == 0:
ops.append(cur.strip())
cur = ""
else:
cur += ch
if cur.strip():
ops.append(cur.strip())
return ops
def reg_range(op):
m = re.fullmatch(r"([sv])\[(\d+):(\d+)\]", op)
if m:
return m.group(1), int(m.group(2)), int(m.group(3))
m = re.fullmatch(r"([sv])(\d+)", op)
if m:
return m.group(1), int(m.group(2)), int(m.group(2))
return None
class Translator:
def __init__(self, stage):
self.stage = stage
self.lines = []
self.sprov = {} # sgpr -> provenance tuple
self.cbs = set() # table indices used as constant buffers
self.textures = set()
self.inputs = [] # VS: (semantic index, fmt, slot, offset, ncomp, kind)
self.attrs = set() # PS attribute indices read
self.exports = {} # name -> list of 4 expressions
self.used_v = set()
self.used_s = set()
self.written_v = set()
self.fetch_call = False # VS: attributes arrive in v4.. from the vertex-fetch subroutine
self.fetch_attrs = set() # attribute indices read that way
self.nexp = 0
self.ntmp = 0
self.tmps = []
# ---- operands -------------------------------------------------------------
def src(self, op, as_float=False):
"""HLSL expression (uint) for a 32-bit source operand."""
neg = False
if op.startswith("-") and not re.fullmatch(r"-\d+(\.\d+)?", op):
neg, op = True, op[1:]
m = re.fullmatch(r"neg\((.+)\)", op)
if m:
neg, op = True, m.group(1)
r = reg_range(op)
if r and r[1] == r[2]:
kind, n, _ = r
(self.used_v if kind == "v" else self.used_s).add(n)
if kind == "v" and self.fetch_call and n >= 4 and n not in self.written_v:
self.fetch_attrs.add((n - 4) // 4)
e = "%s%d" % (kind, n)
elif re.fullmatch(r"-?\d+\.\d+", op):
e = "asuint(%sf)" % op
elif re.fullmatch(r"0x[0-9a-fA-F]+", op):
e = "0x%xu" % int(op, 16)
elif re.fullmatch(r"-?\d+", op):
v = int(op)
e = "%du" % (v & 0xFFFFFFFF)
else:
raise Unsupported("operand %r" % op)
if neg:
e = "(asuint(-asfloat(%s)))" % e
return "asfloat(%s)" % e if as_float else e
def dst(self, op):
r = reg_range(op)
if not r or r[1] != r[2]:
raise Unsupported("destination %r" % op)
(self.used_v if r[0] == "v" else self.used_s).add(r[1])
if r[0] == "v":
self.written_v.add(r[1])
return "%s%d" % (r[0], r[1])
def emit(self, s):
self.lines.append(" " + s)
# ---- instructions -----------------------------------------------------------
def run(self, insts):
ignore = re.compile(r"^(s_waitcnt|s_clause|s_inst_prefetch|s_setprio|s_nop|s_wqm_b64|s_endpgm|v_nop)\b")
for line in insts:
if ignore.match(line):
continue
parts = line.split(None, 1)
op, rest = parts[0], parts[1] if len(parts) > 1 else ""
mods = ""
ops = split_ops(rest)
# modifiers after operands (e.g. "0 idxen offset:12", "dmask:0xf dim:...")
if op.endswith("_e64") and re.search(r"\b(clamp|mul:|div:|op_sel|abs\()", rest):
raise Unsupported("modifier in %r" % line)
handler = getattr(self, "i_" + op, None)
if handler is None:
raise Unsupported("instruction %r" % line)
handler(ops, line)
def exec_write(self, ops):
return ops and ops[0].startswith("exec")
def i_s_mov_b32(self, ops, line):
if ops[0] == "m0":
return
r = reg_range(ops[0])
s = reg_range(ops[1])
if s and s[0] == "s":
self.sprov[r[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
elif re.fullmatch(r"-?(0x[0-9a-fA-F]+|\d+)", ops[1]):
self.sprov[r[1]] = ("imm", int(ops[1], 0) & 0xFFFFFFFF)
else:
self.sprov[r[1]] = ("unknown",)
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
def i_s_swappc_b64(self, ops, line):
# The call to the vertex-fetch subroutine the console runtime builds from the pipeline's
# input layout: on return, input element k is in v[4+4k : 7+4k] (observed: three-element
# layouts read v4..v15 in groups of four). The host input assembler does the fetch.
if self.stage != "vs" or self.lines or ops != ["s[4:5]", "s[4:5]"]:
raise Unsupported(line)
self.fetch_call = True
def i_s_mov_b64(self, ops, line):
if ops[0] == "exec" or ops[1] == "exec":
return
d = reg_range(ops[0])
s = reg_range(ops[1])
if s:
self.sprov[d[1]] = self.sprov.get(s[1], ("sgpr", s[1]))
self.sprov[d[1] + 1] = self.sprov.get(s[1] + 1, ("sgpr", s[1] + 1))
else:
v = int(ops[1], 0)
self.sprov[d[1]] = ("imm", v & 0xFFFFFFFF)
self.sprov[d[1] + 1] = ("imm", (v >> 32) & 0xFFFFFFFF)
def i_s_and_b64(self, ops, line):
# `s_and_b64 exec, exec, s[n:n+1]` restores the execution mask saved before s_wqm_b64
# (helper-pixel bookkeeping); it has no HLSL counterpart.
if ops[0] != "exec" or ops[1] != "exec":
raise Unsupported(line)
def i_s_movk_i32(self, ops, line):
r = reg_range(ops[0])
self.sprov[r[1]] = ("imm", int(ops[1], 0) & 0xFFFFFFFF)
self.emit("%s = %du;" % (self.dst(ops[0]), int(ops[1], 0) & 0xFFFFFFFF))
def i_s_lshl_b32(self, ops, line):
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
self.emit("%s = %s << (%s & 31u);" % (self.dst(ops[0]), self.src(ops[1]), self.src(ops[2])))
def i_s_bfe_u32(self, ops, line):
pass # masks the high half of a copied table pointer; provenance is unchanged
def table_of(self, base):
b = reg_range(base)
p = self.sprov.get(b[1], ("sgpr", b[1]))
if p == ("sgpr", 0) and self.stage == "vs":
return "vbtable"
if p == ("sgpr", 8):
return "root0"
raise Unsupported("descriptor load from %r (provenance %r)" % (base, p))
def smem_load(self, ops, line, ndw):
d = reg_range(ops[0])
try:
table = self.table_of(ops[1])
except Unsupported:
if ndw != 4:
raise
for i in range(ndw):
self.sprov[d[1] + i] = ("smp", ops[1])
return
off = 0 if ops[2] == "null" else int(ops[2], 0)
if table == "vbtable":
prov = ("vb", off // 16)
elif ndw == 4:
prov = ("cb", off // 32)
elif ndw == 8:
prov = ("tex", off // 32)
else:
raise Unsupported(line)
for i in range(ndw):
self.sprov[d[1] + i] = prov
def i_s_load_dwordx4(self, ops, line):
self.smem_load(ops, line, 4)
def i_s_load_dwordx8(self, ops, line):
self.smem_load(ops, line, 8)
def s_buffer_load(self, ops, line, ndw):
d = reg_range(ops[0])
desc = reg_range(ops[1])
p = self.sprov.get(desc[1])
if not p or p[0] != "cb":
raise Unsupported("s_buffer_load from %r" % (p,))
cb = p[1]
self.cbs.add(cb)
off = 0 if ops[2] == "null" else int(ops[2], 0)
for i in range(ndw):
word = off // 4 + i
self.sprov[d[1] + i] = ("cbword", cb, word)
self.emit("s%d = cb%d_word(%d);" % (d[1] + i, cb, word))
self.used_s.add(d[1] + i)
def i_s_buffer_load_dword(self, ops, line):
self.s_buffer_load(ops, line, 1)
def i_s_buffer_load_dwordx2(self, ops, line):
self.s_buffer_load(ops, line, 2)
def i_s_buffer_load_dwordx4(self, ops, line):
self.s_buffer_load(ops, line, 4)
def i_s_buffer_load_dwordx8(self, ops, line):
self.s_buffer_load(ops, line, 8)
def i_s_buffer_load_dwordx16(self, ops, line):
self.s_buffer_load(ops, line, 16)
# vertex fetch -> input layout element
def vb_slot(self, op):
p = self.sprov.get(reg_range(op)[1])
if not p or p[0] != "vb":
raise Unsupported("vertex fetch through %r" % (p,))
return p[1]
def fetch(self, ops, line, ncomp, fmt, kind):
if "idxen" not in line or "offen" in line:
raise Unsupported(line)
d = reg_range(ops[0])
p = self.sprov.get(reg_range(ops[2])[1])
if p and p[0] == "cb" and "offset:" not in line:
# An indexed load from a buffer bound through the root table: element i is 16 bytes.
cb = p[1]
self.cbs.add(cb)
idx = self.src(ops[1])
for i in range(d[2] - d[1] + 1):
self.emit("t%d_%d = cb%d[%s].%s;" % (self.ntmp, i, cb, idx, "xyzw"[i]))
for i in range(d[2] - d[1] + 1):
self.emit("%s = t%d_%d;" % (self.dst("v%d" % (d[1] + i)), self.ntmp, i))
self.tmps.append((self.ntmp, d[2] - d[1] + 1))
self.ntmp += 1
return
slot = self.vb_slot(ops[2])
m = re.search(r"offset:(\d+)", line)
off = int(m.group(1)) if m else 0
sem = len(self.inputs)
self.inputs.append((sem, fmt, slot, off, ncomp, kind))
comps = "xyzw"
for i in range(d[2] - d[1] + 1):
src = "in%d.%s" % (sem, comps[i])
self.emit("v%d = %s;" % (d[1] + i, "asuint(%s)" % src if kind == "float" else src))
self.used_v.add(d[1] + i)
def i_buffer_load_dword(self, ops, line):
self.fetch(ops, line, 1, "R32_UINT", "uint")
def i_buffer_load_dwordx2(self, ops, line):
self.fetch(ops, line, 2, "R32G32_UINT", "uint")
def i_buffer_load_dwordx3(self, ops, line):
self.fetch(ops, line, 3, "R32G32B32_UINT", "uint")
def i_buffer_load_dwordx4(self, ops, line):
self.fetch(ops, line, 4, "R32G32B32A32_UINT", "uint")
def i_tbuffer_load_format_xyzw(self, ops, line):
m = re.search(r"format:\[(\w+)\]", line)
if not m or m.group(1) not in TBUF_FMT:
raise Unsupported(line)
fmt, n, kind = TBUF_FMT[m.group(1)]
self.fetch(ops, line, 4, fmt, kind)
# ALU
def vop2f(self, ops, expr):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr % (a, b)))
def i_v_mul_f32_e32(self, ops, line):
self.vop2f(ops, "%s * %s")
i_v_mul_f32_e64 = i_v_mul_f32_e32
def i_v_add_f32_e32(self, ops, line):
self.vop2f(ops, "%s + %s")
i_v_add_f32_e64 = i_v_add_f32_e32
def i_v_sub_f32_e32(self, ops, line):
self.vop2f(ops, "%s - %s")
def i_v_max_f32_e32(self, ops, line):
self.vop2f(ops, "max(%s, %s)")
def i_v_min_f32_e32(self, ops, line):
self.vop2f(ops, "min(%s, %s)")
def i_v_fmac_f32_e32(self, ops, line):
d = self.dst(ops[0])
self.emit("%s = asuint(mad(%s, %s, asfloat(%s)));" % (d, self.src(ops[1], True), self.src(ops[2], True), d))
# ---- simple ALU, generated from (name, expression) tables ---------------------------------
def _vop2u(self, ops, expr):
a, b = self.src(ops[1]), self.src(ops[2])
self.emit("%s = %s;" % (self.dst(ops[0]), expr.format(a=a, b=b)))
def _vop2f(self, ops, expr):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr.format(a=a, b=b)))
def _vop1f(self, ops, expr):
self.emit("%s = asuint(%s);" % (self.dst(ops[0]), expr.format(a=self.src(ops[1], True))))
def _sop2(self, ops, expr):
a, b = self.src(ops[1]), self.src(ops[2])
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
self.emit("%s = %s;" % (self.dst(ops[0]), expr.format(a=a, b=b)))
def i_v_lshlrev_b32_e32(self, ops, line):
self._vop2u(ops, '({b} << ({a} & 31u))')
def i_v_lshlrev_b32_e64(self, ops, line):
self._vop2u(ops, '({b} << ({a} & 31u))')
def i_v_lshlrev_b32(self, ops, line):
self._vop2u(ops, '({b} << ({a} & 31u))')
def i_v_lshrrev_b32_e32(self, ops, line):
self._vop2u(ops, '({b} >> ({a} & 31u))')
def i_v_lshrrev_b32_e64(self, ops, line):
self._vop2u(ops, '({b} >> ({a} & 31u))')
def i_v_lshrrev_b32(self, ops, line):
self._vop2u(ops, '({b} >> ({a} & 31u))')
def i_v_ashrrev_i32_e32(self, ops, line):
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
def i_v_ashrrev_i32_e64(self, ops, line):
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
def i_v_ashrrev_i32(self, ops, line):
self._vop2u(ops, '(uint)((int){b} >> ({a} & 31u))')
def i_v_and_b32_e32(self, ops, line):
self._vop2u(ops, '({a} & {b})')
def i_v_and_b32_e64(self, ops, line):
self._vop2u(ops, '({a} & {b})')
def i_v_and_b32(self, ops, line):
self._vop2u(ops, '({a} & {b})')
def i_v_or_b32_e32(self, ops, line):
self._vop2u(ops, '({a} | {b})')
def i_v_or_b32_e64(self, ops, line):
self._vop2u(ops, '({a} | {b})')
def i_v_or_b32(self, ops, line):
self._vop2u(ops, '({a} | {b})')
def i_v_xor_b32_e32(self, ops, line):
self._vop2u(ops, '({a} ^ {b})')
def i_v_xor_b32_e64(self, ops, line):
self._vop2u(ops, '({a} ^ {b})')
def i_v_xor_b32(self, ops, line):
self._vop2u(ops, '({a} ^ {b})')
def i_v_sub_nc_u32_e32(self, ops, line):
self._vop2u(ops, '({a} - {b})')
def i_v_sub_nc_u32_e64(self, ops, line):
self._vop2u(ops, '({a} - {b})')
def i_v_sub_nc_u32(self, ops, line):
self._vop2u(ops, '({a} - {b})')
def i_v_subrev_nc_u32_e32(self, ops, line):
self._vop2u(ops, '({b} - {a})')
def i_v_subrev_nc_u32_e64(self, ops, line):
self._vop2u(ops, '({b} - {a})')
def i_v_subrev_nc_u32(self, ops, line):
self._vop2u(ops, '({b} - {a})')
def i_v_mul_u32_u24_e32(self, ops, line):
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
def i_v_mul_u32_u24_e64(self, ops, line):
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
def i_v_mul_u32_u24(self, ops, line):
self._vop2u(ops, '(({a} & 0xffffffu) * ({b} & 0xffffffu))')
def i_v_min_u32_e32(self, ops, line):
self._vop2u(ops, 'min({a}, {b})')
def i_v_min_u32_e64(self, ops, line):
self._vop2u(ops, 'min({a}, {b})')
def i_v_min_u32(self, ops, line):
self._vop2u(ops, 'min({a}, {b})')
def i_v_max_u32_e32(self, ops, line):
self._vop2u(ops, 'max({a}, {b})')
def i_v_max_u32_e64(self, ops, line):
self._vop2u(ops, 'max({a}, {b})')
def i_v_max_u32(self, ops, line):
self._vop2u(ops, 'max({a}, {b})')
def i_v_mul_lo_u32_e32(self, ops, line):
self._vop2u(ops, '({a} * {b})')
def i_v_mul_lo_u32_e64(self, ops, line):
self._vop2u(ops, '({a} * {b})')
def i_v_mul_lo_u32(self, ops, line):
self._vop2u(ops, '({a} * {b})')
def i_v_mul_hi_u32_e32(self, ops, line):
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
def i_v_mul_hi_u32_e64(self, ops, line):
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
def i_v_mul_hi_u32(self, ops, line):
self._vop2u(ops, '(uint)(((uint64_t){a} * (uint64_t){b}) >> 32)')
def i_v_max_f32_e64(self, ops, line):
self._vop2f(ops, 'max({a}, {b})')
def i_v_min_f32_e64(self, ops, line):
self._vop2f(ops, 'min({a}, {b})')
def i_v_sub_f32_e64(self, ops, line):
self._vop2f(ops, '({a} - {b})')
def i_v_subrev_f32_e32(self, ops, line):
self._vop2f(ops, '({b} - {a})')
def i_v_subrev_f32_e64(self, ops, line):
self._vop2f(ops, '({b} - {a})')
def i_v_rcp_f32_e32(self, ops, line):
self._vop1f(ops, '(1.0f / {a})')
def i_v_rcp_f32_e64(self, ops, line):
self._vop1f(ops, '(1.0f / {a})')
def i_v_rsq_f32_e32(self, ops, line):
self._vop1f(ops, 'rsqrt({a})')
def i_v_rsq_f32_e64(self, ops, line):
self._vop1f(ops, 'rsqrt({a})')
def i_v_sqrt_f32_e32(self, ops, line):
self._vop1f(ops, 'sqrt({a})')
def i_v_sqrt_f32_e64(self, ops, line):
self._vop1f(ops, 'sqrt({a})')
def i_v_floor_f32_e32(self, ops, line):
self._vop1f(ops, 'floor({a})')
def i_v_floor_f32_e64(self, ops, line):
self._vop1f(ops, 'floor({a})')
def i_v_fract_f32_e32(self, ops, line):
self._vop1f(ops, 'frac({a})')
def i_v_fract_f32_e64(self, ops, line):
self._vop1f(ops, 'frac({a})')
def i_v_exp_f32_e32(self, ops, line):
self._vop1f(ops, 'exp2({a})')
def i_v_exp_f32_e64(self, ops, line):
self._vop1f(ops, 'exp2({a})')
def i_v_log_f32_e32(self, ops, line):
self._vop1f(ops, 'log2({a})')
def i_v_log_f32_e64(self, ops, line):
self._vop1f(ops, 'log2({a})')
def i_v_trunc_f32_e32(self, ops, line):
self._vop1f(ops, 'trunc({a})')
def i_v_trunc_f32_e64(self, ops, line):
self._vop1f(ops, 'trunc({a})')
def i_v_rndne_f32_e32(self, ops, line):
self._vop1f(ops, 'round({a})')
def i_v_rndne_f32_e64(self, ops, line):
self._vop1f(ops, 'round({a})')
def i_v_ceil_f32_e32(self, ops, line):
self._vop1f(ops, 'ceil({a})')
def i_v_ceil_f32_e64(self, ops, line):
self._vop1f(ops, 'ceil({a})')
def i_v_cvt_f32_u32_e32(self, ops, line):
self._vop1f(ops, '(float)asuint({a})')
def i_v_cvt_f32_u32_e64(self, ops, line):
self._vop1f(ops, '(float)asuint({a})')
def i_v_cvt_f32_i32_e32(self, ops, line):
self._vop1f(ops, '(float)asint({a})')
def i_v_cvt_f32_i32_e64(self, ops, line):
self._vop1f(ops, '(float)asint({a})')
def i_v_sin_f32_e32(self, ops, line):
self._vop1f(ops, 'sin({a} * 6.2831853f)')
def i_v_sin_f32_e64(self, ops, line):
self._vop1f(ops, 'sin({a} * 6.2831853f)')
def i_v_cos_f32_e32(self, ops, line):
self._vop1f(ops, 'cos({a} * 6.2831853f)')
def i_v_cos_f32_e64(self, ops, line):
self._vop1f(ops, 'cos({a} * 6.2831853f)')
def i_s_or_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} | {b})')
def i_s_and_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} & {b})')
def i_s_xor_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} ^ {b})')
def i_s_mul_i32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} * {b})')
def i_s_add_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} + {b})')
def i_s_sub_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} - {b})')
def i_s_lshr_b32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, '({a} >> ({b} & 31u))')
def i_s_min_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, 'min({a}, {b})')
def i_s_max_u32(self, ops, line):
if ops[0].startswith('exec'):
raise Unsupported(line)
self._sop2(ops, 'max({a}, {b})')
def i_s_brev_b32(self, ops, line):
self.sprov[reg_range(ops[0])[1]] = ("unknown",)
self.emit("%s = reversebits(%s);" % (self.dst(ops[0]), self.src(ops[1])))
def i_s_setreg_imm32_b32(self, ops, line):
pass # mode register (rounding, denormals): the host defaults are used
def i_v_cvt_i32_f32_e32(self, ops, line):
self.emit("%s = (uint)(int)%s;" % (self.dst(ops[0]), self.src(ops[1], True)))
def i_v_med3_f32(self, ops, line):
a, b, c = (self.src(o, True) for o in ops[1:4])
self.emit("%s = asuint(max(min(%s, %s), min(max(%s, %s), %s)));" % (self.dst(ops[0]), a, b, a, b, c))
def i_v_mul_legacy_f32_e32(self, ops, line):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = asuint((%s == 0.0f || %s == 0.0f) ? 0.0f : %s * %s);" % (self.dst(ops[0]), a, b, a, b))
i_v_mul_legacy_f32_e64 = i_v_mul_legacy_f32_e32
def i_v_cvt_pkrtz_f16_f32_e32(self, ops, line):
a, b = self.src(ops[1], True), self.src(ops[2], True)
self.emit("%s = f32tof16(%s) | (f32tof16(%s) << 16);" % (self.dst(ops[0]), a, b))
i_v_cvt_pkrtz_f16_f32_e64 = i_v_cvt_pkrtz_f16_f32_e32
def i_v_interp_mov_f32_e32(self, ops, line):
m = re.fullmatch(r"attr(\d+)\.([xyzw])", ops[2])
if not m:
raise Unsupported(line)
n = int(m.group(1))
self.attrs.add(n)
self.emit("%s = asuint(attr%d.%s);" % (self.dst(ops[0]), n, m.group(2)))
def i_v_fma_f32(self, ops, line):
self.emit("%s = asuint(mad(%s, %s, %s));" % (self.dst(ops[0]), self.src(ops[1], True),
self.src(ops[2], True), self.src(ops[3], True)))
def i_v_mov_b32_e32(self, ops, line):
self.emit("%s = %s;" % (self.dst(ops[0]), self.src(ops[1])))
def i_v_add_nc_u32_e32(self, ops, line):
# only the vertex-index computation uses it here; the index itself is the IA's job
if self.stage == "vs":
return
self.emit("%s = %s + %s;" % (self.dst(ops[0]), self.src(ops[1]), self.src(ops[2])))
def fma_mix(self, ops, line, hi):
m = re.search(r"op_sel_hi:\[(\d),(\d),(\d)\]", line)
if "op_sel:" in line or not m:
raise Unsupported(line)
srcs = []
for i, sel in enumerate(m.groups()):
o = ops[1 + i].split()[0]
neg = False
mm = re.fullmatch(r"neg\((.+)\)", o)
if mm:
neg, o = True, mm.group(1)
e = self.src(o)
f = "f16tof32(%s & 0xffffu)" % e if sel == "1" else "asfloat(%s)" % e
srcs.append("(-%s)" % f if neg else f)
d = self.dst(ops[0])
val = "f32tof16(mad(%s, %s, %s))" % tuple(srcs)
if hi:
self.emit("%s = (%s & 0xffffu) | (%s << 16);" % (d, d, val))
else:
self.emit("%s = (%s & 0xffff0000u) | %s;" % (d, d, val))
def i_v_fma_mixlo_f16(self, ops, line):
self.fma_mix(ops, line, False)
def i_v_fma_mixhi_f16(self, ops, line):
self.fma_mix(ops, line, True)
# PS interpolation
def i_v_interp_p1_f32_e32(self, ops, line):
pass
def i_v_interp_p2_f32_e32(self, ops, line):
m = re.fullmatch(r"attr(\d+)\.([xyzw])", ops[2])
if not m:
raise Unsupported(line)
n = int(m.group(1))
self.attrs.add(n)
self.emit("%s = asuint(attr%d.%s);" % (self.dst(ops[0]), n, m.group(2)))
def i_image_sample(self, ops, line):
d = reg_range(ops[0])
c = reg_range(ops[1])
t = self.sprov.get(reg_range(ops[2])[1])
m = re.search(r"dmask:(0x[0-9a-f]+)", line)
if not t or t[0] != "tex" or "dim:SQ_RSRC_IMG_2D" not in line or not m:
raise Unsupported(line)
mask = int(m.group(1), 16)
comps = [c_ for i, c_ in enumerate("xyzw") if mask & (1 << i)]
if len(comps) != d[2] - d[1] + 1:
raise Unsupported("dmask and destination size differ: " + line)
self.textures.add(t[1])
self.used_v.update([c[1], c[1] + 1])
fn = "SampleLevel(smp0, float2(asfloat(v%d), asfloat(v%d)), 0)" if line.startswith("image_sample_lz") else \
"Sample(smp0, float2(asfloat(v%d), asfloat(v%d)))"
self.emit("{ float4 r = tex%d.%s;" % (t[1], fn % (c[1], c[1] + 1)))
for i, comp in enumerate(comps):
self.emit(" v%d = asuint(r.%s);" % (d[1] + i, comp))
self.used_v.add(d[1] + i)
self.emit("}")
i_image_sample_lz = i_image_sample
def i_exp(self, ops, line):
target = ops[0]
vals = [o.split()[0] for o in ops[1:5]]
compr = " compr" in line
if compr:
a, b = self.src(vals[0]), self.src(vals[2])
ex = ["f16tof32(%s & 0xffffu)" % a, "f16tof32(%s >> 16)" % a,
"f16tof32(%s & 0xffffu)" % b, "f16tof32(%s >> 16)" % b]
else:
ex = ["0.0f" if v == "off" else self.src(v, True) for v in vals]
# registers are reused after an export: take the values now
name = "exp%d_%s" % (self.nexp, target)
self.nexp += 1
self.emit("float4 %s = float4(%s);" % (name, ", ".join(ex)))
self.exports[target] = ["%s.%s" % (name, c) for c in "xyzw"]
# ---- output -----------------------------------------------------------------
def resources(self):
out = []
for cb in sorted(self.cbs):
out.append("cbuffer CB%d : register(b%d, space100) { uint4 cb%d[4096]; };" % (cb, cb, cb))
out.append("uint cb%d_word(uint w) { return cb%d[w >> 2][w & 3]; }" % (cb, cb))
for t in sorted(self.textures):
out.append("Texture2D<float4> tex%d : register(t%d, space100);" % (t, t))
if self.textures:
out.append("SamplerState smp0 : register(s0, space100);")
return out
def regs(self):
decl = []
for n in sorted(self.used_v):
k = (n - 4) // 4
if self.fetch_call and n >= 4 and k in self.fetch_attrs:
decl.append("uint v%d = asuint(a%d.%s);" % (n, k, "xyzw"[(n - 4) % 4]))
else:
decl.append("uint v%d = 0;" % n)
decl += ["uint s%d = 0;" % n for n in sorted(self.used_s)]
for n, count in self.tmps:
decl += ["uint t%d_%d = 0;" % (n, i) for i in range(count)]
return [" " + d for d in decl]
def build_vs(t):
ins = ["float4 a%d : ATTR%d" % (k, k) for k in sorted(t.fetch_attrs)]
for sem, fmt, slot, off, n, kind in t.inputs:
ty = ("float%d" if kind == "float" else "uint%d") % n if n > 1 else ("float" if kind == "float" else "uint")
ins.append("%s in%d : ATTR%d" % (ty, sem, sem))
params = sorted(k for k in t.exports if k.startswith("param"))
outs = ["float4 pos : SV_Position"] + ["float4 %s : PARAM%s" % (p, p[5:]) for p in params]
src = t.resources()
src.append("struct VSOut { %s; };" % "; ".join(outs))
src.append("VSOut main(%s) {" % ", ".join(ins))
src += t.regs() + t.lines
src.append(" VSOut o;")
pos = t.exports.get("pos0")
if not pos:
raise Unsupported("VS exports no position")
src.append(" o.pos = float4(%s);" % ", ".join(pos))
for p in params:
src.append(" o.%s = float4(%s);" % (p, ", ".join(t.exports[p])))
src.append(" return o;\n}")
return "\n".join(src) + "\n", params
def build_ps(t, vs_params):
for a in t.attrs:
if "param%d" % a not in vs_params:
raise Unsupported("PS reads attr%d that the VS does not export" % a)
ins = ["float4 pos : SV_Position"] + ["float4 attr%s : PARAM%s" % (p[5:], p[5:]) for p in vs_params]
if "mrt0" not in t.exports:
raise Unsupported("PS exports no mrt0")
src = t.resources()
src.append("float4 main(%s) : SV_Target0 {" % ", ".join(ins))
src += t.regs() + t.lines
src.append(" return float4(%s);\n}" % ", ".join(t.exports["mrt0"]))
return "\n".join(src) + "\n"
def fnv1a(data):
h = 1469598103934665603
for b in data:
h = ((h ^ b) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
return "%016x" % h
def main():
ap = argparse.ArgumentParser()
ap.add_argument("vs")
ap.add_argument("ps")
ap.add_argument("--out", required=True)
ap.add_argument("--dxc", help="command prefix that runs a Windows dxc.exe (e.g. a wine wrapper)")
a = ap.parse_args()
vsb, psb = open(a.vs, "rb").read(), open(a.ps, "rb").read()
key = "%s_%s" % (fnv1a(vsb), fnv1a(psb))
vt, pt = Translator("vs"), Translator("ps")
vt.run(disassemble(vsb))
pt.run(disassemble(psb))
vs_src, params = build_vs(vt)
ps_src = build_ps(pt, params)
os.makedirs(a.out, exist_ok=True)
base = os.path.join(a.out, key)
open(base + ".vs.hlsl", "w").write(vs_src)
open(base + ".ps.hlsl", "w").write(ps_src)
with open(base + ".il", "w") as f:
if vt.fetch_call:
f.write("FETCH %d\n" % (max(vt.fetch_attrs) + 1 if vt.fetch_attrs else 0))
for sem, fmt, slot, off, n, kind in vt.inputs:
f.write("ATTR %d %d %d %d\n" % (sem, DXGI[fmt], slot, off))
for cb in sorted(vt.cbs | pt.cbs):
f.write("USE CB %d\n" % cb)
for tex in sorted(vt.textures | pt.textures):
f.write("USE TEX %d\n" % tex)
if a.dxc:
for st, prof in (("vs", "vs_6_0"), ("ps", "ps_6_0")):
cmd = a.dxc.split() + ["-T", prof, "-E", "main", "-Fo", base + ".%s.dxil" % st, base + ".%s.hlsl" % st]
r = subprocess.run(cmd, capture_output=True, text=True)
err = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if "fixme" not in l)
if r.returncode or not os.path.exists(base + ".%s.dxil" % st):
sys.exit("dxc failed for %s:\n%s" % (st, err))
print(key)
if __name__ == "__main__":
try:
main()
except Unsupported as e:
sys.exit("unsupported: %s" % e)
+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);
}
@@ -185,6 +185,9 @@ pub enum Verdict {
DeviceRemoved { reason: u32 },
/// The GPU did not signal completion in time.
TimedOut { detail: String },
/// The device reported a highest shader model below the 6.6 the harness kernel
/// requires. The field was parsed and printed before, but never judged (#567).
UnsupportedShaderModel { reported: u8 },
/// Every word still holds the sentinel: the kernel never wrote.
KernelDidNotRun,
/// The kernel wrote, but some words differ from the expected values.
@@ -224,6 +227,12 @@ impl fmt::Display for Verdict {
)
}
Self::TimedOut { detail } => write!(f, "FAIL: GPU timeout ({detail})"),
Self::UnsupportedShaderModel { reported } => write!(
f,
"FAIL: highest shader model {}.{} is below the 6.6 the harness kernel requires",
reported >> 4,
reported & 0xf
),
Self::KernelDidNotRun => write!(
f,
"FAIL: all {WORDS} words still hold the sentinel 0x{SENTINEL:08x}; the kernel did not write"
@@ -272,6 +281,14 @@ pub fn judge(report: &ProbeReport) -> Verdict {
let incomplete = |reason: &str| Verdict::Incomplete {
reason: reason.to_owned(),
};
// Every kernel the harness runs is SM 6.6. A device that reports less, or a
// report with no shader_model record, must not pass on a matching readback
// alone (#567). The live Rust test asserted this; the standalone verdict did not.
match report.shader_model {
Some(sm) if sm < 0x66 => return Verdict::UnsupportedShaderModel { reported: sm },
None => return incomplete("no shader_model record"),
Some(_) => {}
}
match report.dispatch {
None => return incomplete("no dispatch record"),
Some(d) if d != expected_dispatch => {
@@ -341,6 +358,29 @@ mod tests {
assert_eq!(judge(&report), Verdict::Pass);
}
#[test]
fn a_shader_model_below_6_6_fails_even_with_a_matching_readback() {
// The kernel is SM 6.6; the readback matching proves only that something wrote.
for reported in ["0x65", "0x60"] {
let lower = output(&good_words()).replace(
"BXD3DM shader_model 0x66",
&format!("BXD3DM shader_model {reported}"),
);
let report = parse_report(&lower).unwrap();
assert_eq!(
judge(&report),
Verdict::UnsupportedShaderModel {
reported: if reported == "0x65" { 0x65 } else { 0x60 }
}
);
}
// Without the record the harness cannot say the device can run the shader.
let absent = output(&good_words()).replace("BXD3DM shader_model 0x66\n", "");
let report = parse_report(&absent).unwrap();
assert_eq!(report.shader_model, None);
assert!(matches!(judge(&report), Verdict::Incomplete { .. }));
}
#[test]
fn untouched_sentinel_means_the_kernel_did_not_run() {
let report = parse_report(&output(&[SENTINEL; WORDS])).unwrap();
@@ -80,12 +80,14 @@ fn collect(rx: &Receiver<Event>, until: Instant) -> io::Result<(Vec<u8>, Vec<u8>
Ok((stdout, stderr, true))
}
fn wait_until(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
/// `deadline: None` means the requested timeout is not representable on this clock, so the
/// probe is allowed to run without one (#587).
fn wait_until(child: &mut Child, deadline: Option<Instant>) -> io::Result<Option<ExitStatus>> {
loop {
if let Some(status) = child.try_wait()? {
return Ok(Some(status));
}
if Instant::now() >= deadline {
if deadline.is_some_and(|at| Instant::now() >= at) {
child.kill()?;
child.wait()?;
return Ok(None);
@@ -112,7 +114,13 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
command.env(key, value);
}
}
let deadline = Instant::now() + timeout;
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow, so a
// huge value would abort the harness with exit 101 instead of one of its verdict codes
// (#586). Saturate at the platform maximum instead: the probe then simply never times out.
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow. When the
// requested timeout is not representable the probe simply has no deadline; representing
// that as `None` avoids inventing a fallback duration that might also not fit (#587).
let deadline = Instant::now().checked_add(timeout);
let mut child = command.spawn()?;
let (tx, rx) = mpsc::channel();
pump(
@@ -126,8 +134,11 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
tx,
);
let status = wait_until(&mut child, deadline)?;
let (stdout, stderr, output_complete) =
collect(&rx, deadline.max(Instant::now() + DRAIN_GRACE))?;
// With no deadline the probe has already exited, so draining still needs a bound.
let drain_until = deadline
.unwrap_or_else(Instant::now)
.max(Instant::now() + DRAIN_GRACE);
let (stdout, stderr, output_complete) = collect(&rx, drain_until)?;
Ok(ProbeRun {
status,
stdout: String::from_utf8_lossy(&stdout).into_owned(),
@@ -161,6 +172,35 @@ mod tests {
}
}
#[test]
fn an_unrepresentable_deadline_leaves_the_probe_without_a_timeout() {
// `checked_add` returns None for a timeout the clock cannot represent; the runner
// must then wait for the probe normally instead of inventing a fallback duration
// that could itself overflow (#587).
let script = Script::new("nodeadline", "sleep 0.2; exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
)
.expect("an unrepresentable deadline must not abort the run");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
assert!(run.output_complete);
}
#[test]
fn an_overflowing_timeout_does_not_panic() {
// u64::MAX seconds overflows `Instant + Duration`; before #586 this panicked.
let script = Script::new("overflow", "exit 0");
let run = run_probe(
&script.0,
std::path::Path::new("/nonexistent/framework"),
Duration::from_secs(u64::MAX),
);
let run = run.expect("an overflowing timeout must still run the probe, not panic");
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
}
#[test]
fn passes_the_framework_and_only_allowlisted_environment() {
let script = Script::new("env", "echo \"args=$*\"; env; echo oops >&2; exit 3");
@@ -186,22 +226,70 @@ mod tests {
assert!(run.output_complete);
}
/// Timeout for the tests below whose stand-in probe has to start and print before the
/// deadline. Starting a freshly written script costs tens of milliseconds here and
/// occasionally far more, so a few hundred milliseconds made these tests fail now and then
/// (#479). They check what happens at the deadline, not how fast a script starts.
const START_MARGIN: Duration = Duration::from_secs(2);
/// Removes the pid file, and kills the recorded process if a failing test left it running.
struct PidFile(PathBuf);
impl Drop for PidFile {
fn drop(&mut self) {
if std::thread::panicking()
&& let Ok(pid) = std::fs::read_to_string(&self.0)
{
let _ = Command::new("/bin/kill").arg(pid.trim()).status();
}
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn kills_a_probe_that_exceeds_the_timeout() {
let script = Script::new("hang", "echo started; exec sleep 30");
let pid_file = PidFile(
std::env::temp_dir().join(format!("bx-harness-probe's-{}.pid", std::process::id())),
);
let _ = std::fs::remove_file(&pid_file.0);
// Pass the path as the value of --framework. The apostrophe tests literal path handling.
// `exec` keeps the pid, so the recorded pid is the process that has to be killed.
let script = Script::new(
"hang",
"echo $$ > \"$2\" || exit 1; echo started; exec sleep 30",
);
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), Duration::from_millis(300)).unwrap();
let run = run_probe(&script.0, &pid_file.0, START_MARGIN).unwrap();
let elapsed = started.elapsed();
assert!(run.status.is_none());
// Output written before the kill is kept.
assert_eq!(run.stdout, "started\n");
assert!(started.elapsed() < Duration::from_secs(10));
// The probe ran until the deadline and no longer: it was killed, not waited for.
assert!(elapsed >= START_MARGIN, "returned early after {elapsed:?}");
assert!(
elapsed < START_MARGIN + DRAIN_GRACE + Duration::from_secs(5),
"returned after {elapsed:?}"
);
// The process is gone. `output_complete` is deliberately not asserted: tests run in
// parallel, and a child spawned by another test at the wrong moment can inherit this
// probe's pipe and hold it open (seen in 2 of 200 runs).
let pid = std::fs::read_to_string(&pid_file.0).unwrap();
let alive = Command::new("/bin/kill")
.args(["-0", pid.trim()])
.stderr(Stdio::null())
.status()
.unwrap()
.success();
assert!(!alive, "probe {} survived the timeout", pid.trim());
}
/// The probe exits at once, but a background descendant inherits stdout and
/// keeps it open well past the timeout.
#[test]
fn a_descendant_holding_the_pipes_cannot_outlast_the_deadline() {
let script = Script::new("orphan", "sleep 5 & echo started");
let timeout = Duration::from_millis(500);
// The descendant has to outlive the bound asserted below by a wide margin.
let script = Script::new("orphan", "sleep 6 & echo started");
let timeout = START_MARGIN;
let started = Instant::now();
let run = run_probe(&script.0, Path::new("/fw"), timeout).unwrap();
let elapsed = started.elapsed();
+18 -4
View File
@@ -2,6 +2,15 @@
Classifies D3D shader containers (`DXBC` with `DXIL`, legacy `SHDR`/`SHEX`, and `ACCC` chunks carrying BetterXen's synthetic `FSPX` table) and exposes the C ABI in [`abi/include/bx_shader_bridge.h`](../../../abi/include/bx_shader_bridge.h): `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal` and `bx_shader_free_buffer`.
## `FSPX` errors
A malformed `FSPX` table fails inspection with a `ParseError`; it never panics. Two bounds errors are kept apart (#599):
- **`FspxLayoutMismatch`:** a descriptor's offset lands inside the 16-byte header or the descriptor table, the region the synthetic layout reserves. The table does not follow BetterXen's clean-room layout. The error carries the section id, the offset and the table length.
- **`FspxSectionOutOfBounds`:** a section starts after the table but runs past the end of the payload.
Both are still errors. Over the C ABI, both are `BX_SHADER_ERR_INVALID_BLOB`, so a caller of `bx_shader_inspect` cannot tell them apart yet; that would need an `[ABI]` change to `abi/include/bx_shader_bridge.h`.
## Guest access: `bx_shader_bridge.dll` (#445)
The shims that see shader bytecode (`d3d12_xs.dll`) are x86-64 Windows PE32+ DLLs running inside CrossOver. They cannot load the arm64 macOS library that `cargo build` produces on the host. The bridge reaches guests as a **Windows build of this same crate**, with no second implementation:
@@ -52,8 +61,13 @@ This is a synthetic, single-host result. It is not a measurement of any title's
Each of these faults compiled into the DLL fails the check: `dxil_chunk_size` clamped to 1, `accc_chunk_size` multiplied, the digest zeroed, `has_root_signature` set to 7, and the DXIL and ACCC kind numbers swapped. The last one also fails when it is rebuilt with `CARGO_TARGET_DIR` set elsewhere.
### Not done here (other owners)
### Related work, owned elsewhere
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`):** the frozen export list for the DLL. Linking with it would also set the export directory's internal name, which is `dxbc_accc.dll` today. Wine loads by file name, so this does not affect loading.
- **Staging in `scripts/build-shims.sh` (Track A):** building the DLL there and verifying it with the other shims, so `build-shims/bin` ships it. That would also make CI build it; today nothing does, and `rustup target add x86_64-pc-windows-gnu` is a manual step.
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (#466):** today `bx_shader_prepare_for_d3dmetal` reports an ACCC-only container on the guest's stderr (`bx-shader event=prepare status=unsupported …`), not through `bx_log_emit`.
Three of these pieces around this crate were recorded here as outstanding when this section was written and have since landed. The fourth is the trace summary of the records the shim emits.
- **`abi/defs/bx_shader_bridge.def` (`[ABI]`, #445, #484):** present and in use. Its `LIBRARY` directive is `bx_shader_bridge.dll`, and `scripts/build-shims.sh` passes it to `cargo rustc` as `-C link-arg=…/abi/defs/bx_shader_bridge.def`, so the built DLL's export directory holds exactly the three header entry points and its internal name is `bx_shader_bridge.dll`, not `dxbc_accc.dll`. Cargo still names the built file `dxbc_accc.dll`; the script copies it to `build-shims/bin/bx_shader_bridge.dll`, and the verifier requires the export-directory name to match the `.def`.
- **Staging in `scripts/build-shims.sh` (Track A, #484):** done. The script builds this crate for `x86_64-pc-windows-gnu`, copies the result to `build-shims/bin/bx_shader_bridge.dll`, and verifies its export directory with the same exact-export, ordinal, forwarder and MinGW-import rules as the other shims. CI's hybrid job installs that target with its pinned toolchain, so `rustup target add x86_64-pc-windows-gnu` is only a one-off step for a local build, and the script stops with that hint when the target's `std` is missing.
- **Calling it from `d3d12_xs` at PSO creation, and JSONL telemetry (Track C, #466):** done. `CreateGraphicsPipelineState` and `CreateComputePipelineState` in `shims/d3d12_xs/proxy.cpp` run every stage through `BxShaderGate::admit` (`shims/d3d12_xs/shader_gate.cpp`), which calls `bx_shader_inspect` and `bx_shader_prepare_for_d3dmetal` and emits `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` records through `bx_log_emit`. The bridge itself still writes its ACCC-only inspection line to the guest's stderr (`bx-shader event=prepare status=unsupported …`), because this crate does not link `bx_log_emit`; the JSONL records come from the shim.
- **Trace summary of those records (`bx-cli trace`, Track A, #496):** the work to parse `shader_gate`, `shader_d3dmetal_gap` and `shader_bridge_missing` into `bx-telemetry` and render them in `bx-cli trace` is tracked in #496. This bullet describes the split of responsibility only — it does not depend on that issue's status, and the crate's own behaviour is unaffected either way.
This change does not touch the crate's code or tests; the tests above still describe its own behavior.
+32 -3
View File
@@ -10,6 +10,13 @@
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
//! count is rejected before any descriptor is compared with another, so
//! inspection stays allocation-free and the pairwise check stays bounded.
//!
//! A descriptor whose offset lands inside the 16-byte header or the
//! descriptor table itself is a layout mismatch, reported apart from a
//! section that runs past the end of the payload. Read through this layout,
//! such a table is not merely truncated or corrupt: its descriptors do not
//! mean `(id, offset, size)` relative to the payload as this module assumes.
//! It is still an error, and the container is still refused.
use super::{ShaderStage, read_u32_le};
@@ -82,9 +89,22 @@ impl FspxInfo {
pub(crate) enum FspxError {
Truncated,
BadVersion(u32),
SectionOutOfBounds { section_id: u32 },
DuplicateSection { section_id: u32 },
Overlap { section_id: u32 },
SectionOutOfBounds {
section_id: u32,
},
/// The descriptor's offset lies inside the header plus descriptor table,
/// the region this layout reserves, so the table does not follow it.
LayoutMismatch {
section_id: u32,
offset: u32,
table_end: u32,
},
DuplicateSection {
section_id: u32,
},
Overlap {
section_id: u32,
},
BadStageConfig,
TooManySections(u32),
}
@@ -217,6 +237,15 @@ fn walk_sections(
) -> Result<(), FspxError> {
for index in 0..header.count {
let (id, offset, size) = descriptor_at(payload, index)?;
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
return Err(FspxError::LayoutMismatch {
section_id: id,
offset,
table_end,
});
}
let end = section_end(offset, size, header.table_end, payload.len())
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
for prev in 0..index {
+685 -56
View File
@@ -9,7 +9,10 @@
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
//! [`ParseError::FspxTooManySections`] before any pairwise comparison.
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
//! descriptor whose offset lands inside the header plus descriptor table is
//! [`ParseError::FspxLayoutMismatch`], kept apart from
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
//! code byte range. The code bytes are not decoded. This layout is synthetic.
@@ -26,13 +29,16 @@
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
//! so preparation does not copy it.
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
//! size and stage metadata but does not classify as executable `DXIL`.
//!
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
//! including when an accompanying `FSPX` table is malformed, and logs only an
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
//! is not implemented.
mod c_abi;
mod fspx;
@@ -94,22 +100,104 @@ pub struct ShaderInspection {
pub chunks: Vec<ChunkInfo>,
}
impl ShaderInspection {
/// Payload of the first chunk tagged `fourcc`, if present and fully
/// inside the container. Returns `None` when absent, when the declared
/// size would run past `container_size` or `container`, or when `offset`
/// points into the DXBC header or chunk-offset table instead of a chunk
/// header.
///
/// `container` must be the same bytes passed to [`inspect_dxbc`]; the
/// inspection only stores chunk metadata, so the original container is
/// required to slice out the payload. `ChunkInfo::offset` is relative to
/// the start of the `DXBC` container and points at the 8-byte chunk
/// header (fourcc + size), so the payload begins at `offset + 8`.
///
/// A zero-size chunk yields `Some(&[])`: the header is present and
/// in-bounds, so an empty payload is a valid result rather than an
/// absence. Callers that require a minimum size must check the returned
/// slice length.
///
/// Only the already-parsed `self.chunks` table is consulted; the raw
/// chunk table is not re-walked. When several chunks share `fourcc`,
/// the first one in table order wins, matching the C++ `find_chunk`.
pub fn chunk_payload<'a>(&self, container: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
let chunk = self.chunks.iter().find(|c| &c.fourcc == fourcc)?;
let table_bytes = u64::try_from(self.chunks.len()).ok()?.checked_mul(4)?;
let table_end = 32u64.checked_add(table_bytes)?;
if u64::from(chunk.offset) < table_end {
return None;
}
let start = u64::from(chunk.offset).checked_add(8)?;
let end = start.checked_add(u64::from(chunk.size))?;
if end > u64::from(self.container_size) {
return None;
}
let start = usize::try_from(start).ok()?;
let end = usize::try_from(end).ok()?;
if end > container.len() {
return None;
}
container.get(start..end)
}
/// True when a chunk header tagged `fourcc` exists, whatever its
/// declared size. Mirrors the C++ `has_chunk_tag`: presence without
/// trusting the size.
pub fn has_chunk_tag(&self, fourcc: &[u8; 4]) -> bool {
self.chunks.iter().any(|c| &c.fourcc == fourcc)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseError {
TooShort,
BadMagic,
UnsupportedVersion(u32),
TruncatedChunkTable,
ChunkOutOfBounds { index: usize },
ChunkOutOfBounds {
index: usize,
},
TruncatedContainer,
FspxTruncated { chunk: usize },
FspxBadVersion { chunk: usize, version: u32 },
FspxSectionOutOfBounds { chunk: usize, section_id: u32 },
FspxDuplicateSection { chunk: usize, section_id: u32 },
FspxSectionOverlap { chunk: usize, section_id: u32 },
FspxBadStageConfig { chunk: usize },
FspxTooManySections { chunk: usize, count: u32 },
BadDxilHeader { chunk: usize },
FspxTruncated {
chunk: usize,
},
FspxBadVersion {
chunk: usize,
version: u32,
},
FspxSectionOutOfBounds {
chunk: usize,
section_id: u32,
},
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
/// table (`table_end` bytes), which the synthetic layout reserves. The
/// table does not follow BetterXen's clean-room layout; it is not reported
/// as an out-of-bounds section. The container is still rejected.
FspxLayoutMismatch {
chunk: usize,
section_id: u32,
offset: u32,
table_end: u32,
},
FspxDuplicateSection {
chunk: usize,
section_id: u32,
},
FspxSectionOverlap {
chunk: usize,
section_id: u32,
},
FspxBadStageConfig {
chunk: usize,
},
FspxTooManySections {
chunk: usize,
count: u32,
},
BadDxilHeader {
chunk: usize,
},
}
impl fmt::Display for ParseError {
@@ -133,6 +221,15 @@ impl fmt::Display for ParseError {
"FSPX section {section_id} out of bounds in chunk {chunk}"
)
}
Self::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
} => write!(
f,
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
),
Self::FspxDuplicateSection { chunk, section_id } => {
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
}
@@ -185,6 +282,16 @@ fn fspx_error(chunk: usize, err: fspx::FspxError) -> ParseError {
fspx::FspxError::SectionOutOfBounds { section_id } => {
ParseError::FspxSectionOutOfBounds { chunk, section_id }
}
fspx::FspxError::LayoutMismatch {
section_id,
offset,
table_end,
} => ParseError::FspxLayoutMismatch {
chunk,
section_id,
offset,
table_end,
},
fspx::FspxError::DuplicateSection { section_id } => {
ParseError::FspxDuplicateSection { chunk, section_id }
}
@@ -209,14 +316,22 @@ fn record_fspx_stage(
}
}
enum DxilProgram {
Executable((ShaderStage, u8, u8)),
HeaderOnly((ShaderStage, u8, u8)),
}
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
///
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
/// and must be at least 16. `BitcodeSize` must be non-zero, and
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
/// bitcode bytes are not decoded.
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
///
/// A bitcode payload beginning with `NOBC` is a header-only container (for
/// example, reflection or signature metadata with bitcode stripped) and is
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
const PROGRAM_PREFIX: u64 = 8;
const BITCODE_HEADER: u64 = 16;
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
@@ -245,7 +360,16 @@ fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
if end > program_bytes {
return Err(());
}
Ok(program_stage(program_version))
let bitcode_start =
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
let stage = program_stage(program_version);
if bitcode.starts_with(b"NOBC") {
Ok(DxilProgram::HeaderOnly(stage))
} else {
Ok(DxilProgram::Executable(stage))
}
}
struct ContainerLimit {
@@ -352,6 +476,37 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
}
}
#[derive(Default)]
struct DxilChunkState {
has_executable: bool,
size: u32,
executable_stage: Option<(ShaderStage, u8, u8)>,
header_only_stage: Option<(ShaderStage, u8, u8)>,
}
impl DxilChunkState {
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
/// header-only placeholders regardless of chunk order.
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
DxilProgram::Executable(stage) => {
self.has_executable = true;
self.size = size;
self.executable_stage = Some(stage);
}
DxilProgram::HeaderOnly(stage) => {
if !self.has_executable {
self.size = size;
}
if self.header_only_stage.is_none() {
self.header_only_stage = Some(stage);
}
}
}
Ok(())
}
}
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
/// keep chunk or section lists.
pub(crate) struct DxbcSummary {
@@ -370,24 +525,16 @@ pub(crate) struct DxbcSummary {
///
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -408,36 +555,40 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
}
Ok(())
})?;
let (stage, shader_model_major, shader_model_minor) = dxil_stage
let (stage, shader_model_major, shader_model_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(DxbcSummary {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major,
shader_model_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
})
}
/// `Ok(Some(container_size))` when the container is structurally valid and
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no `DXIL` chunk.
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
/// structurally valid and has no executable `DXIL` chunk.
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
let mut has_dxil = false;
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
if &fourcc == b"DXIL" {
if read_dxil_program(payload).is_err() {
return Err(ParseError::BadDxilHeader { chunk: index });
match read_dxil_program(payload) {
Ok(DxilProgram::Executable(_)) => has_dxil = true,
Ok(DxilProgram::HeaderOnly(_)) => {}
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
}
has_dxil = true;
}
Ok(())
})?;
@@ -457,27 +608,19 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
/// container through.
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
let mut chunks = Vec::new();
let mut has_dxil = false;
let mut dxil = DxilChunkState::default();
let mut has_accc = false;
let mut has_legacy = false;
let mut has_root_signature = false;
let mut dxil_size = 0u32;
let mut accc_size = 0u32;
let mut accc_is_fspx = false;
let mut dxil_stage = None;
let mut legacy_stage = None;
let mut fspx_stage = None;
let mut fspx = None;
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
match &fourcc {
b"DXIL" => {
let stage = read_dxil_program(payload)
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
has_dxil = true;
dxil_size = size;
dxil_stage = Some(stage);
}
b"DXIL" => dxil.record(index, size, payload)?,
b"ACCC" => {
has_accc = true;
accc_size = size;
@@ -515,21 +658,22 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
Ok(())
})?;
let (stage, sm_major, sm_minor) =
dxil_stage
.or(legacy_stage)
.or(fspx_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
let (stage, sm_major, sm_minor) = dxil
.executable_stage
.or(legacy_stage)
.or(fspx_stage)
.or(dxil.header_only_stage)
.unwrap_or((ShaderStage::Unknown, 0, 0));
Ok(ShaderInspection {
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
stage,
shader_model_major: sm_major,
shader_model_minor: sm_minor,
container_size: header.container_size,
digest: header.digest,
has_root_signature,
dxil_size,
dxil_size: dxil.size,
accc_size,
accc_is_fspx,
fspx,
@@ -868,9 +1012,11 @@ mod tests {
),
(
fspx_header(1, 1, &[(1, 0, 4)], 28),
ParseError::FspxSectionOutOfBounds {
ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 1,
offset: 0,
table_end: 28,
},
),
(
@@ -924,18 +1070,167 @@ mod tests {
#[test]
fn truncated_prefixes_do_not_panic() {
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
nobc_dxil[24..28].copy_from_slice(b"NOBC");
let blobs = [
synthetic_dxil_blob(),
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
vec![0xFF; 64],
];
for blob in blobs {
for len in 0..=blob.len() {
let _ = inspect_dxbc(&blob[..len]);
let _ = summarize_dxbc(&blob[..len]);
let _ = dxil_container_len(&blob[..len]);
}
}
}
/// A two-section table (`table_end` = 16 + 2 * 12 = 40) whose second
/// descriptor's offset is `second_offset`. The first descriptor is a valid
/// 12-byte stage section at 40, and the payload is 64 bytes long.
fn fspx_two_sections(second_offset: u32) -> Vec<u8> {
let mut payload = fspx_header(1, 2, &[(1, 40, 12), (6, second_offset, 4)], 64);
payload[40..44].copy_from_slice(&6u32.to_le_bytes());
payload[44..48].copy_from_slice(&6u32.to_le_bytes());
payload
}
#[test]
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
// Inside the 16-byte header, inside the first descriptor, inside the
// descriptor itself, and the last reserved byte.
for offset in [0u32, 8, 16, 28, 39] {
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
let expected = ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset,
table_end: 40,
};
assert_eq!(
inspect_dxbc(&blob),
Err(expected.clone()),
"offset {offset}"
);
// The C ABI path walks the table through `scan_fspx`, not
// `parse_fspx`, and must classify it the same way.
assert_eq!(
summarize_dxbc(&blob).map(|_| ()),
Err(expected),
"offset {offset}"
);
}
// The first byte after the table is outside the reserved region.
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
assert_eq!(info.kind, ShaderKind::AcccOnly);
assert_eq!(info.stage, ShaderStage::Compute);
assert!(summarize_dxbc(&blob).is_ok());
}
#[test]
fn fspx_layout_mismatch_is_not_out_of_bounds() {
// Past the payload end is still out of bounds, not a layout mismatch.
let mut payload = fspx_two_sections(62);
payload.truncate(64);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let out_of_bounds = ParseError::FspxSectionOutOfBounds {
chunk: 0,
section_id: 6,
};
assert_eq!(inspect_dxbc(&blob), Err(out_of_bounds.clone()));
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(out_of_bounds));
// A reserved offset wins even when the size would also overrun.
let mut payload = fspx_header(1, 1, &[(6, 20, u32::MAX)], 32);
payload.truncate(32);
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::FspxLayoutMismatch {
chunk: 0,
section_id: 6,
offset: 20,
table_end: 28,
})
);
let message = ParseError::FspxLayoutMismatch {
chunk: 2,
section_id: 6,
offset: 20,
table_end: 28,
}
.to_string();
assert!(message.contains("section 6"), "{message}");
assert!(message.contains("offset 20"), "{message}");
assert!(message.contains("28-byte"), "{message}");
assert!(message.contains("chunk 2"), "{message}");
assert!(!message.contains("out of bounds"), "{message}");
}
#[test]
fn c_abi_still_refuses_fspx_layout_mismatch() {
clear_shader_log();
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]);
let mut c_info = BxShaderInspection {
kind: 99,
..BxShaderInspection::default()
};
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert_eq!(c_info.kind, 0);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn arbitrary_fspx_tables_do_not_panic() {
// Deterministic xorshift so a failure reproduces.
let mut state = 0x9E37_79B9_7F4A_7C15u64;
let mut next = || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for round in 0..4096u32 {
let len = 16 + (next() % 240) as usize;
let mut payload: Vec<u8> = (0..len).map(|_| next() as u8).collect();
payload[..4].copy_from_slice(b"FSPX");
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
let count = round % (FSPX_MAX_SECTIONS as u32 + 2);
payload[8..12].copy_from_slice(&count.to_le_bytes());
// Keep some offsets small so the reserved-region branch is hit.
if round % 2 == 0 {
let mut at = 20;
while at + 4 <= len.min(16 + count as usize * 12) {
let small = (next() % 64) as u32;
payload[at..at + 4].copy_from_slice(&small.to_le_bytes());
at += 12;
}
}
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
let _ = inspect_dxbc(&blob);
let _ = summarize_dxbc(&blob);
let mut c_info = BxShaderInspection::default();
let _ = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
}
}
#[test]
fn c_abi_inspect_and_passthrough_round_trip() {
clear_shader_log();
@@ -1268,6 +1563,245 @@ mod tests {
assert!(log[0].contains("sm_minor=0"));
}
#[test]
fn nobc_dxil_is_not_classified_as_executable_dxil() {
clear_shader_log();
// Pixel shader (0), SM 6.6, with the four-byte NOBC placeholder instead of LLVM bitcode.
let mut payload = minimal_dxil_program((6u32 << 4) | 6u32);
payload[24..28].copy_from_slice(b"NOBC");
let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &payload)]);
let info = inspect_dxbc(&blob).expect("valid DXBC with NOBC header-only DXIL");
assert_eq!(info.kind, ShaderKind::Unknown);
assert_eq!(info.stage, ShaderStage::Pixel);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6));
assert_eq!(info.dxil_size, 28);
assert!(info.has_root_signature);
let mut c_info = BxShaderInspection::default();
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_OK);
assert_eq!(c_info.kind, 0); // BX_SHADER_UNKNOWN
assert_eq!(c_info.stage, 1); // BX_STAGE_PIXEL
assert_eq!(c_info.shader_model_major, 6);
assert_eq!(c_info.shader_model_minor, 6);
assert_eq!(c_info.dxil_chunk_size, 28);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn nobc_dxil_with_accc_is_classified_as_accc_only_and_rejected() {
clear_shader_log();
let mut dxil = minimal_dxil_program((1u32 << 16) | (6u32 << 4) | 6u32);
dxil[24..28].copy_from_slice(b"NOBC");
let fspx = fspx_compute_stage();
let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil), (b"ACCC", &fspx)]);
let info = inspect_dxbc(&blob).expect("NOBC + ACCC container");
assert_eq!(info.kind, ShaderKind::AcccOnly);
assert_eq!(info.stage, ShaderStage::Compute);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0));
assert_eq!(info.dxil_size, 28);
assert_eq!(info.accc_size, 40);
let mut c_info = BxShaderInspection::default();
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
assert_eq!(status, BX_SHADER_OK);
assert_eq!(c_info.kind, 3); // BX_SHADER_DXBC_ACCC
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
let log = shader_log_lines();
assert_eq!(log.len(), 1);
assert!(log[0].contains("kind=accc_only(3)"));
}
#[test]
fn nobc_dxil_with_padded_bitcode_is_still_header_only() {
let mut payload = vec![0u8; 32];
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
payload[0..4].copy_from_slice(&prog.to_le_bytes());
payload[4..8].copy_from_slice(&8u32.to_le_bytes());
payload[8..12].copy_from_slice(b"DXIL");
payload[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
payload[16..20].copy_from_slice(&16u32.to_le_bytes());
payload[20..24].copy_from_slice(&8u32.to_le_bytes());
payload[24..28].copy_from_slice(b"NOBC");
let blob = build_synthetic_dxbc(&[(b"DXIL", &payload)]);
let info = inspect_dxbc(&blob).expect("padded NOBC DXIL");
assert_eq!(info.kind, ShaderKind::Unknown);
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
}
#[test]
fn mixed_executable_and_nobc_dxil_preserves_executable_metadata() {
let exec = minimal_dxil_program((5u32 << 16) | (6u32 << 4) | 5u32);
let mut nobc = vec![0u8; 32];
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
nobc[0..4].copy_from_slice(&prog.to_le_bytes());
nobc[4..8].copy_from_slice(&8u32.to_le_bytes());
nobc[8..12].copy_from_slice(b"DXIL");
nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
nobc[16..20].copy_from_slice(&16u32.to_le_bytes());
nobc[20..24].copy_from_slice(&8u32.to_le_bytes());
nobc[24..28].copy_from_slice(b"NOBC");
// Executable first, NOBC second: executable stage and size must win.
let blob_exec_first = build_synthetic_dxbc(&[(b"DXIL", &exec), (b"DXIL", &nobc)]);
let info = inspect_dxbc(&blob_exec_first).expect("mixed DXIL");
assert_eq!(info.kind, ShaderKind::Dxil);
assert_eq!(info.stage, ShaderStage::Compute);
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 5));
assert_eq!(info.dxil_size, 28);
let mut c_info = BxShaderInspection::default();
assert_eq!(
unsafe {
bx_shader_inspect(blob_exec_first.as_ptr(), blob_exec_first.len(), &mut c_info)
},
BX_SHADER_OK
);
assert_eq!(c_info.kind, 1); // BX_SHADER_DXBC_DXIL
assert_eq!(c_info.stage, 6); // BX_STAGE_COMPUTE
assert_eq!(c_info.dxil_chunk_size, 28);
assert_eq!(
dxil_container_len(&blob_exec_first),
Ok(Some(blob_exec_first.len() as u32))
);
// NOBC first, executable second: executable must still win.
let blob_nobc_first = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"DXIL", &exec)]);
let info2 = inspect_dxbc(&blob_nobc_first).expect("mixed DXIL reversed");
assert_eq!(info2.kind, ShaderKind::Dxil);
assert_eq!(info2.stage, ShaderStage::Compute);
assert_eq!((info2.shader_model_major, info2.shader_model_minor), (6, 5));
assert_eq!(info2.dxil_size, 28);
let summary2 = summarize_dxbc(&blob_nobc_first).expect("mixed DXIL summary");
assert_eq!(summary2.kind, ShaderKind::Dxil);
assert_eq!(summary2.stage, ShaderStage::Compute);
assert_eq!(summary2.dxil_size, 28);
}
#[test]
fn nobc_dxil_with_malformed_fspx_returns_invalid_blob() {
clear_shader_log();
let mut nobc = minimal_dxil_program((6u32 << 4) | 6u32);
nobc[24..28].copy_from_slice(b"NOBC");
let bad_fspx = fspx_header(99, 0, &[], 16);
let blob = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"ACCC", &bad_fspx)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::FspxBadVersion {
chunk: 1,
version: 99,
})
);
assert_eq!(dxil_container_len(&blob), Ok(None));
let mut out_ptr = ptr_sentinel();
let mut out_len = 8usize;
let status = unsafe {
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
};
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(out_ptr.is_null());
assert_eq!(out_len, 0);
assert!(shader_log_lines().is_empty());
}
#[test]
fn dxil_bitcode_bounds_and_offset_checks() {
let prog = (5u32 << 16) | (6u32 << 4) | 6u32;
// Bitcode shorter than 4 bytes (`NOB`) must not misclassify as `NOBC` or read out of bounds.
let mut short_bitcode = [0u8; 28];
short_bitcode[0..4].copy_from_slice(&prog.to_le_bytes());
short_bitcode[4..8].copy_from_slice(&7u32.to_le_bytes());
short_bitcode[8..12].copy_from_slice(b"DXIL");
short_bitcode[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
short_bitcode[16..20].copy_from_slice(&16u32.to_le_bytes());
short_bitcode[20..24].copy_from_slice(&3u32.to_le_bytes());
short_bitcode[24..27].copy_from_slice(b"NOB");
let blob_short = build_synthetic_dxbc(&[(b"DXIL", &short_bitcode)]);
assert_eq!(
inspect_dxbc(&blob_short).expect("3-byte bitcode").kind,
ShaderKind::Dxil
);
// `NOBC` check follows `BitcodeOffset`, not a fixed offset 24.
let mut shifted_nobc = vec![0u8; 36];
shifted_nobc[0..4].copy_from_slice(&prog.to_le_bytes());
shifted_nobc[4..8].copy_from_slice(&9u32.to_le_bytes());
shifted_nobc[8..12].copy_from_slice(b"DXIL");
shifted_nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
shifted_nobc[16..20].copy_from_slice(&24u32.to_le_bytes());
shifted_nobc[20..24].copy_from_slice(&4u32.to_le_bytes());
shifted_nobc[32..36].copy_from_slice(b"NOBC");
let blob_shifted_nobc = build_synthetic_dxbc(&[(b"DXIL", &shifted_nobc)]);
assert_eq!(
inspect_dxbc(&blob_shifted_nobc).expect("shifted NOBC").kind,
ShaderKind::Unknown
);
assert_eq!(dxil_container_len(&blob_shifted_nobc), Ok(None));
// Bytes before `BitcodeOffset` containing `NOBC` do not make executable bitcode header-only.
let mut shifted_exec = shifted_nobc;
shifted_exec[24..28].copy_from_slice(b"NOBC");
shifted_exec[32..36].copy_from_slice(&[0xD1, 0x11, 0xC0, 0xDE]);
let blob_shifted_exec = build_synthetic_dxbc(&[(b"DXIL", &shifted_exec)]);
assert_eq!(
inspect_dxbc(&blob_shifted_exec)
.expect("shifted executable")
.kind,
ShaderKind::Dxil
);
// Overflowing bitcode offset / size must reject cleanly as `BadDxilHeader`.
for (bitcode_off, bitcode_sz) in [(16u32, u32::MAX), (u32::MAX - 4, 4u32)] {
let mut overflow = minimal_dxil_program(prog);
overflow[16..20].copy_from_slice(&bitcode_off.to_le_bytes());
overflow[20..24].copy_from_slice(&bitcode_sz.to_le_bytes());
let blob = build_synthetic_dxbc(&[(b"DXIL", &overflow)]);
assert_eq!(
inspect_dxbc(&blob),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
assert_eq!(
summarize_dxbc(&blob).map(|_| ()),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
assert_eq!(
dxil_container_len(&blob),
Err(ParseError::BadDxilHeader { chunk: 0 })
);
}
}
fn fspx_table_with_sections(count: u32) -> Vec<u8> {
let count_usize = count as usize;
let table_end = 16 + count_usize * 12;
@@ -1302,4 +1836,99 @@ mod tests {
fn ptr_sentinel() -> *mut u8 {
std::ptr::dangling_mut()
}
#[test]
fn chunk_payload_returns_sfi0_and_psv0_bytes() {
let sfi0: [u8; 8] = [0x00, 0x40, 0, 0, 0, 0, 0, 0];
let psv0: [u8; 28] = [
24, 0, 0, 0, // info_size = 24
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, // lanes_min
64, 0, 0, 0, // lanes_max
];
let blob = build_synthetic_dxbc(&[(b"SFI0", &sfi0), (b"PSV0", &psv0)]);
let info = inspect_dxbc(&blob).expect("valid container");
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(sfi0.as_slice()));
assert_eq!(info.chunk_payload(&blob, b"PSV0"), Some(psv0.as_slice()));
assert!(info.has_chunk_tag(b"SFI0"));
assert!(info.has_chunk_tag(b"PSV0"));
}
#[test]
fn chunk_payload_rejects_declared_size_past_container() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4])]);
let mut info = inspect_dxbc(&blob).expect("valid container");
// A declared size that runs past container_size must yield None, not
// a panic and not a slice clipped to the container.
info.chunks[0].size = u32::MAX;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// Presence without trusting the size still holds.
assert!(info.has_chunk_tag(b"SFI0"));
// A forged public ChunkInfo must not treat the DXBC header or offset
// table as a chunk header.
info.chunks[0].size = 4;
info.chunks[0].offset = 0;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// A header offset past the container must also yield None.
info.chunks[0].offset = u32::MAX;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
// A chunk header that would end exactly one byte past the container.
info.chunks[0].offset = info.container_size - 7;
info.chunks[0].size = 0;
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
}
#[test]
fn chunk_payload_absent_fourcc() {
let blob = synthetic_dxil_blob();
let info = inspect_dxbc(&blob).expect("valid");
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
assert!(!info.has_chunk_tag(b"SFI0"));
}
#[test]
fn chunk_payload_zero_size_returns_empty_slice() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[])]);
let info = inspect_dxbc(&blob).expect("valid");
assert!(info.has_chunk_tag(b"SFI0"));
let payload = info.chunk_payload(&blob, b"SFI0");
assert_eq!(payload, Some(&[][..]));
}
#[test]
fn chunk_payload_exact_fit_at_container_end() {
let payload = [0xAA, 0xBB, 0xCC, 0xDD];
let blob = build_synthetic_dxbc(&[(b"SFI0", &payload)]);
let info = inspect_dxbc(&blob).expect("valid");
// The chunk is the last thing in the container; payload ends exactly
// at container_size.
let chunk = &info.chunks[0];
assert_eq!(
u64::from(chunk.offset) + 8 + u64::from(chunk.size),
u64::from(info.container_size)
);
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(payload.as_slice()));
}
#[test]
fn chunk_payload_truncated_container_slice() {
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4, 5, 6, 7, 8])]);
let info = inspect_dxbc(&blob).expect("valid");
// Pass a slice shorter than container_size.
let short = &blob[..blob.len() - 4];
assert_eq!(info.chunk_payload(short, b"SFI0"), None);
}
#[test]
fn chunk_payload_first_duplicate_wins() {
let first = [0x11, 0x22];
let second = [0x33, 0x44, 0x55];
let blob = build_synthetic_dxbc(&[(b"SFI0", &first), (b"SFI0", &second)]);
let info = inspect_dxbc(&blob).expect("valid");
assert_eq!(info.chunks.len(), 2);
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(first.as_slice()));
}
}
@@ -0,0 +1,10 @@
[package]
name = "gfx10-translate"
description = "BetterXen's GFX10.3 (RDNA 2) console shader translator: decoder, HLSL translation, coverage"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[lints]
workspace = true
@@ -0,0 +1,48 @@
# gfx10-translate
BetterXen's own translator for console shaders (roadmap, Picture stage): GFX10.3 (RDNA 2) machine code to HLSL, which the public DXC compiles to DXIL for D3DMetal. It is mechanical: one rule per instruction, registers as variables. Control flow is not translated yet.
| Module | Job |
| --- | --- |
| `container` | The stage code inside a console shader container (`XBCH` → `FSSM` → stage record). |
| `inflate` | zlib, ported from BetterXen's own `shims/xcrdapi/zlib_inflate.cpp` (no third-party dependency). |
| `decode` | Instruction words → instructions with structured operands, printed as LLVM-style text. |
| `opcodes` | **Generated.** Opcode → mnemonic per encoding format, and the buffer formats. |
| `translate` | Instructions → HLSL and the host input layout, through family tables and specific rules. |
| `coverage` | What blocks translation across a local folder of shaders, ranked. |
## Use
```sh
bx-cli shader coverage <folder> # *_VS.* / *_PS.* console shaders, on your machine
bx-cli shader translate <vs> <ps> --out <dir> # <vs key>_<ps key>.vs.hlsl / .ps.hlsl / .il
cargo run -p gfx10-translate --example listing -- <shader> # decoded listing
cargo run -p gfx10-translate --example why -- PS <shader>... # why each shader is refused
```
Game shaders stay on your machine: never commit a shader, a listing, or anything else from the target build (AGENTS.md Section 6).
## Adding an instruction
1. Run `bx-cli shader coverage` on your shaders and take the top blocker no open pull request covers (AGENTS.md Section 0, Step 3).
2. If it fits a family (`VOP2_UINT`, `VOP2_FLOAT`, `VOP1_FLOAT`, `SOP2_UINT` in `src/translate.rs`), add one row. Otherwise add an arm in `Translator::step`.
3. Write the expected HLSL from the instruction's definition, not from your code, and add a test in `tests/translate.rs` with the instruction words from `llvm-mc -show-encoding`.
4. Check the instruction's semantics against the console compiler's listing for a shader of our own (`shader-transpiler/corpus/`, source rank 2) where the ISA reference is unclear.
## Where the facts come from
- **Opcode names and buffer formats:** `scripts/console-shader/gen_opcodes.py` asks the public LLVM disassembler (`llvm-mc`, Apache-2.0 WITH LLVM-exception) to name every opcode value of every format: gfx1030 first, gaps filled from gfx1010. The console compiler also emits a few GFX10.1 instructions (`v_mac_f32`, `v_mad_f32`, `v_madak_f32`, `v_madmk_f32`) that LLVM knows only there. Only the facts are committed; LLVM is not.
- **Encoding layouts:** AMD's public RDNA 2 instruction set reference. `tests/llvm_vectors.txt` (from `scripts/console-shader/gen_llvm_vectors.py`) holds 127 instructions encoded and printed by `llvm-mc`. The decoder must print the same text for each.
- **Translation rules:** a port of the Python prototype `scripts/console-shader/translate.py`, kept as the reference. `tests/goldens/` holds small shaders of our own, assembled by `llvm-mc` and translated by the prototype (`scripts/console-shader/gen_translate_goldens.py`). The Rust output must be identical.
- **Container layout and the shader model:** inferences from the target build (module comments), AGENTS.md Section 6.
## Differences from the prototype
- `s_movk_i32` sign-extends its 16-bit immediate. The prototype read it unsigned.
- Output modifiers (`clamp`, `mul:`/`div:`, `op_sel`, `abs`) are refused on every VOP3 instruction, not only on `_e64` forms.
- `v_fma_mix*` with `op_sel_hi` all zero (all 32-bit sources) is accepted. The prototype refused it.
- **New rules:**
- the multiply-add family (`v_mac_f32`, `v_mad_f32`, `v_madak/madmk_f32`, `v_fmaak/fmamk_f32`);
- 32-lane execution-mask bookkeeping (`s_mov_b32 sN, exec_lo`, `s_wqm_b32`, `s_and_b32 exec_lo, exec_lo, sN`);
- compressed exports with a disabled half.
- **Cache keys use standard FNV-1a 64.** The prototype's offset basis is missing its last digit (`1469598103934665603`), so its keys differ. The shim's cache lookup must use the same function as this crate when translation moves into `bx_shader_bridge.dll`.
@@ -0,0 +1,26 @@
//! Prints the decoded listing of a shader: word index, words, and LLVM-style text.
//! usage: cargo run -p gfx10-translate --example listing -- <shader>
use gfx10_translate::container::code_words;
use gfx10_translate::decode::decode_one;
fn main() {
let path = std::env::args().nth(1).expect("usage: listing <shader>");
let words = code_words(&std::fs::read(&path).expect("read")).expect("container");
let mut at = 0;
while at < words.len() {
match decode_one(&words, at) {
Ok(inst) => {
let hex: Vec<String> = inst.words.iter().map(|w| format!("{w:08x}")).collect();
println!("{at:5} {:<26} {inst}", hex.join(" "));
at += inst.words.len();
if inst.name == "s_endpgm" {
break;
}
}
Err(e) => {
println!("{at:5} {:08x} error: {e}", words[at]);
break;
}
}
}
}
@@ -0,0 +1,48 @@
//! Prints why each given shader does not translate, with the instruction words involved.
//! usage: cargo run -p gfx10-translate --example why -- <VS|PS> <shader>...
use gfx10_translate::container::code_words;
use gfx10_translate::decode::{DecodeError, decode};
use gfx10_translate::translate::{Stage, Translator};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let stage = if args.first().map(String::as_str) == Some("VS") {
Stage::Vertex
} else {
Stage::Pixel
};
for path in &args[1..] {
let Ok(blob) = std::fs::read(path) else {
continue;
};
let words = match code_words(&blob) {
Ok(w) => w,
Err(e) => {
println!("{path}: {e}");
continue;
}
};
match decode(&words) {
Err(e) => {
let at = match e {
DecodeError::UnknownOpcode { at, .. }
| DecodeError::UnknownEncoding { at, .. }
| DecodeError::Truncated { at } => at,
DecodeError::NoEndProgram => 0,
};
let around: Vec<String> = words
.iter()
.skip(at)
.take(3)
.map(|w| format!("{w:08x}"))
.collect();
println!("{path}: {e}: {}", around.join(" "));
}
Ok(insts) => {
if let Err(e) = Translator::new(stage).run(&insts) {
println!("{path}: {e}");
}
}
}
}
}
@@ -0,0 +1,185 @@
//! The GPU code of one stage from a console shader container.
//!
//! A console container is a DXBC file whose DXIL part carries no bitcode. The console code is in
//! an `XBCH` record: magic, version, compressed size (u64), uncompressed size (u64), then a zlib
//! stream. It inflates to an `FSSM` block: a 16-byte header (magic, version, size), then offsets
//! relative to the end of that header. One of the per-stage slots at 0x18..0x78 is not
//! 0xDEADBEEF filler and locates the stage record, whose first two u64 fields are the code offset
//! and size. The code starts with 12-byte header records (a VOP3 word whose top half is 0xD580,
//! `v_nop` with a literal) before the first instruction.
//!
//! These are inferences from containers of the project-authorized target build (AGENTS.md
//! section 6), checked by the synthetic container in the tests below.
use crate::inflate::zlib_inflate;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContainerError {
NoXbch,
BadXbch(&'static str),
NoStageRecord,
BadCode(&'static str),
}
impl fmt::Display for ContainerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoXbch => write!(f, "container has no XBCH record"),
Self::BadXbch(why) => write!(f, "XBCH record: {why}"),
Self::NoStageRecord => write!(f, "FSSM block has no stage record"),
Self::BadCode(why) => write!(f, "stage code: {why}"),
}
}
}
impl std::error::Error for ContainerError {}
const HEADER_RECORD_TOP: u32 = 0xD580;
const FILLER: u64 = 0xDEAD_BEEF_DEAD_BEEF;
const MAX_FSSM: usize = 64 << 20;
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
fn u64_at(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_le_bytes(b.get(at..at + 8)?.try_into().ok()?))
}
/// The stage code inside a console container, header records included.
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
let at = blob
.windows(4)
.position(|w| w == b"XBCH")
.ok_or(ContainerError::NoXbch)?;
let csize = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
let usize_ = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
let stream = blob
.get(at + 24..at.saturating_add(24).saturating_add(csize))
.ok_or(ContainerError::BadXbch("compressed size past the end"))?;
let fssm = zlib_inflate(stream, usize_.min(MAX_FSSM))
.map_err(|_| ContainerError::BadXbch("zlib stream"))?;
if fssm.len() != usize_ || fssm.get(..4) != Some(b"FSSM") {
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
}
const BASE: usize = 16;
let record = (0x18..0x78)
.step_by(8)
.filter_map(|slot| u64_at(&fssm, slot))
.find(|&v| v != FILLER)
.ok_or(ContainerError::NoStageRecord)? as usize
+ BASE;
let offset = u64_at(&fssm, record).ok_or(ContainerError::NoStageRecord)? as usize;
let size = u64_at(&fssm, record + 8).ok_or(ContainerError::NoStageRecord)? as usize;
let code = fssm
.get(BASE + offset..BASE + offset + size)
.ok_or(ContainerError::BadCode("outside the FSSM block"))?;
if code.len() < 12 || u32_at(code, 0).map(|w| w >> 16) != Some(HEADER_RECORD_TOP) {
return Err(ContainerError::BadCode(
"does not start with the expected header records",
));
}
Ok(code.to_vec())
}
/// The instruction words of a stage: from a console container (`DXBC` magic) or a raw code blob,
/// with the leading 12-byte header records skipped.
pub fn code_words(blob: &[u8]) -> Result<Vec<u32>, ContainerError> {
let code = if blob.get(..4) == Some(b"DXBC") {
container_code(blob)?
} else {
blob.to_vec()
};
let mut at = 0;
while at + 12 <= code.len() && u32_at(&code, at).map(|w| w >> 16) == Some(HEADER_RECORD_TOP) {
at += 12;
}
Ok(code[at..]
.chunks_exact(4)
.map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &byte in data {
a = (a + u32::from(byte)) % 65521;
b = (b + a) % 65521;
}
(b << 16) | a
}
/// zlib stream with one stored block (no compression), built by hand.
fn stored(data: &[u8]) -> Vec<u8> {
let len = data.len() as u16;
let mut s = vec![0x78, 0x01, 0x01];
s.extend_from_slice(&len.to_le_bytes());
s.extend_from_slice(&(!len).to_le_bytes());
s.extend_from_slice(data);
s.extend_from_slice(&adler32(data).to_be_bytes());
s
}
/// A container laid out as the module comment describes: one header record, then two
/// instruction words, the stage record in slot 0x30.
fn container(code_words_after_header: &[u32]) -> Vec<u8> {
let mut code = Vec::new();
code.extend_from_slice(&0xD580_0000u32.to_le_bytes());
code.extend_from_slice(&[0u8; 8]);
for w in code_words_after_header {
code.extend_from_slice(&w.to_le_bytes());
}
let mut fssm = vec![0u8; 0x100];
fssm[..4].copy_from_slice(b"FSSM");
for slot in (0x18..0x78).step_by(8) {
fssm[slot..slot + 8].copy_from_slice(&FILLER.to_le_bytes());
}
let record = 0x80usize; // relative to byte 16
fssm[0x30..0x38].copy_from_slice(&(record as u64).to_le_bytes());
let code_offset = 0xA0u64;
fssm[16 + record..16 + record + 8].copy_from_slice(&code_offset.to_le_bytes());
fssm[16 + record + 8..16 + record + 16].copy_from_slice(&(code.len() as u64).to_le_bytes());
fssm.resize(16 + code_offset as usize, 0);
fssm.extend_from_slice(&code);
let stream = stored(&fssm);
let mut blob = b"DXBC".to_vec();
blob.extend_from_slice(&[0u8; 28]);
blob.extend_from_slice(b"XBCH");
blob.extend_from_slice(&1u32.to_le_bytes());
blob.extend_from_slice(&(stream.len() as u64).to_le_bytes());
blob.extend_from_slice(&(fssm.len() as u64).to_le_bytes());
blob.extend_from_slice(&stream);
blob
}
#[test]
fn finds_the_stage_code_and_skips_header_records() {
let blob = container(&[0xBF81_0000, 0x1234_5678]);
assert_eq!(code_words(&blob).unwrap(), vec![0xBF81_0000, 0x1234_5678]);
}
#[test]
fn raw_code_blobs_pass_through() {
let mut raw = 0xD580_0000u32.to_le_bytes().to_vec();
raw.extend_from_slice(&[0u8; 8]);
raw.extend_from_slice(&0xBF81_0000u32.to_le_bytes());
assert_eq!(code_words(&raw).unwrap(), vec![0xBF81_0000]);
}
#[test]
fn reports_what_is_missing() {
assert_eq!(
code_words(b"DXBC without a record"),
Err(ContainerError::NoXbch)
);
let mut blob = container(&[0xBF81_0000]);
let at = blob.windows(4).position(|w| w == b"XBCH").unwrap();
blob[at + 24] = 0; // break the zlib header
assert!(matches!(code_words(&blob), Err(ContainerError::BadXbch(_))));
}
}
@@ -0,0 +1,117 @@
//! Translator coverage over a local folder of console shaders.
//!
//! Each file is one stage: a console container or a raw code blob, named `*_VS.*` or `*_PS.*`
//! (other files are skipped). Every shader is decoded and translated on its own; the first
//! reason it is refused counts as its blocker. The ranked list says which instruction or feature
//! to add next. Shaders come from a collaborator's own runs and stay on their machine.
use crate::container::code_words;
use crate::decode::decode;
use crate::translate::{Stage, Translator};
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::Path;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Coverage {
pub shaders: usize,
pub translated: usize,
/// Blocker -> shaders it stops.
pub blockers: BTreeMap<String, usize>,
}
impl Coverage {
/// Blockers, most frequent first.
pub fn ranked(&self) -> Vec<(&str, usize)> {
let mut v: Vec<(&str, usize)> = self
.blockers
.iter()
.map(|(k, n)| (k.as_str(), *n))
.collect();
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
v
}
}
/// The blocker key of a refusal: the instruction name when one was refused, else the reason
/// with register numbers and constants folded so similar cases count together.
pub fn blocker_key(reason: &str) -> String {
if let Some(rest) = reason.strip_prefix("instruction '") {
return rest.split([' ', '\'']).next().unwrap_or(rest).to_string();
}
let mut out = String::new();
let mut chars = reason.chars().peekable();
while let Some(c) = chars.next() {
if c.is_ascii_digit() {
while chars.peek().is_some_and(|d| d.is_ascii_alphanumeric()) {
chars.next();
}
out.push('#');
} else {
out.push(c);
}
}
out.chars().take(80).collect()
}
/// Why one stage does not translate, or `None` when it does.
pub fn stage_blocker(blob: &[u8], stage: Stage) -> Option<String> {
let words = match code_words(blob) {
Ok(w) => w,
Err(e) => return Some(format!("container: {e}")),
};
let insts = match decode(&words) {
Ok(i) => i,
Err(e) => return Some(blocker_key(&format!("decode: {e}"))),
};
let mut t = Translator::new(stage);
t.run(&insts).err().map(|e| blocker_key(&e.0))
}
pub fn scan(dir: &Path) -> io::Result<Coverage> {
let mut cov = Coverage::default();
let mut paths: Vec<_> = fs::read_dir(dir)?
.flatten()
.map(|e| e.path())
.filter(|p| p.is_file())
.collect();
paths.sort();
for path in paths {
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let stage = if name.contains("_VS.") {
Stage::Vertex
} else if name.contains("_PS.") {
Stage::Pixel
} else {
continue;
};
let blob = fs::read(&path)?;
cov.shaders += 1;
match stage_blocker(&blob, stage) {
None => cov.translated += 1,
Some(key) => *cov.blockers.entry(key).or_default() += 1,
}
}
Ok(cov)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blocker_keys_group_similar_reasons() {
assert_eq!(
blocker_key("instruction 'v_cmp_lt_f32_e32 vcc_lo, v1, v2'"),
"v_cmp_lt_f32_e32"
);
assert_eq!(
blocker_key("descriptor load from 's[12:13]' (provenance Sgpr(12))"),
"descriptor load from 's[#:#]' (provenance Sgpr(#))"
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,381 @@
//! zlib (RFC 1950) / deflate (RFC 1951) decoder for console shader containers.
//!
//! A port of BetterXen's own `shims/xcrdapi/zlib_inflate.cpp`, so the crate needs no third-party
//! dependency. It decodes a whole stream into a growing buffer and checks the Adler-32 trailer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InflateError {
BadHeader,
BadData,
Truncated,
BadChecksum,
TooLarge,
}
struct Bits<'a> {
data: &'a [u8],
pos: usize,
buffer: u32,
count: u32,
overrun: bool,
}
impl Bits<'_> {
// RFC 1951 3.1.1: data elements are packed starting with the least significant bit.
fn get(&mut self, n: u32) -> u32 {
while self.count < n {
let Some(&byte) = self.data.get(self.pos) else {
self.overrun = true;
return 0;
};
self.pos += 1;
self.buffer |= u32::from(byte) << self.count;
self.count += 8;
}
let value = if n == 32 {
self.buffer
} else {
self.buffer & ((1u32 << n) - 1)
};
self.buffer = if n == 32 { 0 } else { self.buffer >> n };
self.count -= n;
value
}
fn align_to_byte(&mut self) {
self.buffer >>= self.count & 7;
self.count -= self.count & 7;
}
}
const MAX_BITS: usize = 15;
/// Canonical Huffman decoding (RFC 1951 3.2.2): counts per code length, symbols sorted by code.
struct Huffman {
counts: [u16; MAX_BITS + 1],
symbols: [u16; 320],
}
impl Huffman {
/// `None` for an over-subscribed set of lengths. An incomplete set is allowed (a single
/// distance code is legal); decoding an unassigned code then fails.
fn build(lengths: &[u8]) -> Option<Self> {
let mut h = Huffman {
counts: [0; MAX_BITS + 1],
symbols: [0; 320],
};
for &len in lengths {
h.counts[usize::from(len)] += 1;
}
h.counts[0] = 0;
let mut left: i32 = 1;
for &count in &h.counts[1..] {
left = (left << 1) - i32::from(count);
if left < 0 {
return None;
}
}
let mut offsets = [0u16; MAX_BITS + 2];
for len in 1..=MAX_BITS {
offsets[len + 1] = offsets[len] + h.counts[len];
}
for (symbol, &len) in lengths.iter().enumerate() {
if len != 0 {
let slot = &mut offsets[usize::from(len)];
h.symbols[usize::from(*slot)] = symbol as u16;
*slot += 1;
}
}
Some(h)
}
// Huffman codes are packed most significant bit first, one bit at a time.
fn decode(&self, input: &mut Bits) -> Option<usize> {
let (mut code, mut first, mut index) = (0i32, 0i32, 0i32);
for len in 1..=MAX_BITS {
code |= input.get(1) as i32;
if input.overrun {
return None;
}
let count = i32::from(self.counts[len]);
if code - first < count {
return Some(usize::from(self.symbols[(index + code - first) as usize]));
}
index += count;
first = (first + count) << 1;
code <<= 1;
}
None
}
}
// RFC 1951 3.2.5 length and distance tables.
const LENGTH_BASE: [u16; 29] = [
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131,
163, 195, 227, 258,
];
const LENGTH_EXTRA: [u8; 29] = [
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
];
const DIST_BASE: [u16; 30] = [
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
];
const DIST_EXTRA: [u8; 30] = [
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,
13,
];
fn codes(
input: &mut Bits,
out: &mut Vec<u8>,
limit: usize,
lit: &Huffman,
dist: &Huffman,
) -> Result<(), InflateError> {
let fail = |input: &Bits| {
if input.overrun {
InflateError::Truncated
} else {
InflateError::BadData
}
};
loop {
let symbol = lit.decode(input).ok_or_else(|| fail(input))?;
if symbol < 256 {
if out.len() >= limit {
return Err(InflateError::TooLarge);
}
out.push(symbol as u8);
continue;
}
if symbol == 256 {
return Ok(());
}
let li = symbol - 257;
if li >= 29 {
return Err(InflateError::BadData);
}
let length = usize::from(LENGTH_BASE[li]) + input.get(u32::from(LENGTH_EXTRA[li])) as usize;
let ds = dist.decode(input).ok_or_else(|| fail(input))?;
if ds >= 30 {
return Err(InflateError::BadData);
}
let distance = usize::from(DIST_BASE[ds]) + input.get(u32::from(DIST_EXTRA[ds])) as usize;
if input.overrun {
return Err(InflateError::Truncated);
}
if distance > out.len() {
return Err(InflateError::BadData);
}
if length > limit - out.len() {
return Err(InflateError::TooLarge);
}
for _ in 0..length {
let byte = out[out.len() - distance];
out.push(byte);
}
}
}
fn dynamic_tables(input: &mut Bits) -> Result<(Huffman, Huffman), InflateError> {
let hlit = input.get(5) as usize + 257;
let hdist = input.get(5) as usize + 1;
let hclen = input.get(4) as usize + 4;
if input.overrun {
return Err(InflateError::Truncated);
}
if hlit > 286 || hdist > 30 {
return Err(InflateError::BadData);
}
const ORDER: [usize; 19] = [
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
];
let mut lengths = [0u8; 320];
for &slot in &ORDER[..hclen] {
lengths[slot] = input.get(3) as u8;
}
if input.overrun {
return Err(InflateError::Truncated);
}
let code_lengths = Huffman::build(&lengths[..19]).ok_or(InflateError::BadData)?;
lengths = [0u8; 320];
let mut index = 0;
while index < hlit + hdist {
let symbol = code_lengths.decode(input).ok_or(if input.overrun {
InflateError::Truncated
} else {
InflateError::BadData
})?;
if symbol < 16 {
lengths[index] = symbol as u8;
index += 1;
continue;
}
let (value, repeat) = match symbol {
16 => {
if index == 0 {
return Err(InflateError::BadData);
}
(lengths[index - 1], 3 + input.get(2) as usize)
}
17 => (0, 3 + input.get(3) as usize),
_ => (0, 11 + input.get(7) as usize),
};
if input.overrun {
return Err(InflateError::Truncated);
}
if index + repeat > hlit + hdist {
return Err(InflateError::BadData);
}
lengths[index..index + repeat].fill(value);
index += repeat;
}
if lengths[256] == 0 {
return Err(InflateError::BadData); // no end-of-block code
}
let lit = Huffman::build(&lengths[..hlit]).ok_or(InflateError::BadData)?;
let dist = Huffman::build(&lengths[hlit..hlit + hdist]).ok_or(InflateError::BadData)?;
Ok((lit, dist))
}
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for chunk in data.chunks(5552) {
for &byte in chunk {
a += u32::from(byte);
b += a;
}
a %= 65521;
b %= 65521;
}
(b << 16) | a
}
/// Decodes a whole zlib stream, producing at most `limit` bytes.
pub fn zlib_inflate(input: &[u8], limit: usize) -> Result<Vec<u8>, InflateError> {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if input.len() < 6 {
return Err(InflateError::BadHeader);
}
let (cmf, flg) = (input[0], input[1]);
if cmf & 0x0F != 8
|| cmf >> 4 > 7
|| ((u32::from(cmf) << 8) | u32::from(flg)) % 31 != 0
|| flg & 0x20 != 0
{
return Err(InflateError::BadHeader);
}
let mut bits = Bits {
data: &input[2..],
pos: 0,
buffer: 0,
count: 0,
overrun: false,
};
let mut out = Vec::new();
loop {
let final_block = bits.get(1);
let kind = bits.get(2);
if bits.overrun {
return Err(InflateError::Truncated);
}
match kind {
0 => {
bits.align_to_byte();
let len = bits.get(16) as usize;
let nlen = bits.get(16) as usize;
if bits.overrun {
return Err(InflateError::Truncated);
}
if len ^ 0xFFFF != nlen {
return Err(InflateError::BadData);
}
// After aligning, the bit buffer is empty: copy straight from the byte stream.
let stored = bits
.data
.get(bits.pos..bits.pos + len)
.ok_or(InflateError::Truncated)?;
if len > limit - out.len() {
return Err(InflateError::TooLarge);
}
out.extend_from_slice(stored);
bits.pos += len;
}
1 => {
let mut lengths = [0u8; 288];
lengths[..144].fill(8);
lengths[144..256].fill(9);
lengths[256..280].fill(7);
lengths[280..].fill(8);
let lit = Huffman::build(&lengths).ok_or(InflateError::BadData)?;
let dist = Huffman::build(&[5u8; 30]).ok_or(InflateError::BadData)?;
codes(&mut bits, &mut out, limit, &lit, &dist)?;
}
2 => {
let (lit, dist) = dynamic_tables(&mut bits)?;
codes(&mut bits, &mut out, limit, &lit, &dist)?;
}
_ => return Err(InflateError::BadData),
}
if final_block != 0 {
break;
}
}
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
bits.align_to_byte();
let trailer = bits.pos - (bits.count / 8) as usize;
let t = bits
.data
.get(trailer..trailer + 4)
.ok_or(InflateError::Truncated)?;
if adler32(&out) != u32::from_be_bytes([t[0], t[1], t[2], t[3]]) {
return Err(InflateError::BadChecksum);
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
// zlib.compress(b"hello hello hello hello, compressed by CPython zlib " * 3, 9), made with CPython,
// independently of this code: dynamic Huffman codes and back-references.
const HELLO: [u8; 49] = [
0x78, 0xda, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0xc8, 0x40, 0x27, 0x75, 0x14, 0x92, 0xf3,
0x73, 0x0b, 0x8a, 0x52, 0x8b, 0x8b, 0x53, 0x53, 0x14, 0x92, 0x2a, 0x15, 0x9c, 0x03, 0x2a,
0x4b, 0x32, 0xf2, 0xf3, 0x14, 0xaa, 0x72, 0x32, 0x93, 0x30, 0x55, 0xd3, 0x48, 0x0f, 0x00,
0x91, 0x2d, 0x39, 0x07,
];
#[test]
fn inflates_a_cpython_stream() {
let expected = b"hello hello hello hello, compressed by CPython zlib ".repeat(3);
assert_eq!(zlib_inflate(&HELLO, 4096).unwrap(), expected);
assert_eq!(
zlib_inflate(&HELLO[..HELLO.len() - 3], 4096),
Err(InflateError::Truncated)
);
assert_eq!(zlib_inflate(&HELLO, 10), Err(InflateError::TooLarge));
}
#[test]
fn rejects_what_is_not_zlib() {
assert_eq!(
zlib_inflate(b"\x00\x00\x00\x00\x00\x00", 64),
Err(InflateError::BadHeader)
);
assert_eq!(zlib_inflate(b"x", 64), Err(InflateError::BadHeader));
}
#[test]
fn stored_block_round_trip_and_checksum() {
// A stored block holding "abc": header, final+type 0, LEN, NLEN, data, Adler-32.
let mut s = vec![0x78, 0x01, 0x01, 0x03, 0x00, 0xfc, 0xff, b'a', b'b', b'c'];
s.extend_from_slice(&adler32(b"abc").to_be_bytes());
assert_eq!(zlib_inflate(&s, 64).unwrap(), b"abc");
*s.last_mut().unwrap() ^= 1;
assert_eq!(zlib_inflate(&s, 64), Err(InflateError::BadChecksum));
assert_eq!(zlib_inflate(&s, 2), Err(InflateError::TooLarge));
}
}
@@ -0,0 +1,36 @@
//! Track D: BetterXen's own GFX10.3 (RDNA 2) shader translator (roadmap, Picture stage).
//!
//! Console vertex and pixel shaders carry RDNA 2 machine code; D3DMetal needs DXIL. This crate
//! translates mechanically, one rule per instruction, with registers as variables:
//!
//! 1. [`container`]: the stage code inside a console container.
//! 2. [`decode`]: code words to instructions, with names from the generated [`opcodes`] tables.
//! 3. [`translate`]: instructions to HLSL, through family tables plus specific rules. The public
//! DXC compiles that HLSL to DXIL.
//! 4. [`coverage`]: which instructions block the most shaders in a local folder.
//!
//! The Python prototype it ports, `scripts/console-shader/translate.py`, stays as the reference
//! for identical output. Next steps (handoff issues): more instruction families, control flow as
//! numbered blocks, texture and sampler forms, and translation inside `bx_shader_bridge.dll` at
//! first draw. See this crate's README.
pub mod container;
pub mod coverage;
pub mod decode;
pub mod inflate;
#[rustfmt::skip]
pub mod opcodes;
pub mod translate;
pub use decode::{Format, Inst, Operand, decode};
pub use translate::{Stage, Translation, Unsupported, translate_pair};
/// Decodes and translates a VS/PS pair given as console containers or raw code blobs.
pub fn translate_blobs(vs: &[u8], ps: &[u8]) -> Result<Translation, Unsupported> {
let words = |blob: &[u8], what: &str| {
container::code_words(blob).map_err(|e| Unsupported(format!("{what}: {e}")))
};
let vs = decode(&words(vs, "VS")?).map_err(|e| Unsupported(format!("VS decode: {e}")))?;
let ps = decode(&words(ps, "PS")?).map_err(|e| Unsupported(format!("PS decode: {e}")))?;
translate_pair(&vs, &ps)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
FETCH 2
@@ -0,0 +1 @@
c8080000 c8090001 c80e0102 b0141234 be9503f2 8f168214 88178716 87171517 89171417 93171617 8017c017 80971417 90178417 83981617 84981418 be990b18 939aff19 00100000 ba801801 00000003 34080482 2c080890 30080881 360808ff 000000ff 38080704 3a080504 4c080704 4e080504 16080704 26080504 28080704 d5690004 02020504 d56a0004 02003304 d51a0004 02020818 060a04f0 100a0aff 3e800000 080a0705 0a0a0705 200a0505 1e0a0705 d5030005 42020505 d5080005 22020705 d5040005 02020505 d5100005 02002b05 560a0702 7e0c5505 7e0c5d06 7e0c6706 7e0c4906 7e0c4106 7e0c4b06 7e0c4f06 7e0c4306 7e0c4706 7e0c4506 7e0c6b06 7e0c6d06 d5aa0006 22010106 7e0e0d04 7e0e0b04 7e101107 d5570007 03c90107 d54b0007 23ca0507 0e0e0707 5e120d07 cc21000a 0c0e0509 cc22400a 1c2a1309 7e160217 4a16110b f8001c0f 00000a09 bf810000
@@ -0,0 +1,84 @@
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0) : SV_Target0 {
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
uint v5 = 0;
uint v6 = 0;
uint v7 = 0;
uint v8 = 0;
uint v9 = 0;
uint v10 = 0;
uint v11 = 0;
uint s20 = 0;
uint s21 = 0;
uint s22 = 0;
uint s23 = 0;
uint s24 = 0;
uint s25 = 0;
v2 = asuint(attr0.x);
v3 = asuint(attr0.y);
s20 = 4660u;
s21 = asuint(1.0f);
s22 = s20 << (2u & 31u);
s23 = (s22 | 7u);
s23 = (s23 & s21);
s23 = (s23 ^ s20);
s23 = (s23 * s22);
s23 = (s23 + 64u);
s23 = (s23 - s20);
s23 = (s23 >> (4u & 31u));
s24 = min(s23, s22);
s24 = max(s24, s20);
s25 = reversebits(s24);
v4 = (v2 << (2u & 31u));
v4 = (v4 >> (16u & 31u));
v4 = (uint)((int)v4 >> (1u & 31u));
v4 = (0xffu & v4);
v4 = (v4 | v3);
v4 = (v4 ^ v2);
v4 = (v4 - v3);
v4 = (v2 - v4);
v4 = ((v4 & 0xffffffu) * (v3 & 0xffffffu));
v4 = min(v4, v2);
v4 = max(v4, v3);
v4 = (v4 * v2);
v4 = (uint)(((uint64_t)v4 * (uint64_t)s25) >> 32);
v4 = (v4 << (s24 & 31u));
v5 = asuint(asfloat(asuint(0.5f)) + asfloat(v2));
v5 = asuint(asfloat(0x3e800000u) * asfloat(v5));
v5 = asuint(asfloat(v5) - asfloat(v3));
v5 = asuint((asfloat(v3) - asfloat(v5)));
v5 = asuint(max(asfloat(v5), asfloat(v2)));
v5 = asuint(min(asfloat(v5), asfloat(v3)));
v5 = asuint(asfloat(v5) + asfloat((asuint(-asfloat(v2)))));
v5 = asuint(asfloat((asuint(-asfloat(v5)))) * asfloat(v3));
v5 = asuint((asfloat(v5) - asfloat(v2)));
v5 = asuint(max(asfloat(v5), asfloat(s21)));
v5 = asuint(mad(asfloat(v2), asfloat(v3), asfloat(v5)));
v6 = asuint((1.0f / asfloat(v5)));
v6 = asuint(rsqrt(asfloat(v6)));
v6 = asuint(sqrt(asfloat(v6)));
v6 = asuint(floor(asfloat(v6)));
v6 = asuint(frac(asfloat(v6)));
v6 = asuint(exp2(asfloat(v6)));
v6 = asuint(log2(asfloat(v6)));
v6 = asuint(trunc(asfloat(v6)));
v6 = asuint(round(asfloat(v6)));
v6 = asuint(ceil(asfloat(v6)));
v6 = asuint(sin(asfloat(v6) * 6.2831853f));
v6 = asuint(cos(asfloat(v6) * 6.2831853f));
v6 = asuint((1.0f / asfloat((asuint(-asfloat(v6))))));
v7 = asuint((float)asuint(asfloat(v4)));
v7 = asuint((float)asint(asfloat(v4)));
v8 = (uint)(int)asfloat(v7);
v7 = asuint(max(min(asfloat(v7), asfloat(0u)), min(max(asfloat(v7), asfloat(0u)), asfloat(asuint(1.0f)))));
v7 = asuint(mad(asfloat((asuint(-asfloat(v7)))), asfloat(v2), asfloat(asuint(1.0f))));
v7 = asuint((asfloat(v7) == 0.0f || asfloat(v3) == 0.0f) ? 0.0f : asfloat(v7) * asfloat(v3));
v9 = f32tof16(asfloat(v7)) | (f32tof16(asfloat(v6)) << 16);
v10 = (v10 & 0xffff0000u) | f32tof16(mad(f16tof32(v9 & 0xffffu), asfloat(v2), asfloat(v3)));
v10 = (v10 & 0xffffu) | (f32tof16(mad(f16tof32(v9 & 0xffffu), f16tof32(v9 & 0xffffu), f16tof32(v10 & 0xffffu))) << 16);
v11 = s23;
v11 = v11 + v8;
float4 exp0_mrt0 = float4(f16tof32(v9 & 0xffffu), f16tof32(v9 >> 16), f16tof32(v10 & 0xffffu), f16tof32(v10 >> 16));
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
}
@@ -0,0 +1 @@
be842104 f80008cf 07060504 f800020f 0b0a0908 bf810000
@@ -0,0 +1,17 @@
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; };
VSOut main(float4 a0 : ATTR0, float4 a1 : ATTR1) {
uint v4 = asuint(a0.x);
uint v5 = asuint(a0.y);
uint v6 = asuint(a0.z);
uint v7 = asuint(a0.w);
uint v8 = asuint(a1.x);
uint v9 = asuint(a1.y);
uint v10 = asuint(a1.z);
uint v11 = asuint(a1.w);
float4 exp0_pos0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
float4 exp1_param0 = float4(asfloat(v8), asfloat(v9), asfloat(v10), asfloat(v11));
VSOut o;
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
return o;
}
@@ -0,0 +1,4 @@
ATTR 0 17 0 0
ATTR 1 28 1 8
ATTR 2 7 0 8
USE CB 1
@@ -0,0 +1 @@
c80a0402 c80e0702 c8100200 c8110201 f8001807 00040302 bf810000
@@ -0,0 +1,10 @@
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0, float4 attr1 : PARAM1) : SV_Target0 {
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
v2 = asuint(attr1.x);
v3 = asuint(attr1.w);
v4 = asuint(attr0.z);
float4 exp0_mrt0 = float4(asfloat(v2), asfloat(v3), asfloat(v4), 0.0f);
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
}
@@ -0,0 +1 @@
f4080300 fa000000 f4080400 fa000010 f4080504 fa000020 4a020002 bf8cc07f e0342000 80030201 e9c32008 80040401 e03c2008 80030801 e0382000 80050c00 bf8c3f70 7e1602f2 f80008cf 0b080302 f800020f 07060504 f800021f 0f0e0d0c bf810000
@@ -0,0 +1,50 @@
cbuffer CB1 : register(b1, space100) { uint4 cb1[4096]; };
uint cb1_word(uint w) { return cb1[w >> 2][w & 3]; }
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; float4 param1 : PARAM1; };
VSOut main(uint2 in0 : ATTR0, float4 in1 : ATTR1, uint3 in2 : ATTR2) {
uint v0 = 0;
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
uint v5 = 0;
uint v6 = 0;
uint v7 = 0;
uint v8 = 0;
uint v9 = 0;
uint v10 = 0;
uint v11 = 0;
uint v12 = 0;
uint v13 = 0;
uint v14 = 0;
uint v15 = 0;
uint t0_0 = 0;
uint t0_1 = 0;
uint t0_2 = 0;
uint t0_3 = 0;
v2 = in0.x;
v3 = in0.y;
v4 = asuint(in1.x);
v5 = asuint(in1.y);
v6 = asuint(in1.z);
v7 = asuint(in1.w);
v8 = in2.x;
v9 = in2.y;
v10 = in2.z;
t0_0 = cb1[v0].x;
t0_1 = cb1[v0].y;
t0_2 = cb1[v0].z;
t0_3 = cb1[v0].w;
v12 = t0_0;
v13 = t0_1;
v14 = t0_2;
v15 = t0_3;
v11 = asuint(1.0f);
float4 exp0_pos0 = float4(asfloat(v2), asfloat(v3), asfloat(v8), asfloat(v11));
float4 exp1_param0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
float4 exp2_param1 = float4(asfloat(v12), asfloat(v13), asfloat(v14), asfloat(v15));
VSOut o;
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
o.param1 = float4(exp2_param1.x, exp2_param1.y, exp2_param1.z, exp2_param1.w);
return o;
}
@@ -0,0 +1,3 @@
FETCH 1
USE CB 0
USE TEX 1
@@ -0,0 +1 @@
be8a047e befe0a7e befc0302 c8080000 c8090001 c80c0100 c80d0101 f40c0004 fa000020 f408030a fa000000 87fe0a7e bf8cc07f f0800f08 00600402 bf8c3f70 10080904 f800180f 07060504 bf810000
@@ -0,0 +1,21 @@
Texture2D<float4> tex1 : register(t1, space100);
SamplerState smp0 : register(s0, space100);
float4 main(float4 pos : SV_Position, float4 attr0 : PARAM0) : SV_Target0 {
uint v2 = 0;
uint v3 = 0;
uint v4 = 0;
uint v5 = 0;
uint v6 = 0;
uint v7 = 0;
v2 = asuint(attr0.x);
v3 = asuint(attr0.y);
{ float4 r = tex1.Sample(smp0, float2(asfloat(v2), asfloat(v3)));
v4 = asuint(r.x);
v5 = asuint(r.y);
v6 = asuint(r.z);
v7 = asuint(r.w);
}
v4 = asuint(asfloat(v4) * asfloat(v4));
float4 exp0_mrt0 = float4(asfloat(v4), asfloat(v5), asfloat(v6), asfloat(v7));
return float4(exp0_mrt0.x, exp0_mrt0.y, exp0_mrt0.z, exp0_mrt0.w);
}
@@ -0,0 +1 @@
be842104 f4080304 fa000000 bf8cc07f f4280406 fa000000 bf8cc07f 10000810 d54b0001 004e0a11 7e040280 7e0602f2 f80008cf 03020100 f800020f 03020706 bf810000
@@ -0,0 +1,31 @@
cbuffer CB0 : register(b0, space100) { uint4 cb0[4096]; };
uint cb0_word(uint w) { return cb0[w >> 2][w & 3]; }
struct VSOut { float4 pos : SV_Position; float4 param0 : PARAM0; };
VSOut main(float4 a0 : ATTR0) {
uint v0 = 0;
uint v1 = 0;
uint v2 = 0;
uint v3 = 0;
uint v4 = asuint(a0.x);
uint v5 = asuint(a0.y);
uint v6 = asuint(a0.z);
uint v7 = asuint(a0.w);
uint s16 = 0;
uint s17 = 0;
uint s18 = 0;
uint s19 = 0;
s16 = cb0_word(0);
s17 = cb0_word(1);
s18 = cb0_word(2);
s19 = cb0_word(3);
v0 = asuint(asfloat(s16) * asfloat(v4));
v1 = asuint(mad(asfloat(s17), asfloat(v5), asfloat(s19)));
v2 = 0u;
v3 = asuint(1.0f);
float4 exp0_pos0 = float4(asfloat(v0), asfloat(v1), asfloat(v2), asfloat(v3));
float4 exp1_param0 = float4(asfloat(v6), asfloat(v7), asfloat(v2), asfloat(v3));
VSOut o;
o.pos = float4(exp0_pos0.x, exp0_pos0.y, exp0_pos0.z, exp0_pos0.w);
o.param0 = float4(exp1_param0.x, exp1_param0.y, exp1_param0.z, exp1_param0.w);
return o;
}
@@ -0,0 +1,42 @@
//! The decoder against the public LLVM AMDGPU disassembler: every line of llvm_vectors.txt
//! (generated by scripts/console-shader/gen_llvm_vectors.py) gives instruction words and the
//! text llvm-mc prints for them. Decoding the words must give the same text and consume exactly
//! those words.
use gfx10_translate::decode::decode_one;
#[test]
fn decoder_matches_llvm() {
let mut failures = Vec::new();
let mut checked = 0;
for line in include_str!("llvm_vectors.txt").lines() {
if line.starts_with('#') || line.trim().is_empty() {
continue;
}
let (hex, expected) = line.split_once(" | ").expect("vector line");
let words: Vec<u32> = hex
.split_whitespace()
.map(|w| u32::from_str_radix(w, 16).unwrap())
.collect();
checked += 1;
match decode_one(&words, 0) {
Ok(inst) if inst.words.len() != words.len() => failures.push(format!(
"{expected}: consumed {} of {} words",
inst.words.len(),
words.len()
)),
Ok(inst) if inst.to_string() != expected => {
failures.push(format!("{expected}\n got: {inst}"))
}
Ok(_) => {}
Err(e) => failures.push(format!("{expected}: {e}")),
}
}
assert!(checked > 100, "only {checked} vectors");
assert!(
failures.is_empty(),
"{} of {checked} differ from llvm-mc:\n {}",
failures.len(),
failures.join("\n ")
);
}
@@ -0,0 +1,129 @@
# @generated by scripts/console-shader/gen_llvm_vectors.py from Homebrew LLVM version 23.1.6 (gfx1030).
# <instruction words> | <llvm-mc's text for them>
80000201 | s_add_u32 s0, s1, s2
8003ff01 12345678 | s_add_u32 s3, s1, 0x12345678
88008701 | s_or_b32 s0, s1, 7
8704c105 | s_and_b32 s4, s5, -1
89000201 | s_xor_b32 s0, s1, s2
93000201 | s_mul_i32 s0, s1, s2
8080c001 | s_sub_u32 s0, s1, 64
90008401 | s_lshr_b32 s0, s1, 4
8f008201 | s_lshl_b32 s0, s1, 2
83800201 | s_min_u32 s0, s1, s2
84800201 | s_max_u32 s0, s1, s2
9380ff01 00100000 | s_bfe_u32 s0, s1, 0x100000
be800301 | s_mov_b32 s0, s1
be8003f2 | s_mov_b32 s0, 1.0
befc0301 | s_mov_b32 m0, s1
be800402 | s_mov_b64 s[0:1], s[2:3]
be80047e | s_mov_b64 s[0:1], exec
87fe027e | s_and_b64 exec, exec, s[2:3]
befe0a7e | s_wqm_b64 exec, exec
be800b01 | s_brev_b32 s0, s1
be842104 | s_swappc_b64 s[4:5], s[4:5]
b0001234 | s_movk_i32 s0, 0x1234
bf060100 | s_cmp_eq_u32 s0, s1
bf840004 | s_cbranch_scc0 4
bf810000 | s_endpgm
f4080002 fa000010 | s_load_dwordx4 s[0:3], s[4:5], 0x10
f40c0202 fa000020 | s_load_dwordx8 s[8:15], s[4:5], 0x20
f4080002 fa000000 | s_load_dwordx4 s[0:3], s[4:5], null
f4200002 fa000000 | s_buffer_load_dword s0, s[4:7], null
f4240002 fa000008 | s_buffer_load_dwordx2 s[0:1], s[4:7], 0x8
f4280202 fa000010 | s_buffer_load_dwordx4 s[8:11], s[4:7], 0x10
f42c0202 fa000020 | s_buffer_load_dwordx8 s[8:15], s[4:7], 0x20
f4300402 fa000040 | s_buffer_load_dwordx16 s[16:31], s[4:7], 0x40
7e000301 | v_mov_b32_e32 v0, v1
7e000202 | v_mov_b32_e32 v0, s2
7e0002ff 40490fdb | v_mov_b32_e32 v0, 0x40490fdb
7e0002f2 | v_mov_b32_e32 v0, 1.0
7e0002f7 | v_mov_b32_e32 v0, -4.0
7e0002f8 | v_mov_b32_e32 v0, 0.15915494
7e000291 | v_mov_b32_e32 v0, 17
7e0002c3 | v_mov_b32_e32 v0, -3
06000501 | v_add_f32_e32 v0, v1, v2
060002f0 | v_add_f32_e32 v0, 0.5, v1
100002ff 3e800000 | v_mul_f32_e32 v0, 0x3e800000, v1
08000501 | v_sub_f32_e32 v0, v1, v2
0a000501 | v_subrev_f32_e32 v0, v1, v2
20000501 | v_max_f32_e32 v0, v1, v2
1e000501 | v_min_f32_e32 v0, v1, v2
56000501 | v_fmac_f32_e32 v0, v1, v2
0e000501 | v_mul_legacy_f32_e32 v0, v1, v2
5e000501 | v_cvt_pkrtz_f16_f32_e32 v0, v1, v2
34000282 | v_lshlrev_b32_e32 v0, 2, v1
2c000290 | v_lshrrev_b32_e32 v0, 16, v1
30000290 | v_ashrrev_i32_e32 v0, 16, v1
360002ff 000000ff | v_and_b32_e32 v0, 0xff, v1
38000501 | v_or_b32_e32 v0, v1, v2
3a000501 | v_xor_b32_e32 v0, v1, v2
4c000501 | v_sub_nc_u32_e32 v0, v1, v2
4e000501 | v_subrev_nc_u32_e32 v0, v1, v2
4a000202 | v_add_nc_u32_e32 v0, s2, v1
16000501 | v_mul_u32_u24_e32 v0, v1, v2
26000501 | v_min_u32_e32 v0, v1, v2
28000501 | v_max_u32_e32 v0, v1, v2
7e005501 | v_rcp_f32_e32 v0, v1
7e005d01 | v_rsq_f32_e32 v0, v1
7e006701 | v_sqrt_f32_e32 v0, v1
7e004901 | v_floor_f32_e32 v0, v1
7e004101 | v_fract_f32_e32 v0, v1
7e004b01 | v_exp_f32_e32 v0, v1
7e004f01 | v_log_f32_e32 v0, v1
7e004301 | v_trunc_f32_e32 v0, v1
7e004701 | v_rndne_f32_e32 v0, v1
7e004501 | v_ceil_f32_e32 v0, v1
7e000d01 | v_cvt_f32_u32_e32 v0, v1
7e000b01 | v_cvt_f32_i32_e32 v0, v1
7e001101 | v_cvt_i32_f32_e32 v0, v1
7e006b01 | v_sin_f32_e32 v0, v1
7e006d01 | v_cos_f32_e32 v0, v1
d5030000 02020501 | v_add_f32_e64 v0, v1, v2
d5080000 22020501 | v_mul_f32_e64 v0, -v1, v2
d5080000 42020501 | v_mul_f32_e64 v0, v1, -v2
d5080200 22020501 | v_mul_f32_e64 v0, -v1, |v2|
d5038000 02020501 | v_add_f32_e64 v0, v1, v2 clamp
d5080000 0a020501 | v_mul_f32_e64 v0, v1, v2 mul:2
d5100000 02000501 | v_max_f32_e64 v0, v1, s2
d5040000 02020501 | v_sub_f32_e64 v0, v1, v2
d5aa0000 22010101 | v_rcp_f32_e64 v0, -v1
d51a0000 02020202 | v_lshlrev_b32_e64 v0, s2, v1
d5690000 02020501 | v_mul_lo_u32 v0, v1, v2
d56a0000 02020501 | v_mul_hi_u32 v0, v1, v2
d54b0000 040e0501 | v_fma_f32 v0, v1, v2, v3
d54b0000 23ca0501 | v_fma_f32 v0, -v1, v2, 1.0
d5570000 03c90101 | v_med3_f32 v0, v1, 0, 1.0
d5480000 02211101 | v_bfe_u32 v0, v1, 8, 8
7c020501 | v_cmp_lt_f32_e32 vcc_lo, v1, v2
7da40501 | v_cmpx_eq_u32_e32 v1, v2
02000501 | v_cndmask_b32_e32 v0, v1, v2, vcc_lo
c8080000 | v_interp_p1_f32_e32 v2, v0, attr0.x
c8090001 | v_interp_p2_f32_e32 v2, v1, attr0.x
c80d0f01 | v_interp_p2_f32_e32 v3, v1, attr3.w
c8020902 | v_interp_mov_f32_e32 v0, p0, attr2.y
cc210000 1c0e0501 | v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]
cc224000 1c0e0501 | v_fma_mixhi_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]
e0302000 80010001 | buffer_load_dword v0, v1, s[4:7], 0 idxen
e030200c 80010001 | buffer_load_dword v0, v1, s[4:7], 0 idxen offset:12
e0342000 80010002 | buffer_load_dwordx2 v[0:1], v2, s[4:7], 0 idxen
e03c2004 80010003 | buffer_load_dwordx3 v[0:2], v3, s[4:7], 0 idxen offset:4
e0382000 80020004 | buffer_load_dwordx4 v[0:3], v4, s[8:11], 0 idxen
e0301000 80010001 | buffer_load_dword v0, v1, s[4:7], 0 offen
e0300010 02010000 | buffer_load_dword v0, off, s[4:7], s2 offset:16
e9c32000 80000004 | tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_8_8_8_8_UNORM] idxen
e8eb2008 80000004 | tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] idxen offset:8
f0800f08 00820004 | image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
f0800808 00820004 | image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
f09c0308 00820002 | image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
f80008cf 03020100 | exp pos0, v0, v1, v2, v3 done
f800180f 03020100 | exp mrt0, v0, v1, v2, v3 done vm
f8000001 00000000 | exp mrt0, v0, off, off, off
f800023f 07060504 | exp param3, v4, v5, v6, v7
f8001c0f 00000100 | exp mrt0, v0, v0, v1, v1 done compr vm
5a000501 3f800000 | v_fmaak_f32 v0, v1, v2, 0x3f800000
58000501 40000000 | v_fmamk_f32 v0, v1, 0x40000000, v2
3e000501 | v_mac_f32_e32 v0, v1, v2
d51f0000 22020501 | v_mac_f32_e64 v0, -v1, v2
d5410000 040e0501 | v_mad_f32 v0, v1, v2, v3
42000501 3f800000 | v_madak_f32 v0, v1, v2, 0x3f800000
40000501 40000000 | v_madmk_f32 v0, v1, 0x40000000, v2
@@ -0,0 +1,230 @@
//! The translator against its reference. The golden files hold small VS/PS pairs written in
//! GFX10.3 assembly, assembled by the public LLVM assembler, with the HLSL and input layout the
//! Python prototype (scripts/console-shader/translate.py) produces for them; regenerate them
//! with scripts/console-shader/gen_translate_goldens.py. Between them the cases use every rule
//! the translator has. Refusals are checked separately.
use gfx10_translate::decode::decode;
use gfx10_translate::translate::{Stage, Translator, translate_pair};
fn words(hex: &str) -> Vec<u32> {
hex.split_whitespace()
.map(|w| u32::from_str_radix(w, 16).unwrap())
.collect()
}
fn golden(case: &str, vs: &str, ps: &str, vs_hlsl: &str, ps_hlsl: &str, il: &str) {
let vs = decode(&words(vs)).unwrap_or_else(|e| panic!("{case} VS: {e}"));
let ps = decode(&words(ps)).unwrap_or_else(|e| panic!("{case} PS: {e}"));
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{case}: {e}"));
assert_eq!(t.vs_hlsl, vs_hlsl, "{case} VS HLSL");
assert_eq!(t.ps_hlsl, ps_hlsl, "{case} PS HLSL");
assert_eq!(t.layout, il, "{case} layout");
}
macro_rules! golden_case {
($test:ident, $name:literal) => {
#[test]
fn $test() {
golden(
$name,
include_str!(concat!("goldens/", $name, ".vs.hex")),
include_str!(concat!("goldens/", $name, ".ps.hex")),
include_str!(concat!("goldens/", $name, ".vs.hlsl")),
include_str!(concat!("goldens/", $name, ".ps.hlsl")),
include_str!(concat!("goldens/", $name, ".il")),
);
}
};
}
golden_case!(textured_pair_matches_the_prototype, "textured");
golden_case!(alu_families_match_the_prototype, "alu");
golden_case!(vertex_buffers_match_the_prototype, "buffers");
/// Translates one stage given as instruction words, returning the refusal if any.
fn refusal(stage: Stage, hex: &str) -> Option<String> {
let insts = decode(&words(hex)).unwrap();
Translator::new(stage).run(&insts).err().map(|e| e.0)
}
// Encodings from llvm-mc (gfx1030); each program ends in s_endpgm (bf810000).
#[test]
fn refuses_what_it_does_not_model() {
// v_cmp_lt_f32_e32 vcc_lo, v1, v2: no rule for compares yet.
assert!(
refusal(Stage::Pixel, "7c020501 bf810000")
.unwrap()
.starts_with("instruction 'v_cmp_lt_f32_e32")
);
// v_add_f32_e64 v0, v1, v2 clamp: output modifiers are refused, not dropped.
assert!(
refusal(Stage::Pixel, "d5038000 02020501 bf810000")
.unwrap()
.starts_with("modifier in")
);
// v_mul_f32_e64 v0, v1, v2 mul:2
assert!(
refusal(Stage::Pixel, "d5080000 0a020501 bf810000")
.unwrap()
.starts_with("modifier in")
);
// s_load_dwordx8 s[8:15], s[4:5], 0x20: a texture from a descriptor table the model does not
// know. (A 4-dword load from such a table is a sampler and is accepted.)
assert!(
refusal(Stage::Pixel, "f40c0202 fa000020 bf810000")
.unwrap()
.starts_with("descriptor load from")
);
assert_eq!(refusal(Stage::Pixel, "f4080002 fa000010 bf810000"), None);
// s_swappc_b64 s[4:5], s[4:5] in a pixel shader.
assert!(refusal(Stage::Pixel, "be842104 bf810000").is_some());
}
#[test]
fn a_pixel_shader_reading_an_attribute_the_vertex_shader_does_not_export_is_refused() {
// VS: s_swappc_b64 s[4:5], s[4:5]; exp pos0, v4, v5, v6, v7 done; s_endpgm
// PS: v_interp_mov_f32_e32 v2, p0, attr1.x; exp mrt0, v2, off, off, off done; s_endpgm
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
let ps = decode(&words("c80a0402 f8000801 00000002 bf810000")).unwrap();
let err = translate_pair(&vs, &ps).unwrap_err();
assert_eq!(err.0, "PS reads attr1 that the VS does not export");
}
#[test]
fn s_movk_sign_extends() {
// s_movk_i32 s0, 0xffff; v_mov_b32_e32 v0, s0; exp mrt0, v0, off, off, off done; s_endpgm
let insts = decode(&words("b000ffff 7e000200 f8000801 00000000 bf810000")).unwrap();
let mut t = Translator::new(Stage::Pixel);
t.run(&insts).unwrap();
let (vs, params) = gfx10_translate::translate::build_vs(&{
let mut v = Translator::new(Stage::Vertex);
v.run(&decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap())
.unwrap();
v
})
.unwrap();
let ps = gfx10_translate::translate::build_ps(&t, &params).unwrap();
assert!(vs.contains("o.pos"));
assert!(ps.contains("s0 = 4294967295u;"), "{ps}");
}
/// The multiply-add family (not in the prototype). Encodings from llvm-mc (v_mac/v_mad/v_madak/
/// v_madmk for gfx1010, v_fmaak/v_fmamk for gfx1030); the expected HLSL follows the ISA's
/// definitions (D = S0*S1 + D; S0*S1 + S2; S0*S1 + K; S0*K + S1), written out here.
#[test]
fn multiply_add_family() {
let cases = [
(
"3e000501",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(v0)));",
),
(
"d51f0000 22020501",
"v0 = asuint(mad(asfloat((asuint(-asfloat(v1)))), asfloat(v2), asfloat(v0)));",
),
(
"d5410000 040e0501",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(v3)));",
),
(
"42000501 3f800000",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(0x3f800000u)));",
),
(
"40000501 40000000",
"v0 = asuint(mad(asfloat(v1), asfloat(0x40000000u), asfloat(v2)));",
),
(
"5a000501 3f800000",
"v0 = asuint(mad(asfloat(v1), asfloat(v2), asfloat(0x3f800000u)));",
),
(
"58000501 40000000",
"v0 = asuint(mad(asfloat(v1), asfloat(0x40000000u), asfloat(v2)));",
),
];
// VS: s_swappc_b64 s[4:5], s[4:5]; exp pos0, v4, v5, v6, v7 done; s_endpgm
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
for (hex, line) in cases {
// PS: <instruction>; exp mrt0, v0, off, off, off done; s_endpgm
let ps = decode(&words(&format!("{hex} f8000801 00000000 bf810000"))).unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{hex}: {e}"));
assert!(
t.ps_hlsl.contains(&format!(" {line}\n")),
"{hex}:\n{}",
t.ps_hlsl
);
}
}
/// Extensions beyond the prototype: 32-lane execution-mask bookkeeping has no HLSL counterpart
/// (as the 64-lane form), and a compressed export with its second half disabled exports zeros
/// there. Encodings from llvm-mc (gfx1030, wave32).
#[test]
fn wave32_mask_bookkeeping_and_half_compressed_exports() {
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
// s_mov_b32 s94, exec_lo; s_wqm_b32 exec_lo, exec_lo; v_mov_b32_e32 v0, s2;
// s_and_b32 exec_lo, exec_lo, s94; exp mrt0, v0, v0, off, off done compr vm; s_endpgm
let ps = decode(&words(
"bede037e befe097e 7e000202 877e5e7e f8001c03 00000000 bf810000",
))
.unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
assert!(t.ps_hlsl.contains(" v0 = s2;\n"), "{}", t.ps_hlsl);
assert!(
t.ps_hlsl.contains(
"float4 exp0_mrt0 = float4(f16tof32(v0 & 0xffffu), f16tof32(v0 >> 16), 0.0f, 0.0f);"
),
"{}",
t.ps_hlsl
);
assert!(
!t.ps_hlsl.contains("s94 ="),
"the mask copy must not be emitted:\n{}",
t.ps_hlsl
);
}
/// Integer, conversion and lane instructions (#716). Encodings from llvm-mc (gfx1030); each
/// expected line follows the instruction's ISA definition.
#[test]
fn integer_conversion_and_lane_instructions() {
// (instruction words, register moved to v0 before the export, expected line)
let cases: &[(&str, &str, &str)] = &[
("81000201", "7e000200", "s0 = (s1 + s2);"),
(
"8300c201",
"7e000200",
"s0 = (uint)min((int)s1, (int)4294967294u);",
),
(
"7e000f01",
"",
"v0 = (isnan(asfloat(v1)) ? 0u : (asfloat(v1) >= 4294967296.0f ? 0xffffffffu : (uint)max(asfloat(v1), 0.0f)));",
),
("7e002301", "", "v0 = asuint((float)(v1 & 0xffu));"),
("7e002701", "", "v0 = asuint((float)((v1 >> 16) & 0xffu));"),
("7e005701", "", "v0 = asuint((1.0f / asfloat(v1)));"),
("d7460000 04090501", "", "v0 = ((v1 << (2u & 31u)) + v2);"),
(
"d5480000 02111101",
"",
"v0 = (((4u & 31u) == 0u) ? 0u : ((8u & 31u) + (4u & 31u) >= 32u ? (v1 >> (8u & 31u)) : ((v1 >> (8u & 31u)) & ((1u << (4u & 31u)) - 1u))));",
),
("d54a0000 040e0501", "", "v0 = ((v1 & v2) | (~v1 & v3));"),
("d76d0000 000e0501", "", "v0 = (v1 + v2 + s3);"),
("7e080501", "7e000204", "s4 = WaveReadLaneFirst(v1);"),
];
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
for (inst, mov, line) in cases {
// PS: <instruction>; [v_mov_b32_e32 v0, sN]; exp mrt0, v0, off, off, off done; s_endpgm
let ps = decode(&words(&format!("{inst} {mov} f8000801 00000000 bf810000"))).unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{inst}: {e}"));
assert!(
t.ps_hlsl.contains(&format!(" {line}\n")),
"{inst}:\n{}",
t.ps_hlsl
);
}
}
+106 -16
View File
@@ -1,29 +1,52 @@
#include <windows.h>
#include <unknwn.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <new>
#include "bx_log.h"
namespace {
class AcpHal final : public IUnknown {
LONG refs = 1;
// IAcpHal (authorized GDK documentation; slot order derived from it): not a COM interface. Its
// six methods are Connect(numCommands, numMessages), Disconnect(), SubmitCommand(command,
// commandId, audioFrame, data, notification), PopMessage(ACP_MESSAGE*), GetNumMessages() and
// Release(). BetterXen has no audio control processor: commands are accepted and logged once,
// and no message ever arrives.
class AcpHal {
UINT32 commands_ = 0, messages_ = 0;
bool connected_ = false;
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown) return E_NOINTERFACE;
AddRef();
*out = this;
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
commands_ = num_commands;
messages_ = num_messages;
connected_ = true;
char detail[96];
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
ULONG left = InterlockedDecrement(&refs);
if (!left) delete this;
return left;
virtual HRESULT WINAPI Disconnect() {
connected_ = false;
return S_OK;
}
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
if (!connected_) return E_UNEXPECTED;
static LONG logged = 0;
if (InterlockedIncrement(&logged) == 1) {
char detail[96];
std::snprintf(detail, sizeof(detail), "first command type %u accepted; ACP commands are not processed", command);
bx_log_emit(BX_LOG_WARN, "acphal", "submit_command", detail);
}
return S_OK;
}
virtual bool WINAPI PopMessage(void*) { return false; }
virtual UINT32 WINAPI GetNumMessages() { return 0; }
virtual void WINAPI Release() { delete this; }
virtual ~AcpHal() = default;
};
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
@@ -47,19 +70,86 @@ HRESULT WINAPI AcpHalCreate(void** out) {
return *out ? S_OK : E_OUTOFMEMORY;
}
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment);
HRESULT WINAPI ApuFree(void* va);
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) / AcpHalReleaseShapeContexts() (authorized GDK
// documentation; layout and element sizes derived from it, no header text): the caller fills six
// counts, the call allocates each array from the APU heap and returns its CPU pointer and APU
// address. Allocating twice without a release fails with ACP_E_ALREADY_ALLOCATED.
struct ShapeContexts {
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
void* arrays[6]; // CPU pointers, same order
uint32_t apu[6]; // APU addresses, same order
};
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS is 96 bytes");
static_assert(offsetof(ShapeContexts, arrays) == 24 && offsetof(ShapeContexts, apu) == 72, "SHAPE_CONTEXTS layout");
constexpr uint32_t kShapeElementBytes[6] = {32, 160, 32, 16, 64, 32};
constexpr HRESULT kAcpAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
constexpr uint32_t kDefaultApuHeapBytes = 64u << 20;
void* shape_arrays[6];
bool shape_allocated = false;
HRESULT WINAPI AcpHalAllocateShapeContexts(void* argument) {
auto* contexts = static_cast<ShapeContexts*>(argument);
if (!contexts) return E_INVALIDARG;
if (shape_allocated) return kAcpAlreadyAllocated;
for (int i = 0; i < 6; ++i) {
if (contexts->counts[i] > (0xFFFFFFFFu / kShapeElementBytes[i])) return E_INVALIDARG;
}
{
// The console has a default non-cached APU heap; create one when the title made none.
std::lock_guard guard(heap_lock);
if (!heap_created) {
capacity = kDefaultApuHeapBytes;
used = 0;
heap_created = true;
bx_log_emit(BX_LOG_INFO, "acphal", "apu_default_heap", "no ApuCreateHeap before shape contexts: 64 MB default heap");
}
}
void* arrays[6] = {};
uint32_t apu[6] = {};
for (int i = 0; i < 6; ++i) {
if (!contexts->counts[i]) continue;
const uint32_t bytes = contexts->counts[i] * kShapeElementBytes[i];
const HRESULT hr = ApuAlloc(&arrays[i], &apu[i], bytes, 64);
if (FAILED(hr)) {
for (int j = 0; j < i; ++j) ApuFree(arrays[j]);
return E_OUTOFMEMORY;
}
std::memset(arrays[i], 0, bytes);
}
for (int i = 0; i < 6; ++i) {
contexts->arrays[i] = arrays[i];
contexts->apu[i] = apu[i];
shape_arrays[i] = arrays[i];
}
shape_allocated = true;
char detail[160];
std::snprintf(detail, sizeof(detail), "src=%u eqcomp=%u filtvol=%u dma=%u xma=%u pcm=%u", contexts->counts[0],
contexts->counts[1], contexts->counts[2], contexts->counts[3], contexts->counts[4], contexts->counts[5]);
bx_log_emit(BX_LOG_INFO, "acphal", "shape_contexts_allocated", detail);
return S_OK;
}
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
if (!shape_allocated) return S_OK;
for (void*& array : shape_arrays) {
ApuFree(array);
array = nullptr;
}
shape_allocated = false;
return S_OK;
}
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
std::lock_guard guard(heap_lock);
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
// A zero-capacity heap must not report S_OK: it can never satisfy an
// allocation, so creating it is a caller error (#580). ApuAlloc already
// refused such requests with E_OUTOFMEMORY.
if (uint64_t(cached) + non_cached == 0) return E_INVALIDARG;
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
used = 0;
capacity = uint64_t(cached) + non_cached;
+18 -1
View File
@@ -1,6 +1,23 @@
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
d3d12_xs.cpp
vmem.cpp
presentx.cpp
proxy.cpp
proxy_generated.cpp
shader_gate.cpp
xbox_facade.cpp
frame_pacing.cpp
placed_x.cpp
gdk_xg.cpp
descriptor_heaps.cpp
committed.cpp
console_formats.cpp
pipelines.cpp
rect_list.cpp
gpu_writes.cpp
fences.cpp
presentx_xbox.cpp
page_mappings.cpp
xbox_tables_generated.cpp
)
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32 user32 dxguid)
+205
View File
@@ -0,0 +1,205 @@
/*
* Committed resources with title-visible memory (ADR 0009).
*
* On the console the D3D12 runtime allocates a committed resource's memory through XMemAlloc
* with AllocatorId eXALLOCAllocatorId_D3D (128) and ObjectType Resource (4) (authorized GDK
* documentation, "Direct3D 12 XMemAlloc object types"). Titles hook XMemAlloc to place that
* memory themselves, and some check afterwards how much of their own pool those requests used.
*
* Here the host committed resource holds the contents. The resource also gets the same
* XMemAlloc request, and its GPU virtual address is the address that request returned, so title
* hooks and title address checks see what they would see on the console. The page size the
* console runtime requests is not documented: this layer asks for 2 MB pages for allocations of
* at least 2 MB and 64 KB pages otherwise (measured against one title; logged per resource).
*
* The size of that request is the console's, not the host's, where the console layout is known:
* a 2D render-target or unordered-access texture with one mip and one sample is laid out by the
* console in 64 KB tiles (swizzle mode 64KB_R_X for every size; authorized GDK XG library). A
* title that sizes its pool for those requests and checks what is left over sees the amount it
* expects. The compression metadata XG adds after the tiles of a render target (8 KB to 96 KB in
* the cases measured) is not included; every other resource keeps the host's size.
*/
#include "xbox_facade.h"
#include "console_formats.h"
#include <atomic>
#include <cstdio>
#include <cstring>
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
namespace {
constexpr ULONGLONG kObjectTypeResource = 4;
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
constexpr ULONGLONG kPageSize64K = 1ull << 14; // XALLOC_ATTRIBUTES.PageSize, bits 14-15
constexpr ULONGLONG kPageSize2M = 2ull << 14;
constexpr UINT64 k2M = 2ull << 20;
constexpr UINT64 k64K = 64ull << 10;
// Bytes per element of an uncompressed colour format, 0 for anything else (depth, block
// compressed, video, 96-bit). Formats 116, 117, 189 and 190 are console-only (GDK DXGI_FORMAT).
UINT colour_element_bytes(DXGI_FORMAT f) {
const UINT v = static_cast<UINT>(f);
if (v >= DXGI_FORMAT_R32G32B32A32_TYPELESS && v <= DXGI_FORMAT_R32G32B32A32_SINT) return 16;
if (v >= DXGI_FORMAT_R16G16B16A16_TYPELESS && v <= DXGI_FORMAT_R32G32_SINT) return 8;
if (v >= DXGI_FORMAT_R10G10B10A2_TYPELESS && v <= DXGI_FORMAT_R32_SINT) return v == DXGI_FORMAT_D32_FLOAT ? 0 : 4;
if (v >= DXGI_FORMAT_R8G8_TYPELESS && v <= DXGI_FORMAT_R16_SINT) return v == DXGI_FORMAT_D16_UNORM ? 0 : 2;
if (v >= DXGI_FORMAT_R8_TYPELESS && v <= DXGI_FORMAT_A8_UNORM) return 1;
if (v >= DXGI_FORMAT_B8G8R8A8_UNORM && v <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return 4;
if (v == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM || v == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) return 4;
if (v >= DXGI_FORMAT_B5G6R5_UNORM && v <= DXGI_FORMAT_B5G5R5A1_UNORM) return 2;
if (v == DXGI_FORMAT_B4G4R4A4_UNORM) return 2;
if (v == 116 || v == 117 || v == 189) return 4; // R10G10B10_7E3_A2_FLOAT, _6E4_A2_FLOAT, _SNORM_A2_UNORM
if (v == 190) return 1; // R4G4_UNORM
return 0;
}
// The console's size for `desc` (the host's geometry, the title's format) where its layout is
// known, else 0. The tile of a 64 KB swizzle holds 64 KB of elements: 256x256 at 1 byte,
// 256x128 at 2, 128x128 at 4, 128x64 at 8 and 64x64 at 16 (authorized GDK XG library: these
// tile counts match its sizes exactly, before the metadata of a render target).
UINT64 console_tiled_size(const D3D12_RESOURCE_DESC& desc, DXGI_FORMAT title_format) {
constexpr UINT kTargets = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN ||
desc.MipLevels != 1 || desc.SampleDesc.Count != 1 || !(desc.Flags & kTargets) ||
(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
return 0;
}
UINT tile_w = 0, tile_h = 0;
switch (colour_element_bytes(title_format)) {
case 1: tile_w = 256; tile_h = 256; break;
case 2: tile_w = 256; tile_h = 128; break;
case 4: tile_w = 128; tile_h = 128; break;
case 8: tile_w = 128; tile_h = 64; break;
case 16: tile_w = 64; tile_h = 64; break;
default: return 0;
}
const UINT64 across = (desc.Width + tile_w - 1) / tile_w;
const UINT64 down = (static_cast<UINT64>(desc.Height) + tile_h - 1) / tile_h;
return across * down * desc.DepthOrArraySize * k64K;
}
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method,
DXGI_FORMAT title_format) {
if (FAILED(hr) || !ppv || !*ppv) return hr;
// *ppv is the host resource as `riid`; every ID3D12Resource* interface pointer is the object.
auto* resource = static_cast<ID3D12Resource*>(*ppv);
const D3D12_RESOURCE_DESC desc = resource->GetDesc();
const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
const UINT64 host_size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
const UINT64 console_size = console_tiled_size(desc, title_format);
const UINT64 size = console_size ? console_size : host_size;
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D | (size >= k2M ? kPageSize2M : kPageSize64K);
void* title = XMemAlloc(static_cast<SIZE_T>(size), attributes);
char detail[240];
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu (%s, host %llu) page=%s title_va=%p", method,
static_cast<int>(desc.Dimension), static_cast<unsigned long long>(size),
console_size ? "console 64 KB tiles" : "host", static_cast<unsigned long long>(host_size),
size >= k2M ? "2MB" : "64KB", title);
bx_log_emit(title ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "committed_title_memory", detail);
if (!title || !bx_xbox_title_memory_attach(resource, reinterpret_cast<uint64_t>(title), size, attributes)) {
resource->Release();
*ppv = nullptr;
return E_OUTOFMEMORY;
}
return bx_xbox_wrap_result(hr, riid, ppv);
}
} // namespace
extern "C" {
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
desc = host_desc.of_resource(desc, "CreateCommittedResource");
clear = host_clear.of(clear, "CreateCommittedResource");
auto* device = bx_xbox_host<ID3D12Device>(self);
return finish(device, device->CreateCommittedResource(heap, flags, desc, state, clear, riid, ppv), riid, ppv,
"CreateCommittedResource", title_format);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource1");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
desc = host_desc.of_resource(desc, "CreateCommittedResource1");
clear = host_clear.of(clear, "CreateCommittedResource1");
auto* device = bx_xbox_host<ID3D12Device4>(self);
return finish(device, device->CreateCommittedResource1(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
riid, ppv, "CreateCommittedResource1", title_format);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource2");
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
desc = host_desc.of_resource(desc, "CreateCommittedResource2");
clear = host_clear.of(clear, "CreateCommittedResource2");
auto* device = bx_xbox_host<ID3D12Device8>(self);
return finish(device, device->CreateCommittedResource2(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
riid, ppv, "CreateCommittedResource2", title_format);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
ID3D12ProtectedResourceSession* session, UINT32 formats,
DXGI_FORMAT* castable, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource3");
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
desc = host_desc.of_resource(desc, "CreateCommittedResource3");
clear = host_clear.of(clear, "CreateCommittedResource3");
auto* device = bx_xbox_host<ID3D12Device10>(self);
return finish(device,
device->CreateCommittedResource3(heap, flags, desc, layout, clear, bx_xbox_unwrap_as(session), formats,
castable, riid, ppv),
riid, ppv, "CreateCommittedResource3", title_format);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource_x(void* self, const D3D12_HEAP_PROPERTIES* heap,
D3D12_HEAP_FLAGS flags, const void* xbox_desc,
D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid,
void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommittedResourceX");
if (!xbox_desc) return E_INVALIDARG;
// D3D12XBOX_RESOURCE_DESC begins with the PC description; DccOptions follows it. DccOptions is
// a struct of two 32-bit enums, CompressionLevel and ColorTransform; every value of either
// selects some form of colour compression (CompressionLevel 0 is 64B, not "none").
D3D12_RESOURCE_DESC desc{};
std::memcpy(&desc, xbox_desc, sizeof(desc));
UINT32 dcc[2] = {};
std::memcpy(dcc, static_cast<const char*>(xbox_desc) + sizeof(desc), sizeof(dcc));
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[128];
std::snprintf(detail, sizeof(detail),
"DccOptions CompressionLevel=%u ColorTransform=%u ignored (no colour compression on the host)",
dcc[0], dcc[1]);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommittedResourceX", detail);
}
return bx_xbox_device_create_committed_resource(self, heap, flags, &desc, state, clear, riid, ppv);
}
} // extern "C"
+244
View File
@@ -0,0 +1,244 @@
/*
* Console-only DXGI formats and console-only view combinations: the Xbox-layout device entry
* points that carry a format to the host and are otherwise plain forwarders. See
* console_formats.h for the formats and the reason.
*
* Covered here: the three GetResourceAllocationInfo forms, CreatePlacedResource,
* CreateReservedResource and the four view-creation methods. Committed resources and the placed
* (X) resources and views translate in committed.cpp and placed_x.cpp. Pipeline-state formats are
* not translated yet: no console pipeline is created on the host so far.
*/
#include "console_formats.h"
#include "xbox_facade.h"
#include "gdk_xg.h"
#include <atomic>
#include <cstdio>
#include <vector>
void bx_note_console_format(DXGI_FORMAT format, const char* where) {
static std::atomic<uint32_t> noted{0}; // one bit per console-only format
const int f = static_cast<int>(format);
const uint32_t bit = 1u << (f >= 189 ? f - 189 + 8 : f - 116);
if (noted.fetch_or(bit) & bit) return;
char detail[200];
std::snprintf(detail, sizeof(detail),
"console-only format %d is translated for the host (view and clear format %d, resource format %d; first seen in %s)",
f, static_cast<int>(bx_host_format(format)), static_cast<int>(bx_host_resource_format(format)), where);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_format", detail);
}
/* The console allows D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL together with ALLOW_UNORDERED_ACCESS,
* and a title writes the depth plane from a compute shader through an R32_FLOAT unordered-access
* view. PC Direct3D 12 forbids the combination. D3DMetal accepts the resource, answers the view
* with a Metal texture view that Metal refuses ("texture view pixelFormat
* (MTLPixelFormatDepth32Float) not castable"), and Metal aborts the process.
*
* Until that write path is emulated, such a descriptor gets a null view of the same description
* (Direct3D 12 defines it: reads return zero, writes are discarded) and the call is logged as
* unimplemented, so the gap is visible in every run report instead of ending the process. */
void bx_xbox_create_host_uav(ID3D12Device* device, ID3D12Resource* host, ID3D12Resource* counter,
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE host_dest,
const char* method) {
BxHostFormat<D3D12_UNORDERED_ACCESS_VIEW_DESC> translated;
desc = translated.of(desc, method);
if (host && (host->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
BX_STUB_LOG("d3d12_xs.dll", "CreateUnorderedAccessView(depth-stencil resource)");
// A null view needs a description; without one the descriptor is left as it was.
if (desc) device->CreateUnorderedAccessView(nullptr, nullptr, desc, host_dest);
return;
}
device->CreateUnorderedAccessView(host, counter, desc, host_dest);
}
namespace {
/* An array of resource descriptions as the host must see it. */
template <typename Desc>
class HostDescs {
public:
HostDescs(const Desc* in, UINT count, const char* where) : descs_(in) {
if (!in) return;
for (UINT i = 0; i < count; ++i) {
if (!bx_is_console_only_format(in[i].Format)) continue;
if (copy_.empty()) copy_.assign(in, in + count);
bx_note_console_format(in[i].Format, where);
copy_[i].Format = bx_host_resource_format(in[i].Format);
}
if (!copy_.empty()) descs_ = copy_.data();
}
const Desc* get() const { return descs_; }
private:
const Desc* descs_;
std::vector<Desc> copy_;
};
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC& d) { return d; }
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC1& d) {
D3D12_RESOURCE_DESC out{};
out.Dimension = d.Dimension;
out.Alignment = d.Alignment;
out.Width = d.Width;
out.Height = d.Height;
out.DepthOrArraySize = d.DepthOrArraySize;
out.MipLevels = d.MipLevels;
out.Format = d.Format;
out.SampleDesc = d.SampleDesc;
out.Layout = d.Layout;
out.Flags = d.Flags;
return out;
}
/* Allocation info for descriptions that include a console texture layout. The console sizes come
from the GDK's XG (gdk_xg.h); other descriptions keep the host's answer, one at a time. The
total follows Direct3D 12: each resource at its alignment, in order; the total alignment is the
largest. Returns false (the host answers everything) when no description has a console layout
or XG is not loaded. */
template <typename Desc>
bool console_allocation(ID3D12Device* device, UINT mask, UINT count, const Desc* descs, D3D12_RESOURCE_ALLOCATION_INFO* total,
D3D12_RESOURCE_ALLOCATION_INFO1* each, const char* method) {
if (!descs || !count || !bx_gdk_xg_available()) return false;
bool any = false;
for (UINT i = 0; i < count && !any; ++i) any = bx_is_console_texture_layout(as_desc(descs[i]));
if (!any) return false;
uint64_t offset = 0, max_alignment = 0;
for (UINT i = 0; i < count; ++i) {
const D3D12_RESOURCE_DESC desc = as_desc(descs[i]);
uint64_t size = 0, alignment = 0;
if (!bx_is_console_texture_layout(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
D3D12_RESOURCE_DESC host = desc;
if (bx_is_console_only_format(host.Format)) host.Format = bx_host_resource_format(host.Format);
if (bx_is_console_texture_layout(host)) host.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
D3D12_RESOURCE_ALLOCATION_INFO one{};
device->GetResourceAllocationInfo(&one, mask, 1, &host);
size = one.SizeInBytes;
alignment = one.Alignment;
} else {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 24) {
char detail[192];
std::snprintf(detail, sizeof(detail), "%s %llux%ux%u mips=%u format=%d layout=0x%x: console size %llu, alignment %llu",
method, static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
static_cast<int>(desc.Format), static_cast<UINT>(desc.Layout), static_cast<unsigned long long>(size),
static_cast<unsigned long long>(alignment));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_allocation", detail);
}
}
if (size == UINT64_MAX || !alignment) return false;
offset = (offset + alignment - 1) / alignment * alignment;
if (each) each[i] = D3D12_RESOURCE_ALLOCATION_INFO1{offset, alignment, size};
offset += size;
if (alignment > max_alignment) max_alignment = alignment;
}
total->SizeInBytes = offset;
total->Alignment = max_alignment;
return true;
}
} // namespace
extern "C" {
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
const D3D12_RESOURCE_DESC* descs) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, nullptr, "GetResourceAllocationInfo")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, mask, count, host.get());
return result;
}
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info1(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo1")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, mask, count, host.get(), each);
return result;
}
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info2(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo2")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, mask, count, host.get(), each);
return result;
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource(void* self, ID3D12Heap* heap, UINT64 offset,
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreatePlacedResource(
bx_xbox_unwrap_as<ID3D12Heap>(heap), offset, host_desc.of_resource(desc, "CreatePlacedResource"), state,
host_clear.of(clear, "CreatePlacedResource"), riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreatePlacedResource", hr);
return bx_xbox_wrap_result(hr, riid, ppv);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_reserved_resource(void* self, const D3D12_RESOURCE_DESC* desc,
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateReservedResource");
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateReservedResource(
host_desc.of_resource(desc, "CreateReservedResource"), state, host_clear.of(clear, "CreateReservedResource"), riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource", hr);
return bx_xbox_wrap_result(hr, riid, ppv);
}
void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID3D12Resource* resource,
const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateShaderResourceView"),
bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateUnorderedAccessView");
bx_xbox_create_host_uav(bx_xbox_host<ID3D12Device>(self), bx_xbox_unwrap_as<ID3D12Resource>(resource),
bx_xbox_unwrap_as<ID3D12Resource>(counter), desc, bx_xbox_host_cpu_handle(dest),
"CreateUnorderedAccessView");
}
void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D12Resource* resource,
const D3D12_RENDER_TARGET_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
BxHostFormat<D3D12_RENDER_TARGET_VIEW_DESC> host;
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateRenderTargetView"),
bx_xbox_host_cpu_handle(dest));
}
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
BxHostFormat<D3D12_DEPTH_STENCIL_VIEW_DESC> host;
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
host.of(desc, "CreateDepthStencilView"),
bx_xbox_host_cpu_handle(dest));
}
} // extern "C"
+91
View File
@@ -0,0 +1,91 @@
/* Console-only DXGI formats.
*
* The Xbox Series DXGI_FORMAT enumeration (GDK d3d12_xs.h) has values the PC enumeration does
* not have: 116-120, 189 and 190. A PC Direct3D 12 implementation does not know them. D3DMetal
* turns one into an invalid Metal pixel format, and Metal then aborts the process ("Texture
* Descriptor Validation: MTLTextureDescriptor has invalid pixelFormat"), so no error code ever
* comes back. Every format that reaches the host therefore goes through bx_host_format first.
*
* The host format is the nearest one the host can create that holds at least the same precision:
*
* 116 R10G10B10_7E3_A2_FLOAT -> R16G16B16A16_FLOAT
* 117 R10G10B10_6E4_A2_FLOAT -> R16G16B16A16_FLOAT
* 118 D16_UNORM_S8_UINT -> D32_FLOAT_S8X24_UINT (depth + stencil; views, clear values)
* -> R32G8X24_TYPELESS (the texture itself, see below)
* 119 R16_UNORM_X8_TYPELESS -> R32_FLOAT_X8X24_TYPELESS (its depth plane, read)
* 120 X16_TYPELESS_G8_UINT -> X32_TYPELESS_G8X24_UINT (its stencil plane, read)
* 189 R10G10B10_SNORM_A2_UNORM -> R16G16B16A16_SNORM
* 190 R4G4_UNORM -> R8G8_UNORM
*
* A depth texture that is also read is created typeless on the host, with the concrete format
* named by each view: D3DMetal creates a fully typed depth-stencil texture without the ability
* to be viewed in another format, and Metal aborts on the depth-plane view. The title's own
* D32 buffers already follow that pattern (R32G8X24_TYPELESS texture, D32_FLOAT_S8X24_UINT view).
* bx_host_resource_format is therefore used for resource descriptions and bx_host_format for
* everything else.
*
* Known limits. The texel size differs, so a host resource of a substituted format cannot take
* the title's raw texel bytes (part of uploading placed texture contents, which is separate
* work), the sizes GetResourceAllocationInfo and GetCopyableFootprints report are the host
* format's, and GetDesc on such a resource reports the host format.
*/
#ifndef BX_D3D12_XS_CONSOLE_FORMATS_H
#define BX_D3D12_XS_CONSOLE_FORMATS_H
#include <dxgiformat.h>
constexpr int kBxFormatR10G10B10_7E3_A2_FLOAT = 116;
constexpr int kBxFormatR10G10B10_6E4_A2_FLOAT = 117;
constexpr int kBxFormatD16_UNORM_S8_UINT = 118;
constexpr int kBxFormatR16_UNORM_X8_TYPELESS = 119;
constexpr int kBxFormatX16_TYPELESS_G8_UINT = 120;
constexpr int kBxFormatR10G10B10_SNORM_A2_UNORM = 189;
constexpr int kBxFormatR4G4_UNORM = 190;
constexpr bool bx_is_console_only_format(DXGI_FORMAT format) {
const int f = static_cast<int>(format);
return (f >= 116 && f <= 120) || f == 189 || f == 190;
}
constexpr DXGI_FORMAT bx_host_format(DXGI_FORMAT format) {
switch (static_cast<int>(format)) {
case kBxFormatR10G10B10_7E3_A2_FLOAT:
case kBxFormatR10G10B10_6E4_A2_FLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT;
case kBxFormatD16_UNORM_S8_UINT: return DXGI_FORMAT_D32_FLOAT_S8X24_UINT;
case kBxFormatR16_UNORM_X8_TYPELESS: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS;
case kBxFormatX16_TYPELESS_G8_UINT: return DXGI_FORMAT_X32_TYPELESS_G8X24_UINT;
case kBxFormatR10G10B10_SNORM_A2_UNORM: return DXGI_FORMAT_R16G16B16A16_SNORM;
case kBxFormatR4G4_UNORM: return DXGI_FORMAT_R8G8_UNORM;
default: return format;
}
}
constexpr DXGI_FORMAT bx_host_resource_format(DXGI_FORMAT format) {
return static_cast<int>(format) == kBxFormatD16_UNORM_S8_UINT ? DXGI_FORMAT_R32G8X24_TYPELESS : bx_host_format(format);
}
/* Logs the first translation of each console-only format (console_formats.cpp). */
void bx_note_console_format(DXGI_FORMAT format, const char* where);
/* A structure with a `Format` member (resource description, clear value, view description) as
* the host must see it. of() returns the caller's pointer unchanged when nothing needs
* translating, so the common case costs one comparison and no copy. */
template <typename T>
class BxHostFormat {
public:
const T* of(const T* in, const char* where) { return translate(in, where, false); }
/* For D3D12_RESOURCE_DESC and D3D12_RESOURCE_DESC1. */
const T* of_resource(const T* in, const char* where) { return translate(in, where, true); }
private:
const T* translate(const T* in, const char* where, bool resource) {
if (!in || !bx_is_console_only_format(in->Format)) return in;
bx_note_console_format(in->Format, where);
value_ = *in;
value_.Format = resource ? bx_host_resource_format(in->Format) : bx_host_format(in->Format);
return &value_;
}
T value_;
};
#endif
+127 -25
View File
@@ -1,8 +1,11 @@
#include "proxy.h"
#include "vmem.h"
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include "bx_xmem_internal.h"
#include <cstring>
#include <mutex>
/*
* Track C (M1-C1, #414): Xbox Series D3D12 entry points over the host's d3d12.dll
@@ -20,9 +23,44 @@ HMODULE get_host_d3d12() {
return mod;
}
void refresh_trace_flag() {
const bx_runtime_config_t* cfg = bx_get_runtime_config();
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
// A failed host serialization is the title's error to handle, but it is logged with the host's
// message and the shape of the description so the rejected feature can be found.
void log_serialize_failure(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, HRESULT hr, ID3DBlob* errors) {
static std::atomic<uint32_t> logged{0};
if (logged.fetch_add(1) >= 32) return;
char shape[160] = "desc=null";
if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_1) {
const auto& d = desc->Desc_1_1;
std::snprintf(shape, sizeof(shape), "version=1.1 params=%u samplers=%u flags=0x%x", d.NumParameters,
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
} else if (desc && desc->Version == D3D_ROOT_SIGNATURE_VERSION_1_0) {
const auto& d = desc->Desc_1_0;
std::snprintf(shape, sizeof(shape), "version=1.0 params=%u samplers=%u flags=0x%x", d.NumParameters,
d.NumStaticSamplers, static_cast<unsigned>(d.Flags));
} else if (desc) {
std::snprintf(shape, sizeof(shape), "version=%u", static_cast<unsigned>(desc->Version));
}
char message[160] = "";
if (errors && errors->GetBufferPointer() && errors->GetBufferSize()) {
const size_t n = errors->GetBufferSize() < sizeof(message) - 1 ? errors->GetBufferSize() : sizeof(message) - 1;
std::memcpy(message, errors->GetBufferPointer(), n);
message[n] = '\0';
for (char& ch : message) {
if (ch == '"' || ch == '\\' || static_cast<unsigned char>(ch) < 0x20) ch = ' ';
}
}
char detail[384];
std::snprintf(detail, sizeof(detail), "hr=0x%08lx %s host_error=%s", static_cast<unsigned long>(hr), shape,
message[0] ? message : "(none)");
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "root_signature_serialize_failed", detail);
}
void initialize_trace_flag() {
static std::once_flag initialized;
std::call_once(initialized, [] {
const bx_runtime_config_t* cfg = bx_get_runtime_config();
g_bx_trace_d3d = (cfg && cfg->trace_d3d) ? 1u : 0u;
});
}
} // namespace
@@ -30,17 +68,34 @@ void refresh_trace_flag() {
extern "C" {
/*
* `params` is the console creation-parameter block. Its layout is not defined in abi/ and is not
* interpreted here: the host device is created on the default adapter at the lowest feature level
* D3D12 accepts, and that fact is logged. `riid` must name an interface the proxy models (or one
* the host device answers); anything else fails with E_NOINTERFACE and a logged IID.
* The documented four-parameter form (authorized GDK documentation, d3d12_x.h / d3d12_xs.h):
* an optional adapter, a required D3D12XBOX_CREATE_DEVICE_PARAMETERS block, the interface ID and
* the device out pointer. A NULL parameter block fails with E_INVALIDARG, as documented.
*
* BetterXen has no adapter objects, so a non-NULL adapter is logged and the default host adapter
* is used (an inference, not a documented fallback). Of the parameter block only `Version`, its
* first UINT, is read and logged; the other fields are not interpreted. The host device is
* created at the lowest feature level D3D12 accepts. `riid` must name an interface the proxy
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
* IID.
*/
HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
extern "C" void bx_gdk_xg_enable_locking();
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
// The title creates XG texture computers on its own threads; the shim does too (gdk_xg.h).
static const bool xg_locking = (bx_gdk_xg_enable_locking(), true);
(void)xg_locking;
if (!ppv) {
return E_POINTER;
}
*ppv = nullptr;
refresh_trace_flag();
initialize_trace_flag();
if (!params) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "D3D12XboxCreateDevice", "refused: NULL parameter block (E_INVALIDARG)");
return E_INVALIDARG;
}
UINT version = 0;
std::memcpy(&version, params, sizeof(version));
using CreateFn = HRESULT(WINAPI*)(IUnknown*, D3D_FEATURE_LEVEL, REFIID, void**);
HMODULE d3d12 = get_host_d3d12();
@@ -53,12 +108,24 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
}
ID3D12Device* host = nullptr;
HRESULT hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
if (FAILED(hr) || !host) {
char detail[96];
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
return FAILED(hr) ? hr : E_FAIL;
char reuse[8] = {};
/* Test hook. While the backing cache holds a host heap, that heap keeps the host
device alive, and a real runtime then returns the same ID3D12Device. Set the
variable so the next proxy wraps that device even if this host does not. */
const bool reuse_backing = GetEnvironmentVariableA("BX_D3D12_REUSE_BACKING_HOST", reuse, sizeof(reuse)) > 0 &&
reuse[0] == '1' && reuse[1] == '\0';
if (reuse_backing) {
host = static_cast<ID3D12Device*>(bx_vmem_addref_backing_host());
}
HRESULT hr = S_OK;
if (!host) {
hr = create(nullptr, D3D_FEATURE_LEVEL_11_0, __uuidof(ID3D12Device), reinterpret_cast<void**>(&host));
if (FAILED(hr) || !host) {
char detail[96];
std::snprintf(detail, sizeof(detail), "D3D12CreateDevice hr=0x%08lx", static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "host_device_failed", detail);
return FAILED(hr) ? hr : E_FAIL;
}
}
BxDeviceProxy* proxy = BxDeviceProxy::create(host);
@@ -66,6 +133,10 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
if (!proxy) {
return E_OUTOFMEMORY;
}
if (!bx_vmem_install_device_hooks(proxy)) {
proxy->Release();
return E_FAIL;
}
/* Record how far up the ID3D12DeviceN chain the host goes: QueryInterface on the proxy stops there. */
int highest = 0;
@@ -77,21 +148,47 @@ HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv) {
for (int i = 0; i < 10; ++i) {
if (levels[i]) highest = i + 1;
}
char detail[192];
char detail[256];
std::snprintf(detail, sizeof(detail),
"host device wrapped; highest_host_interface=ID3D12Device%d feature_level=11_0 params=%s (not interpreted) trace_d3d=%u",
highest, params ? "non-null" : "null", g_bx_trace_d3d);
"host_device=%p highest_host_interface=ID3D12Device%d feature_level=11_0 params_version=%u "
"(other fields not interpreted) adapter=%s trace_d3d=%u",
static_cast<void*>(proxy->h_ID3D12Device), highest, version,
adapter ? "non-null (ignored, default host adapter)" : "default", g_bx_trace_d3d);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "D3D12XboxCreateDevice", detail);
/*
* ADR 0009: a title built against the Xbox header calls through Xbox-order function tables,
* so it gets an Xbox-layout device over the PC proxy. The documentation requires titles to
* set Version (D3D12_SDK_VERSION); BetterXen's synthetic fixtures, which are PC-layout
* clients built against <d3d12.h>, pass a zeroed block and keep the PC proxy.
*/
if (version != 0 && bx_xbox_iface_for(riid) == &bx_xbox_Device) {
void* pc = nullptr;
hr = proxy->QueryInterface(riid, &pc);
proxy->Release();
if (FAILED(hr) || !pc) return FAILED(hr) ? hr : E_NOINTERFACE;
// The wrap fails (E_NOINTERFACE, logged) when the host device lacks the interface the Xbox
// table forwards to: a title must not get a PC-layout device reported as an Xbox one.
HRESULT failure = E_OUTOFMEMORY;
*ppv = bx_xbox_wrap(riid, pc, &failure);
bx_log_emit(*ppv ? BX_LOG_INFO : BX_LOG_ERROR, "d3d12_xs", "xbox_layout",
*ppv ? "device=xbox_function_tables"
: "device=refused: the host device lacks the interface the Xbox device table forwards to "
"(the D3DMetal backend provides it)");
return *ppv ? S_OK : failure;
}
hr = proxy->QueryInterface(riid, ppv);
proxy->Release();
if (SUCCEEDED(hr)) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "xbox_layout",
version == 0 ? "device=pc_layout (params Version 0: synthetic PC-layout client)"
: "device=pc_layout (interface has no Xbox table)");
}
return hr;
}
/* Logged no-op: console startup sequences check SUCCEEDED(hr) before reserving virtual memory. */
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID /*config*/) {
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
return S_OK;
HRESULT WINAPI D3D12ConfigureVirtualMemoryX(PVOID config) {
return bx_d3d12_configure_virtual_memory(config);
}
HRESULT WINAPI D3D12SerializeVersionedRootSignature(
@@ -105,7 +202,12 @@ HRESULT WINAPI D3D12SerializeVersionedRootSignature(
auto fn = reinterpret_cast<Fn>(reinterpret_cast<void*>(
GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature")));
if (fn) {
return fn(desc, blob, error_blob);
ID3DBlob* local_error = nullptr;
ID3DBlob** errors = error_blob ? error_blob : &local_error;
const HRESULT hr = fn(desc, blob, errors);
if (FAILED(hr)) log_serialize_failure(desc, hr, *errors);
if (local_error) local_error->Release();
return hr;
}
}
BX_STUB_LOG("d3d12_xs.dll", "D3D12SerializeVersionedRootSignature");
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff. Show more