Compare commits

...
Author SHA1 Message Date
Ateş 713e2d72db Merge pull request #764 from 1Bartosz/track-f/abi-heap-pointers
[Picture] docs: directly indexed descriptor heaps on the ACO path
2026-12-01 01:18:22 +03:00
Ateş c6bb82a6a8 Merge pull request #761 from devil8blade/track-a/757-open-source-dxc
[Picture] Shader compiler: build open-source DXC instead of staging GDK dxcompiler.dll (#757)
2026-12-01 01:17:37 +03:00
Ateş 95b1b154fa Merge pull request #760 from devil8blade/track-d/721-xbch-container
[Picture] XBCH record: compressed size past the end (#721)
2026-12-01 01:13:26 +03:00
Bartosz Szczepański bc2b0add5d docs: directly indexed descriptor heaps on the ACO path
Measured with pixel shaders of our own compiled by xdxc: with
CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED and SAMPLER_HEAP_DIRECTLY_INDEXED the
resource and sampler heap pointers follow the root data, one 32-bit
register each, with 32-byte resource and 16-byte sampler descriptors.
The target build's pixel shaders with the sampler flag read their
sampler this way.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 22:17:52 +01:00
devil8blade 28041c38a3 [Picture] Build open-source DXC and prefer it over GDK dxcompiler.dll (#757)
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-30 13:31:15 -05:00
devil8blade bb21c4da3c [Picture] Scan all XBCH candidates and support v2 uncompressed records (#721)
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-30 13:30:30 -05:00
devil8blade 32f7bf2be1 [Picture] Claim #757: open-source DXC build and staging
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-30 13:10:24 -05:00
devil8blade 19c9667b5a [Picture] Claim #721: XBCH record bounds in gfx10-translate
Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-30 13:10:24 -05:00
Ateş dcb9e434c6 Merge pull request #749 from 1Bartosz/track-c/744-use-root-layout-lines
[Picture] d3d12_xs: USE ROOT layout lines are read as descriptor-table entries
2026-11-30 18:19:40 +03:00
Ateş a94888d1c7 Merge pull request #753 from MacosPorters/track-d/abi-bridge-wording
[ABI] bx_shader_bridge.h: two comments that disagreed with the code
2026-11-30 17:52:29 +03:00
ates a5f6dadc6f [ABI] bx_shader_bridge.h: say what the code does in two places
The comment said d3d12_xs caches under the two container keys, and that
an input that is not console code is invalid. d3d12_xs names cached
shaders by a hash of the HLSL, and bare bytes that are not code come
back unsupported, since bare code has no magic to check. Comments only.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 17:52:10 +03:00
Ateş 2420c52ee5 Merge pull request #752 from MacosPorters/track-f/roadmap-matches-translator
Roadmap: the Picture stage as it was built; ADR 0010 names the compiler
2026-11-30 17:51:42 +03:00
ates ecee277cfa Roadmap: the Picture stage as it was built; ADR 0010 names the compiler
The translator item said GFX10-to-DXIL and that every rule is checked
against the console compiler. The translator produces HLSL, compiled
with the GDK's dxcompiler.dll at first draw, and rules are checked from
public assembler encodings and the instruction's definition. Dated
state notes record what is done and what is open.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 17:51:21 +03:00
Bartosz Szczepański b92cfa8047 d3d12_xs: read only USE CB and USE TEX layout lines as table entries (#744)
The translator names each root constants or root descriptor parameter a
shader reads in a `USE ROOT <parameter>` layout line. The shim parsed it
like `USE CB <entry>`, as a constant-buffer read of entry <parameter> of
root parameter 0's table. With a parameter index of 8 or more the
pipeline was refused (beyond the eight widened entries) and drew
nothing; below 8 every submission looked up a table entry the shader
never reads and logged it as an unresolved descriptor.

Only CB and TEX lines name table entries now; other kinds are ignored,
as abi/include/bx_shader_bridge.h requires.

test_d3d12_console_root_constants draws with a vertex shader that reads
root parameter 8 of nine root constants.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 15:49:40 +01:00
Ateş bf468e8c48 Merge pull request #748 from MacosPorters/track-f/readme-current-state
README: describe the current state
2026-11-30 17:35:24 +03:00
ates d08aaa0e33 Revise the tracks page; drop a line from the README banner
docs/architecture/parallel-tracks.md listed the M0-M6 milestones and an
issue-claiming protocol that AGENTS.md has replaced. It now gives the
current directory table and points to AGENTS.md and the roadmap.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 17:34:09 +03:00
ates 1351925f40 README: describe the current state
The README still presented the M0-M6 milestone plan with M2 active and
listed existing work as unimplemented. It now states the stage and what
the target build does today, the stages of the roadmap, the run-time
shader translation, the current layout and commands, the requirements
for contributing, and what is and is not verified.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 17:28:59 +03:00
Ateş 663c8597ad Merge pull request #743 from MacosPorters/track-c/715-pass-root-layout
[Picture] Pass root signature layouts to the translator at run time
2026-11-30 14:56:17 +03:00
ates cb4683b688 Pass root signature layouts to the translator at run time (#715)
bx_shader_bridge.dll exports bx_shader_translate_pair_rooted. d3d12_xs
keeps each root signature's parameter list with its host object and
passes it when a console pipeline is first drawn. Root CBV and SRV
bindings give an address in plain title memory a host buffer, copied at
submission, when translated console shaders are enabled.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 14:55:58 +03:00
Ateş 837129f9d2 Merge pull request #742 from MacosPorters/track-d/715-root-layout
[Picture] gfx10-translate: root signature layouts
2026-11-30 14:46:53 +03:00
ates 0fc212b907 gfx10-translate: root signature layouts (#715)
Given the pipeline's root parameter list, each packed root value is
mapped to its parameter, in the register form (from s8) and in the
memory form (through s0 and the low byte of s1). A table is the
parameter its pointer belongs to; a root CBV, SRV or UAV becomes a
buffer at the title's own register and space, read by indexed and
byte-offset loads; root constants become a constant buffer. With a
layout, v0 on entry to a vertex shader is the vertex index and
v_add_nc_u32 is a real addition. Without one nothing changes.
bx-cli shader translate takes --root.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 14:46:32 +03:00
Ateş 4817914b50 Merge pull request #741 from MacosPorters/track-d/abi-translate-pair-rooted
[ABI] Define bx_shader_translate_pair_rooted
2026-11-30 14:26:10 +03:00
ates 29b8ec8ca2 [ABI] Define bx_shader_translate_pair_rooted (#715)
The translation of a console vertex/pixel pair given the layout of the
pipeline's root signature: the parameter list and the signature's flags.
Root descriptors and constants are declared at the title's own registers;
tables are translated as before. Header only.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 14:25:50 +03:00
Ateş 09f66dcd77 Merge pull request #740 from MacosPorters/track-f/root-data-memory-abi
[Picture] docs: the memory-based root ABI (follow-up to #739)
2026-11-30 14:25:14 +03:00
ates 75a958f655 docs: the memory-based root ABI of vertex shaders (#715)
With XBOX_FORCE_MEMORY_BASED_ABI the packed root data is read from
memory at four bytes per root dword, through an address in s0 and the
low byte of s1, in the same parameter order as the registers.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 14:24:52 +03:00
Ateş 3446c2a954 Merge pull request #739 from MacosPorters/track-f/graphics-root-data-abi
[Picture] docs: root data of vertex and pixel shaders (measurement for #715)
2026-11-30 14:24:00 +03:00
ates 99d17af66e docs: root data of vertex and pixel shaders on the ACO path (#715)
Six probes of our own compiled with the console xdxc: root data starts
at s8 in root-parameter order; a table pointer takes one register, a
root constant one per value, a root SRV or CBV two; there is no alignment
padding and stage visibility does not renumber.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 14:23:30 +03:00
Ateş fd970820c7 Merge pull request #735 from 1Bartosz/track-d/718-image-sample-3d
[Picture] gfx10-translate: image_sample_lz on 3D textures
2026-11-30 14:04:22 +03:00
Ateş 406198fcf9 Merge pull request #738 from MacosPorters/track-c/console-descriptors
[Picture] d3d12_xs: descriptors the title copies itself reach translated draws
2026-11-30 14:03:09 +03:00
ates eb356c0342 d3d12_xs: descriptors the title copies itself reach translated draws (#720)
Console descriptors are 32 bytes at their handle and the target build
copies them with memcpy. View creation now also writes a marker into the
title's descriptor memory, Direct3D's own copies carry the title-side
bytes too, and at submission the table entries each translated draw
reads are found through their markers and written to the host heap.
Constant data is copied from title memory at that moment.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 14:02:40 +03:00
Bartosz Szczepański ca3dfe72c6 changelog: image_sample on 3D textures (#718)
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 11:33:22 +01:00
Bartosz Szczepański 9d829a5269 gfx10-translate: image_sample and image_sample_lz on 3D textures (#718)
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 11:22:28 +01:00
Bartosz Szczepański feb3197e2f gfx10-translate: claim: image_sample_lz on 3D textures (#718)
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-30 11:20:54 +01:00
Ateş b3c6b2e885 Merge pull request #734 from MacosPorters/track-c/console-pipelines-first-draw
[Picture] d3d12_xs: translate console pipelines when they are first drawn
2026-11-30 13:09:54 +03:00
ates ba3f31418d d3d12_xs: translate console pipelines when they are first drawn (#720)
A stream pipeline the shader gate refuses as console code, when it is a
plain vertex/pixel pair, is kept with its stream. At its first draw the
pair is translated by bx_shader_translate_pair, compiled with the GDK's
PC dxcompiler.dll, and a host pipeline is created from the title's own
stream with the shaders, the input layout and the bound render-target
formats substituted. Compiled shaders are kept on disk by the hash of
their source. Root signatures are widened with the register spaces the
translated shaders use. bx-cli run stages the compiler with the other
GDK libraries. Opt-in with BX_CONSOLE_SHADERS=1.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 13:09:37 +03:00
Ateş 64d2ab15a0 Merge pull request #733 from MacosPorters/track-d/bridge-translate-pair
[Picture] bx_shader_bridge: translate a console vertex/pixel pair to HLSL
2026-11-30 12:49:34 +03:00
ates 32fc81cc9c bx_shader_bridge: translate a console vertex/pixel pair to HLSL (#720)
bx_shader_translate_pair returns the two HLSL sources, the layout lines
the host pipeline needs and the FNV-1a cache keys, using gfx10-translate.
A stage that is not modelled yet is refused with its reason and the keys.
bx_shader_free_pair_translation frees every buffer. Nothing calls the
export yet.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 12:48:30 +03:00
Ateş a6c922c480 Merge pull request #732 from MacosPorters/track-d/abi-shader-translate-pair
[ABI] Define bx_shader_translate_pair
2026-11-30 12:43:54 +03:00
ates 3f01646e48 [ABI] Define bx_shader_translate_pair (#720)
The contract between d3d12_xs and bx_shader_bridge.dll for translating a
console vertex/pixel pair to HLSL at first draw: the two sources, the
layout lines the host pipeline needs, the cache keys, and the reason
when a shader is not modelled yet. Header only; the export list and the
implementation follow.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 12:43:24 +03:00
Ateş 9acd450445 Merge pull request #731 from MacosPorters/track-d/translator-control-flow
[Picture] gfx10-translate: compares, execution masks and branches
2026-11-30 06:53:40 +03:00
ates 9ab94bdd68 gfx10-translate: compares, execution masks and branches (#717)
Shaders with compares, masks or branches are translated in structured
mode: exec, vcc and SGPR masks are per-lane bools, scc is uniform,
vector instructions act only where exec is set (image instructions are
computed for the whole quad and only their writes are selected), and
the code runs as numbered blocks under a dispatch loop with uniform
branch conditions. The final export's vm bit discards lanes no longer
in exec. The decoder reads past an s_endpgm that a branch jumps over.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:53:06 +03:00
Ateş e99a0af3f3 Merge pull request #730 from MacosPorters/track-b/zlib-prefix-reads-hang
[Menus] CopyTextureRegionX, and retry title faults on pages being remapped
2026-11-30 06:39:02 +03:00
ates d672271c6a Keep the documented zlib size rule; the fix is CopyTextureRegionX and the remap retry
Removing the zlib destination-size check did not stop the hangs, and the
short reads it allowed come from #708's sizes, so the GDK's rule stays
and test_xcrdapi_xbox keeps checking it.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:38:25 +03:00
ates aa41d275c6 Merge remote-tracking branch 'origin/main' into track-b/zlib-prefix-reads-hang 2026-11-30 06:34:49 +03:00
ates 0d1fcc3460 Fix three causes of the menu hangs and crashes (#722)
CopyTextureRegionX is implemented as CopyTextureRegion; as a stub it left
a copy undone and the title's hang watchdog ended the process. A title
fault on a page that xmem is remapping is retried once the remap is
over. zlib requests whose compressed size is not smaller than the
destination are accepted and only their first DestinationSize bytes
are decoded.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:34:47 +03:00
Ateş 6ecd70bac5 Merge pull request #728 from MacosPorters/track-d/translator-image-load
[Picture] gfx10-translate: image_load and image_gather4_lz
2026-11-30 06:22:48 +03:00
ates 83cdd49fab gfx10-translate: image_load and image_gather4_lz (#718)
Integer-coordinate loads (mip 0) from 2D, 3D and 2D-array textures,
declared by the dimension they are read with, and single-component
gathers on 2D textures. Locally 900 of 4,331 shaders translate.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:22:31 +03:00
Ateş e667dfe435 Merge pull request #727 from MacosPorters/track-d/translator-descriptor-tables
[Picture] gfx10-translate: descriptor tables of every root parameter
2026-11-30 06:18:27 +03:00
ates f06dc97414 gfx10-translate: descriptor tables of every root parameter (#715)
s8+k holds root parameter k's table pointer; its resources go in
register space 100+k (root parameter 0 keeps the prototype's names).
Constant-buffer loads with a register offset become indexed reads. Also
v_fmac_f32_e64 and s_mul_hi_u32. Locally 894 of 4,331 shaders translate
(811 before); the 214 prototype pairs stay identical.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:18:11 +03:00
Ateş fc74ea53f8 Merge pull request #726 from MacosPorters/track-d/translator-output-modifiers
[Picture] gfx10-translate: VOP3 abs, neg, omod and clamp on float instructions
2026-11-30 06:15:13 +03:00
ates 7f689cb542 Merge main; record VOP3 float modifiers in the changelog
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:14:56 +03:00
ates 9bc65d7010 gfx10-translate: VOP3 abs, neg, omod and clamp on float instructions (#719)
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 06:14:10 +03:00
Ateş a35dc6e3a8 Merge pull request #725 from MacosPorters/track-d/translator-integer-conversions
[Picture] gfx10-translate: integer, conversion and lane instructions
2026-11-30 06:10:40 +03:00
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
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
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
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 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
155 changed files with 22336 additions and 446 deletions

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
name: Build open-source DXC (dxcompiler.dll)
# Builds x64 Release dxcompiler.dll from the pinned microsoft/DirectXShaderCompiler
# tag on a Windows runner so BetterXen does not redistribute Microsoft's prebuilt
# release zip or stage the GDK's dxcompiler.dll (#757).
on:
workflow_dispatch:
inputs:
tag:
description: DirectXShaderCompiler release tag to build
required: true
default: v1.9.2609
type: string
permissions:
contents: read
concurrency:
group: dxc-build-${{ github.ref }}
cancel-in-progress: true
jobs:
build-dxcompiler:
name: Build dxcompiler.dll (x64 Release)
runs-on: windows-latest
timeout-minutes: 45
steps:
- name: Checkout DirectXShaderCompiler
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: microsoft/DirectXShaderCompiler
ref: ${{ inputs.tag }}
path: dxc
submodules: recursive
persist-credentials: false
- name: Configure CMake (x64)
run: >
cmake -B build -S dxc -A x64
-C dxc/cmake/caches/PredefinedParams.cmake
-DHLSL_INCLUDE_TESTS=OFF
-DENABLE_SPIRV_CODEGEN=OFF
- name: Build dxcompiler (Release)
run: cmake --build build --config Release --target dxcompiler --parallel
- name: Verify DxcCreateInstance export and collect artifact
shell: pwsh
run: |
$dll = Get-ChildItem -Path build -Recurse -Filter dxcompiler.dll |
Where-Object { $_.FullName -match '\\Release\\' } |
Select-Object -First 1
if (-not $dll) {
throw "dxcompiler.dll not found under build/**/Release/"
}
$bytes = [System.IO.File]::ReadAllBytes($dll.FullName)
$marker = [System.Text.Encoding]::ASCII.GetBytes("DxcCreateInstance`0")
$found = $false
for ($i = 0; $i -le $bytes.Length - $marker.Length; $i++) {
$match = $true
for ($j = 0; $j -lt $marker.Length; $j++) {
if ($bytes[$i + $j] -ne $marker[$j]) { $match = $false; break }
}
if ($match) { $found = $true; break }
}
if (-not $found) {
throw "DxcCreateInstance export string not found in $($dll.FullName)"
}
New-Item -ItemType Directory -Force -Path dist | Out-Null
Copy-Item $dll.FullName dist/dxcompiler.dll
$hash = (Get-FileHash dist/dxcompiler.dll -Algorithm SHA256).Hash
Write-Host "Built $($dll.FullName)"
Write-Host "SHA-256: $hash"
- name: Upload dxcompiler.dll artifact
uses: actions/upload-artifact@v4
with:
name: dxcompiler-${{ inputs.tag }}-win64-release
path: dist/dxcompiler.dll
if-no-files-found: error
+22 -5
View File
@@ -23,13 +23,16 @@ cargo build --locked -p bx-cli && target/debug/bx-cli preflight
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
| **The Ghidra results of the target build** (the static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable | Found and saved by `bx-cli setup --find` |
| At least 10 GiB of free disk space | Measured |
**The target build, the GDK and the Ghidra results are a hard requirement.** An agent that lacks even one of them does not work on this repository at all: no code, tests, reviews, merges, issues or documentation.
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
| `MISSING` line | What you do |
| --- | --- |
| Target build, GDK | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header and the build by its structure (never by name), and saves both. |
| Target build, GDK, Ghidra results | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header, the build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three. |
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
@@ -37,13 +40,13 @@ cargo build --locked -p bx-cli && target/debug/bx-cli preflight
- the host is not an Apple Silicon Mac;
- CrossOver is not installed (it is licensed software; do not install it);
- `setup --find` reports that the target build or the GDK is not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
- `setup --find` reports that the target build, the GDK or the Ghidra results covering the build are not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
In those cases do not work around it: no fixes, tests or reviews "for someone else to verify". Work here is found by running the target build and checked against the GDK; an agent without them is guessing.
In those cases stop and do not work around it: no fixes, tests, reviews, merges or documentation "for someone else to verify". Work here is found by running the target build, located in the Ghidra results and checked against the GDK; an agent without all three is guessing.
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
`bx-cli setup` remembers the two locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE` and `BX_GDK_ROOT` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build or the GDK into a commit, issue or pull request (Section 6).
`bx-cli setup` remembers the three locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE`, `BX_GDK_ROOT` and `BX_GHIDRA_RESULTS` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build, the GDK or the Ghidra results into a commit, issue or pull request (Section 6).
### Step 2 — Pick exactly one thing, in this order
@@ -75,6 +78,19 @@ Take the first that applies.
### Step 3 — Work one blocker
**Before touching any problem the game shows you, find out whether someone already has it.** This applies every time: to the blocker you picked, and to every further problem you meet along the way (a failed load, a refused request, an assert, a crash). Search by the log event, stub symbol, error code and the files you would change:
```sh
gh pr list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,headRefName
gh pr list --repo MacosPorters/betterxen --state merged --search "<event, symbol or file>" --limit 10 --json number,title,mergedAt
gh issue list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,labels
```
- **An open pull request covers it:** check out that branch (`gh pr checkout <n>`), run the build with it, and work there: report what you saw on the pull request, and push a fix to its branch or request changes. Do not write a second fix.
- **A merged pull request covers it:** sync with `origin/main` and run again before investigating.
- **An issue covers it:** take it up from the issue's notes, and link it from your pull request.
- **Nothing covers it:** carry on with step 1 below.
1. **Claim with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. Check the contract against the GDK where the GDK covers it.
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
@@ -99,6 +115,7 @@ Take the first that applies.
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
- **GDK texture libraries (ADR 0010):** Console texture layouts (tiling) and BCPack decompression come from the GDK's own PC libraries, `xg_xs.dll` and `BCPack.dll`, which `bx-cli run` stages for the target build from the configured GDK. Do not reimplement them, and never commit or ship them.
---
@@ -156,7 +173,7 @@ _Reserved — policy migration in progress._
## 7. Claiming, Git Safety & Changelog
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. A draft with no push for 3 days may be taken over. Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. Every problem met while running the game, not only the one picked, is searched for in open and merged pull requests and open issues before it is investigated; when a pull request covers it, check that branch out and work there (Section 0, Step 3). A draft with no push for 3 days may be taken over. Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
2. **Isolate with branches or worktrees:**
```sh
git worktree add ../wt-<slug> -b track-<a..f>/<slug> origin/main
+133
View File
@@ -9,7 +9,22 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Fixed
- **`gfx10-translate`: scan all `XBCH` candidates and support version 2/3 payloads** (#721). `container_code` previously stopped at the first `b"XBCH"` byte sequence in a container, so incidental `b"XBCH"` bytes earlier in the blob (for example in `STAT` or `DXIL` bitcode) caused it to read garbage sizes and fail with `XBCH record: compressed size past the end`. It now scans all `b"XBCH"` occurrences, validates the 24-byte header, bounds, version (`2` uncompressed `FSSM`, `1` and `3` zlib-compressed `FSSM`), and `FSSM` magic, and skips non-matching candidates. Covered by synthetic unit tests in `gfx10_translate::container::tests`.
### Changed
- **Open-source DXC (`dxcompiler.dll`) replaces the GDK's shader compiler as the primary source** (#757, ADR 0010).
- `.github/workflows/dxc-build.yml` builds x64 Release `dxcompiler.dll` from `microsoft/DirectXShaderCompiler` at pinned tag `v1.9.2609` on a Windows runner and uploads it as a workflow artifact.
- `bx-cli setup --dxc-dir <dir>` (and `BX_DXC_DIR`) records the local open-source DXC folder in `local.conf` (`dxc_dir`).
- `bx-cli run` (`gdk_libs::resolve`) stages `dxcompiler.dll` from `dxc_dir` first, falling back to the GDK's `dxcompiler.dll` only if no open-source build is configured. `dxcompiler.dll` is recognised by name and the `DxcCreateInstance` export, and `dxil.dll` is no longer staged.
- ADR 0010, `docs/research/upstream-registry.md`, and `docs/research/component-reuse-matrix.md` record the source build and its `LICENSE.TXT` / per-file licence check.
- **`docs/roadmap.md`, Picture stage, corrected to what was built.** The translator item said "GFX10-to-DXIL"; it produces HLSL, and `d3d12_xs` compiles that with the GDK's `dxcompiler.dll` at first draw. The item also said each rule is checked against the console compiler's output; it now says how rules are checked today (public assembler encodings and the instruction's definition) and where the console compiler has been used (the root-data layout). Dated state notes record that the capability checks were not done first, what is translated at run time, and what is open (#744, #745, #746). ADR 0010's title now names the shader compiler it has covered since #734; its file name is unchanged.
- **`README.md` rewritten for the current state** (2026-11-30). It described the M0–M6 milestone plan with M2 active and listed as unimplemented several things that exist. It now gives the stage (Picture) and what the target build does today, the stages from `docs/roadmap.md`, an architecture diagram with the run-time shader translation and the GDK libraries, the current repository layout and `bx-cli` commands, the hard requirements for contributing, and a section that separates what the repository's tests verify from what was observed on the target build and from what is not claimed. `docs/architecture/parallel-tracks.md` is revised the same way: it listed the M0–M6 milestones and an issue-claiming protocol that `AGENTS.md` has replaced; it now gives the current directory table and points to `AGENTS.md` and the roadmap for the rules and the stages.
- **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.
@@ -26,6 +41,98 @@ remains unsupported.
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
### Added
- **`docs/research/console-shader-abi.md`: directly indexed descriptor heaps** (SM 6.6 `ResourceDescriptorHeap` / `SamplerDescriptorHeap`). Measured with probes of our own compiled by `xdxc`: the heap pointers follow the root data (resource heap, then sampler heap), as 32-bit pointers, with 32-byte resource and 16-byte sampler descriptors. The target build's pixel shaders with `SAMPLER_HEAP_DIRECTLY_INDEXED` take their sampler that way; the translator does not model it yet.
- **Root signature layouts reach the translator at run time** (#715, #720; with `BX_CONSOLE_SHADERS=1`).
- `bx_shader_bridge.dll` exports `bx_shader_translate_pair_rooted` (contract #741): the translation given the root parameter list and the signature's flags. `bx_shader_translate_pair` is the same call with no layout. The export list has 118 names across the 17 DLLs.
- `d3d12_xs.dll` keeps each root signature's parameter list with its host object and passes it when a console pipeline is first drawn. With an older bridge it falls back to the table-only translation.
- `SetGraphicsRootShaderResourceView` and `SetGraphicsRootConstantBufferView` give an address in plain title memory a host buffer, copied at submission. A root buffer has no size, so what is readable there is copied, up to 256 KiB for an SRV and 64 KiB for a CBV; a shader that reads further sees zeros.
- Tests: `test_d3d12_console_pipeline_first_draw` gains a root SRV case, a vertex shader that pulls its positions by vertex index, drawn from an upload buffer and from plain process memory (46 checks); `tests/translate_pair.rs` covers the export, including inconsistent layouts.
- On the target build every vertex/pixel pair it draws with in its first two minutes now translates; none is refused. The picture is unchanged (the menu's bars).
- **`gfx10-translate`: root signature layouts** (#715; the rules are measured in `docs/research/console-shader-abi.md`). `translate_pair_rooted` and `translate_blobs_rooted` take the pipeline's root parameter list (`RootLayout`).
- Each packed root value is mapped to its parameter: a table pointer is one value, a root CBV, SRV or UAV two, a constant one each. Both forms are read: registers from `s8`, and root data in memory through `s0` and the low byte of `s1` (`memory_based`).
- A descriptor table is the parameter its pointer belongs to, no longer its register's position.
- A root CBV, SRV or UAV, whose buffer descriptor the shader builds from the address, becomes a buffer at the title's own register and space. Indexed (`idxen`) and byte-offset (`offen`) loads and `s_buffer_load` read it.
- A constants parameter becomes a constant buffer at its own register and space.
- In a vertex shader translated with a layout, `v0` read before it is written is `SV_VertexID`, and `v_add_nc_u32` is a real addition (without a layout it is still dropped, as the prototype did).
- Each root descriptor or constants parameter a stage reads adds a `USE ROOT <parameter>` layout line.
- Without a layout nothing changes: the golden pairs still match.
- `bx-cli shader translate` takes `--root <layout>`, e.g. `T,S:0:0,C2:1:0,B:2:0,mem`.
- Tests: `root_layout_register_form`, `root_layout_memory_form`, `root_layout_decides_what_a_register_holds` and `root_buffer_byte_offsets_and_the_vertex_index`, from our own assembly through llvm-mc.
- The last vertex/pixel pair the target build's menus draw with that was refused (a single root SRV, vertex pulling) now translates with its layout, and its HLSL compiles with dxc. Nothing passes a layout at run time yet: the bridge export (#741) and `d3d12_xs` follow.
- **`docs/research/console-shader-abi.md`: root data of vertex and pixel shaders** (#715). Six probes of our own, compiled with the console `xdxc` (the ACO path that ACCC containers carry): root data starts at `s8` in root-parameter order; a table pointer takes one register, a root constant one per value, a root SRV or CBV two; no alignment padding; stage visibility does not renumber. This is the measurement behind passing the root-signature layout to the translator. With `XBOX_FORCE_MEMORY_BASED_ABI`, which the target build's root signatures set, the same packed data is read from memory at four bytes per root dword, through an address in `s0` and the low byte of `s1`.
- **`d3d12_xs.dll`: descriptors the title copies itself reach translated draws** (#720; with `BX_CONSOLE_SHADERS=1`). On the console a descriptor is 32 bytes at its handle, and the target build fills per-draw tables with `memcpy`, so the host heap held nothing there.
- Every `CreateConstantBufferView` and `CreateShaderResourceView` also writes a marker into the title's descriptor memory. `CopyDescriptors` and `CopyDescriptorsSimple` copy the title-side bytes too.
- Each translated draw records the tables bound to its list. At submission, the entries its shaders read are found through their markers and written to the host heap at the same index.
- A constant buffer's bytes are copied from title memory into an upload ring at submission.
- An entry without a marker is left as the host heap has it and logged (`console_descriptor`).
- Test: `test_d3d12_console_pipeline_first_draw` gains a case with a view copied by Direct3D and then by hand into the bound table (36 checks).
- On the target build about 25,000 entries were resolved in a 110 s run. The frames are still black: the pipelines that would fill the presented buffer are refused by the translator (a 3D `image_sample_lz`, a buffer loaded from a root register) and compute is not translated.
- **`d3d12_xs.dll`: console pipelines are translated when first drawn** (#720; opt-in with `BX_CONSOLE_SHADERS=1`).
- A stream pipeline the shader gate refuses as console code, when it is a plain vertex/pixel pair, is kept with its stream instead of becoming a bare null pipeline.
- At its first draw the pair is translated by `bx_shader_translate_pair`, the HLSL is compiled with the GDK's PC `dxcompiler.dll`, and a host pipeline is created from the title's own stream with the shaders, the input layout and the bound render-target formats substituted. One host pipeline is kept per bound format set.
- Compiled shaders are kept on disk (`BX_SHADER_CACHE`, default `%LOCALAPPDATA%\BetterXen\shader-cache`), named by the hash of their HLSL source, so a translator change never reuses an old result.
- Every root signature is widened with the register spaces translated shaders use (`CreateRootSignature` now goes through `pipelines.cpp`).
- A pair that cannot be translated yet is not drawn, and its reason is logged (`console_pipeline`).
- `bx-cli run` stages the GDK's `dxcompiler.dll` and `dxil.dll` with the other GDK libraries (ADR 0010) and passes `BX_CONSOLE_SHADERS` and `BX_SHADER_CACHE` to the guest.
- Test: `test_d3d12_console_pipeline_first_draw` draws a red ramp with a console pair of our own into two target formats, checks the disk cache on a second pipeline and the logged reason of an untranslatable pair (25 checks; it skips without `--gdk-libraries`).
- Not yet: the title's own descriptors and textures reach translated draws only in follow-up changes, so the target build still shows no picture.
- **`bx_shader_bridge.dll`: `bx_shader_translate_pair`** (#720, contract in `abi/include/bx_shader_bridge.h`, #732). Translates a console vertex/pixel pair to HLSL with `gfx10-translate`.
- Returns the two sources, the layout lines the host pipeline needs (`FETCH`, `ATTR`, `USE CB`, `USE TEX`) and the cache keys (64-bit FNV-1a of each input).
- A stage the translator does not model returns `BX_SHADER_ERR_UNSUPPORTED` with a one-line reason and the keys, so a refusal can be cached.
- `bx_shader_free_pair_translation` frees every buffer. The export list has both names (117 exports across the 17 DLLs).
- Nothing calls it yet: `d3d12_xs` using it at first draw, with DXC and a disk cache, is the next step of #720.
- Tests: `test_shader_bridge_translate` calls the built DLL (25 checks); `tests/translate_pair.rs` compares the output through the C entry point with the reference translator's golden files.
- **`gfx10-translate`: `image_sample` and `image_sample_lz` on 3D textures** (#718). MIMG `dim` 2 (`SQ_RSRC_IMG_3D`) reads three address registers, the normalized coordinates s, t and r (RDNA 2 ISA); the sample becomes `Texture3D.Sample`/`SampleLevel(smp0, float3(...), 0)` and the texture is declared `Texture3D`. Samples now go through the same texture check as `image_load` and `image_gather4_lz`: a texture read with two dimensions, cube maps, other dimensions, and 16-bit addresses or data (`a16`, `d16`, `tfe`) are refused instead of being translated as 2D. In the target build this translates one more vertex/pixel pair that its menus draw with. Tests: `image_samples_on_3d_textures`, `refuses_cube_and_a16_samples`.
- **`gfx10-translate`: compares, execution masks and branches** (#717). A shader with any of them is translated in structured mode.
- Each lane's `exec`, `vcc` and every mask kept in SGPRs is a per-lane `bool`; `scc` is a wave-uniform `bool`.
- Vector instructions act only where `exec` is set. Image instructions are computed for the whole quad, since their derivatives need it, and only their register writes are selected.
- The program is split into blocks at branch targets and after branches, and a loop dispatches on the current block. Branch conditions are uniform: `scc`, or `WaveActiveAnyTrue` of a mask.
- Translated:
- `v_cmp`/`v_cmpx` on f32, u32 and i32, including `class`;
- `v_cndmask`, `s_cmp`, `s_cselect`;
- the scalar mask operations and their `saveexec` forms;
- `s_wqm` (lanes of a set quad, via `QuadReadAcross*`);
- `s_branch` and the `s_cbranch` forms on scc, vcc and exec.
- The final export's `vm` bit discards lanes no longer in `exec`.
- The decoder now reads past an `s_endpgm` that a branch jumps over (an early exit).
- Tests: `divergent_if_runs_under_exec`, `cmpx_removes_lanes_before_the_final_export`, `early_exit_keeps_the_code_after_it` and `samples_run_for_the_whole_quad`, all from llvm-mc encodings.
- Locally, 1,535 of the target build's 4,331 shaders translate, up from 900. The 632 that use structured mode all compile with dxc (`ps_6_0`/`vs_6_0`); compiling is not running them.
- Blockers now: register-offset descriptor loads, `ds_swizzle_b32`, buffer stores, and vertex fetch through a constant buffer.
- **`gfx10-translate`: `image_load` and `image_gather4_lz`** (#718). Loads at integer coordinates, mip 0, from 2D, 3D and 2D-array textures, each declared by the dimension it is read with. A texture read with two dimensions, and 16-bit addresses or data, are refused. Gathers of one component (`GatherRed` to `GatherAlpha`) on 2D textures. The test `image_loads_and_gathers` uses llvm-mc encodings. Locally 900 of the target build's 4,331 shaders translate; the shaders unblocked here next stop mostly on compares (#717).
- **`gfx10-translate`: descriptor tables of every root parameter** (#715).
- **Tables:** s8+k holds root parameter k's table pointer (s8 for 0, s9 for 1, ...), read zero-extended through `s_mov_b32`. Its constant buffers and textures are declared in register space 100+k, as `cb{k}_{entry}` and `tex{k}_{entry}`. The layout file gains `USE CB <k> <entry>`. Root parameter 0 keeps the prototype's names and lines.
- **Computed offsets:** a constant-buffer load with a register offset is an indexed read. A 4-dword descriptor loaded with a computed index keeps the unknown-origin treatment; an 8-dword one (a texture array) stays refused.
- **Two more rules** now reachable: `v_fmac_f32_e64` and `s_mul_hi_u32`.
- **Measured locally:** 894 of the target build's 4,331 shaders translate (811 before); all 214 prototype pipeline pairs are still identical.
- **Test:** `root_parameter_tables_and_register_offsets`.
- **`gfx10-translate`: VOP3 modifiers on 32-bit float instructions** (#719). Input `abs` is applied before `neg` on each source, and `omod` (×2, ×4, ÷2) then `clamp` (`saturate`) on the result. `clamp` or `abs` on integer instructions and `op_sel` stay refused. The test `vop3_float_modifiers` uses llvm-mc encodings. Locally 811 of the target build's 4,331 shaders translate; the shaders that stopped on `clamp` now mostly stop on descriptor tables (#715).
- **`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.
@@ -90,6 +197,32 @@ remains unsupported.
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
### Fixed
- **`d3d12_xs.dll`: a translated pipeline that reads a root constants or root descriptor parameter is no longer refused or mistaken for a table read** (#744). The shim read the translator's `USE ROOT <parameter>` layout line as `USE CB <entry>`: as a constant-buffer read of entry `<parameter>` of root parameter 0's table. With a parameter index of 8 or more the pipeline was refused ("reads table entry 8, beyond the 8 widened ones") and drew nothing; below 8 each submission looked up a table entry the shader never reads and logged it as an unresolved descriptor, which was most of the `console_descriptor` warnings on the target build's first screens and hid the real ones. Only `USE CB` and `USE TEX` lines now name table entries; other kinds are ignored, as `abi/include/bx_shader_bridge.h` says. `test_d3d12_console_root_constants` draws with a vertex shader that reads root parameter 8.
- **Two causes of the target build's menu crashes are fixed** (#722). Before, most runs ended with exit status 5 within a few minutes.
- **`d3d12_xs.dll`: `CopyTextureRegionX` is implemented**, as `CopyTextureRegion`; its `D3D12XBOX_COPY_FLAGS` steer console compression metadata the host does not have. As a stub it left a copy undone, the title's frame never completed, and its hang watchdog ended the process 30 s later (every watchdog crash followed its first call by 32–41 s). Test: `test_d3d12_copy_texture_region_x`, a box copy and a whole-texture copy through slot 85, read back. On the previous shim no pixel is copied.
- **`bx_runtime_veh.dll`: a title fault on a page being remapped is retried.** xmem replaces part of a mapped run by unmapping the whole view and mapping the rest back, so other pages of the run briefly disappear; on the console that update is atomic. A fault in the title's own code on an inaccessible address now waits for any remap in progress (the remap guard) and retries if the address has become accessible. Each retry is logged (`remap_window_retry`). Genuine faults still reach the title. Test: `test_veh_remap_window`, four unguarded readers of one page while two pages of its run are remapped for four seconds. It crashes 4 of 4 times without the retry. A rarer silent case, a read that sees other data without faulting, remains (#729).
- **Measured** on the target build (Apple Silicon, offline, scripted input, 210 s runs):
- with `CopyTextureRegionX`, 1 of 9 runs still hit the watchdog (before, every crash did); that hang has another cause, still open in #722;
- with the retry, a fault at the earlier recurring site was retried and the run completed.
- **`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.
+41 -22
View File
@@ -1,35 +1,53 @@
# Contributing to BetterXen
BetterXen is a modular, CrossOver-based Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS. Contributions are organized into **6 parallel tracks** so 5–8+ human contributors and coding agents can work simultaneously without merge conflicts.
BetterXen runs a project-authorized Xbox Series title on Apple Silicon Macs, through CrossOver, Rosetta 2 and D3DMetal plus BetterXen's own shims. Members work by pointing a coding agent at this repository and saying **"work"**; the agent follows [AGENTS.md](AGENTS.md). This page is the short version for a person joining.
## Active Work & Track Ownership
## What you need
The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones M0–M6), supported by [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and the ready-to-claim Wave 1 issues in [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md). The earlier native-first workspace was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently at Git tag `native-first-final`.
These are a **hard requirement**. Without every one of them you, and your agent, do not work on the repository:
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. Maintainer-directed tasks have a narrow exception ([AGENTS.md](AGENTS.md) §2).
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
- an Apple Silicon Mac with CrossOver 26.3+ (licensed separately, never bundled), D3DMetal, and at least 10 GiB free;
- **the project-authorized target build**;
- **the GDK**, under the project's authorization;
- **the Ghidra results of the target build** (its static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`).
## Development & Verification
The target build, the GDK and the Ghidra results are distributed among members. Ask a maintainer for them; never get them anywhere else, and never commit, upload or post anything from them (paths, file names, hashes or bytes).
Requirements on Apple Silicon macOS: Rust 1.85+ (`aarch64-apple-darwin`), `mingw-w64` & `cmake` (`brew install mingw-w64 cmake`), Python 3.11+, Rosetta 2, and CrossOver 26.3+ (externally installed, never bundled).
Run these checks before opening a PR:
## Getting started
```sh
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli && lipo -archs target/debug/bx-cli
scripts/build-shims.sh
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
python3 scripts/audit/docs_hygiene.py
git clone https://github.com/MacosPorters/betterxen.git && cd betterxen
brew install mingw-w64 cmake gh # Rust 1.85+ and Python 3.11+ are also needed
cargo build --locked -p bx-cli
target/debug/bx-cli setup --find # finds the build, the GDK and the Ghidra results in your home folder
target/debug/bx-cli preflight # must print: Ready to work.
```
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
`setup` saves the three locations in `~/.config/betterxen/local.conf`, outside the repository, once per machine. If `--find` finds more than one distinct build, choose with `bx-cli setup --target-exe <path>`.
Then tell your agent **"work"**. If you work by hand, follow the same steps yourself: [AGENTS.md](AGENTS.md) Section 0.
## How work is organised
The full process is [AGENTS.md](AGENTS.md) Section 0 and [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md). In short:
1. **Pick one thing**, in this order: your own pull requests that need attention; a review of someone else's; a `handoff` issue of the current stage (named on the pinned `ladder` issue); or the first thing the target build stops on.
2. **Check for existing work first.** Before investigating any problem the game shows, search open and merged pull requests and open issues for it. If an open pull request covers it, check that branch out and work there.
3. **Claim it with a draft pull request** titled `[<Stage>] <signature>`, before writing the fix. A draft with no push for 3 days may be taken over.
4. **Evidence, smallest fix, test.** Every contract the fix introduces gets a conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row with it.
5. **Verify** with [AGENTS.md](AGENTS.md) Section 8, fill in the five-part description (Blocker, Contract, Fix, Test, Proof), and mark it ready.
Something you can't finish goes into a `handoff` issue instead, with what you saw, tried and still don't know.
## Running the target build
Runs are made offline, inside a sandbox that blocks outbound network: [docs/testing/target-build-review.md](docs/testing/target-build-review.md) has the procedure and the diagnostic switches. Three switches matter for getting through the title unattended:
- `BX_INPUT_SCRIPT=A@40,A@50` presses buttons;
- `BX_CONTINUE_ASSERTS=1` steps over the title's continuable asserts;
- `BX_PRESENT_DUMP=<folder>` saves frames.
`bx-cli run` stages the GDK's texture libraries for the target build automatically ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)). `bx-cli report <log.jsonl>...` turns run logs into the report and the blocker signatures that pull requests are titled with.
## Licensing & Provenance Policy
@@ -39,9 +57,10 @@ Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/ski
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
## Pull Requests & DCO Sign-Off
- Branch from `main`, keep changes focused inside your track scope, link the issue with `Closes #<number>`, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Branch from `main`, keep changes focused inside your track scope, link any related issue (`Closes #<number>` for a handoff it finishes), update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, and update [docs/README.md](docs/README.md) when adding or reorganizing docs.
- Disclose material AI assistance and personally review generated changes. Never include secrets, personal paths, or credentials in patches or logs.
- Sign off every commit under the [Developer Certificate of Origin](https://developercertificate.org/):
Generated
+8
View File
@@ -9,6 +9,7 @@ dependencies = [
"bx-probe",
"bx-telemetry",
"dxbc-accc",
"gfx10-translate",
"libc",
]
@@ -30,6 +31,13 @@ dependencies = [
[[package]]
name = "dxbc-accc"
version = "0.2.0"
dependencies = [
"gfx10-translate",
]
[[package]]
name = "gfx10-translate"
version = "0.2.0"
[[package]]
name = "libc"
+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"
+143 -129
View File
@@ -2,236 +2,250 @@
# BetterXen
**Modular Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS — built on CrossOver, Rosetta 2, and D3DMetal 3.0.**
**An Xbox Series (`Scarlett`) compatibility layer for Apple Silicon Macs, built on CrossOver, Rosetta 2 and D3DMetal 3.0.**
[![Hybrid build and shim checks](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml)
[![Repository hygiene](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml)
![Platform: Apple Silicon](https://img.shields.io/badge/platform-Apple%20Silicon%20(ARM64)-1f6feb?logo=apple&logoColor=white)
![Graphics: D3DMetal 3.0](https://img.shields.io/badge/graphics-D3DMetal%203.0%20%2F%20Metal-8957e5)
![Stack: Rust + C++20 PE32+](https://img.shields.io/badge/stack-Rust%20%2B%20C%2B%2B20%20PE32%2B-dea584)
![Status: experimental](https://img.shields.io/badge/status-experimental%20(M2)-0969da)
![Stage: Picture](https://img.shields.io/badge/stage-Picture-0969da)
![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-2ea043)
</div>
> [!IMPORTANT]
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
> **Experimental.** The goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. Today that build boots, reaches its frame loop and its first menus, and translates its own shaders at run time, but it shows almost no picture yet. CrossOver, Rosetta 2 and D3DMetal are installed separately and are never bundled or redistributed.
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
- **Cross-compiled x86-64 Windows PE32+ shim DLLs** (`shims/`, C++20 via `mingw-w64`) implementing Xbox runtime APIs (`xmem`, `XCRDAPI`, `d3d12_xs`, `xg_xs`, `xgameruntime`, `GameInput`, `AcpHal`/`xapu`/`chad`, Win32/PSM forwarders, and a `clwb` Vectored Exception Handler).
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
## Where it stands
> [!CAUTION]
> **Provenance and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
*As of 2026-11-30, on `main`. The live status is on the pinned issue labelled [`ladder`](https://github.com/MacosPorters/betterxen/issues?q=is%3Aissue+is%3Aopen+label%3Aladder).*
---
The current stage is **Picture**: the target build should show its first non-black screen, correctly.
## Progress Tracker
| | State |
| --- | --- |
| **Boot** | The target build starts, creates its Xbox-layout D3D12 device, loads through DirectStorage, and presents frames. |
| **Menus reached** | With scripted input it goes through its first-run setup screens. A hang watchdog in the build still ends most runs after a few minutes ([#722](https://github.com/MacosPorters/betterxen/issues/722)). |
| **Shaders** | The build ships console (RDNA 2) code only. BetterXen's own translator turns a vertex/pixel pair into HLSL when a pipeline is first drawn; the result is compiled and cached on disk. Every vertex/pixel pipeline the build draws with in its first two minutes translates and runs. Opt-in: `BX_CONSOLE_SHADERS=1`. |
| **Picture** | Only the menu's background bars appear, in a few frames. The rest is open work: [#744](https://github.com/MacosPorters/betterxen/issues/744) (why only the bars), [#745](https://github.com/MacosPorters/betterxen/issues/745) (texture contents), [#746](https://github.com/MacosPorters/betterxen/issues/746) (compute shaders). |
| **Translator coverage** | 1,538 of 4,331 vertex and pixel shaders in one member's dump of the build translate offline (35.5%). That means "produces HLSL that compiles", not "verified against the console". |
| **Sound, saves, gameplay, performance** | Not started as stages. Audio and save shims answer the build's calls so that it runs; nothing is audible. |
> *Tracks engineering milestones and synthetic conformance progress only — not commercial game compatibility percentages.*
Without `BX_CONSOLE_SHADERS=1` the window stays black: pipelines with console shaders are refused and their draws are skipped.
### Stages
From the Boot stage on, progress is measured by how far the target build gets in repeated, recorded runs, not by subsystems. Each stage has one exit gate: ten runs out of ten on a 16 GB Mac.
```mermaid
flowchart LR
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
M3["M3: Shaders &\nTexture Tiling"]:::planned
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
M5["M5: Audio, Saves\n& Stability"]:::planned
M6["M6: Cache & 16 GB\nOptimization"]:::planned
F["Foundation\nM0–M2, synthetic"]:::done
B["Boot"]:::done
P["Picture\n(current)"]:::active
M["Menus"]:::planned
W["World"]:::planned
Fi["Fidelity"]:::planned
Pl["Playable"]:::planned
M0 --> M1 --> M2 --> M3 --> M4 --> M5 --> M6
F --> B --> P --> M --> W --> Fi --> Pl
classDef done fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:2px
classDef active fill:#ddf4ff,stroke:#0969da,color:#0a3069,stroke-width:2px
classDef planned fill:#f6f8fa,stroke:#8c959f,color:#57606a
```
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
| Track | Focus | Visual Status | Live Issues |
| --- | --- | --- | --- |
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
### Milestone Roadmap (M0 → M6)
| Milestone | Scope | Status |
| Stage | The target build… | Status |
| --- | --- | --- |
| **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 |
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
| **M6 — Cache, 16 GB Tuning & Polish** | Persistent PSO/shader disk cache, Lockhart 16 GB unified memory optimization, Metal System Trace tuning | ⚪ Planned |
| **Foundation** | (synthetic tests only) repository, frozen ABI, cross-built shims, a synthetic first frame, the shader format decision | Done |
| **Boot** | starts, reaches its frame loop and stays there | Left on 2026-11-30 by the repository owner's decision; its ten-run gate was not run |
| **Picture** | shows its first non-black screen, correctly | **Current** |
| **Menus** | plays its opening sequence and menus with sound and input | Planned |
| **World** | loads into gameplay and keeps running | Planned |
| **Fidelity** | draws its 3D scenes as the console does | Planned |
| **Playable** | is playable start to finish on every supported Mac | Planned |
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
[docs/roadmap.md](docs/roadmap.md) is the single authoritative roadmap, with each gate's exact wording. [docs/process/working-method.md](docs/process/working-method.md) explains how runs are made and recorded.
---
## Architecture
## How it works
Rosetta 2 executes x86-64 CPU code (including AVX/AVX2/FMA/F16C/BMI1/BMI2/128-bit VAES when launched with `ROSETTA_ADVERTISE_AVX=1`), CrossOver/Wine provides Win32/NT/CRT/XAudio2/WinHTTP, and D3DMetal 3.0 translates Direct3D 12 + DXR onto Metal. BetterXen supplies the modular Xbox Game OS shims, `clwb` exception handling, shader bridge, and ARM64 orchestration around that stack.
Rosetta 2 executes the build's x86-64 code. CrossOver/Wine provides Win32. D3DMetal 3.0 translates Direct3D 12 to Metal. BetterXen supplies what is missing between an Xbox title and that stack:
- **Xbox Game OS shims** (`shims/`): x86-64 Windows DLLs, cross-compiled on macOS, that implement the Xbox runtime the title imports: memory, DirectStorage, the Xbox flavour of Direct3D 12, the GDK runtime, input and audio.
- **A shader translator** (`shader-transpiler/`): console shaders are AMD RDNA 2 machine code. The translator turns them into HLSL, one rule per instruction, and the Direct3D shim compiles and caches the result.
- **A native launcher** (`launcher/`): `bx-cli` checks the host, runs a program in an isolated CrossOver environment, and turns the shims' logs into a run report.
```mermaid
flowchart TD
Guest["Scarlett x86-64 PE32+ Executable"]
Guest["Xbox Series title (x86-64 PE32+)"]
subgraph Shims["BetterXen x86-64 Wine Shims (Cross-Compiled on macOS)"]
VEH["bx_runtime_veh.dll (clwb VEH trap, JSONL trace, Lockhart cap)"]
XMem["xmem.dll (Physical/Virtual/Scatter Allocator)"]
DS["XCRDAPI.dll (DirectStorage Async I/O)"]
D3DX["d3d12_xs.dll + xg_xs.dll (Xbox D3D12 COM Proxy & RDNA2 Tiling)"]
XGR["xgameruntime.dll + GameInput.dll + Audio/DSP"]
Bridge["PSM AppNotify & ntuser Win32 Forwarders"]
subgraph Shims["BetterXen shims (x86-64 DLLs, built on macOS)"]
VEH["bx_runtime_veh.dll\ninstruction traps, logging, fault diagnostics"]
XMem["xmem.dll\nvirtual and physical page mapping"]
DS["XCRDAPI.dll\nDirectStorage queues, zlib, BCPack"]
D3DX["d3d12_xs.dll\nXbox-layout D3D12 over the host's D3D12"]
XGR["xgameruntime.dll, GameInput.dll, audio DLLs"]
Bridge["bx_shader_bridge.dll (Rust)\nshader classifier and translator"]
end
subgraph Shaders["Shader & DXR Bridge"]
DXIL["DXIL Fast Path (SM 6.5/6.6)"]
ACCC["ACCC / FSPX RDNA2 Transpiler"]
subgraph GDK["From the member's own GDK, staged at run time, never shipped"]
XG["xg_xs.dll (texture layouts)\nBCPack.dll"]
DXC["dxcompiler.dll (HLSL to DXIL)"]
end
subgraph External["External Foundation (User-Installed)"]
Wine["CrossOver 26.3 / Wine (Win32, CRT, XAudio2, WinHTTP)"]
Rosetta["Rosetta 2 (ROSETTA_ADVERTISE_AVX=1)"]
D3DM["D3DMetal 3.0 (D3D12 + DXR on Apple Silicon Metal)"]
subgraph External["External foundation (installed by the user)"]
Wine["CrossOver 26.3+ / Wine"]
Rosetta["Rosetta 2"]
D3DM["D3DMetal 3.0"]
end
CLI["bx-cli (Native ARM64 macOS Launcher, Probe & Telemetry)"]
CLI["bx-cli (native ARM64)\nsetup, preflight, run, report"]
Guest --> Shims
D3DX --> DXIL --> D3DM
D3DX --> ACCC --> D3DM
D3DX -->|"console shaders, at first draw"| Bridge
Bridge -->|"HLSL"| DXC
DXC -->|"DXIL, cached on disk"| D3DX
D3DX --> D3DM
D3DX --> XG
XMem --> Wine
DS --> Wine
XGR --> Wine
Bridge --> Wine
VEH --> Rosetta
Wine --> Rosetta
CLI -.->|"Launches, sets overrides, summarizes traces"| External
CLI -.->|"launches, isolates, stages, reports"| External
```
Design decisions are recorded as ADRs in [docs/adr/](docs/adr/): the CrossOver-based direction (0005), the shader format gate (0008), Xbox-layout Direct3D objects (0009), and using the GDK's own texture libraries and compiler at run time (0010).
---
## Repository Layout
## Repository layout
The repository is organized into disjoint track directories around a single frozen `abi/` contract so **5–8+ contributors (and coding agents)** can work concurrently with minimal merge conflicts.
Work is split into tracks with their own directories, around one frozen `abi/` contract, so several contributors and coding agents can work at once ([docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md)).
| 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 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)) |
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Track E | C++20 (`x86_64` PE) | Offline GDK runtime (`xgameruntime.dll`), `GameInput.dll` (`@1`), and `AcpHal.dll`/`xapu.dll`/`chad.dll` |
| [`tests/conformance/`](tests/conformance/README.md) | Track F | C++20 (`x86_64` PE) | Auto-discovered clean-room synthetic PE32+ test binaries (`test_*/CMakeLists.txt`) |
| [`abi/`](abi/README.md) | ABI gate | C headers, `.def` | Cross-DLL headers and the canonical export table of every shim DLL (17 DLLs, 118 exports) |
| `launcher/` | A | Rust (`arm64`) | `bx-cli`, `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/`, `shims/win32_bridge/` | A | C++20 (x86-64 PE) | `bx_runtime_veh.dll` (traps for instructions Rosetta 2 lacks, structured logging, fault diagnostics) and API-set forwarders ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/`, `shims/xcrdapi/` | B | C++20 (x86-64 PE) | `xmem.dll` (Xbox memory APIs, physical page mapping) and `XCRDAPI.dll` (DirectStorage) |
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | C | C++20 (x86-64 PE) | The Xbox-layout Direct3D 12 layer, `PresentX`, console pipelines translated at first draw, title-memory resources, and the texture-layout shim |
| `shader-transpiler/` | D | Rust | `gfx10-translate` (RDNA 2 decoder and translator to HLSL), `dxbc-accc` (container classifier; built for Windows as `bx_shader_bridge.dll`), `d3dmetal-harness` |
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | E | C++20 (x86-64 PE) | Offline GDK runtime, `GameInput.dll`, and `AcpHal.dll` / `xapu.dll` / `chad.dll` |
| [`tests/conformance/`](tests/conformance/README.md), `docs/` | F | C++20 (x86-64 PE), Markdown | 54 synthetic test programs, auto-discovered from `test_*/CMakeLists.txt`, and the documentation |
---
## Quick Start
## Quick start
### Requirements
### Building and running the synthetic tests
- **Apple Silicon Mac** running native ARM64 macOS with **Rosetta 2** and **CrossOver 26.3+** (external install).
- **Rust toolchain** (`aarch64-apple-darwin`, Rust 1.85+ / 1.100.0).
- **`mingw-w64` & `cmake`** (`brew install mingw-w64 cmake`) for cross-compiling x86-64 Windows PE32+ shims on macOS.
- **Python 3.11+** for export verification and repository hygiene checks.
This needs no game and no GDK:
### Build & Verify
- an **Apple Silicon Mac** with **Rosetta 2** and **CrossOver 26.3+** (licensed separately);
- **Rust** 1.85 or later, **Python** 3.11 or later;
- `brew install mingw-w64 cmake`.
```sh
git clone https://github.com/MacosPorters/betterxen.git
cd betterxen
# 1. Build & test the native ARM64 Rust workspace (launcher + shader-transpiler)
# 1. The native ARM64 Rust workspace (launcher and shader translator)
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo build -p bx-cli
cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
cargo build --locked -p bx-cli
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
# 2. Host readiness: Apple Silicon, Rosetta 2, CrossOver, D3DMetal, mingw-w64
target/debug/bx-cli doctor
# 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)
# 3. Cross-compile the 16 C++ shim DLLs, build the Rust bx_shader_bridge.dll and the
# conformance programs; verifies every export of all 17 DLLs against abi/defs/*.def
scripts/build-shims.sh
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
# 4. Two synthetic tests inside CrossOver and Rosetta 2
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
target/debug/bx-cli trace /tmp/bx-test.jsonl
# 5. Check Markdown links & repository hygiene
# 5. Markdown links and repository hygiene
python3 scripts/audit/docs_hygiene.py
```
### `bx-cli` Commands
The graphics tests need a CrossOver bottle with D3DMetal (`--bottle <name> --backend d3dmetal`); in a plain prefix they skip.
### Working on the project
Contributing needs three more things, and they are a **hard requirement**: the **project-authorized target build**, the **GDK** under the project's authorization, and the **Ghidra results** of the target build. They are distributed among members only. Nothing from them (files, names, hashes, paths, bytes) is ever committed or posted.
```sh
target/debug/bx-cli setup --find # finds the build, the GDK and the Ghidra results on this machine
target/debug/bx-cli preflight # must print: Ready to work.
```
Then point a coding agent at the repository and say **"work"**, or follow the same steps by hand. [CONTRIBUTING.md](CONTRIBUTING.md) explains what you need and how work is organised; [AGENTS.md](AGENTS.md) (also `CLAUDE.md`) holds the full rules, including how one item is picked, claimed with a draft pull request, tested and proven.
### `bx-cli` commands
| Command | Purpose |
| --- | --- |
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
| `bx-cli doctor` | Inspects the host: chip, memory, Rosetta 2, CrossOver, D3DMetal, `mingw-w64` |
| `bx-cli setup [--find]` | Remembers where the target build, the GDK and the Ghidra results are on this machine, outside the repository |
| `bx-cli preflight` | Checks everything work needs; fails if anything is missing |
| `bx-cli run --exe <path> ...` | Runs a program under CrossOver with a cleared environment, the shim overrides and a JSONL log. For the target build it stages the GDK's libraries beside the shims |
| `bx-cli report <log.jsonl>...` | One run report per log, then a summary with blocker signatures |
| `bx-cli trace <log.jsonl>` | Summarises a log: unimplemented calls, trapped instructions, shader-gate decisions |
| `bx-cli probe <pe32+>` | Classifies a program's imports by track |
| `bx-cli shader <blob>` | Classifies a shader container (DXIL, legacy, or console code) |
| `bx-cli shader translate <vs> <ps> --out <dir> [--root <layout>]` | Translates a console vertex/pixel pair to HLSL |
| `bx-cli shader coverage <dir>` | Counts how many shaders in a folder translate and ranks what blocks the rest |
---
## Contributing with Humans & Coding Agents
## What is verified, and what is not
BetterXen is built for **parallel work across 5–8+ contributors and coding agents** (`AGENTS.md` — symlinked as `CLAUDE.md` — holds the full ruleset):
**Verified by tests in this repository** (synthetic programs of the project's own, on Apple Silicon with CrossOver 26.3 and Rosetta 2):
1. **Pick a track & claim an issue** from [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md) (or GitHub Issues using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` before coding.
2. **Isolate your branch or worktree:** `git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main`.
3. **Stay inside your issue's exclusive file scope:** Never edit another track's directory inside a feature PR. Need a new cross-DLL helper? Open a small `[ABI]` PR touching only `abi/` first.
4. **Add a conflict-free conformance test:** Drop `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories with zero edits to shared files.
5. **Run the verification commands above**, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, sign off commits (DCO `Signed-off-by`), and open a PR with `Closes #<issue>`.
- All 17 shim DLLs build, and their export tables match `abi/defs/*.def` exactly (118 exports, no extras, no MinGW runtime dependency).
- 54 conformance programs cover the shims' contracts: memory mapping, DirectStorage, the Xbox-layout Direct3D objects, `PresentX`, rectangle lists, console formats, the shader gate, and console pipelines translated at first draw.
- The translator's output matches a reference translator on its golden pairs, and its instruction decoder matches LLVM's on its test vectors.
See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md), and [docs/README.md](docs/README.md).
A conformance test shows that a shim matches the contract the project recorded. It does not show that the recorded contract is what a console does.
**Observed on the target build, on members' machines** (recorded in pull requests and issues, not reproducible without the build): the states in "Where it stands" above.
**Not claimed:**
- Nothing is verified on Xbox hardware. The project has none.
- No commercial game is supported or playable.
- Translated shaders are not checked against console output yet; most have never been drawn.
- Performance has not been measured.
Evidence classes are defined in [docs/claims.toml](docs/claims.toml).
---
## Current Verified Scope & Limitations
## Provenance and legal boundaries
- **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 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 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.
- `xg_xs.dll` RDNA 2 texture tiling/deswizzling and DXR/BVH4 rehydration interception.
- Console `ACCC`/`FSPX` RDNA 2 → DXIL/MSL shader transpilation (gated on M2).
- Real software audio/DSP decoding behind `AcpHal`/`xapu`/`chad` and full `GameInput` polling.
- Commercial Xbox game execution.
> [!CAUTION]
> BetterXen opposes piracy. The repository contains no game files, firmware, keys, DRM circumvention, GDK files or compiler outputs, and none may be added to it or to its history.
- Contracts that have no public documentation are established from the authorized GDK, from the project-authorized target build (call sites and run-time diagnostics), and from compilers run on the project's own shaders. Each implemented contract gets a synthetic conformance test.
- The GDK's own libraries (`xg_xs.dll`, `BCPack.dll`, `dxcompiler.dll`) are loaded at run time from each member's GDK. They are not reimplemented, committed or shipped ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)).
- See [docs/legal.md](docs/legal.md), [docs/licenses.md](docs/licenses.md) and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
---
## Historical Native-First Research
## History
The earlier paused native-first implementation (independent x86-64 interpreter/ARM64 DBT, bounded `gfx1030` RDNA 2 → MSL translator, native Metal backend, and Swift app) was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently in Git history at tag `native-first-final`.
The earlier native-first implementation (an x86-64 interpreter and ARM64 translator, a native Metal backend and a Swift app) was retired from `main` by [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md). It is preserved at the Git tag `native-first-final`.
---
## License
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [docs/legal.md](docs/legal.md) for attribution and legal scope.
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, or any game publisher.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, AMD or any game publisher.
+3
View File
@@ -3,3 +3,6 @@ EXPORTS
bx_shader_inspect
bx_shader_prepare_for_d3dmetal
bx_shader_free_buffer
bx_shader_translate_pair
bx_shader_free_pair_translation
bx_shader_translate_pair_rooted
+2
View File
@@ -17,3 +17,5 @@ EXPORTS
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
+114
View File
@@ -76,6 +76,120 @@ bx_shader_status_t bx_shader_prepare_for_d3dmetal(
void bx_shader_free_buffer(uint8_t* ptr, size_t len);
/*
* Translation of a console graphics pipeline's vertex and pixel shader to HLSL (#720).
*
* The inputs are the two stages as the title hands them to a pipeline: RDNA 2 code in the
* console's shader container, or the bare code. d3d12_xs calls this when such a pipeline is
* first drawn and compiles the HLSL with a DXC library (entry point `main`, profiles `vs_6_0`
* and `ps_6_0`). The two keys identify the pair, in logs and wherever a caller wants a name for
* it (`<vs_key>_<ps_key>`, 16 lower-case hex digits each). How compiled shaders are cached is the
* caller's business: d3d12_xs names them by a hash of the HLSL, so that a change of the
* translator can never reuse an old result.
*
* All text is UTF-8 without a terminator. A buffer that is not NULL belongs to the caller, who
* frees it with bx_shader_free_buffer(ptr, len); bx_shader_free_pair_translation frees all of
* them and clears the structure.
*/
typedef struct bx_shader_pair_translation {
/* 64-bit FNV-1a (offset basis 0xcbf29ce484222325, prime 0x100000001b3) of each input, as
passed. Set whenever both inputs are readable, also when translation is refused. */
uint64_t vs_key;
uint64_t ps_key;
/* On BX_SHADER_OK: the two HLSL sources. */
uint8_t* vs_hlsl;
size_t vs_hlsl_len;
uint8_t* ps_hlsl;
size_t ps_hlsl_len;
/*
* On BX_SHADER_OK: what the host pipeline needs, one line each, '\n' after every line:
* FETCH <n> the vertex shader reads its n attributes through the
* console vertex-fetch call; the host input layout is
* the pipeline's own, with semantics ATTR0..ATTR<n-1>
* ATTR <semantic index> <DXGI_FORMAT> <slot> <byte offset>
* an input element (semantic name ATTR) the vertex
* shader loads itself from vertex buffer <slot>
* USE CB <entry> a constant buffer: entry <entry> of root parameter
* USE CB <root parameter> <entry> 0's descriptor table (two numbers: of that root
* USE TEX <entry> parameter's), declared as register b<entry> or
* USE TEX <root parameter> <entry> t<entry> in space 100 + <root parameter>
* Unknown lines must be ignored by the caller, so lines can be added.
*/
uint8_t* layout;
size_t layout_len;
/* On BX_SHADER_ERR_UNSUPPORTED: one line saying what the translator does not model yet. */
uint8_t* reason;
size_t reason_len;
} bx_shader_pair_translation_t;
/*
* BX_SHADER_OK: translated. BX_SHADER_ERR_UNSUPPORTED: an input uses something not modelled
* (`reason` says what); the pipeline then stays untranslated. BX_SHADER_ERR_INVALID_BLOB: a NULL
* or empty input, a NULL `out`, or an input in a `DXBC` container that holds no console code.
* Bare code has no magic to check: bytes that are not shader code are decoded as code and come
* back BX_SHADER_ERR_UNSUPPORTED (an unknown or unmodelled instruction), not invalid.
* BX_SHADER_ERR_TRANSLATE: an internal failure. `*out` is cleared first in every case.
* Thread-safe; holds no state between calls.
*/
bx_shader_status_t bx_shader_translate_pair(
const uint8_t* vs_bytes,
size_t vs_len,
const uint8_t* ps_bytes,
size_t ps_len,
bx_shader_pair_translation_t* out
);
void bx_shader_free_pair_translation(bx_shader_pair_translation_t* translation);
/*
* The same translation, given the layout of the pipeline's root signature (#715).
*
* A console shader receives its root arguments as packed 32-bit values in root-parameter order:
* a descriptor-table parameter is one value (a 32-bit table pointer), a root CBV, SRV or UAV two
* (a 64-bit address, low half first), a constants parameter one per constant. Value d is in
* user-data register s(8 + d) of a vertex or pixel shader, or, when the root signature has
* D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI, at byte 4 * d of root data the shader
* reads from memory (docs/research/console-shader-abi.md). Which parameter a shader reads
* therefore depends on the parameters before it, and bx_shader_translate_pair, which is not told
* them, treats every parameter as a table.
*
* With a layout:
* - a descriptor table is translated as before: entry k of root parameter i is register k of
* space 100 + i, and is named in a `USE CB` / `USE TEX` layout line;
* - a root CBV, SRV or UAV is declared at the title's own register and space, as given here
* (b, t or u), so the root signature needs no change for it;
* - a constants parameter is declared as a constant buffer at its own register and space;
* - each root parameter of the last two kinds that a shader reads adds one layout line,
* `USE ROOT <root parameter>`.
*/
typedef struct bx_shader_root_parameter {
uint32_t type; /* D3D12_ROOT_PARAMETER_TYPE: 0 table, 1 constants, 2 CBV, 3 SRV, 4 UAV */
uint32_t num_32bit_values; /* constants: how many; otherwise 0 */
uint32_t shader_register; /* constants and root descriptors: the register; tables: 0 */
uint32_t register_space; /* constants and root descriptors: the space; tables: 0 */
} bx_shader_root_parameter_t;
typedef struct bx_shader_root_layout {
const bx_shader_root_parameter_t* parameters; /* in root-parameter order */
uint32_t parameter_count;
uint32_t flags; /* the root signature's D3D12_ROOT_SIGNATURE_FLAGS, Xbox bits included */
} bx_shader_root_layout_t;
/*
* As bx_shader_translate_pair, with `layout` describing the pipeline's root signature. A NULL
* `layout` gives exactly bx_shader_translate_pair. BX_SHADER_ERR_INVALID_BLOB also covers a
* layout whose `parameters` is NULL with a non-zero count, or a parameter of an unknown type.
* A shader that reads root data the layout does not account for is BX_SHADER_ERR_UNSUPPORTED.
*/
bx_shader_status_t bx_shader_translate_pair_rooted(
const uint8_t* vs_bytes,
size_t vs_len,
const uint8_t* ps_bytes,
size_t ps_len,
const bx_shader_root_layout_t* layout,
bx_shader_pair_translation_t* out
);
#ifdef __cplusplus
}
#endif
+12
View File
@@ -51,6 +51,18 @@ int bx_xmem_try_charge_external(uint64_t bytes);
* 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
+3 -1
View File
@@ -5,7 +5,7 @@
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
- [Parallel Track Architecture](architecture/parallel-tracks.md) — Which track owns which directories, and how the tracks stay apart (one blocker per pull request, ABI first, self-contained tests). The rules themselves are in `AGENTS.md`.
- [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/`).
- [Synthetic Conformance Suite](../tests/conformance/README.md) — Auto-discovered PE32+ conformance binaries.
@@ -17,6 +17,7 @@
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
- [ADR 0010: The GDK's own 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`), and translated shaders are compiled with its PC `dxcompiler.dll`; all are staged by `bx-cli run` for the target build from each machine's GDK, and never reimplemented, committed or shipped.
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
## Research, Testing & Licensing
@@ -27,6 +28,7 @@
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
- [gfx10-translate](../shader-transpiler/crates/gfx10-translate/README.md) — BetterXen's GFX10.3 console shader translator: container reader, decoder with an LLVM-generated opcode table, HLSL translation ported from the Python prototype, coverage over local shaders, and how to add an instruction.
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
+30
View File
@@ -0,0 +1,30 @@
# ADR 0010: The GDK's own libraries at run time (textures and the shader compiler)
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. **The shader compiler is open-source DXC, with the GDK as fallback** (added 2026-11-30, #720; revised #757). `d3d12_xs` compiles the HLSL of translated console shaders with `dxcompiler.dll`. Because Microsoft's prebuilt DXC release zip carries closed-source licence terms (`LICENSE-MS.txt`) and the GDK's `dxcompiler.dll` cannot be redistributed, BetterXen builds `dxcompiler.dll` (x64 Release) from the open-source `microsoft/DirectXShaderCompiler` repository (pinned tag `v1.9.2609`) via `.github/workflows/dxc-build.yml`. `bx-cli run` stages `dxcompiler.dll` from the configured open-source DXC folder (`bx-cli setup --dxc-dir <dir>` / `BX_DXC_DIR`) first, falling back to the GDK's PC `dxcompiler.dll` only when no open-source build is configured. `dxcompiler.dll` is recognised by name and export (`DxcCreateInstance`), never committed to the repository, and `dxil.dll` is not needed (`dxcompiler.dll` alone validates and signs DXIL).
6. **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.
+32 -37
View File
@@ -1,46 +1,41 @@
# Parallel Track Architecture & Contributor Handoff Guide
# Parallel Track Architecture
BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-based Apple Silicon compatibility stack concurrently via Git and GitHub Issues without merge conflicts.
BetterXen is organized so several contributors and coding agents can work at the same time without merge conflicts: the code is split into tracks, each with its own directories, around one frozen `abi/` contract.
## Repository Layout
This page describes the layout. The rules themselves are in [AGENTS.md](../../AGENTS.md) (Sections 0, 2 and 7), and [docs/process/working-method.md](../process/working-method.md) explains the method behind them. Where this page and those disagree, they are right.
| Directory | Track | Language / Build | Purpose |
## Tracks and directories
| Directory | Track | Language / build | Purpose |
| --- | --- | --- | --- |
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
| `shims/xg_xs/` | Track C2 | C++20 (`mingw-w64`) | `xg_xs.dll`: RDNA 2 texture tile addressing & swizzle layout computer |
| `shims/ffx_bvh_hooks/` | Track C3 | C++20 (`mingw-w64`) | Optional PC FidelityFX/MetalFX upscaler shim & BVH4 rehydration → DXR live rebuild bridge |
| `shader-transpiler/` | Track D | Rust (`aarch64` / C ABI) | `DXBC`/`DXIL`/`ACCC`/`FSPX` shader classifier, RDNA 2 → DXIL/MSL transpiler (M2 gate), shader cache, `d3dmetal-native` harness |
| `shims/xgameruntime/` | Track E1 | C++20 (`mingw-w64`) | `xgameruntime.dll`: offline GDK runtime (`XTaskQueue`, `XAsync`, `XUser`, `XStore`, `XSystem`, `XPersistentLocalStorage`) |
| `shims/gameinput/`, `shims/audio/` | Track E2 | C++20 (`mingw-w64`) | `GameInput.dll` ordinal 1 adapter + `AcpHal.dll`, `xapu.dll`, `chad.dll` audio/DSP shims |
| `tests/conformance/` | Track F | C++20 (`mingw-w64`) | Clean-room synthetic PE32+ test executables verifying each shim under CrossOver/Wine |
| `abi/` | ABI gate | C headers, `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and the canonical export list of every shim DLL |
| `launcher/` | A | Rust (`aarch64-apple-darwin`) | `bx-cli` (setup, preflight, run, report), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
| `shims/runtime_veh/` | A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: traps for instructions Rosetta 2 lacks, structured logging, fault diagnostics, the retry for faults on pages being remapped |
| `shims/win32_bridge/` | A | C++20 (`mingw-w64`) | PSM AppNotify stubs and `ext-ms-win-rtcore-ntuser-*` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
| `shims/xmem/` | B | C++20 (`mingw-w64`) | `xmem.dll`: Xbox virtual and physical memory APIs, physical page mapping, the Lockhart memory budget |
| `shims/xcrdapi/` | B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage factory, queues, zlib and BCPack requests |
| `shims/d3d12_xs/` | C | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox-layout Direct3D 12 objects over the host's Direct3D 12 ([ADR 0009](../adr/0009-xbox-layout-d3d12-objects.md)), `PresentX`, resources in title memory, console pipelines translated at first draw |
| `shims/xg_xs/` | C | C++20 (`mingw-w64`) | `xg_xs.dll`: BetterXen's texture-layout shim. For the target build `bx-cli run` stages the GDK's own library in its place ([ADR 0010](../adr/0010-gdk-texture-libraries.md)) |
| `shims/ffx_bvh_hooks/` | C | C++20 (`mingw-w64`) | Reserved for upscaler and BVH work |
| `shader-transpiler/` | D | Rust | `gfx10-translate` (RDNA 2 decoder and translator to HLSL), `dxbc-accc` (container classifier and the C interface, built for Windows as `bx_shader_bridge.dll`), `d3dmetal-harness` |
| `shims/xgameruntime/` | E | C++20 (`mingw-w64`) | `xgameruntime.dll`: offline GDK runtime (task queues, async, users, saves, packages) |
| `shims/gameinput/`, `shims/audio/` | E | C++20 (`mingw-w64`) | `GameInput.dll`, and `AcpHal.dll`, `xapu.dll`, `chad.dll` |
| `tests/conformance/`, `docs/` | F | C++20 (`mingw-w64`), Markdown | Synthetic test programs, one folder each (`test_<name>/`), discovered automatically; documentation |
*(The earlier native-first research workspace was retired from `main` per [ADR 0006](../adr/0006-retire-in-tree-native-workspace.md) and remains permanently accessible at Git tag `native-first-final`.)*
The earlier native-first workspace was retired from `main` by [ADR 0006](../adr/0006-retire-in-tree-native-workspace.md) and is preserved at the Git tag `native-first-final`.
## Milestones (M0 → M6)
## How the tracks stay apart
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 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.
6. **M5 — Real Audio, Saves & Stability:** Software audio/DSP decoding behind `AcpHal`/`xapu`/`chad`, `PersistentLocalStorage` saves, multi-hour soak testing.
7. **M6 — Shader Cache, 16 GB Optimization & Polish:** Persistent disk PSO/shader cache, Lockhart 16 GB unified memory tuning, Metal System Trace optimization, Swift launcher UI.
- **One blocker, one pull request.** Work is found by running the target build and taking the first thing it stops on. A draft pull request titled with the blocker's signature is the claim; open pull requests are checked first, and a pull request that already covers the problem is worked on, not duplicated.
- **Stay in the track's directories.** A fix touches only the directories its blocker needs. Maintainer-directed startup and compatibility work may cross tracks, without overlapping anyone's open claim.
- **ABI first.** A new cross-DLL helper or export starts as a small `[ABI]` pull request that touches only `abi/`, so the provider and the consumer can be written in parallel. The header carries the contract; the `.def` line arrives with the implementation, because the build verifies every export.
- **Tests never collide.** A conformance test is its own folder, `tests/conformance/test_<name>/` with a `CMakeLists.txt` and a `main.cpp`. Nothing shared is edited to add one.
- **Branches.** `track-<a..f>/<slug>` from `origin/main`, in the contributor's own worktree and their own CrossOver bottle.
## Zero-Conflict Git & Issue Protocol
## Stages, not milestones
- **ABI-first:** Any cross-track header or `.def` change lands first in a small `[ABI]` PR touching only `abi/`.
- **Branch naming:** `track-<a..f>/<issue>-<slug>` off `main`, squash-merged daily.
- **Exclusive file scope:** Every issue lists the exact directories it may edit (using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Never edit another track's folder in a feature PR.
- **Local verification:**
```sh
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
scripts/build-shims.sh
```
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests, and are history. Since then progress is measured in stages of what the target build does: Boot, Picture, Menus, World, Fidelity, Playable. [docs/roadmap.md](../roadmap.md) is the single authoritative roadmap and names the current stage.
## Verification before a pull request
The commands are in [AGENTS.md](../../AGENTS.md) Section 8: the Rust checks, `scripts/build-shims.sh` (which also verifies every DLL's exports), the live conformance tests under CrossOver, and the documentation check.
+12 -8
View File
@@ -2,7 +2,7 @@
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
BetterXen is built by collaborators who each have the project-authorized target build and the GDK, and who work by pointing a coding agent at this repository and saying **"work"**. This document answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
BetterXen is built by collaborators who each have the project-authorized target build, the GDK and the target build's Ghidra results, and who work by pointing a coding agent at this repository and saying **"work"**. This document answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
The short answer: run the build, fix the first thing it stops on, and open a pull request. The pull request is the unit of work. There are no meetings, no rotating roles and no backlog to interpret.
@@ -13,11 +13,14 @@ No agent works without all of these. `bx-cli preflight` checks them and fails if
- an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`;
- **the project-authorized target build**;
- **the GDK**, headers and compilers, under the project's authorization;
- **the Ghidra results of the target build**: the static-analysis run (`RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable;
- at least 10 GiB of free disk space.
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header and the target build by its structure (never by name), and saves both in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
The target build, the GDK and the Ghidra results are a hard requirement: an agent that lacks even one of them does not work on the repository at all.
Work here is found by running the build and checked against the GDK. Without them an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build or the GDK is not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header, the target build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
Work here is found by running the build, located in the Ghidra results and checked against the GDK. Without all three an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build, the GDK or the Ghidra results are not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
## Why this shape
@@ -82,11 +85,12 @@ run → signature → draft pull request (the claim) → evidence → smallest f
```
1. **Claim with a draft pull request.** Check open pull requests for the signature. If nobody has it, branch from `origin/main`, push, and open a draft titled `[<Stage>] <signature>`. A draft with no push for 3 days may be taken over.
2. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
3. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
4. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
5. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
6. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
2. **Is it already someone's?** Before investigating any problem the game shows (the picked blocker or one met along the way), search open and merged pull requests and open issues for its log event, stub symbol, error code and the files a fix would touch. If an open pull request covers it, check that branch out, run with it and work there. If a merged one does, sync and run again. On 2026-11-30 a session fixed physical-page DirectStorage requests in parallel with an open pull request for the same problem (#707), and found the overlap only afterwards.
3. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
4. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
5. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
6. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
7. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
If the blocker turns out to be more than you can finish, close the draft and file a handoff issue.
+1
View File
@@ -11,6 +11,7 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
| Direct3D 12 to Metal | D3DMetal | **Evaluate as external**, subject to license | Not in CodeWeavers' FOSS list; terms and availability to verify (#349, #354). Not redistributable until proven. |
| D3D12 on D3DMetal outside Wine (fault isolation) | utmapp/d3dmetal-native | **Adopt as external, opt-in test dependency** (#417) | MIT; built and run at `af1ee17` (see the registry's M1-D2 section). The user builds it; BetterXen copies none of it, and only the x86_64 probe links it. It forces an x86_64 process under Rosetta 2 because D3DMetal is x86_64-only. BetterXen's arm64 tools drive that process instead of loading the framework. Never use its D3DMetal binary patcher. |
| Shader compilation for BetterXen's own test kernels | DirectX Shader Compiler (official release) | **Use as external tool** (#417) | Run under CrossOver Wine because there is no macOS release. Only compiler output of BetterXen's own HLSL is committed, with version and hashes recorded. The package's Microsoft licence terms cover its closed-source parts, which are never redistributed. |
| Run-time HLSL compilation for translated console shaders (`dxcompiler.dll`) | DirectX Shader Compiler (source build at `v1.9.2609`) | **Build from source in CI and stage as external binary** (#757) | University of Illinois/NCSA Open Source License (`LICENSE.TXT`, permissive and GPL-3.0-compatible; per-file check recorded in `upstream-registry.md`). Built x64 Release by `.github/workflows/dxc-build.yml` and staged by `bx-cli run` via `--dxc-dir` / `BX_DXC_DIR` ahead of any GDK fallback. No binary is committed to `main`. |
| Direct3D 11/10 to Metal | DXMT | **Evaluate** as external binary or build | LGPL 2.1-or-later; usable as a separate process or library under LGPL terms; linking or copying needs legal review (#354). |
| Direct3D to Vulkan | DXVK | **Evaluate** only together with MoltenVK | zlib/libpng is permissive and GPL-compatible. Value on macOS unknown. |
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
+54 -1
View File
@@ -58,9 +58,62 @@ For each such load, the compiler also reported the instruction offset and the HL
- **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.
## Graphics stages: root data in registers (ACO path)
Recorded 2026-11-30, for the translator's root-signature layout (#715). Unlike the probes above, these six were compiled with `xdxc`, whose ACO back end produces the code that ACCC containers carry, and read with the project's own disassembler (`cargo run -p gfx10-translate --example listing`). Same host and GDK as above. Each probe is a `vs_6_6` vertex shader (one is `ps_6_6`) of the project's own with an explicit `[RootSignature]`; every declared parameter is used, so none is optimised away.
| Probe | Root signature | Where the shader reads each parameter |
| --- | --- | --- |
| g0 (VS) | `SRV(t0)` | address in `s8` (low), `s9` (high) |
| g1 (VS) | `RootConstants(1, b0), SRV(t0)` | constant `s8`; address `s9`, `s10` |
| g2 (VS) | `DescriptorTable(CBV(b0)), SRV(t0), RootConstants(2, b1), CBV(b2)` | table pointer `s8`; SRV address `s9`, `s10`; constants `s11`, `s12`; CBV address `s13`, `s14` |
| g3 (PS) | the same as g2 | the same registers as g2 |
| g4 (VS) | `SRV(t0, visibility = PIXEL), SRV(t1)` | `t1` address in `s10`, `s11` |
| g5 (VS) | `DescriptorTable(CBV(b0)), DescriptorTable(CBV(b1)), SRV(t0)` | table pointers `s8`, `s9`; address `s10`, `s11` |
**Measured:**
- **Start and order.** Root data starts at `s8` in a vertex and in a pixel shader, in root-parameter order (g2 and g3 agree register for register).
- **Sizes.** A descriptor-table parameter takes one SGPR, a root constant one per 32-bit value, a root SRV or CBV two (low dword first).
- **No alignment.** A 64-bit address directly follows an odd number of one-SGPR parameters (g1: `s9`, `s10`). This answers the "SGPR alignment" question below for this path.
- **Visibility does not renumber.** A parameter the stage cannot see still occupies its registers (g4).
- **Table pointers are 32-bit.** The shader copies the next register away if it needs it, writes 0 to it, and loads through the pair (g2: `s_mov_b32 s9, 0`, then `s_load_dwordx4 s[0:3], s[8:9]`). For a table that is not first, it builds the pair in other registers (g5: `s2 = s9`, `s3 = 0`).
- **Root buffers.** For a root SRV or CBV the shader builds the buffer descriptor itself: word 0 the low address, word 1 the high address OR the stride in bits 16 and up (`0x100000` for a 16-byte element), word 2 `-1`, word 3 `0x11014fac`. A structured-buffer read is `buffer_load_dwordx4 ..., idxen` with the element index; a root CBV is read with `s_buffer_load_dwordx4` at a byte offset.
**The memory-based form.** Two more probes set root flags that the target build's root signatures also set (the compiler accepts them as `RootFlags(XBOX_FORCE_MEMORY_BASED_ABI)` and `XBOX_FORCE_COMPUTE_2_SPILL_AREA`):
| Probe | Root signature | Where the shader reads each parameter |
| --- | --- | --- |
| g6 (VS) | `RootFlags(XBOX_FORCE_MEMORY_BASED_ABI), SRV(t0)` | two dwords loaded from offset 0 of the root data in memory |
| g7 (VS) | both flags, then the parameters of g2 | table pointer at offset 0; SRV address at 4; constants at 0xC and 0x10; CBV address at 0x14 |
- The shader forms the address of the root data from `s0` (low dword) and the low 8 bits of `s1` (`s_and_b32 s3, s1, 0xff`), and reads every parameter from there with `s_load_dword` / `s_load_dwordx2`. No root data is read from `s8` and up.
- The offsets are four bytes per root dword, in the same packed parameter order as the registers: a parameter that would be in `s(8 + d)` is at byte `4 * d`.
- `s0:s1` as the address of the root data matches the overflow case seen on the other compiler path (p10 above).
**Inferred:** the layout is a function of the root parameter list alone: each parameter has a root dword index, read from `s(8 + d)` or, in the memory-based form, from byte `4 * d` of the root data. A translator that is given the list (type and number of 32-bit values per parameter) can tell which parameter a shader reads. Not probed: root UAVs in graphics stages, more root data than fits in registers without the flag, what the upper bits of `s1` hold, and the other graphics stages.
## Directly indexed descriptor heaps (SM 6.6, ACO path)
Recorded 2026-11-30, from pixel shaders of the target build that index the sampler heap. Their root signature has the flag `0x800`, `D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED`, and their code reads a register past the root data. Probes of the project's own, compiled with `xdxc -T ps_6_6` and read with `cargo run -p gfx10-translate --example listing`:
| Probe | Root signature | What the code reads |
| --- | --- | --- |
| s0 | `DescriptorTable(SRV(t0)), RootConstants(2, b0), DescriptorTable(Sampler(s0, numDescriptors=8))` | texture descriptor from the SRV table `s8`; sampler `samplers[idx]` from the sampler table `s11`, at `idx << 4` (`idx` = constant `s9`) |
| s2 | `RootFlags(SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t2, space=1)), RootConstants(2, b500)` | texture descriptor from the table `s8`; `SamplerDescriptorHeap[idx]` from `s11`, at `idx << 4` |
| s3 | `RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED \| SAMPLER_HEAP_DIRECTLY_INDEXED), RootConstants(2, b500)` | `ResourceDescriptorHeap[other]` from `s10` at `other << 5`; `SamplerDescriptorHeap[idx]` from `s11` at `idx << 4`; `m0` from `s12` |
**Measured:**
- **Heap pointers follow the root data**, one register each: the resource heap (`CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED`, `0x400`) first, then the sampler heap (`SAMPLER_HEAP_DIRECTLY_INDEXED`, `0x800`). With the root data of s2 (`s8`, `s9`, `s10`) the sampler heap is `s11`; with that of s3 (`s8`, `s9`) the resource heap is `s10` and the sampler heap `s11`. A pixel shader's `m0` value follows them (`s12` in s3).
- They are **32-bit pointers**, like table pointers: the shader writes 0 to the next register and loads through the pair (`s_mov_b32 s11, 0` then `s_load_dwordx8 s[0:7], s[10:11], s0`), or copies the pointer away first (`s14 = s11`, `s15 = 0`).
- **Strides:** a resource descriptor is 32 bytes (`s_lshl_b32 s0, s9, 5`, then `s_load_dwordx8`), a sampler descriptor 16 bytes (`s_lshl_b32 ..., 4`, then `s_load_dwordx4`), the same sizes as table entries.
- The target build's shaders with this flag have exactly s2's code at their start (the sampler from `s11` at a root constant times 16), so this is the form ACCC containers carry for `SamplerDescriptorHeap[i]`.
- With a sampler table instead of the flag (s0), the code is the same; only what `s11` points at differs.
**Not probed:** the memory-based form with these flags, vertex shaders, compute (where root data starts at `s4`), and whether a heap pointer can be absent from user data when a stage does not index that heap.
## Open
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
- **Graphics stages:** root data is probed above; vertex and pixel inputs and exports are not.
- **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.
+20
View File
@@ -127,6 +127,26 @@ for a recording recipe. Through `bx-cli run` the guest status is returned unchan
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
+3 -1
View File
@@ -14,6 +14,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
| VIctory | [Marvisak/VIctory](https://github.com/Marvisak/VIctory) | `13f91caee25f` | GPL-3.0 (GitHub); a prior local review found per-file notices (see `experiments/victory-native/licenses.md`, local, untracked) | Discovery reference only | Described as an attempt at running one commercial game on PC. Its inputs are an Xbox Series build of that game. PortWatch describes the efforts it tracks as targeting a "leaked Xbox Series build". |
| VIctory-macOS | [pragyaangaur/VIctory-macOS](https://github.com/pragyaangaur/VIctory-macOS) | `485b230ef596` | GPL-3.0 (GitHub) | Discovery reference only | A macOS port of VIctory using Rosetta, CrossOver Wine and D3DMetal per its README (also noted in retired `portwatch-native-macos.md` at tag `native-first-final`). Same input concern. Its test and "works" claims are self-reported and not verified here. The repository has no parent fork, so the "canonical upstream" is VIctory. |
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
| LLVM (AMDGPU target) | [llvm/llvm-project](https://github.com/llvm/llvm-project) | Homebrew LLVM 23.1.6 (`llvm-mc`) | Apache-2.0 WITH LLVM-exception | Source of the generated GFX10.3 opcode table and decoder test vectors (`shader-transpiler/crates/gfx10-translate`) | Run locally by `scripts/console-shader/gen_opcodes.py` and `gen_llvm_vectors.py`. Only facts are committed (opcode number to mnemonic, instruction words to text); no LLVM code or tables are copied. Accepted by the repository owner on 2026-11-30 (AGENTS.md Section 4). |
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
## Built and run for M1-D2 (#417)
@@ -24,7 +25,8 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
| --- | --- | --- | --- | --- | --- |
| d3dmetal-native | [utmapp/d3dmetal-native](https://github.com/utmapp/d3dmetal-native) | `af1ee1710711fadff41dead87960d0f1336c1047` (2026-10-26) | Repository `LICENSE`: MIT, © 2026 Turing Software LLC. 34 of 37 `src/` files and the public header carry `SPDX-License-Identifier: MIT`. `src/dmn_dxil_reflect.{cpp,h}`, `src/exports.symbols`, `scripts/` and about half of `tests/` have no per-file notice, so only the repository `LICENSE` covers them. `include/native/` holds WIDL-generated MinGW-w64/Wine headers under LGPL-2.1-or-later (`include/native/directx/README.md`, `COPYING.MinGW-w64.txt`). | External, opt-in, built by the user. It hosts a user-supplied `D3DMetal.framework` outside Wine for the M1-D2 harness. No source is copied into BetterXen. | It builds only as x86_64, because `meson.build` rejects other targets and D3DMetal is x86_64-only. Consumers must therefore be x86_64 processes under Rosetta 2. It loads the framework from an explicit path, `$D3DMETAL_FRAMEWORK_PATH`, or locations next to the dylib. Its optional `scripts/patch_d3dmetal_imports.py` rewrites the D3DMetal binary for App Store builds; BetterXen must not use it, and the harness works with an unpatched framework. Against CrossOver 26.3's D3DMetal 3.0, its `dmn-smoke` and `dmn-device-test` passed, while `d3d12-atomic64-test` read back zeros (not diagnosed). |
| 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)`. |
| 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 prebuilt zip 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)`. |
| DirectX Shader Compiler (source build for `dxcompiler.dll`) | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/tree/v1.9.2609) | Tag `v1.9.2609` | Repository `LICENSE.TXT` is the University of Illinois/NCSA Open Source License (LLVM Release License), with third-party notices in `LICENSE.TXT` for `lib/Miniz/*` (MIT / Unlicense), `lib/Support/*` (Henry Spencer), and `include/llvm/Support/ConvertUTF.h` (Unicode). Source files inspected (e.g. `tools/clang/tools/dxcompiler/DXCompiler.cpp`) carry the University of Illinois Open Source License header. No `LICENSE-MS.txt` is present in the source tree. | Run-time HLSL compiler (`dxcompiler.dll`, x64 Release) built from source by `.github/workflows/dxc-build.yml` and staged by `bx-cli run` (#757). | Built from source on Windows to avoid both the GDK's non-redistributable `dxcompiler.dll` and the prebuilt zip's `LICENSE-MS.txt`. `dxcompiler.dll` alone validates and signs DXIL (`dxil.dll` is not needed). |
## Interface facts for XGameSave and XPackage (#468, #492)
+7 -3
View File
@@ -53,8 +53,8 @@ Every gate below is measured the same way ([working method](process/working-meth
| Stage | The target build… | Exit gate | Status |
| --- | --- | --- | --- |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **In development** |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | Planned |
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **Left** (repository owner's decision, 2026-11-30; the gate was not run under the run protocol) |
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | **Current** (since 2026-11-30) |
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
@@ -82,10 +82,14 @@ Every gate below is measured the same way ([working method](process/working-meth
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.** Vendor a pinned copy of the authorized upstream GFX10-to-DXIL translator into `shader-transpiler/` (per-file licence check, upstream registry and reuse matrix entries, ADR 0008 amendment), and expose it through `bx_shader_bridge.dll`. BetterXen owns its copy and fixes it.
*State (2026-11-30): not done in this order.* The translator and its run-time path were built first, on the vertex and pixel shaders of the build's first screens, which need none of these capabilities. The checks still come before compute shaders (64-lane behaviour, 64-bit atomics) and before anything that indexes descriptor heaps directly.
2. **The translator.** BetterXen writes its own translator in `shader-transpiler/` (`gfx10-translate`) and exposes it through `bx_shader_bridge.dll`; the upstream emulator's translator is not used (repository owner's decision, 2026-11-29). It turns GFX10 code into **HLSL**, not DXIL directly: `d3d12_xs` compiles the HLSL to DXIL with the GDK's PC `dxcompiler.dll` when a pipeline is first drawn, and keeps the result on disk ([ADR 0010](adr/0010-gdk-texture-libraries.md)). 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.
*How rules are checked today:* each rule has a test whose instruction words come from the public LLVM assembler and whose expected HLSL is written from the instruction's definition. Checking against the console compiler's output for a shader of our own (source rank 2) is the standard this item set; so far it has been done for the root-data layout ([docs/research/console-shader-abi.md](research/console-shader-abi.md)) and not rule by rule. The Python prototype on branch `experiment/visible-frame` is kept as a reference; the Rust translator matched its output on the pairs both translate.
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.
*State (2026-11-30):* vertex/pixel pipelines are translated at first draw (opt-in, `BX_CONSOLE_SHADERS=1`), and every one the build draws with in its first two minutes translates. Compute pipelines are not translated; their dispatches are skipped (#746).
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.
*State (2026-11-30):* descriptors the title copies itself are followed, and root signature layouts are passed to the translator. Open: texture contents (#745), and why the first screen shows only its background bars (#744). Two known simplifications: every translated shader samples with one fixed sampler (#750), and a descriptor table is widened for its first 8 entries only (#751).
### Menus to Playable — known work and unknowns
+3 -1
View File
@@ -94,7 +94,7 @@ sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null
# 3. Run the title inside the same profile. Every process it starts, including the new
# wineserver, inherits the sandbox.
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 \
BX_TRACE_D3D=0 BX_NULL_RENDER=1 BX_PRESENT_DUMP='Z:\<frames folder>' BX_INPUT_SCRIPT=A@40,A@50 \
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
@@ -116,6 +116,8 @@ All switches are off unless set, and none changes behaviour beyond what its row
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
| `BX_INPUT_SCRIPT=<presses>` | `GameInput` | Scripted gamepad presses for unattended runs, without window focus: comma-separated `BUTTON@SECONDS` (`A@40,DOWN@50.5,A@52`), each held 300 ms, timed from the first gamepad reading. Buttons `MENU VIEW A B X Y UP DOWN LEFT RIGHT`. Each press is logged (`input_script`), and so is each entry that cannot be read |
| `BX_CONTINUE_ASSERTS=1` | `bx_runtime_veh` | Steps over an `int3` in the title's own executable (a continuable assert) instead of letting it reach the title's crash reporter. Each address is logged once (`assert_continued`), so the report still lists every assert. Use it to get past a known assert to the next blocker, and say so in the evidence |
Their output can contain title addresses and file names, so it goes only into the private evidence store.
+1
View File
@@ -13,6 +13,7 @@ path = "src/main.rs"
bx-probe = { path = "../bx-probe" }
bx-telemetry = { path = "../bx-telemetry" }
dxbc-accc = { path = "../../../shader-transpiler/crates/dxbc-accc" }
gfx10-translate = { path = "../../../shader-transpiler/crates/gfx10-translate" }
# POSIX signals and process groups for `run` supervision.
libc = "=0.2.191"
+306
View File
@@ -0,0 +1,306 @@
//! Runtime texture and shader-compiler 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`.
//!
//! `d3d12_xs` compiles the HLSL of translated console shaders with `dxcompiler.dll` (#720, #757).
//! `dxcompiler.dll` is taken first from the configured BetterXen-built open-source DXC folder
//! (`--dxc-dir` / `BX_DXC_DIR`), falling back to the GDK's PC `dxcompiler.dll` only if no
//! open-source build is configured. It is recognised as an x86-64 PE32+ file named
//! `dxcompiler.dll` that exports `DxcCreateInstance`; `dxil.dll` is not needed.
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>,
/// The PC `dxcompiler.dll` (open-source DXC first, GDK fallback).
pub dxc: 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")
}
/// Whether `bytes` are a PC `dxcompiler.dll` (x86-64 PE32+ exporting `DxcCreateInstance`).
pub fn is_dxc(bytes: &[u8]) -> bool {
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"DxcCreateInstance\0")
}
/// Finds `dxcompiler.dll` under `dir` (bounded depth), recognised by name and `DxcCreateInstance`.
pub fn find_dxc(dir: &Path) -> Option<PathBuf> {
let mut dxc = Vec::new();
let mut stack = vec![(dir.to_path_buf(), 0usize)];
while let Some((cur, depth)) = stack.pop() {
let Ok(entries) = fs::read_dir(&cur) 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 != "dxcompiler.dll" {
continue;
}
if fs::read(&path).is_ok_and(|bytes| is_dxc(&bytes)) {
dxc.push(path);
}
}
}
dxc.sort();
dxc.into_iter().next()
}
/// Finds the 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 dxc = 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 !matches!(name.as_str(), "xg_xs.dll" | "bcpack.dll" | "dxcompiler.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);
} else if name == "dxcompiler.dll" && is_dxc(&bytes) {
dxc.push(path);
}
}
}
xg.sort();
bcpack.sort();
dxc.sort();
GdkLibraries {
xg: xg.into_iter().next(),
bcpack: bcpack.into_iter().next(),
dxc: dxc.into_iter().next(),
}
}
/// Resolves runtime libraries, preferring BetterXen-built open-source `dxcompiler.dll` under
/// `dxc_dir` and falling back to the GDK's `dxcompiler.dll` under `gdk_root` only if needed.
pub fn resolve(dxc_dir: Option<&Path>, gdk_root: Option<&Path>) -> GdkLibraries {
let mut libs = gdk_root.map(find).unwrap_or_default();
if let Some(dxc) = dxc_dir.and_then(find_dxc) {
libs.dxc = Some(dxc);
}
libs
}
/// Builds `out` as a copy of the shim folder's files with the runtime libraries added: the
/// GDK's `xg_xs.dll` replaces BetterXen's shim, `dxcompiler.dll` is staged beside it, 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"))?;
}
if let Some(dxc) = &libs.dxc {
fs::copy(dxc, out.join("dxcompiler.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")));
assert!(is_dxc(&pe(b"DxcCreateInstance\0DxcCreateInstance2\0")));
assert!(!is_dxc(&pe(b"DxcCreateInstance2\0")));
assert!(!is_dxc(b"DxcCreateInstance\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();
// The PC compiler; a console compiler has another name, and dxil.dll is not needed.
fs::write(gdk.join("a/dxcompiler.dll"), pe(b"DxcCreateInstance\0")).unwrap();
fs::write(gdk.join("a/dxil.dll"), pe(b"DxcCreateInstance\0dxil")).unwrap();
fs::write(gdk.join("c/dxcompiler_xs.dll"), pe(b"DxcCreateInstance\0")).unwrap();
let libs = find(&gdk);
assert_eq!(libs.dxc, Some(gdk.join("a/dxcompiler.dll")));
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");
assert_eq!(
fs::read(out.join("dxcompiler.dll")).unwrap(),
fs::read(gdk.join("a/dxcompiler.dll")).unwrap()
);
assert!(!out.join("dxil.dll").exists());
assert!(!out.join("dxcompiler_xs.dll").exists());
let _ = fs::remove_dir_all(&root);
}
#[test]
fn open_source_dxc_takes_precedence_over_gdk_fallback() {
let root = std::env::temp_dir().join(format!("bx-dxc-prec-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let gdk = root.join("gdk");
let dxc_dir = root.join("open-source-dxc");
let empty_dir = root.join("empty");
fs::create_dir_all(&gdk).unwrap();
fs::create_dir_all(&dxc_dir).unwrap();
fs::create_dir_all(&empty_dir).unwrap();
fs::write(
gdk.join("xg_xs.dll"),
pe(b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"),
)
.unwrap();
fs::write(gdk.join("dxcompiler.dll"), pe(b"DxcCreateInstance\0gdk")).unwrap();
fs::write(
dxc_dir.join("dxcompiler.dll"),
pe(b"DxcCreateInstance\0oss"),
)
.unwrap();
// A file without DxcCreateInstance is ignored.
fs::write(empty_dir.join("dxcompiler.dll"), pe(b"NotDxc\0")).unwrap();
// Open-source DXC wins over GDK fallback.
let libs = resolve(Some(&dxc_dir), Some(&gdk));
assert_eq!(libs.dxc, Some(dxc_dir.join("dxcompiler.dll")));
assert_eq!(libs.xg, Some(gdk.join("xg_xs.dll")));
// Without dxc_dir (or with an invalid one), GDK dxcompiler.dll is used as fallback.
let fallback = resolve(None, Some(&gdk));
assert_eq!(fallback.dxc, Some(gdk.join("dxcompiler.dll")));
let invalid_dxc = resolve(Some(&empty_dir), Some(&gdk));
assert_eq!(invalid_dxc.dxc, Some(gdk.join("dxcompiler.dll")));
// Open-source DXC works even without a GDK.
let oss_only = resolve(Some(&dxc_dir), None);
assert_eq!(oss_only.dxc, Some(dxc_dir.join("dxcompiler.dll")));
assert_eq!(oss_only.xg, None);
assert_eq!(oss_only.bcpack, None);
let _ = fs::remove_dir_all(&root);
}
}
+576 -31
View File
@@ -1,6 +1,7 @@
//! Track A (M1-A1): Native ARM64 macOS CLI for BetterXen hybrid execution.
mod drives;
mod gdk_libs;
mod stage;
mod supervise;
@@ -10,7 +11,7 @@ use std::fmt::Write as _;
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
use std::process::{Command, ExitCode, Stdio};
use std::time::{Duration, Instant};
use bx_probe::{ShimTrack, classify_dll, probe_pe32_plus};
@@ -26,6 +27,11 @@ ext-ms-win-rtcore-ntuser-window-l1-1-0,ext-ms-win-rtcore-ntuser-window-ansi-l1-1
/// Accepted `--backend` values. CrossOver ignores an unknown value silently, so one is refused.
const BACKENDS: [&str; 4] = ["d3dmetal", "dxmt", "dxvk", "wined3d"];
/// Accepted `--profile` values. The shims compare `BX_PROFILE` without regard to case and take
/// anything but "anaconda" for Lockhart, while `ConsoleMode` is chosen here, so the value is
/// normalized and an unknown one is refused instead of the two disagreeing.
const PROFILES: [&str; 2] = ["lockhart", "anaconda"];
const SAFE_CHILD_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin";
const HOST_ENV_ALLOWLIST: &[&str] = &[
@@ -41,10 +47,13 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
"XPC_SERVICE_NAME",
];
/// Opt-in `bx_runtime_veh.dll` diagnostic switches. They carry addresses and counts, never
/// credentials, so the isolated guest environment lets them through by name; every other
/// variable is still stripped.
/// Opt-in shim switches: `bx_runtime_veh.dll` diagnostics, and `d3d12_xs.dll`'s translation of
/// console pipelines (`BX_CONSOLE_SHADERS=1`, with `BX_SHADER_CACHE` naming the folder for
/// compiled shaders, #720). They carry addresses, counts and a folder, never credentials, so the
/// isolated guest environment lets them through by name; every other variable is still stripped.
const DIAGNOSTIC_ENV_ALLOWLIST: &[&str] = &[
"BX_CONSOLE_SHADERS",
"BX_SHADER_CACHE",
"BX_VEH_AV_CONTEXT",
"BX_VEH_AV_ALL",
"BX_VEH_WATCH",
@@ -63,12 +72,14 @@ fn usage_text() -> &'static str {
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] Remember where the target build and the GDK are on this machine (saved outside the repository); --find searches the home folder for them\n\
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, disk space. Fails if anything is missing\n\
bx-cli shader translate <vs> <ps> --out <dir> [--root <layout>] Translate a console VS/PS pair to HLSL (gfx10-translate); <layout> is the root signature's parameters, e.g. T,S:0:0,C2:1:0,B:2:0[,mem]\n\
bx-cli shader coverage <dir> Rank what blocks translation across a folder of *_VS.* / *_PS.* shaders\n\
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] [--dxc-dir <dir>] Remember where the target build, the GDK, the target build's Ghidra results and open-source DXC are on this machine (saved outside the repository); --find searches the home folder for them\n\
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, the Ghidra results, disk space. Fails if anything is missing\n\
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
bx-cli report <log.jsonl>... Run report per log (one log = one run), then a summary with blocker signatures\n\
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix)\n"
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)] [--gdk-libraries | --no-gdk-libraries]\n\
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix; the GDK's XG and BCPack libraries are staged for the configured target build)\n"
}
fn run_capture(program: &str, args: &[&str]) -> Option<String> {
@@ -233,6 +244,58 @@ fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -
const TARGET_EXE_KEY: &str = "target_exe";
const GDK_ROOT_KEY: &str = "gdk_root";
const GHIDRA_RESULTS_KEY: &str = "ghidra_results";
const DXC_DIR_KEY: &str = "dxc_dir";
/// The static-analysis results of the target build, recognised by structure: a folder with the
/// run's `RUN_REPORT.md`, a `decompiled/` folder, and `exports/<program>/` folders each holding a
/// `manifest.json` (naming the program) and a `functions.csv`.
const GHIDRA_REPORT: &str = "RUN_REPORT.md";
/// The `"program"` value of an exports manifest, read without a JSON parser.
fn manifest_program(text: &str) -> Option<String> {
let rest = &text[text.find("\"program\"")? + "\"program\"".len()..];
let rest = rest
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
Some(rest[..rest.find('"')?].to_owned())
}
/// The programs a Ghidra results folder covers, or `None` when it is not one.
fn ghidra_programs(root: &Path) -> Option<Vec<String>> {
if !root.join(GHIDRA_REPORT).is_file() || !root.join("decompiled").is_dir() {
return None;
}
let mut programs = Vec::new();
for entry in fs::read_dir(root.join("exports")).ok()?.flatten() {
let dir = entry.path();
if !dir.join("functions.csv").is_file() {
continue;
}
if let Some(program) = fs::read_to_string(dir.join("manifest.json"))
.ok()
.and_then(|text| manifest_program(&text))
{
programs.push(program);
}
}
(!programs.is_empty()).then_some(programs)
}
/// Whether the results cover the executable at `target` (by its file name, compared on this
/// machine only).
fn ghidra_covers(root: &Path, target: &Path) -> bool {
let Some(name) = target
.file_name()
.map(|n| n.to_string_lossy().to_ascii_lowercase())
else {
return false;
};
ghidra_programs(root)
.is_some_and(|programs| programs.iter().any(|p| p.to_ascii_lowercase() == name))
}
/// An Xbox Series title's executable is recognised by structure, never by name: a large PE32+
/// file that imports the console's D3D12 library. BetterXen's own test executables import it
@@ -273,6 +336,7 @@ fn gdk_root_for(home: &Path, header: &Path) -> Option<PathBuf> {
struct Found {
gdk_roots: Vec<PathBuf>,
target_exes: Vec<PathBuf>,
ghidra_results: Vec<PathBuf>,
/// The search gave up before visiting everything.
truncated: bool,
}
@@ -318,7 +382,13 @@ fn search_for_materials(home: &Path) -> Found {
stack.push((path, depth + 1));
}
} else if kind.is_file() {
if name_text == GDK_MARKER {
if name_text == GHIDRA_REPORT {
if let Some(dir) = path.parent()
&& ghidra_programs(dir).is_some()
{
found.ghidra_results.push(dir.to_path_buf());
}
} else if name_text == GDK_MARKER {
if let Some(root) = gdk_root_for(home, &path)
&& !found.gdk_roots.contains(&root)
&& check_gdk_root(root.to_str()).is_ok()
@@ -335,6 +405,7 @@ fn search_for_materials(home: &Path) -> Found {
}
found.gdk_roots.sort();
found.target_exes.sort();
found.ghidra_results.sort();
// The GDK ships tools that import the same library; they are not titles.
let roots = found.gdk_roots.clone();
found
@@ -409,7 +480,12 @@ fn distinct_builds_by(candidates: Vec<PathBuf>, siblings: impl Fn(&Path) -> usiz
fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
let need_target = check_target_exe(config.get(TARGET_EXE_KEY).map(String::as_str)).is_err();
let need_gdk = check_gdk_root(config.get(GDK_ROOT_KEY).map(String::as_str)).is_err();
if !need_target && !need_gdk {
let need_ghidra = check_ghidra_for_target(
config.get(GHIDRA_RESULTS_KEY).map(String::as_str),
config.get(TARGET_EXE_KEY).map(String::as_str),
)
.is_err();
if !need_target && !need_gdk && !need_ghidra {
return false;
}
let Some(home) = env::var_os("HOME").map(PathBuf::from) else {
@@ -417,7 +493,7 @@ fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
return false;
};
println!(
"Searching the home folder for the GDK and the target build (this can take a minute)..."
"Searching the home folder for the GDK, the target build and its Ghidra results (this can take a minute)..."
);
let found = search_for_materials(&home);
let mut changed = false;
@@ -453,6 +529,30 @@ fn find_materials(config: &mut BTreeMap<String, String>) -> bool {
}
}
}
if need_ghidra {
// Results are only useful for the build being worked on: the first that covers it.
let target = config.get(TARGET_EXE_KEY).map(PathBuf::from);
let covering = target
.as_deref()
.and_then(|t| found.ghidra_results.iter().find(|r| ghidra_covers(r, t)));
match (covering, target.is_some(), found.ghidra_results.is_empty()) {
(Some(results), _, _) => {
config.insert(
GHIDRA_RESULTS_KEY.to_owned(),
results.to_string_lossy().into_owned(),
);
changed = true;
println!(" Ghidra results: found and saved");
}
(None, false, _) => {
println!(" Ghidra results: set the target build first, then run --find again")
}
(None, true, true) => println!(" Ghidra results: not found in the home folder"),
(None, true, false) => {
println!(" Ghidra results: found, but none covers the target build")
}
}
}
if found.truncated {
println!(" (the search stopped early: the home folder has too many entries)");
}
@@ -480,6 +580,8 @@ fn cmd_setup(args: &[String]) -> ExitCode {
let (key, check): (&str, SettingCheck) = match args[i].as_str() {
"--target-exe" => (TARGET_EXE_KEY, check_target_exe),
"--gdk-root" => (GDK_ROOT_KEY, check_gdk_root),
"--ghidra-results" => (GHIDRA_RESULTS_KEY, check_ghidra_results),
"--dxc-dir" => (DXC_DIR_KEY, check_dxc_dir),
other => {
eprintln!("error: unknown argument: {other}");
return ExitCode::FAILURE;
@@ -520,6 +622,11 @@ fn cmd_setup(args: &[String]) -> ExitCode {
state(TARGET_EXE_KEY, check_target_exe)
);
println!(" GDK : {}", state(GDK_ROOT_KEY, check_gdk_root));
println!(
" Ghidra results: {}",
state(GHIDRA_RESULTS_KEY, check_ghidra_results)
);
println!(" DXC : {}", state(DXC_DIR_KEY, check_dxc_dir));
println!("They are kept outside the repository. Run `bx-cli preflight` to check everything.");
ExitCode::SUCCESS
}
@@ -538,6 +645,49 @@ fn check_target_exe(value: Option<&str>) -> Result<String, String> {
}
}
/// The Ghidra results: the setting must be a results folder (see [`ghidra_programs`]).
fn check_ghidra_results(value: Option<&str>) -> Result<String, String> {
let root = value.filter(|v| !v.is_empty()).ok_or(
"not set; run `bx-cli setup --find`, or `bx-cli setup --ghidra-results <folder with RUN_REPORT.md, exports/ and decompiled/>`",
)?;
match ghidra_programs(Path::new(root)) {
Some(programs) => Ok(format!("present ({} programs analysed)", programs.len())),
None => Err("that folder is not a Ghidra results folder (RUN_REPORT.md, exports/*/manifest.json, decompiled/)".to_owned()),
}
}
/// Preflight's view of the Ghidra results: present, and covering the configured target build.
fn check_ghidra_for_target(results: Option<&str>, target: Option<&str>) -> Result<String, String> {
let found = check_ghidra_results(results)?;
match target.filter(|t| !t.is_empty()) {
Some(target)
if ghidra_covers(Path::new(results.unwrap_or_default()), Path::new(target)) =>
{
Ok(found)
}
Some(_) => {
Err("the results do not cover the configured target build's executable".to_owned())
}
None => Err("cannot be matched: the target build is not set".to_owned()),
}
}
/// Open-source DXC: the setting must be a folder that contains a PC `dxcompiler.dll`
/// exporting `DxcCreateInstance`.
fn check_dxc_dir(value: Option<&str>) -> Result<String, String> {
let dir = value.filter(|v| !v.is_empty()).ok_or(
"not set (optional; GDK dxcompiler.dll used as fallback, or run `bx-cli setup --dxc-dir <folder with dxcompiler.dll>`)",
)?;
let path = Path::new(dir);
if !path.is_dir() {
return Err("the saved path is not a folder".to_owned());
}
match gdk_libs::find_dxc(path) {
Some(_) => Ok("present (dxcompiler.dll found)".to_owned()),
None => Err("no PC dxcompiler.dll exporting DxcCreateInstance under it".to_owned()),
}
}
/// The GDK: the setting must be a folder that contains the GDK's `d3d12_xs.h`.
fn check_gdk_root(value: Option<&str>) -> Result<String, String> {
let root = value
@@ -588,7 +738,7 @@ fn render_preflight(requirements: &[Requirement]) -> (String, bool) {
"Ready to work.\n"
} else {
"Not ready. Fix what you can yourself (AGENTS.md section 0, step 1): `bx-cli setup --find` for the \
target build and the GDK, Homebrew for missing tools, your own scratch files for disk space. \
target build, the GDK and the Ghidra results, Homebrew for missing tools, your own scratch files for disk space. \
Stop only for what is not on this machine.\n"
});
(out, ready)
@@ -650,6 +800,13 @@ fn cmd_preflight() -> ExitCode {
"GDK",
check_gdk_root(local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config).as_deref()),
),
(
"Ghidra results",
check_ghidra_for_target(
local_setting("BX_GHIDRA_RESULTS", GHIDRA_RESULTS_KEY, &config).as_deref(),
local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config).as_deref(),
),
),
(
"Free disk space",
match free {
@@ -1045,6 +1202,9 @@ struct RunArgs {
inherit_env: bool,
timeout: Option<Duration>,
backend: Option<String>,
/// The GDK's texture libraries (gdk_libs): `Some` when asked for or refused, `None` to use
/// them only for the configured target build.
gdk_libraries: Option<bool>,
}
fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
@@ -1057,6 +1217,7 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut inherit_env = false;
let mut timeout = None;
let mut backend: Option<String> = None;
let mut gdk_libraries: Option<bool> = None;
let mut i = 0;
while i < args.len() {
@@ -1070,7 +1231,15 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
i += 2;
}
"--profile" if i + 1 < args.len() => {
profile = args[i + 1].clone();
let name = args[i + 1].to_ascii_lowercase();
if !PROFILES.contains(&name.as_str()) {
return Err(format!(
"unknown profile {:?}; use one of {}",
args[i + 1],
PROFILES.join(", ")
));
}
profile = name;
i += 2;
}
"--bottle" if i + 1 < args.len() => {
@@ -1109,6 +1278,14 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
inherit_env = true;
i += 1;
}
"--gdk-libraries" => {
gdk_libraries = Some(true);
i += 1;
}
"--no-gdk-libraries" => {
gdk_libraries = Some(false);
i += 1;
}
other => return Err(format!("unknown argument: {other}")),
}
}
@@ -1133,6 +1310,7 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
inherit_env,
timeout,
backend,
gdk_libraries,
})
}
@@ -1450,6 +1628,7 @@ fn cmd_run(args: &[String]) -> ExitCode {
inherit_env,
timeout,
backend,
gdk_libraries,
} = run;
let cx_root = Path::new("/Applications/CrossOver.app/Contents/SharedSupport/CrossOver");
@@ -1460,8 +1639,71 @@ fn cmd_run(args: &[String]) -> ExitCode {
return ExitCode::FAILURE;
}
let abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
let mut abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
let abs_exe = fs::canonicalize(&exe).unwrap_or(exe);
// Runtime texture and shader-compiler libraries (gdk_libs.rs, ADR 0010): staged for the
// configured target build, or with --gdk-libraries. Open-source DXC (`--dxc-dir` /
// `BX_DXC_DIR`) takes precedence for `dxcompiler.dll`, with the GDK as fallback.
let config = local_config_path()
.map(|p| read_local_config(&p))
.unwrap_or_default();
let is_target = local_setting("BX_TARGET_EXE", TARGET_EXE_KEY, &config)
.and_then(|t| fs::canonicalize(t).ok())
.is_some_and(|t| t == abs_exe);
let mut staged_bcpack: Option<PathBuf> = None;
let mut gdk_shims_dir: Option<PathBuf> = None;
if gdk_libraries.unwrap_or(is_target) {
let dxc_dir = local_setting("BX_DXC_DIR", DXC_DIR_KEY, &config);
let gdk_root = local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config);
if dxc_dir.is_none() && gdk_root.is_none() {
diag(
"warning: GDK texture libraries and DXC not staged: neither GDK nor DXC configured (bx-cli setup --find / --dxc-dir)",
);
} else {
let libs = gdk_libs::resolve(
dxc_dir.as_deref().map(Path::new),
gdk_root.as_deref().map(Path::new),
);
let dxc_from_oss = dxc_dir
.as_deref()
.is_some_and(|dir| libs.dxc.as_ref().is_some_and(|p| p.starts_with(dir)));
let out = env::temp_dir().join(format!("bx-gdk-shims-{}", std::process::id()));
match gdk_libs::merge_shims(&abs_shims, &libs, &out) {
Ok(bcpack) => {
let state = |found: bool| if found { "staged" } else { "not found" };
let dxc_state = if libs.dxc.is_none() {
"not found"
} else if dxc_from_oss {
"staged (open-source)"
} else {
"staged (GDK fallback)"
};
diag(format_args!(
"bx-cli: runtime libraries: XG {}, BCPack {}, DXC {}",
state(libs.xg.is_some()),
state(bcpack.is_some()),
dxc_state
));
staged_bcpack = bcpack;
abs_shims = out.clone();
gdk_shims_dir = Some(out);
}
Err(e) => diag(format_args!(
"warning: GDK texture libraries not staged: {e}"
)),
}
}
}
struct RemoveOnDrop(Option<PathBuf>);
impl Drop for RemoveOnDrop {
fn drop(&mut self) {
if let Some(dir) = &self.0 {
let _ = fs::remove_dir_all(dir);
}
}
}
let _gdk_shims_cleanup = RemoveOnDrop(gdk_shims_dir);
let wine_shims_path = unix_to_wine_z_path(&abs_shims);
let resolved_prefix =
@@ -1575,30 +1817,89 @@ fn cmd_run(args: &[String]) -> ExitCode {
None => diag("warning: Xbox drive G: not mapped: the executable has no parent directory"),
}
let mut cmd = if let Some(ref bname) = bottle {
let mut c = Command::new(&wine_wrapper);
c.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()))
.arg(&abs_exe);
c
} else {
let _ = fs::create_dir_all(&resolved_prefix);
let mut c = Command::new(&wineloader);
c.arg(&abs_exe);
c
let guest_command = || {
let mut command = if let Some(ref bname) = bottle {
let mut command = Command::new(&wine_wrapper);
command
.args(["--bottle", bname])
.args(bottle_options(backend.as_deref()));
command
} else {
Command::new(&wineloader)
};
apply_host_env(&mut command, inherit_env);
if bottle.is_none() {
apply_prefix_env(&mut command, cx_root, &resolved_prefix, &wineloader);
}
command.env("WINEDEBUG", "-all");
command
};
apply_host_env(&mut cmd, inherit_env);
if bottle.is_none() {
apply_prefix_env(&mut cmd, cx_root, &resolved_prefix, &wineloader);
if staged_names.iter().any(|name| name == "bx_runtime_veh.dll") {
// This title reads the console profile before it calls any shim entry point.
// Publish the same profile as XSystemGetDeviceType while the prefix is locked.
let mode = if profile == "anaconda" {
"0x64"
} else {
"0x60"
};
let mut registry = guest_command();
registry
.args([
"reg.exe",
"add",
r"HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM",
"/v",
"ConsoleMode",
"/t",
"REG_DWORD",
"/d",
mode,
"/f",
])
.stdout(Stdio::null());
let active = active_time(started.elapsed(), supervise::suspended_time());
let remaining = match guest_time_left(timeout, active) {
Ok(remaining) => remaining,
Err(e) => {
diag(format_args!("timed out before setting ConsoleMode: {e}"));
return ExitCode::from(124);
}
};
match supervise::supervise(registry, remaining, supervise::received_signal) {
Ok(Outcome::Exited(status)) if status.success() => {
diag(format_args!("bx-cli: ConsoleMode={mode} profile={profile}"));
}
Ok(Outcome::Exited(status)) => {
diag(format_args!("warning: could not set ConsoleMode: {status}"));
}
Ok(outcome @ Outcome::Stopped(stop)) => {
let failed = stop_environment(
stop,
cx_root,
&environment_dir,
bottle.as_deref(),
inherit_env,
);
let code = outcome.exit_code();
return ExitCode::from(if failed { code.max(1) } else { code });
}
Err(e) => diag(format_args!("warning: could not set ConsoleMode: {e}")),
}
}
if bottle.is_none() {
let _ = fs::create_dir_all(&resolved_prefix);
}
let mut cmd = guest_command();
cmd.arg(&abs_exe);
cmd.env("ROSETTA_ADVERTISE_AVX", "1")
.env("WINEDLLOVERRIDES", SHIM_DLL_OVERRIDES)
.env("WINEPATH", &wine_shims_path)
.env("BX_PROFILE", &profile)
.env("WINEDEBUG", "-all");
.env("BX_PROFILE", &profile);
if let Some(bcpack) = &staged_bcpack {
cmd.env("BX_BCPACK_DLL", unix_to_wine_z_path(bcpack));
}
let abs_log = log_file.map(|lf| {
if lf.is_absolute() {
@@ -1722,6 +2023,132 @@ fn cmd_run(args: &[String]) -> ExitCode {
})
}
/// `bx-cli shader translate <vs> <ps> --out <dir>`: translates a console VS/PS pair (containers
/// or raw code blobs) with the gfx10-translate crate. Writes `<vs key>_<ps key>.vs.hlsl`,
/// `.ps.hlsl` and `.il` (the host pipeline's input layout and resources), keyed by FNV-1a of each
/// blob as the shim's shader cache expects. Compile the HLSL with the public DXC (vs_6_0/ps_6_0).
/// A root signature layout from its short form: comma-separated parameters in order, `T` (a
/// descriptor table), `C<n>:<register>:<space>` (n constants), `B:`, `S:` or `U:` followed by
/// `<register>:<space>` (a root CBV, SRV or UAV), and a final `mem` when the signature sets
/// D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI.
fn parse_root_layout(text: &str) -> Option<gfx10_translate::RootLayout> {
use gfx10_translate::{RootKind, RootLayout, RootParameter};
let mut layout = RootLayout::default();
for item in text.split(',') {
if item == "mem" {
layout.memory_based = true;
continue;
}
let mut fields = item.split(':');
let head = fields.next()?;
let (kind, values) = match head.split_at_checked(1)? {
("T", "") => (RootKind::Table, 0),
("C", n) => (RootKind::Constants, n.parse().ok()?),
("B", "") => (RootKind::Cbv, 0),
("S", "") => (RootKind::Srv, 0),
("U", "") => (RootKind::Uav, 0),
_ => return None,
};
let mut number = || fields.next().map_or(Some(0), |v| v.parse().ok());
let (register, space) = (number()?, number()?);
layout.parameters.push(RootParameter {
kind,
values,
register,
space,
});
}
Some(layout)
}
fn cmd_shader_translate(args: &[String]) -> ExitCode {
const USAGE: &str = "usage: bx-cli shader translate <vs container> <ps container> --out <dir> [--root <layout>]\n \
<layout>: the root parameters in order, e.g. T,S:0:0,C2:1:0,B:2:0[,mem]";
let (vs_path, ps_path, out, root) = match args {
[vs, ps, flag, out] if flag == "--out" => (vs, ps, out, None),
[vs, ps, flag, out, root_flag, root] if flag == "--out" && root_flag == "--root" => {
let Some(layout) = parse_root_layout(root) else {
eprintln!("error: cannot read the root layout '{root}'\n{USAGE}");
return ExitCode::FAILURE;
};
(vs, ps, out, Some(layout))
}
_ => {
eprintln!("{USAGE}");
return ExitCode::FAILURE;
}
};
let (vs, ps) = match (fs::read(vs_path), fs::read(ps_path)) {
(Ok(vs), Ok(ps)) => (vs, ps),
(Err(e), _) | (_, Err(e)) => {
eprintln!("error: cannot read the shaders: {e}");
return ExitCode::FAILURE;
}
};
let translated = match &root {
Some(layout) => gfx10_translate::translate_blobs_rooted(&vs, &ps, layout),
None => gfx10_translate::translate_blobs(&vs, &ps),
};
let t = match translated {
Ok(t) => t,
Err(e) => {
eprintln!("unsupported: {e}");
return ExitCode::FAILURE;
}
};
let key = format!(
"{}_{}",
gfx10_translate::translate::fnv1a(&vs),
gfx10_translate::translate::fnv1a(&ps)
);
let base = Path::new(out).join(&key);
let write = |ext: &str, text: &str| fs::write(base.with_extension(ext), text);
let written = fs::create_dir_all(out)
.and_then(|()| write("vs.hlsl", &t.vs_hlsl))
.and_then(|()| write("ps.hlsl", &t.ps_hlsl))
.and_then(|()| write("il", &t.layout));
match written {
Ok(()) => {
println!("{key}");
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("error: cannot write to {out}: {e}");
ExitCode::FAILURE
}
}
}
/// `bx-cli shader coverage <dir>`: how many of the console shaders in a local folder (`*_VS.*`,
/// `*_PS.*`) translate, and what blocks the rest, most frequent first.
fn cmd_shader_coverage(args: &[String]) -> ExitCode {
let [dir] = args else {
eprintln!("usage: bx-cli shader coverage <folder of *_VS.* / *_PS.* shaders>");
return ExitCode::FAILURE;
};
let cov = match gfx10_translate::coverage::scan(Path::new(dir)) {
Ok(c) => c,
Err(e) => {
eprintln!("error: cannot scan {dir}: {e}");
return ExitCode::FAILURE;
}
};
let pct = if cov.shaders == 0 {
0.0
} else {
100.0 * cov.translated as f64 / cov.shaders as f64
};
println!(
"shaders: {} translated: {} ({pct:.1}%)",
cov.shaders, cov.translated
);
println!("blockers (shaders stopped, reason):");
for (key, n) in cov.ranked().into_iter().take(40) {
println!(" {n:6} {key}");
}
ExitCode::SUCCESS
}
fn cmd_shader(path: &str) -> ExitCode {
let data = match fs::read(path) {
Ok(d) => d,
@@ -1808,6 +2235,10 @@ fn main() -> ExitCode {
"setup" => cmd_setup(&args[1..]),
"preflight" => cmd_preflight(),
"probe" if args.len() >= 2 => cmd_probe(&args[1]),
"shader" if args.len() >= 2 && args[1] == "translate" => {
cmd_shader_translate(&args[2..])
}
"shader" if args.len() >= 2 && args[1] == "coverage" => cmd_shader_coverage(&args[2..]),
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
"report" if args.len() >= 2 => cmd_report(&args[1..]),
@@ -1821,6 +2252,44 @@ fn main() -> ExitCode {
}
}
#[cfg(test)]
mod root_layout_tests {
use super::parse_root_layout;
use gfx10_translate::RootKind;
#[test]
fn reads_the_short_form() {
let layout = parse_root_layout("T,S:3:2,C2:1,B:2:1,mem").unwrap();
assert!(layout.memory_based);
let kinds: Vec<RootKind> = layout.parameters.iter().map(|p| p.kind).collect();
assert_eq!(
kinds,
[
RootKind::Table,
RootKind::Srv,
RootKind::Constants,
RootKind::Cbv
]
);
assert_eq!(
(layout.parameters[1].register, layout.parameters[1].space),
(3, 2)
);
assert_eq!(
(
layout.parameters[2].values,
layout.parameters[2].register,
layout.parameters[2].space
),
(2, 1, 0)
);
assert!(!parse_root_layout("T,S:0:0").unwrap().memory_based);
for bad in ["", "X", "C:0:0", "S:x", "T1"] {
assert!(parse_root_layout(bad).is_none(), "{bad}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2111,12 +2580,16 @@ mod tests {
assert_eq!(run.backend.as_deref(), Some("d3dmetal"));
assert_eq!(run.shims_dir, PathBuf::from("build-shims/bin"));
assert_eq!(run.profile, "lockhart");
// ConsoleMode and BX_PROFILE must name the same console whatever the case.
let mixed = parse_run_args(&args(&["--exe", "a.exe", "--profile", "Anaconda"])).unwrap();
assert_eq!(mixed.profile, "anaconda");
let plain = parse_run_args(&args(&["--exe", "a.exe"])).unwrap();
assert!(plain.timeout.is_none() && plain.bottle.is_none() && plain.prefix.is_none());
for bad in [
&["--exe", "a.exe", "--timeout", "0"][..],
&["--exe", "a.exe", "--timeout", "soon"],
&["--exe", "a.exe", "--backend", "dmxt2"],
&["--exe", "a.exe", "--profile", "scarlett"],
&["--exe", "a.exe", "--bottle", "../x"],
&["--exe", "a.exe", "--timeout"],
&["--bottle", "b"],
@@ -2592,6 +3065,44 @@ sub setup_bottle_wineprefix {
fs::write(dir.join("a/b/include").join(GDK_MARKER), b"// header").unwrap();
assert!(check_gdk_root(dir.to_str()).unwrap().contains("found"));
// Ghidra results: unset, not a results folder, results for another program, results
// covering the target build (matched by its file name, whatever the case).
assert!(check_ghidra_results(None).unwrap_err().contains("not set"));
let results = dir.join("results");
fs::create_dir_all(results.join("exports/other")).unwrap();
assert!(
check_ghidra_results(results.to_str())
.unwrap_err()
.contains("not a Ghidra results folder")
);
fs::create_dir_all(results.join("decompiled")).unwrap();
fs::write(results.join(GHIDRA_REPORT), b"# RUN_REPORT").unwrap();
fs::write(results.join("exports/other/functions.csv"), b"").unwrap();
fs::write(
results.join("exports/other/manifest.json"),
br#"{"program": "other.dll", "rows": {}}"#,
)
.unwrap();
assert!(check_ghidra_results(results.to_str()).is_ok());
assert!(
check_ghidra_for_target(results.to_str(), pe.to_str())
.unwrap_err()
.contains("do not cover")
);
assert!(
check_ghidra_for_target(results.to_str(), None)
.unwrap_err()
.contains("target build is not set")
);
fs::create_dir_all(results.join("exports/t")).unwrap();
fs::write(results.join("exports/t/functions.csv"), b"").unwrap();
fs::write(
results.join("exports/t/manifest.json"),
br#"{"program":"TITLE.exe"}"#,
)
.unwrap();
assert!(check_ghidra_for_target(results.to_str(), pe.to_str()).is_ok());
// One missing requirement makes the whole preflight not ready, and says so.
let (text, ready) = render_preflight(&[
("Target build", Ok("present".to_owned())),
@@ -2608,15 +3119,49 @@ sub setup_bottle_wineprefix {
"free space is measurable for an existing folder"
);
// Open-source DXC: unset, not a folder, folder without dxcompiler.dll, folder with valid PE32+ dxcompiler.dll.
assert!(check_dxc_dir(None).unwrap_err().contains("not set"));
assert!(
check_dxc_dir(pe.to_str())
.unwrap_err()
.contains("not a folder")
);
let dxc_dir = dir.join("dxc");
fs::create_dir_all(&dxc_dir).unwrap();
assert!(
check_dxc_dir(dxc_dir.to_str())
.unwrap_err()
.contains("no PC dxcompiler.dll")
);
let mut fake_dxc = vec![0u8; 0x200];
fake_dxc[0..2].copy_from_slice(b"MZ");
fake_dxc[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
fake_dxc[0x40..0x44].copy_from_slice(b"PE\0\0");
fake_dxc[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
fake_dxc[0x54..0x56].copy_from_slice(&240u16.to_le_bytes());
fake_dxc[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
fake_dxc[0x58 + 108..0x58 + 112].copy_from_slice(&16u32.to_le_bytes());
fake_dxc.extend_from_slice(b"DxcCreateInstance\0");
fs::write(dxc_dir.join("dxcompiler.dll"), &fake_dxc).unwrap();
assert!(check_dxc_dir(dxc_dir.to_str()).unwrap().contains("found"));
// Local settings: written, read back, unknown keys kept, comments ignored; the
// environment variable wins over the saved value.
let conf = dir.join("conf/local.conf");
let mut values = BTreeMap::new();
values.insert(TARGET_EXE_KEY.to_owned(), pe.to_string_lossy().into_owned());
values.insert(
DXC_DIR_KEY.to_owned(),
dxc_dir.to_string_lossy().into_owned(),
);
values.insert("future_key".to_owned(), "kept".to_owned());
write_local_config(&conf, &values).unwrap();
let read = read_local_config(&conf);
assert_eq!(read, values);
assert_eq!(
local_setting("BX_TEST_UNSET_VARIABLE_FOR_PREFLIGHT", DXC_DIR_KEY, &read).as_deref(),
dxc_dir.to_str()
);
assert!(
fs::read_to_string(&conf)
.unwrap()
+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)
@@ -8,5 +8,8 @@ rust-version.workspace = true
[lib]
crate-type = ["rlib", "cdylib"]
[dependencies]
gfx10-translate = { path = "../gfx10-translate" }
[lints]
workspace = true
@@ -420,3 +420,260 @@ fn free_buffer(ptr: *mut u8, len: usize) {
pub unsafe extern "C" fn bx_shader_free_buffer(ptr: *mut u8, len: usize) {
let _ = catch_unwind(AssertUnwindSafe(|| free_buffer(ptr, len)));
}
/// Mirror of `bx_shader_pair_translation_t` (abi/include/bx_shader_bridge.h).
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BxShaderPairTranslation {
pub vs_key: u64,
pub ps_key: u64,
pub vs_hlsl: *mut u8,
pub vs_hlsl_len: usize,
pub ps_hlsl: *mut u8,
pub ps_hlsl_len: usize,
pub layout: *mut u8,
pub layout_len: usize,
pub reason: *mut u8,
pub reason_len: usize,
}
impl BxShaderPairTranslation {
const EMPTY: Self = Self {
vs_key: 0,
ps_key: 0,
vs_hlsl: ptr::null_mut(),
vs_hlsl_len: 0,
ps_hlsl: ptr::null_mut(),
ps_hlsl_len: 0,
layout: ptr::null_mut(),
layout_len: 0,
reason: ptr::null_mut(),
reason_len: 0,
};
fn free_buffers(&mut self) {
for (buffer, len) in [
(&mut self.vs_hlsl, &mut self.vs_hlsl_len),
(&mut self.ps_hlsl, &mut self.ps_hlsl_len),
(&mut self.layout, &mut self.layout_len),
(&mut self.reason, &mut self.reason_len),
] {
free_buffer(*buffer, *len);
*buffer = ptr::null_mut();
*len = 0;
}
}
}
/// 64-bit FNV-1a, the cache key of a shader as the title passes it.
fn fnv1a64(data: &[u8]) -> u64 {
data.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| {
(h ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)
})
}
/// Copies `text` into a caller-owned buffer; an empty text stays (NULL, 0).
fn publish(text: &str, buffer: &mut *mut u8, len: &mut usize) -> Result<(), ()> {
if text.is_empty() {
return Ok(());
}
*buffer = alloc_copy(text.as_bytes())?;
*len = text.len();
Ok(())
}
/// Mirror of `bx_shader_root_parameter_t`.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BxShaderRootParameter {
pub r#type: u32,
pub num_32bit_values: u32,
pub shader_register: u32,
pub register_space: u32,
}
/// Mirror of `bx_shader_root_layout_t`.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct BxShaderRootLayout {
pub parameters: *const BxShaderRootParameter,
pub parameter_count: u32,
pub flags: u32,
}
/// D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI.
const ROOT_FLAG_MEMORY_BASED: u32 = 0x0100_0000;
/// More parameters than a root signature can have (its cost limit is 64 values).
const MAX_ROOT_PARAMETERS: u32 = 64;
/// The translator's layout for a C layout; None when it is inconsistent.
///
/// # Safety
///
/// `layout.parameters` must be readable for `parameter_count` entries when it is non-null.
unsafe fn root_layout(layout: &BxShaderRootLayout) -> Option<gfx10_translate::RootLayout> {
use gfx10_translate::{RootKind, RootParameter};
if layout.parameter_count > MAX_ROOT_PARAMETERS
|| (layout.parameters.is_null() && layout.parameter_count != 0)
{
return None;
}
let parameters: &[BxShaderRootParameter] = if layout.parameter_count == 0 {
&[]
} else {
// SAFETY: non-null, and the caller guarantees `parameter_count` readable entries.
unsafe { std::slice::from_raw_parts(layout.parameters, layout.parameter_count as usize) }
};
let mut out = gfx10_translate::RootLayout {
parameters: Vec::with_capacity(parameters.len()),
memory_based: layout.flags & ROOT_FLAG_MEMORY_BASED != 0,
};
for p in parameters {
let kind = match p.r#type {
0 => RootKind::Table,
1 => RootKind::Constants,
2 => RootKind::Cbv,
3 => RootKind::Srv,
4 => RootKind::Uav,
_ => return None,
};
out.parameters.push(RootParameter {
kind,
values: p.num_32bit_values,
register: p.shader_register,
space: p.register_space,
});
}
Some(out)
}
fn translate_pair_status(
vs: &[u8],
ps: &[u8],
root: Option<&gfx10_translate::RootLayout>,
out: &mut BxShaderPairTranslation,
) -> i32 {
if vs.is_empty() || ps.is_empty() {
return BX_SHADER_ERR_INVALID_BLOB;
}
out.vs_key = fnv1a64(vs);
out.ps_key = fnv1a64(ps);
// An input that holds no console code is invalid; code the translator does not model is
// unsupported and says why.
if gfx10_translate::container::code_words(vs).is_err()
|| gfx10_translate::container::code_words(ps).is_err()
{
return BX_SHADER_ERR_INVALID_BLOB;
}
let translated = match root {
Some(layout) => gfx10_translate::translate_blobs_rooted(vs, ps, layout),
None => gfx10_translate::translate_blobs(vs, ps),
};
match translated {
Ok(t) => {
let published = publish(&t.vs_hlsl, &mut out.vs_hlsl, &mut out.vs_hlsl_len)
.and_then(|()| publish(&t.ps_hlsl, &mut out.ps_hlsl, &mut out.ps_hlsl_len))
.and_then(|()| publish(&t.layout, &mut out.layout, &mut out.layout_len));
match published {
Ok(()) => BX_SHADER_OK,
Err(()) => BX_SHADER_ERR_OOM,
}
}
Err(e) => match publish(&e.0, &mut out.reason, &mut out.reason_len) {
Ok(()) => BX_SHADER_ERR_UNSUPPORTED,
Err(()) => BX_SHADER_ERR_OOM,
},
}
}
/// Translate a console vertex/pixel shader pair to HLSL (see `bx_shader_translate_pair` in
/// abi/include/bx_shader_bridge.h for the contract).
///
/// # Safety
///
/// `vs_bytes` and `ps_bytes` must be readable for their lengths when non-null. `out` must be
/// null or point to a writable `bx_shader_pair_translation_t`; its previous contents are
/// overwritten without being freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_shader_translate_pair(
vs_bytes: *const u8,
vs_len: usize,
ps_bytes: *const u8,
ps_len: usize,
out: *mut BxShaderPairTranslation,
) -> i32 {
// SAFETY: the caller's guarantees are those of the rooted form with no layout.
unsafe { bx_shader_translate_pair_rooted(vs_bytes, vs_len, ps_bytes, ps_len, ptr::null(), out) }
}
/// Translate a console vertex/pixel shader pair given the layout of the pipeline's root
/// signature (see `bx_shader_translate_pair_rooted` in abi/include/bx_shader_bridge.h). A null
/// `layout` gives `bx_shader_translate_pair`.
///
/// # Safety
///
/// As [`bx_shader_translate_pair`]. `layout` must be null or point to a readable
/// `bx_shader_root_layout_t` whose `parameters` is readable for `parameter_count` entries.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_shader_translate_pair_rooted(
vs_bytes: *const u8,
vs_len: usize,
ps_bytes: *const u8,
ps_len: usize,
layout: *const BxShaderRootLayout,
out: *mut BxShaderPairTranslation,
) -> i32 {
if out.is_null() {
return BX_SHADER_ERR_INVALID_BLOB;
}
// SAFETY: `out` is non-null and the caller guarantees it is writable.
unsafe { out.write(BxShaderPairTranslation::EMPTY) };
let mut result = BxShaderPairTranslation::EMPTY;
let status = match catch_unwind(AssertUnwindSafe(|| {
match (input_bytes(vs_bytes, vs_len), input_bytes(ps_bytes, ps_len)) {
(Some(vs), Some(ps)) => {
if layout.is_null() {
translate_pair_status(vs, ps, None, &mut result)
} else {
// SAFETY: non-null, and the caller guarantees the layout is readable.
match unsafe { root_layout(&*layout) } {
Some(root) => translate_pair_status(vs, ps, Some(&root), &mut result),
None => BX_SHADER_ERR_INVALID_BLOB,
}
}
}
_ => BX_SHADER_ERR_INVALID_BLOB,
}
})) {
Ok(status) => status,
Err(_) => BX_SHADER_ERR_TRANSLATE,
};
// Buffers that do not belong to the returned status are not handed out.
if status != BX_SHADER_OK && status != BX_SHADER_ERR_UNSUPPORTED {
result.free_buffers();
}
// SAFETY: as above.
unsafe { out.write(result) };
status
}
/// Free every buffer of a translation and clear it. A null pointer is a no-op.
///
/// # Safety
///
/// `translation` must be null or point to a structure filled by [`bx_shader_translate_pair`]
/// whose buffers have not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_shader_free_pair_translation(
translation: *mut BxShaderPairTranslation,
) {
if translation.is_null() {
return;
}
let _ = catch_unwind(AssertUnwindSafe(|| {
// SAFETY: non-null, and the caller guarantees it is a filled structure.
let t = unsafe { &mut *translation };
t.free_buffers();
*t = BxShaderPairTranslation::EMPTY;
}));
}
@@ -37,8 +37,9 @@
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
//! 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.
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. `bx_shader_translate_pair`
//! translates a console vertex/pixel pair to HLSL with the `gfx10-translate`
//! crate (#720); compiling that HLSL to DXIL is the caller's step.
mod c_abi;
mod fspx;
@@ -47,8 +48,10 @@ use std::fmt;
pub use c_abi::{
BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_ERR_OOM, BX_SHADER_ERR_TRANSLATE,
BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderInspection, bx_shader_free_buffer,
bx_shader_inspect, bx_shader_prepare_for_d3dmetal,
BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderInspection, BxShaderPairTranslation,
BxShaderRootLayout, BxShaderRootParameter, bx_shader_free_buffer,
bx_shader_free_pair_translation, bx_shader_inspect, bx_shader_prepare_for_d3dmetal,
bx_shader_translate_pair, bx_shader_translate_pair_rooted,
};
pub use fspx::{FSPX_MAX_SECTIONS, FspxCodeBounds, FspxInfo, FspxSection, FspxStageConfig};
@@ -0,0 +1,241 @@
//! `bx_shader_translate_pair` through its C entry point.
//!
//! The expected HLSL and layout are the Python prototype's output for the same pair (the golden
//! files of `gfx10-translate`); the expected keys are computed here from the FNV authors'
//! published parameters, not by the bridge.
use dxbc_accc::{
BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderPairTranslation,
bx_shader_free_pair_translation, bx_shader_translate_pair,
};
use dxbc_accc::{BxShaderRootLayout, BxShaderRootParameter, bx_shader_translate_pair_rooted};
const VS_HEX: &str = include_str!("../../gfx10-translate/tests/goldens/textured.vs.hex");
const PS_HEX: &str = include_str!("../../gfx10-translate/tests/goldens/textured.ps.hex");
const VS_HLSL: &str = include_str!("../../gfx10-translate/tests/goldens/textured.vs.hlsl");
const PS_HLSL: &str = include_str!("../../gfx10-translate/tests/goldens/textured.ps.hlsl");
const LAYOUT: &str = include_str!("../../gfx10-translate/tests/goldens/textured.il");
/// Instruction words as the little-endian bytes of a raw code blob.
fn code(hex: &str) -> Vec<u8> {
hex.split_whitespace()
.flat_map(|w| u32::from_str_radix(w, 16).unwrap().to_le_bytes())
.collect()
}
fn fnv1a64(data: &[u8]) -> u64 {
let mut h: u64 = 14_695_981_039_346_656_037;
for b in data {
h = (h ^ u64::from(*b)).wrapping_mul(1_099_511_628_211);
}
h
}
fn text(ptr: *const u8, len: usize) -> String {
if ptr.is_null() {
return String::new();
}
// SAFETY: the bridge returned `len` bytes at `ptr`.
String::from_utf8(unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()).unwrap()
}
fn translate(vs: &[u8], ps: &[u8]) -> (i32, BxShaderPairTranslation) {
let mut out = std::mem::MaybeUninit::<BxShaderPairTranslation>::uninit();
// SAFETY: both inputs are readable slices and `out` is writable.
let status = unsafe {
bx_shader_translate_pair(
vs.as_ptr(),
vs.len(),
ps.as_ptr(),
ps.len(),
out.as_mut_ptr(),
)
};
// SAFETY: the bridge fills `out` in every case.
(status, unsafe { out.assume_init() })
}
#[test]
fn a_pair_translates_to_the_prototypes_output() {
let (vs, ps) = (code(VS_HEX), code(PS_HEX));
let (status, mut t) = translate(&vs, &ps);
assert_eq!(status, BX_SHADER_OK);
assert_eq!(text(t.vs_hlsl, t.vs_hlsl_len), VS_HLSL);
assert_eq!(text(t.ps_hlsl, t.ps_hlsl_len), PS_HLSL);
assert_eq!(text(t.layout, t.layout_len), LAYOUT);
assert!(t.reason.is_null() && t.reason_len == 0);
assert_eq!((t.vs_key, t.ps_key), (fnv1a64(&vs), fnv1a64(&ps)));
// SAFETY: `t` was filled by the bridge and is freed once.
unsafe { bx_shader_free_pair_translation(&mut t) };
assert!(t.vs_hlsl.is_null() && t.ps_hlsl.is_null() && t.layout.is_null());
assert_eq!(
(t.vs_hlsl_len, t.ps_hlsl_len, t.layout_len, t.vs_key),
(0, 0, 0, 0)
);
// Freeing a cleared structure, or none, does nothing.
unsafe { bx_shader_free_pair_translation(&mut t) };
unsafe { bx_shader_free_pair_translation(std::ptr::null_mut()) };
}
#[test]
fn a_refusal_carries_its_reason_and_the_keys() {
// image_store v0, v[1:2], s[20:27] dmask:0x1 dim:2D ; s_endpgm (llvm-mc, gfx1030): the
// translator has no rule for image stores.
let (vs, ps) = (code(VS_HEX), code("f0200108 00050001 bf810000"));
let (status, mut t) = translate(&vs, &ps);
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
let reason = text(t.reason, t.reason_len);
assert!(reason.contains("image_store"), "{reason}");
assert!(t.vs_hlsl.is_null() && t.ps_hlsl.is_null() && t.layout.is_null());
assert_eq!((t.vs_key, t.ps_key), (fnv1a64(&vs), fnv1a64(&ps)));
// SAFETY: as above.
unsafe { bx_shader_free_pair_translation(&mut t) };
assert!(t.reason.is_null());
}
#[test]
fn unreadable_inputs_are_invalid() {
let (vs, ps) = (code(VS_HEX), code(PS_HEX));
// An empty stage.
let (status, t) = translate(&vs, &[]);
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(t.vs_hlsl.is_null() && t.reason.is_null());
// A container (DXBC magic) that holds no console code.
let mut not_code = b"DXBC".to_vec();
not_code.extend([0u8; 60]);
let (status, t) = translate(&not_code, &ps);
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(t.vs_hlsl.is_null() && t.reason.is_null());
// No output structure, and NULL inputs with a length.
// SAFETY: a null `out` is not written; null inputs are not read.
unsafe {
assert_eq!(
bx_shader_translate_pair(
vs.as_ptr(),
vs.len(),
ps.as_ptr(),
ps.len(),
std::ptr::null_mut()
),
BX_SHADER_ERR_INVALID_BLOB
);
let mut out = std::mem::MaybeUninit::<BxShaderPairTranslation>::uninit();
assert_eq!(
bx_shader_translate_pair(
std::ptr::null(),
16,
ps.as_ptr(),
ps.len(),
out.as_mut_ptr()
),
BX_SHADER_ERR_INVALID_BLOB
);
}
}
// One root SRV at t5: s0 = s8 ; s1 = s9 | (1 << 16) ; s2 = -1 ; s3 = 0x11014fac ; v1 = v0 + v0 ;
// buffer_load_dwordx3 v[1:3], v1, s[0:3], 8 offen offset:4 ; v4 = 1.0 ; exp pos0 ; s_endpgm
// (our own assembly through llvm-mc; the same program as gfx10-translate's root-buffer test).
const ROOT_SRV_VS: &str = "be800308 8801ff09 00010000 be8203c1 be8303ff 11014fac 4a020100 e03c1004 88000101 7e0802f2 f80008cf 04030201 bf810000";
/// v_mov_b32 v0, 1.0 ; exp mrt0 v0, v0, v0, v0 done vm ; s_endpgm
const FLAT_PS: &str = "7e0002f2 f800180f 00000000 bf810000";
fn translate_rooted(
vs: &[u8],
ps: &[u8],
layout: *const BxShaderRootLayout,
) -> (i32, BxShaderPairTranslation) {
let mut out = std::mem::MaybeUninit::<BxShaderPairTranslation>::uninit();
// SAFETY: the inputs are readable slices, `layout` is null or valid, `out` is writable.
let status = unsafe {
bx_shader_translate_pair_rooted(
vs.as_ptr(),
vs.len(),
ps.as_ptr(),
ps.len(),
layout,
out.as_mut_ptr(),
)
};
// SAFETY: the bridge fills `out` in every case.
(status, unsafe { out.assume_init() })
}
#[test]
fn a_root_layout_changes_what_the_registers_mean() {
let (vs, ps) = (code(ROOT_SRV_VS), code(FLAT_PS));
// Without a layout s8 is taken for a table pointer, and building a buffer from it is refused.
let (status, mut t) = translate_rooted(&vs, &ps, std::ptr::null());
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
unsafe { bx_shader_free_pair_translation(&mut t) };
// With the layout "one root SRV at t5, space 3" it is that parameter's buffer.
let parameters = [BxShaderRootParameter {
r#type: 3,
num_32bit_values: 0,
shader_register: 5,
register_space: 3,
}];
let layout = BxShaderRootLayout {
parameters: parameters.as_ptr(),
parameter_count: 1,
flags: 0,
};
let (status, mut t) = translate_rooted(&vs, &ps, &layout);
assert_eq!(status, BX_SHADER_OK);
let hlsl = text(t.vs_hlsl, t.vs_hlsl_len);
assert!(
hlsl.contains("ByteAddressBuffer rootbuf0 : register(t5, space3);"),
"{hlsl}"
);
assert!(hlsl.contains("uint vertex_id : SV_VertexID"), "{hlsl}");
assert_eq!(text(t.layout, t.layout_len), "USE ROOT 0\n");
unsafe { bx_shader_free_pair_translation(&mut t) };
// The memory-based flag changes where root data is read: this register-form shader then
// reads nothing the layout accounts for and is refused.
let memory = BxShaderRootLayout {
flags: 0x0100_0000,
..layout
};
let (status, mut t) = translate_rooted(&vs, &ps, &memory);
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
unsafe { bx_shader_free_pair_translation(&mut t) };
}
#[test]
fn inconsistent_layouts_are_invalid() {
let (vs, ps) = (code(ROOT_SRV_VS), code(FLAT_PS));
// A count without parameters.
let missing = BxShaderRootLayout {
parameters: std::ptr::null(),
parameter_count: 2,
flags: 0,
};
let (status, t) = translate_rooted(&vs, &ps, &missing);
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
assert!(t.vs_hlsl.is_null() && t.reason.is_null());
// A parameter type Direct3D 12 does not have.
let parameters = [BxShaderRootParameter {
r#type: 9,
num_32bit_values: 0,
shader_register: 0,
register_space: 0,
}];
let unknown = BxShaderRootLayout {
parameters: parameters.as_ptr(),
parameter_count: 1,
flags: 0,
};
assert_eq!(
translate_rooted(&vs, &ps, &unknown).0,
BX_SHADER_ERR_INVALID_BLOB
);
// An empty signature is a layout like any other: the shader reads past it and is refused.
let empty = BxShaderRootLayout {
parameters: std::ptr::null(),
parameter_count: 0,
flags: 0,
};
let (status, mut t) = translate_rooted(&vs, &ps, &empty);
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
unsafe { bx_shader_free_pair_translation(&mut t) };
}
@@ -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,269 @@
//! The GPU code of one stage from a console shader container.
//!
//! A console container is a DXBC file whose DXIL part carries no bitcode (or carries an `XDAT`
//! section after the bitcode/`NOBC` placeholder). The console code is in an `XBCH` record:
//! - `+0..+4`: magic `b"XBCH"`
//! - `+4..+8`: version (`u32`, low byte checked: `2` = uncompressed `FSSM` payload of `csize`
//! bytes at `+24`; `3` = zlib-compressed `FSSM` stream of `csize` bytes at `+24` inflating to
//! `usize` bytes; synthetic conformance tests also use `1` for zlib-compressed)
//! - `+8..+16`: `csize` (`u64`), payload/compressed stream size in bytes
//! - `+16..+24`: `usize` (`u64`), uncompressed size in bytes (used for zlib-compressed records)
//! - `+24..+24+csize`: payload (`FSSM` block or zlib stream)
//!
//! It inflates (or decodes directly for version 2) 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.
//!
//! Because the 4-byte sequence `b"XBCH"` can also appear incidentally in earlier chunks (such as
//! `STAT` or `DXIL` bitcode) before the real `XBCH` record, [`container_code`] scans all `b"XBCH"`
//! occurrences and validates each candidate's header, bounds, version, and `FSSM` magic rather than
//! stopping at the first match.
//!
//! These are inferences from containers of the project-authorized target build and the GDK
//! compiler (`AGENTS.md` section 6), checked by the synthetic containers 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()?))
}
fn try_xbch_at(blob: &[u8], at: usize) -> Result<Vec<u8>, ContainerError> {
let ver = u32_at(blob, at + 4).ok_or(ContainerError::BadXbch("truncated header"))? & 0xff;
let csize_u64 = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))?;
let usize_u64 = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))?;
let csize = usize::try_from(csize_u64)
.map_err(|_| ContainerError::BadXbch("compressed size past the end"))?;
let end = at
.checked_add(24)
.and_then(|start| start.checked_add(csize))
.filter(|&end| end <= blob.len())
.ok_or(ContainerError::BadXbch("compressed size past the end"))?;
let payload = &blob[at + 24..end];
match ver {
2 => {
if payload.get(..4) != Some(b"FSSM") {
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
}
Ok(payload.to_vec())
}
1 | 3 => {
let usize_ = usize::try_from(usize_u64)
.map_err(|_| ContainerError::BadXbch("does not inflate to an FSSM block"))?;
let fssm = zlib_inflate(payload, 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"));
}
Ok(fssm)
}
_ => Err(ContainerError::BadXbch("unsupported version")),
}
}
fn extract_fssm_code(fssm: &[u8]) -> Result<Vec<u8>, ContainerError> {
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 stage code inside a console container, header records included.
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
let mut last_err = None;
for (at, w) in blob.windows(4).enumerate() {
if w != b"XBCH" {
continue;
}
match try_xbch_at(blob, at) {
Ok(fssm) => return extract_fssm_code(&fssm),
Err(e) => last_err = Some(e),
}
}
Err(last_err.unwrap_or(ContainerError::NoXbch))
}
/// 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
}
fn build_fssm(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);
fssm
}
fn container_with_version(code_words_after_header: &[u32], version: u32) -> Vec<u8> {
let fssm = build_fssm(code_words_after_header);
let (payload, usize_) = if (version & 0xff) == 2 {
(fssm, 0u64)
} else {
let usize_ = fssm.len() as u64;
(stored(&fssm), usize_)
};
let mut blob = b"DXBC".to_vec();
blob.extend_from_slice(&[0u8; 28]);
blob.extend_from_slice(b"XBCH");
blob.extend_from_slice(&version.to_le_bytes());
blob.extend_from_slice(&(payload.len() as u64).to_le_bytes());
blob.extend_from_slice(&usize_.to_le_bytes());
blob.extend_from_slice(&payload);
blob
}
/// 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> {
container_with_version(code_words_after_header, 1)
}
#[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 skips_incidental_xbch_bytes_before_the_record() {
let mut blob = container_with_version(&[0xBF81_0000, 0x1234_5678], 3);
// Simulate an incidental "XBCH" sequence in an earlier chunk (e.g. STAT or DXIL bitcode)
// whose +8 bytes look like a compressed size past the end of the container.
blob[8..12].copy_from_slice(b"XBCH");
blob[16..24].copy_from_slice(&u64::MAX.to_le_bytes());
assert_eq!(code_words(&blob).unwrap(), vec![0xBF81_0000, 0x1234_5678]);
}
#[test]
fn supports_uncompressed_version_2_and_compressed_version_3() {
let v2 = container_with_version(&[0xBF81_0000], 2);
assert_eq!(code_words(&v2).unwrap(), vec![0xBF81_0000]);
let v3 = container_with_version(&[0xBF81_0000], 3);
assert_eq!(code_words(&v3).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(_))));
let v4 = container_with_version(&[0xBF81_0000], 4);
assert_eq!(
code_words(&v4),
Err(ContainerError::BadXbch("unsupported version"))
);
}
}
@@ -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,53 @@
//! 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::{
RootKind, RootLayout, RootParameter, Stage, Translation, Unsupported, translate_pair,
translate_pair_rooted,
};
/// 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)
}
/// As `translate_blobs`, given the layout of the pipeline's root signature.
pub fn translate_blobs_rooted(
vs: &[u8],
ps: &[u8],
root: &RootLayout,
) -> 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_rooted(&vs, &ps, Some(root))
}
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,646 @@
//! 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_add_nc_u32_e64 v0, v1, v2 clamp: saturating integer arithmetic is refused, not dropped
// (float clamp and omod are translated; see vop3_float_modifiers).
assert!(
refusal(Stage::Pixel, "d5258000 02020501 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
);
}
/// VOP3 modifiers (#719): input abs then neg on float sources, omod then clamp on a float
/// result; clamp on an integer instruction (saturating arithmetic) stays refused. Encodings from
/// llvm-mc (gfx1030).
#[test]
fn vop3_float_modifiers() {
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
let hlsl = |inst: &str| {
let ps = decode(&words(&format!("{inst} f8000801 00000000 bf810000"))).unwrap();
translate_pair(&vs, &ps).map(|t| t.ps_hlsl)
};
// v_max_f32_e64 v0, v1, v2 clamp
let t = hlsl("d5108000 02020501").unwrap();
assert!(
t.contains(" v0 = asuint(saturate(max(asfloat(v1), asfloat(v2))));\n"),
"{t}"
);
// v_mul_f32_e64 v0, v1, v2 mul:2
let t = hlsl("d5080000 0a020501").unwrap();
assert!(
t.contains(" v0 = asuint((asfloat(v1) * asfloat(v2)) * 2.0f);\n"),
"{t}"
);
// v_add_f32_e64 v0, |v1|, -|v2|: abs first, then neg.
let t = hlsl("d5030300 42020501").unwrap();
assert!(t.contains("asfloat((asuint(abs(asfloat(v1)))))"), "{t}");
assert!(
t.contains("asfloat((asuint(-asfloat((asuint(abs(asfloat(v2))))))))"),
"{t}"
);
// v_mul_legacy_f32_e64 v0, |v1|, |v2|
let t = hlsl("d5070300 02020501").unwrap();
assert!(
t.contains("abs(asfloat(v1))") && t.contains("abs(asfloat(v2))"),
"{t}"
);
// v_add_nc_u32_e64 v0, v1, v2 clamp: integer saturation is a different operation.
let err = hlsl("d5258000 02020501").unwrap_err();
assert!(err.0.starts_with("modifier in"), "{err}");
}
/// 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
);
}
}
/// Descriptor tables of further root parameters (#715): s9 is root parameter 1's table pointer,
/// read through `s_mov_b32 s10, s9; s_mov_b32 s11, 0`. Its entry 2 (byte 0x40, 32-byte entries)
/// is a constant buffer in register space 101; a constant-buffer load with a register offset is
/// an indexed read. Encodings from llvm-mc (gfx1030).
#[test]
fn root_parameter_tables_and_register_offsets() {
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
// s_mov_b32 s10, s9; s_mov_b32 s11, 0; s_load_dwordx4 s[0:3], s[10:11], 0x40;
// s_buffer_load_dword s4, s[0:3], 0x8; s_buffer_load_dword s5, s[0:3], s6;
// v_mov_b32_e32 v0, s4; v_mov_b32_e32 v1, s5; exp mrt0, v0, v1, off, off done; s_endpgm
let ps = decode(&words(
"be8a0309 be8b0380 f4080005 fa000040 f4200100 fa000008 f4200140 0c000000 7e000204 7e020205 f8000803 00000100 bf810000",
))
.unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
assert!(
t.ps_hlsl
.contains("cbuffer CB1_2 : register(b2, space101) { uint4 cb1_2[4096]; };"),
"{}",
t.ps_hlsl
);
assert!(
t.ps_hlsl.contains(" s4 = cb1_2_word(2);\n"),
"{}",
t.ps_hlsl
);
assert!(
t.ps_hlsl.contains(" s5 = cb1_2_word((s6 >> 2) + 0u);\n"),
"{}",
t.ps_hlsl
);
assert_eq!(t.layout, "FETCH 1\nUSE CB 1 2\n");
}
/// image_load and image_gather4_lz (#718): integer-coordinate loads from 2D and 3D textures
/// (declared by the dimension they are read with) and a green-channel gather. Textures come from
/// root table 0 entries 1 and 2. Encodings from llvm-mc (gfx1030).
#[test]
fn image_loads_and_gathers() {
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
// s_load_dwordx8 s[20:27], s[8:9], 0x20; s_load_dwordx8 s[28:35], s[8:9], 0x40;
// image_load v[0:3], v[4:5], s[20:27] dmask:0xf dim:2D; image_load v6, v[4:6], s[28:35] dmask:0x1 dim:3D;
// image_gather4_lz v[8:11], v[4:5], s[20:27], s[36:39] dmask:0x2 dim:2D;
// exp mrt0, v0, v6, v8, v11 done; s_endpgm
let ps = decode(&words(
"f40c0504 fa000020 f40c0704 fa000040 f0000f08 00050004 f0000110 00070604 f11c0208 01250804 f800080f 0b080600 bf810000",
))
.unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
let h = &t.ps_hlsl;
assert!(
h.contains("Texture2D<float4> tex1 : register(t1, space100);"),
"{h}"
);
assert!(
h.contains("Texture3D<float4> tex2 : register(t2, space100);"),
"{h}"
);
assert!(
h.contains("{ float4 r = tex1.Load(int3(asint(v4), asint(v5), 0));"),
"{h}"
);
assert!(
h.contains("{ float4 r = tex2.Load(int4(asint(v4), asint(v5), asint(v6), 0));"),
"{h}"
);
assert!(
h.contains("{ float4 r = tex1.GatherGreen(smp0, float2(asfloat(v4), asfloat(v5)));"),
"{h}"
);
assert!(h.contains(" v11 = asuint(r.w);"), "{h}");
assert_eq!(t.layout, "FETCH 1\nUSE TEX 1\nUSE TEX 2\n");
}
/// image_sample_lz on a 3D texture (#718). MIMG `dim` 2 is SQ_RSRC_IMG_3D; a 3D sample reads
/// three address registers, the normalized coordinates s, t and r, and `_lz` samples mip level 0
/// (RDNA 2 ISA, MIMG). In HLSL that is `Texture3D.SampleLevel(sampler, float3, 0)`. A 2D sample of
/// another texture in the same shader keeps its form. Textures come from root table 0 entries 1
/// and 2. Encodings from llvm-mc (gfx1030).
#[test]
fn image_samples_on_3d_textures() {
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
// s_load_dwordx8 s[20:27], s[8:9], 0x20; s_load_dwordx8 s[28:35], s[8:9], 0x40;
// image_sample_lz v[0:2], v[4:6], s[28:35], s[36:39] dmask:0x7 dim:SQ_RSRC_IMG_3D;
// image_sample v3, v[4:5], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D;
// exp mrt0, v0, v1, v2, v3 done; s_endpgm
let ps = decode(&words(
"f40c0504 fa000020 f40c0704 fa000040 f09c0710 01270004 f0800108 01250304 f800080f 03020100 bf810000",
))
.unwrap();
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
let h = &t.ps_hlsl;
assert!(
h.contains("Texture3D<float4> tex2 : register(t2, space100);"),
"{h}"
);
assert!(
h.contains("Texture2D<float4> tex1 : register(t1, space100);"),
"{h}"
);
assert!(
h.contains(
"{ float4 r = tex2.SampleLevel(smp0, float3(asfloat(v4), asfloat(v5), asfloat(v6)), 0);"
),
"{h}"
);
assert!(h.contains(" v0 = asuint(r.x);"), "{h}");
assert!(h.contains(" v2 = asuint(r.z);"), "{h}");
assert!(
h.contains("{ float4 r = tex1.Sample(smp0, float2(asfloat(v4), asfloat(v5)));"),
"{h}"
);
assert!(h.contains(" v3 = asuint(r.x);"), "{h}");
assert_eq!(t.layout, "FETCH 1\nUSE TEX 1\nUSE TEX 2\n");
}
/// Sample forms still outside the model are refused, not translated as 2D: a cube map, and 16-bit
/// (a16) addresses. Encodings from llvm-mc (gfx1030).
#[test]
fn refuses_cube_and_a16_samples() {
// s_load_dwordx8 s[20:27], s[8:9], 0x20;
// image_sample_lz v[0:3], v[4:6], s[20:27], s[36:39] dmask:0xf dim:SQ_RSRC_IMG_CUBE; s_endpgm
assert!(refusal(Stage::Pixel, "f40c0504 fa000020 f09c0f18 01250004 bf810000").is_some());
// image_sample_lz v[0:2], v[4:5], s[20:27], s[36:39] dmask:0x7 dim:SQ_RSRC_IMG_3D a16
assert!(refusal(Stage::Pixel, "f40c0504 fa000020 f09c0710 41250004 bf810000").is_some());
}
/// A pixel shader's HLSL from instruction words (no interpolated inputs).
fn pixel_hlsl(hex: &str) -> String {
let insts = decode(&words(hex)).unwrap();
let mut t = Translator::new(Stage::Pixel);
t.run(&insts).unwrap();
gfx10_translate::translate::build_ps(&t, &[]).unwrap()
}
// Encodings from llvm-mc (gfx1030). Expected lines follow the ISA's definitions, not the
// translator: a compare writes the condition for active lanes only; s_and_saveexec saves exec and
// ANDs it with the source; s_cbranch_execz jumps when no lane is active; the export's vm bit
// marks the lanes that survive.
#[test]
fn divergent_if_runs_under_exec() {
// v_cmp_lt_f32_e32 vcc_lo, v0, v1 (word 0)
// s_and_saveexec_b32 s0, vcc_lo (1)
// s_cbranch_execz 1 (2: to word 4)
// v_mov_b32_e32 v2, 1.0 (3)
// s_or_b32 exec_lo, exec_lo, s0 (4)
// exp mrt0 v2, v2, v2, v2 done vm (5-6)
// s_endpgm (7)
let ps = pixel_hlsl("7c020300 be803c6a bf880001 7e0402f2 887e007e f800180f 02020202 bf810000");
let has = |line: &str| assert!(ps.contains(line), "missing `{line}` in\n{ps}");
has("vcc = exec && (");
has("bool old_exec = exec;");
has("exec = exec && vcc;");
has("m0 = old_exec;");
has("blk = (!WaveActiveAnyTrue(exec)) ? 4u : 3u;");
// The move runs only for active lanes; restoring exec reads the saved mask.
has("if (exec) {");
has("exec = exec || m0;");
has("if (!exec) discard;");
has("return float4(exp_mrt0.x, exp_mrt0.y, exp_mrt0.z, exp_mrt0.w);");
}
#[test]
fn cmpx_removes_lanes_before_the_final_export() {
// v_cmpx_gt_f32_e32 0.5, v0 ; exp mrt0 v0, v0, v0, v0 done vm ; s_endpgm
let ps = pixel_hlsl("7c2800f0 f800180f 00000000 bf810000");
assert!(
ps.contains("exec = exec && (asfloat(asuint(0.5f)) > asfloat(v0));"),
"{ps}"
);
assert!(ps.contains("if (!exec) discard;"), "{ps}");
}
#[test]
fn early_exit_keeps_the_code_after_it() {
// s_cmp_eq_u32 s0, 0 (word 0)
// s_cbranch_scc1 3 (1: to word 5)
// exp mrt0 v0, v0, v0, v0 done vm (2-3)
// s_endpgm (4)
// v_mov_b32_e32 v0, 0 (5)
// exp mrt0 v0, v0, v0, v0 done vm (6-7)
// s_endpgm (8)
let hex = "bf068000 bf850003 f800180f 00000000 bf810000 7e000280 f800180f 00000000 bf810000";
assert_eq!(decode(&words(hex)).unwrap().len(), 7);
let ps = pixel_hlsl(hex);
assert!(ps.contains("scc = s0 == 0u;"), "{ps}");
assert!(ps.contains("blk = (scc) ? 5u : 2u;"), "{ps}");
// Both exits export to the same variable, so the one that ran is returned.
assert_eq!(
ps.matches("exp_mrt0 = float4(asfloat(v0)").count(),
2,
"{ps}"
);
// Each s_endpgm ends the loop, as does the fallback for an unknown block.
assert_eq!(ps.matches("blk = 0xffffffffu;").count(), 3, "{ps}");
}
#[test]
fn samples_run_for_the_whole_quad() {
// s_load_dwordx8 s[20:27], s[8:9], 0x20 ; v_cmpx_lt_f32_e32 0, v4 ;
// image_sample v[0:3], v[4:5], s[20:27], s[36:39] dmask:0xf dim:2D ;
// exp mrt0 v0, v1, v2, v3 done vm ; s_endpgm
// A sample's derivatives come from its quad, whatever exec holds, so it is not placed under
// control flow that depends on exec; only the register writes are.
let ps = pixel_hlsl("f40c0504 fa000020 7c220880 f0800f08 01250004 f800180f 03020100 bf810000");
assert!(ps.contains("v0 = exec ? (asuint(r.x)) : v0;"), "{ps}");
assert!(ps.contains("v3 = exec ? (asuint(r.w)) : v3;"), "{ps}");
let sample = ps.find(".Sample(").expect("a sample");
assert!(!ps[..sample].contains("if (exec)"), "{ps}");
}
// ---- Root signature layouts (#715) ---------------------------------------------------------
// The layout rules are measured in docs/research/console-shader-abi.md ("Graphics stages"): root
// arguments are packed 32-bit values in parameter order (table pointer 1, root CBV/SRV/UAV 2,
// constants 1 each); value d is s(8 + d), or byte 4 * d of root data addressed through s0 and the
// low byte of s1. The programs below are our own assembly (llvm-mc, gfx1030), not compiler
// output; the expected lines follow from those rules and each program's comments.
use gfx10_translate::{RootKind, RootLayout, RootParameter, translate_pair_rooted};
/// A table, a root SRV at t3 space 2, two constants at b1 space 0, a root CBV at b2 space 1.
fn mixed_layout(memory_based: bool) -> RootLayout {
let p = |kind, values, register, space| RootParameter {
kind,
values,
register,
space,
};
RootLayout {
parameters: vec![
p(RootKind::Table, 0, 0, 0),
p(RootKind::Srv, 0, 3, 2),
p(RootKind::Constants, 2, 1, 0),
p(RootKind::Cbv, 0, 2, 1),
],
memory_based,
}
}
/// v_mov_b32 v0, 1.0 ; exp mrt0 v0, v0, v0, v0 done vm ; s_endpgm
const FLAT_PS: &str = "7e0002f2 f800180f 00000000 bf810000";
// Root values: 0 table pointer (s8); 1, 2 SRV address (s9, s10); 3, 4 constants (s11, s12);
// 5, 6 CBV address (s13, s14).
// s0 = s9 ; s1 = s10 | (16 << 16) ; s2 = -1 ; s3 = 0x11014fac the SRV's descriptor, stride 16
// buffer_load_dwordx4 v[0:3], v0, s[0:3], 0 idxen element v0 (the vertex index)
// s4 = s13 ; s5 = s14 | (16 << 16) ; s6 = -1 ; s7 = 0x11014fac the CBV's descriptor
// s_buffer_load_dwordx4 s[4:7], s[4:7], 0x10 its bytes 16..31
// s9 = 0 ; s_load_dwordx4 s[16:19], s[8:9], 0x20 entry 1 of the table
// s_buffer_load_dwordx4 s[16:19], s[16:19], 0
// v0 *= s11 ; v1 *= s12 ; v2 += s4 ; v3 += s16 ; exp pos0 ; s_endpgm
const REGISTER_FORM_VS: &str = "be800309 8801ff0a 00100000 be8203c1 be8303ff 11014fac e0382000 80000000 be84030d 8805ff0e 00100000 \
be8603c1 be8703ff 11014fac f4280102 fa000010 be890380 f4080404 fa000020 f4280408 fa000000 1000000b 1002020c 06040404 06060610 \
f80008cf 03020100 bf810000";
#[test]
fn root_layout_register_form() {
let vs = decode(&words(REGISTER_FORM_VS)).unwrap();
let ps = decode(&words(FLAT_PS)).unwrap();
let t = translate_pair_rooted(&vs, &ps, Some(&mixed_layout(false)))
.unwrap_or_else(|e| panic!("{e}"));
let h = &t.vs_hlsl;
let has = |line: &str| assert!(h.contains(line), "missing `{line}` in\n{h}");
// Each root parameter at the title's own register and space; the table in space 100 + 0.
has("ByteAddressBuffer rootbuf1 : register(t3, space2);");
has("cbuffer ROOTC2 : register(b1, space0) { uint rootc2_0; uint rootc2_1; };");
has("cbuffer ROOTCB3 : register(b2, space1) { uint4 rootcb3[4096]; };");
has("cbuffer CB1 : register(b1, space100) { uint4 cb1[4096]; };");
// The SRV read: element v0 of 16 bytes, and v0 on entry is the vertex index.
has("uint vertex_id : SV_VertexID");
has("uint v0 = vertex_id;");
has("rootbuf1.Load((v0 * 16u + 0u) + 0u)");
has("rootbuf1.Load((v0 * 16u + 0u) + 12u)");
// The CBV read at byte 16, the constants in their registers, the table entry.
has("s4 = rootcb3_word(((16u) >> 2) + 0u);");
has("uint s11 = rootc2_0;");
has("uint s12 = rootc2_1;");
has("s16 = cb1_word(0);");
assert_eq!(t.layout, "USE CB 1\nUSE ROOT 1\nUSE ROOT 2\nUSE ROOT 3\n");
}
#[test]
fn root_layout_decides_what_a_register_holds() {
let vs = decode(&words(REGISTER_FORM_VS)).unwrap();
let ps = decode(&words(FLAT_PS)).unwrap();
// Without a layout every parameter is taken for a table, and this shader is refused.
assert!(translate_pair(&vs, &ps).is_err());
// With a layout in which s9 is a table pointer, building a buffer from it is refused too.
let p = |kind| RootParameter {
kind,
values: 0,
register: 0,
space: 0,
};
let tables = RootLayout {
parameters: vec![p(RootKind::Table); 7],
memory_based: false,
};
assert!(translate_pair_rooted(&vs, &ps, Some(&tables)).is_err());
// A shader that reads past the root signature is refused: here s9 and s10 are beyond a
// signature of one table.
let short = RootLayout {
parameters: vec![p(RootKind::Table)],
memory_based: false,
};
assert!(translate_pair_rooted(&vs, &ps, Some(&short)).is_err());
}
// The same parameters with the root data in memory:
// s3 = s1 & 0xff ; s2 = s0 the address of the root data
// s_load_dwordx2 s[10:11], s[2:3], 0x4 values 1, 2: the SRV address
// s_load_dwordx2 s[8:9], s[2:3], 0xc values 3, 4: the constants
// s_load_dword s6, s[2:3], 0 ; s7 = 0 value 0: the table pointer
// s0 = s10 ; s1 = s11 | (4 << 16) ; s2 = -1 ; s3 = 0x11014fac the SRV's descriptor, stride 4
// buffer_load_dword v0, v0, s[0:3], 0 idxen
// s_load_dwordx4 s[16:19], s[6:7], 0x40 entry 2 of the table
// s_buffer_load_dword s16, s[16:19], 0
// v1 = s8 * v0 ; v2 = s9 * v0 ; v3 = s16 ; exp pos0 ; s_endpgm
const MEMORY_FORM_VS: &str = "8703ff01 000000ff be820300 f4040281 fa000004 f4040201 fa00000c f4000181 fa000000 be870380 be80030a \
8801ff0b 00040000 be8203c1 be8303ff 11014fac e0302000 80000000 f4080403 fa000040 f4200408 fa000000 10020008 10040009 7e060210 \
f80008cf 03020100 bf810000";
#[test]
fn root_layout_memory_form() {
let vs = decode(&words(MEMORY_FORM_VS)).unwrap();
let ps = decode(&words(FLAT_PS)).unwrap();
let t = translate_pair_rooted(&vs, &ps, Some(&mixed_layout(true)))
.unwrap_or_else(|e| panic!("{e}"));
let h = &t.vs_hlsl;
let has = |line: &str| assert!(h.contains(line), "missing `{line}` in\n{h}");
has("ByteAddressBuffer rootbuf1 : register(t3, space2);");
has("cbuffer ROOTC2 : register(b1, space0) { uint rootc2_0; uint rootc2_1; };");
has("cbuffer CB2 : register(b2, space100) { uint4 cb2[4096]; };");
// The constants are assigned where they are loaded, not on entry: s8 and s9 are ordinary
// registers in this form.
has("s8 = rootc2_0;");
has("s9 = rootc2_1;");
assert!(!h.contains("uint s8 = rootc2_0;"), "{h}");
has("rootbuf1.Load((v0 * 4u + 0u) + 0u)");
has("s16 = cb2_word(0);");
assert_eq!(t.layout, "USE CB 2\nUSE ROOT 1\nUSE ROOT 2\n");
// Read as the register form, the same code loads from s0 as from the vertex-buffer table
// and is refused.
assert!(translate_pair_rooted(&vs, &ps, Some(&mixed_layout(false))).is_err());
}
#[test]
fn root_buffer_byte_offsets_and_the_vertex_index() {
// One root SRV at t5 (s8, s9), a byte-addressed buffer (stride 1):
// s0 = s8 ; s1 = s9 | (1 << 16) ; s2 = -1 ; s3 = 0x11014fac
// v1 = v0 + v0 v0 on entry: the vertex index
// buffer_load_dwordx3 v[1:3], v1, s[0:3], 8 offen offset:4
// three dwords at byte v1 + 8 + 4: the
// scalar offset operand and the immediate
// v4 = 1.0 ; exp pos0, v1, v2, v3, v4 done ; s_endpgm
let vs = decode(&words(
"be800308 8801ff09 00010000 be8203c1 be8303ff 11014fac 4a020100 e03c1004 88000101 7e0802f2 f80008cf 04030201 bf810000",
))
.unwrap();
let ps = decode(&words(FLAT_PS)).unwrap();
let layout = RootLayout {
parameters: vec![RootParameter {
kind: RootKind::Srv,
values: 0,
register: 5,
space: 0,
}],
memory_based: false,
};
let t = translate_pair_rooted(&vs, &ps, Some(&layout)).unwrap_or_else(|e| panic!("{e}"));
let h = &t.vs_hlsl;
assert!(
h.contains("ByteAddressBuffer rootbuf0 : register(t5, space0);"),
"{h}"
);
assert!(
h.contains("VSOut main(uint vertex_id : SV_VertexID)"),
"{h}"
);
assert!(h.contains("uint v0 = vertex_id;"), "{h}");
assert!(h.contains("v1 = v0 + v0;"), "{h}");
assert!(h.contains("rootbuf0.Load((v1 + 8u + 4u) + 0u)"), "{h}");
assert!(h.contains("rootbuf0.Load((v1 + 8u + 4u) + 8u)"), "{h}");
assert_eq!(t.layout, "USE ROOT 0\n");
}
+4
View File
@@ -8,10 +8,14 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
xbox_facade.cpp
frame_pacing.cpp
placed_x.cpp
gdk_xg.cpp
descriptor_heaps.cpp
committed.cpp
console_formats.cpp
pipelines.cpp
console_pipelines.cpp
console_descriptors.cpp
rect_list.cpp
gpu_writes.cpp
fences.cpp
presentx_xbox.cpp
+95 -8
View File
@@ -11,12 +11,21 @@
* 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);
@@ -28,18 +37,67 @@ constexpr ULONGLONG kPageSize64K = 1ull << 14; // XALLOC_ATTRIBUTES.PageS
constexpr ULONGLONG kPageSize2M = 2ull << 14;
constexpr UINT64 k2M = 2ull << 20;
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method) {
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 size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
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[200];
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu page=%s title_va=%p", method,
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)) {
@@ -61,11 +119,12 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, c
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");
"CreateCommittedResource", title_format);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
@@ -76,11 +135,12 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self,
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");
riid, ppv, "CreateCommittedResource1", title_format);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
@@ -91,11 +151,12 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self,
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");
riid, ppv, "CreateCommittedResource2", title_format);
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
@@ -106,13 +167,39 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self,
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");
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"
+270
View File
@@ -0,0 +1,270 @@
/*
* Descriptors of translated console draws (#720). Active with BX_CONSOLE_SHADERS=1.
*
* On the console a CBV/SRV/UAV descriptor is 32 bytes of memory at its handle, and a title may
* copy those bytes itself: the target build fills per-draw descriptor tables with memcpy, never
* telling Direct3D. The host heap behind such a table then holds nothing at those indices.
*
* So that the copies can be followed:
* 1. every CreateConstantBufferView and CreateShaderResourceView also writes a marker into the
* title's descriptor memory at the handle: a magic word, the id of a registry entry that
* holds the view, and the id's complement. The title copies the marker with its bytes;
* 2. SetGraphicsRootDescriptorTable is noted per command list, and each translated draw
* records the tables bound at that moment;
* 3. when the list is submitted, the entries the draw's shaders read (the translation's
* `USE` lines) are looked up through their markers and written to the host heap at the same
* index, before the host executes the list.
* Direct3D's own copies (CopyDescriptors, CopyDescriptorsSimple) copy the title-side bytes as
* well as the host descriptors, as they do on the console: the title goes on to copy from their
* destinations by hand.
* A constant buffer's bytes are copied from title memory into an upload ring at that moment, so
* the host sees what the title had written by submission whatever backs the title's address.
*
* The marker is BetterXen's own format, not the console's descriptor encoding (which is not
* known here): a title that reads its descriptors back, rather than only copying them, would
* see it. Entries without a marker are left as the host heap has them and are logged.
*
* Limits, logged when met: a registered texture is kept referenced for the life of the process;
* a table changed between a draw and the submission of its list is read at submission.
*/
#include "console_pipelines.h"
#include "xbox_facade.h"
#include "bx_log.h"
#include <array>
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace {
constexpr uint32_t kMarkerMagic = 0x31445842u; // "BXD1"
constexpr UINT kDescriptorSize = 32; // console CBV/SRV/UAV descriptor
constexpr UINT kTables = 8; // root parameters followed per list
void log(bx_log_level_t level, const char* event, const char* fmt, ...) {
char detail[400];
va_list args;
va_start(args, fmt);
std::vsnprintf(detail, sizeof(detail), fmt, args);
va_end(args);
bx_log_emit(level, "d3d12_xs", event, detail);
}
bool sampled(std::atomic<uint64_t>& counter, uint64_t* total) {
*total = ++counter;
return (*total & (*total - 1)) == 0;
}
struct View {
bool texture = false;
D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{}; // host description
uint64_t title_va = 0; // the title's address of the constant data
ID3D12Resource* resource = nullptr; // SRV: host resource, referenced
bool has_srv_desc = false;
D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
};
std::mutex g_view_lock;
std::vector<View> g_views(1); // id 0 is never used
std::unordered_map<std::string, uint32_t> g_view_ids;
uint32_t intern(const std::string& key, const View& view) {
std::lock_guard<std::mutex> guard(g_view_lock);
auto it = g_view_ids.find(key);
if (it != g_view_ids.end()) return it->second;
const uint32_t id = static_cast<uint32_t>(g_views.size());
g_views.push_back(view);
if (view.resource) view.resource->AddRef();
g_view_ids.emplace(key, id);
return id;
}
void write_marker(uint64_t title_handle, uint32_t id) {
if (!bx_xbox_title_descriptors(title_handle, 1)) return;
const uint32_t words[8] = {kMarkerMagic, id, ~id, 0, 0, 0, 0, 0};
std::memcpy(reinterpret_cast<void*>(title_handle), words, sizeof(words));
}
bool readable(uint64_t address, uint64_t size) {
MEMORY_BASIC_INFORMATION info{};
if (!address || !VirtualQuery(reinterpret_cast<void*>(address), &info, sizeof(info))) return false;
if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD))) return false;
return address + size <= reinterpret_cast<uint64_t>(info.BaseAddress) + info.RegionSize;
}
/* The constant data at `title_va`, copied to an upload ring at a 256-byte-aligned offset. The
ring wraps: at 16 MiB it holds at least 256 buffers of the largest size, far more than the
draws of the lists in flight. */
bool constant_copy(ID3D12Device* device, uint64_t title_va, uint64_t size, D3D12_CONSTANT_BUFFER_VIEW_DESC* out) {
constexpr uint64_t kRing = 16ull << 20;
static ID3D12Resource* ring = nullptr;
static uint8_t* mapped = nullptr;
static uint64_t cursor = 0;
static std::mutex lock;
if (!size || size > 65536 || !readable(title_va, size)) return false;
std::lock_guard<std::mutex> guard(lock);
if (!ring) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
d.Width = kRing;
d.Height = d.DepthOrArraySize = d.MipLevels = 1;
d.SampleDesc.Count = 1;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&ring))) ||
FAILED(ring->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) {
ring = nullptr;
return false;
}
}
const uint64_t aligned = (size + 255) & ~255ull;
if (cursor + aligned > kRing) cursor = 0;
std::memset(mapped + cursor, 0, aligned);
std::memcpy(mapped + cursor, reinterpret_cast<const void*>(title_va), size);
out->BufferLocation = ring->GetGPUVirtualAddress() + cursor;
out->SizeInBytes = static_cast<UINT>(aligned);
cursor += aligned;
return true;
}
struct Draw {
std::shared_ptr<BxConsolePipeline> pipeline;
uint64_t tables[kTables];
};
std::mutex g_list_lock;
std::unordered_map<const void*, std::vector<Draw>> g_draws; // per list, since its reset
std::unordered_map<const void*, std::array<uint64_t, kTables>> g_tables; // title table handles bound
std::atomic<uint64_t> g_resolved{0};
std::atomic<uint64_t> g_unmarked{0};
/* Writes the host view for one table entry a translated draw reads. */
void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uint64_t entry) {
uint32_t words[8] = {};
std::memcpy(words, reinterpret_cast<const void*>(entry), sizeof(words));
View view;
bool ok = words[0] == kMarkerMagic && words[2] == ~words[1];
if (ok) {
std::lock_guard<std::mutex> guard(g_view_lock);
ok = words[1] != 0 && words[1] < g_views.size();
if (ok) view = g_views[words[1]];
}
const D3D12_CPU_DESCRIPTOR_HANDLE host = bx_xbox_host_cpu_handle({static_cast<SIZE_T>(entry)});
uint64_t total = 0;
if (ok && !use.texture && !view.texture) {
D3D12_CONSTANT_BUFFER_VIEW_DESC copy{};
// Fresh bytes from title memory when it can be read; otherwise the view as created.
if (constant_copy(device, view.title_va, view.cbv.SizeInBytes, &copy)) {
device->CreateConstantBufferView(&copy, host);
} else {
device->CreateConstantBufferView(&view.cbv, host);
}
++g_resolved;
} else if (ok && use.texture && view.texture) {
device->CreateShaderResourceView(view.resource, view.has_srv_desc ? &view.srv : nullptr, host);
++g_resolved;
} else if (sampled(g_unmarked, &total)) {
log(BX_LOG_WARN, "console_descriptor",
"pipeline %s reads %s entry %u of root parameter %u, which holds %s (%08x %08x %08x %08x); left as the host heap has it; "
"total=%llu, resolved=%llu",
key, use.texture ? "texture" : "constant buffer", use.entry, use.param,
ok ? "a view of the other kind" : "no view this layer created", words[0], words[1], words[2], words[3],
static_cast<unsigned long long>(total), static_cast<unsigned long long>(g_resolved.load()));
}
}
} // namespace
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc) {
if (!bx_console_shaders_enabled() || !title_handle) return;
View view;
view.cbv = host_desc;
view.title_va = title_va;
char key[80];
std::snprintf(key, sizeof(key), "c%llx:%llx:%u", static_cast<unsigned long long>(title_va),
static_cast<unsigned long long>(host_desc.BufferLocation), host_desc.SizeInBytes);
write_marker(title_handle, intern(key, view));
}
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc) {
if (!bx_console_shaders_enabled() || !title_handle || !host) return;
View view;
view.texture = true;
view.resource = host;
view.has_srv_desc = host_desc != nullptr;
if (host_desc) view.srv = *host_desc;
std::string key = "s" + std::to_string(reinterpret_cast<uintptr_t>(host)) + ":";
if (host_desc) key.append(reinterpret_cast<const char*>(host_desc), sizeof(*host_desc));
write_marker(title_handle, intern(key, view));
}
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count) {
if (!bx_console_shaders_enabled() || !count || dest == src) return;
if (!bx_xbox_title_descriptors(dest, count) || !bx_xbox_title_descriptors(src, count)) return;
std::memmove(reinterpret_cast<void*>(dest), reinterpret_cast<const void*>(src), static_cast<size_t>(kDescriptorSize) * count);
}
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle) {
if (!bx_console_shaders_enabled() || param >= kTables) return;
std::lock_guard<std::mutex> guard(g_list_lock);
g_tables[list][param] = title_handle;
}
void bx_console_record_draw(ID3D12GraphicsCommandList* list, const std::shared_ptr<BxConsolePipeline>& pipeline) {
std::lock_guard<std::mutex> guard(g_list_lock);
Draw draw{pipeline, {}};
auto bound = g_tables.find(list);
if (bound != g_tables.end()) std::memcpy(draw.tables, bound->second.data(), sizeof(draw.tables));
std::vector<Draw>& draws = g_draws[list];
// Consecutive draws with the same pipeline and tables resolve the same entries.
if (!draws.empty() && draws.back().pipeline == pipeline && std::memcmp(draws.back().tables, draw.tables, sizeof(draw.tables)) == 0) {
return;
}
draws.push_back(std::move(draw));
}
void bx_console_descriptors_reset(ID3D12GraphicsCommandList* list) {
std::lock_guard<std::mutex> guard(g_list_lock);
g_draws.erase(list);
g_tables.erase(list);
}
void bx_console_submit(ID3D12CommandList* const* host_lists, UINT count) {
if (!bx_console_shaders_enabled()) return;
std::vector<Draw> draws;
{
std::lock_guard<std::mutex> guard(g_list_lock);
for (UINT i = 0; i < count; ++i) {
auto it = g_draws.find(host_lists[i]);
if (it != g_draws.end()) draws.insert(draws.end(), it->second.begin(), it->second.end());
}
}
std::unordered_set<uint64_t> done; // entries written for this submission
for (const Draw& draw : draws) {
ID3D12Device* device = nullptr;
const BxConsoleUse* uses = nullptr;
size_t use_count = 0;
const char* key = "";
if (!bx_console_pipeline_info(draw.pipeline.get(), &device, &uses, &use_count, &key)) continue;
for (size_t u = 0; u < use_count; ++u) {
if (uses[u].param >= kTables || !draw.tables[uses[u].param]) continue;
const uint64_t entry = draw.tables[uses[u].param] + static_cast<uint64_t>(kDescriptorSize) * uses[u].entry;
if (!bx_xbox_title_descriptors(entry, 1)) continue;
if (!done.insert(entry * 2 + (uses[u].texture ? 1 : 0)).second) continue;
resolve(device, key, uses[u], entry);
}
}
}
+96 -12
View File
@@ -11,11 +11,21 @@
#include "console_formats.h"
#include "xbox_facade.h"
#include "console_pipelines.h"
#include "gdk_xg.h"
#include <atomic>
#include <cstdio>
#include <vector>
namespace {
/* The format a view has: its own, or the resource's when the view names none. */
DXGI_FORMAT view_format(ID3D12Resource* host_resource, DXGI_FORMAT format) {
if (format != DXGI_FORMAT_UNKNOWN || !host_resource) return format;
return host_resource->GetDesc().Format;
}
} // namespace
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);
@@ -74,6 +84,68 @@ private:
std::vector<Desc> copy_;
};
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC& d) { return d; }
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC1& d) {
D3D12_RESOURCE_DESC out{};
out.Dimension = d.Dimension;
out.Alignment = d.Alignment;
out.Width = d.Width;
out.Height = d.Height;
out.DepthOrArraySize = d.DepthOrArraySize;
out.MipLevels = d.MipLevels;
out.Format = d.Format;
out.SampleDesc = d.SampleDesc;
out.Layout = d.Layout;
out.Flags = d.Flags;
return out;
}
/* Allocation info for descriptions that include a console texture layout. The console sizes come
from the GDK's XG (gdk_xg.h); other descriptions keep the host's answer, one at a time. The
total follows Direct3D 12: each resource at its alignment, in order; the total alignment is the
largest. Returns false (the host answers everything) when no description has a console layout
or XG is not loaded. */
template <typename Desc>
bool console_allocation(ID3D12Device* device, UINT mask, UINT count, const Desc* descs, D3D12_RESOURCE_ALLOCATION_INFO* total,
D3D12_RESOURCE_ALLOCATION_INFO1* each, const char* method) {
if (!descs || !count || !bx_gdk_xg_available()) return false;
bool any = false;
for (UINT i = 0; i < count && !any; ++i) any = bx_is_console_texture_layout(as_desc(descs[i]));
if (!any) return false;
uint64_t offset = 0, max_alignment = 0;
for (UINT i = 0; i < count; ++i) {
const D3D12_RESOURCE_DESC desc = as_desc(descs[i]);
uint64_t size = 0, alignment = 0;
if (!bx_is_console_texture_layout(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
D3D12_RESOURCE_DESC host = desc;
if (bx_is_console_only_format(host.Format)) host.Format = bx_host_resource_format(host.Format);
if (bx_is_console_texture_layout(host)) host.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
D3D12_RESOURCE_ALLOCATION_INFO one{};
device->GetResourceAllocationInfo(&one, mask, 1, &host);
size = one.SizeInBytes;
alignment = one.Alignment;
} else {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 24) {
char detail[192];
std::snprintf(detail, sizeof(detail), "%s %llux%ux%u mips=%u format=%d layout=0x%x: console size %llu, alignment %llu",
method, static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
static_cast<int>(desc.Format), static_cast<UINT>(desc.Layout), static_cast<unsigned long long>(size),
static_cast<unsigned long long>(alignment));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_allocation", detail);
}
}
if (size == UINT64_MAX || !alignment) return false;
offset = (offset + alignment - 1) / alignment * alignment;
if (each) each[i] = D3D12_RESOURCE_ALLOCATION_INFO1{offset, alignment, size};
offset += size;
if (alignment > max_alignment) max_alignment = alignment;
}
total->SizeInBytes = offset;
total->Alignment = max_alignment;
return true;
}
} // namespace
extern "C" {
@@ -81,8 +153,11 @@ extern "C" {
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
const D3D12_RESOURCE_DESC* descs) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, nullptr, "GetResourceAllocationInfo")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, mask, count, host.get());
return result;
}
@@ -90,8 +165,11 @@ D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_all
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info1(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo1")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, mask, count, host.get(), each);
return result;
}
@@ -99,8 +177,11 @@ D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_all
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info2(
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
D3D12_RESOURCE_ALLOCATION_INFO result{};
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo2")) {
return result;
}
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, mask, count, host.get(), each);
return result;
}
@@ -135,9 +216,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID
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));
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc = host.of(desc, "CreateShaderResourceView");
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
bx_console_mark_srv(dest.ptr, host_resource, host_desc);
}
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
@@ -154,9 +236,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D
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));
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
const D3D12_RENDER_TARGET_VIEW_DESC* host_desc = host.of(desc, "CreateRenderTargetView");
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
bx_console_rtv_created(bx_xbox_host_cpu_handle(dest).ptr, view_format(host_resource, host_desc ? host_desc->Format : DXGI_FORMAT_UNKNOWN));
}
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
@@ -164,9 +247,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D
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));
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
const D3D12_DEPTH_STENCIL_VIEW_DESC* host_desc = host.of(desc, "CreateDepthStencilView");
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
bx_console_dsv_created(bx_xbox_host_cpu_handle(dest).ptr, view_format(host_resource, host_desc ? host_desc->Format : DXGI_FORMAT_UNKNOWN));
}
} // extern "C"
+756
View File
@@ -0,0 +1,756 @@
/*
* Console graphics pipelines translated at first draw (#720). Opt-in: BX_CONSOLE_SHADERS=1.
*
* A title's pipelines carry console shaders (RDNA 2 code), which the shader gate refuses. A
* refused stream pipeline that is a plain vertex/pixel pair is kept here with its stream. When
* it is first drawn:
* 1. bx_shader_bridge.dll translates the pair to HLSL (bx_shader_translate_pair);
* 2. the HLSL is compiled to DXIL with dxcompiler.dll, the GDK's PC compiler that `bx-cli run`
* stages beside the shims. Compiled shaders are kept on disk, named by the FNV-1a hash of
* their source, so a later run compiles nothing it has seen and a translator change can
* never reuse an old result;
* 3. a host pipeline is created from the title's own stream with three substitutions: the two
* shaders, the input layout the translated vertex shader expects, and the formats of the
* render targets bound at the draw (the title binds targets whose formats differ from the
* ones a pipeline was created for, and a Metal pipeline must match its attachments). One
* host pipeline is kept per bound format set.
* Translation happens at the draw and not at creation because a title creates far more
* pipelines than it draws.
*
* Translated shaders read entry k of root parameter i's descriptor table as register k of space
* 100 + i (b for constant buffers, t for textures), and sample with s0 of space 100. Every root
* signature is therefore widened with those ranges, overlapping the title's own, and with one
* static sampler. That sampler is linear and wrapping whatever the title asked for: the console
* sampler a shader names is not decoded yet.
*
* Root signature layouts (#715). A console shader's root arguments are packed values in
* root-parameter order, so which register holds which parameter depends on the parameter list
* (docs/research/console-shader-abi.md). Each root signature's list is kept with its host object
* and handed to the translator (bx_shader_translate_pair_rooted). Root CBVs, SRVs, UAVs and
* constants are then declared at the title's own registers, which the root signature already
* has; only descriptor tables need the widening above.
*
* Not handled here, and logged when met: pipelines with other stages, stream output or view
* instancing; table entries beyond the widened range.
*/
#include "console_pipelines.h"
#include "console_formats.h"
#include "proxy.h"
#include "xbox_facade.h"
#include "bx_log.h"
#include "bx_shader_bridge.h"
#include <dxcapi.h>
#include <atomic>
#include <memory>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <string>
#include <unordered_map>
namespace {
constexpr UINT kWidenedEntries = 8; // registers 0..7 of each widened space
constexpr UINT kFirstSpace = 100; // space of root parameter 0's table
bool env_is_one(const char* name) {
char value[8] = {};
const DWORD n = GetEnvironmentVariableA(name, value, sizeof(value));
return n == 1 && value[0] == '1';
}
void log(bx_log_level_t level, const char* event, const char* fmt, ...) {
char detail[700];
va_list args;
va_start(args, fmt);
std::vsnprintf(detail, sizeof(detail), fmt, args);
va_end(args);
bx_log_emit(level, "d3d12_xs", event, detail);
}
/* Logs the 1st, 2nd, 4th, ... occurrence, with the running total. */
bool sampled(std::atomic<uint64_t>& counter, uint64_t* total) {
*total = ++counter;
return (*total & (*total - 1)) == 0;
}
uint64_t fnv1a64(const void* data, size_t size) {
uint64_t h = 14695981039346656037ull;
for (size_t i = 0; i < size; ++i) h = (h ^ static_cast<const uint8_t*>(data)[i]) * 1099511628211ull;
return h;
}
/* A library beside d3d12_xs.dll, where bx-cli stages the bridge and the compiler; otherwise by
the process's search path (a shim loaded from the executable's own folder is not in the staged
one). */
HMODULE load_beside(const wchar_t* name) {
HMODULE self = nullptr;
wchar_t path[MAX_PATH];
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&load_beside), &self)) {
const DWORD length = GetModuleFileNameW(self, path, MAX_PATH);
wchar_t* slash = length && length < MAX_PATH ? std::wcsrchr(path, L'\\') : nullptr;
if (slash && static_cast<size_t>(slash + 1 - path) + std::wcslen(name) + 1 <= MAX_PATH) {
std::wcscpy(slash + 1, name);
if (HMODULE module = LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH)) return module;
}
}
return LoadLibraryW(name);
}
/* ---- Translation and compilation -------------------------------------------------------- */
using TranslateFn = bx_shader_status_t (*)(const uint8_t*, size_t, const uint8_t*, size_t, bx_shader_pair_translation_t*);
using FreeTranslationFn = void (*)(bx_shader_pair_translation_t*);
using TranslateRootedFn = bx_shader_status_t (*)(const uint8_t*, size_t, const uint8_t*, size_t, const bx_shader_root_layout_t*,
bx_shader_pair_translation_t*);
struct Tools {
TranslateFn translate = nullptr;
TranslateRootedFn translate_rooted = nullptr; // absent in an older bridge: every parameter is then taken for a table
FreeTranslationFn release = nullptr;
DxcCreateInstanceProc dxc = nullptr;
};
const Tools& tools() {
static const Tools loaded = [] {
Tools t;
if (HMODULE bridge = load_beside(L"bx_shader_bridge.dll")) {
t.translate = reinterpret_cast<TranslateFn>(reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_translate_pair")));
t.release = reinterpret_cast<FreeTranslationFn>(
reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_free_pair_translation")));
t.translate_rooted = reinterpret_cast<TranslateRootedFn>(
reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_translate_pair_rooted")));
}
if (HMODULE dxc = load_beside(L"dxcompiler.dll")) {
t.dxc = reinterpret_cast<DxcCreateInstanceProc>(reinterpret_cast<void*>(GetProcAddress(dxc, "DxcCreateInstance")));
}
if (!t.translate || !t.release) {
log(BX_LOG_WARN, "console_shaders", "bx_shader_bridge.dll has no bx_shader_translate_pair; console pipelines stay undrawn");
}
if (!t.dxc) {
log(BX_LOG_WARN, "console_shaders",
"dxcompiler.dll not found (bx-cli run stages the GDK's for the target build, or with "
"--gdk-libraries); console pipelines stay undrawn");
}
return t;
}();
return loaded;
}
/* The folder compiled shaders are kept in: BX_SHADER_CACHE, or
%LOCALAPPDATA%\BetterXen\shader-cache. Empty when neither can be made. */
const std::string& cache_folder() {
static const std::string folder = [] {
char value[MAX_PATH] = {};
DWORD n = GetEnvironmentVariableA("BX_SHADER_CACHE", value, sizeof(value));
std::string path;
if (n > 0 && n < sizeof(value)) {
path = value;
} else {
n = GetEnvironmentVariableA("LOCALAPPDATA", value, sizeof(value));
if (n == 0 || n >= sizeof(value)) return std::string();
path = std::string(value) + "\\BetterXen";
CreateDirectoryA(path.c_str(), nullptr);
path += "\\shader-cache";
}
CreateDirectoryA(path.c_str(), nullptr);
const DWORD attributes = GetFileAttributesA(path.c_str());
if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
log(BX_LOG_WARN, "console_shaders", "shader cache folder cannot be created; shaders are compiled every run");
return std::string();
}
return path;
}();
return folder;
}
bool read_file(const std::string& path, std::vector<uint8_t>& out) {
HANDLE file = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return false;
LARGE_INTEGER size{};
bool ok = GetFileSizeEx(file, &size) && size.QuadPart > 0 && size.QuadPart < (64ll << 20);
if (ok) {
out.resize(static_cast<size_t>(size.QuadPart));
DWORD got = 0;
ok = ReadFile(file, out.data(), static_cast<DWORD>(out.size()), &got, nullptr) && got == out.size();
}
CloseHandle(file);
return ok;
}
/* Writes through a temporary name, so a reader never sees half a file. */
void write_file(const std::string& path, const void* data, size_t size) {
char temporary[MAX_PATH + 32];
std::snprintf(temporary, sizeof(temporary), "%s.%lu.tmp", path.c_str(), static_cast<unsigned long>(GetCurrentThreadId()));
HANDLE file = CreateFileA(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file == INVALID_HANDLE_VALUE) return;
DWORD put = 0;
const bool ok = WriteFile(file, data, static_cast<DWORD>(size), &put, nullptr) && put == size;
CloseHandle(file);
if (!ok || !MoveFileExA(temporary, path.c_str(), MOVEFILE_REPLACE_EXISTING)) DeleteFileA(temporary);
}
std::atomic<uint64_t> g_compiled{0};
std::atomic<uint64_t> g_from_cache{0};
/* HLSL to DXIL (entry `main`), from the disk cache when this source was compiled before. */
bool compile(const uint8_t* source, size_t size, bool pixel, std::vector<uint8_t>& out, std::string& why) {
char name[48];
std::snprintf(name, sizeof(name), "\\%016llx.%s.dxil", static_cast<unsigned long long>(fnv1a64(source, size)), pixel ? "ps" : "vs");
const std::string cached = cache_folder().empty() ? std::string() : cache_folder() + name;
if (!cached.empty() && read_file(cached, out)) {
++g_from_cache;
return true;
}
const Tools& t = tools();
if (!t.dxc) {
why = "no dxcompiler.dll";
return false;
}
IDxcCompiler3* compiler = nullptr;
HRESULT hr = t.dxc(CLSID_DxcCompiler, __uuidof(IDxcCompiler3), reinterpret_cast<void**>(&compiler));
if (FAILED(hr) || !compiler) {
why = "DxcCreateInstance failed";
return false;
}
const DxcBuffer buffer{source, size, DXC_CP_UTF8};
LPCWSTR arguments[] = {L"-T", pixel ? L"ps_6_0" : L"vs_6_0", L"-E", L"main"};
IDxcResult* result = nullptr;
hr = compiler->Compile(&buffer, arguments, 4, nullptr, __uuidof(IDxcResult), reinterpret_cast<void**>(&result));
HRESULT status = hr;
if (SUCCEEDED(hr) && result) result->GetStatus(&status);
bool ok = false;
if (SUCCEEDED(status) && result) {
IDxcBlob* code = nullptr;
if (SUCCEEDED(result->GetResult(&code)) && code && code->GetBufferSize()) {
const auto* bytes = static_cast<const uint8_t*>(code->GetBufferPointer());
out.assign(bytes, bytes + code->GetBufferSize());
ok = true;
}
if (code) code->Release();
}
if (!ok) {
why = "the compiler refused the translated source";
IDxcBlobEncoding* errors = nullptr;
if (result && SUCCEEDED(result->GetErrorBuffer(&errors)) && errors && errors->GetBufferSize()) {
why += ": ";
why.append(static_cast<const char*>(errors->GetBufferPointer()), errors->GetBufferSize() < 300 ? errors->GetBufferSize() : 300);
}
if (errors) errors->Release();
}
if (result) result->Release();
compiler->Release();
if (ok) {
++g_compiled;
if (!cached.empty()) write_file(cached, out.data(), out.size());
}
return ok;
}
/* ---- Render targets bound per list ------------------------------------------------------- */
struct Targets {
bool known = false;
UINT count = 0;
DXGI_FORMAT rtv[8] = {};
DXGI_FORMAT dsv = DXGI_FORMAT_UNKNOWN;
};
std::mutex g_target_lock;
std::unordered_map<SIZE_T, DXGI_FORMAT> g_rtv_formats;
std::unordered_map<SIZE_T, DXGI_FORMAT> g_dsv_formats;
std::unordered_map<const void*, Targets> g_list_targets;
/* ---- Root signatures ----------------------------------------------------------------------- */
using DeserializerFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, REFIID, void**);
using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
template <typename Fn>
Fn host_d3d12(const char* name) {
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
return d3d12 ? reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(d3d12, name))) : nullptr;
}
/* What the translator needs to know about a root signature: its parameters and flags. */
struct RootLayout {
std::vector<bx_shader_root_parameter_t> parameters;
UINT flags = 0;
};
std::mutex g_root_lock;
std::unordered_map<const void*, std::shared_ptr<RootLayout>> g_root_layouts; // by host root signature
/* The layout of a serialized root signature, or nullptr when it cannot be read. */
std::shared_ptr<RootLayout> read_layout(const void* blob, size_t size) {
static const DeserializerFn deserialize = host_d3d12<DeserializerFn>("D3D12CreateVersionedRootSignatureDeserializer");
if (!deserialize || !blob || !size) return nullptr;
ID3D12VersionedRootSignatureDeserializer* d = nullptr;
if (FAILED(deserialize(blob, size, __uuidof(ID3D12VersionedRootSignatureDeserializer), reinterpret_cast<void**>(&d))) || !d) {
return nullptr;
}
std::shared_ptr<RootLayout> layout;
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* v = nullptr;
if (SUCCEEDED(d->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &v)) && v) {
layout = std::make_shared<RootLayout>();
layout->flags = static_cast<UINT>(v->Desc_1_1.Flags);
for (UINT i = 0; i < v->Desc_1_1.NumParameters; ++i) {
const D3D12_ROOT_PARAMETER1& p = v->Desc_1_1.pParameters[i];
bx_shader_root_parameter_t out{};
out.type = static_cast<uint32_t>(p.ParameterType);
if (p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) {
out.num_32bit_values = p.Constants.Num32BitValues;
out.shader_register = p.Constants.ShaderRegister;
out.register_space = p.Constants.RegisterSpace;
} else if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) {
out.shader_register = p.Descriptor.ShaderRegister;
out.register_space = p.Descriptor.RegisterSpace;
}
layout->parameters.push_back(out);
}
}
d->Release();
return layout;
}
/* The title's root signature with the translated shaders' ranges and sampler added, or nullptr. */
ID3DBlob* widen(const void* blob, size_t size) {
static const DeserializerFn deserialize = host_d3d12<DeserializerFn>("D3D12CreateVersionedRootSignatureDeserializer");
static const SerializeFn serialize = host_d3d12<SerializeFn>("D3D12SerializeVersionedRootSignature");
if (!deserialize || !serialize) return nullptr;
ID3D12VersionedRootSignatureDeserializer* d = nullptr;
if (FAILED(deserialize(blob, size, __uuidof(ID3D12VersionedRootSignatureDeserializer), reinterpret_cast<void**>(&d))) || !d) {
return nullptr;
}
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* v = nullptr;
ID3DBlob* out = nullptr;
if (SUCCEEDED(d->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &v)) && v) {
const D3D12_ROOT_SIGNATURE_DESC1& src = v->Desc_1_1;
std::vector<D3D12_ROOT_PARAMETER1> params(src.pParameters, src.pParameters + src.NumParameters);
std::vector<std::vector<D3D12_DESCRIPTOR_RANGE1>> ranges(params.size());
for (size_t i = 0; i < params.size(); ++i) {
if (params[i].ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) continue;
const auto& table = params[i].DescriptorTable;
if (table.NumDescriptorRanges && table.pDescriptorRanges[0].RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) continue;
ranges[i].assign(table.pDescriptorRanges, table.pDescriptorRanges + table.NumDescriptorRanges);
for (D3D12_DESCRIPTOR_RANGE_TYPE type : {D3D12_DESCRIPTOR_RANGE_TYPE_CBV, D3D12_DESCRIPTOR_RANGE_TYPE_SRV}) {
D3D12_DESCRIPTOR_RANGE1 r{};
r.RangeType = type;
r.NumDescriptors = kWidenedEntries;
r.BaseShaderRegister = 0;
r.RegisterSpace = kFirstSpace + static_cast<UINT>(i);
r.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
r.OffsetInDescriptorsFromTableStart = 0;
ranges[i].push_back(r);
}
params[i].DescriptorTable.NumDescriptorRanges = static_cast<UINT>(ranges[i].size());
params[i].DescriptorTable.pDescriptorRanges = ranges[i].data();
}
std::vector<D3D12_STATIC_SAMPLER_DESC> samplers(src.pStaticSamplers, src.pStaticSamplers + src.NumStaticSamplers);
D3D12_STATIC_SAMPLER_DESC s{};
s.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
s.AddressU = s.AddressV = s.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
s.MaxLOD = D3D12_FLOAT32_MAX;
s.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
s.ShaderRegister = 0;
s.RegisterSpace = kFirstSpace;
s.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
samplers.push_back(s);
D3D12_VERSIONED_ROOT_SIGNATURE_DESC wide{};
wide.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
wide.Desc_1_1 = src;
wide.Desc_1_1.NumParameters = static_cast<UINT>(params.size());
wide.Desc_1_1.pParameters = params.data();
wide.Desc_1_1.NumStaticSamplers = static_cast<UINT>(samplers.size());
wide.Desc_1_1.pStaticSamplers = samplers.data();
ID3DBlob* errors = nullptr;
if (FAILED(serialize(&wide, &out, &errors))) out = nullptr;
if (errors) errors->Release();
}
d->Release();
return out;
}
} // namespace
bool bx_console_shaders_enabled() {
static const bool enabled = [] {
const bool on = env_is_one("BX_CONSOLE_SHADERS");
if (on) log(BX_LOG_INFO, "console_shaders", "enabled: refused vertex/pixel pipelines are translated when first drawn");
return on;
}();
return enabled;
}
namespace {
/* Keeps the layout of the title's blob with the host root signature just created from it. */
void remember_layout(void* host_root, const void* blob, size_t size) {
std::shared_ptr<RootLayout> layout = read_layout(blob, size);
std::lock_guard<std::mutex> guard(g_root_lock);
if (layout) {
g_root_layouts[host_root] = std::move(layout);
} else {
g_root_layouts.erase(host_root); // an address reused by a signature that cannot be read
}
}
} // namespace
HRESULT bx_console_create_root_signature(ID3D12Device* device, UINT node_mask, const void* blob, SIZE_T size, REFIID riid,
void** ppv) {
if (bx_console_shaders_enabled() && blob && size) {
static std::atomic<uint64_t> refused{0};
ID3DBlob* wide = widen(blob, size);
if (wide) {
const HRESULT hr = device->CreateRootSignature(node_mask, wide->GetBufferPointer(), wide->GetBufferSize(), riid, ppv);
wide->Release();
if (SUCCEEDED(hr)) {
remember_layout(*ppv, blob, size);
return hr;
}
}
uint64_t total = 0;
if (sampled(refused, &total)) {
log(BX_LOG_WARN, "console_root_signature",
"a root signature could not be widened for translated shaders (%s); the title's own is used; total=%llu",
wide ? "the host refused the widened form" : "it could not be read or serialized", static_cast<unsigned long long>(total));
}
const HRESULT hr = device->CreateRootSignature(node_mask, blob, size, riid, ppv);
if (SUCCEEDED(hr)) remember_layout(*ppv, blob, size);
return hr;
}
return device->CreateRootSignature(node_mask, blob, size, riid, ppv);
}
/* ---- Pipelines --------------------------------------------------------------------------- */
struct BxConsolePipeline {
ID3D12Device2* device = nullptr; // referenced
ID3D12RootSignature* root = nullptr; // host object, referenced
std::vector<uint8_t> stream; // host stream, shader slots patched per variant
size_t vs_at = SIZE_MAX, ps_at = SIZE_MAX, layout_at = SIZE_MAX, rt_at = SIZE_MAX, ds_at = SIZE_MAX;
std::vector<uint8_t> vs_code, ps_code; // the title's stages
std::vector<D3D12_INPUT_ELEMENT_DESC> title_elements;
std::mutex lock;
enum class State { Untried, Ready, Failed } state = State::Untried;
char key[40] = {};
std::vector<uint8_t> vs_dxil, ps_dxil;
std::vector<D3D12_INPUT_ELEMENT_DESC> elements; // the host input layout
std::vector<BxConsoleUse> uses; // table entries the shaders read
std::unordered_map<std::string, ID3D12PipelineState*> variants;
~BxConsolePipeline() {
for (auto& v : variants) {
if (v.second) v.second->Release();
}
if (root) root->Release();
if (device) device->Release();
}
};
std::shared_ptr<BxConsolePipeline> bx_console_pipeline_create(ID3D12Device* device, const std::vector<uint8_t>& stream,
const std::vector<size_t>& stage_offsets,
const std::vector<const char*>& stage_names, size_t root_offset) {
if (!bx_console_shaders_enabled() || !device || root_offset == SIZE_MAX) return nullptr;
auto p = std::make_shared<BxConsolePipeline>();
const char* unsupported = nullptr;
for (size_t i = 0; i < stage_offsets.size(); ++i) {
D3D12_SHADER_BYTECODE code{};
std::memcpy(&code, &stream[stage_offsets[i]], sizeof(code));
if (!code.pShaderBytecode || !code.BytecodeLength) continue;
const auto* bytes = static_cast<const uint8_t*>(code.pShaderBytecode);
if (std::strcmp(stage_names[i], "VS") == 0) {
p->vs_at = stage_offsets[i];
p->vs_code.assign(bytes, bytes + code.BytecodeLength);
} else if (std::strcmp(stage_names[i], "PS") == 0) {
p->ps_at = stage_offsets[i];
p->ps_code.assign(bytes, bytes + code.BytecodeLength);
} else {
unsupported = "a stage other than vertex and pixel";
}
}
if (!unsupported && (p->vs_code.empty() || p->ps_code.empty())) unsupported = "no vertex/pixel pair";
const size_t so_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT);
if (so_at != SIZE_MAX) {
D3D12_STREAM_OUTPUT_DESC so{};
std::memcpy(&so, &stream[so_at], sizeof(so));
if (so.NumEntries || so.NumStrides) unsupported = "stream output";
}
const size_t vi_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING);
if (vi_at != SIZE_MAX) {
D3D12_VIEW_INSTANCING_DESC vi{};
std::memcpy(&vi, &stream[vi_at], sizeof(vi));
if (vi.ViewInstanceCount) unsupported = "view instancing";
}
if (unsupported) {
static std::atomic<uint64_t> skipped{0};
uint64_t total = 0;
if (sampled(skipped, &total)) {
log(BX_LOG_WARN, "console_pipeline", "a refused pipeline is not translated: %s; total=%llu", unsupported,
static_cast<unsigned long long>(total));
}
return nullptr;
}
if (FAILED(device->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast<void**>(&p->device)))) return nullptr;
p->stream = stream;
// A cached blob belongs to the title's console pipeline, never to the host's.
const size_t cached_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO);
if (cached_at != SIZE_MAX) std::memset(&p->stream[cached_at], 0, sizeof(D3D12_CACHED_PIPELINE_STATE));
std::memcpy(&p->root, &p->stream[root_offset], sizeof(p->root));
if (!p->root) return nullptr;
p->root->AddRef();
p->layout_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT);
if (p->layout_at != SIZE_MAX) {
D3D12_INPUT_LAYOUT_DESC layout{};
std::memcpy(&layout, &p->stream[p->layout_at], sizeof(layout));
for (UINT k = 0; layout.pInputElementDescs && k < layout.NumElements; ++k) {
// The translated vertex shader names its inputs ATTR<k> in element order. The title's
// semantic names are not kept: their strings need not outlive the creation call.
D3D12_INPUT_ELEMENT_DESC e = layout.pInputElementDescs[k];
e.SemanticName = "ATTR";
e.SemanticIndex = k;
e.Format = bx_host_format(e.Format);
p->title_elements.push_back(e);
}
}
p->rt_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS);
if (p->rt_at != SIZE_MAX) {
D3D12_RT_FORMAT_ARRAY formats{};
std::memcpy(&formats, &p->stream[p->rt_at], sizeof(formats));
for (DXGI_FORMAT& f : formats.RTFormats) f = bx_host_format(f);
std::memcpy(&p->stream[p->rt_at], &formats, sizeof(formats));
}
p->ds_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT);
if (p->ds_at != SIZE_MAX) {
DXGI_FORMAT depth{};
std::memcpy(&depth, &p->stream[p->ds_at], sizeof(depth));
depth = bx_host_format(depth);
std::memcpy(&p->stream[p->ds_at], &depth, sizeof(depth));
}
std::snprintf(p->key, sizeof(p->key), "%016llx_%016llx", static_cast<unsigned long long>(fnv1a64(p->vs_code.data(), p->vs_code.size())),
static_cast<unsigned long long>(fnv1a64(p->ps_code.data(), p->ps_code.size())));
return p;
}
namespace {
std::atomic<uint64_t> g_translated{0};
std::atomic<uint64_t> g_untranslated{0};
/* Translates and compiles the pair, and builds the host input layout. Called once, locked. */
void prepare(BxConsolePipeline* p) {
p->state = BxConsolePipeline::State::Failed;
const Tools& t = tools();
uint64_t total = 0;
if (!t.translate || !t.release) return;
const ULONGLONG started = GetTickCount64();
bx_shader_pair_translation_t out{};
// With the root signature's layout when both sides have it; otherwise as a signature of tables.
std::shared_ptr<RootLayout> root;
{
std::lock_guard<std::mutex> guard(g_root_lock);
auto it = g_root_layouts.find(p->root);
if (it != g_root_layouts.end()) root = it->second;
}
bx_shader_status_t status;
if (root && t.translate_rooted) {
const bx_shader_root_layout_t layout{root->parameters.data(), static_cast<uint32_t>(root->parameters.size()), root->flags};
status = t.translate_rooted(p->vs_code.data(), p->vs_code.size(), p->ps_code.data(), p->ps_code.size(), &layout, &out);
} else {
status = t.translate(p->vs_code.data(), p->vs_code.size(), p->ps_code.data(), p->ps_code.size(), &out);
}
std::string why;
if (status == BX_SHADER_OK) {
const std::string layout(reinterpret_cast<const char*>(out.layout), out.layout_len);
const uint64_t before = g_compiled.load();
const bool compiled = compile(out.vs_hlsl, out.vs_hlsl_len, false, p->vs_dxil, why) &&
compile(out.ps_hlsl, out.ps_hlsl_len, true, p->ps_dxil, why);
unsigned fetch = 0;
bool fetched = false;
for (size_t at = 0; compiled && at < layout.size();) {
const size_t end = layout.find('\n', at);
const std::string line = layout.substr(at, end == std::string::npos ? std::string::npos : end - at);
at = end == std::string::npos ? layout.size() : end + 1;
unsigned a = 0, b = 0, c = 0, d = 0;
char kind[8] = {};
if (std::sscanf(line.c_str(), "FETCH %u", &fetch) == 1) {
fetched = true;
} else if (std::sscanf(line.c_str(), "ATTR %u %u %u %u", &a, &b, &c, &d) == 4) {
D3D12_INPUT_ELEMENT_DESC e{};
e.SemanticName = "ATTR";
e.SemanticIndex = a;
e.Format = static_cast<DXGI_FORMAT>(b);
e.InputSlot = c;
e.AlignedByteOffset = d;
e.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
p->elements.push_back(e);
} else if (std::sscanf(line.c_str(), "USE %7s %u %u", kind, &a, &b) >= 2 &&
(std::strcmp(kind, "CB") == 0 || std::strcmp(kind, "TEX") == 0)) {
// Only CB and TEX lines name descriptor-table entries. `USE ROOT <parameter>` is a
// root constants or root descriptor parameter, which the host root signature binds
// as it is (abi/include/bx_shader_bridge.h); other kinds are ignored.
const int numbers = std::sscanf(line.c_str(), "USE %7s %u %u", kind, &a, &b) - 1;
const unsigned entry = numbers == 2 ? b : a;
p->uses.push_back({std::strcmp(kind, "TEX") == 0, numbers == 2 ? a : 0, entry});
if (entry >= kWidenedEntries) {
char text[96];
std::snprintf(text, sizeof(text), "it reads table entry %u, beyond the %u widened ones", entry, kWidenedEntries);
why = text;
}
}
}
if (compiled && why.empty() && fetched) {
if (fetch > p->title_elements.size()) {
char text[96];
std::snprintf(text, sizeof(text), "the vertex shader fetches %u attributes, the pipeline has %zu", fetch,
p->title_elements.size());
why = text;
} else {
p->elements.assign(p->title_elements.begin(), p->title_elements.begin() + fetch);
}
}
if (compiled && why.empty()) {
p->state = BxConsolePipeline::State::Ready;
if (sampled(g_translated, &total)) {
log(BX_LOG_INFO, "console_pipeline", "pipeline %s translated in %llu ms (%s); total=%llu, compiled=%llu, from cache=%llu",
p->key, static_cast<unsigned long long>(GetTickCount64() - started),
g_compiled.load() == before ? "shaders from the disk cache" : "compiled", static_cast<unsigned long long>(total),
static_cast<unsigned long long>(g_compiled.load()), static_cast<unsigned long long>(g_from_cache.load()));
}
}
} else if (status == BX_SHADER_ERR_UNSUPPORTED) {
why.assign(reinterpret_cast<const char*>(out.reason), out.reason_len);
} else {
why = "the stages are not console shader code";
}
t.release(&out);
if (p->state != BxConsolePipeline::State::Ready && sampled(g_untranslated, &total)) {
log(BX_LOG_WARN, "console_pipeline", "pipeline %s is not drawn: %.500s; total=%llu", p->key, why.c_str(),
static_cast<unsigned long long>(total));
}
}
} // namespace
ID3D12PipelineState* bx_console_pipeline_for_draw(BxConsolePipeline* p, ID3D12GraphicsCommandList* list) {
if (!p) return nullptr;
Targets bound;
{
std::lock_guard<std::mutex> guard(g_target_lock);
auto it = g_list_targets.find(list);
if (it != g_list_targets.end()) bound = it->second;
}
std::lock_guard<std::mutex> guard(p->lock);
if (p->state == BxConsolePipeline::State::Untried) prepare(p);
if (p->state != BxConsolePipeline::State::Ready) return nullptr;
char formats[96] = "declared";
if (bound.known) {
int n = std::snprintf(formats, sizeof(formats), "%u", static_cast<unsigned>(bound.dsv));
for (UINT i = 0; i < bound.count; ++i) {
n += std::snprintf(formats + n, sizeof(formats) - static_cast<size_t>(n), ",%u", static_cast<unsigned>(bound.rtv[i]));
}
}
auto found = p->variants.find(formats);
if (found != p->variants.end()) return found->second;
std::vector<uint8_t> stream = p->stream;
const D3D12_SHADER_BYTECODE vs{p->vs_dxil.data(), p->vs_dxil.size()};
const D3D12_SHADER_BYTECODE ps{p->ps_dxil.data(), p->ps_dxil.size()};
std::memcpy(&stream[p->vs_at], &vs, sizeof(vs));
std::memcpy(&stream[p->ps_at], &ps, sizeof(ps));
if (p->layout_at != SIZE_MAX) {
const D3D12_INPUT_LAYOUT_DESC layout{p->elements.data(), static_cast<UINT>(p->elements.size())};
std::memcpy(&stream[p->layout_at], &layout, sizeof(layout));
}
if (bound.known && p->rt_at != SIZE_MAX) {
D3D12_RT_FORMAT_ARRAY actual{};
actual.NumRenderTargets = bound.count;
for (UINT i = 0; i < bound.count; ++i) actual.RTFormats[i] = bound.rtv[i];
std::memcpy(&stream[p->rt_at], &actual, sizeof(actual));
}
if (bound.known && p->ds_at != SIZE_MAX) std::memcpy(&stream[p->ds_at], &bound.dsv, sizeof(bound.dsv));
const D3D12_PIPELINE_STATE_STREAM_DESC desc{stream.size(), stream.data()};
ID3D12PipelineState* host = nullptr;
const HRESULT hr = p->device->CreatePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&host));
if (FAILED(hr)) {
host = nullptr;
log(BX_LOG_WARN, "console_pipeline", "pipeline %s for formats %s: the host refused the translated pipeline hr=0x%08lx", p->key,
formats, static_cast<unsigned long>(hr));
} else {
bx_xbox_rect_pipeline_created(host, p->elements.data(), static_cast<UINT>(p->elements.size()));
}
p->variants[formats] = host; // a refusal is remembered too, so it is tried and logged once
return host;
}
bool bx_console_pipeline_info(BxConsolePipeline* p, ID3D12Device** device, const BxConsoleUse** uses, size_t* count,
const char** key) {
if (!p) return false;
std::lock_guard<std::mutex> guard(p->lock);
if (p->state != BxConsolePipeline::State::Ready) return false;
*device = p->device;
*uses = p->uses.data(); // not changed once the pipeline is ready
*count = p->uses.size();
*key = p->key;
return true;
}
/* ---- Render-target bookkeeping --------------------------------------------------------------- */
void bx_console_rtv_created(SIZE_T host_cpu, DXGI_FORMAT format) {
if (!bx_console_shaders_enabled()) return;
std::lock_guard<std::mutex> guard(g_target_lock);
g_rtv_formats[host_cpu] = format;
}
void bx_console_dsv_created(SIZE_T host_cpu, DXGI_FORMAT format) {
if (!bx_console_shaders_enabled()) return;
std::lock_guard<std::mutex> guard(g_target_lock);
g_dsv_formats[host_cpu] = format;
}
void bx_console_list_targets(ID3D12GraphicsCommandList* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* host_rtvs,
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* host_dsv) {
if (!bx_console_shaders_enabled()) return;
UINT increment = 0;
if (single_range && count > 1 && host_rtvs) {
ID3D12Device* device = nullptr;
if (SUCCEEDED(list->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) && device) {
increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
device->Release();
}
}
std::lock_guard<std::mutex> guard(g_target_lock);
Targets t;
t.count = count > 8 ? 8 : count;
t.known = true;
for (UINT i = 0; i < t.count; ++i) {
// A single range is `count` consecutive descriptors starting at the first handle.
const SIZE_T handle = !host_rtvs ? 0 : single_range ? host_rtvs[0].ptr + static_cast<SIZE_T>(i) * increment : host_rtvs[i].ptr;
auto it = g_rtv_formats.find(handle);
if (it == g_rtv_formats.end() || it->second == DXGI_FORMAT_UNKNOWN) {
t.known = false; // a view this layer did not see: keep the pipeline's declared formats
break;
}
t.rtv[i] = it->second;
}
if (host_dsv) {
auto it = g_dsv_formats.find(host_dsv->ptr);
if (it == g_dsv_formats.end()) {
t.known = false;
} else {
t.dsv = it->second;
}
}
g_list_targets[list] = t;
}
void bx_console_list_forget(ID3D12GraphicsCommandList* list) {
std::lock_guard<std::mutex> guard(g_target_lock);
g_list_targets.erase(list);
}
+64
View File
@@ -0,0 +1,64 @@
#pragma once
/*
* Console graphics pipelines translated at first draw (#720). See console_pipelines.cpp.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <vector>
/* True when BX_CONSOLE_SHADERS=1 (opt-in while the draw path is being completed). */
bool bx_console_shaders_enabled();
/* CreateRootSignature on the host device. With console shaders enabled the root signature is
widened with the register spaces translated shaders use; if the host refuses the widened form,
the title's own is created and that is logged. `*ppv` is the host object (not wrapped). */
HRESULT bx_console_create_root_signature(ID3D12Device* device, UINT node_mask, const void* blob, SIZE_T size, REFIID riid,
void** ppv);
/* A stream pipeline the shader gate refused, kept to be translated when it is first drawn. */
struct BxConsolePipeline;
/* `stream` is the host form of the title's stream (root signature unwrapped, topology type
converted) with the title's shader stages still in it. Returns nullptr when console shaders
are disabled or the pipeline is not a plain vertex/pixel pair. */
std::shared_ptr<BxConsolePipeline> bx_console_pipeline_create(ID3D12Device* device, const std::vector<uint8_t>& stream,
const std::vector<size_t>& stage_offsets,
const std::vector<const char*>& stage_names, size_t root_offset);
/* The host pipeline for a draw on `list` with its bound render targets: translated, compiled and
created on first use. nullptr when the pipeline cannot be translated or created (logged); the
draw is then skipped by the caller. */
ID3D12PipelineState* bx_console_pipeline_for_draw(BxConsolePipeline* pipeline, ID3D12GraphicsCommandList* list);
/* Render-target bookkeeping (host handles), so a host pipeline matches the bound formats. */
void bx_console_rtv_created(SIZE_T host_cpu, DXGI_FORMAT format);
void bx_console_dsv_created(SIZE_T host_cpu, DXGI_FORMAT format);
void bx_console_list_targets(ID3D12GraphicsCommandList* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* host_rtvs,
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* host_dsv);
void bx_console_list_forget(ID3D12GraphicsCommandList* list);
/* A descriptor-table entry a translated pipeline's shaders read (a `USE` line of its layout). */
struct BxConsoleUse {
bool texture; // false: constant buffer
UINT param; // root parameter of the table
UINT entry; // index in the table
};
/* What a translated pipeline reads, once it has been translated; false before that. */
bool bx_console_pipeline_info(BxConsolePipeline* pipeline, ID3D12Device** device, const BxConsoleUse** uses, size_t* count,
const char** key);
/* console_descriptors.cpp: descriptors the title copies itself. `title_handle` is the title's
descriptor handle (an address in its descriptor memory). */
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc);
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc);
/* Direct3D copied `count` descriptors between title handles: the title-side bytes follow. */
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count);
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle);
void bx_console_record_draw(ID3D12GraphicsCommandList* list, const std::shared_ptr<BxConsolePipeline>& pipeline);
void bx_console_descriptors_reset(ID3D12GraphicsCommandList* list);
/* Before the host executes `host_lists`: writes the views their translated draws read. */
void bx_console_submit(ID3D12CommandList* const* host_lists, UINT count);
+5
View File
@@ -79,7 +79,12 @@ extern "C" {
* models (or one the host device answers); anything else fails with E_NOINTERFACE and a logged
* IID.
*/
extern "C" void bx_gdk_xg_enable_locking();
HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid, void** ppv) {
// The title creates XG texture computers on its own threads; the shim does too (gdk_xg.h).
static const bool xg_locking = (bx_gdk_xg_enable_locking(), true);
(void)xg_locking;
if (!ppv) {
return E_POINTER;
}
+116 -9
View File
@@ -14,6 +14,8 @@
*/
#include "xbox_facade.h"
#include "console_pipelines.h"
#include <atomic>
#include <cstdio>
#include <cstring>
@@ -77,6 +79,12 @@ void log_untranslated(const char* what, uint64_t value) {
} // namespace
bool bx_xbox_title_descriptors(uint64_t address, UINT count) {
std::lock_guard<std::mutex> guard(g_lock);
const Heap* h = find_locked(static_cast<uintptr_t>(address));
return h && h->xbox_size == 32 && address + 32ull * count <= h->base + static_cast<uint64_t>(h->count) * h->xbox_size;
}
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type) {
switch (type) {
case D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV: return 32;
@@ -187,6 +195,7 @@ void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, co
host_desc.BufferLocation = bx_xbox_host_gpu_va(desc->BufferLocation);
}
bx_xbox_host<ID3D12Device>(self)->CreateConstantBufferView(desc ? &host_desc : nullptr, bx_xbox_host_cpu_handle(dest));
if (desc) bx_console_mark_cbv(dest.ptr, desc->BufferLocation, host_desc);
}
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
@@ -201,6 +210,28 @@ void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ran
for (UINT i = 0; i < src_ranges; ++i) src[i] = bx_xbox_host_cpu_handle(src_starts[i]);
bx_xbox_host<ID3D12Device>(self)->CopyDescriptors(dest_ranges, dst, dest_sizes, src_ranges, src, src_sizes, type);
delete[] dst;
if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && dest_starts && src_starts) {
// Descriptor by descriptor across the two range lists; a missing size array means 1 each.
UINT di = 0, dn = 0, si = 0, sn = 0;
while (di < dest_ranges && si < src_ranges) {
bx_console_copy_title(dest_starts[di].ptr + 32ull * dn, src_starts[si].ptr + 32ull * sn, 1);
if (++dn >= (dest_sizes ? dest_sizes[di] : 1u)) {
++di;
dn = 0;
}
if (++sn >= (src_sizes ? src_sizes[si] : 1u)) {
++si;
sn = 0;
}
}
}
}
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors_simple(void* self, UINT count, D3D12_CPU_DESCRIPTOR_HANDLE dest,
D3D12_CPU_DESCRIPTOR_HANDLE src, D3D12_DESCRIPTOR_HEAP_TYPE type) {
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(count, bx_xbox_host_cpu_handle(dest), bx_xbox_host_cpu_handle(src), type);
if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) bx_console_copy_title(dest.ptr, src.ptr, count);
}
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
@@ -212,22 +243,25 @@ void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count
const D3D12_CPU_DESCRIPTOR_HANDLE host_dsv = dsv ? bx_xbox_host_cpu_handle(*dsv) : D3D12_CPU_DESCRIPTOR_HANDLE{};
bx_xbox_host<ID3D12GraphicsCommandList>(self)->OMSetRenderTargets(n, rtvs ? host_rtvs : nullptr, single_range,
dsv ? &host_dsv : nullptr);
bx_console_list_targets(bx_xbox_host<ID3D12GraphicsCommandList>(self), n, rtvs ? host_rtvs : nullptr, single_range,
dsv ? &host_dsv : nullptr);
}
namespace {
/* On the console a GPU virtual address is the title's own address, so a title can bind index and
* vertex data that lives in plain title memory, with no Direct3D resource created for it. This
* layer has a host buffer only for memory it was told about (placed and committed resources).
* An address without one must not reach the host: it is not a host address, and D3DMetal
* dereferences the buffer it fails to find (a null read under IASetIndexBuffer). Such a binding
* is left empty and logged as unimplemented; the first few are logged with their details.
* Supplying the data (a host buffer filled from the title memory) is separate work. */
* vertex data that lives in plain title memory, with no Direct3D resource created for it.
* bx_xbox_bind_title_memory (placed_x.cpp) gives such a range a host buffer and has it refreshed
* when the list is submitted. When that is not possible (the memory is not readable, or no
* buffer could be made) the address must still not reach the host: it is not a host address,
* and D3DMetal dereferences the buffer it fails to find (a null read under IASetIndexBuffer).
* The binding is then left empty and logged as unimplemented; the first few are logged with
* their details. */
void note_unbacked(const char* what, D3D12_GPU_VIRTUAL_ADDRESS address, UINT size, const char* stub) {
static std::atomic<uint32_t> noted{0};
if (noted.fetch_add(1) < 8) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s at 0x%llx (%u bytes) has no host buffer; the binding is left empty", what,
std::snprintf(detail, sizeof(detail), "%s at 0x%llx (%u bytes) cannot get a host buffer; the binding is left empty", what,
static_cast<unsigned long long>(address), size);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "unbacked_buffer", detail);
}
@@ -236,6 +270,74 @@ void note_unbacked(const char* what, D3D12_GPU_VIRTUAL_ADDRESS address, UINT siz
} // namespace
namespace {
/* How much of the title memory at `address` is readable, up to `limit` bytes. */
UINT64 readable_extent(D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 limit) {
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQuery(reinterpret_cast<const void*>(address), &info, sizeof(info))) return 0;
if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD))) return 0;
const UINT64 end = reinterpret_cast<UINT64>(info.BaseAddress) + info.RegionSize;
return end - address < limit ? end - address : limit;
}
/* A root CBV or SRV. A root buffer has no size (a console shader reads it unchecked), so plain
* title memory behind one gets a host buffer of what is readable there, up to `limit`, copied
* when the list is submitted: a shader that reads further sees zeros. Only with translated
* console shaders enabled, the only ones that read such buffers; otherwise the address is
* translated as before. Returns false when the binding must be left empty. */
bool root_buffer_address(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 limit, const char* what,
const char* stub, D3D12_GPU_VIRTUAL_ADDRESS* host) {
*host = address;
if (!address || bx_xbox_try_host_gpu_va(address, host)) return true;
if (!bx_console_shaders_enabled()) {
*host = bx_xbox_host_gpu_va(address);
return true;
}
const UINT64 size = readable_extent(address, limit);
if (size && bx_xbox_bind_title_memory(list, address, size, host)) {
static std::atomic<uint64_t> bound{0};
const uint64_t n = ++bound;
if ((n & (n - 1)) == 0) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s at 0x%llx: %llu bytes of title memory get a host buffer; total=%llu", what,
static_cast<unsigned long long>(address), static_cast<unsigned long long>(size),
static_cast<unsigned long long>(n));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "root_buffer", detail);
}
return true;
}
note_unbacked(what, address, static_cast<UINT>(size), stub);
return false;
}
constexpr UINT64 kRootSrvBytes = 256 * 1024; // copied per submission: a prefix of the buffer
constexpr UINT64 kRootCbvBytes = 64 * 1024; // the largest constant buffer
} // namespace
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_shader_resource_view(void* self, UINT param,
D3D12_GPU_VIRTUAL_ADDRESS address) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
D3D12_GPU_VIRTUAL_ADDRESS host = 0;
if (root_buffer_address(list, address, kRootSrvBytes, "root SRV", "SetGraphicsRootShaderResourceView(title memory without a host buffer)",
&host)) {
list->SetGraphicsRootShaderResourceView(param, host);
}
}
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_constant_buffer_view(void* self, UINT param,
D3D12_GPU_VIRTUAL_ADDRESS address) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootConstantBufferView");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
D3D12_GPU_VIRTUAL_ADDRESS host = 0;
if (root_buffer_address(list, address, kRootCbvBytes, "root CBV", "SetGraphicsRootConstantBufferView(title memory without a host buffer)",
&host)) {
list->SetGraphicsRootConstantBufferView(param, host);
}
}
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
@@ -243,13 +345,16 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start
const UINT n = count > 32 ? 32 : count;
for (UINT i = 0; views && i < n; ++i) {
host[i] = views[i];
if (views[i].BufferLocation && !bx_xbox_try_host_gpu_va(views[i].BufferLocation, &host[i].BufferLocation)) {
if (views[i].BufferLocation &&
!bx_xbox_bind_title_memory(bx_xbox_host<ID3D12GraphicsCommandList>(self), views[i].BufferLocation, views[i].SizeInBytes,
&host[i].BufferLocation)) {
note_unbacked("vertex buffer", views[i].BufferLocation, views[i].SizeInBytes,
"IASetVertexBuffers(title memory without a host buffer)");
host[i] = D3D12_VERTEX_BUFFER_VIEW{};
}
}
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetVertexBuffers(start, n, views ? host : nullptr);
bx_xbox_rect_note_vertex_buffers(bx_xbox_host<ID3D12GraphicsCommandList>(self), start, n, views);
}
void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_INDEX_BUFFER_VIEW* view) {
@@ -257,7 +362,9 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_index_buffer(void* self, const D3D12_
D3D12_INDEX_BUFFER_VIEW host{};
if (view) {
host = *view;
if (view->BufferLocation && !bx_xbox_try_host_gpu_va(view->BufferLocation, &host.BufferLocation)) {
if (view->BufferLocation &&
!bx_xbox_bind_title_memory(bx_xbox_host<ID3D12GraphicsCommandList>(self), view->BufferLocation, view->SizeInBytes,
&host.BufferLocation)) {
note_unbacked("index buffer", view->BufferLocation, view->SizeInBytes,
"IASetIndexBuffer(title memory without a host buffer)");
view = nullptr;
+104 -1
View File
@@ -7,10 +7,17 @@
* FLIP events, and IntervalOffsetInMicroseconds later the ORIGIN event, which also produces a
* new frame pipeline token. Each signal also sets the ancillary events given to
* ScheduleFrameEventX. Timing follows the host's Sleep granularity; no display is involved.
*
* GetFrameStatisticsX (authorized GDK documentation) answers from a history of the last 17
* frames, kept per pipeline token: the ORIGIN event (wait call, signal and wait return times)
* and PresentX (call and return times), in QueryPerformanceCounter ticks as documented. The
* other statistics types (interval, power scaling, render, display, input) have no host source
* and are never reported; a query for only those answers S_FALSE, "not available yet".
*/
#include "xbox_facade.h"
#include <cstdio>
#include <cstring>
#include <mutex>
#include <thread>
@@ -43,6 +50,35 @@ UINT64 g_next_token = 1;
UINT64 g_last_origin_token = 0;
bool g_thread_started = false;
// Frame statistics history (GetFrameStatisticsX): the runtime keeps the last 17 frames.
constexpr UINT kHistory = 17;
struct FrameRecord {
UINT64 token = 0;
UINT64 wait_call = 0, signal = 0, wait_return = 0;
UINT offset_us = 0;
bool signaled = false;
bool waited = false;
bool presented = false;
UINT64 present_call = 0, present_return = 0;
};
FrameRecord g_history[kHistory];
UINT64 qpc_now() {
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return static_cast<UINT64>(t.QuadPart);
}
// The record for `token`, created when `create` (replacing the one 17 frames older); else null.
FrameRecord* record_for(UINT64 token, bool create) {
FrameRecord& r = g_history[token % kHistory];
if (r.token == token) return &r;
if (!create) return nullptr;
r = FrameRecord{};
r.token = token;
return &r;
}
void close_ancillary(Scheduled& e) {
for (UINT i = 0; i < e.ancillary_count; ++i) CloseHandle(e.ancillary[i]);
e.ancillary_count = 0;
@@ -52,7 +88,13 @@ void signal(UINT type) {
std::lock_guard<std::mutex> guard(g_lock);
const Scheduled& e = g_events[type];
if (!e.active) return;
if (type == kOrigin) g_last_origin_token = g_next_token++;
if (type == kOrigin) {
g_last_origin_token = g_next_token++;
FrameRecord* r = record_for(g_last_origin_token, true);
r->signal = qpc_now();
r->offset_us = e.offset_us;
r->signaled = true;
}
SetEvent(g_signal[type]);
for (UINT i = 0; i < e.ancillary_count; ++i) SetEvent(e.ancillary[i]);
}
@@ -156,6 +198,7 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
}
const UINT ancillary = waits ? waits->Count : 0;
for (UINT i = 0; i < ancillary; ++i) handles[1 + i] = waits->pObjects[i];
const UINT64 wait_call = qpc_now();
const DWORD result = WaitForMultipleObjects(1 + ancillary, handles, (flags & kWaitAll) != 0,
timeout_ms == kInfinite ? INFINITE : timeout_ms);
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
@@ -166,8 +209,68 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
std::lock_guard<std::mutex> guard(g_lock);
*token = satisfied ? g_last_origin_token : g_next_token++;
if (FrameRecord* r = record_for(*token, true)) {
r->wait_call = wait_call;
r->wait_return = qpc_now();
r->waited = true;
}
}
return satisfied ? S_OK : S_FALSE;
}
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time) {
if (!token) return;
std::lock_guard<std::mutex> guard(g_lock);
if (FrameRecord* r = record_for(token, false)) {
r->presented = true;
r->present_call = call_time;
r->present_return = return_time;
}
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void*, UINT64 token, UINT type_set, UINT* count,
void* statistics) {
BX_D3D_TRACE("XboxDevice", "GetFrameStatisticsX");
if (!count || type_set == 0 || (type_set & ~kStatsKnownTypes) != 0 || (*count && !statistics)) return E_INVALIDARG;
BxXboxFrameStatistics found[2];
UINT n = 0;
{
std::lock_guard<std::mutex> guard(g_lock);
if (token == 0 || token >= g_next_token) return E_INVALIDARG; // documented: unknown pipeline token
if (const FrameRecord* r = record_for(token, false)) {
if ((type_set & kStatsFrameEvent) && (r->signaled || r->waited)) {
BxXboxFrameStatistics& out = found[n++];
std::memset(&out, 0, sizeof(out));
out.Type = kStatsFrameEvent;
out.Event.EventType = kOrigin;
out.Event.WaitCallTime = r->wait_call;
out.Event.SignalTime = r->signal;
out.Event.WaitReturnTime = r->wait_return;
out.Event.IntervalOffsetInMicroseconds = r->offset_us;
out.Event.StatisticsFlags = r->signaled ? 0 : kEventSignalPending;
}
if ((type_set & kStatsPresent) && r->presented) {
BxXboxFrameStatistics& out = found[n++];
std::memset(&out, 0, sizeof(out));
out.Type = kStatsPresent;
out.Present.PlaneIndex = 0;
out.Present.PlaneCount = 1;
out.Present.ViewCount = 1;
out.Present.PresentCallTime = r->present_call;
out.Present.PresentQueueTime = r->present_call; // queued in the call itself
out.Present.PresentReturnTime = r->present_return;
out.Present.PlaneSwapMask = 1; // GPUProcessTime: not measured, 0
}
}
}
if (!statistics) { // a size query
*count = n;
return n ? S_OK : S_FALSE;
}
const UINT written = n < *count ? n : *count;
std::memcpy(statistics, found, written * sizeof(BxXboxFrameStatistics));
*count = written;
return n ? S_OK : S_FALSE;
}
} // extern "C"
+94
View File
@@ -0,0 +1,94 @@
/* Console texture layouts through the GDK's own XG library (see gdk_xg.h).
*
* The documented interface (GDK xg_xs.h):
* HRESULT XGCreateTextureComputer(const XG_RESOURCE_DESC*, XGTextureAddressComputer**);
* XG_RESOURCE_DESC has the field order and sizes of D3D12_RESOURCE_DESC, with
* XG12_RESOURCE_MISC_FLAG in place of D3D12_RESOURCE_FLAGS; the title's console flags
* (render target, depth, UAV, deny-compression) are those values.
* XGTextureAddressComputer vtable: 0 AddRef, 1 Release, 2 GetResourceLayout,
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, ...
* void XGEnableExclusiveLocking(BOOL), to be called before any computer is created.
*/
#include "gdk_xg.h"
#include "bx_log.h"
#include <atomic>
#include <cstdio>
namespace {
struct XgComputer;
struct XgComputerVtbl {
ULONG(__cdecl* AddRef)(XgComputer*);
ULONG(__cdecl* Release)(XgComputer*);
void* GetResourceLayout;
UINT64 (*GetResourceSizeBytes)(XgComputer*);
UINT64 (*GetResourceBaseAlignmentBytes)(XgComputer*);
};
struct XgComputer {
const XgComputerVtbl* vtbl;
};
using CreateTextureComputerFn = HRESULT(__cdecl*)(const D3D12_RESOURCE_DESC*, XgComputer**);
using EnableLockingFn = void(__cdecl*)(BOOL);
HMODULE microsoft_xg() {
static const HMODULE module = [] {
HMODULE xg = GetModuleHandleW(L"xg_xs.dll");
if (!xg) xg = LoadLibraryW(L"xg_xs.dll");
const bool microsoft = xg && GetProcAddress(xg, "XGComputeTexture2DLayout");
bx_log_emit(microsoft ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "gdk_xg",
microsoft ? "GDK XG library loaded: console texture layouts are computed by it"
: "GDK XG library not loaded: console textures are sized linearly (bx-cli run stages it "
"from the configured GDK)");
return microsoft ? xg : static_cast<HMODULE>(nullptr);
}();
return module;
}
CreateTextureComputerFn create_computer() {
static const CreateTextureComputerFn fn = [] {
HMODULE xg = microsoft_xg();
return xg ? reinterpret_cast<CreateTextureComputerFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGCreateTextureComputer")))
: nullptr;
}();
return fn;
}
} // namespace
bool bx_gdk_xg_available() { return create_computer() != nullptr; }
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc) {
return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN &&
static_cast<UINT>(desc.Layout) >= 0x100;
}
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment) {
const CreateTextureComputerFn create = create_computer();
if (!create || !bx_is_console_texture_layout(desc)) return false;
XgComputer* computer = nullptr;
const HRESULT hr = create(&desc, &computer);
if (FAILED(hr) || !computer) {
static std::atomic<int> logged{0};
if (logged.fetch_add(1) < 8) {
char detail[160];
std::snprintf(detail, sizeof(detail), "XGCreateTextureComputer refused %llux%u layout=0x%x format=%d: hr=0x%08lx",
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<UINT>(desc.Layout),
static_cast<int>(desc.Format), static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gdk_xg", detail);
}
return false;
}
*size = computer->vtbl->GetResourceSizeBytes(computer);
*alignment = computer->vtbl->GetResourceBaseAlignmentBytes(computer);
computer->vtbl->Release(computer);
return true;
}
extern "C" void bx_gdk_xg_enable_locking() {
HMODULE xg = microsoft_xg();
if (!xg) return;
auto enable = reinterpret_cast<EnableLockingFn>(reinterpret_cast<void*>(GetProcAddress(xg, "XGEnableExclusiveLocking")));
if (enable) enable(TRUE);
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
/* Console texture layouts through the GDK's own XG library.
*
* Console textures are laid out in tiled swizzle modes (D3D12XBOX_TEXTURE_LAYOUT / XG_TEXTURE_LAYOUT,
* 0x100 | XG_SWIZZLE_MODE). A title sizes its loads and placements from those layouts, so a
* linear answer makes it read less than the tiled data it stored. The layouts are computed by
* Microsoft's xg_xs.dll from the collaborator's own GDK, staged by `bx-cli run` in place of
* BetterXen's xg_xs shim (which exports only the two functions titles import). Nothing from the
* GDK is shipped. Without it these helpers report that no console layout is available.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
/* True when Microsoft's XG library is the loaded xg_xs.dll (it exports XGComputeTexture2DLayout). */
bool bx_gdk_xg_available();
/* A console texture layout (Layout >= 0x100) that the GDK's XG can describe. */
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc);
/* Size and base alignment of `desc` in the console layout. False when XG is not available or
refuses the description; `size` and `alignment` are then untouched. */
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment);
/* Enables XG's internal lock (XGEnableExclusiveLocking) before any texture computer is created,
so the title's threads and the shim can both create computers. Called at device creation. */
extern "C" void bx_gdk_xg_enable_locking();
+4
View File
@@ -9,6 +9,8 @@
*/
#include "xbox_facade.h"
#include "console_pipelines.h"
#include <atomic>
#include <cstdio>
#include <mutex>
@@ -155,6 +157,8 @@ void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
}
}
bx_xbox_sync_mapped_buffers();
bx_xbox_refresh_bound_memory(host.data(), count);
bx_console_submit(host.data(), count);
for (const Write& w : pending) {
if (w.wait) apply_wait(queue, w);
}
+122 -15
View File
@@ -13,15 +13,23 @@
* are skipped. Everything else still runs, so fences complete and frames present, with the
* skipped work missing from them. Each refusal and each skip is logged: the mode exists to see
* how far a title gets, not to hide what it cannot run.
*
* Console pipelines (BX_CONSOLE_SHADERS=1, console_pipelines.cpp, #720): a refused stream
* pipeline that is a vertex/pixel pair is returned as a null pipeline that carries the pair. A
* draw with it bound asks for its translated host pipeline, binds that and draws; when there is
* none (not translatable yet), the draw is skipped and logged like any null pipeline's.
*/
#include "xbox_facade.h"
#include "console_pipelines.h"
#include "proxy.h"
#include "shader_gate.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <memory>
#include <unordered_map>
#include <vector>
#include <mutex>
@@ -43,6 +51,8 @@ class NullPipelineState final : public ID3D12PipelineState {
public:
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
std::shared_ptr<BxConsolePipeline> console; // the console pair to translate at first draw, if any
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
if (!ppv) return E_POINTER;
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
@@ -88,6 +98,7 @@ size_t g_null_capacity = 0;
ID3D12GraphicsCommandList** g_lists = nullptr; // lists whose bound pipeline is a null pipeline
size_t g_list_count = 0;
size_t g_list_capacity = 0;
std::unordered_map<const void*, std::shared_ptr<BxConsolePipeline>> g_list_console; // its console pair, if any
template <typename T>
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
@@ -124,24 +135,55 @@ bool contains(T* const* items, size_t count, const T* item) {
}
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null,
std::shared_ptr<BxConsolePipeline>* console = nullptr) {
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
std::lock_guard<std::mutex> guard(g_lock);
*is_null = host && contains(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
auto* as_null = static_cast<NullPipelineState*>(static_cast<void*>(host));
*is_null = host && contains(g_nulls, g_null_count, as_null);
if (console && *is_null) *console = as_null->console;
return *is_null ? nullptr : host;
}
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound, std::shared_ptr<BxConsolePipeline> console = nullptr) {
std::lock_guard<std::mutex> guard(g_lock);
const bool present = contains(g_lists, g_list_count, list);
if (null_bound && !present) push(g_lists, g_list_count, g_list_capacity, list);
if (!null_bound && present) erase(g_lists, g_list_count, list);
if (console) {
g_list_console[list] = std::move(console);
} else {
g_list_console.erase(list);
}
}
bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
/* True when the work must be skipped. A draw (`draw`) with a console pipeline bound binds its
translated host pipeline instead, when there is one. */
bool list_skips(ID3D12GraphicsCommandList* list, const char* what, bool draw = false) {
std::shared_ptr<BxConsolePipeline> console;
{
std::lock_guard<std::mutex> guard(g_lock);
if (!contains(g_lists, g_list_count, list)) return false;
if (draw) {
auto it = g_list_console.find(list);
if (it != g_list_console.end()) console = it->second;
}
}
if (console) {
if (ID3D12PipelineState* host = bx_console_pipeline_for_draw(console.get(), list)) {
bx_console_record_draw(list, console);
list->SetPipelineState(host);
bx_xbox_rect_note_pipeline(list, host);
static std::atomic<uint64_t> drawn{0};
const uint64_t k = ++drawn;
if ((k & (k - 1)) == 0) {
char detail[96];
std::snprintf(detail, sizeof(detail), "%s with a translated console pipeline; total=%llu", what,
static_cast<unsigned long long>(k));
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_draw", detail);
}
return false;
}
}
static std::atomic<uint64_t> skipped{0};
const uint64_t n = ++skipped;
@@ -154,14 +196,16 @@ bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
return true;
}
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv) {
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv,
std::shared_ptr<BxConsolePipeline> console = nullptr) {
char detail[128];
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx%s", kind, static_cast<unsigned long>(hr),
null_render_enabled() ? "; null pipeline returned" : "");
console ? "; kept for translation at first draw" : null_render_enabled() ? "; null pipeline returned" : "");
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
if (!null_render_enabled() || !ppv) return hr;
if ((!null_render_enabled() && !console) || !ppv) return hr;
auto* null_pso = new (std::nothrow) NullPipelineState(device);
if (!null_pso) return E_OUTOFMEMORY;
null_pso->console = std::move(console);
{
std::lock_guard<std::mutex> guard(g_lock);
if (!push(g_nulls, g_null_count, g_null_capacity, null_pso)) {
@@ -200,6 +244,12 @@ HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc
return bx_xbox_wrap_result(hr, riid, ppv);
}
/* The console's pipeline topology types for rectangle and quad lists
(D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT = 19, _QUAD = 32) are drawn with triangles on the host. */
D3D12_PRIMITIVE_TOPOLOGY_TYPE host_topology_type(D3D12_PRIMITIVE_TOPOLOGY_TYPE type) {
return type > D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : type;
}
HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
if (!desc || !ppv) return E_INVALIDARG;
*ppv = nullptr;
@@ -212,8 +262,11 @@ HRESULT create_graphics(void* self, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* de
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "DS", desc->DS, admitted.DS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "HS", desc->HS, admitted.HS);
if (SUCCEEDED(hr)) hr = gate.admit("graphics", "GS", desc->GS, admitted.GS);
admitted.PrimitiveTopologyType = host_topology_type(desc->PrimitiveTopologyType);
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "graphics", riid, ppv);
bx_xbox_rect_pipeline_created(static_cast<ID3D12PipelineState*>(*ppv), desc->InputLayout.pInputElementDescs,
desc->InputLayout.NumElements);
return bx_xbox_wrap_result(hr, riid, ppv);
}
@@ -247,10 +300,25 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
hr = gate.admit("stream", names[i], in, out);
if (SUCCEEDED(hr)) std::memcpy(&stream[offsets[i]], &out, sizeof(out));
}
const size_t topology_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY);
if (topology_at != SIZE_MAX) {
D3D12_PRIMITIVE_TOPOLOGY_TYPE type{};
std::memcpy(&type, &stream[topology_at], sizeof(type));
type = host_topology_type(type);
std::memcpy(&stream[topology_at], &type, sizeof(type));
}
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
admitted.pPipelineStateSubobjectStream = stream.data();
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
// The shader gate refused a stage: console code. The pair is kept for its first draw.
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv, bx_console_pipeline_create(device, stream, offsets, names, root_offset));
hr = device->CreatePipelineState(&admitted, riid, ppv);
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
{
D3D12_INPUT_LAYOUT_DESC layout{};
const size_t layout_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT);
if (layout_at != SIZE_MAX) std::memcpy(&layout, &stream[layout_at], sizeof(layout));
bx_xbox_rect_pipeline_created(static_cast<ID3D12PipelineState*>(*ppv), layout.pInputElementDescs, layout.NumElements);
}
return bx_xbox_wrap_result(hr, riid, ppv);
}
@@ -274,12 +342,29 @@ void bx_xbox_pipeline_forget(IUnknown* host) {
}
void bx_xbox_list_forget(IUnknown* host) {
bx_xbox_rect_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
bx_console_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
bx_console_descriptors_reset(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
std::lock_guard<std::mutex> guard(g_lock);
g_list_console.erase(host);
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
}
extern "C" {
void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_PRIMITIVE_TOPOLOGY topology) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetPrimitiveTopology");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
list->IASetPrimitiveTopology(bx_xbox_rect_note_topology(list, topology));
}
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_descriptor_table(void* self, UINT param, D3D12_GPU_DESCRIPTOR_HANDLE base) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootDescriptorTable");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bx_console_note_table(list, param, base.ptr);
list->SetGraphicsRootDescriptorTable(param, bx_xbox_host_gpu_handle(base));
}
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
@@ -312,8 +397,10 @@ void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12Pipelin
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
std::shared_ptr<BxConsolePipeline> console;
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &console);
set_list_null(list, is_null, std::move(console));
bx_xbox_rect_note_pipeline(list, host);
if (!is_null) list->SetPipelineState(host);
}
@@ -321,9 +408,13 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator*
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
bool is_null = false;
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
set_list_null(list, is_null);
std::shared_ptr<BxConsolePipeline> console;
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &console);
set_list_null(list, is_null, std::move(console));
bx_xbox_gpu_writes_reset(list);
bx_console_descriptors_reset(list);
bx_xbox_bound_memory_reset(list);
bx_xbox_rect_list_reset(list, host);
return list->Reset(bx_xbox_unwrap_as(allocator), host);
}
@@ -331,16 +422,22 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UI
UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawInstanced")) list->DrawInstanced(vertices, instances, first_vertex, first_instance);
if (list_skips(list, "DrawInstanced", true)) return;
if (!bx_xbox_draw_rect_list(list, vertices, instances, first_vertex, first_instance)) {
list->DrawInstanced(vertices, instances, first_vertex, first_instance);
}
}
void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indices, UINT instances, UINT first_index,
INT base_vertex, UINT first_instance) {
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
if (!list_skips(list, "DrawIndexedInstanced")) {
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
if (list_skips(list, "DrawIndexedInstanced", true)) return;
if (bx_xbox_rect_list_bound(list)) {
BX_STUB_LOG("d3d12_xs.dll", "DrawIndexedInstanced(rectangle list)");
return;
}
list->DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance);
}
void STDMETHODCALLTYPE bx_xbox_list_dispatch(void* self, UINT x, UINT y, UINT z) {
@@ -361,6 +458,16 @@ void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSi
} // extern "C"
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_root_signature(void* self, UINT node_mask, const void* blob, SIZE_T size,
REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateRootSignature");
if (!ppv) return E_POINTER;
*ppv = nullptr;
const HRESULT hr = bx_console_create_root_signature(bx_xbox_host<ID3D12Device>(self), node_mask, blob, size, riid, ppv);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
return bx_xbox_wrap_result(hr, riid, ppv);
}
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
ID3D12RootSignature* root, REFIID riid, void** ppv) {
BX_D3D_TRACE("XboxDevice", "CreateCommandSignature");
+102
View File
@@ -22,6 +22,8 @@
#include <cstdio>
#include <cstring>
#include <mutex>
#include <vector>
#include <unordered_map>
extern "C" __declspec(dllimport) VOID WINAPI XMemFree(PVOID address, ULONGLONG attributes);
@@ -260,6 +262,106 @@ bool bx_xbox_try_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title, D3D12_GPU_VIRTUAL_
return false;
}
/*
* Title memory bound as index or vertex data.
*
* 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 therefore binds index and vertex data that it keeps in
* plain memory, with no Direct3D resource, and may still be writing it after it has recorded the
* draw. Here such a range gets a CPU-writable host buffer of its own (once: later ranges inside
* it reuse it; like the other implicit shadows it lives for the rest of the process), and every
* range bound on a list is copied from the title memory to its host buffer when that list is
* submitted. A range inside a buffer this layer already has is refreshed the same way.
*/
namespace {
constexpr UINT64 kMaxBoundBytes = 256ull << 20; // refuse absurd sizes instead of allocating them
struct BoundRange {
uint64_t va, size;
};
std::mutex g_bound_lock;
std::unordered_map<const void*, std::vector<BoundRange>> g_bound; // host list -> ranges bound since its reset
// The index of a buffer shadow that holds the whole range, or SIZE_MAX. g_lock must be held.
size_t buffer_holding_locked(uint64_t va, uint64_t size) {
for (size_t i = 0; i < g_count; ++i) {
const Shadow& s = g_shadows[i];
if (s.buffer && va >= s.title_va && va + size <= s.title_va + s.size) return i;
}
return SIZE_MAX;
}
} // namespace
bool bx_xbox_bind_title_memory(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS title, UINT64 size,
D3D12_GPU_VIRTUAL_ADDRESS* host) {
if (!list || !title || !size || size > kMaxBoundBytes) return false;
bool found = false;
{
std::lock_guard<std::mutex> guard(g_lock);
const size_t i = buffer_holding_locked(title, size);
if (i != SIZE_MAX) {
*host = g_shadows[i].host->GetGPUVirtualAddress() + (title - g_shadows[i].title_va);
found = true;
}
}
if (!found) {
if (!readable(reinterpret_cast<const void*>(title), size)) return false;
ID3D12Device* device = nullptr;
if (FAILED(list->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return false;
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = size;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* resource = nullptr;
const HRESULT hr = make_shadow(device, title, desc, "host buffer for bound title memory", &resource);
device->Release();
if (FAILED(hr) || !resource) return false;
*host = resource->GetGPUVirtualAddress();
}
std::lock_guard<std::mutex> guard(g_bound_lock);
std::vector<BoundRange>& ranges = g_bound[list];
for (const BoundRange& r : ranges) {
if (title >= r.va && title + size <= r.va + r.size) return true; // already recorded
}
ranges.push_back({title, size});
return true;
}
void bx_xbox_bound_memory_reset(IUnknown* host_list) {
std::lock_guard<std::mutex> guard(g_bound_lock);
g_bound.erase(host_list);
}
void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT count) {
std::vector<BoundRange> ranges;
{
std::lock_guard<std::mutex> guard(g_bound_lock);
for (UINT i = 0; i < count; ++i) {
auto it = g_bound.find(host_lists[i]);
if (it == g_bound.end()) continue;
for (const BoundRange& r : it->second) {
bool covered = false;
for (const BoundRange& have : ranges) covered = covered || (r.va >= have.va && r.va + r.size <= have.va + have.size);
if (!covered) ranges.push_back(r);
}
}
}
for (const BoundRange& r : ranges) {
if (!readable(reinterpret_cast<const void*>(r.va), r.size)) continue; // freed since it was bound
std::lock_guard<std::mutex> guard(g_lock);
const size_t i = buffer_holding_locked(r.va, r.size);
if (i == SIZE_MAX) continue;
const uint64_t begin = r.va - g_shadows[i].title_va;
copy_buffer(g_shadows[i], true, begin, begin + r.size);
}
}
D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title) {
if (!title) return title;
std::lock_guard<std::mutex> guard(g_lock);
+15
View File
@@ -281,6 +281,21 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
const void* parameters) {
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
(void)parameters;
// Call and return times for GetFrameStatisticsX, kept for the first plane's pipeline token.
struct PresentTimes {
UINT64 token;
UINT64 call;
~PresentTimes() {
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
bx_xbox_frame_stats_present(token, call, static_cast<UINT64>(now.QuadPart));
}
} times{plane_count && planes_raw ? static_cast<const PlaneParameters*>(planes_raw)[0].Token : 0, 0};
{
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
times.call = static_cast<UINT64>(now.QuadPart);
}
const auto* planes = static_cast<const PlaneParameters*>(planes_raw);
if (plane_count == 0 || !planes || planes[0].ResourceCount == 0 || !planes[0].ppResources) return S_OK;
ID3D12Resource* source = bx_xbox_unwrap_as(planes[0].ppResources[0]);
+13
View File
@@ -559,6 +559,19 @@ HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<ui
return S_OK;
}
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type) {
size_t offset = 0;
while (offset + sizeof(SIZE_T) <= stream.size()) {
uint32_t raw = 0;
std::memcpy(&raw, &stream[offset], sizeof(raw));
const StreamSubobject* entry = find_subobject(raw);
if (!entry) return SIZE_MAX;
if (raw == type) return offset + entry->payload_offset;
offset += entry->record_size;
}
return SIZE_MAX;
}
HRESULT STDMETHODCALLTYPE BxDeviceProxy::CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, void** ppv) {
BX_D3D_TRACE("ID3D12Device2", "CreatePipelineState");
if (!h_ID3D12Device2) {
+2
View File
@@ -124,3 +124,5 @@ using BxCommandListProxy = BxChildProxy<BxCommandListProxyGen>;
HRESULT copy_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, std::vector<uint8_t>& copy,
std::vector<size_t>& stage_offsets, std::vector<const char*>& stage_names,
size_t* root_offset);
/* The payload offset of the subobject of `type` in a stream copy_stream accepted, or SIZE_MAX. */
size_t bx_stream_payload(const std::vector<uint8_t>& stream, uint32_t type);
+261
View File
@@ -0,0 +1,261 @@
/*
* Console rectangle lists.
*
* The Xbox Series headers add primitive topologies PC Direct3D 12 does not have. A title draws
* its full-screen passes with D3D_PRIMITIVE_TOPOLOGY_RECTLIST (17): three vertices per rectangle,
* the fourth corner being v0 + v2 - v1, in pipelines whose topology type is
* D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT (19). The host knows neither value. Passed through, the
* pipeline is created anyway and the three vertices are drawn as one triangle: half of every
* rectangle is missing and no error is reported.
*
* Here a rectangle list is drawn as triangle strips:
* - the pipeline's topology type becomes TRIANGLE when it is created (pipelines.cpp);
* - IASetPrimitiveTopology(RECTLIST) sets TRIANGLESTRIP on the host and is remembered;
* - a non-indexed draw builds four vertices per rectangle, in the order v1, v2, v0, v3 (which
* keeps the winding of v0, v1, v2), in a host upload buffer and draws them. The vertices are
* read from the title's memory behind vertex-buffer slot 0, and v3 is computed element by
* element from the pipeline's input layout.
*
* Limits, each logged as unimplemented when reached: indexed rectangle lists; layouts with
* per-vertex elements outside slot 0; element formats other than 32-bit float and 8-bit
* normalised (those elements take the third vertex's value). Quad lists, quad strips and line
* loops are not emulated.
*/
#include "xbox_facade.h"
#include <atomic>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <unordered_map>
#include <vector>
namespace {
constexpr int kRectList = 17; // D3D_PRIMITIVE_TOPOLOGY_RECTLIST (Xbox extension)
struct Element {
DXGI_FORMAT format;
UINT slot;
UINT offset;
bool per_vertex;
};
struct ListState {
int topology = 0; // the title's last IASetPrimitiveTopology value
D3D12_VERTEX_BUFFER_VIEW vb0{}; // the title's view of slot 0 (title address)
ID3D12PipelineState* pipeline = nullptr; // host pipeline bound, or nullptr
};
std::mutex g_lock;
std::unordered_map<const void*, ListState> g_lists;
std::unordered_map<const void*, std::vector<Element>> g_layouts; // host pipeline -> input elements
bool readable(uint64_t address, uint64_t size) {
uint64_t cursor = address;
const uint64_t end = address + size;
while (cursor < end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(cursor), &region, sizeof(region)) || region.State != MEM_COMMIT ||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
return false;
}
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
return true;
}
/* Space for generated vertices: one upload buffer used as a ring. A position is reused after the
ring wraps, which is 4 MiB of generated rectangles later; frames use a few hundred bytes. */
bool ring_place(ID3D12Device* device, const uint8_t* data, size_t size, D3D12_GPU_VIRTUAL_ADDRESS* address) {
constexpr uint64_t kRing = 4ull << 20;
static std::mutex lock;
static ID3D12Resource* ring = nullptr;
static uint8_t* mapped = nullptr;
static uint64_t cursor = 0;
if (size == 0 || size > kRing) return false;
std::lock_guard<std::mutex> guard(lock);
if (!ring) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = kRing;
desc.Height = 1;
desc.DepthOrArraySize = 1;
desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
ID3D12Resource* created = nullptr;
void* base = nullptr;
if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&created))) ||
!created) {
return false;
}
if (FAILED(created->Map(0, nullptr, &base)) || !base) {
created->Release();
return false;
}
ring = created;
mapped = static_cast<uint8_t*>(base);
}
const uint64_t aligned = (size + 15) & ~15ull;
if (cursor + aligned > kRing) cursor = 0;
std::memcpy(mapped + cursor, data, size);
*address = ring->GetGPUVirtualAddress() + cursor;
cursor += aligned;
return true;
}
void unimplemented(const char* what) { BX_STUB_LOG("d3d12_xs.dll", what); }
} // namespace
void bx_xbox_rect_pipeline_created(ID3D12PipelineState* host, const D3D12_INPUT_ELEMENT_DESC* elements, UINT count) {
if (!host) return;
std::vector<Element> layout;
for (UINT i = 0; elements && i < count; ++i) {
layout.push_back({elements[i].Format, elements[i].InputSlot, elements[i].AlignedByteOffset,
elements[i].InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA});
}
std::lock_guard<std::mutex> guard(g_lock);
g_layouts[host] = std::move(layout); // also replaces a released pipeline's entry at a reused address
}
D3D12_PRIMITIVE_TOPOLOGY bx_xbox_rect_note_topology(ID3D12GraphicsCommandList* list, D3D12_PRIMITIVE_TOPOLOGY topology) {
{
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list].topology = static_cast<int>(topology);
}
return static_cast<int>(topology) == kRectList ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : topology;
}
void bx_xbox_rect_note_vertex_buffers(ID3D12GraphicsCommandList* list, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views) {
if (start != 0 || count == 0) return;
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list].vb0 = views ? views[0] : D3D12_VERTEX_BUFFER_VIEW{};
}
void bx_xbox_rect_note_pipeline(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host) {
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list].pipeline = host;
}
void bx_xbox_rect_list_reset(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host) {
std::lock_guard<std::mutex> guard(g_lock);
g_lists[list] = ListState{};
g_lists[list].pipeline = host;
}
void bx_xbox_rect_list_forget(ID3D12GraphicsCommandList* list) {
std::lock_guard<std::mutex> guard(g_lock);
g_lists.erase(list);
}
bool bx_xbox_rect_list_bound(ID3D12GraphicsCommandList* list) {
std::lock_guard<std::mutex> guard(g_lock);
auto it = g_lists.find(list);
return it != g_lists.end() && it->second.topology == kRectList;
}
/* True when the list's topology is the rectangle list: the draw was done here, or could not be
and was logged as unimplemented. Either way the caller must not issue its own draw. */
bool bx_xbox_draw_rect_list(ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance) {
ListState state;
std::vector<Element> layout;
bool have_layout = false;
{
std::lock_guard<std::mutex> guard(g_lock);
auto it = g_lists.find(list);
if (it == g_lists.end() || it->second.topology != kRectList) return false;
state = it->second;
auto found = g_layouts.find(state.pipeline);
if (found != g_layouts.end()) {
layout = found->second;
have_layout = true;
}
}
const UINT stride = state.vb0.StrideInBytes;
const UINT rects = vertices / 3;
if (rects == 0) return true;
if (!have_layout || !state.vb0.BufferLocation || stride == 0 || stride > 1024) {
unimplemented("DrawInstanced(rectangle list without a known input layout or slot-0 vertex buffer)");
return true;
}
for (const Element& e : layout) {
if (e.per_vertex && e.slot != 0) {
unimplemented("DrawInstanced(rectangle list with per-vertex elements outside slot 0)");
return true;
}
}
const uint64_t source = state.vb0.BufferLocation + static_cast<uint64_t>(first_vertex) * stride;
if (!readable(source, static_cast<uint64_t>(rects) * 3 * stride)) {
unimplemented("DrawInstanced(rectangle list whose vertices are not readable title memory)");
return true;
}
std::vector<uint8_t> out(static_cast<size_t>(rects) * 4 * stride);
for (UINT r = 0; r < rects; ++r) {
const auto* v0 = reinterpret_cast<const uint8_t*>(source + static_cast<uint64_t>(3 * r) * stride);
const uint8_t* v1 = v0 + stride;
const uint8_t* v2 = v1 + stride;
uint8_t* dst = &out[static_cast<size_t>(r) * 4 * stride];
std::memcpy(dst, v1, stride);
std::memcpy(dst + stride, v2, stride);
std::memcpy(dst + 2 * stride, v0, stride);
uint8_t* v3 = dst + 3 * stride;
std::memcpy(v3, v2, stride);
for (const Element& e : layout) {
if (!e.per_vertex || e.offset >= stride) continue;
unsigned floats = 0, bytes = 0;
switch (e.format) {
case DXGI_FORMAT_R32G32B32A32_FLOAT: floats = 4; break;
case DXGI_FORMAT_R32G32B32_FLOAT: floats = 3; break;
case DXGI_FORMAT_R32G32_FLOAT: floats = 2; break;
case DXGI_FORMAT_R32_FLOAT: floats = 1; break;
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM: bytes = 4; break;
default: unimplemented("DrawInstanced(rectangle list element format; third vertex's value used)"); break;
}
for (unsigned i = 0; i < floats && e.offset + 4 * (i + 1) <= stride; ++i) {
float a, b, c;
std::memcpy(&a, v0 + e.offset + 4 * i, 4);
std::memcpy(&b, v1 + e.offset + 4 * i, 4);
std::memcpy(&c, v2 + e.offset + 4 * i, 4);
const float d = a + c - b;
std::memcpy(v3 + e.offset + 4 * i, &d, 4);
}
for (unsigned i = 0; i < bytes && e.offset + i < stride; ++i) {
const int d = static_cast<int>(v0[e.offset + i]) + v2[e.offset + i] - v1[e.offset + i];
v3[e.offset + i] = static_cast<uint8_t>(d < 0 ? 0 : d > 255 ? 255 : d);
}
}
}
ID3D12Device* device = nullptr;
D3D12_GPU_VIRTUAL_ADDRESS placed = 0;
const bool ok = SUCCEEDED(list->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) && device &&
ring_place(device, out.data(), out.size(), &placed);
if (device) device->Release();
if (!ok) {
unimplemented("DrawInstanced(rectangle list: no host buffer for the generated vertices)");
return true;
}
const D3D12_VERTEX_BUFFER_VIEW generated{placed, static_cast<UINT>(out.size()), stride};
list->IASetVertexBuffers(0, 1, &generated);
for (UINT r = 0; r < rects; ++r) list->DrawInstanced(4, instances, 4 * r, first_instance);
// Put the title's own slot-0 binding back.
D3D12_VERTEX_BUFFER_VIEW title = state.vb0;
if (bx_xbox_try_host_gpu_va(state.vb0.BufferLocation, &title.BufferLocation)) {
list->IASetVertexBuffers(0, 1, &title);
} else {
list->IASetVertexBuffers(0, 1, nullptr);
}
static std::atomic<bool> logged{false};
if (!logged.exchange(true)) {
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "rect_list",
"console rectangle lists are drawn as triangle strips (fourth corner v0 + v2 - v1); later draws are not logged");
}
return true;
}
+9
View File
@@ -54,11 +54,15 @@ CUSTOM = {
"WaitFrameEventX": "bx_xbox_device_wait_frame_event_x",
"CreatePlacedResourceX": "bx_xbox_device_create_placed_resource_x",
"CreatePlacedResourceX1": "bx_xbox_device_create_placed_resource_x1",
"GetFrameStatisticsX": "bx_xbox_device_get_frame_statistics_x",
"CreateCommittedResourceX": "bx_xbox_device_create_committed_resource_x",
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
"CreateConstantBufferView": "bx_xbox_device_create_constant_buffer_view",
"CopyDescriptorsSimple": "bx_xbox_device_copy_descriptors_simple",
"CopyDescriptors": "bx_xbox_device_copy_descriptors",
"CreateCommandSignature": "bx_xbox_device_create_command_signature",
"CreateRootSignature": "bx_xbox_device_create_root_signature",
"CreatePipelineState": "bx_xbox_device_create_pipeline_state",
"DeserializeGraphicsPipelineStateX": "bx_xbox_device_deserialize_graphics_pipeline_state_x",
"CreateDerivedGraphicsPipelineStateX": "bx_xbox_device_create_derived_graphics_pipeline_state_x",
@@ -103,8 +107,13 @@ CUSTOM = {
"GetGPUDescriptorHandleForHeapStart": "bx_xbox_heap_gpu_start"},
"GraphicsCommandList": {"ResourceBarrier": "bx_xbox_list_resource_barrier",
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
"CopyTextureRegionX": "bx_xbox_list_copy_texture_region_x",
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
"IASetPrimitiveTopology": "bx_xbox_list_ia_set_primitive_topology",
"SetGraphicsRootDescriptorTable": "bx_xbox_list_set_graphics_root_descriptor_table",
"SetGraphicsRootShaderResourceView": "bx_xbox_list_set_graphics_root_shader_resource_view",
"SetGraphicsRootConstantBufferView": "bx_xbox_list_set_graphics_root_constant_buffer_view",
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
"Reset": "bx_xbox_list_reset",
+13
View File
@@ -218,6 +218,7 @@ ULONG STDMETHODCALLTYPE bx_xbox_release(void* self) {
if (object->iface == &bx_xbox_GraphicsCommandList) {
bx_xbox_list_forget(object->host);
bx_xbox_gpu_writes_reset(object->host);
bx_xbox_bound_memory_reset(object->host);
}
object->host->Release();
delete object;
@@ -313,4 +314,16 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
}
/* CopyTextureRegionX (GDK d3d12_xs.h): CopyTextureRegion plus D3D12XBOX_COPY_FLAGS, which only
steer the console's compression metadata (HTILE resummarize, forced decompress, clear
propagation). The host keeps no such metadata, so the copy is the PC one. Leaving the call a
stub left the copy undone, and the target build then stalled its frame until its hang
watchdog ended the process (#722). */
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region_x(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box, UINT /*flags*/) {
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyTextureRegionX");
bx_xbox_list_copy_texture_region(self, dst, x, y, z, src, box);
}
} // extern "C"
+88
View File
@@ -154,6 +154,48 @@ struct BxXboxFrameObjectList {
UINT Count;
HANDLE* pObjects;
};
// GetFrameStatisticsX (authorized GDK header): D3D12XBOX_FRAME_STATISTICS is a 32-bit Type and,
// 8 bytes in, a union of the per-type structures; the two this layer fills are mirrored here.
constexpr UINT kStatsFrameEvent = 0x2, kStatsPresent = 0x1000;
constexpr UINT kStatsKnownTypes = 0x1 | 0x2 | 0x4 | 0x100 | 0x1000 | 0x10000 | 0x100000;
constexpr UINT kEventSignalPending = 0x1; // D3D12XBOX_FRAME_EVENT_STATISTICS_FLAG_SIGNAL_PENDING
struct BxXboxFrameEventStatistics { // D3D12XBOX_FRAME_EVENT_STATISTICS
UINT32 EventType;
UINT64 WaitCallTime;
UINT64 SignalTime;
UINT64 WaitReturnTime;
UINT32 IntervalOffsetInMicroseconds;
UINT32 SignalFlags;
UINT32 StatisticsFlags;
};
struct BxXboxPresentStatistics { // D3D12XBOX_PRESENT_STATISTICS
UINT8 PlaneIndex;
UINT8 PlaneCount;
UINT8 ViewCount;
UINT64 PresentCallTime;
UINT64 PresentQueueTime;
UINT64 PresentReturnTime;
UINT64 GPUProcessTime;
UINT8 QueuedFrameCount;
UINT16 PlaneSwapMask;
UINT32 Flags;
};
struct BxXboxFrameStatistics { // D3D12XBOX_FRAME_STATISTICS
UINT32 Type;
union {
BxXboxFrameEventStatistics Event;
BxXboxPresentStatistics Present;
UINT8 Bytes[48]; // the union's size: its largest members are 48 bytes
};
};
static_assert(sizeof(BxXboxFrameEventStatistics) == 48 && sizeof(BxXboxPresentStatistics) == 48, "statistics layout");
static_assert(sizeof(BxXboxFrameStatistics) == 56 && offsetof(BxXboxFrameStatistics, Event) == 8, "frame statistics layout");
HRESULT STDMETHODCALLTYPE bx_xbox_device_get_frame_statistics_x(void* self, UINT64 token, UINT type_set, UINT* count,
void* statistics);
// Records PresentX for its frame pipeline token (frame_pacing.cpp keeps the history).
void bx_xbox_frame_stats_present(UINT64 token, UINT64 call_time, UINT64 return_time);
struct BxXboxFrameWaitList {
UINT Count;
HANDLE* pObjects;
@@ -179,6 +221,14 @@ D3D12_GPU_VIRTUAL_ADDRESS bx_xbox_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title);
/* True, with the host address in *host, when `title` lies in memory this layer has a host buffer
* for; false (and *host untouched) otherwise. */
bool bx_xbox_try_host_gpu_va(D3D12_GPU_VIRTUAL_ADDRESS title, D3D12_GPU_VIRTUAL_ADDRESS* host);
/* Title memory bound as index or vertex data (placed_x.cpp). Finds the host buffer that holds
* [title, title + size), creating one for plain title memory that has none, gives its address
* in *host and records the range on `list` so that it is copied from the title memory when the
* list is submitted. False when the memory is not readable or no buffer could be made. */
bool bx_xbox_bind_title_memory(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS title, UINT64 size,
D3D12_GPU_VIRTUAL_ADDRESS* host);
void bx_xbox_bound_memory_reset(IUnknown* host_list);
void bx_xbox_refresh_bound_memory(ID3D12CommandList* const* host_lists, UINT count);
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
void bx_xbox_descriptor_heap_forget(IUnknown* host);
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
@@ -227,6 +277,18 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
ID3D12RootSignature* root, REFIID riid, void** ppv);
/* True when [address, address + 32 * count) lies in the title-visible storage of a
CBV/SRV/UAV descriptor heap (descriptor_heaps.cpp). */
bool bx_xbox_title_descriptors(uint64_t address, UINT count);
/* descriptor_heaps.cpp: root buffers. An address in plain title memory gets a host buffer when
translated console shaders are enabled; otherwise it is translated as before. */
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_shader_resource_view(void* self, UINT param, D3D12_GPU_VIRTUAL_ADDRESS address);
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_constant_buffer_view(void* self, UINT param, D3D12_GPU_VIRTUAL_ADDRESS address);
/* pipelines.cpp: the table handle is noted for translated console draws, then bound. */
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_descriptor_table(void* self, UINT param, D3D12_GPU_DESCRIPTOR_HANDLE base);
/* pipelines.cpp: root signatures, widened for translated console shaders when those are enabled. */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_root_signature(void* self, UINT node_mask, const void* blob, SIZE_T size,
REFIID riid, void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void* state, REFIID riid,
void** ppv);
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void* state, REFIID riid,
@@ -273,6 +335,14 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_register_page_pool_x(void* self, D3D12_
HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void* self, HANDLE handle);
/* Committed resources with title-visible memory (committed.cpp). */
// CreateCommittedResourceX takes D3D12XBOX_RESOURCE_DESC: the PC D3D12_RESOURCE_DESC followed by
// DccOptions, a struct of CompressionLevel and ColorTransform (authorized GDK header). DccOptions
// selects console colour compression, which the host does not have; it is logged and otherwise ignored.
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);
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,
@@ -325,12 +395,27 @@ void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D
const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* Console rectangle lists (rect_list.cpp). */
void bx_xbox_rect_pipeline_created(ID3D12PipelineState* host, const D3D12_INPUT_ELEMENT_DESC* elements, UINT count);
D3D12_PRIMITIVE_TOPOLOGY bx_xbox_rect_note_topology(ID3D12GraphicsCommandList* list, D3D12_PRIMITIVE_TOPOLOGY topology);
void bx_xbox_rect_note_vertex_buffers(ID3D12GraphicsCommandList* list, UINT start, UINT count,
const D3D12_VERTEX_BUFFER_VIEW* views);
void bx_xbox_rect_note_pipeline(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host);
void bx_xbox_rect_list_reset(ID3D12GraphicsCommandList* list, ID3D12PipelineState* host);
void bx_xbox_rect_list_forget(ID3D12GraphicsCommandList* list);
bool bx_xbox_rect_list_bound(ID3D12GraphicsCommandList* list);
bool bx_xbox_draw_rect_list(ID3D12GraphicsCommandList* list, UINT vertices, UINT instances, UINT first_vertex,
UINT first_instance);
extern "C" void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_PRIMITIVE_TOPOLOGY topology);
/* Descriptor heaps with title-visible storage (descriptor_heaps.cpp). */
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc,
REFIID riid, void** ppv);
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void* self, D3D12_DESCRIPTOR_HEAP_TYPE type);
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self);
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self);
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors_simple(void* self, UINT count, D3D12_CPU_DESCRIPTOR_HANDLE dest,
D3D12_CPU_DESCRIPTOR_HANDLE src, D3D12_DESCRIPTOR_HEAP_TYPE type);
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
D3D12_CPU_DESCRIPTOR_HANDLE dest);
/* `xbox_desc` is a D3D12XBOX_SAMPLER_DESC. */
@@ -371,6 +456,9 @@ UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, con
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box);
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region_x(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
const D3D12_BOX* box, UINT flags);
}
#include "xbox_tables_generated.h"
+11 -43
View File
@@ -56,20 +56,10 @@ static HRESULT STDMETHODCALLTYPE x_Device_13(void* self, D3D12_FEATURE a0, void
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CheckFeatureSupport", hr);
return hr;
}
static HRESULT STDMETHODCALLTYPE x_Device_16(void* self, UINT a0, const void * a1, SIZE_T a2, REFIID a3, void ** a4) {
BX_D3D_TRACE("XboxDevice", "CreateRootSignature");
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, a1, a2, a3, a4);
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
return bx_xbox_wrap_result(hr, a3, a4);
}
static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC * a0, D3D12_CPU_DESCRIPTOR_HANDLE a1) {
BX_D3D_TRACE("XboxDevice", "CreateSampler");
bx_xbox_host<ID3D12Device>(self)->CreateSampler(a0, bx_xbox_host_cpu_handle(a1));
}
static void STDMETHODCALLTYPE x_Device_24(void* self, UINT a0, const D3D12_CPU_DESCRIPTOR_HANDLE a1, const D3D12_CPU_DESCRIPTOR_HANDLE a2, D3D12_DESCRIPTOR_HEAP_TYPE a3) {
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(a0, bx_xbox_host_cpu_handle(a1), bx_xbox_host_cpu_handle(a2), a3);
}
static D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE x_Device_26(void* self, UINT a0, D3D12_HEAP_TYPE a1) {
BX_D3D_TRACE("XboxDevice", "GetCustomHeapProperties");
D3D12_HEAP_PROPERTIES result{};
@@ -187,12 +177,8 @@ static HRESULT STDMETHODCALLTYPE x_Device_69(void*) { BX_VTABLE_STUB_LOG("XboxDe
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_72(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 72u, "SetGpuMemoryPriorityX"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_76(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 76u, "CreateCommittedResourceX"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_77(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 77u, "CreateComponentPlacedResourceX1"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_81(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 81u, "GetFrameStatisticsX"); return E_NOTIMPL; }
/* Xbox-only method */
static HRESULT STDMETHODCALLTYPE x_Device_82(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 82u, "CreateCounterSetX"); return E_NOTIMPL; }
static HRESULT STDMETHODCALLTYPE x_Device_83(void* self, const void * a0, SIZE_T a1, REFIID a2, void ** a3) {
BX_D3D_TRACE("XboxDevice", "CreatePipelineLibrary");
@@ -420,7 +406,7 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&x_Device_13),
reinterpret_cast<const void*>(&bx_xbox_device_create_descriptor_heap),
reinterpret_cast<const void*>(&bx_xbox_device_get_descriptor_handle_increment_size),
reinterpret_cast<const void*>(&x_Device_16),
reinterpret_cast<const void*>(&bx_xbox_device_create_root_signature),
reinterpret_cast<const void*>(&bx_xbox_device_create_constant_buffer_view),
reinterpret_cast<const void*>(&bx_xbox_device_create_shader_resource_view),
reinterpret_cast<const void*>(&bx_xbox_device_create_unordered_access_view),
@@ -428,7 +414,7 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&bx_xbox_device_create_depth_stencil_view),
reinterpret_cast<const void*>(&x_Device_22),
reinterpret_cast<const void*>(&bx_xbox_device_copy_descriptors),
reinterpret_cast<const void*>(&x_Device_24),
reinterpret_cast<const void*>(&bx_xbox_device_copy_descriptors_simple),
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info),
reinterpret_cast<const void*>(&x_Device_26),
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource),
@@ -480,12 +466,12 @@ const void* const kDeviceTable[] = {
reinterpret_cast<const void*>(&bx_xbox_device_create_command_list_x),
reinterpret_cast<const void*>(&bx_xbox_device_register_page_pool_x),
reinterpret_cast<const void*>(&bx_xbox_device_unregister_page_pool_x),
reinterpret_cast<const void*>(&x_Device_76),
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource_x),
reinterpret_cast<const void*>(&x_Device_77),
reinterpret_cast<const void*>(&bx_xbox_device_set_frame_interval_x),
reinterpret_cast<const void*>(&bx_xbox_device_schedule_frame_event_x),
reinterpret_cast<const void*>(&bx_xbox_device_wait_frame_event_x),
reinterpret_cast<const void*>(&x_Device_81),
reinterpret_cast<const void*>(&bx_xbox_device_get_frame_statistics_x),
reinterpret_cast<const void*>(&x_Device_82),
reinterpret_cast<const void*>(&x_Device_83),
reinterpret_cast<const void*>(&x_Device_84),
@@ -561,7 +547,7 @@ const IID kDeviceIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12Device11: 139 slots (54 forwarded, 44 shared, 41 stubs); hosted on ID3D12Device10. */
/* ID3D12Device11: 139 slots (52 forwarded, 48 shared, 39 stubs); hosted on ID3D12Device10. */
const IID kHostDevice = __uuidof(ID3D12Device10);
static HRESULT STDMETHODCALLTYPE x_Resource_3(void* self, REFGUID a0, UINT * a1, void * a2) {
@@ -1302,10 +1288,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_19(void* self, ID3D12Resourc
BX_D3D_TRACE("XboxGraphicsCommandList", "ResolveSubresource");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ResolveSubresource(bx_xbox_unwrap_as<ID3D12Resource>(a0), a1, bx_xbox_unwrap_as<ID3D12Resource>(a2), a3, a4);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_20(void* self, D3D12_PRIMITIVE_TOPOLOGY a0) {
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetPrimitiveTopology");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->IASetPrimitiveTopology(a0);
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_21(void* self, UINT a0, const D3D12_VIEWPORT * a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "RSSetViewports");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->RSSetViewports(a0, a1);
@@ -1360,10 +1342,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_35(void* self, UINT a0, D3D1
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootDescriptorTable");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootDescriptorTable(a0, bx_xbox_host_gpu_handle(a1));
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_36(void* self, UINT a0, D3D12_GPU_DESCRIPTOR_HANDLE a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootDescriptorTable");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootDescriptorTable(a0, bx_xbox_host_gpu_handle(a1));
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_37(void* self, UINT a0, UINT a1, UINT a2) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRoot32BitConstant");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRoot32BitConstant(a0, a1, a2);
@@ -1384,18 +1362,10 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_41(void* self, UINT a0, D3D1
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootConstantBufferView");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootConstantBufferView(a0, bx_xbox_host_gpu_va(a1));
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_42(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootConstantBufferView");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootConstantBufferView(a0, bx_xbox_host_gpu_va(a1));
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_43(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootShaderResourceView");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_44(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
}
static void STDMETHODCALLTYPE x_GraphicsCommandList_45(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootUnorderedAccessView");
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootUnorderedAccessView(a0, bx_xbox_host_gpu_va(a1));
@@ -1483,8 +1453,6 @@ static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_83(void*) { BX_VTABLE_STUB
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_84(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 84u, "NopX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_85(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 85u, "CopyTextureRegionX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_86(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 86u, "CopyResourceX"); return 0; }
/* Xbox-only method */
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_87(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 87u, "Deprecated_SetPredicationBufferX"); return 0; }
@@ -1670,7 +1638,7 @@ const void* const kGraphicsCommandListTable[] = {
reinterpret_cast<const void*>(&x_GraphicsCommandList_17),
reinterpret_cast<const void*>(&x_GraphicsCommandList_18),
reinterpret_cast<const void*>(&x_GraphicsCommandList_19),
reinterpret_cast<const void*>(&x_GraphicsCommandList_20),
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_primitive_topology),
reinterpret_cast<const void*>(&x_GraphicsCommandList_21),
reinterpret_cast<const void*>(&x_GraphicsCommandList_22),
reinterpret_cast<const void*>(&x_GraphicsCommandList_23),
@@ -1686,15 +1654,15 @@ const void* const kGraphicsCommandListTable[] = {
reinterpret_cast<const void*>(&x_GraphicsCommandList_33),
reinterpret_cast<const void*>(&x_GraphicsCommandList_34),
reinterpret_cast<const void*>(&x_GraphicsCommandList_35),
reinterpret_cast<const void*>(&x_GraphicsCommandList_36),
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_descriptor_table),
reinterpret_cast<const void*>(&x_GraphicsCommandList_37),
reinterpret_cast<const void*>(&x_GraphicsCommandList_38),
reinterpret_cast<const void*>(&x_GraphicsCommandList_39),
reinterpret_cast<const void*>(&x_GraphicsCommandList_40),
reinterpret_cast<const void*>(&x_GraphicsCommandList_41),
reinterpret_cast<const void*>(&x_GraphicsCommandList_42),
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_constant_buffer_view),
reinterpret_cast<const void*>(&x_GraphicsCommandList_43),
reinterpret_cast<const void*>(&x_GraphicsCommandList_44),
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_shader_resource_view),
reinterpret_cast<const void*>(&x_GraphicsCommandList_45),
reinterpret_cast<const void*>(&x_GraphicsCommandList_46),
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_index_buffer),
@@ -1735,7 +1703,7 @@ const void* const kGraphicsCommandListTable[] = {
reinterpret_cast<const void*>(&x_GraphicsCommandList_82),
reinterpret_cast<const void*>(&x_GraphicsCommandList_83),
reinterpret_cast<const void*>(&x_GraphicsCommandList_84),
reinterpret_cast<const void*>(&x_GraphicsCommandList_85),
reinterpret_cast<const void*>(&bx_xbox_list_copy_texture_region_x),
reinterpret_cast<const void*>(&x_GraphicsCommandList_86),
reinterpret_cast<const void*>(&x_GraphicsCommandList_87),
reinterpret_cast<const void*>(&x_GraphicsCommandList_88),
@@ -1817,7 +1785,7 @@ const IID kGraphicsCommandListIids[] = {
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
};
/* ID3D12GraphicsCommandList8: 150 slots (66 forwarded, 24 shared, 60 stubs); hosted on ID3D12GraphicsCommandList7. */
/* ID3D12GraphicsCommandList8: 150 slots (62 forwarded, 29 shared, 59 stubs); hosted on ID3D12GraphicsCommandList7. */
const IID kHostGraphicsCommandList = __uuidof(ID3D12GraphicsCommandList7);
} // namespace
+2 -1
View File
@@ -1,4 +1,5 @@
bx_add_shim_dll(gameinput GameInput GameInput.def
gameinput.cpp
keyboard_gamepad.cpp
)
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32)
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32 user32)
+56 -21
View File
@@ -7,16 +7,19 @@
#include <unordered_map>
#include "bx_log.h"
#include "keyboard_gamepad.h"
namespace {
// GameInputCreate @1 exposes the legacy v0 COM layout.
constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
using Callback = void (WINAPI*)();
using DeviceCallback = void (WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
// GameInputEnumerationKind values from Microsoft's public GDK GameInput (v0) reference:
// 0 = GameInputNoEnumeration, 1 = GameInputAsyncEnumeration, 2 = GameInputBlockingEnumeration.
constexpr uint32_t kMaxEnumerationKind = 2;
constexpr uint32_t kAsyncEnumeration = 1;
constexpr uint32_t kBlockingEnumeration = 2;
struct SrwExclusiveLock {
explicit SrwExclusiveLock(SRWLOCK& lock) : lock_(lock) { AcquireSRWLockExclusive(&lock_); }
@@ -34,7 +37,7 @@ struct RegisteredDeviceCallback {
uint32_t status_filter = 0;
uint32_t enumeration_kind = 0;
void* context = nullptr;
Callback callback = nullptr;
DeviceCallback callback = nullptr;
bool stopped = false;
};
@@ -91,9 +94,15 @@ public:
virtual uint64_t WINAPI GetCurrentTimestamp() {
return GetTickCount64() * 1000;
}
virtual HRESULT WINAPI GetCurrentReading(uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading");
return unavailable(out);
virtual HRESULT WINAPI GetCurrentReading(uint32_t kind, void* device, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!(kind & keyboard_gamepad::input_kind)) {
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading(non-gamepad)");
return E_NOTIMPL;
}
if (device && device != keyboard_gamepad::device()) return keyboard_gamepad::device_not_found;
return keyboard_gamepad::read(out);
}
virtual HRESULT WINAPI GetNextReading(void*, uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 5, "GetNextReading");
@@ -117,25 +126,45 @@ public:
uint32_t status_filter,
uint32_t enumeration_kind,
void* context,
Callback callback,
DeviceCallback callback,
uint64_t* out_token
) {
if (out_token) *out_token = 0;
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kMaxEnumerationKind) {
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kBlockingEnumeration) {
return E_INVALIDARG;
}
SrwExclusiveLock guard(callback_lock_);
const uint64_t token = next_token_++;
callbacks_.emplace(token, RegisteredDeviceCallback{
device,
input_kind,
status_filter,
enumeration_kind,
context,
callback,
false,
});
uint64_t token;
{
SrwExclusiveLock guard(callback_lock_);
token = next_token_++;
callbacks_.emplace(token, RegisteredDeviceCallback{
device,
input_kind,
status_filter,
enumeration_kind,
context,
callback,
false,
});
}
if (out_token) *out_token = token;
auto* pad = keyboard_gamepad::device();
const bool matches = (!device || device == pad) &&
(input_kind & keyboard_gamepad::input_kind) &&
(status_filter & keyboard_gamepad::device_status);
if (matches && enumeration_kind == kBlockingEnumeration) {
// The title requests blocking enumeration. The callback may reenter
// GameInput, so never call it under the registration lock.
static std::atomic_flag reported;
if (!reported.test_and_set(std::memory_order_relaxed)) {
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_connected",
"keyboard gamepad announced through v0 device enumeration");
}
callback(token, context, pad, GetCurrentTimestamp(), keyboard_gamepad::device_status, 0);
} else if (matches && enumeration_kind == kAsyncEnumeration) {
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback(async gamepad enumeration)");
}
return S_OK;
}
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
@@ -166,9 +195,15 @@ public:
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromId(const void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 16, "FindDeviceFromId");
return unavailable(out);
virtual HRESULT WINAPI FindDeviceFromId(const void* id, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!id) return E_INVALIDARG;
if (!keyboard_gamepad::has_id(id)) return keyboard_gamepad::device_not_found;
auto* pad = keyboard_gamepad::device();
pad->AddRef();
*out = pad;
return S_OK;
}
virtual HRESULT WINAPI FindDeviceFromObject(IUnknown*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 17, "FindDeviceFromObject");
+393
View File
@@ -0,0 +1,393 @@
#include "keyboard_gamepad.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdio>
#include <cstring>
#include <new>
#include "bx_log.h"
namespace keyboard_gamepad {
namespace {
// Legacy GameInput v0 interface identities and Win64 data layouts.
constexpr GUID device_iid = {0x31dd86fb, 0x4c1b, 0x408a, {0x86, 0x8f, 0x43, 0x9b, 0x3c, 0xd4, 0x71, 0x25}};
constexpr GUID reading_iid = {0x2156947a, 0xe1fa, 0x4de0, {0xa3, 0x0b, 0xd8, 0x12, 0x93, 0x1d, 0xbd, 0x8d}};
struct GamepadState {
uint32_t buttons;
float left_trigger;
float right_trigger;
float left_x;
float left_y;
float right_x;
float right_y;
};
static_assert(sizeof(GamepadState) == 28);
struct BatteryState {
float rate, max_rate, remaining, capacity;
uint32_t status;
};
static_assert(sizeof(BatteryState) == 20);
struct DeviceString {
uint32_t bytes;
uint32_t code_points;
const char* text;
};
using DeviceId = std::array<uint8_t, 32>;
constexpr DeviceId device_id{{'B', 'e', 't', 't', 'e', 'r', 'X', 'e', 'n', '-', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd'}};
constexpr char device_name[] = "BetterXen Keyboard Gamepad";
constexpr DeviceString display_name{
sizeof(device_name) - 1, sizeof(device_name) - 1, device_name,
};
// Menu, View, A/B/X/Y, D-pad, shoulders, and stick clicks, in v0 label order.
constexpr std::array<uint32_t, 14> gamepad_labels{{4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 17, 20}};
// The virtual device supplies only fixed-format gamepad data. The arrays group
// the zero-valued v0 metadata for raw reports, other input kinds, and motors.
struct DeviceInfo {
uint32_t size;
uint16_t vendor_id, product_id, revision;
uint8_t interface_number, collection_number;
uint16_t usage_page, usage;
uint16_t hardware_version[4], firmware_version[4];
DeviceId id, root_id;
int32_t family;
uint32_t capabilities, supported_input, supported_rumble;
uint32_t counts[12];
const void* other_input_info[12];
const uint32_t* gamepad_info;
const void* wheel_navigation_motor_info[4];
const DeviceString* display_name;
const void* device_strings;
const void* descriptor;
};
static_assert(sizeof(DeviceInfo) == 320);
static_assert(offsetof(DeviceInfo, id) == 32);
static_assert(offsetof(DeviceInfo, supported_input) == 104);
static_assert(offsetof(DeviceInfo, gamepad_info) == 256);
static_assert(offsetof(DeviceInfo, display_name) == 296);
constexpr DeviceInfo device_info{
.size = sizeof(DeviceInfo),
.vendor_id = 0,
.product_id = 0,
.revision = 0,
.interface_number = 0,
.collection_number = 0,
.usage_page = 1,
.usage = 5,
.hardware_version = {},
.firmware_version = {},
.id = device_id,
.root_id = device_id,
.family = -1, // GameInputFamilyVirtual
.capabilities = 0,
.supported_input = input_kind,
.supported_rumble = 0,
.counts = {},
.other_input_info = {},
.gamepad_info = gamepad_labels.data(),
.wheel_navigation_motor_info = {},
.display_name = &display_name,
.device_strings = nullptr,
.descriptor = nullptr,
};
#define DEVICE_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputDevice", slot, method)
#define READING_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputReading", slot, method)
class Device final : public IUnknown {
LONG refs_ = 1; // The shim owns one reference for the lifetime of the device.
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown && iid != device_iid) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
ULONG WINAPI Release() override { return InterlockedDecrement(&refs_); }
virtual const DeviceInfo* WINAPI GetDeviceInfo() { return &device_info; }
virtual uint32_t WINAPI GetDeviceStatus() { return device_status; }
virtual void WINAPI GetBatteryState(BatteryState* out) { if (out) *out = {}; }
virtual HRESULT WINAPI CreateForceFeedbackEffect(uint32_t, const void*, void** out) {
DEVICE_STUB(6, "CreateForceFeedbackEffect");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual bool WINAPI IsForceFeedbackMotorPoweredOn(uint32_t) { return false; }
virtual void WINAPI SetForceFeedbackMotorGain(uint32_t, float) { DEVICE_STUB(8, "SetForceFeedbackMotorGain"); }
virtual HRESULT WINAPI SetHapticMotorState(uint32_t, const void*) {
DEVICE_STUB(9, "SetHapticMotorState");
return E_NOTIMPL;
}
virtual void WINAPI SetRumbleState(const void*) { DEVICE_STUB(10, "SetRumbleState"); }
virtual void WINAPI SetInputSynchronizationState(bool) { DEVICE_STUB(11, "SetInputSynchronizationState"); }
virtual void WINAPI SendInputSynchronizationHint() { DEVICE_STUB(12, "SendInputSynchronizationHint"); }
virtual void WINAPI PowerOff() { DEVICE_STUB(13, "PowerOff"); }
virtual HRESULT WINAPI CreateRawDeviceReport(uint32_t, uint32_t, void** out) {
DEVICE_STUB(14, "CreateRawDeviceReport");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual HRESULT WINAPI GetRawDeviceFeature(uint32_t, void** out) {
DEVICE_STUB(15, "GetRawDeviceFeature");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual HRESULT WINAPI SetRawDeviceFeature(void*) {
DEVICE_STUB(16, "SetRawDeviceFeature");
return E_NOTIMPL;
}
virtual HRESULT WINAPI SendRawDeviceOutput(void*) {
DEVICE_STUB(17, "SendRawDeviceOutput");
return E_NOTIMPL;
}
virtual HRESULT WINAPI SendRawDeviceOutputWithResponse(void*, void** out) {
DEVICE_STUB(18, "SendRawDeviceOutputWithResponse");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual HRESULT WINAPI ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* out) {
DEVICE_STUB(19, "ExecuteRawDeviceIoControl");
if (out) *out = 0;
return E_NOTIMPL;
}
virtual bool WINAPI AcquireExclusiveRawDeviceAccess(uint64_t) {
DEVICE_STUB(20, "AcquireExclusiveRawDeviceAccess");
return false;
}
virtual void WINAPI ReleaseExclusiveRawDeviceAccess() { DEVICE_STUB(21, "ReleaseExclusiveRawDeviceAccess"); }
};
Device virtual_device;
bool pressed(int key) { return (GetAsyncKeyState(key) & 0x8000) != 0; }
bool owns_foreground() {
const HWND foreground = GetForegroundWindow();
DWORD pid = 0;
return foreground && GetWindowThreadProcessId(foreground, &pid) && pid == GetCurrentProcessId();
}
void sample_stick(int left, int right, int down, int up, float& x, float& y) {
x = static_cast<float>(pressed(right) - pressed(left));
y = static_cast<float>(pressed(up) - pressed(down));
if (x != 0 && y != 0) {
constexpr float diagonal = 0.70710678f;
x *= diagonal;
y *= diagonal;
}
}
/* Diagnostic (off unless BX_INPUT_SCRIPT is set): scripted gamepad presses, so an unattended run
can get past screens that wait for input without window focus. The script is a comma-separated
list of BUTTON@SECONDS, for example "A@40,DOWN@50.5,A@52"; each press holds the button for
300 ms, timed from the first reading of the keyboard gamepad. Buttons: MENU VIEW A B X Y UP DOWN
LEFT RIGHT. Each press is logged once (input_script); an entry it cannot read is logged and
skipped. */
struct ScriptedPress {
uint32_t button;
uint64_t at_ms;
};
constexpr size_t kMaxScriptedPresses = 128;
constexpr uint64_t kScriptedHoldMs = 300;
struct InputScript {
ScriptedPress presses[kMaxScriptedPresses];
std::atomic<bool> logged[kMaxScriptedPresses];
size_t count = 0;
uint64_t start_ms = 0;
};
uint32_t script_button(const char* name, size_t length) {
constexpr struct { const char* name; uint32_t bit; } names[] = {
{"MENU", 0x1}, {"VIEW", 0x2}, {"A", 0x4}, {"B", 0x8}, {"X", 0x10},
{"Y", 0x20}, {"UP", 0x40}, {"DOWN", 0x80}, {"LEFT", 0x100}, {"RIGHT", 0x200},
};
for (const auto& n : names) {
if (std::strlen(n.name) == length && std::strncmp(n.name, name, length) == 0) return n.bit;
}
return 0;
}
InputScript* load_script() {
char spec[2048] = {};
const DWORD n = GetEnvironmentVariableA("BX_INPUT_SCRIPT", spec, sizeof(spec));
if (n == 0 || n >= sizeof(spec)) return nullptr;
auto* script = new (std::nothrow) InputScript();
if (!script) return nullptr;
for (const char* item = spec; *item && script->count < kMaxScriptedPresses;) {
const char* end = std::strchr(item, ',');
const size_t length = end ? static_cast<size_t>(end - item) : std::strlen(item);
const char* at = static_cast<const char*>(std::memchr(item, '@', length));
char seconds[32] = {};
uint32_t button = 0;
if (at && static_cast<size_t>(item + length - at - 1) < sizeof(seconds)) {
std::memcpy(seconds, at + 1, static_cast<size_t>(item + length - at - 1));
button = script_button(item, static_cast<size_t>(at - item));
}
char* parsed_end = nullptr;
const double when = std::strtod(seconds, &parsed_end);
if (button && parsed_end != seconds && *parsed_end == 0 && when >= 0) {
script->presses[script->count++] = {button, static_cast<uint64_t>(when * 1000.0)};
} else {
char detail[96];
std::snprintf(detail, sizeof(detail), "unreadable entry '%.*s' skipped", static_cast<int>(length < 40 ? length : 40), item);
bx_log_emit(BX_LOG_WARN, "gameinput", "input_script", detail);
}
item = end ? end + 1 : item + length;
}
script->start_ms = GetTickCount64();
return script;
}
uint32_t scripted_buttons() {
static InputScript* const script = load_script();
if (!script) return 0;
const uint64_t now = GetTickCount64() - script->start_ms;
uint32_t buttons = 0;
for (size_t i = 0; i < script->count; ++i) {
const ScriptedPress& press = script->presses[i];
if (now < press.at_ms || now >= press.at_ms + kScriptedHoldMs) continue;
buttons |= press.button;
if (!script->logged[i].exchange(true)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "scripted press 0x%x at %.1f s", press.button, now / 1000.0);
bx_log_emit(BX_LOG_INFO, "gameinput", "input_script", detail);
}
}
return buttons;
}
GamepadState sample_keyboard() {
GamepadState state{};
const uint32_t scripted = scripted_buttons();
if (!owns_foreground()) {
state.buttons = scripted;
return state;
}
constexpr struct KeyBinding { int key; uint32_t button; } buttons[] = {
{'P', 0x1}, {VK_TAB, 0x2}, {VK_RETURN, 0x4}, {VK_SPACE, 0x4},
{VK_ESCAPE, 0x8}, {VK_BACK, 0x8}, {'X', 0x10}, {'Y', 0x20},
{VK_UP, 0x40}, {VK_DOWN, 0x80}, {VK_LEFT, 0x100}, {VK_RIGHT, 0x200},
{'Q', 0x400}, {'E', 0x800}, {'F', 0x1000}, {'H', 0x2000},
};
for (const auto& binding : buttons) {
if (pressed(binding.key)) state.buttons |= binding.button;
}
state.left_trigger = pressed('Z') ? 1.0f : 0.0f;
state.right_trigger = pressed('C') ? 1.0f : 0.0f;
sample_stick('A', 'D', 'S', 'W', state.left_x, state.left_y);
sample_stick('J', 'L', 'K', 'I', state.right_x, state.right_y);
if (!owns_foreground()) state = GamepadState{};
state.buttons |= scripted;
return state;
}
struct Sample {
GamepadState state{};
uint64_t sequence = 0;
uint64_t timestamp = 0;
};
SRWLOCK sample_lock = SRWLOCK_INIT;
Sample latest;
Sample sample() {
AcquireSRWLockExclusive(&sample_lock);
const GamepadState state = sample_keyboard();
if (!latest.sequence || std::memcmp(&state, &latest.state, sizeof(state)) != 0) {
latest = {state, latest.sequence + 1, GetTickCount64() * 1000};
}
const Sample snapshot = latest;
ReleaseSRWLockExclusive(&sample_lock);
return snapshot;
}
class Reading final : public IUnknown {
LONG refs_ = 1;
const Sample sample_;
public:
explicit Reading(const Sample& value) : sample_(value) {}
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown && iid != reading_iid) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
ULONG WINAPI Release() override {
const auto left = InterlockedDecrement(&refs_);
if (!left) delete this;
return left;
}
virtual uint32_t WINAPI GetInputKind() { return input_kind; }
virtual uint64_t WINAPI GetSequenceNumber(uint32_t kind) { return kind & input_kind ? sample_.sequence : 0; }
virtual uint64_t WINAPI GetTimestamp() { return sample_.timestamp; }
virtual void WINAPI GetDevice(void** out) {
if (!out) return;
virtual_device.AddRef();
*out = &virtual_device;
}
virtual bool WINAPI GetRawReport(void** out) {
if (out) *out = nullptr;
return false;
}
virtual uint32_t WINAPI GetControllerAxisCount() { return 0; }
virtual uint32_t WINAPI GetControllerAxisState(uint32_t, float*) { return 0; }
virtual uint32_t WINAPI GetControllerButtonCount() { return 0; }
virtual uint32_t WINAPI GetControllerButtonState(uint32_t, bool*) { return 0; }
virtual uint32_t WINAPI GetControllerSwitchCount() { return 0; }
virtual uint32_t WINAPI GetControllerSwitchState(uint32_t, uint32_t*) { return 0; }
virtual uint32_t WINAPI GetKeyCount() { return 0; }
virtual uint32_t WINAPI GetKeyState(uint32_t, void*) { return 0; }
virtual bool WINAPI GetMouseState(void*) { READING_STUB(16, "GetMouseState"); return false; }
virtual uint32_t WINAPI GetTouchCount() { return 0; }
virtual uint32_t WINAPI GetTouchState(uint32_t, void*) { return 0; }
virtual bool WINAPI GetMotionState(void*) { READING_STUB(19, "GetMotionState"); return false; }
virtual bool WINAPI GetArcadeStickState(void*) { READING_STUB(20, "GetArcadeStickState"); return false; }
virtual bool WINAPI GetFlightStickState(void*) { READING_STUB(21, "GetFlightStickState"); return false; }
virtual bool WINAPI GetGamepadState(GamepadState* out) {
if (!out) return false;
*out = sample_.state;
static std::atomic_flag reported;
if ((out->buttons || out->left_trigger || out->right_trigger || out->left_x || out->left_y ||
out->right_x || out->right_y) && !reported.test_and_set(std::memory_order_relaxed)) {
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_input",
"guest read a non-neutral keyboard gamepad state");
}
return true;
}
virtual bool WINAPI GetRacingWheelState(void*) { READING_STUB(23, "GetRacingWheelState"); return false; }
virtual bool WINAPI GetUiNavigationState(void*) { READING_STUB(24, "GetUiNavigationState"); return false; }
};
} // namespace
IUnknown* device() { return &virtual_device; }
bool has_id(const void* id) {
return id && std::memcmp(id, device_id.data(), device_id.size()) == 0;
}
HRESULT read(void** out) {
*out = new (std::nothrow) Reading(sample());
return *out ? S_OK : E_OUTOFMEMORY;
}
} // namespace keyboard_gamepad
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
namespace keyboard_gamepad {
constexpr uint32_t input_kind = 0x00040000;
constexpr uint32_t device_status = 0x3; // connected and input enabled
constexpr HRESULT device_not_found = static_cast<HRESULT>(0x838a0002u);
IUnknown* device();
bool has_id(const void* id);
HRESULT read(void** out);
} // namespace keyboard_gamepad
+186
View File
@@ -1,6 +1,7 @@
#include <windows.h>
#include <tlhelp32.h>
#include <atomic>
#include <utility>
#include <cstdio>
#include <cstdarg>
#include <cstdlib>
@@ -327,6 +328,65 @@ uint64_t clzero_loop_fast_path(CONTEXT& context) {
return done;
}
// A title that flushes an address range with CLWB does it in a loop, and each iteration would
// trap again: an exception round trip per 64 bytes, tens of thousands per second for as long as
// the range lasts. CLWB writes a cache line back to memory and changes no register, flag or
// memory content, so emulating it is skipping it, and skipping a whole range has the same result
// as skipping its lines one by one. When the trapped CLWB has the form `clwb [reg]` (no index, no
// displacement) and is followed by exactly
// add reg, 0x40 ; cmp reg, <reg64> ; jbe|jb <the clwb>
// the pointer register is advanced here to the last value for which the loop would still have run
// the CLWB, so the title's own add/cmp/jcc then leaves the loop. `length` is the decoded length
// of the CLWB at RIP. Returns the number of iterations skipped (0 when the form does not match).
uint64_t clwb_loop_fast_path(CONTEXT& context, size_t length) {
const auto* code = reinterpret_cast<const uint8_t*>(context.Rip);
MEMORY_BASIC_INFORMATION text{};
if (length < 4 || length > 5 || !VirtualQuery(code, &text, sizeof(text)) || text.State != MEM_COMMIT ||
reinterpret_cast<uintptr_t>(code) + length + 9 > reinterpret_cast<uintptr_t>(text.BaseAddress) + text.RegionSize) {
return 0;
}
// 66 [REX] 0F AE /6, ModRM mod=00 with a plain base register.
size_t i = 0;
if (code[i++] != 0x66) return 0;
uint8_t rex = 0;
if (length == 5) {
rex = code[i++];
if ((rex & 0xF0) != 0x40 || (rex & 0x02)) return 0; // no index extension: there is no SIB byte
}
if (code[i] != 0x0F || code[i + 1] != 0xAE) return 0;
const uint8_t modrm = code[i + 2];
if ((modrm & 0xC0) != 0x00 || ((modrm >> 3) & 7) != 6) return 0;
const unsigned low = modrm & 7;
if (low == 4 || low == 5) return 0; // SIB or RIP-relative
const unsigned pointer = low | ((rex & 0x01) ? 8 : 0);
const uint8_t* next = code + length;
// add pointer, 0x40 REX.W [+B] 83 /0 ib
if (next[0] != (pointer >= 8 ? 0x49 : 0x48) || next[1] != 0x83 || next[2] != (0xC0 | low) || next[3] != 0x40) return 0;
// cmp pointer, limit REX.W [+R] [+B] 39 /r, ModRM mod=11, rm = pointer, reg = limit
if ((next[4] & 0xFA) != 0x48 || next[5] != 0x39 || (next[6] & 0xC7) != (0xC0 | low)) return 0;
if (((next[4] & 0x01) != 0) != (pointer >= 8)) return 0;
const unsigned limit_reg = ((next[6] >> 3) & 7) | ((next[4] & 0x04) ? 8 : 0);
// jbe|jb back to the CLWB
const bool inclusive = next[7] == 0x76;
if (!inclusive && next[7] != 0x72) return 0;
if (next + 9 + static_cast<int8_t>(next[8]) != code) return 0;
if (limit_reg == pointer || pointer == 4 || limit_reg == 4) return 0;
DWORD64* registers = &context.Rax; // Rax, Rcx, Rdx, Rbx, Rsp, Rbp, Rsi, Rdi, R8..R15
constexpr uint64_t line = 64;
const uint64_t current = registers[pointer];
const uint64_t limit = registers[limit_reg];
// The loop runs the CLWB again for pointer values current + 64k that are <= limit (jbe) or
// < limit (jb). `top` is the largest value that still runs.
if (!inclusive && limit == 0) return 0;
const uint64_t top = inclusive ? limit : limit - 1;
if (current > top || top - current < line) return 0; // no further iteration
if (top > UINT64_MAX - line) return 0; // the title's add would wrap
const uint64_t skipped = (top - current) / line;
registers[pointer] = current + skipped * line;
return skipped;
}
bool apply_amd_instruction(const AmdInstruction& instruction, CONTEXT& context,
EXCEPTION_RECORD& exception) {
switch (instruction.kind) {
@@ -1271,6 +1331,125 @@ void disarm_diagnostics() {
}
}
/* Diagnostic (off unless BX_CONTINUE_ASSERTS=1): a title's continuable assert is an int3 in its
own executable followed by code that carries on when no debugger is attached to take it. With
the switch, such an int3 in the main executable is stepped over instead of reaching the title's
crash reporter. Each address is logged once (assert_continued), so the run report still lists
every assert that fired. An int3 anywhere else (BetterXen, system or other modules) is left as
it was. */
static bool continue_assert(PEXCEPTION_POINTERS ep) {
// Reading the switch and querying memory must not change the faulting thread's last-error
// value, which the title may read after it continues (test_veh_breakpoint checks it).
struct KeepLastError {
DWORD saved = GetLastError();
~KeepLastError() { SetLastError(saved); }
} keep_last_error;
static const bool enabled = [] {
char v[4] = {};
const DWORD n = GetEnvironmentVariableA("BX_CONTINUE_ASSERTS", v, sizeof(v));
return n == 1 && v[0] == '1';
}();
if (!enabled) return false;
const auto at = reinterpret_cast<uintptr_t>(ep->ExceptionRecord->ExceptionAddress);
const auto exe = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(at), &region, sizeof(region)) ||
reinterpret_cast<uintptr_t>(region.AllocationBase) != exe || *reinterpret_cast<const uint8_t*>(at) != 0xCC) {
return false;
}
static std::atomic<uintptr_t> seen[256];
bool first = true;
for (auto& slot : seen) {
uintptr_t value = slot.load();
if (value == at) {
first = false;
break;
}
if (value == 0 && slot.compare_exchange_strong(value, at)) break;
if (value == at) {
first = false;
break;
}
}
if (first) {
char detail[96];
std::snprintf(detail, sizeof(detail), "title assert at rva 0x%llx stepped over",
static_cast<unsigned long long>(at - exe));
bx_log_emit(BX_LOG_WARN, "runtime_veh", "assert_continued", detail);
}
ep->ContextRecord->Rip = at + 1;
return true;
}
/* A title thread can read or write a page of an XMEM_MAPPABLE reservation while another thread
remaps part of the same run of pages. xmem replaces the whole run's view and maps the rest
back (physical_pages.cpp), so for a moment every page of the run is unmapped; on the console
the page-table update is atomic and other pages never disappear (#722). When a fault in the
title's own code hits an address that is not accessible, wait for any remap in progress (the
xmem remap guard: entering it waits for exclusive remaps to finish) and retry the instruction
if the address is now accessible for that access. Genuine faults still reach the title: the
address stays inaccessible, or the same instruction faults again more than three times in a
row. Faults in BetterXen's own code are left alone, since they may already hold the guard. */
static bool accessible(uintptr_t address, ULONG_PTR access) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<void*>(address), &region, sizeof(region)) || region.State != MEM_COMMIT) return false;
const DWORD p = region.Protect & 0xFF;
if ((region.Protect & PAGE_GUARD) || p == PAGE_NOACCESS) return false;
if (access == 1) {
return p == PAGE_READWRITE || p == PAGE_WRITECOPY || p == PAGE_EXECUTE_READWRITE || p == PAGE_EXECUTE_WRITECOPY;
}
return true;
}
static bool retry_after_remap(PEXCEPTION_POINTERS ep) {
using GuardFn = void (*)(void);
static const std::pair<GuardFn, GuardFn> guard = [] {
HMODULE xmem = GetModuleHandleW(L"xmem.dll");
auto enter = xmem ? reinterpret_cast<GuardFn>(reinterpret_cast<void*>(GetProcAddress(xmem, "bx_xmem_remap_guard_enter"))) : nullptr;
auto leave = xmem ? reinterpret_cast<GuardFn>(reinterpret_cast<void*>(GetProcAddress(xmem, "bx_xmem_remap_guard_leave"))) : nullptr;
return (enter && leave) ? std::make_pair(enter, leave) : std::make_pair(GuardFn{}, GuardFn{});
}();
const EXCEPTION_RECORD& rec = *ep->ExceptionRecord;
if (!guard.first || rec.NumberParameters < 2 || rec.ExceptionInformation[0] == 8) return false;
const auto rip = static_cast<uintptr_t>(ep->ContextRecord->Rip);
const auto exe = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
MEMORY_BASIC_INFORMATION code{};
if (!VirtualQuery(reinterpret_cast<void*>(rip), &code, sizeof(code)) || reinterpret_cast<uintptr_t>(code.AllocationBase) != exe) {
return false;
}
thread_local uintptr_t last_rip = 0;
thread_local int repeats = 0;
repeats = (rip == last_rip) ? repeats + 1 : 0;
last_rip = rip;
if (repeats > 3) return false;
const uintptr_t address = rec.ExceptionInformation[1];
const ULONG_PTR access = rec.ExceptionInformation[0];
const DWORD saved_error = GetLastError();
guard.first(); // waits until no remap is in progress
guard.second();
const bool now = accessible(address, access);
static std::atomic<uint64_t> retries{0}, refused{0};
char detail[160];
if (!now) {
const uint64_t n = refused.fetch_add(1) + 1;
if (n <= 8) {
std::snprintf(detail, sizeof(detail), "title fault at rva 0x%llx on %s of an address still unmapped after waiting for remaps",
static_cast<unsigned long long>(rip - exe), access == 1 ? "write" : "read");
bx_log_emit(BX_LOG_INFO, "runtime_veh", "remap_window_checked", detail);
}
SetLastError(saved_error);
return false;
}
const uint64_t n = retries.fetch_add(1) + 1;
if (n <= 16 || (n & (n - 1)) == 0) {
std::snprintf(detail, sizeof(detail), "title fault at rva 0x%llx on %s of a page being remapped: retried (%llu so far)",
static_cast<unsigned long long>(rip - exe), access == 1 ? "write" : "read", static_cast<unsigned long long>(n));
bx_log_emit(BX_LOG_WARN, "runtime_veh", "remap_window_retry", detail);
}
SetLastError(saved_error);
return true;
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
return EXCEPTION_CONTINUE_SEARCH;
@@ -1281,9 +1460,11 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
const DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code == EXCEPTION_BREAKPOINT || code == kStatusAssertionFailure) {
log_breakpoint(*ep->ExceptionRecord);
if (code == EXCEPTION_BREAKPOINT && continue_assert(ep)) return EXCEPTION_CONTINUE_EXECUTION;
return EXCEPTION_CONTINUE_SEARCH;
}
if (code == EXCEPTION_ACCESS_VIOLATION) {
if (retry_after_remap(ep)) return EXCEPTION_CONTINUE_EXECUTION;
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
MEMORY_BASIC_INFORMATION region{};
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, &region, sizeof(region)) && region.Type == MEM_IMAGE)) {
@@ -1302,6 +1483,11 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
if (len > 0) {
uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1;
log_sampled_trap("clwb_trapped", count, ep->ContextRecord->Rip, len);
static std::atomic<uint64_t> batched{0};
if (clwb_loop_fast_path(*ep->ContextRecord, len) && batched.fetch_add(1) == 0) {
bx_log_emit(BX_LOG_INFO, "runtime_veh", "clwb_loop",
"CLWB range loop (add reg,0x40; cmp; jbe|jb) completed in one trap; later loops are not logged");
}
ep->ContextRecord->Rip += len;
return EXCEPTION_CONTINUE_EXECUTION;
}
+9 -1
View File
@@ -55,7 +55,15 @@ struct Request {
UINT compression;
ID3D12Resource* resource = nullptr;
UINT64 resource_offset = 0;
DWORD output_size = 0; // compression_zlib: bytes the stream inflates to at `destination`
DWORD output_size = 0; // compression_zlib/bcpack: bytes the stream decodes to at `destination`
UINT bcpack_mode = 0; // compression_bcpack: DSTORAGE_BCPACK_MODE (BCn format 1-7)
// Xbox physical-page destination: the title's array of 64 KB page numbers and the offset into
// the first page. The title may fill the array after it enqueues the request, so the pages are
// mapped into `page_span` only when the request runs, and unmapped once it has been fulfilled.
const ULONG_PTR* page_array = nullptr;
UINT32 page_offset = 0;
void* page_span = nullptr;
ULONG_PTR page_span_count = 0;
};
inline constexpr UINT compression_none = 0;
+215 -15
View File
@@ -212,11 +212,48 @@ void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource,
list->ResourceBarrier(1, &barrier);
}
HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* source, DWORD size) {
// Title memory can be temporarily inaccessible while xmem replaces a mapped view. Keep reads
// and writes out of that window. Never nest guards or hold one across an XMem call.
class RemapGuard {
public:
explicit RemapGuard(bool needed = true) {
if (!needed) return;
const HMODULE xmem = GetModuleHandleW(L"xmem.dll");
if (!xmem) return;
const auto enter = resolve(xmem, "bx_xmem_remap_guard_enter");
leave_ = resolve(xmem, "bx_xmem_remap_guard_leave");
if (enter && leave_) {
enter();
} else {
leave_ = nullptr;
static std::atomic<bool> warned{false};
if (!warned.exchange(true)) {
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_remap_guard",
"loaded xmem.dll does not provide both remap guard exports");
}
}
}
~RemapGuard() {
if (leave_) leave_();
}
RemapGuard(const RemapGuard&) = delete;
RemapGuard& operator=(const RemapGuard&) = delete;
private:
using Fn = void (*)();
static Fn resolve(HMODULE module, const char* name) {
return reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(module, name)));
}
Fn leave_ = nullptr;
};
HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* source, DWORD size,
bool title_destination = false) {
if (!size) return S_OK;
if (!destination) return E_INVALIDARG;
if (!file) {
if (!source) return E_INVALIDARG;
RemapGuard remap_guard;
std::memmove(destination, source, size);
return S_OK;
}
@@ -229,6 +266,7 @@ HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* so
DWORD bytes = 0;
HRESULT result = S_OK;
RemapGuard remap_guard(title_destination);
if (!ReadFile(file, destination, size, &bytes, &operation)) {
const DWORD error = GetLastError();
if (error != ERROR_IO_PENDING) {
@@ -252,7 +290,7 @@ HRESULT write_mapped(HANDLE file, const Request& request) {
return E_FAIL;
}
auto* destination = static_cast<unsigned char*>(mapped) + static_cast<SIZE_T>(request.resource_offset);
const HRESULT read_hr = read_bytes(file, request.file_offset, destination, request.source, request.size);
const HRESULT read_hr = read_bytes(file, request.file_offset, destination, request.source, request.size, true);
D3D12_RANGE written{
static_cast<SIZE_T>(request.resource_offset),
static_cast<SIZE_T>(request.resource_offset + request.size)};
@@ -418,14 +456,89 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
return staged.finish(win32_error());
}
/* A title may read only the first part of a compressed block: the stream then holds more than
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and its first
`output_size` bytes are delivered. A stream shorter than the destination stays an error. */
BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& request) {
const size_t capacity = static_cast<size_t>(request.output_size) * 64 + 0x40000;
auto* whole = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, capacity));
if (!whole) return BxInflateResult::output_mismatch;
size_t produced = 0;
BxInflateResult r = bx_zlib_inflate_any(compressed, request.size, whole, capacity, &produced);
if (r == BxInflateResult::ok && produced > request.output_size) {
std::memcpy(request.destination, whole, request.output_size);
} else if (r == BxInflateResult::ok) {
r = BxInflateResult::output_mismatch;
}
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
std::snprintf(detail, sizeof(detail), "zlib stream of %lu bytes holds %llu bytes, destination %lu: %s", request.size,
static_cast<unsigned long long>(produced), request.output_size,
r == BxInflateResult::ok ? "first part delivered" : bx_inflate_result_name(r));
bx_log_emit(r == BxInflateResult::ok ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "dstorage_zlib_partial", detail);
}
HeapFree(GetProcessHeap(), 0, whole);
return r;
}
/* BCPack (Xbox texture block compression, DSTORAGE_BCPACK_MODE). The codec is Microsoft's
BCPack.dll from the GDK's PC tools, loaded from BX_BCPACK_DLL when set (each collaborator's own
GDK; never shipped). Its documented entry point (GDK BCPack.h): BCPackDecompress(bcIndex,
output, outputSize, packed, packedSize). Without it, BCPack requests stay refused (E_NOTIMPL). */
using BcpackDecompressFn = HRESULT(__cdecl*)(size_t, void*, size_t, const void*, size_t);
BcpackDecompressFn bcpack_decompress() {
static const BcpackDecompressFn fn = [] {
wchar_t path[MAX_PATH];
const DWORD n = GetEnvironmentVariableW(L"BX_BCPACK_DLL", path, MAX_PATH);
if (n == 0 || n >= MAX_PATH) return static_cast<BcpackDecompressFn>(nullptr);
HMODULE dll = LoadLibraryW(path);
auto found = dll ? reinterpret_cast<BcpackDecompressFn>(reinterpret_cast<void*>(GetProcAddress(dll, "BCPackDecompress")))
: nullptr;
char detail[96];
std::snprintf(detail, sizeof(detail), "BX_BCPACK_DLL %s (error %lu)", found ? "loaded" : "not usable",
found ? 0ul : GetLastError());
bx_log_emit(found ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "bcpack_codec", detail);
return found;
}();
return fn;
}
HRESULT bcpack_request(HANDLE file, const Request& request) {
const BcpackDecompressFn decompress = bcpack_decompress();
if (!decompress) return E_NOTIMPL;
if (!request.destination || !request.output_size || !request.size) return E_INVALIDARG;
auto* packed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
if (!packed) return E_OUTOFMEMORY;
HRESULT hr = read_bytes(file, request.file_offset, packed, request.source, request.size);
if (SUCCEEDED(hr)) {
RemapGuard remap_guard;
hr = decompress(request.bcpack_mode, request.destination, request.output_size, packed, request.size);
if (FAILED(hr)) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
char detail[160];
std::snprintf(detail, sizeof(detail), "BCPack BC%u stream of %lu bytes to %lu bytes: hr=0x%08lx", request.bcpack_mode,
request.size, request.output_size, static_cast<unsigned long>(hr));
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_bcpack_failed", detail);
}
hr = E_DSTORAGE_DECOMPRESSION_ERROR;
}
}
HeapFree(GetProcessHeap(), 0, packed);
return hr;
}
HRESULT inflate_request(HANDLE file, const Request& request) {
if (!request.destination || !request.output_size || request.size >= request.output_size) return E_INVALIDARG;
auto* compressed = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, request.size));
if (!compressed) return E_OUTOFMEMORY;
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
if (SUCCEEDED(hr)) {
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
RemapGuard remap_guard;
BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
request.output_size);
if (r == BxInflateResult::output_mismatch) r = inflate_first_part(compressed, request);
if (r != BxInflateResult::ok) {
static std::atomic<UINT> logged{0};
if (logged.fetch_add(1) < 16) {
@@ -459,9 +572,13 @@ CopyResult fulfill(HANDLE file, const Request& request) {
if (!dstorage_trace_enabled() || request.resource) return result;
static std::atomic<UINT> traced{0};
if (traced.fetch_add(1) >= 20000) return result;
const DWORD out = request.compression == compression_zlib ? request.output_size : request.size;
const DWORD out = (request.compression == compression_zlib || request.compression == compression_bcpack) ? request.output_size
: request.size;
uint64_t head[2] = {0, 0};
if (SUCCEEDED(result.hr) && request.destination && out >= 16) std::memcpy(head, request.destination, 16);
if (SUCCEEDED(result.hr) && request.destination && out >= 16) {
RemapGuard remap_guard;
std::memcpy(head, request.destination, 16);
}
char detail[220];
std::snprintf(detail, sizeof(detail), "dst=%p..%p out=%lu src=%lu offset=0x%llx compression=%u hr=0x%08lx head=%016llx %016llx",
request.destination, static_cast<const uint8_t*>(request.destination) + out, out, request.size,
@@ -473,6 +590,10 @@ CopyResult fulfill(HANDLE file, const Request& request) {
}
CopyResult fulfill_request(HANDLE file, const Request& request) {
if (request.compression == compression_bcpack && request.bcpack_mode) {
if (request.resource) return {E_NOTIMPL, false};
return {bcpack_request(file, request), false};
}
if (request.compression == compression_zlib) {
if (request.resource) return {E_NOTIMPL, false};
return {inflate_request(file, request), false};
@@ -483,7 +604,7 @@ CopyResult fulfill_request(HANDLE file, const Request& request) {
}
if (!request.size) return {};
if (!request.resource) {
return {read_bytes(file, request.file_offset, request.destination, request.source, request.size), false};
return {read_bytes(file, request.file_offset, request.destination, request.source, request.size, true), false};
}
const D3D12_RESOURCE_DESC desc = request.resource->GetDesc();
@@ -511,6 +632,56 @@ CopyResult fulfill_request(HANDLE file, const Request& request) {
// before Submit: a full queue stalls the enqueuer until Submit is called on
// another thread and the drain frees a slot. The public DirectStorage queues use
// both; the BetterXen synthetic queues use neither.
// Xbox physical-page destinations (DSTORAGE_REQUEST.DestinationPageArray, authorized GDK header):
// 64 KB page numbers from XMemAllocatePhysicalPages. The request writes through a span of its own:
// xmem.dll's XMemMapPhysicalPages with a NULL address (a BetterXen extension, see
// shims/xmem/physical_pages.cpp) maps the pages contiguously, and the same call with a NULL page
// array unmaps the span. The pages are sections, so the title's own views see the bytes.
using MapPhysicalPagesFn = PVOID(WINAPI*)(PVOID, ULONG_PTR, PULONG_PTR);
MapPhysicalPagesFn map_physical_pages() {
static const MapPhysicalPagesFn fn = [] {
HMODULE xmem = GetModuleHandleW(L"xmem.dll");
if (!xmem) xmem = LoadLibraryW(L"xmem.dll");
return xmem ? reinterpret_cast<MapPhysicalPagesFn>(
reinterpret_cast<void*>(GetProcAddress(xmem, "XMemMapPhysicalPages")))
: nullptr;
}();
return fn;
}
/* Maps a physical-page destination's pages when the request runs. The title can fill its page
array after EnqueueRequest returns, so the array is read here, not at enqueue. */
HRESULT map_page_destination(Request& request) {
if (!request.page_array) return S_OK;
const MapPhysicalPagesFn map = map_physical_pages();
void* span = map ? map(nullptr, request.page_span_count, const_cast<PULONG_PTR>(request.page_array)) : nullptr;
if (!span) {
const DWORD error = map ? GetLastError() : ERROR_PROC_NOT_FOUND;
char detail[128];
std::snprintf(detail, sizeof(detail), "mapping %llu destination pages failed error=%lu",
static_cast<unsigned long long>(request.page_span_count), error);
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
return HRESULT_FROM_WIN32(error);
}
request.page_span = span;
request.destination = static_cast<BYTE*>(span) + request.page_offset;
return S_OK;
}
void unmap_page_span(Request& request) {
if (!request.page_span) return;
const MapPhysicalPagesFn map = map_physical_pages();
if (!map || !map(request.page_span, request.page_span_count, nullptr)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "unmapping %llu destination pages failed error=%lu",
static_cast<unsigned long long>(request.page_span_count), GetLastError());
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_page_destination", detail);
}
request.page_span = nullptr;
request.page_span_count = 0;
}
class WorkQueue final : public Object<Queue, queue_iid> {
public:
WorkQueue(Entry* entries, UINT capacity, bool blocking = false, UINT auto_submit = 0)
@@ -536,7 +707,8 @@ public:
Entry entry{Kind::request, *request};
if (request->resource) request->resource->AddRef();
// Uncompressed and zlib requests read the file; other compressions are refused when fulfilled.
if (request->file && (request->compression == compression_none || request->compression == compression_zlib)) {
if (request->file && (request->compression == compression_none || request->compression == compression_zlib ||
request->compression == compression_bcpack)) {
const HRESULT result = request->file->GetHandle(&entry.handle);
if (FAILED(result)) {
if (request->resource) request->resource->Release();
@@ -727,8 +899,10 @@ private:
HRESULT result = S_OK;
switch (entry.kind) {
case Kind::request: {
const CopyResult outcome = fulfill(entry.handle, entry.request);
const HRESULT mapped = map_page_destination(entry.request);
const CopyResult outcome = SUCCEEDED(mapped) ? fulfill(entry.handle, entry.request) : CopyResult{mapped, false};
result = outcome.hr;
unmap_page_span(entry.request);
if (entry.handle) CloseHandle(entry.handle);
// keep_destination holds the AddRef taken at enqueue. Releasing
// it while the staged copy is still on the GPU frees the dest.
@@ -1362,8 +1536,10 @@ static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
struct XboxRequest {
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
void* destination; // +0x08
UINT64 destination_pad; // +0x10
void* destination; // +0x08: buffer, or the 64 KB page-number array (DestinationIsPhysicalPages)
UINT16 destination_page_offset; // +0x10: offset into the first page (DestinationIsPhysicalPages)
UINT16 reserved12;
UINT32 reserved14;
UINT32 destination_size; // +0x18
UINT32 reserved1c; // +0x1c
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
@@ -1374,6 +1550,7 @@ struct XboxRequest {
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
static_assert(offsetof(XboxRequest, destination_page_offset) == 0x10, "destination_page_offset offset");
static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size offset");
static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
@@ -1521,7 +1698,10 @@ public:
return;
}
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
if (request->options & kXboxRequestBcpackMask) {
// BCPack (BcpackMode, DSTORAGE_BCPACK_MODE 1-7) is decoded by the GDK's BCPack.dll when
// BX_BCPACK_DLL names it; combined with zlib, or without the codec, it stays refused.
const UINT bcpack_mode = static_cast<UINT>((request->options & kXboxRequestBcpackMask) >> 1);
if (bcpack_mode && ((request->options & kXboxRequestCompressedBit) || bcpack_mode > 7 || !bcpack_decompress())) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_bcpack");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
@@ -1531,14 +1711,15 @@ public:
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
if (request->options & (kXboxRequestDestinationPagesBit | kXboxRequestSourcePagesBit)) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_pages");
if (request->options & kXboxRequestSourcePagesBit) {
BX_VTABLE_STUB_LOG("IDStorageQueueX", 3u, "EnqueueRequest_physical_page_source");
reject(E_NOTIMPL, Kind::request, "EnqueueRequest");
return;
}
const bool to_pages = (request->options & kXboxRequestDestinationPagesBit) != 0;
const bool zlib = (request->options & kXboxRequestCompressedBit) != 0;
if (!request->destination || (zlib ? request->source_size >= request->destination_size
: request->source_size != request->destination_size)) {
: (!bcpack_mode && request->source_size != request->destination_size))) {
reject(E_DSTORAGE_INVALID_DESTINATION_SIZE, Kind::request, "EnqueueRequest");
return;
}
@@ -1549,6 +1730,10 @@ public:
if (zlib) {
translated.compression = compression_zlib;
translated.output_size = request->destination_size;
} else if (bcpack_mode) {
translated.compression = compression_bcpack;
translated.bcpack_mode = bcpack_mode;
translated.output_size = request->destination_size;
}
if (is_memory) {
if (!request->source_ptr) {
@@ -1565,6 +1750,21 @@ public:
translated.file = file->inner();
translated.file_offset = request->file_offset;
}
if (to_pages) {
// DestinationSize bytes from DestinationPageOffset in the first page, across as many
// 64 KB pages of the array as that covers.
constexpr UINT64 page = 64 * 1024;
const UINT64 end = static_cast<UINT64>(request->destination_page_offset) + request->destination_size;
const ULONG_PTR count = static_cast<ULONG_PTR>((end + page - 1) / page);
if (!map_physical_pages()) {
reject(HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND), Kind::request, "EnqueueRequest");
return;
}
// The array stays the title's: it is read when the request runs (map_page_destination).
translated.page_array = static_cast<const ULONG_PTR*>(request->destination);
translated.page_offset = request->destination_page_offset;
translated.page_span_count = count;
}
accept(queue_->EnqueueRequest(&translated), Kind::request, "EnqueueRequest");
}
+13 -3
View File
@@ -191,7 +191,7 @@ uint32_t adler32(const uint8_t* data, size_t size) {
} // namespace
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size, size_t* produced) {
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
const uint8_t cmf = input[0], flg = input[1];
@@ -225,7 +225,8 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
if (r != BxInflateResult::ok) return r;
if (final_block) break;
}
if (out.pos != out.size) return BxInflateResult::output_mismatch;
if (produced) *produced = out.pos;
else if (out.pos != out.size) return BxInflateResult::output_mismatch;
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
in.align_to_byte();
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
@@ -233,7 +234,16 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
const uint8_t* t = in.data + trailer;
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
(static_cast<uint32_t>(t[2]) << 8) | t[3];
return adler32(output, output_size) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
return adler32(output, out.pos) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
}
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
return inflate_impl(input, input_size, output, output_size, nullptr);
}
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced) {
*produced = 0;
return inflate_impl(input, input_size, output, capacity, produced);
}
const char* bx_inflate_result_name(BxInflateResult result) {
+4
View File
@@ -25,4 +25,8 @@ enum class BxInflateResult {
/* Decodes `input` into exactly `output_size` bytes at `output`. */
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size);
/* Decodes `input` into at most `capacity` bytes and reports how many the stream produced
(checksum verified over those bytes). */
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced);
const char* bx_inflate_result_name(BxInflateResult result);
+22
View File
@@ -97,6 +97,17 @@ struct Lock {
~Lock() { ReleaseSRWLockExclusive(&memory_lock); }
};
// Replacing part of a mapped view can leave a temporary gap across that view
// while its remaining runs are restored. DirectStorage holds remap_lock shared
// while accessing title memory. Mapping and freeing take it exclusively during
// replacement. Acquire it before memory_lock to keep the lock order consistent.
SRWLOCK remap_lock = SRWLOCK_INIT;
struct RemapExclusive {
RemapExclusive() { AcquireSRWLockExclusive(&remap_lock); }
~RemapExclusive() { ReleaseSRWLockExclusive(&remap_lock); }
};
using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
MEM_EXTENDED_PARAMETER*, ULONG);
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
@@ -690,6 +701,7 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_ar
return FALSE;
}
RemapExclusive remap;
Lock lock;
SIZE_T validated = 0;
for (; validated < count; ++validated) {
@@ -741,6 +753,7 @@ extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PUL
return nullptr;
}
if (!have_placeholder_api()) return nullptr;
RemapExclusive remap;
Lock lock;
auto* base = static_cast<BYTE*>(address);
const auto begin = reinterpret_cast<uintptr_t>(address);
@@ -799,6 +812,7 @@ static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_arra
return FALSE;
}
if (!have_placeholder_api()) return FALSE;
RemapExclusive remap;
Lock lock;
for (ULONG_PTR i = 0; i < count; ++i) {
const auto slot = reinterpret_cast<uintptr_t>(addresses[i]);
@@ -838,6 +852,14 @@ static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_arra
return TRUE;
}
extern "C" void bx_xmem_remap_guard_enter(void) {
AcquireSRWLockShared(&remap_lock);
}
extern "C" void bx_xmem_remap_guard_leave(void) {
ReleaseSRWLockShared(&remap_lock);
}
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
if (!out_info) return 0;
+89 -15
View File
@@ -85,6 +85,53 @@ void update_peak() {
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes + external_bytes);
}
// The accounting as the internal ABI reports it. The caller holds usage_lock.
bx_xmem_stats_t stats_locked() {
return {title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
}
// XMEM_WORKING_SET_STATISTICS as the authorized GDK header lays it out for x64: SIZE_T fields
// are 8 bytes and UINT32 fields 4, in declaration order with natural alignment.
struct WorkingSetStatistics {
uint64_t game_limit;
uint64_t game_used;
uint64_t tools_limit;
uint64_t tools_used;
uint32_t stack_used;
uint32_t game_allocated_physical_page_count;
uint64_t gpu_optimal_bandwidth_limit;
uint64_t gpu_optimal_bandwidth_used;
uint64_t tools_gpu_optimal_bandwidth_limit;
uint64_t tools_gpu_optimal_bandwidth_used;
uint32_t kernel_pool_used;
uint32_t kernel_pool_limit;
uint32_t direct_storage_used;
uint32_t frame_preserve_buffer_size;
uint64_t game_used_peak;
uint32_t gpu_page_table_size;
uint32_t cpu_page_table_size;
uint64_t reserved[2];
};
static_assert(offsetof(WorkingSetStatistics, stack_used) == 0x20);
static_assert(offsetof(WorkingSetStatistics, gpu_optimal_bandwidth_limit) == 0x28);
static_assert(offsetof(WorkingSetStatistics, kernel_pool_used) == 0x48);
static_assert(offsetof(WorkingSetStatistics, game_used_peak) == 0x58);
static_assert(offsetof(WorkingSetStatistics, reserved) == 0x68);
static_assert(sizeof(WorkingSetStatistics) == 0x78);
// XMEM_WORKING_SET_TITLE, _TOOLS, _STACK, _KERNEL_POOL and _CPU_PTE are 0x20000001, 0x20000002,
// 0x20000004, 0x20000008 and 0x20000010: a shared 0x20000000 bit and one bit per category.
constexpr DWORD working_set_marker = 0x20000000;
constexpr DWORD working_set_categories = 0x1F;
bool valid_working_set_flags(DWORD flags) {
return (flags & working_set_marker) && (flags & working_set_categories)
&& !(flags & ~(working_set_marker | working_set_categories));
}
// Physical pages are always 64 KiB (physical_pages.cpp).
constexpr uint64_t physical_page_bytes = 64 * 1024;
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
return reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
@@ -365,19 +412,47 @@ BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*
return TRUE;
}
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
if (!out_stats || stats_size < sizeof(bx_xmem_stats_t)) {
/*
* XMemGetWorkingSetStatistics(WorkingSetFlags, Statistics), as the authorized GDK header declares
* it. The whole structure is written, whichever categories the flags select, from xmem's own
* accounting:
* - GameLimit: the title memory cap.
* - GameUsed: everything the cap counts (XMem heap, virtual commits, physical pages and
* external charges); GameUsedPeak is its highest value so far.
* - GameAllocatedPhysicalPageCount: the 64 KiB physical pages allocated.
* - Tools fields: 0, since tools memory is unavailable (XMemIsToolsMemAvailable).
* - Every other field: 0. The host has no console kernel pool, GPU or CPU page tables,
* frame-preserve buffer or separate GPU-optimal memory, and xmem does not count thread
* stacks or DirectStorage buffers.
* A NULL Statistics, or flags outside the five XMEM_WORKING_SET_* values, is refused.
*/
BOOL WINAPI XMemGetWorkingSetStatistics(DWORD flags, PVOID statistics) {
if (!statistics || !valid_working_set_flags(flags)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "refused flags=0x%lx statistics=%p",
static_cast<unsigned long>(flags), statistics);
bx_log_emit(BX_LOG_WARN, "xmem", "working_set_statistics", detail);
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
bx_xmem_stats_t stats;
{
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
bx_log_emit(BX_LOG_ERROR, "xmem", "working_set_statistics",
"refresh_virtual_commits failed; statistics not reported");
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
stats = stats_locked();
}
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
std::memset(out_stats, 0, stats_size);
std::memcpy(out_stats, &stats, sizeof(stats));
WorkingSetStatistics out{};
out.game_limit = stats.title_limit_bytes;
out.game_used = stats.committed_virtual_bytes + stats.allocated_physical_bytes;
out.game_used_peak = stats.peak_committed_bytes;
out.game_allocated_physical_page_count = static_cast<uint32_t>(std::min<uint64_t>(
stats.allocated_physical_bytes / physical_page_bytes, std::numeric_limits<uint32_t>::max()));
std::memcpy(statistics, &out, sizeof(out));
return TRUE;
}
@@ -387,12 +462,11 @@ BOOL WINAPI XMemIsToolsMemAvailable(void) {
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
if (!out_stats) return;
if (!XMemGetWorkingSetStatistics(out_stats, sizeof(*out_stats))) {
// The internal ABI has no error return. Preserve the most recent
// accounting snapshot if refreshing it runs out of bookkeeping memory.
std::lock_guard guard(usage_lock);
*out_stats = {title_limit(), heap_bytes + virtual_bytes + external_bytes, physical_bytes, peak_bytes};
}
std::lock_guard guard(usage_lock);
// The internal ABI has no error return. If refreshing runs out of bookkeeping memory, the
// tracked commits are left as they were and the most recent snapshot is reported.
(void)refresh_virtual_commits();
*out_stats = stats_locked();
}
int bx_xmem_try_charge_external(uint64_t bytes) {
@@ -0,0 +1,2 @@
add_executable(test_console_mode main.cpp)
target_link_libraries(test_console_mode PRIVATE xgameruntime advapi32 kernel32)
@@ -0,0 +1,69 @@
/*
* The console type in the registry. A title can read the REG_DWORD ConsoleMode under
* HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM instead of calling XSystemGetDeviceType
* (target-build observation): it opens the key with RegOpenKeyW, reads the value with
* RegQueryValueExW and maps 0x60 to Series S, 0x64 to Series X and 0x68 to the Scarlett devkit;
* with no key it takes itself for a PC and sizes its memory for Series X. The XSystemDeviceType
* numbers below are those of the authorized GDK (XboxScarlettLockhart 6, XboxScarlettAnaconda 7,
* XboxScarlettDevkit 8, Pc 1). This test reads the value the same way and checks it against the
* BetterXen profile (BX_PROFILE, as bx-cli run sets it) and against XSystemGetDeviceType.
*/
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" uint32_t WINAPI XSystemGetDeviceType();
namespace {
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::fprintf(stderr, "console mode:%d: %s\n", __LINE__, #condition); \
return 1; \
} \
} while (false)
// The title's mapping of ConsoleMode to XSystemDeviceType, written out from the observation.
uint32_t device_type_for(DWORD mode) {
switch (mode) {
case 0x10: case 0x20: case 0x21: case 0x30: case 0x31: return 2; // XboxOne
case 0x40: return 3; // XboxOneS
case 0x50: return 4; // XboxOneX
case 0x58: return 5; // XboxOneXDevkit
case 0x60: return 6; // XboxScarlettLockhart
case 0x64: return 7; // XboxScarlettAnaconda
case 0x68: return 8; // XboxScarlettDevkit
default: return 0; // Unknown
}
}
} // namespace
int main() {
char profile[32] = {};
GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile));
const bool anaconda = _stricmp(profile, "anaconda") == 0;
const DWORD expected_mode = anaconda ? 0x64 : 0x60;
HKEY key = nullptr;
CHECK(RegOpenKeyW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM", &key) ==
ERROR_SUCCESS); // without it the title takes itself for a PC
DWORD mode = 0;
DWORD type = 0;
DWORD size = sizeof(mode);
const LSTATUS status = RegQueryValueExW(key, L"ConsoleMode", nullptr, &type, reinterpret_cast<BYTE*>(&mode), &size);
RegCloseKey(key);
CHECK(status == ERROR_SUCCESS);
CHECK(type == REG_DWORD && size == sizeof(DWORD));
std::printf("ConsoleMode=0x%lx profile=%s XSystemGetDeviceType=%u\n", static_cast<unsigned long>(mode),
anaconda ? "anaconda" : "lockhart", XSystemGetDeviceType());
CHECK(mode == expected_mode);
CHECK(device_type_for(mode) == (anaconda ? 7u : 6u));
CHECK(device_type_for(mode) == XSystemGetDeviceType()); // both ways of asking agree
std::puts("PASS: test_console_mode");
return 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_committed_resource_x main.cpp)
target_compile_definitions(test_d3d12_committed_resource_x PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_committed_resource_x PRIVATE d3d12_xs xmem kernel32 uuid)
@@ -0,0 +1,143 @@
/*
* CreateCommittedResourceX (Xbox device table slot 76): CreateCommittedResource with a
* D3D12XBOX_RESOURCE_DESC, which is the PC D3D12_RESOURCE_DESC followed by DccOptions, a struct of
* two 32-bit enums, CompressionLevel and ColorTransform (authorized GDK header). The resource must be created with the PC part of the description,
* whatever DccOptions says, and its memory requested through XMemAlloc like any committed
* resource (AllocatorId D3D 128, ObjectType Resource 4), so a title hooking XMemAlloc sees it.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
extern "C" __declspec(dllimport) PVOID WINAPI XMemAllocDefault(SIZE_T, ULONGLONG);
extern "C" __declspec(dllimport) VOID WINAPI XMemFreeDefault(PVOID, ULONGLONG);
namespace {
// D3D12XBOX_RESOURCE_DESC, written out from the GDK header's field list.
struct DccOptions {
UINT32 CompressionLevel; // D3D12XBOX_DCC_COMPRESSION_LEVEL: 64B 0, 128B 1, 256B 2, DEFAULT 3
UINT32 ColorTransform; // D3D12XBOX_DCC_COLOR_TRANSFORM: 0..3
};
struct XboxResourceDesc {
D3D12_RESOURCE_DESC pc;
DccOptions Dcc;
};
static_assert(offsetof(XboxResourceDesc, Dcc) == 56, "DccOptions follows the 56-byte PC description");
static_assert(sizeof(XboxResourceDesc) == 64, "DccOptions is two 32-bit enums");
constexpr ULONGLONG kD3DResource = (128ull << 16) | 4;
int g_d3d_requests = 0;
PVOID WINAPI alloc_hook(SIZE_T size, ULONGLONG attributes) {
if ((attributes & ((0xFFull << 16) | 0x1F)) == kD3DResource) ++g_d3d_requests;
return XMemAllocDefault(size, attributes);
}
VOID WINAPI free_hook(PVOID address, ULONGLONG attributes) { XMemFreeDefault(address, attributes); }
constexpr int kRelease = 2, kResGetDesc = 10, kDevCreateCommittedResourceX = 76;
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using GetDescFn = void(STDMETHODCALLTYPE*)(void*, D3D12_RESOURCE_DESC*);
using CreateCommittedXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const XboxResourceDesc*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
int g_failed = 0;
#define CHECK(cond, ...) \
do { \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL: test_d3d12_committed_resource_x:%d: ", __LINE__); \
std::fprintf(stderr, __VA_ARGS__); \
std::fprintf(stderr, "\n"); \
} \
} while (0)
void create_and_check(void* dev, const XboxResourceDesc& x, const char* what) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
const int before = g_d3d_requests;
void* resource = nullptr;
const HRESULT hr = slot<CreateCommittedXFn>(dev, kDevCreateCommittedResourceX)(
dev, &heap, D3D12_HEAP_FLAG_NONE, &x, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), &resource);
CHECK(hr == S_OK && resource, "%s: hr=0x%08lx", what, static_cast<unsigned long>(hr));
if (!resource) return;
D3D12_RESOURCE_DESC got{};
slot<GetDescFn>(resource, kResGetDesc)(resource, &got);
CHECK(got.Dimension == x.pc.Dimension && got.Width == x.pc.Width && got.Height == x.pc.Height &&
got.MipLevels == x.pc.MipLevels && got.Format == x.pc.Format,
"%s: created with dim=%d %llux%u mips=%u format=%d", what, static_cast<int>(got.Dimension),
static_cast<unsigned long long>(got.Width), got.Height, got.MipLevels, static_cast<int>(got.Format));
CHECK(g_d3d_requests == before + 1, "%s: %d XMemAlloc requests for its memory", what, g_d3d_requests - before);
std::printf("%s: hr=0x%08lx %llux%u format=%d, XMemAlloc requests=%d\n", what, static_cast<unsigned long>(hr),
static_cast<unsigned long long>(got.Width), got.Height, static_cast<int>(got.Format),
g_d3d_requests - before);
slot<ReleaseFn>(resource, kRelease)(resource);
}
} // namespace
struct AllocationHooks {
PVOID(WINAPI* alloc)(SIZE_T, ULONGLONG);
VOID(WINAPI* free)(PVOID, ULONGLONG);
};
extern "C" __declspec(dllexport) AllocationHooks __XMemAllocationHooks__ = {alloc_hook, free_hook};
int main() {
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_committed_resource_x: host lacks the Xbox-layout device interface\n");
return 77;
}
if (FAILED(hr) || !dev) {
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
XboxResourceDesc target{};
target.pc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
target.pc.Width = 1920;
target.pc.Height = 1080;
target.pc.DepthOrArraySize = 1;
target.pc.MipLevels = 1;
target.pc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
target.pc.SampleDesc.Count = 1;
target.pc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
target.Dcc = {2, 3}; // 256B with a correlated colour transform: the host has no compression
create_and_check(dev, target, "render target with DccOptions");
XboxResourceDesc buffer{};
buffer.pc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
buffer.pc.Width = 256 * 1024;
buffer.pc.Height = 1;
buffer.pc.DepthOrArraySize = 1;
buffer.pc.MipLevels = 1;
buffer.pc.SampleDesc.Count = 1;
buffer.pc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
create_and_check(dev, buffer, "buffer");
void* none = reinterpret_cast<void*>(1);
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
hr = slot<CreateCommittedXFn>(dev, kDevCreateCommittedResourceX)(dev, &heap, D3D12_HEAP_FLAG_NONE, nullptr,
D3D12_RESOURCE_STATE_COMMON, nullptr,
__uuidof(ID3D12Resource), &none);
CHECK(hr == E_INVALIDARG, "null description: hr=0x%08lx", static_cast<unsigned long>(hr));
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) return 1;
std::puts("PASS: test_d3d12_committed_resource_x");
return 0;
}
@@ -0,0 +1,3 @@
add_executable(test_d3d12_committed_tile_size main.cpp)
target_compile_definitions(test_d3d12_committed_tile_size PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
target_link_libraries(test_d3d12_committed_tile_size PRIVATE d3d12_xs xmem kernel32 uuid)
@@ -0,0 +1,128 @@
/*
* The XMemAlloc request a committed render-target or unordered-access texture makes. On the
* console the D3D12 runtime asks XMemAlloc (AllocatorId D3D 128, ObjectType Resource 4) for the
* resource's memory, and a title hooking XMemAlloc can size its pool for those requests and check
* what is left. A 2D render-target or UAV texture with one mip and one sample is laid out in 64 KB
* tiles (64KB_R_X): 128x128 elements at 4 bytes, 128x64 at 8, per slice. The expected sizes below
* are the tile part of the sizes the authorized GDK XG library reports for these descriptions,
* written out here; XG's render-target compression metadata after the tiles is not modelled.
*/
#include <windows.h>
#include <d3d12.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
void** ppv);
extern "C" __declspec(dllimport) PVOID WINAPI XMemAllocDefault(SIZE_T, ULONGLONG);
extern "C" __declspec(dllimport) VOID WINAPI XMemFreeDefault(PVOID, ULONGLONG);
namespace {
constexpr ULONGLONG kD3DResource = (128ull << 16) | 4; // AllocatorId bits 16-23, ObjectType bits 0-4
SIZE_T g_last_request = 0;
PVOID WINAPI alloc_hook(SIZE_T size, ULONGLONG attributes) {
if ((attributes & ((0xFFull << 16) | 0x1F)) == kD3DResource) g_last_request = size;
return XMemAllocDefault(size, attributes);
}
VOID WINAPI free_hook(PVOID address, ULONGLONG attributes) { XMemFreeDefault(address, attributes); }
constexpr int kRelease = 2, kDevGetResourceAllocationInfo = 25, kDevCreateCommittedResource = 27;
int g_failed = 0;
template <typename Fn>
Fn slot(void* object, int index) {
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
}
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
using AllocationInfoFn = D3D12_RESOURCE_ALLOCATION_INFO(STDMETHODCALLTYPE*)(void*, UINT, UINT, const D3D12_RESOURCE_DESC*);
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
const D3D12_CLEAR_VALUE*, REFIID, void**);
D3D12_RESOURCE_DESC texture(UINT64 w, UINT h, UINT16 slices, DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) {
D3D12_RESOURCE_DESC d{};
d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
d.Width = w;
d.Height = h;
d.DepthOrArraySize = slices;
d.MipLevels = 1;
d.Format = format;
d.SampleDesc.Count = 1;
d.Flags = flags;
return d;
}
// Creates the resource and returns the size of the XMemAlloc request it made (0 on failure).
SIZE_T request_for(void* dev, const D3D12_RESOURCE_DESC& desc) {
D3D12_HEAP_PROPERTIES heap{};
heap.Type = D3D12_HEAP_TYPE_DEFAULT;
g_last_request = 0;
void* resource = nullptr;
const HRESULT hr = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource)(
dev, &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), &resource);
if (FAILED(hr) || !resource) return 0;
slot<ReleaseFn>(resource, kRelease)(resource);
return g_last_request;
}
void expect(const char* what, SIZE_T got, SIZE_T want) {
std::printf("%-44s request=0x%llx expected=0x%llx\n", what, static_cast<unsigned long long>(got),
static_cast<unsigned long long>(want));
if (got != want) {
std::fprintf(stderr, "FAIL: test_d3d12_committed_tile_size: %s\n", what);
++g_failed;
}
}
} // namespace
struct AllocationHooks {
PVOID(WINAPI* alloc)(SIZE_T, ULONGLONG);
VOID(WINAPI* free)(PVOID, ULONGLONG);
};
extern "C" __declspec(dllexport) AllocationHooks __XMemAllocationHooks__ = {alloc_hook, free_hook};
int main() {
alignas(8) unsigned char title_params[80] = {};
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
std::memcpy(title_params, &version, sizeof(version));
void* dev = nullptr;
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
if (hr == E_NOINTERFACE) {
std::printf("SKIP: test_d3d12_committed_tile_size: host lacks the Xbox-layout device interface\n");
return 77;
}
if (FAILED(hr) || !dev) {
std::fprintf(stderr, "FAIL: device creation hr=0x%08lx\n", static_cast<unsigned long>(hr));
return 1;
}
constexpr auto RT = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
constexpr auto UAV = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
constexpr SIZE_T k64K = 64 * 1024;
expect("1920x1080 RGBA8 RT+UAV: 15x9 tiles",
request_for(dev, texture(1920, 1080, 1, DXGI_FORMAT_R8G8B8A8_UNORM, RT | UAV)), 135 * k64K);
expect("3840x2160 RGBA8 RT: 30x17 tiles",
request_for(dev, texture(3840, 2160, 1, DXGI_FORMAT_R8G8B8A8_UNORM, RT)), 510 * k64K);
expect("1920x1080 RGBA16F UAV: 15x17 tiles",
request_for(dev, texture(1920, 1080, 1, DXGI_FORMAT_R16G16B16A16_FLOAT, UAV)), 255 * k64K);
expect("1920x1080 RGBA8 RT+UAV x4 slices",
request_for(dev, texture(1920, 1080, 4, DXGI_FORMAT_R8G8B8A8_UNORM, RT | UAV)), 4 * 135 * k64K);
expect("64x64 RGBA8 RT: one tile",
request_for(dev, texture(64, 64, 1, DXGI_FORMAT_R8G8B8A8_UNORM, RT)), k64K);
// Outside that scope (no render-target or UAV flag) the request stays the host's size.
const D3D12_RESOURCE_DESC sampled = texture(1920, 1080, 1, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE);
const D3D12_RESOURCE_ALLOCATION_INFO host =
slot<AllocationInfoFn>(dev, kDevGetResourceAllocationInfo)(dev, 0, 1, &sampled);
expect("1920x1080 RGBA8 sampled only: host size", request_for(dev, sampled), static_cast<SIZE_T>(host.SizeInBytes));
slot<ReleaseFn>(dev, kRelease)(dev);
if (g_failed) return 1;
std::puts("PASS: test_d3d12_committed_tile_size");
return 0;
}
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more