mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-12-03 10:42:27 +00:00
Compare commits
544
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b8c67a4a7 | ||
|
|
aaa0171c0e | ||
|
|
180156806c | ||
|
|
98f4a16daa | ||
|
|
358435595e | ||
|
|
6fd1438e67 | ||
|
|
875b326c57 | ||
|
|
6b0f62a62f | ||
|
|
1b53450da4 | ||
|
|
cabdcd63cb | ||
|
|
14c0abd930 | ||
|
|
fb69c0ef8e | ||
|
|
2216cd2c2a | ||
|
|
051accbba3 | ||
|
|
269a8d7d70 | ||
|
|
4a125c6ae9 | ||
|
|
8ed5430051 | ||
|
|
d6c4db93a0 | ||
|
|
5ca2dcc304 | ||
|
|
2aaef338b8 | ||
|
|
7bb28ad220 | ||
|
|
931390e9aa | ||
|
|
8f1c82fd42 | ||
|
|
2bd8766553 | ||
|
|
d01a7c004f | ||
|
|
f6bb3409e0 | ||
|
|
b420e89ba4 | ||
|
|
1c0ec5cc9a | ||
|
|
2370f97df5 | ||
|
|
0967b7413b | ||
|
|
9898f6b095 | ||
|
|
73c0815285 | ||
|
|
b8dfe5652c | ||
|
|
ebcfd27fce | ||
|
|
75d0f99b5c | ||
|
|
5398714f12 | ||
|
|
c465e03459 | ||
|
|
0b0c43173c | ||
|
|
ecd8a218f7 | ||
|
|
b0850c102d | ||
|
|
655102c06c | ||
|
|
b04b9ead4d | ||
|
|
5a64cc98ee | ||
|
|
fcc5b9c51c | ||
|
|
82b3dc28ff | ||
|
|
c4c90ef9ea | ||
|
|
03da5a03bb | ||
|
|
db6c361f47 | ||
|
|
d19ee55d25 | ||
|
|
f9500edd25 | ||
|
|
f9d2568009 | ||
|
|
f6315b09a8 | ||
|
|
ea956e0c91 | ||
|
|
9de78e0040 | ||
|
|
14be28e735 | ||
|
|
d922f87604 | ||
|
|
2236ee1c89 | ||
|
|
f6dedc95f3 | ||
|
|
a244f4172d | ||
|
|
9b25c50798 | ||
|
|
08a0dd562e | ||
|
|
d3000739d4 | ||
|
|
5d1b0ba8e4 | ||
|
|
b1319ca8d1 | ||
|
|
6e297c02a8 | ||
|
|
1b3a7d924e | ||
|
|
40eb3362be | ||
|
|
cc494f0222 | ||
|
|
f398dff965 | ||
|
|
3b51c3e562 | ||
|
|
29ebcdc192 | ||
|
|
b74b37b6af | ||
|
|
e70a72010d | ||
|
|
9c92845fae | ||
|
|
59bf82ac61 | ||
|
|
fe6240ecd6 | ||
|
|
58956469ef | ||
|
|
f76b60f162 | ||
|
|
c545d15530 | ||
|
|
714d90baf8 | ||
|
|
d18c2d514a | ||
|
|
f7858ca991 | ||
|
|
526d73b678 | ||
|
|
c1403b7bf9 | ||
|
|
17939f4acd | ||
|
|
924f2d1453 | ||
|
|
ea069a108a | ||
|
|
0ad5a18afc | ||
|
|
9ba9ff0ee1 | ||
|
|
ed3a0cb53d | ||
|
|
9bdd01f261 | ||
|
|
00c19f1d8c | ||
|
|
42c52415e1 | ||
|
|
3ead0599a2 | ||
|
|
87c5972e7c | ||
|
|
628c4ef89f | ||
|
|
5e5ce4318f | ||
|
|
a711d24946 | ||
|
|
952e9a315e | ||
|
|
ae4ce59ecf | ||
|
|
7433aa1487 | ||
|
|
6251953fbb | ||
|
|
711f977c7a | ||
|
|
6a22307db7 | ||
|
|
e5314efe67 | ||
|
|
8783454bb0 | ||
|
|
ce562bf99d | ||
|
|
aa4961b305 | ||
|
|
ddcfe6dfaa | ||
|
|
713e2d72db | ||
|
|
c6bb82a6a8 | ||
|
|
95b1b154fa | ||
|
|
3ac16471f1 | ||
|
|
bc2b0add5d | ||
|
|
28041c38a3 | ||
|
|
a328fb84a6 | ||
|
|
bb21c4da3c | ||
|
|
32f7bf2be1 | ||
|
|
21c729a6e5 | ||
|
|
19c9667b5a | ||
|
|
339ab9cb48 | ||
|
|
91455f43d5 | ||
|
|
ba81e8633d | ||
|
|
620eda1c62 | ||
|
|
af473fbfc2 | ||
|
|
60ce8fbd75 | ||
|
|
24dea84c7e | ||
|
|
e32e1349a9 | ||
|
|
160a200b56 | ||
|
|
dcb9e434c6 | ||
|
|
a94888d1c7 | ||
|
|
a5f6dadc6f | ||
|
|
2420c52ee5 | ||
|
|
ecee277cfa | ||
|
|
b92cfa8047 | ||
|
|
bf468e8c48 | ||
|
|
d08aaa0e33 | ||
|
|
1351925f40 | ||
|
|
a679c463dd | ||
|
|
55c31e71c6 | ||
|
|
3e456cf124 | ||
|
|
663c8597ad | ||
|
|
cb4683b688 | ||
|
|
837129f9d2 | ||
|
|
0fc212b907 | ||
|
|
4817914b50 | ||
|
|
29b8ec8ca2 | ||
|
|
09f66dcd77 | ||
|
|
75a958f655 | ||
|
|
3446c2a954 | ||
|
|
99d17af66e | ||
|
|
fd970820c7 | ||
|
|
406198fcf9 | ||
|
|
eb356c0342 | ||
|
|
ca3dfe72c6 | ||
|
|
9d829a5269 | ||
|
|
feb3197e2f | ||
|
|
b3c6b2e885 | ||
|
|
ba3f31418d | ||
|
|
64d2ab15a0 | ||
|
|
32fc81cc9c | ||
|
|
a6c922c480 | ||
|
|
3f01646e48 | ||
|
|
9acd450445 | ||
|
|
9ab94bdd68 | ||
|
|
e99a0af3f3 | ||
|
|
d672271c6a | ||
|
|
aa41d275c6 | ||
|
|
0d1fcc3460 | ||
|
|
6ecd70bac5 | ||
|
|
83cdd49fab | ||
|
|
e667dfe435 | ||
|
|
f06dc97414 | ||
|
|
fc74ea53f8 | ||
|
|
7f689cb542 | ||
|
|
9bc65d7010 | ||
|
|
a35dc6e3a8 | ||
|
|
e59a1eb1b7 | ||
|
|
e52d5b0df7 | ||
|
|
0dae988c7c | ||
|
|
ba24aed650 | ||
|
|
5c3d4df8cf | ||
|
|
56783a31b1 | ||
|
|
2567d87a65 | ||
|
|
b0b4f82f1d | ||
|
|
6e0b882691 | ||
|
|
6c52bfb030 | ||
|
|
6059d701e2 | ||
|
|
d0a1c21a4e | ||
|
|
4fde342db1 | ||
|
|
a17edafe3b | ||
|
|
3cd97c3cc0 | ||
|
|
c504eb8fc8 | ||
|
|
0f9a6e1e11 | ||
|
|
e24fa6d42f | ||
|
|
c46611ff9d | ||
|
|
29a5cd70c0 | ||
|
|
15b11b4be8 | ||
|
|
690c756037 | ||
|
|
5c1efdb517 | ||
|
|
413c46545d | ||
|
|
0565e0ac37 | ||
|
|
a74ad2da44 | ||
|
|
fc358d0525 | ||
|
|
e502559470 | ||
|
|
06cd29a9a4 | ||
|
|
b49b0d9696 | ||
|
|
5a53fe1fd5 | ||
|
|
0c8a583378 | ||
|
|
6fbe856b4e | ||
|
|
084714739f | ||
|
|
23f73ee906 | ||
|
|
33a3ec2329 | ||
|
|
84dd9e2df5 | ||
|
|
2dc58a3b25 | ||
|
|
8d7c3bf66c | ||
|
|
394525b8d0 | ||
|
|
5acabd2f6e | ||
|
|
6957389fef | ||
|
|
147888c125 | ||
|
|
d649610b7b | ||
|
|
7f241ad170 | ||
|
|
97947085bf | ||
|
|
f5aed211b5 | ||
|
|
49e98cd684 | ||
|
|
df7a83c734 | ||
|
|
710103c70a | ||
|
|
bddd6f0030 | ||
|
|
daca10b4fb | ||
|
|
441fec14c8 | ||
|
|
9dd8f4f916 | ||
|
|
c9388313e4 | ||
|
|
073aa40a97 | ||
|
|
142fec28a2 | ||
|
|
a1fcd96836 | ||
|
|
26003c37e2 | ||
|
|
05b27f886f | ||
|
|
86ebd5c12c | ||
|
|
73cee37ee3 | ||
|
|
10238c33b4 | ||
|
|
5a8aa63835 | ||
|
|
c0698e9fd4 | ||
|
|
75f2ed8c3c | ||
|
|
9f6fef064c | ||
|
|
94a22926d2 | ||
|
|
f6bec97548 | ||
|
|
638673a173 | ||
|
|
1e0ffb642c | ||
|
|
b88fb86dbc | ||
|
|
7feebe38f6 | ||
|
|
b8d709fed0 | ||
|
|
f3eadff31c | ||
|
|
c4ceadc39e | ||
|
|
00c270062b | ||
|
|
00782e62e9 | ||
|
|
961cf7e26c | ||
|
|
4389f74b2b | ||
|
|
0ab348cb5d | ||
|
|
46e7135f6c | ||
|
|
784e1ea439 | ||
|
|
bff53517be | ||
|
|
6898077c20 | ||
|
|
49585b92b0 | ||
|
|
c2f5652694 | ||
|
|
41b755014a | ||
|
|
9d5ecf39e4 | ||
|
|
d910e43df3 | ||
|
|
c0aaaa005b | ||
|
|
69242d1215 | ||
|
|
808c5d17c5 | ||
|
|
23d631e3c7 | ||
|
|
64f9b1dcb5 | ||
|
|
740df46b10 | ||
|
|
a648cdecc7 | ||
|
|
911c27f62b | ||
|
|
9b9c3c63ee | ||
|
|
b16bdc1d4a | ||
|
|
340cd1deec | ||
|
|
ab7863142e | ||
|
|
21700c2869 | ||
|
|
a4026459d9 | ||
|
|
80fb4cc1f6 | ||
|
|
77af218878 | ||
|
|
da82407073 | ||
|
|
2e55cf2259 | ||
|
|
4cb858e6f5 | ||
|
|
b36e397681 | ||
|
|
5bc4ff5cf4 | ||
|
|
5e204bd883 | ||
|
|
620019564b | ||
|
|
36a0f3f6c5 | ||
|
|
29c8a29051 | ||
|
|
6db66dc4a4 | ||
|
|
5c2e2c9b63 | ||
|
|
77dd9ffef3 | ||
|
|
abecde1c39 | ||
|
|
e532fc56ba | ||
|
|
9239ba6551 | ||
|
|
ef58b18147 | ||
|
|
2deada1f9d | ||
|
|
65eef5b08e | ||
|
|
4c5cd55884 | ||
|
|
ec3dea9942 | ||
|
|
1fed04a80c | ||
|
|
a9efeffc6f | ||
|
|
365b411fed | ||
|
|
1b4b1bf7d7 | ||
|
|
aeac1892c1 | ||
|
|
a9674bf9c7 | ||
|
|
eee9a4fcdc | ||
|
|
fe28c5c2af | ||
|
|
e21f41ae24 | ||
|
|
506defdd45 | ||
|
|
64141e9ae6 | ||
|
|
04148f77f8 | ||
|
|
5a6e786850 | ||
|
|
34f744aa5d | ||
|
|
afc093ee54 | ||
|
|
224586917f | ||
|
|
2af3e7d10a | ||
|
|
17e2e2a835 | ||
|
|
3ec40ba7fb | ||
|
|
b3aad0d948 | ||
|
|
277edd592a | ||
|
|
d4996ba9fd | ||
|
|
ca2b48ef83 | ||
|
|
dc41f00cb3 | ||
|
|
1b04d6e237 | ||
|
|
9116c0a39e | ||
|
|
b96a9b5978 | ||
|
|
dcec248837 | ||
|
|
40b5ee7a8e | ||
|
|
b975e6335b | ||
|
|
8f4786e436 | ||
|
|
0c398214fa | ||
|
|
78b56747fb | ||
|
|
63bd059182 | ||
|
|
24b124e144 | ||
|
|
cff3e754a9 | ||
|
|
27bfa17cb1 | ||
|
|
261d71d8d1 | ||
|
|
2cc64bd617 | ||
|
|
d99e35ad42 | ||
|
|
f7748387da | ||
|
|
28a9c868e6 | ||
|
|
6cfade83fe | ||
|
|
c963b9bc1a | ||
|
|
30197aa236 | ||
|
|
957b8efb21 | ||
|
|
e04a3b3f62 | ||
|
|
ea29d3fc56 | ||
|
|
d724c6c013 | ||
|
|
43cb1aab54 | ||
|
|
af869008a0 | ||
|
|
8627285a59 | ||
|
|
aec6766b4d | ||
|
|
84f4370227 | ||
|
|
e57046a17d | ||
|
|
79e1906c27 | ||
|
|
d65c12f6a9 | ||
|
|
b325320549 | ||
|
|
9f8b4c7f69 | ||
|
|
2e5fbc70b1 | ||
|
|
3f2f2732ed | ||
|
|
7c807d8b3a | ||
|
|
a2d153605d | ||
|
|
4a34ec3e50 | ||
|
|
2e96d93439 | ||
|
|
30e666b86c | ||
|
|
41bc72887b | ||
|
|
c206a3f85d | ||
|
|
c893436269 | ||
|
|
00b8344a40 | ||
|
|
451c6308c0 | ||
|
|
4d69562b59 | ||
|
|
656eff8459 | ||
|
|
3ba0eb20d5 | ||
|
|
8a00743d99 | ||
|
|
ce1940d84c | ||
|
|
bd744727bd | ||
|
|
b141c4b261 | ||
|
|
c7a4b4cf19 | ||
|
|
b88ea24a30 | ||
|
|
b2ae7a604e | ||
|
|
901b68ffba | ||
|
|
3eb8900442 | ||
|
|
335e3e4d60 | ||
|
|
ca2ad143f9 | ||
|
|
c345ada8e9 | ||
|
|
3154497424 | ||
|
|
6eaf8faa95 | ||
|
|
3c1ee93df5 | ||
|
|
87a03d0421 | ||
|
|
bf9dd7b383 | ||
|
|
b59696975a | ||
|
|
43bb5636bf | ||
|
|
b7a660d4b9 | ||
|
|
10f78645cb | ||
|
|
8c4610b51c | ||
|
|
3b1d168de7 | ||
|
|
7a380bd3d7 | ||
|
|
931c09c6af | ||
|
|
186836e1d6 | ||
|
|
133ffd4c97 | ||
|
|
0d9997ce66 | ||
|
|
bfbc84d251 | ||
|
|
e96de7c455 | ||
|
|
4b2985114a | ||
|
|
0b474941f0 | ||
|
|
fe749b1436 | ||
|
|
b76066eafb | ||
|
|
b7bb7615d8 | ||
|
|
2b2a9e15a6 | ||
|
|
3c65b393a4 | ||
|
|
67f3b618ab | ||
|
|
b0e40e29ea | ||
|
|
90dc310b61 | ||
|
|
4bf52b14a3 | ||
|
|
bc7b622018 | ||
|
|
d8fea7b351 | ||
|
|
fe50a8edff | ||
|
|
d47eac809f | ||
|
|
8db5552e32 | ||
|
|
297251fb00 | ||
|
|
030c63f8c9 | ||
|
|
9a6f71abbc | ||
|
|
ad4bcc66b1 | ||
|
|
3d244ddcb0 | ||
|
|
b29ccc60e1 | ||
|
|
5f8235f607 | ||
|
|
c1b3edf9ba | ||
|
|
1eecf6a20c | ||
|
|
ceaad9aee9 | ||
|
|
6bf2b9ab95 | ||
|
|
527cd6208f | ||
|
|
93a1f12bc6 | ||
|
|
32b371e55f | ||
|
|
e48454bdd3 | ||
|
|
55dfa39600 | ||
|
|
c39d33821e | ||
|
|
e17a8281eb | ||
|
|
355197c4ac | ||
|
|
01ef819910 | ||
|
|
085e0d450e | ||
|
|
2d2ee990a7 | ||
|
|
1f3e45eaf7 | ||
|
|
a4742dd137 | ||
|
|
d5eb5ae97d | ||
|
|
2fc6c16f9d | ||
|
|
cb6688c836 | ||
|
|
f1db93e2b4 | ||
|
|
71fa30c29b | ||
|
|
050b0b279c | ||
|
|
162ed81eaf | ||
|
|
dcd0a5127d | ||
|
|
f644569578 | ||
|
|
5b015a2b9e | ||
|
|
2549d724dd | ||
|
|
9bcb121322 | ||
|
|
48378f8c35 | ||
|
|
88e6cf00b9 | ||
|
|
0521ea0c6c | ||
|
|
ce23d0b2b9 | ||
|
|
d17525c165 | ||
|
|
3cfb9ed690 | ||
|
|
51ac3bd766 | ||
|
|
e816c16495 | ||
|
|
076b354d61 | ||
|
|
0bd188e602 | ||
|
|
b86be87576 | ||
|
|
62290b2f21 | ||
|
|
2d8685681b | ||
|
|
25d5240dd0 | ||
|
|
97a2ad5d8b | ||
|
|
d93a3f3084 | ||
|
|
30c071845f | ||
|
|
781f473ea3 | ||
|
|
6b83bbbd8b | ||
|
|
9f81aadc49 | ||
|
|
724347fd98 | ||
|
|
6f588bc862 | ||
|
|
74fffaa350 | ||
|
|
23de596a23 | ||
|
|
00e1b2fce9 | ||
|
|
846690befc | ||
|
|
04ad81ee26 | ||
|
|
e0f8b0e8f6 | ||
|
|
2fc82c4d58 | ||
|
|
c33199264a | ||
|
|
82ec02e754 | ||
|
|
6cd94140b1 | ||
|
|
c08571ac74 | ||
|
|
d57aba26b9 | ||
|
|
de0d5bd7d9 | ||
|
|
f48c42fd20 | ||
|
|
2217eb83a1 | ||
|
|
63f5640a99 | ||
|
|
4509911df0 | ||
|
|
76c81468c7 | ||
|
|
f3976b24f4 | ||
|
|
0f5a2ab6fd | ||
|
|
987b404a4e | ||
|
|
fa06be79b7 | ||
|
|
56a27dfd80 | ||
|
|
8d904a7f69 | ||
|
|
1300eb7892 | ||
|
|
1894ef23b7 | ||
|
|
989abbdc2c | ||
|
|
140dce0be1 | ||
|
|
1b25f3422b | ||
|
|
766055e948 | ||
|
|
494e53b8fb | ||
|
|
54b87f613c | ||
|
|
bbd3b8a9d4 | ||
|
|
32d02efc33 | ||
|
|
ac82a55039 | ||
|
|
e40d7293f8 | ||
|
|
981bd3c64e | ||
|
|
63b5f5dac6 | ||
|
|
6484cb70a3 | ||
|
|
87da1752ad | ||
|
|
1bc42fcaec | ||
|
|
25ceb05230 | ||
|
|
2bc97a4f68 | ||
|
|
f2efeaf79d | ||
|
|
ab81b0beca | ||
|
|
b16797f576 | ||
|
|
3409bf4ec0 | ||
|
|
420c2329b7 | ||
|
|
ae869522ce | ||
|
|
6e3ef5459b | ||
|
|
bec15f43b6 | ||
|
|
7dde71e2fd | ||
|
|
33d439f828 | ||
|
|
a27284ab26 | ||
|
|
311f4124fa | ||
|
|
46a6a4baca | ||
|
|
8245c30b56 | ||
|
|
be647332cb | ||
|
|
fbd2f8cf43 | ||
|
|
6a1451b265 | ||
|
|
c64534fb21 | ||
|
|
b096424f33 | ||
|
|
f2af367da6 |
No files matched your search
@@ -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
|
||||
@@ -29,6 +29,8 @@ jobs:
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Unit-test the hygiene checks
|
||||
run: python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
|
||||
@@ -4,46 +4,103 @@ These rules apply to every human contributor and coding agent (`CLAUDE.md` is a
|
||||
|
||||
---
|
||||
|
||||
## 0. Contributor & Agent Task Dispatch (Onboarding & Priority Order)
|
||||
## 0. What to Do When Told "Work"
|
||||
|
||||
Whenever a user points their agent at BetterXen to contribute, get started, or pick work (even with a short prompt like *"help me contribute"* or *"what should we work on?"*), walk through preflight and then select work in the **strict 3-tier priority order** below:
|
||||
Collaborators point their agent at this repository and say "work" (or "contribute", "continue", "what next?"). That is a complete instruction. Do not ask what to work on: follow this section. The method behind it is in [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **Select work in strict priority order:**
|
||||
- **Priority 1 (Highest) — Handle your own claimed PRs with requested changes or review feedback:**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,reviewDecision,reviews,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Inspect comments and reviews (`gh pr view <pr> --repo MacosPorters/betterxen --comments` and `gh api repos/MacosPorters/betterxen/pulls/<pr>/comments`). If any of the user's open/claimed PRs has `CHANGES_REQUESTED`, unresolved reviewer feedback, failing CI, or merge conflicts, **address that PR first before starting new work**: check out the PR branch, resolve every review item, re-run Section 8 checks, push the DCO-signed update (with the user's authorization, per Section 7), and summarize how each comment was addressed.
|
||||
- **Priority 2 — Pick an unclaimed open issue:**
|
||||
If Priority 1 is clear, query open issues (preferring `status: ready` in the active milestone, then other actionable open issues):
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
gh issue list --repo MacosPorters/betterxen --state open --json number,title,labels,assignees
|
||||
```
|
||||
Inspect comments and open PRs on candidate issues to filter out any issue with an active claim (< 7 days old) or open PR. Present the unclaimed options in plain English (recommending 1–2 good matches) and confirm with the user before coding.
|
||||
- **Priority 3 — Review & independently verify open PRs needing review:**
|
||||
When Priority 1 is clear and no unclaimed open issues remain (or the user asks to help unblock the queue), query open non-draft PRs by other contributors that still need review/verification:
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,headRefName,reviewDecision,isDraft
|
||||
```
|
||||
Fetch a candidate PR (`reviewDecision` empty or `REVIEW_REQUIRED`) into an isolated worktree, independently verify its contract and implementation per Section 5, run the Section 8 checks locally (including live CrossOver / D3DMetal runs where available), and draft an honest evidence-backed review for user approval before posting.
|
||||
3. **Claim & isolate (for Priority 2 issue work):**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (cross-compiling the 16 mingw-w64 C++ shim DLLs, building the Rust `bx_shader_bridge.dll` with `cargo`, and verifying the exact exports of all 17 PE32+ DLLs), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
**"Work" authorizes, for the one item you pick:** opening a draft pull request, posting a review, committing with DCO sign-off, and pushing a branch. It does not authorize merging your own person's pull request, changing rules, or anything marked `needs-human`. A more specific instruction from your person always wins.
|
||||
|
||||
### Step 1 — Preflight: make the machine ready yourself
|
||||
|
||||
```sh
|
||||
cargo build --locked -p bx-cli && target/debug/bx-cli preflight
|
||||
```
|
||||
|
||||
`bx-cli preflight` must print `Ready to work.` It requires **all** of:
|
||||
|
||||
| Required | How it is found |
|
||||
| --- | --- |
|
||||
| An Apple Silicon Mac with CrossOver 26.3+, D3DMetal and `mingw-w64` | Checked on the host |
|
||||
| **The project-authorized target build** | Found and saved by `bx-cli setup --find` |
|
||||
| **The GDK** (headers and compilers, under the project's authorization) | Found and saved by `bx-cli setup --find` |
|
||||
| **The Ghidra results of the target build** (the static-analysis run: `RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable | Found and saved by `bx-cli setup --find` |
|
||||
| At least 10 GiB of free disk space | Measured |
|
||||
|
||||
**The target build, the GDK and the Ghidra results are a hard requirement.** An agent that lacks even one of them does not work on this repository at all: no code, tests, reviews, merges, issues or documentation.
|
||||
|
||||
**If preflight fails, fix it yourself and run it again.** Your person said "work"; do not hand the setup back to them.
|
||||
|
||||
| `MISSING` line | What you do |
|
||||
| --- | --- |
|
||||
| Target build, GDK, Ghidra results | `target/debug/bx-cli setup --find`. It searches the home folder, recognises the GDK by its header, the build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three. |
|
||||
| `mingw-w64 g++` (also `cmake`, `gh`) | `brew install mingw-w64 cmake gh`. Being told to "work" authorizes installing these three. |
|
||||
| Free disk space | Remove your own scratch: build folders and scratch bottles of worktrees you created. Never another session's files. |
|
||||
|
||||
**Stop only for what an agent cannot supply**, and say exactly which:
|
||||
|
||||
- the host is not an Apple Silicon Mac;
|
||||
- CrossOver is not installed (it is licensed software; do not install it);
|
||||
- `setup --find` reports that the target build, the GDK or the Ghidra results covering the build are not on this machine, or found more than one distinct build (which build to use is your person's choice: they run `bx-cli setup --target-exe <path>` once).
|
||||
|
||||
In those cases stop and do not work around it: no fixes, tests, reviews, merges or documentation "for someone else to verify". Work here is found by running the target build, located in the Ghidra results and checked against the GDK; an agent without all three is guessing.
|
||||
|
||||
Also check `git`, `gh` (`gh auth status`; if not logged in, ask the user to run `gh auth login`), `cargo`, `cmake` and `python3`; verify push access or fork (`gh repo fork MacosPorters/betterxen --remote`); sync with `origin/main`. Work in your own worktree and your own bottle; never use a bottle another session is using.
|
||||
|
||||
`bx-cli setup` remembers the three locations in `~/.config/betterxen/local.conf`, outside every checkout, so it happens once per machine and works in every worktree, shell and agent session. (`BX_TARGET_EXE`, `BX_GDK_ROOT` and `BX_GHIDRA_RESULTS` override it for one command.) Never commit those paths, and never put a path, file name, hash or byte from the target build, the GDK or the Ghidra results into a commit, issue or pull request (Section 6).
|
||||
|
||||
### Step 2 — Pick exactly one thing, in this order
|
||||
|
||||
Take the first that applies.
|
||||
|
||||
1. **Your person's pull requests that need attention.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --author "@me" --state open --json number,title,headRefName,isDraft,reviewDecision,statusCheckRollup,mergeStateStatus
|
||||
```
|
||||
Requested changes, unresolved review comments, failing checks, conflicts, or a draft you opened and have not finished: do that. Resolve every review point, re-run Section 8, push, and reply to each point.
|
||||
|
||||
2. **Review someone else's pull request.**
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --json number,title,author,reviewDecision,isDraft,createdAt
|
||||
```
|
||||
Take the oldest open, non-draft pull request that your person did not open and that has no current review. Check out its branch, run Section 8 and its new test **twice in a row**, confirm the test fails without the fix, and post an approval or a change request with what you ran. If it is approved, green and not your person's, merge it (Section 7).
|
||||
|
||||
3. **A handoff issue of the current stage.**
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label handoff --label "stage: <current>" --json number,title,labels
|
||||
```
|
||||
A handoff is something a collaborator found and could not finish. The current stage is named on the pinned issue labelled `ladder`. Take the lowest-numbered one that no open pull request mentions, and follow Step 3.
|
||||
|
||||
4. **Run the target build and fix the first thing it stops on.** Run it under the [run protocol](docs/process/working-method.md#run-protocol) and read `bx-cli report`. Take the first signature in the report that no open pull request is titled with or mentions, and follow Step 3. A blocker you can see and fix needs **no issue**: the pull request is the record.
|
||||
|
||||
5. **The run stops on nothing.** Make the stage's gate check (ten runs). If it passes, post the result on the ladder issue and label it `needs-human`; a person confirms the stage change. Then stop.
|
||||
|
||||
**Stop and label `needs-human`** whenever the next step is a decision that is not yours: a decision gate, a licence or provenance question, sources of truth that disagree, or a rule change.
|
||||
|
||||
### Step 3 — Work one blocker
|
||||
|
||||
**Before touching any problem the game shows you, find out whether someone already has it.** This applies every time: to the blocker you picked, and to every further problem you meet along the way (a failed load, a refused request, an assert, a crash). Search by the log event, stub symbol, error code and the files you would change:
|
||||
|
||||
```sh
|
||||
gh pr list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,headRefName
|
||||
gh pr list --repo MacosPorters/betterxen --state merged --search "<event, symbol or file>" --limit 10 --json number,title,mergedAt
|
||||
gh issue list --repo MacosPorters/betterxen --state open --search "<event, symbol or file>" --json number,title,labels
|
||||
```
|
||||
|
||||
- **An open pull request covers it:** check out that branch (`gh pr checkout <n>`), run the build with it, and work there: report what you saw on the pull request, and push a fix to its branch or request changes. Do not write a second fix.
|
||||
- **A merged pull request covers it:** sync with `origin/main` and run again before investigating.
|
||||
- **An issue covers it:** take it up from the issue's notes, and link it from your pull request.
|
||||
- **Nothing covers it:** carry on with step 1 below.
|
||||
|
||||
1. **Claim with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. **Before you instrument or run the build again, look the call up in the Ghidra results:** `bx-cli report` lists each unimplemented call's callers as `module+offset`, and `bx-cli ghidra <module+offset>` names the decompiled function; search the module's strings too (middleware often prints its own errors and asserts). Run the build only for what depends on run-time state. Check the contract against the GDK where the GDK covers it. ([Order of lookup](docs/process/working-method.md#order-of-lookup).)
|
||||
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row. The test is what holds on every machine; your run is only why you looked.
|
||||
5. **Verify:** every command in Section 8.
|
||||
6. **Proof:** runs before and after on your machine, every run reported, with the machine and the `main` commit. Another collaborator's machine may never take the path yours took; say which path your runs took.
|
||||
7. **Finish:** fill in the five-part description (Blocker, Contract with its source rank, Fix, Test, Proof), sign off, no AI trailers, mark the pull request ready. Do not wait for CI before moving on.
|
||||
8. **Stop.** The next "work" starts again at Step 2.
|
||||
|
||||
**If you cannot fix what you found** (too large, out of session, or it needs a decision): close your draft, file one **handoff issue** labelled `handoff` and `stage: <name>`, titled `[handoff] <signature>`, with what you saw, what you tried and what is still unknown. That is the only time a blocker gets an issue.
|
||||
|
||||
---
|
||||
|
||||
@@ -58,6 +115,7 @@ Whenever a user points their agent at BetterXen to contribute, get started, or p
|
||||
- `tests/conformance/` — Clean-room synthetic x86-64 PE32+ test binaries (auto-discovered via `test_*/CMakeLists.txt`).
|
||||
- **Retired native-first code:** The earlier native-first workspace was retired from `main` per ADR 0006 and remains preserved permanently at Git tag `native-first-final`. Do not open native-only issues; if hybrid work requires an independent component (such as RDNA 2 decoding), file a focused track issue.
|
||||
- **No unverified compatibility assumptions:** This is an active engineering foundation, not a verified Xbox game compatibility stack. Do not assume CrossOver, Rosetta 2, or D3DMetal provide Xbox runtime behavior without measurement.
|
||||
- **GDK texture libraries (ADR 0010):** Console texture layouts (tiling) and BCPack decompression come from the GDK's own PC libraries, `xg_xs.dll` and `BCPack.dll`, which `bx-cli run` stages for the target build from the configured GDK. Do not reimplement them, and never commit or ship them.
|
||||
|
||||
---
|
||||
|
||||
@@ -115,13 +173,13 @@ _Reserved — policy migration in progress._
|
||||
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
1. **Check before coding (open backlog issues):** When picking an unclaimed backlog issue, read every comment and check open PRs so you never claim over an active claim; reply `Claiming — branch: track-<a..f>/<issue>-<slug>` (stale after 7 days without commits/PR). Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
1. **Check before coding (claims):** A blocker is claimed by an open draft pull request titled with its signature (Section 0, Step 3); check open pull requests before opening yours. Every problem met while running the game, not only the one picked, is searched for in open and merged pull requests and open issues before it is investigated; when a pull request covers it, check that branch out and work there (Section 0, Step 3). A draft with no push for 3 days may be taken over. Direct maintainer-assigned tasks do not require a prior issue claim, but still check open issues and PRs first and never take over another contributor's active claim.
|
||||
2. **Isolate with branches or worktrees:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
git worktree add ../wt-<slug> -b track-<a..f>/<slug> origin/main
|
||||
```
|
||||
3. **Link & sign off:** Reference any related issue (`Closes #<issue>` when applicable) in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user; never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
4. **Git safety:** Commit, push, and open PRs only when requested or authorized by the user (being told to "work" authorizes them for the one item picked, Section 0); never change repository visibility without explicit instruction. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
5. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
|
||||
### Merge eligibility
|
||||
|
||||
+394
-1
@@ -10,16 +10,390 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- **Ghidra first: unimplemented calls name their callers, and `bx-cli ghidra` finds the function.**
|
||||
- `runtime_veh` logs a `stub_caller` event once for each unimplemented call (signature, stub, direct caller): the stub, its caller and one more frame, as `module+offset`. The stub's own event is unchanged, so report signatures don't change.
|
||||
- `bx-cli report` lists those caller chains under each unimplemented call.
|
||||
- `bx-cli ghidra <module> <offset>` (or `<module+offset>`) names the function holding that offset in the configured Ghidra results (`exports/<program>/functions.csv`, image base from `sections.csv`) and its decompiled file.
|
||||
- AGENTS.md Step 3.2 and the working method's new "Order of lookup" say to look the call up in the Ghidra results before instrumenting or running the build again. Ghidra's rank as a source of truth is unchanged.
|
||||
- Tests: `test_stub_caller`, plus unit tests for the report and the lookup.
|
||||
|
||||
### Fixed
|
||||
- **`xgameruntime`: a delayed task-queue callback no longer holds back the callbacks submitted after it** (#775, part 3). `XTaskQueueSubmitDelayedCallback` put the task in the port's FIFO, and the port waited for it to be due. So one multi-second retry timer blocked every later callback on that port, and on a pool lane a thread-pool thread slept meanwhile. In the GDK the delay elapses before the callback is submitted. Delayed tasks now wait outside the FIFO and a thread-pool timer moves them in when due, so a callback submitted later without a delay runs first. Delayed tasks still pending when the queue closes are drained or cancelled like the rest. `test_xgameruntime` checks both a manual and a serialized queue.
|
||||
- **`d3d12_xs`: `D3D12ConfigureVirtualMemoryX` accepts the DEFAULT page count and the legacy lower bound; `WaitFrameEventX` reports PRIMARY** (#772). These follow the authorized GDK header `d3d12_xs.h`.
|
||||
- `PageTableMemory4MBPageCount` = `D3D12XBOX_PAGE_TABLE_MEMORY_4MB_PAGE_COUNT_DEFAULT` (0) selects the default of 5 pages. It used to be refused with `E_INVALIDARG`.
|
||||
- `D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAG_ENABLE_LEGACY_LOWER_BOUND` (0x1) reports a 1 GiB minimum graphics address. A configuration with this flag used to be taken as an unrecognized block and returned `S_OK` without writing its outputs.
|
||||
- The outputs are now written even when the call returns `E_FAIL` because a device already exists, as the header documents.
|
||||
- `WaitFrameEventX` writes `D3D12XBOX_SIGNALED_OBJECT_INDEX_PRIMARY` (0xFFFFFFFE) when the frame event satisfied the wait, `NONE` only on a timeout, and otherwise the index of the first signalled ancillary object. A title testing for PRIMARY used to see every frame origin as a timeout.
|
||||
- **`xmem`: allocations follow their `XALLOC_ATTRIBUTES`, physical page numbers are reused, and `XMemVirtualQuery` / `XMemTransferMemory` have the GDK prototypes** (#768, #642).
|
||||
- `XMemAllocDefault` returned 64-byte-aligned memory whatever the attributes asked for. It now honours the alignment code (`1 << code`, up to 512 KB), aligns a block of at least one 64 KB or 2 MB page to that page, and keeps an `Address32BitMapping` block below 4 GB. `XMemFreeDefault` frees either kind.
|
||||
- `XMemAllocatePhysicalPages` gave every call new page numbers on the next 16 MB boundary and never reused freed ones, so after 8,192 calls every call failed. A call now takes the lowest free 16 MB-aligned numbers. The numbering rules are unchanged. `XMemFreePhysicalPages` no longer zeroes the caller's `PageArray`, which the GDK declares `_In_reads_`.
|
||||
- `XMemVirtualAlloc` with `MEM_2MB_PAGES` places the allocation on a 2 MB boundary, and `XMEM_GRAPHICS_32BIT_ADDRESS` keeps a system-placed plain allocation below 4 GB.
|
||||
- `XMemVirtualQuery(Process, Address, Buffer)` fills `XMEM_BASIC_INFORMATION`: the `VirtualQuery` fields, the `XMemFlags` the reservation was made with (0 for memory xmem did not reserve) and zero tags. It had the Win32 `VirtualQuery` shape, so a title passing `GetCurrentProcess()` always got FALSE.
|
||||
- `XMemTransferMemory(TransferType, TransferSize)`: a size of 0 succeeds. Title-to-system lowers the title cap by the size rounded up to 2 MB, if the free budget covers it. The tools transfers fail with a logged `ERROR_NOT_SUPPORTED`, since tools memory is not modelled. It used to be a `memmove(dst, src, bytes)`.
|
||||
- `test_xmem_gdk_forms` covers each of these with values from the GDK header.
|
||||
- **`d3d12_xs`: command-list and device forwards no longer pass wrapper objects or title addresses that sit inside structures** (#771). `Barrier`, `BeginRenderPass`, `DispatchRays`, `BuildRaytracingAccelerationStructure` (bottom-level; top-level builds are logged via `BX_VTABLE_STUB_LOG` until GPU-memory instance descriptors are translated), `EmitRaytracingAccelerationStructurePostbuildInfo`, `WriteBufferImmediate` and `SOSetTargets` are hand-written: embedded interface pointers are unwrapped, descriptor handles and GPU addresses are translated, and temporary allocation failures are logged instead of silently dropped. `CreateStateObject` and `AddToStateObject` are changed from plain forwarders to logged `BX_VTABLE_STUB_LOG` stubs because their subobject payloads are untyped and carry wrapper pointers. `GetRaytracingAccelerationStructurePrebuildInfo` stays forwarded because D3D12 only inspects counts, formats, flags, and nullness rather than dereferencing GPU addresses. The generator refuses a plain forward for any other method whose parameters are structures holding an interface pointer, a GPU address, or a descriptor handle. New test `test_d3d12_forwarder_struct`.
|
||||
- **`dxbc-accc` reads a 16-byte FSPX section table `{id, offset, size, 0}`, so a container whose first section begins at `16 + count * 16` classifies as ACCC** (#797). The 12-byte descriptor stays, because this repository's own synthetic fixtures use it (the `dxbc-accc` tests and `tests/conformance/test_shader_gate`). A table is 16-byte only when every entry's fourth word is 0 and the first section's offset equals `16 + count * 16`; every other table keeps the 12-byte parse. For 16-byte tables, section 1 is treated as opaque (its bounds are validated and recorded, while stage stays unknown unless supplied by another chunk) instead of requiring the 12-byte synthetic stage layout. A section that starts inside the header plus the table in use is still a layout mismatch.
|
||||
- **`xapu.dll` exports have the `xapu.h` prototypes** (#777). `XApuConnect`, `XApuEnqueueCommand`, `XApuDequeueResult` and `XApuGetResultCount` had BetterXen-defined shapes; called with the documented argument list, `XApuConnect` wrote the connection id through its first argument (the input block) and left the caller's handle and output parameters unset. The five exports now take the prototypes of the authorized GDK header `xapu.h`. Connecting succeeds and writes the handle and `XApuConnectOutputParameters`: `baseData`, and `resultReadyEvent` when the connect options request it. Each connection has its own command queue; a dequeued result echoes the submitted command id and carries no decoded audio. The APU device is not modelled and that is logged (`BX_STUB_LOG`). A dequeued result's `errorCode` is `S_OK` for a command that was not processed, and `BX_STUB_LOG` records it. `test_xapu_signatures` covers the argument lists, and `test_audio_input` and `test_integration_boot` call them the same way.
|
||||
- **`d3d12_xs`: a compute pipeline the host cannot make comes back as the logged null pipeline, so the target build no longer exits with status 5 on its next dispatch** (#722). Console compute shaders are not translated yet (#746), and `CreateComputePipelineStateX` returned `E_NOTIMPL` unless `BX_NULL_RENDER=1` was set. The target build keeps the shader program it was making even then, with no pipeline in it, and the next dispatch through that program read inside the missing pipeline (call-site observation). Refused compute pipelines now return the null pipeline whatever `BX_NULL_RENDER` says, logged as before (`pipeline_refused ... null pipeline returned`); dispatches with it are skipped and logged, as every untranslated dispatch is. Serialized and derived pipelines still fail. New test `test_d3d12_compute_placeholder`.
|
||||
- **`d3d12_xs.dll`: a placed texture has one host storage; host resources for title memory are released** (#782, #745).
|
||||
- **One storage per texture.** A texture placed in title memory now gets its contents uploaded into its host shadow itself, not into a side copy. On the console a placed texture has one storage, and now every view and copy command of it sees the texels; before, only views resolved for translated draws did, and copy commands read an empty texture. Read-only shadows are made with simultaneous access, so the upload promotes them from COMMON without barriers that contradict the title's own. A drawn texture no longer occupies a second host texture.
|
||||
- **Upload buffers.** A texture's upload buffer is released once the GPU has copied from it, and made again only if a later check finds the title memory changed.
|
||||
- **Implicit shadows.** `CreatePlacedRawShaderResourceViewX` and `CreatePlacedRawUnorderedAccessViewX` back each view with a host resource of the shim's own, which was made per (address, shape) and kept for the life of the process. A new view whose title memory overlaps an older implicit shadow of another address or shape now retires that shadow. The host resource is released 64 queue submissions later. Translated-draw markers of it then resolve to null views, and a constant view's fallback that lay in it is dropped.
|
||||
- **Effect on memory.** The target build's footprint on a 16 GB Mac (Series S profile) is about the same as before, 10 to 11 GB after about two minutes. Most of it is the title's own memory and one host texture per placed texture, which this design needs.
|
||||
- **Tests.** `test_d3d12_console_texture_contents` copies each placed texture out after a translated draw and checks every texel. `test_d3d12_placed_implicit_release` views four slots 256 times with new shapes and checks that at most one host resource per slot stays live.
|
||||
- **`d3d12_xs`: GPU value writes and waits in title memory take effect in list order, and Execute no longer blocks on them** (#773). `Wait32/64BitValueX` were all evaluated on the CPU before a submission went to the host (a busy loop of up to 10 s each), and every `Write*BitValue*X` was stored only after the host had finished the whole submission, so each Execute that carried a write waited for the GPU, and a wait on a write earlier in the same submission could only time out. A submission that carries them is now split at its lists: a list's waits hold the host queue on a fence before it (the fence slot itself, or a fence a per-queue worker signals once the value holds, checked with sleeps instead of a spin), and its writes are stored by that worker when the host GPU has finished the list. Inside one list, waits still count as being at its start and writes at its end. New test `test_d3d12_gpu_value_order` (a wait on a write earlier in the same submission, a wait on a value the CPU stores later, two writes to one address).
|
||||
- **`d3d12_xs`: `GetResourceAllocationInfo` answers textures with `Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN` in the console's default tiling** (#708). On the console `UNKNOWN` selects the default tiling mode (GDK documentation of `XG_RESOURCE_DESC::Layout`), but `d3d12_xs` passed such textures to the host, which has no console tiling. The target build sizes some of its loads that way (call-site observation): a 128x4 `R16G16B16A16_UNORM` texture came back as 4096 bytes where the GDK's XG gives 16384 (4 KB tiles, layout `0x105`), so it asked for a quarter of a 16 KB compressed chunk; its loader asserts on that, and `XCRDAPI.dll` refused the 47 such requests per run. With the GDK's XG loaded, these textures now get XG's size and alignment for the layout as given, as #710 does for explicit console layouts; buffers keep the host's answer. `test_d3d12_gdk_xg_sizes` checks an `UNKNOWN`-layout texture and uses a buffer as the host-answered case.
|
||||
- **`chad.dll`: `XDspConnectWithMaximumStreamLimit` connects again, so the target build no longer stops after 64 frames** (follow-up to #780). Since #780 connecting was refused with `E_NOTIMPL`, and the target build then hits its own assert a few seconds later and exits with status 3 (every default run; the same `main` with the earlier `chad.dll` runs on). Connecting now succeeds with a placeholder client handle and is logged as not modelled (`BX_STUB_LOG`); activating a stream on it is refused with `E_NOTIMPL`, and `XDspDisconnect` closes it. The prototypes from #780 stay, so nothing is written outside the documented outputs. `test_audio_input` and `test_integration_boot` check the new answers.
|
||||
- **`d3d12_xs.dll`: a texture the title rewrites every frame is copied as often as it changes** (#745). Texture contents from title memory were re-checked at most every 250 ms after a change. So a texture the title rewrites every frame (the intro movie's luma and chroma planes, decoded on the CPU) was re-copied at most 4 times a second, and the video stuttered: measured, about 10 re-copies a second of the luma planes during the movie. A texture found changed is now checked again at its next draw; one found unchanged waits 16 ms, doubling up to 4 s as before. Checks are a sampled hash, and only a change copies. Measured during the movie: 30 re-copies a second of the luma planes, the video's own rate, and 60 of the two chroma planes. `test_d3d12_console_texture_contents` gains a fourth round, in which the title rewrites a texture right after a copy and the next draw must show it.
|
||||
- **`chad.dll` exports have the `xdspaudio.h` prototypes** (#776). `XDspConnectWithMaximumStreamLimit`, `XDspActivate` and `XDspSubmitCommand` had BetterXen-defined shapes; called with the documented argument list, `XDspConnectWithMaximumStreamLimit` took `baseBufferLength` for its out pointer and wrote a NULL to that address. The five exports now take the prototypes of the authorized GDK header. XDSP is not modelled: connecting is refused with `E_NOTIMPL` and a NULL client handle (logged through `BX_STUB_LOG`), and the calls that take a client or stream handle answer `E_HANDLE` with their documented outputs cleared. `test_audio_input` and `test_integration_boot` call them with the documented argument lists; `test_integration_boot` reports the stage as pending, as for its other stubs. The DSP-only fields of the audio command ring are removed (`xapu.dll` still uses it; its signatures are #777).
|
||||
- **`xgameruntime`: the IXStore dispatch table covers every slot titles call** (#774). The table behind `QueryApiImpl` for the store interface (CLSID `0DD112AC-…`, IID `B09D803C-…`) had 40 entries, while the console runtime library calls it at slots up to 69 (call-site observation of a project-authorized target build); such a call read past the end of the table and jumped to whatever followed it. The table now has 80 entries, like the IXStoreDurables table under the same CLSID, and every slot without an implementation is the logged `E_NOTIMPL` stub. `test_xgameruntime` calls slots 40 to 79 through `QueryApiImpl`.
|
||||
- **`d3d12_xs`: a typed buffer view from `CreatePlacedRawShaderResourceViewX` is counted in its format's elements.** The constant-view marker counted every non-structured view at 4 bytes per element, so a typed view (for example `R32G32B32A32_FLOAT`, 16 bytes) with a non-zero first element pointed into the wrong part of the buffer. Typed views now use the format's size; a format of unknown size or a block-compressed one gets no marker. Follow-up of the review note on #767. New test `test_d3d12_console_typed_buffer_constants`.
|
||||
- **`d3d12_xs.dll`: translated draws find texture views made by `CreatePlacedRawShaderResourceViewX`** (#745). That function makes a view of memory placed at an address from a resource description, with no resource object behind it; "raw" does not mean a byte-address buffer. The target build makes the views of its menu textures this way, once per frame, and copies them into each draw's descriptor table. The handler made the host view but did not write the descriptor marker that `CreateShaderResourceView` and `CreatePlacedShaderResourceViewX` write, so with `BX_CONSOLE_SHADERS=1` every such entry was left unresolved and the menu drew without its artwork. A texture view now leaves that marker, and the texture's contents come from title memory like any other placed texture's. Buffer views are not changed here (#767 makes them constant views). `test_d3d12_console_texture_contents` draws a third texture, described but never created, through a view made this way, and checks every pixel in all three rounds.
|
||||
- **`d3d12_xs`: PresentX logs what its composition leaves out.** A plane given as two resources (a colour texture and a separate alpha texture, such as an RGBE + A8 pair) is composed from its first resource only, and with several views (`D3D12XBOX_PRESENT_PARAMETERS::ViewCount`) only the first view is composed. Both were dropped without a word; each is now logged once (`presentx_xbox`). Follow-up of the review notes on #758; `test_d3d12_presentx_planes` checks both lines and that the frame is unchanged.
|
||||
- **`gfx10-translate`: image instructions in the NSA encoding read their addresses from the registers it lists.** MIMG with NSA (non-sequential address) set lists the address VGPRs after the first one byte each in extra words. The decoder counted those words but read the addresses as a contiguous range from the first, so a 2D `image_sample` of `[v4, v7]` sampled at `(v4, v5)`. The list is now decoded, printed as LLVM prints it, and used by `image_sample`, `image_load` and `image_gather4`. Tests: NSA vectors from llvm-mc in `llvm_vectors.txt` (the vector test now compares up to runs of spaces: llvm-mc prints two after an NSA mnemonic), and `image_instructions_read_nsa_addresses`.
|
||||
- **`d3d12_xs`: translated pipelines bind input elements to the vertex shader by semantic.** The host input layout took the title's elements in their layout order as `ATTR0`, `ATTR1`, …, while the translated vertex shader reads input register r as `ATTR<r>` and the console shader's input signature (ISG1/ISGN) gives each register its semantic. Direct3D 12 links elements to shader inputs by semantic name and index, not by order, so a layout listing its elements in another order than the signature fed the wrong data to the shader (for example colour in place of texture coordinates). Each input register now gets the element whose semantic the signature names; a container without a signature keeps layout order, and a missing element is logged as the reason the pipeline is not drawn. New test `test_d3d12_console_input_semantics`.
|
||||
- **`d3d12_xs`: a buffer view made with `CreatePlacedRawShaderResourceViewX` reaches translated draws as a constant buffer.** The view wrote nothing into the title's 32-byte descriptor, so a title that copies it into a draw's table with plain stores copied zeros, and a console shader that reads it with scalar buffer loads (a constant buffer) read zeros. The view now leaves a marker of a constant view of its title memory, and translated draws get the buffer's current contents. New test `test_d3d12_console_raw_buffer_constants`.
|
||||
- **`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.
|
||||
- **Roadmap and working method (proposed).** `docs/roadmap.md` replaces the subsystem milestones M3–M6 with stages the project-authorized target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), each judged on ten recorded runs on a 16 GB Mac, with decision gates for the D3DMetal back end, reference images, memory and frame rate. [docs/process/working-method.md](docs/process/working-method.md) describes the blocker queue for a team that works by telling coding agents to "work": where state lives, the order of work (own pull requests, review, one blocker, discover), the run protocol, source ranks and pull-request shape. AGENTS.md §0 is rewritten to match.
|
||||
- `xg_xs.dll` follows the documented XG contract titles call: `XG_RESOURCE_DESC` and the 14-method `XGTextureAddressComputer`, from the authorized GDK documentation. Behaviour:
|
||||
- **Linear layouts:** every texture is laid out linearly with BetterXen's documented alignment.
|
||||
- **`SW_64KB_S` addressing** for a texture that fits one 64 KiB tile.
|
||||
- **Other requested swizzle modes** are laid out linearly and reported as `LINEAR`, logged once per mode. Refusing them crashed a title that does not check the result.
|
||||
- **`GetResourceTiling`** reports the D3D12 standard 64 KB tile shapes and a packed mip tail. 3D resources get the 3D tile shapes with depth tiles; 1D textures and buffers get 64 KiB tiles.
|
||||
- **Limits:** descriptions past the public D3D12 limits (16384 for 1D/2D, 2048 for 3D and array sizes) are refused rather than truncated, and so is a 3D subresource past the mip count.
|
||||
|
||||
The earlier clean-room interface is removed: `xg_xs.cpp`, `xg_texture.h` and `test_xg_xs`. `test_xg_xbox` (42 checks) replaces it, and stage 13 of `test_integration_boot` uses the documented contract.
|
||||
- `BXVM` configuration writes the output `cpu_pointer` before changing shared configuration or releasing a cached backing heap. If that write fails after the accessibility check, the call returns `E_INVALIDARG` without applying the configuration.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- **`gfx10-translate`: image sample/load/gather forms and `off`-address buffer loads** (#718).
|
||||
- **Image instructions:** `image_sample*` (`_l`, `_b`, `_d`, `_o`, `_cl`), `image_load_mip`, and `image_gather4*` (`image_gather4`, `_o`) across `1D`, `2D`, `3D`, `1D_ARRAY`, and `2D_ARRAY` textures (`Sample`, `SampleLevel`, `SampleBias`, `SampleGrad`, `Load`, `Gather*`). Fixed `decode::address_count` so `_cl` and `_cd` are not treated as comparison `_c`; comparison (`_c`) forms stay refused until a comparison sampler slot is added to the root-signature ABI (`d3d12_xs` `widen()`).
|
||||
- **Buffer loads:** `tbuffer_load_format_{x,xy,xyz}` and `off`-address (`!idxen && !offen`) loads on root buffers, table-bound constant/buffer descriptors, and vertex buffers.
|
||||
- **Refused with a reason:** `buffer_load_format_*` (its data format is in the buffer descriptor, not known at translation) and `v_interp_p2_f16` (the result's register half and the packed attribute layout aren't sourced). `decode` reads the 16-bit interpolation forms.
|
||||
- **Tests:** `address_count_matches_isa`, `decodes_f16_interpolation`, `image_sample_forms_and_dimensions`, `image_sample_grad_load_mip_and_gather`, `vconst_overwrite_clears_constant_offset`, `typed_buffer_loads_refused_off_loads_translated`, and `f16_interpolation_refused` from `llvm-mc` encodings.
|
||||
- **`xg_xs` computes requested swizzle modes with AMD addrlib** (#756). Mesa `src/amd/addrlib` at `mesa-25.2.0` (`0b97dcdd`) is vendored unmodified under `shims/xg_xs/third_party/addrlib`. A title that asks for a swizzle mode other than the one-tile `64KB_S` case (still the public D3D12 standard swizzle) gets that mode's gfx10 layout: size, alignment, mip offsets, texel offsets and copies. `XGSuggestSwizzleMode` suggests `64KB_S` for a 2D colour texture and `64KB_Z` when the format has a stencil plane. `XGComputeTexture2DLayout` and `XGEnableExclusiveLocking` are implemented in the same file and are not exported: `abi/defs/xg_xs.def` still lists the two functions titles import. Linear layouts are unchanged.
|
||||
- **`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 stays refused, and so does `op_sel` on a 32-bit source. 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`: SDWA, DPP, and `v_fma_mix` half select** (#719).
|
||||
- **SDWA** (VOP1/VOP2): a source byte or word is zero- or sign-extended, float `abs` then `neg` apply, then `omod` and `clamp` on an f32 result, then the result is written into the selected destination slice (`UNUSED_PAD`, `UNUSED_SEXT`, or `UNUSED_PRESERVE`). A scalar source is read from the extension word. Reserved selectors, and `clamp` or `abs` on an integer instruction, are refused.
|
||||
- **VOPC SDWA** uses the same source modifiers and writes the mask to `vcc` or the SGPR the word names. DPP compares are refused: gfx1030 does not encode them.
|
||||
- **DPP16**, on the translator's 32-lane waves: `quad_perm`, `row_shl` / `row_shr` / `row_ror`, `row_mirror`, `row_half_mirror`, `row_share`, and `row_xmask`, as `WaveReadLaneAt`. A shift that leaves the row of 16 reads 0 when bound control is set; when bound control is clear the write is disabled and the destination keeps its old value (the same for an inactive source lane when `fi` is clear in structured mode). A clear `row_mask` or `bank_mask` bit keeps the old destination. Bank `k` is lanes `4k..4k+3` of each row of 16, selected by `(lane >> 2) & 3`. `wave_*` and `row_bcast` are refused.
|
||||
- **DPP8**: the eight 3-bit selectors within each group of 8 lanes.
|
||||
- **`v_fma_mix*`**: `op_sel` takes the high half of an f16 source (`op_sel_hi` set), and `clamp` saturates the f32 product-sum before it is packed. `op_sel` on an f32 source is refused.
|
||||
- Tests `sdwa_and_dpp_forms` and `refuses_unmodeled_sdwa_and_dpp` use llvm-mc encodings. A selector or DPP control the assembler will not emit is the llvm-mc word of a legal neighbour with that field replaced.
|
||||
- **`gfx10-translate`: integer, conversion and lane instructions** (#716).
|
||||
- **Scalar:** `s_add_i32`, `s_sub_i32`, `s_min_i32`, `s_max_i32`.
|
||||
- **Conversions:** `v_cvt_u32_f32`, with the ISA's clamping of NaN, negative and too-large values; `v_cvt_f32_ubyte0`–`3`; `v_rcp_iflag_f32`.
|
||||
- **New three-source integer table (`VOP3_UINT3`):** `v_lshl_add_u32`, `v_add_lshl_u32`, `v_lshl_or_b32`, `v_and_or_b32`, `v_or3_b32`, `v_xor3_b32`, `v_add3_u32`, `v_bfi_b32` and `v_bfe_u32`.
|
||||
- **Lanes:** `v_readfirstlane_b32` as `WaveReadLaneFirst`.
|
||||
- **Measured locally:** 802 of the target build's 4,331 vertex and pixel shaders translate on their own, up from 703.
|
||||
- **Tests:** `integer_conversion_and_lane_instructions`, with llvm-mc encodings and expected HLSL from the ISA definitions. The prototype goldens are unchanged.
|
||||
- **`shader-transpiler/crates/gfx10-translate`: BetterXen's GFX10.3 shader translator on `main`** (roadmap, Picture stage). It replaces the experiment-branch Python prototype, which moves to `scripts/console-shader/translate.py` as the reference.
|
||||
- **Pieces:** console container reader (zlib ported from `zlib_inflate.cpp`); a decoder for every encoding format, with SDWA/DPP extension words; HLSL translation of every prototype rule through family tables; and coverage. `bx-cli shader translate <vs> <ps> --out <dir>` and `bx-cli shader coverage <dir>` run it.
|
||||
- **Opcode table:** generated from the public LLVM disassembler by `scripts/console-shader/gen_opcodes.py` (gfx1030, gaps from gfx1010, whose GFX10.1 multiply-adds the console compiler emits). Facts only; recorded in the upstream registry.
|
||||
- **Tests:** 127 instructions decode to exactly the text `llvm-mc` prints (`tests/llvm_vectors.txt`). Three shader pairs of our own, assembled by `llvm-mc`, translate to exactly the prototype's HLSL and layout (`tests/goldens/`). Plus refusals, the multiply-add family, wave32 mask bookkeeping and half compressed exports, and FNV-1a against the published vectors.
|
||||
- **Measured locally on the target build's 4,331 vertex and pixel shaders** (they stay local):
|
||||
- every one decodes; the scan takes 3.6 s, against about 10 minutes through `llvm-mc`;
|
||||
- 703 (16.2%) translate on their own, against 491 for the prototype's rules alone;
|
||||
- all 214 pipeline pairs the prototype translated give identical HLSL and layout.
|
||||
- **Differences from the prototype** are listed in the crate README. Among them: `s_movk_i32` sign-extends, and cache keys use standard FNV-1a (the prototype's offset basis is missing a digit).
|
||||
- **Unattended runs get past input screens and continuable asserts** (`docs/testing/target-build-review.md`, Diagnostics).
|
||||
- **`GameInput.dll`:** `BX_INPUT_SCRIPT=A@40,DOWN@50.5,...` presses gamepad buttons at given seconds after the first reading, each for 300 ms, without window focus. Each press, and each entry it cannot read, is logged (`input_script`).
|
||||
- **`bx_runtime_veh.dll`:** `BX_CONTINUE_ASSERTS=1` steps over an `int3` in the title's own executable instead of letting it reach the crash reporter, and logs each address once (`assert_continued`). An `int3` anywhere else is left alone.
|
||||
- **Tests:** `test_gameinput_script` (readings at fixed times carry exactly the scripted buttons, and unreadable entries are skipped) and `test_veh_continue_asserts` (the executable's `int3` is stepped over twice; one outside any module is not). Both fail on `main`'s shims and pass twice with these.
|
||||
- **The GDK's texture libraries at run time (ADR 0010).** Console texture layouts and BCPack come from the GDK's own PC libraries instead of being reimplemented.
|
||||
- **`bx-cli run`** stages the configured GDK's `xg_xs.dll` (in place of the `xg_xs` shim) and `BCPack.dll` (named to `XCRDAPI.dll` through `BX_BCPACK_DLL`) when the executable is the configured target build, or with `--gdk-libraries`; `--no-gdk-libraries` turns it off. The libraries are recognised by their exports (`gdk_libs.rs`), copied into a temporary shim folder for the run, and never committed. Conformance tests keep BetterXen's own shims.
|
||||
- **`d3d12_xs.dll`** answers `GetResourceAllocationInfo`, `GetResourceAllocationInfo1` and `GetResourceAllocationInfo2` for console texture layouts (`Layout >= 0x100`) with the GDK's XG size and base alignment (`gdk_xg.cpp`), other descriptions with the host's answer, laid out in order at their alignments. It enables XG's exclusive locking at device creation, since the title and the shim both create XG texture computers. Without the GDK's XG, sizes stay as before and the run log says so (`gdk_xg`).
|
||||
- **Tests:** `test_d3d12_gdk_xg_sizes` loads a stand-in XG library with answers the test computes (not Microsoft's code) and checks the sizes, alignments, the two-description layout and the locking. On the previous `d3d12_xs.dll` 6 checks fail; with this change it passes twice. `bx-cli` unit tests cover recognising the libraries by their exports and merging them beside the shims.
|
||||
- **Measured** on the target build (Apple Silicon, CrossOver 26.3, offline, scripted input): the launcher staged both libraries; XG answered 48 console-layout size queries; with #709, 0 page-destination errors, 0 zlib failures and 0 refused BCPack requests. 14 partial reads of compressed blocks remain, so the allocation size is not the only place the title gets a short size (#708 stays open).
|
||||
- `GameInput.dll` exposes one keyboard-backed gamepad through v0 blocking enumeration and current readings. Enter or Space maps to A, Escape or Backspace to B, arrow keys to the D-pad, WASD and IJKL to the two sticks, Q/E to shoulders, Z/C to triggers, F/H to stick clicks, X/Y to the matching face buttons, and P/Tab to Menu/View. Input returns to neutral when another application owns the foreground.
|
||||
- **D3DMetal capability checks for translated console shaders** (#671). `test_d3dmetal_translator_caps` measures, against the host D3D12 runtime, the features a translator of console code needs: SM 6.6 descriptors fetched by index (UAV, raw and typed SRVs, texture and sampler) run correctly; a 64-lane wave emulated over a 64-thread group gives the 64-lane answers through groupshared memory and through merged 32-lane host waves; amplification and mesh shaders draw correctly. With the 64-bit atomic results of `test_d3dmetal_gpu_limits` (native 64-bit atomics are not run even though D3DMetal reports support; the lock emulation with a 1024 cap is exact), no need is blocked. Results are in [D3DMetal GPU limits](docs/research/d3dmetal-gpu-limits.md#capability-checks-for-translated-console-shaders-671).
|
||||
- `xgameruntime.dll` serves `XGameSaveGetContainerInfo` (slot 13) and `XGameSaveEnumerateContainerInfoByName` (slot 15) on `IXGameSaveImpl` (#667). `XGameSaveGetContainerInfo` reads container metadata without loading blob payloads and, when the named container does not exist, succeeds without invoking the callback (source rank 3 inference). `XGameSaveEnumerateContainerInfoByName` filters containers by name prefix (treating `nullptr` or empty prefix as all containers), sorts by name, and stops early when the callback returns `false`. `test_xgameruntime_saves` checks both slots through `QueryApiImpl`.
|
||||
- `xgameruntime.dll` serves `XAsyncRun`, `XTaskQueueCreateComposite`, `XTaskQueueGetPort` and `XTaskQueueDuplicateHandle` through `IXGameRuntimeCore` slots 6, 13, 14 and 15 (#666). `XAsyncRun` runs the title's work callback on the block's work port and completes the block with its result. A duplicated queue handle shares the queue, and only the last close shuts its lanes down. A composite queue forwards each port to the port it was made from, and an async block's completion returns through the queue the block named. A project-authorized target build uses these for its save-game work and exited when `XAsyncRun` was unimplemented. `test_xgameruntime` checks all four through `QueryApiImpl`.
|
||||
- `bx-cli report <log.jsonl>...` (#664, part 1): a run report per log (one log is one run) and a summary across runs. Per run: how it ended, the frames presented (a lower bound), every unimplemented call with its count, faults whose innermost frame is in a BetterXen module, and pipelines by kind. The summary counts clean runs and lists each blocker signature with the number of runs that hit it; blocker issues are titled with those signatures. `bx-cli run` now appends a `run_end` record to its log (exited with a status, timeout, signal or launch failure), which the report reads. A log without it has an unknown outcome and is never counted as clean.
|
||||
- `xgameruntime.dll` serves `XUserDuplicateHandle` through `IXUser` slot 3 (#680). A duplicate is a new handle to the one offline user; each handle is closed on its own, and `XUserCompare` returns 0 for any two valid handles of that user. A project-authorized target build duplicates its user handle after sign-in and waited when the slot was unimplemented. `test_xgameruntime` checks the slot through `QueryApiImpl`.
|
||||
- Shader corpus, Phase 0 of the console shader translator (#649). `shader-transpiler/corpus/hlsl/` holds eight BetterXen-authored compute kernels covering integer and float ALU, divergent branches, loops, groupshared memory, wave operations, atomics and system values. `scripts/shader-corpus/build.sh` compiles each one locally with the console `xdxc` (a title-style container: `DXIL` plus `ACCC`/`FSPX`), the console PIX compiler (Microsoft's ISA listing) and the public PC DXC (DXIL for a D3DMetal reference run). `extract_code.py` then takes the code from the `FSPX` kind-6 section, skips the leading `v_nop_xbox_data` words and disassembles it with LLVM's public `gfx1030` decoder. All eight kernels build and decode cleanly. The extractor has nine unit tests on synthetic containers that need no GDK. Compiler outputs stay in the git-ignored `target/shader-corpus/`. One open question is recorded: a `v_cmp_class_f16` in the `wave` kernel's ballot sequence.
|
||||
- `docs/research/console-shader-abi.md` and `CLAIM-XBOX-CS-ENTRY-ABI` (class U, not yet independently reproduced): the compute shader entry ABI observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler, used under Microsoft's authorization, on eleven project-authored probes. Compute code is wave64. Root data starts at `s4` in root-parameter order: one SGPR per constant, two per root descriptor address, one per 32-bit table pointer. The thread-group IDs follow the root data, and `s0:s1` holds the root-data address when it overflows. Root buffer descriptors are built inline with no effective bounds check, table buffer descriptors are 32 bytes apart (samplers 16), and the compiler reports the HLSL binding of each descriptor load. No compiler output, binary or documentation text is in the repository. Register roles are inferences, and the ACCC container layout remains unknown.
|
||||
- Opt-in diagnostics in `bx_runtime_veh.dll`, all off by default:
|
||||
- an access-violation context with the memory type and the faulting thread's stack (`BX_VEH_AV_CONTEXT`, `BX_VEH_AV_ALL`);
|
||||
- software write watches over one address, a range or a pointer chain (`BX_VEH_WATCH`, `BX_VEH_WATCH_RANGE`);
|
||||
- software code breakpoints that log string arguments (`BX_VEH_HIT`, `BX_VEH_HIT_ALL`);
|
||||
- an all-threads sampling profiler (`BX_VEH_SAMPLE`).
|
||||
|
||||
Records are bounded, JSON-escaped and UTF-8. A protection change that fails disarms the diagnostic, which is logged, and the guest gets its exception. Detach disarms everything. With the switches unset, nothing runs. `bx-cli run` lets these named switches through its isolated guest environment. `test_veh_diagnostics` covers every mode.
|
||||
- `bx_runtime_veh.dll` records breakpoints (`0x80000003`) and assertion failures (`0xC0000420`) from its vectored handler as `breakpoint_exception` JSONL records with the exception code, module name, module base and RVA. A guest with its own crash reporter replaces the top-level filter installed at attach, so its assertions never reached `unhandled_exception`; the vectored handler runs before the guest's top-level filter and any vectored handler the guest registers last (one it registers first can resume the exception before BetterXen sees it). Module names are written as UTF-8, and `bx-cli trace` notes when the record cap was reached. The records are first-chance (the guest may still handle the exception), handling is unchanged, and at most 16 are written per process. `bx-telemetry` parses them and `bx-cli trace` lists them under "Breakpoint/assert exceptions, first chance".
|
||||
- **Test:** `tests/conformance/test_veh_breakpoint/` replaces the top-level filter and resumes from its own vectored handler, as such a guest does. It raises 21 int3 breakpoints at a labelled site and one `STATUS_ASSERTION_FAILURE`, and requires exactly 16 records, the int3 records at the RVA it computes from the label and its own module base, and no `unhandled_exception`. It fails against the previous `bx_runtime_veh.dll`.
|
||||
- [Target-build bring-up: development cycle and review](docs/testing/target-build-review.md): how contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently.
|
||||
- `xgameruntime.dll` serves the XPackage installation monitor offline: the running package is reported fully installed, launchable and complete. Monitor handles share the mount handles' table, generation and lock: stale handles are rejected, closing twice is harmless, and uninitialize releases them. Progress registrations are accepted, logged and never fired. `XPackageEnumeratePackages` reports this game for `XPackageKind::Game` and no content packages. Both replace stubs that a project-authorized target build calls at startup. The save-container mount path ends with the drive-root separator, and `test_xgameruntime_saves` expects it.
|
||||
- `AcpHal.dll`:
|
||||
- **Shape contexts:** `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` allocate from the APU heap. The layout is the documented `SHAPE_CONTEXTS` (96 bytes; CPU pointers at 24, APU addresses at 72). A second allocation returns `ACP_E_ALREADY_ALLOCATED`.
|
||||
- **`IAcpHal`** has the documented non-COM slot order: `Connect`, `Disconnect`, `SubmitCommand`, `PopMessage`, `GetNumMessages`, `Release`.
|
||||
- **The default APU heap** is 64 MB.
|
||||
- **Tests:** `test_audio_input` checks both. `test_integration_boot` releases `IAcpHal` through its own `Release` slot.
|
||||
- `d3d12_xs.dll` carries a project-authorized target build from device creation into its frame loop. The Xbox-layout device and its objects get:
|
||||
- **Descriptor heaps** with title-visible storage and the console descriptor sizes.
|
||||
- **Committed and placed resources** in title memory, with copy coherence for `Map`/`Unmap`.
|
||||
- **Samplers and page pools.**
|
||||
- **Pipelines** through the shader gate.
|
||||
- **Opt-in null rendering** (`BX_NULL_RENDER=1`): pipelines that cannot be built become null pipelines, and their draws and dispatches are skipped and logged.
|
||||
- **Fences** at GPU addresses and GPU value writes.
|
||||
- **`PresentX`** onto a DXGI swapchain.
|
||||
- **Console page mappings:** `CopyPageMappingsX`, `CopyPageMappingsBatchX` and `ClearPageMappingsX`.
|
||||
- **The full 1,384-byte Xbox command-list area.**
|
||||
- **Opt-in dumps of presented frames** (`BX_PRESENT_DUMP`).
|
||||
|
||||
`test_d3d12_xbox_layout` checks the page mappings and the command-list area.
|
||||
- `xgameruntime.dll!QueryApiImpl` now serves the runtime objects behind **`XSystemGetAnalyticsInfo`** and **`XDisplayTryEnableHdrMode`**, which a project-authorized target title requests during System Init (previously logged as unsupported `B884675D-…` and `03F0FE74-…/35F07670-…`). The keys and slots (analytics slot 3, which returns `XSystemAnalyticsInfo` by value; HDR slot 4) were derived from authorized GDK material, and no GDK files are in the repository. The function contracts follow Microsoft's public `XSystem.h` / `XDisplay.h` documentation. `XSystemGetAnalyticsInfo` reports family `Xbox`, a form that follows the profile (`Xbox Series S` for Lockhart, `Xbox Series X` for Anaconda) and BetterXen's synthetic OS version `10.0.26100.0` (logged with `synthetic=1`). `XDisplayTryEnableHdrMode` returns `XDisplayHdrModeResult::Disabled`, the documented success answer when HDR is not enabled, because BetterXen presents SDR. It clears the optional luminance output and logs the preference. `test_xgameruntime` calls both through `QueryApiImpl` and checks the public contract. The target title now gets past both calls; its next stops are fixed by #643 and #640.
|
||||
- `xmem.dll` exports two new internal cross-DLL hooks, `bx_xmem_try_charge_external` and `bx_xmem_release_charge_external` (`abi/defs/xmem.def` grows 15 → 17; `scripts/build-shims.sh` now reports 113 exact exports) (#550). They admit and release bytes against the combined Lockhart/Anaconda title cap under the same `usage_lock` `can_commit` takes, and `can_commit` now counts a new `external_bytes` counter in `used`. `XMemGetWorkingSetStatistics` / `bx_xmem_get_internal_stats` report external charges inside `committed_virtual_bytes`, so reported usage matches what the cap counts. A release larger than the outstanding external charge is refused and logged (the counter is left unchanged, so other owners' charges survive), and a failed bookkeeping refresh during a charge is logged as `external_charge` instead of being reported silently as a budget rejection. New `test_xmem_external_charge` charges externally and checks that `XMemVirtualAlloc` is then refused at the cap, that the stats include the charge, that an over-release is refused, and that the allocation is admitted again after release. `d3d12_xs` switches to the hook in the same change (#552, below).
|
||||
- `bx-cli run` maps the Xbox title drives before launch: `G:` to the executable's directory and `T:` to `drive_c/bx_temp` in the prefix or bottle (`launcher/crates/bx-cli/src/drives.rs`). An Xbox title opens its package on `G:` and writes crash logs to `T:`, and stops at startup when either is missing (observed on a project-authorized target build; the drive roles are an inference). Ownership is recorded before creating or retargeting links, so a failed manifest write cannot leave an unrecorded mapping; temporary links use per-process names and manifest targets use lossless path-byte encoding. A prefix lock prevents another `bx-cli run` from changing its drive mappings while a guest is active. The `.bx-drives` manifest is written to a temporary file and renamed into place without following an existing temporary symlink, so an interrupted write keeps the previous manifest instead of leaving a truncated one that later runs refuse. **Behaviour change:** `bx-cli run` takes a prefix-wide lock before system32 staging and holds it until the guest exits, so runs sharing a prefix or bottle are serial: a second launcher on the same prefix is refused, before it stages anything. `test_xbox_drives` checks the resulting layout, not who created the links.
|
||||
- **Ownership:** like system32 staging (#474), a `.bx-drives` manifest in `dosdevices` records each link the tool made. Only those are re-pointed. A drive letter mapped elsewhere by anything else is left unchanged and reported as a warning. A prefix without `dosdevices` is reported and the run continues.
|
||||
- **Test:** `tests/conformance/test_xbox_drives/` reads its own executable through `G:` and compares it byte for byte with the copy at its module path, then creates, reads back and deletes a file on `T:`. Unit tests in `drives.rs` cover creation, reruns, re-pointing an own link, foreign links and entries, a missing `dosdevices`, malformed manifests, a failed manifest write, lock contention and non-UTF-8 path round-tripping.
|
||||
- `d3d12_xs.dll` gives titles Xbox-layout D3D12 objects ([ADR 0009](docs/adr/0009-xbox-layout-d3d12-objects.md)). A title built against the Xbox Series D3D12 header calls through function tables whose order differs from PC D3D12. `ID3D12Device` matches only up to slot 43, and `ID3D12Device11` has 139 slots. So before, every call past those slots reached the wrong PC method, and on a project-authorized target build the first such call jumped to address 0.
|
||||
- **Objects and tables:** `BxXboxObject` (`shims/d3d12_xs/xbox_facade.{h,cpp}`) has the Xbox object layout and sets `m_OutOfLineFlags`. Its Xbox-order table forwards to the PC proxies. `shims/d3d12_xs/tools/gen_xbox_tables.py` generates the tables (`xbox_tables_generated.cpp`) from the Xbox header, used under Microsoft's authorization, and the toolchain's `<d3d12.h>`. It takes only slot order, names, IIDs and parameter types, and the header is not committed.
|
||||
- **Slots:** a slot with an equivalent PC signature forwards with the PC types, unwrapping interface parameters and wrapping created objects. Every other slot logs `BX_VTABLE_STUB_LOG`.
|
||||
- **Coverage:** the device chain up to `ID3D12Device11`, plus resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues. Command lists are not covered yet.
|
||||
- **`CreateCommandQueueX`:** maps the Xbox queue description onto PC `CreateCommandQueue`.
|
||||
- **Layout choice:** titles set `Version` in the device parameter block and get the Xbox layout. BetterXen's PC-layout fixtures pass a zeroed block and keep the PC proxy. The choice is logged as `xbox_layout`.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, created through `CreateCommandListX` or `CreateCommandList`. Their zeroed put-buffer fields force the five inline fast paths through the table.
|
||||
- **Embedded interface pointers:** `ResourceBarrier` and `CopyTextureRegion` unwrap the interface pointers inside their structures.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` are emulated by a host timer (`frame_pacing.cpp`).
|
||||
- **Generator fixes:** CRLF lines, a table-boundary overrun that hid `ID3D12GraphicsCommandList1`, nested SAL, and `FLOAT`.
|
||||
- **Resources at title-chosen addresses:** `CreatePlacedResourceX`/`X1` create host shadow resources (`placed_x.cpp`), with buffer contents copied from the title's memory at creation. The resource reports the title's address from `GetGPUVirtualAddress`. Ongoing synchronisation, GPU-to-CPU copies, title-address translation in GPU calls and texture contents are not implemented yet.
|
||||
- **Test:** `tests/conformance/test_d3d12_xbox_layout/` calls Xbox slots by number, with the slot numbers and offsets written out by hand from the header and the expected values taken from a PC-layout device. It also records a buffer copy through Xbox command objects, runs it on the GPU and reads the result back, and checks frame pacing. It fails against the previous DLL (8 checks against the Phase 1 build).
|
||||
- Added `tests/conformance/test_xcrdapi_abi/` (#597), an independent verification of the public DirectStorage ABI that `XCRDAPI.dll` serves. Every call goes through a hand-typed C vtable read out of the object (`slots(object)[n]`, cast to a signature typed in the test), with slot numbers and parameter types transcribed from the `DECLARE_INTERFACE_IID_` blocks of the vendored `dstorage.h` 1.4.0 in declaration order, including the inherited `IUnknown` slots — not from the shim's C++ class declarations. Derived slot counts, one per interface, are `IDStorageFile` 5, `IDStorageFactory` 8, `IDStorageFactory1` 9, `IDStorageStatusArray` 5, `IDStorageQueue` 12, `IDStorageQueue1` 13, `IDStorageQueue2` 14, `IDStorageQueue3` 15 and `IDStorageQueue4` 16; the test prints the `IDStorageFile`, `IDStorageFactory1`, `IDStorageStatusArray` and `IDStorageQueue4` tables (the last covering every one of the 16 queue slots). It asserts that each slot resolves to the method the header names: `IUnknown` identity and refcount arithmetic, `CreateQueue`/`CreateQueue1` capacity, priority and `UsesGaclShuffleTransform` validation, `OpenFile` error and success paths, `CreateStatusArray`, `SetDebugFlags`, `SetStagingBufferSize`, `Close`/`GetFileInformation`, `IsComplete == (GetHResult != E_PENDING)`, `EnqueueRequest`/`EnqueueStatus`/`EnqueueSignal`/`Submit`/`CancelRequestsWithTag`/`Close`/`GetErrorEvent`/`RetrieveErrorRecord`/`Query`, `EnqueueSetEvent`, `GetCompressionSupport`, `EnqueueRequests` and `Query1`. The `ID3D12Fence` and foreign `IDStorageStatusArray` arguments are hand-built C vtables, so a wrong slot cannot be absorbed by a matching C++ declaration. Slot order and IIDs were cross-checked against Silk.NET's MIT DirectStorage bindings (which bind the same slots through `EnqueueRequests` at 14; Silk.NET 1.3.0 predates `IDStorageFactory1` and `IDStorageQueue4`, so `CreateQueue1` at 8 and `Query1` at 15 come from the header's inheritance chain). No slot mismatch and no staged-copy lifetime bug was found: `StagedGpu`/`copy_staged()` keeps the device, upload buffer, queue, allocator, list, completion fence, defer fence, event and destination alive on every path where the submitted fence has not reached 1, including the `defer_staged_copy()` seam and the timeout path, which `test_xcrdapi` exercises. A mutant `XCRDAPI.dll` built with `Submit` and `CancelRequestsWithTag` swapped in the header fails the test (`queue slot 6 (Submit) did not submit`), proving it distinguishes slots. Ran under Wine 11.21 (Gcenx build) + Rosetta 2 on Apple Silicon with the **vkd3d** backend: `test_xcrdapi_abi.exe` and `test_xcrdapi.exe` both passed. CrossOver and D3DMetal are not installed on this host, so no D3DMetal run was performed and `bx-cli run` (which requires `/Applications/CrossOver.app`) was not run.
|
||||
- The synthetic M2 first-frame fixture (#469) requires the placed-resource and PresentX contract headers; missing contracts fail the build rather than silently omitting the gate. It checks dynamic GDK boot, SM 6.6 shader inspection, and one host present. It compares 256 pre-flip RGBA8 pixels through a placed buffer in the D3D12 WRITE_BACK heap and checks that the separate xmem region used for virtual-memory configuration retains its sentinel bytes. The pixel check covers the swapchain back buffer before the flip. The `tests/conformance/README.md` documents the negative-control command; it uses a sanitized launcher environment with `--inherit-env` to pass `BX_M2_FIRST_FRAME_INJECT_PIXEL_MISMATCH=1` and expects a `pixel_readback` failure.
|
||||
- `d3d12_xs.dll` now runs stream pipeline states through the M2 shader gate (#576). `ID3D12Device2::CreatePipelineState` forwarded `D3D12_PIPELINE_STATE_STREAM_DESC` to the host unparsed, so an ACCC-only container that `CreateComputePipelineState` and `CreateGraphicsPipelineState` refuse with `E_NOTIMPL` still reached D3DMetal through the stream form — the crash the gate exists to prevent — and was logged only as `pso_stream ... shaders_not_parsed=1` with no `shader_gate` record.
|
||||
- **What is parsed:** the stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, and `AS`/`MS`) are classified with `BxShaderGate::admit`; every other payload is copied verbatim. An unknown type, a duplicated type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim works on its own copy, so the gate can substitute prepared DXIL without writing to the caller's memory.
|
||||
- **Layout correction (review):** the first version assumed every payload sat at offset 8. `alignas(void*)` on the subobject class aligns the *record*, not the payload, so 4-byte-aligned payloads (`BLEND`, `SAMPLE_MASK`, `RASTERIZER`, `DEPTH_STENCIL`, `DEPTH_STENCIL1`, `IB_STRIP_CUT_VALUE`, `PRIMITIVE_TOPOLOGY`, `RENDER_TARGET_FORMATS`, `DEPTH_STENCIL_FORMAT`, `SAMPLE_DESC`, `NODE_MASK`, `FLAGS`) sit at **offset 4**. The table now derives `payload_at<T>()` and `record_size<T>()` from a `struct alignas(void*)` record, with `static_assert`s pinning the measured offsets (shader 8/24, UINT 4/8, BLEND/RASTERIZER/RT_FORMAT_ARRAY/DEPTH_STENCIL1 at 4). A valid graphics stream with those tags was desynced and rejected before the fix. `test_shader_gate`'s `StreamBuilder` now encodes the same real layout and adds a graphics stream with 4-byte-aligned payloads, so the tests can catch a desync instead of asserting the shim's own assumption.
|
||||
- **Logging:** `pso_stream` keeps its record and now reports `shaders_not_parsed=0` when it parsed the stages; each stage adds its own `shader_gate` record with `pso=stream`.
|
||||
- **Tests:** `test_shader_gate` adds a stream PSO whose CS is the synthetic ACCC-only container (`E_NOTIMPL`, `*ppv == nullptr`), the same stream with the SM 6.6 DXIL blob (succeeds and its 256 output words are verified), a truncated stream, an unknown subobject type, and a duplicated `CS` (`E_INVALIDARG` each), plus the `--no-bridge` child refusing ACCC-only through the stream. It also asserts the new `pso=stream` `shader_gate` records and `shaders_not_parsed=0`. The stream walker's accept/reject decisions were checked on the host with a native `clang++` harness (valid, truncated, unknown-tag and out-of-range-tag cases).
|
||||
- `abi/` unchanged; `d3d12_xs.dll` still exports 4. **`test_shader_gate.exe` was not executed** — no CrossOver on this host. The ADR 0008 wording recording stream PSOs as covered by the shader gate now lands with this stream-PSO gate change (#578 / PR #607).
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- **`d3d12_xs.dll`: `PresentX` composes its planes** (authorized GDK documentation, *Hardware overlays*). It copied plane 0 alone to the window and logged that plane 1, rectangles and scaling were not applied. The target build presents its scene in plane 0 (1920×1080) and its UI in plane 1 (3840×2160), so its first menus, drawn correctly into plane 1, never showed. Planes are now drawn in order, plane 1 in front, as premultiplied alpha (`ONE`, `INV_SRC_ALPHA`) over transparent black, each scaled from its source rectangle (`pSrcViewRects`, texels) to its destination rectangle (`pDestPlacementBase`, normalized), into a texture the size of the swapchain that is copied to the back buffer and dumped by `BX_PRESENT_DUMP`. The shaders are compiled at the first such present with the GDK's PC `dxcompiler.dll`; without it plane 0 is copied as before (logged). Colour spaces other than RGB full G2.2 P709 are composed as SDR in plane order (logged once). One plane without rectangles is copied as before. `test_d3d12_presentx_planes` presents two planes of its own with and without rectangles and checks the composed frames.
|
||||
- **`d3d12_xs.dll`: texture contents are uploaded by the GPU** (follow-up of #747). The texels of a texture placed in title memory were written into its copy from the CPU (`WriteToSubresource`), on the submitting thread; for the target build's two continually rewritten 3840×2160 textures that cost about 30 % of the frame rate. They are now written into an upload buffer of the copy's own (rows copied, or untiled by XG straight into it) and copied by the GPU, on a list of the shim's own executed on the submitting queue ahead of the title's lists; the copy lives on a default heap in the shim's own states. An upload buffer is not rewritten until the GPU is past its last copy, and buffers of released textures are freed only then.
|
||||
- **`d3d12_xs.dll`: a texture placed in title memory shows its pixels in a translated draw** (#745). With `BX_CONSOLE_SHADERS=1`, when a translated draw reads a texture that `CreatePlacedResourceX` placed in title memory, its contents are copied from that memory into a CPU-writable copy of the host texture, which the view then reads: the linear console layout (`0x100`) row by row at its 256-byte pitch, other console layouts untiled through the GDK's XG library (`CopyFromSubresource`, ADR 0010). A view reads the copy only once a copy has succeeded; until then, and after a failure, it reads the host texture and the next draw tries again. So that textures still being streamed fill in, a later draw checks a hash over a sample of the title memory (64 bytes every 64 KiB), at an interval that starts at 250 ms and doubles up to 4 s while nothing changes; only a change copies the texture again (logged). The contents live in this side copy, not in the host texture: copy commands and other views read the empty host texture, and the first `CopyTextureRegion(X)` out of such a texture is logged. Render-target, depth and UAV textures are not copied over. `CreatePlacedShaderResourceViewX` now writes the descriptor marker that `CreateShaderResourceView` writes, so translated draws find views made that way. Before, every such texture was sampled empty. `test_d3d12_console_texture_contents` draws a linear and a tiled texture of its own (through a stand-in XG), with a view made each way, and checks every pixel over three rounds: a copy from unreadable memory, its retry at the next draw, and a copy again after the title rewrites one texture (and not of the unchanged one).
|
||||
- **`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.
|
||||
- **xmem: remapping some pages of a reservation no longer takes its other pages out** (#729). A run mapped with one call was one view, and remapping part of it unmapped the whole view and mapped the rest back, so a title thread reading an untouched page could fault (the #722 retry turned that into a wait) or, rarely, read other data. The console's page-table update is atomic.
|
||||
- Every 64 KB page of an `XMEM_MAPPABLE` reservation is now its own view, so a remap replaces only the views of the pages it names.
|
||||
- Mapped views are found by address instead of by walking all of them: with about 100,000 views, the per-page lookups of `CopyPageMappingsBatchX` stalled the target build's frames for over 30 s.
|
||||
- Mapping a page no longer queries its range first (`VirtualQuery`, about 7 s of the Series X boot): placeholders in a reservation begin and end on 64 KB boundaries.
|
||||
- Cost, measured on the target build: the first presented frame comes at about 18.6 s instead of 3.7 s with the Series X profile, and 10.9 s instead of 3.6 s with Series S, from mapping the page pool one view per page (`MapViewOfFile3`, a Wine server call per page). The `remap_window_retry` of #722 stays for now.
|
||||
- Tests: `test_xmem_remap_neighbours` (new) reads two untouched pages of a four-page run from four threads while the middle two are remapped, with no warm-up remap; `test_veh_remap_window` now checks its reads. Both count faults ahead of the #722 retry and require no fault and no wrong value. Without the change both fail (3 to 4 faults per run).
|
||||
- **xmem: pages of an `XMEM_MAPPABLE` reservation are mapped on first touch, which recovers the boot time and frame pacing that one view per page cost** (#754, #729). `XMemMapPhysicalPages` and `XMemMapPhysicalPagesScatter` now record each slot's page; the slot is mapped when an instruction first touches it, by a vectored exception handler in `xmem.dll`, and a remap of a slot that was never touched changes no host mapping. On the target build at least 16,384 of 135,040 mapped pages are touched in two minutes with Series X, and at least 12,288 of about 85,800 with Series S. Measured on the target build (Apple M5, 120 s, `BX_CONSOLE_SHADERS=1`, two runs each), against `main` dcb9e434 and one view per page mapped at once: first frame 3.9–4.1 s (3.8 s, 18.6 s) and frame 2,048 at 77.7–78.0 s (83.6 s, 110.9 s) with Series X; 3.9 s (3.7 s, 10.9 s) and 76.1–76.3 s (78.0 s, 90.6 s) with Series S.
|
||||
- **System calls that write into title memory map its untouched pages first**, since such a write fails (`ERROR_NOACCESS`) where an instruction would fault: `ReadFile` imports of the modules loaded at the first mapping go through a wrapper (the target build reads a file of about 270 MB straight into its page pool), and `XCRDAPI.dll` touches a destination before its own `ReadFile`. Writes by instructions, `XCRDAPI.dll`'s decompression and copies and `d3d12_xs.dll`'s copies included, fault and are mapped by the handler.
|
||||
- **Page sections are `SEC_RESERVE`, and a view is committed after it is mapped.** Over a placeholder, Wine first makes a committed section's view accessible as the placeholder's zeroed memory and only then maps the section, so a second thread touching the slot at that moment read zeros (or lost its write); a reserved section's view stays inaccessible until it is committed.
|
||||
- **`d3d12_xs.dll` checks title memory without mapping it:** a page xmem reports mapped counts as present (`title_memory.cpp`), so registering a page pool does not map its 100,000 pages and the copy that follows maps only what it reads.
|
||||
- Tests: `test_xmem_lazy_map` (an untouched slot stays a placeholder through 2,000 remaps, the query reports it, eight threads touch the same new slots at once, an unmapped slot still faults), `test_xmem_lazy_file_read` (a title's own `ReadFile`, synchronous and overlapped, into untouched pages) and `test_xcrdapi_lazy_destination` (uncompressed, zlib and memory requests into untouched pages). `test_xmem_physical` now expects an untouched slot to be reserved until its first touch.
|
||||
- **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.
|
||||
- **Depth-stencil unordered-access views** (allowed on the console, forbidden on PC): the descriptor gets a null view and the call is logged as unimplemented (`CreateUnorderedAccessView(depth-stencil resource)`).
|
||||
- **Limits:** sizes reported for a translated format are the host format's, `GetDesc` reports the host format, and pipeline-state formats are not translated yet.
|
||||
- **Test:** `test_d3d12_console_formats` (21 checks; without the fix the process dies at the first console-only format).
|
||||
- `bx_runtime_veh.dll` completes a `CLZERO` loop in one exception (#665). A title that zeroes memory with `clzero; add rax,0x40; cmp rax,<reg64>; jb` raised one illegal-instruction exception per 64 bytes under Rosetta 2, which stalled a project-authorized target build's frame loop for tens of seconds. When the trapped `CLZERO` is followed by exactly that form, the handler zeroes every remaining line below the limit and leaves `RAX` at the last one, so the title's own `add`/`cmp`/`jb` leaves the loop. The range is zeroed region by region and stops at memory that is not committed and writable, where the next `CLZERO` traps and faults as before. Other loop forms keep the per-instruction path. `test_veh_clzero_loop` checks the memory result and counts the exceptions; it fails on the old handler.
|
||||
- `d3d12_xs.dll` no longer turns `DeserializeGraphicsPipelineStateX`, `DeserializeComputePipelineStateX`, `CreateDerivedGraphicsPipelineStateX` or `CreateDerivedComputePipelineStateX` into null pipelines in null-render mode (`BX_NULL_RENDER=1`) (#669). All four calls now always return `E_NOTIMPL`, clear `*ppv` and log `pipeline_refused` without `; null pipeline returned`, so a title falls back to creating pipelines from shader containers instead of silently receiving null pipelines. `test_d3d12_serialized_pipelines` checks all four slots and their refusal log lines with `BX_NULL_RENDER=1` active alongside a control shader-container null pipeline.
|
||||
- `XCRDAPI.dll` Xbox DirectStorage fixes:
|
||||
- **Zlib requests read the file.** The file handle was not set for them, so every compressed file request failed. The request options are now decoded, and zlib streams are inflated in-tree.
|
||||
- **`AutoSubmitDisabled` is honoured.** Xbox `CreateQueueX` respects `DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled`: a queue with the flag runs nothing before `Submit`, and when it is full the enqueuer waits until `Submit` is called on another thread. A queue without the flag submits by itself once half full.
|
||||
- **Request trace:** `BX_DSTORAGE_TRACE=1`.
|
||||
- **Tests:** `test_xcrdapi_xbox` covers a file-source zlib request and both queue behaviours. Each check fails with its fix reverted.
|
||||
- `xmem.dll` physical page numbers count 4 KiB frames. A 64 KiB page's number is a multiple of 16, and each allocation's numbers start at a multiple of 0x1000 frames. With consecutive numbers, callers that keep `number >> 4` collapsed 16 pages into one, and memory written through one page appeared in others. Physical pages are mapped as runs: one view per run of consecutive pages instead of one per page. On a project-authorized target build, startup went from 36 s to 6 s, under the title's 30-second watchdog. Allocation goes through the title's registered allocation hooks, with one section per physical-page call. A GPU-only reservation with large pages (no CPU access, a `PAGE_GRAPHICS_*` bit set) becomes a mappable placeholder region, so console page-mapping calls can fill it. `BX_XMEM_TRACE=1` logs allocations, frees and maps. `test_xmem_physical` checks the page-number units, and `test_xmem_hooks` checks the hooks.
|
||||
- `d3d12_xs.dll` refuses an Xbox-layout object the host cannot back. If the host object lacked the interface an Xbox table forwards to (on vkd3d, `ID3D12Device10`), `bx_xbox_wrap` returned the PC object, and `D3D12XboxCreateDevice` reported an Xbox-layout device. A title calling Xbox slot numbers would then have reached PC methods. The device and every wrapped family now fail with `E_NOINTERFACE`, logged as `xbox_wrap_refused`. `test_d3d12_xbox_layout` verifies the refusal on such a host and skips (exit 77); it passes on D3DMetal.
|
||||
- `d3d12_xs` validates placement on **every heap and every placement entry point** (#554, #572). `CreatePlacedResource` (slot 29) checked alignment, extent, buffer clear value and the UPLOAD/READBACK initial state only on the backing heap, and `CreatePlacedResource1` (`ID3D12Device8` slot 70) and `CreatePlacedResource2` (`ID3D12Device10` slot 77) were generated pass-throughs with no check and no `kPlacedResourceHeap` retention, so the shim heap wrapper and its xmem charge could be released while a resource placed through them was still alive. All three now share `create_placed_common` in `vmem.cpp`: a null heap or desc, a misaligned offset or a resource past the heap end returns `E_INVALIDARG` with `*out` null and a `placed_resource` log line naming the method, and a shim heap is retained by the resource on all three. `CreatePlacedResource2` takes a barrier layout, so the resource-state rule is not applied to it, and its allocation info comes from `GetResourceAllocationInfo2` without the castable-format list. `tools/gen_proxy.py` gains a `HANDOFF` table that keeps the generated trace and null-host stub and passes the host interface and unmodified arguments to a function declared from the header signature; `proxy_generated.{h,cpp}` are regenerated, and no new vtable slot is patched. `test_d3d12_placed` adds misaligned, aligned-overhang, valid-offset and UPLOAD-state cases on an ordinary heap for each entry point, and runs the heap-charge retention check through all three. Run live under CrossOver 26.3 in a D3DMetal bottle: passes (173 checks, 1 skipped — the 512 MiB pairing check; at `BX_MEM_LIMIT_MB=512`, 189 checks, 0 skipped), including every `CreatePlacedResource2` case. Against the previous shim the new cases fail ten checks there: D3DMetal returned `S_OK` for a misaligned offset, an aligned overhang and an UPLOAD heap in `COPY_DEST` on all three entry points it was asked about, and the slot 70/77 resources dropped the heap charge. Under `bx-cli run` (vkd3d) the fixture also passes (163 checks, 3 skipped); that host does not expose `ID3D12Device10`.
|
||||
- `xmem.dll` follows the documented signatures of five exports (source: the authorized GDK documentation). Before, a title calling them as documented had its arguments misread: on a project-authorized target build, `XMemAllocatePhysicalPages` failed and the title's check broke into its crash reporter. `XMemAllocatePhysicalPages` accepts `MEM_64K_PAGES` (`MEM_2MB_PAGES | MEM_PHYSICAL`) as 64 KB pages, as Microsoft's public samples pass it; the `MEM_2MB_PAGES` bit alone is `XMEM_2MB_CLUSTERS`, still unimplemented and logged. `test_xmem_physical` adds the samples' shape: a `MEM_64K_PAGES` page mapped into a mappable reservation made with protection `0x2404`.
|
||||
- **Signatures:** `XMemAllocatePhysicalPages(XMemFlags, NumberOfPages, PageArray)`, `XMemFreePhysicalPages(NumberOfPages, PageArray)` (count by value), `XMemMapPhysicalPages(VirtualAddress, NumberOfPages, PageArray)` and `XMemMapPhysicalPagesScatter(VirtualAddressArray, NumberOfPages, PageArray)` (parallel arrays, returns `BOOL`). `XMemVirtualAlloc(BaseAddress, Size, AllocationType, XMemFlags, PageProtection)` takes five arguments, which supersedes the closed #518.
|
||||
- **Pages and flags:** physical pages are always 64 KB. The four memory-bandwidth values are accepted. `XMEM_2MB_CLUSTERS` and mapping into `MEM_2MB_PAGES` reservations are not implemented: they log `BX_STUB_LOG` and fail with `ERROR_NOT_SUPPORTED`. Other flag bits fail with `ERROR_INVALID_PARAMETER`.
|
||||
- **Mapping:** `XMemVirtualAlloc(MEM_RESERVE | MEM_64K_PAGES, XMEM_MAPPABLE)` reserves a placeholder, and `XMemMapPhysicalPages` maps into it. It replaces pages already mapped there, a NULL page array unmaps, and an unmapped range stays reserved and can be mapped again. Scatter checks every entry before changing any, and a 0 tag unmaps its slot. Mapping outside a mappable reservation is refused. A NULL address remains a BetterXen extension for synthetic fixtures: the shim picks the span, and unmapping it frees it.
|
||||
- **Title-managed placeholders:**
|
||||
- `XMemVirtualAlloc(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)` reserves a placeholder the title splits itself with `VirtualFree(MEM_PRESERVE_PLACEHOLDER)`.
|
||||
- `MEM_REPLACE_PLACEHOLDER` with `XMEM_MAPPABLE` turns a split part into a mappable range without a new reservation. It is refused unless the part is still a placeholder.
|
||||
- `XMEM_GRAPHICS_32BIT_ADDRESS` keeps new reservations below 4 GB.
|
||||
- The `PAGE_GRAPHICS_*` protection bits set a GPU view the host does not have, so mapped views use the low-byte CPU protection.
|
||||
- Replacing a placeholder with committed memory is not implemented and logs `BX_STUB_LOG`.
|
||||
- A project-authorized target build lays out its descriptor memory this way.
|
||||
- **Tests:** `test_xmem_physical` is rewritten against the documented contracts, with constants written out from the documentation, and fails against the previous `xmem.dll`. `test_xmem`, `test_xmem_external_charge`, `test_d3d12_placed`, `test_d3d12_vmem_xbox`, `test_m2_first_frame` and `test_integration_boot` use the documented signatures.
|
||||
- **Not covered:** `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` still differ from their documented signatures (#642).
|
||||
- A recognized BetterXen `BXVM` configuration is validated before an unwritable output can trigger the logged fallback. Invalid sizes still return `E_INVALIDARG` on read-only pages.
|
||||
- `d3d12_xs.dll!D3D12XboxCreateDevice` takes the documented four parameters `(pAdapter, pParameters, riid, ppDevice)`. Before, it took three `(params, riid, ppv)`, so a title calling it as documented had its interface ID treated as the out pointer, and the shim wrote through it. On a project-authorized target build that faulted on a write into read-only data. Source: the authorized GDK documentation of the function and of `D3D12XBOX_CREATE_DEVICE_PARAMETERS`. A NULL parameter block now fails with `E_INVALIDARG`, as documented. A non-NULL adapter is logged and the default host adapter is used, which is an inference, since BetterXen has no adapter objects. Of the parameter block only `Version` is read and logged. All fixtures that create a device pass a zeroed 80-byte parameter block. `test_d3d12_xs` checks the NULL-parameter refusal and that it clears the out pointer.
|
||||
- The docs anchor audit now slugs a heading's **rendered** text, so an inline link contributes only its link text instead of its text plus its URL (#632). `markdown_slugs()` ran on the raw source, so `## Setup [guide](other.md) notes` produced `setup-guideothermd-notes` where GitHub renders `#setup-guide-notes`; the same applied to `README.md:53`, whose anchor is `#active-milestone--m2-first-rendered-frame--shader-format-gate` but slugged with the milestone URL appended. Nothing linked to those anchors yet, so `main` passed, but the first link written exactly as GitHub displays it would have been reported as a broken fragment.
|
||||
- Inline links are now replaced with their text before slugging (the `(?<!\!)` guard leaves images alone). Link syntax inside a **code span** still counts literally, as GitHub renders it, so code spans are set aside before the substitution and restored afterwards; without that, a heading whose code span contains link syntax lost the URL where GitHub keeps it (the observed anchors were `code-x-span` and `code-xy-span` respectively). Every rule here was checked against GitHub's own renderer via its Markdown API, and the new unit tests fail on the previous implementation. Evidence class D.
|
||||
- `xg_xs.dll`'s `SW_64KB_S` copy path now bounds each offset by the buffer that offset belongs to. `CopyFromSubresource` passes the caller's linear image as `resource` and the tiled resource as `image`, so the old check compared the image offset against the *tiled* size and the tile offset against the *image* size; with a caller row pitch wider than the tight row, a short destination passed and the copy wrote past it (AddressSanitizer: 4-byte heap-buffer-overflow on a 2x2 RGBA8 readback with a 1000-byte pitch into a 1004-byte buffer that needed 1008). The bounds now follow the direction (`to_resource`), and `test_xg_xs` gains a short-readback case that must return `E_INVALIDARG` and leave its canary intact. `CopyIntoSubresource` was not affected.
|
||||
- Also corrected two stated reasons: the RB+ table choice is inert for `SW_64KB_S` (`GFX10_SW_64K_S_PATINFO` and `GFX10_SW_64K_S_RBPLUS_PATINFO` select the same nibble indices at every element size, so the comment no longer claims they differ for this mode), and a non-zero depth pitch is now required to cover one slice at the caller's row pitch (`blocks_h * row_pitch`), not the tight row — the old bound accepted a pitch smaller than a slice.
|
||||
- `test_xg_xs.exe` `test_sw64kb_s_round_trip` sized the `R8G8B8A8_UNORM` texture with the BC block dimension (`tile_bx * 4`, `tile_by * 4`), requesting a 512×512 texture (16 tiles, 1 MiB) while passing a 64 KiB resource. `CopyIntoSubresource` correctly returned `E_INVALIDARG`, cascading into the offset and byte-identity checks. The fixture now scales by the format's actual block dimension: 1 for `R8G8B8A8_UNORM`, 4 for BC1/BC7. BC1 and BC7 dimensions are unchanged.
|
||||
- `xg_xs.dll` computes `SW_64KB_S` tile addressing for `TEXTURE2D`, one array slice and one mip, over the element sizes AMD's public AddrLib RB+ tables specify: 32-bpp `R8G8B8A8_*` (4-byte elements) and the **BC family** — BC1/BC4 with 8-byte blocks and BC2/BC3/BC5/BC6H/BC7 with 16-byte blocks, where one "texel" element is a 4x4 block and `elemLog2 = log2(block_bytes)` (#505). `GetTexelElementOffsetBytes` returns a real byte offset for all of them instead of `E_NOTIMPL`: `pdep(x, x_mask) | pdep(y, y_mask)` over **block** indices, with per-element-size masks expanded by hand from `GFX10_SW_PATTERN_NIBBLE01/2/3` at the `GFX10_SW_64K_S_RBPLUS_PATINFO` indices (AddrLib, MIT, public in Mesa and AMD PAL). At 32 bpp the x mask `0xAA8C` equals Microsoft's public `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE` `xBytesMask` `0xAA8F` with the two intra-texel byte bits cleared, and the y mask matches `0x5570` exactly — two independent public sources agreeing, which is why S is the mode implemented. The 8-byte (`0xAAC8`/`0x5530`, 128x64-block tile) and 16-byte (`0xAAC0`/`0x5530`, 64x64-block tile) rows are AddrLib-only. All three mappings were checked to be bijections over the 64 KiB tile (16384 / 8192 / 4096 distinct, block-aligned offsets) against an independently written pdep reference. `GetResourceBaseAlignmentBytes` reports the 64 KiB tile alignment, and `CopyIntoSubresource`/`CopyFromSubresource` move blocks in swizzle order. `test_xg_xs.exe` re-derives its expected offsets from those masks rather than from the shim: per-format block sizes (8 vs 16 bytes), intra-block offsets (the 16 texels of a BC block share one byte offset), independently derived absolute offsets, and an offset -> texel -> offset round trip. It keeps asserting `E_NOTIMPL` for what is still unimplemented.
|
||||
- **Still `E_NOTIMPL`, deliberately:** `SW_64KB_D` (it differs from S at 32 bpp - the masks swap address bits 6 and 7), `SW_64KB_R` (no public GFX10 form: Mesa marks `ADDR_SW_64KB_R` Reserved, and the render-target mode `ADDR_SW_64KB_R_X` XORs on a pipe/packer configuration that is not public), TEXTURE1D/3D, MSAA, and every multi-mip or multi-slice case, because the mip tail is adapter-specific by Microsoft's own wording. `XGSuggestSwizzleMode` still returns the linear mode.
|
||||
- **Caveat:** BetterXen's `BX_XG_LAYOUT_*` values 1/2/3 are local constants, not the real `XG_SWIZZLE_MODE` values, which are NDA.
|
||||
- **Not run:** live CrossOver execution; cross-compiled and export-verified only. Synthetic evidence; no Xbox-hardware claim.
|
||||
- `d3d12_xs.dll` now **refuses** a shader stage whose wave is wider than 32 lanes, instead of creating a pipeline D3DMetal will not run (#591). `#453` measured that a `[WaveSize(64)]` PSO is created and then silently produces nothing: every output word keeps its sentinel. The gate detected it (`known_d3dmetal_gap`) but only logged `shader_d3dmetal_gap` and returned `S_OK`, so a caller saw success and drew nothing. Such a stage now returns `E_NOTIMPL` with `*ppv == nullptr`, logs `decision=reject_wave_wide` on the `shader_gate` record and keeps the `shader_d3dmetal_gap` record.
|
||||
- **Stance: refuse, not lower.** Lowering 64 lanes to 32 is a semantic transform — reductions, lane indices, 64-bit lane masks, cross-half permutes and group barriers all change meaning — and cross-lane agreement has no general solution without knowing the kernel. Lowering is M3 work; this change converts a silent no-op into a caller-visible error in the meantime.
|
||||
- **Scope:** the wave-width predicate is separated from `known_d3dmetal_gap`, so 64-bit atomics remain warn-only until their detection is complete (#589). `abi/` unchanged; `d3d12_xs.dll` still exports 4. `test_shader_gate` now asserts the refusal and the `reject_wave_wide` record; it previously only printed `hr` for the wave64 PSO. **`test_shader_gate.exe` was not executed** — no CrossOver on this host; the fixture was cross-compiled warning-free.
|
||||
- `bx-cli trace` now also groups the `shader_d3dmetal_gap` records by `(pso, stage)` (#590), reporting each group's count together with its `wave_lanes_min` and `atomic64_flags`, in deterministic first-seen order, so a run says which pipeline **kind and stage** are created-but-not-run. `pso=` is the pipeline kind the gate passes in (`graphics` or `compute`), not a per-pipeline identity: the emitter only ever writes those two literals, so `(pso, stage)` has at most six values and 40 affected compute pipelines collapse into `40x pso=compute stage=CS` (review on #593). The distinct `(wave_lanes_min, atomic64_flags)` variants separate them only where their constraints differ. The #496 per-record list and every existing summary line are unchanged; the grouped view is additive. A record with a missing or empty `pso`, `stage`, `wave_lanes_min` or `atomic64_flags` is grouped under `unknown` and counted (`gaps w/o pso/stage`, `gaps w/o constraints`) rather than dropped or guessed. The summary only reflects records a run wrote; it adds no live run, and no live CrossOver run was performed for this change.
|
||||
- `GameInput.dll` now implements `IGameInput::CreateDispatcher` (v0 slot 14) and a new `IGameInputDispatcher` object (`IUnknown` + `Dispatch` + `OpenWaitHandle`) (#500). `CreateDispatcher` returns `E_POINTER` for a null out-pointer and `S_OK` with a fresh reference-counted dispatcher otherwise, without changing the `IGameInput` singleton's own refcount. `OpenWaitHandle` returns a new manual-reset event per call (caller `CloseHandle`s it); `Dispatch` returns `false` for every quota including 0, because this shim has no real background input work, so the documented "flush at least one item even at quota 0" shape is honoured trivially — no real work is scheduled. `QueryInterface` serves only `IID_IUnknown`: the v0 dispatcher IID is not published in the public Microsoft Learn / GDK documentation, so no GUID was invented; any other queried id is logged (`qi_unsupported`) and answered `E_NOINTERFACE`. A live dispatcher reference count on the singleton logs `dispatch_mode` (`mode=manual` / `mode=automatic`) on each transition, matching the documented manual/automatic-dispatch lifetime rule. `test_audio_input.exe` now exercises slot 14: null-out errors, `QueryInterface`/`AddRef`/`Release` counting, `Dispatch` return values, `OpenWaitHandle` success + `CloseHandle`, `Release` returning 0 on the last reference (the test confirms the count, not the deallocation itself). The returned wait handle is created non-signaled and this shim never signals it, because there is no background input work to make it ready, so a caller that waits `INFINITE` blocks; poll with a timeout or call `Dispatch` instead. `GameInput.dll` still exports exactly `GameInputCreate @1`. Cross-compiled and export-verified only; the EXE was not run under CrossOver on this host.
|
||||
- `bx-probe`'s PE32+ parser is hardened and now has real coverage (#507). `rva_to_off` computed `s.raw_ptr + delta` as a `u32` add, which wraps on a crafted image (e.g. `0xFFFFFFF0 + 0x20` → `0x10`, a byte offset near the start of the file instead of ~4 GiB). It now uses a checked 64-bit-safe add and returns `None` on overflow. `Vec::with_capacity(section_count)` allocated from an unvalidated `u16` before the section table was bounds-checked; the table is now validated to fit first. `u32_le(...).unwrap_or(0)` on the import data-directory read treated a truncated directory as "no imports", indistinguishable from a genuine zero; it is now a real error. The import descriptor walk is bounded by the image size and by a checked `desc_off` increment, so a malformed table cannot run past the end.
|
||||
- **Tests:** 9 new unit tests built from synthetic byte buffers (no real DLLs, no network): a minimal valid PE32+, a two-DLL import table (one by name, one by ordinal), truncation at every header boundary, a section whose `raw_ptr` would wrap, `section_count` larger than the file, a PE32 (0x010B) image, and an import directory outside all sections. `rejects_section_rva_mapping_that_would_wrap_u32` was confirmed to **fail** when the `u32` add is re-introduced and to pass with the fix. `PeSummary` now derives `PartialEq`/`Eq` for the assertions.
|
||||
- **Compatibility:** every public signature in `PeSummary`, `ProbeError`, `probe_pe32_plus` and `classify_dll` is unchanged for `bx-cli`; `cargo test --locked --workspace` (including `bx-cli`) passes.
|
||||
- **Import data-directory bounds:** the import entry (data-directory index 1, an RVA/size pair) is now validated before it is read: its index must be `< NumberOfRvaAndSizes` AND its 8 bytes must lie within `SizeOfOptionalHeader`, so a short optional header can no longer make the RVA/size read bytes from the section table. The 20-byte `IMAGE_IMPORT_DESCRIPTOR` walk is bounded by BOTH the declared directory `Size` AND the containing section's raw bytes, whichever ends first, stopping at a null terminator or when the next descriptor would exceed the directory. New synthetic regressions: a short `SizeOfOptionalHeader` that puts the import entry out of range, `NumberOfRvaAndSizes == 1`, and a directory `Size` shorter than the section so descriptors past the declared size are not reported.
|
||||
- `XTaskQueueSubmitDelayedCallback` now **honours a non-zero delay** instead of logging a stub and submitting immediately (#515). `core_tq_submit_delayed` in `shims/xgameruntime/com_dispatch.cpp` discarded `delay_ms` and fell through to `XTaskQueueSubmitCallback`, which has no delay parameter, so the callback ran on the next dispatch and the call still returned `S_OK` — a caller scheduling a backoff or deferred teardown was told the delay succeeded when it had not happened.
|
||||
- **What changed:** each queued task carries a `GetTickCount64` deadline (`Task::due_ms`, zero meaning due now). `XTaskQueueSubmitDelayedCallback` sets it; `XTaskQueueSubmitCallback` forwards with `delay_ms == 0`, so the common immediate path is unchanged. Dispatch gates on the deadline: a delayed head holds FIFO order until it is due, and `XTaskQueueDispatch` waits exactly until that deadline (or the caller's timeout) rather than spinning.
|
||||
- **Log:** the record now names the consequence — `queued delay_ms=N` — instead of the old `(nonzero_delay)` text, which named only the symbol. It is emitted at `INFO` rather than as a stub warning, since the delay is now implemented.
|
||||
- **Underflow guard:** the wait computes `due_ms - now`, and the deadline can pass between the due check and the clock read; the subtraction is saturating, because an unsigned wrap there would block for ~584 million years.
|
||||
- **Infinite-sleep clamp:** `delay_ms` is a `uint32_t`, so `0xFFFFFFFF` is a valid delay (~49.7 days), and a remainder of exactly `0xFFFFFFFF` used to be passed to Win32 `Sleep`, where `INFINITE` means "wait forever": the loop never woke to re-check the deadline, so the callback never ran on the lanes that sleep out the remainder themselves. The chunk calculation is now the `finite_sleep_chunk_ms` helper in `shims/xgameruntime/task_queue.h`, which clamps every chunk to at most `INFINITE - 1` (`0xFFFFFFFE`) and is always positive. The test asserts the clamp for a `0xFFFFFFFF` remainder without waiting 49 days, and that a `0xFFFFFFFF` delay is still accepted and its callback fires on both the `parallel` and manual lanes.
|
||||
- **Every lane, not just `dispatch()`:** the gating had to cover the gateways that do not go through `XTaskQueueDispatch` at all — the `parallel`/`serialized` threadpool worker (which popped and ran a delayed head as soon as it was pushed), `immediate` mode, and a closed manual lane (which runs pending work on the submitting thread). All four now wait out the deadline, so a delayed callback cannot fire early on any path.
|
||||
- **Test:** `test_xgameruntime.exe` reaches slot 19 through `QueryApiImpl`'s `IXGameRuntimeCore` COM object (it is not an export). Covered: `delay_ms == 0` still runs on the next dispatch; a 100 ms delay does not run at ~0 ms nor after a 10 ms sleep, and does after 250 ms; the callback receives its context and a `cancelled == false` flag, checked with a canary in the caller's record; a dispatch `timeout` shorter than the deadline returns "nothing ran" and ends on the timeout rather than the deadline; a delayed head holds FIFO so a later immediate task cannot overtake it; closing a manual lane with a 60 s delayed task pending runs it as a **cancel**, not a normal run; and the **pool path** — a `parallel` work lane — does not run a 100 ms delayed task during the first 10 ms. Margins are 10 ms early / 250 ms late against a 100 ms deadline, deliberately wide so a slow host is not flaky.
|
||||
- **ABI:** `abi/defs/xgameruntime.def` unchanged (49 exports); the delayed entry point is a COM slot, not a new export.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `tests/conformance/test_d3d12_xs` now checks the padded `BxBeyondPublicVtableNN` slots that `gen_proxy.py` (`PAD_SLOTS = 32`) appends after each generated `d3d12_xs` proxy vtable (#547), so a caller indexing past the interface it was handed lands on a logged `E_NOTIMPL` stub instead of unrelated memory — the guard for exactly the console-only-method case. Before this, `grep -n 'E_NOTIMPL\|beyond_public\|pad' tests/conformance/test_d3d12_xs/main.cpp` returned **nothing**, so the `E_NOTIMPL` return, the log record, and the **presence** of the 32 slots were all unverified; the generator could have stopped emitting them and no test would have noticed. Indices are derived from the generated code, not guessed: `ID3D12Device10` **79**, `ID3D12CommandQueue` **19**, `ID3D12CommandAllocator` **9**, `ID3D12GraphicsCommandList7` **81**, cross-checked by parsing `proxy_generated.cpp` for the `BX_VTABLE_STUB_LOG("<leaf>", N u, "beyond_public_vtable")` calls (all four have exactly **32**). Coverage is boundary-only: for each of the four proxies the fixture calls just the **first** (`BxBeyondPublicVtable00`) and **last** (`BxBeyondPublicVtable31`) padded slot — 8 calls in total, not all 128 — and requires `E_NOTIMPL` without a crash, plus a `BX_LOG_FILE` `unimpl_vtable` record naming the slot and `beyond_public_vtable` (the log check `skip`s when `BX_LOG_FILE` is unset, matching the fixture's existing behaviour). `abi/` and `gen_proxy.py` unchanged. **`test_d3d12_xs.exe` was not executed** — no CrossOver on the authoring host.
|
||||
- `test_d3d12_placed` now captures the host identity associated with the cached backing heap before its final same-host check. It previously compared device B with a later, unrelated proxy's host log entry; all 147 checks remain intact.
|
||||
- `bx-d3dmetal-harness` no longer panics on an overflowing `--timeout` (#586). `runner.rs` computed `Instant::now() + timeout`, and `Add<Duration> for Instant` panics on overflow, so a user-supplied value like `9223372036854775807` aborted the harness with exit 101 and a Rust backtrace instead of one of its documented verdict codes. The deadline is now `Option<Instant>`: when `checked_add` cannot represent the requested timeout, the probe runs without one. The first version of this fix substituted `Duration::from_secs(1 << 62)`, which is itself beyond the monotonic clock's range on common targets, so its `expect` panicked with the same exit 101 (review on #587). `main.rs` still rejects 0. New test `an_overflowing_timeout_does_not_panic` runs a probe with `Duration::from_secs(u64::MAX)`; it panics on the previous implementation and passes now. `cargo fmt/clippy/test` pass (23/23 harness unit tests). No ABI or export change; no live D3DMetal run was needed.
|
||||
- `bx-cli` system32 staging now rolls a published shim back when the `.bx-staged` manifest write fails, so the next run does not refuse bx-cli's own file as foreign (#573). The publish happened before the manifest write and the error path discarded only temporary files, leaving a regular file in `system32` with no manifest entry; the next run then reported `already exists and was not staged by bx-cli (or was changed since)` and only manual deletion unblocked it. A `Copied` file is now removed and a replaced one restored **from a snapshot taken before the rename**, with the manifest left exactly as it was. The first version of this fix read `dst` *after* the rename, so it restored the bytes it had just written; `a_manifest_write_failure_restores_the_previous_bytes` now proves the old bytes come back (it fails on that version). New unit test `a_manifest_write_failure_leaves_no_unowned_file` pre-creates `system32/.bx-staged.<pid>.bx-staging` as a directory; it fails on the previous implementation and passes now. This restores the invariant `stage.rs` and the changelog already claimed.
|
||||
- Merge eligibility rules in `AGENTS.md` §7 and `CONTRIBUTING.md`: a PR's original author does not merge it, other maintainers may push fixes and still merge, and substantive changes need approval from someone who did not write them. The `Protect main` ruleset no longer requires approval of the most recent push from someone other than the pusher; every changing push still dismisses approvals. A new `Merge policy audit` workflow fails after an author self-merge; it detects but cannot prevent one.
|
||||
- `XCRDAPI.dll!DStorageGetFactory` now also dispatches the Xbox Series DirectStorage COM interfaces (`IDStorageFactoryX`, `IDStorageFileX`, `IDStorageStatusArrayX`, and `IDStorageQueueX`) over the existing batched `WorkQueue`/`StorageFile`/`StatusArray` engine while preserving the public PC DirectStorage interfaces and synthetic `bx::storage` interfaces. The IIDs, vtable slot orders and request layout are inferences from call-site observation of a project-authorized target build, not a public contract, and their provenance is pending maintainer review. Compressed requests return `E_NOTIMPL`. Unimplemented vtable slots log through `BX_VTABLE_STUB_LOG`. `IDStorageQueueX::RetrieveErrorRecord` is a logged stub and leaves the caller's buffer untouched until the Xbox output layout and size are verified. The PC queue's record behavior is unchanged. Added synthetic conformance coverage in `tests/conformance/test_xcrdapi_xbox/`, including the buffer canary and queue error diagnostics. `IDStorageFactoryX::SetStagingBufferSize` returns `S_OK` and logs that the size has no effect, like the public factory, and `CreateQueueX` ignores the queue priority on purpose, because the Xbox priority range is not part of the inferred contract. `test_xcrdapi_xbox` requires `BX_LOG_FILE` and reads only the records its own run appended. It also covers a memory request on a file queue (`E_DSTORAGE_INVALID_SOURCE_TYPE`), a source/destination size mismatch (`E_DSTORAGE_INVALID_DESTINATION_SIZE`), an out-of-range status index (`E_DSTORAGE_INDEX_BOUND`), a null memory source (`E_INVALIDARG`) and a request enqueued after `Close` (dropped and logged).
|
||||
- `XCRDAPI.dll!DStorageGetFactory` serves the public PC DirectStorage interfaces from Microsoft's MIT-licensed `dstorage.h` (SDK 1.4.0, vendored unmodified in `shims/xcrdapi/dstorage/`) over the existing queue engine: `IDStorageFactory`/`IDStorageFactory1`, `IDStorageFile`, `IDStorageQueue`…`IDStorageQueue4` and `IDStorageStatusArray` (#483). An unknown IID is logged with its value (`dstorage_get_factory_unknown_iid`) next to `BX_STUB_LOG`, so `bx-cli trace` names the interface a guest asked for. The synthetic `bx::storage` interfaces are unchanged. MinGW ignores the header's `__declspec(uuid)`, so `shims/xcrdapi/dstorage_mingw.h` restates its IIDs, generated from the header; the test checks `IDStorageFactory`'s IID against an independently typed value.
|
||||
- **Behaviour, from the header's documentation:** queue capacity 128–8192 (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`) with capacity − 1 usable slots, priority and source type checked at creation, automatic submission at half capacity, a full queue makes `EnqueueRequest` wait for a slot, status entries scoped to the requests since the previous one, and `IsComplete == (GetHResult != E_PENDING)`. The `void` enqueue methods report a rejected command in queue order: a rejected request feeds the next status entry, and every rejection reaches the error event and `RetrieveErrorRecord` (`FailureCount`, `FirstFailure.HResult`, `FirstFailure.CommandType`; per-command parameters stay zeroed).
|
||||
- **Supported:** uncompressed file or memory sources into memory or buffer destinations. A buffer destination needs a queue device.
|
||||
- **Not implemented, logged with `BX_VTABLE_STUB_LOG`:** GDeflate, Zstandard and custom compression (`E_NOTIMPL`; `GetCompressionSupport` reports none), GACL shuffle transforms, texture, subresource and tile destinations, fence-synchronized `EnqueueRequests`, `CancelRequestsWithTag` (requests still run) and the debug layer. `SetStagingBufferSize` returns `S_OK` and logs that it has no effect. `Close` drains what was already submitted.
|
||||
- **Not included:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source. Provenance is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **Not from this header:** the Xbox `IDStorage*X` interfaces, whose IIDs have no licence-compatible public source; they are served separately, from target-build observation (see the `IDStorage*X` entry above). Provenance of the vendored header is recorded in the upstream registry, the reuse matrix and `THIRD_PARTY_NOTICES.md`.
|
||||
- **Test:** `test_xcrdapi` gains public-interface checks whose expected values come from the header and `dstorageerr.h`: factory IIDs and identity, capacity and priority limits, `Query`/`Query1` counts, file and memory reads, rejection ordering and error records, unsupported shapes, auto-submission without `Submit`, 384 requests through a 127-slot queue, `Close`, and a memory-to-upload-buffer copy on a D3D12 device.
|
||||
- `bx-d3dmetal-harness` now judges the reported shader model: `judge()` requires `shader_model >= 0x66` for `Verdict::Pass` (#567). The field was parsed and printed but never judged, so a device below 6.6 — or a report with no `shader_model` record — passed on a matching readback alone, even though every kernel the harness runs is SM 6.6. A lower model returns the new `Verdict::UnsupportedShaderModel`; a missing record returns `Incomplete`. The live Rust test asserted this, but the standalone `bx-d3dmetal-harness run` verdict did not. Negative unit tests with `0x65`, `0x60`, and the record removed fail on the previous implementation. The live D3DMetal test remains `#[ignore]`d (no user-supplied framework on this host); 23/23 harness unit tests pass.
|
||||
- `bx-cli`'s `cleanup_runs_outside_the_callers_process_group` test now observes the fake `wineserver`'s PGID with macOS's bundled Perl and its built-in `getpgrp` instead of `/bin/ps` (#558). `/bin/ps -o pgid= -p $$` returns `Operation not permitted` on restricted macOS hosts, making the fake server exit 126 and failing an otherwise unrelated supervision test. The test still records one PGID for each `-k` and `-w` invocation and asserts both differ from the caller's group. Test-only change; no supervision behavior changed.
|
||||
- `AcpHal.dll` now rejects `ApuCreateHeap(0, 0)` with `E_INVALIDARG` (#580). The call previously reported `S_OK` and set `heap_created = true` with `capacity == 0`, representing a heap that could never satisfy an allocation; `ApuAlloc` still rejected requests with `E_OUTOFMEMORY`. `ERROR_BUSY` is still returned first when allocations are live, so the existing busy-path assertion is unchanged. `test_audio_input` now asserts the zero-capacity call is rejected and that `ApuAlloc` still fails with `E_OUTOFMEMORY` before a real heap is created. `abi/` unchanged (9 exports). **`test_audio_input.exe` was not executed** — no CrossOver on this host.
|
||||
- `docs/claims.toml` now defines evidence classes A, B, D, E and U in a legend derived from their existing claims and prose usages (#549). `docs/README.md` now lists the complete vocabulary and describes the file as a claim ledger. No claim's class was changed. The legend records that the in-tree `AGENTS.md` §5 refers to `claims.toml` and does not contain the longer vocabulary named in the issue. Class E explicitly covers both public tool/format documentation and observed tool behavior, with the claim's `test` field distinguishing documentation review from execution; `CLAIM-DXCONTAINER-PAYLOAD` and `CLAIM-LLVM-GFX1030` are documentation-only examples and are not reclassified here.
|
||||
- Documented the conformance exit-status contract: `bx-cli run` returns the guest's status unchanged, and fixtures that cannot reach a conclusion exit **77** with a `SKIP: <reason>` line (#563). `tests/conformance/README.md` now gives a `case` recipe that records PASS / UNAVAILABLE / FAIL separately, so a skip is never counted as a pass (AGENTS.md §5). `docs/research/d3dmetal-gpu-limits.md` states the fixture's 0/1/77 outcomes and links the recipe. Documentation only; no fixture or runner behaviour changed.
|
||||
- `bx-cli run` now propagates the guest's numeric exit code instead of collapsing every nonzero status to 1 (#565). `Outcome::exit_code` returned `u8::from(!status.success())`, so a conformance fixture's documented **exit 77** skip (see #563) arrived as 1 and was indistinguishable from a failure; a `case $status in 77)` recorder could never fire. Timeout (124) and signal (128+N) codes are unchanged, a failed cleanup or misplaced staging still turns success into failure with `code.max(1)`, and a signalled guest still has no code. `classifies_exit_timeout_and_signal` now asserts 7 for `exit 7` and 77 for `exit 77`; it previously asserted 1 for `exit 7`, which is why the collapse was invisible. No CrossOver run was needed for the tests that ran; live `bx-cli run` under CrossOver was not performed on this host.
|
||||
- ADR 0005 now points at `docs/progress.md` **at tag `native-first-final`** rather than a bare path that no longer exists on `main` (#569). The file was deleted with the native workspace (`30e551a`) and survives only at that tag, which ADR 0006 makes the canonical archive. The ADR's meaning is unchanged: no hybrid capability is claimed, and every listed item remains synthetic evidence. `docs_hygiene.py` cannot catch this class of error because it validates Markdown links only, and this reference is inline code.
|
||||
- `scripts/audit/docs_hygiene.py` now detects the **diff3** conflict marker `||||||| merged common ancestors` (#583). `MARKER` matched `<<<<<<<`, `=======` and `>>>>>>>` only, so a `git merge --diff3` conflict resolved down to just its base line passed the Repository hygiene gate. Added `MarkerTests` (all four markers, a full diff3 block, and negative controls for table/prose lines) and `WorkflowTests` (valid and invalid YAML, using temporary fixtures). `.github/workflows/hygiene.yml` now runs `python3 -m unittest scripts/audit/test_docs_hygiene.py` as a CI step, so the suite is gated rather than advisory. Fault injection: removing the `\|{7}` alternative makes 3 of the 25 tests fail; with it, all 25 pass. `python3 scripts/audit/docs_hygiene.py --require-yaml` reports 199 tracked files, 0 problems. **Stacked on PR #538**, which creates `test_docs_hygiene.py`.
|
||||
- `tests/conformance/test_veh_clwb` now verifies the `clwb` decoded instruction length (`len=`) that `bx_runtime_veh.dll` logs and uses to advance RIP (#539). The fixture reads `BX_LOG_FILE` (it fails with a clear message when `BX_LOG_FILE` is unset: the EXE imports `bx_runtime_veh.dll`, which reads the variable in `DLL_PROCESS_ATTACH`, so a temp log set in `main` would never be written) and asserts the `len=` values on the sampled `clwb_trapped` records. `log_sampled_trap` logs only traps 1, 2, 4, 8, …, so six `clwb` forms produce exactly three records (`total_traps=1, 2, 4`); the assertions cover **only those sampled records** — `total_traps=1` → `clwb (%rax)` → len 4, `total_traps=2` → `clwb 0x40(%rax)` → len 5, `total_traps=4` → `clwb (%r8)` → len 5 — plus a `len >= 4` floor on every observed record. Forms 3, 5, 6 (`clwb 0x100(%rax)`, `clwb 0x40(%rax,%rcx,4)`, `clwb 0x0(%rip)`) are **not** covered by a `len=` assertion. Expected lengths were re-derived by assembling with `x86_64-w64-mingw32-as` and disassembling with `x86_64-w64-mingw32-objdump -d`. The existing `delta == 6` trap-count check is unchanged. `test_veh_clwb.exe` passes live on CrossOver 26.3 under `bx-cli run --log` (records `len=4` and `len=5`), and fails with a clear message when `BX_LOG_FILE` is unset. Record fields are parsed with a checked `strtoull`, so a malformed record cannot throw past the failure message.
|
||||
- `AcpHalAllocateShapeContexts` and `AcpHalReleaseShapeContexts` no longer return a bare `S_OK` for work they did not do (#509). They logged a stub and reported success while ignoring their arguments: `Allocate` discarded its only parameter (unnamed) and `Release` takes no parameter at all, so neither could be held to anything. Both now return `E_NOTIMPL` and keep their `BX_STUB_LOG` record, so `bx-cli trace` still surfaces the call and a caller is told to fall back rather than being told the work happened.
|
||||
- **NDA constraint:** the public Microsoft Learn page for `AcpHal` returns HTTP 200 with only the membership gate, so the true signatures and the shape-context layout are **unknown** from public sources, including whether `Release` should take an argument. `E_NOTIMPL` is therefore BetterXen's choice, not the console's; no signature was invented and `abi/defs/AcpHal.def` is unchanged (9 exports).
|
||||
- **Tests:** `test_audio_input.exe` calls both through the DLL: null and sentinel pointers must not crash and must return `E_NOTIMPL`; calling `Release` twice must also return `E_NOTIMPL` (idempotent); and when `BX_LOG_FILE` is set it asserts both symbols still appear on `unimpl_api` lines, printing an explicit `SKIP` rather than a pass when the variable is unset.
|
||||
- `test_win32_bridge.exe` now asserts that the PSM **context pointer round-trips** through the JSONL (#519). #514 stored `(token, callback, context)` and logs `context=0x%llx`, so the context is observable — but the test only counted `callback_unfired` records, so a dropped (`context=0x0`), swapped or mis-tagged context would have passed unnoticed, leaving the storage decorative. The context field is parsed from the value after `context=`. The original version of this check parsed from the key, read the hex digit `c` and got `0xc` for every record, so it could never pass.
|
||||
- **What is checked:** every logged `context=` on **both** families must be non-zero and present in the set of `&entry` pointers the test actually passed; at least **two distinct** pointers must appear per family, so one registration cannot overwrite another's; and each family's set must cover the whole `&entry` set, which is what catches a swap or mis-tag between families. A record with a missing or malformed `context=` fails.
|
||||
- **Limit, stated rather than asserted:** the shim's unregister records carry only a detail string (`unregistered` / `foreign_token` / `unknown_token`), so **context-drop on unregister is not observable** in the log. The test documents that and prints a note if a future shim starts logging context there.
|
||||
- **Base:** this sits on #514, which introduces the `context=` field; it rebases cleanly once that merges.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `win32_bridge`'s PSM notifications now **store** the callback and context they accept, and **say** that they never fire it (#513). `register_notification` in `shims/win32_bridge/psm_appnotify.cpp` validated `callback` for null and then dropped it: nothing stored it, nothing ever invoked it, and the context pointer was discarded as `PVOID /*context*/`. So `ERROR_SUCCESS` meant "token allocated", not "you will be notified", and neither the code nor the log said so.
|
||||
- **What changed:** each registration now keeps a `(token, callback, context)` record in the process-heap-backed open-addressed table under the existing `SRWLOCK`; it starts at 64 slots and grows as needed, with allocation failure reported as `ERROR_NOT_ENOUGH_MEMORY`. The exported wrappers thread `context` through instead of discarding it; unregistering drops the record so no later event can reach a retired registration.
|
||||
- **Honesty:** a comment on `register_notification` and the JSONL detail (now `registered_offline callback_unfired`) both state that the callbacks are accepted and currently **never invoked**, because this shim has no source of app-state or constrained-change events and the console firing contract is not publicly documented. **No firing policy was invented** — the callback is deliberately left unfired rather than called spuriously to look implemented.
|
||||
- **Test:** `test_win32_bridge.exe` now also asserts that no callback fires, and that every registration's log detail carries `callback_unfired` (state and constrained counted separately). The existing per-event JSONL counts still pass unchanged, since the detail grep is a substring match.
|
||||
- **ABI:** `abi/defs/api-ms-win-core-psm-appnotify-l1-1-0.def` and `-l1-1-1.def` unchanged (2 exports each); all six API-set DLLs keep their original export counts.
|
||||
- **Not run:** live CrossOver execution. The fixture compiles and links; its runtime pass still needs a CrossOver host. Synthetic evidence only.
|
||||
- `dxbc-accc` now exposes a **bounds-checked chunk-lookup API** on `ShaderInspection` (#521). `chunk_payload(&container, &fourcc)` returns the payload of the first chunk tagged `fourcc`, and `has_chunk_tag(&fourcc)` answers presence **without** trusting the declared size. Both **reuse the already-parsed `chunks` vector** rather than re-walking the raw table; `chunk_payload` rejects offsets inside the DXBC header/offset table and validates `offset + 8 + size` against **both** `container_size` and `container.len()` with checked arithmetic, returning `None` instead of panicking.
|
||||
- **Why:** `dxbc-accc` already parsed the table into `ChunkInfo { fourcc, offset, size }` but exposed **no public lookup**, so `shims/d3d12_xs/shader_gate.cpp:94` re-implements the same bounds-checked walk in C++ (`find_chunk`), plus a second variant `has_chunk_tag` that ignores the declared size. Two parsers for one container is how a fix lands in one and not the other.
|
||||
- **Semantics:** `offset` points at the 8-byte chunk header (fourcc + size), so the payload begins at `offset + 8`. A zero-size chunk yields `Some(&[])` (the header is present and in-bounds); callers needing a minimum size must check the returned length. When several chunks share a FourCC, the **first** in table order wins, matching the C++ `find_chunk`.
|
||||
- **Scope:** the C++ gate is **not** migrated here — `find_chunk`/`has_chunk_tag` in `shader_gate.cpp` stay for now, and the PR names the migration as a follow-up, since it is a larger change needing a live run. `abi/defs/bx_shader_bridge.def` unchanged (3 exports).
|
||||
- **Tests:** 7 new unit tests: `SFI0` and `PSV0` payloads returned exactly; a declared size past the container → `None`; an absent FourCC → `None` and `has_chunk_tag == false`; a zero-size chunk → `Some(&[])`; an exact-fit chunk at the container end (no off-by-one); a truncated container slice → `None`; and duplicate FourCCs → first wins.
|
||||
- `test_shader_gate.exe` now asserts the **shape** of the JSONL it writes, so the `bx-cli trace` fixtures stop resting on a hand reading of `shader_gate.cpp` (#535). It checks, against the log the fixture actually produced: that at least one `shader_gate` and one `shader_d3dmetal_gap` record exist; that every gate record writes `pso=`, `stage=`, `decision=`, `hr=` **in that order**; that an `*_unclassified` record carries **no** `kind=`; that every gap record has `pso=`, `stage=`, `wave_lanes_min=` and the colon that ends its structured part; and that no `key=value` value is split by a space — the assumption `parse_key_values(..., false)` rests on.
|
||||
- **Why shape, not counts:** decision and kind totals vary by GPU, so they are not asserted. What is asserted is the field order and the token boundaries the summarizer depends on, which a hand-typed fixture could get wrong without any test noticing.
|
||||
- **Executed natively, not under CrossOver:** the assertions compile and link, and their logic was checked in a native harness against a sample log — including a **negative control** where an `atomic64=typed, raw` value containing a space correctly trips the check. `test_shader_gate.exe` itself was **not** run here; that still needs a CrossOver host.
|
||||
- Placed resources created via `CreatePlacedResource` retain the shim heap's budget charge until their final release. The D3D12 backing map returned in `cpu_pointer` expires when the region changes or another host device replaces the cache. Concurrent device creations wait for both proxy hooks to be installed (#464).
|
||||
- `D3D12ConfigureVirtualMemoryX` copies a BetterXen version-1 block only when the first 8 bytes are magic `BXVM` (`0x4D565842`) and the struct size. The caller's pointer is not kept. `cpu_pointer` is written only before that call returns (the current persistent map, or 0). After `CreateHeap` builds the backing heap, a second call with the same region reads the map and does not recreate the heap. `CreateHeap` returns that one `WRITE_BACK` / `L0` heap only when the block sets `BX_D3D12_VMEM_FLAG_BACKING_HEAP` and the desc is `CUSTOM`, `WRITE_BACK`, `L0`, `D3D12_HEAP_FLAG_NONE`, alignment 0 or 64 KiB, node masks 0 or 1, and the configured size. Every other `CreateHeap` forwards the desc unchanged and returns the host `HRESULT`, wrapped so the live-heap charge against the xmem title budget is credited on the final `Release` (`E_OUTOFMEMORY` only when that budget is exceeded). The wrapper answers `ID3D12Heap1` when the host heap does. `CreatePlacedResource` on any other heap forwards the placement parameters to the host. On the backing heap the offset must be a multiple of the alignment `GetResourceAllocationInfo` reports and the resource must fit. A null output pointer on `CreateHeap` or `CreatePlacedResource` is forwarded to the host with no budget charge and no wrapper. `GetDevice` on every heap wrapper returns the `BxDeviceProxy`. An ordinary heap `AddRef`s that proxy until the wrapper's final `Release`, matching `BxChildProxy`, so the caller can release the device and keep the heap. The process-wide backing heap does not: the cache would keep the device and its budget charge alive. Its pointer is weak. It is cleared when that heap leaves the cache, including a region change or a different host device, and when the proxy's reference count goes from 1 to 0. A weak `GetDevice` never increments a count that is already zero, and that acquire shares one lock with the 1-to-0 release, so only one thread runs final cleanup. Handing out the cached heap checks the host and the configured size, retargets `GetDevice`, and takes the caller's reference in that same lock. A concurrent backing configuration change makes an in-flight backing request return `HRESULT_FROM_WIN32(ERROR_RETRY)` before it can publish a stale heap. `CreatePlacedResource1` and `CreatePlacedResource2` unwrap the wrapper before calling the host. `test_d3d12_placed.exe` checks aliasing, ordinary heaps, small-resource placement, `ID3D12Heap1`, config lifetime, the write-through pointer, a fence-separated GPU copy in both directions, that an ordinary heap keeps its device alive, that `GetDevice` fails closed after a reconfigure and after a forced host replacement even once the proxy is released, that those newer placement calls accept a wrapped heap, and that a second proxy forced onto the same host device places a resource in the configured region without doubling the charge (#464).
|
||||
- `bx-cli trace` now summarizes the shader-format gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list (wave width and 64-bit-atomic flags), and `shader_bridge_missing`, per [ADR 0008](docs/adr/0008-m2-shader-format-gate.md). It only summarizes records a run wrote; no live CrossOver run was performed for this change.
|
||||
@@ -67,6 +441,11 @@ remains unsupported.
|
||||
- EXTRQ and INSERTQ implement both the immediate and register-control forms, including XMM8–XMM15. The fixture checks the defined low-quadword results with and without REX, including both length-zero forms. It also covers the MONITORX address-size override and asserts the emulated CF result only when CPUID lacks RDPRU.
|
||||
- Each instruction logs sampled `<name>_trapped` events, and `bx-cli trace` prints per-kind lower bounds.
|
||||
- **Local result:** 28/28 synthetic AMD-instruction checks passed on one Apple M5 with macOS 27.2.1, CrossOver 26.3 and Rosetta 2. Trace lower bounds were CLZERO 4, MONITORX 2, MWAITX 2, RDPRU 4, EXTRQ 4 and INSERTQ 4. The CLWB and shim export fixtures passed. The boot fixture reported 19 passed and 2 pending host API-set checkpoints.
|
||||
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
|
||||
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` rejects zero and infinite timeouts with E_INVALIDARG and shares one budget between lock acquisition, fence signaling, event registration and fence waiting (returning `ERROR_TIMEOUT` without signaling if lock acquisition uses the whole budget), and re-entering either call on one thread is refused. `Present` never waits for another thread's call on the swapchain: it returns `BX_PRESENT_E_BUSY` with nothing presented, so a host `Present` that depends on the caller cannot deadlock with it. On a live device, if the fence signal after a host `Present` fails, it returns `BX_PRESENT_E_COMPLETION_UNCONFIRMED` (the frame was presented); if waiting on the next back buffer after a host `Present` fails for a reason other than timeout, it logs the underlying wait `HRESULT` and returns `BX_PRESENT_E_NEXT_BUFFER_WAIT_FAILED` (the frame was presented). Post-present synchronization failures on a live device refuse further presents with `BX_PRESENT_E_NEEDS_IDLE` until `WaitForIdle` succeeds. Device-removal HRESULTs (`DXGI_ERROR_DEVICE_REMOVED` / `DXGI_ERROR_DEVICE_RESET` / `GetDeviceRemovedReason()`) are logged and returned unchanged. The recovery requirement still applies if the device reports itself as live. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
|
||||
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
|
||||
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits (including rejection of `WaitForIdle(0)` and slow-`Signal` budgets) and the leak path with the queue deliberately blocked, a concurrent `Present`, a failed post-present signal, pre- and post-present `SetEventOnCompletion` failures, post-present device-removal passthrough (`GetCompletedValue() == UINT64_MAX`, `DXGI_ERROR_DEVICE_RESET` wait, `DXGI_ERROR_DEVICE_REMOVED` signal) injected through copied vtables, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each of 6 negative controls. It reads the back buffer before presentation; it does not capture the window.
|
||||
- **Local result:** the earlier `8245c30b` revision passed 332 checks with 0 skipped on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0) and was independently verified on one Apple M5 (332 checks passed, `run_controls.sh` passed). Not a check of what reached the screen, and not an Xbox hardware result.
|
||||
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
|
||||
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
|
||||
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
|
||||
@@ -147,7 +526,21 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- `d3d12_xs` now charges its private host heaps through **`bx_xmem_try_charge_external` / `bx_xmem_release_charge_external`**, so `xmem::can_commit` sees graphics usage and **both allocation orders** obey one combined title cap (#552). Before this, `shims/d3d12_xs/vmem.cpp` kept a private `g_record.charged_private_bytes` ledger that `xmem` could not see, so **graphics-first (6) then CPU (3) admitted 9 against a cap of 8**, while xmem-first was rejected correctly. `try_charge` now lets the xmem hook decide on its own, because it admits atomically under `usage_lock` against every owner; the removed local pre-check worked from a snapshot taken outside that lock and, once the stats included external charges, would have counted every live graphics heap twice. `release_charge` checks its diagnostic mirror before crediting xmem, so a double release is refused instead of erasing another heap's charge. The graphics-first pairing check in `test_d3d12_placed` runs only at a 512 MiB cap; run it with `BX_MEM_LIMIT_MB=512`. At other caps the fixture reports the pairing check as skipped in its summary.
|
||||
- **The local pre-check is gone.** `try_charge` lets the xmem hook decide; it admits under `usage_lock` against every owner, so no overflow guards are needed on the d3d12_xs side.
|
||||
- **`g_record.charged_private_bytes` is retained as a diagnostic mirror**, labelled as such; `xmem`'s `external_bytes` is authoritative. Each heap wrapper releases its own charge exactly once, on its final `Release`. `release_charge` checks the mirror before crediting xmem and refuses a release larger than the **total** outstanding graphics charge. Because the mirror is one global total, it is not a per-heap guard: it cannot catch a double release of one heap while another heap is alive. The once-per-wrapper release is what prevents that.
|
||||
- **Lock order checked:** `try_charge`/`release_charge` hold `g_section` and then call into `xmem`, which takes `usage_lock`. `grep` over both files shows `xmem` never calls back into `d3d12_xs` (the only mention is a comment), so `g_section -> usage_lock` is never inverted.
|
||||
- `xmem.dll` exports 17 and `d3d12_xs.dll` exports 4. `test_d3d12_placed.exe` was run live on CrossOver 26.3. At the default cap the pairing check does not run and prints a `SKIP` line. With `BX_MEM_LIMIT_MB=512 bx-cli run --inherit-env` it runs and passes, and the same fixture against the pre-hook DLLs fails the pairing check. The `D3D12ConfigureVirtualMemoryX` log record's `xmem_used=` field is renamed `cap_used=`: it already includes graphics heaps, so it must not be added to `gpu_heap_bytes=`.
|
||||
- **Test:** `tests/conformance/test_d3d12_placed/` gained `check_graphics_xmem_pairing`, which uses only public exports: at a 512 MiB cap (`BX_MEM_LIMIT_MB=512`) a 300 MiB `CreateHeap` must make a 300 MiB `XMemAlloc` fail (300+300 > 512) while a 200 MiB `XMemAlloc` succeeds (300+200 <= 512), and after the heap is released the 300 MiB `XMemAlloc` must succeed. This is the graphics-first overcommit the private ledger allowed. It is a no-op unless the cap is exactly 512 MiB, and it was **not executed** here (no CrossOver).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed — removing `delete this` would leak the dispatcher while every existing check still passed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. A `delete this` removal that leaks the object would leave `live_dispatchers=1` behind and fail. The fixture also creates its own temp `BX_LOG_FILE` when the runner has not set one, so the assertions work standalone rather than reading an empty file. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none; the same offset-slicing works whether the path came from the runner or from the fixture's temp file.
|
||||
- `test_audio_input.exe` now fails with a clear message when `BX_LOG_FILE` is unset, instead of creating a temp log it can never fill. `AcpHal.dll` imports `bx_runtime_veh.dll`, which reads `BX_LOG_FILE` once in `DLL_PROCESS_ATTACH`, before `main` runs, so setting the variable in `main` left the dispatcher log checks reading an empty file and failing for the wrong reason. Run it under `bx-cli run --log`, as before. The comments on those checks no longer claim they catch a dispatcher that leaks: `Release` updates the live-dispatcher counter before `delete this`, so a missing `delete this` leaves the log unchanged. Not run live here (no CrossOver host).
|
||||
- `test_audio_input.exe` now asserts the GameInput dispatcher's **live-reference count** through the JSONL log (#500, review follow-up). `Release` returning 0 proves the count reached zero, **not** that the object was freed. `dispatch_mode` logs `mode=manual live_dispatchers=N` on each transition, so the test now reads the log and requires `live_dispatchers=1`, `live_dispatchers=0`, `mode=manual` and `mode=automatic`. **Test isolation:** `bx-cli run` appends to the supplied `BX_LOG_FILE`, so the fixture captures the log's byte length before the run and asserts only on the bytes appended by this run (`read_log_file_from(log_path, log_start)`). A re-run with the same log can no longer pass from stale `live_dispatchers`/`mode=` lines when this run emits none.
|
||||
- `test_shim_exports.exe` now loads `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), closing the gap #526 documented (#527). The fixture covers **17 DLLs / 28 checks** (16 mingw-w64 C++ shims + the 1 cargo-built Rust bridge; 25 + 3 checks), and its summary line reports the counted DLL number. `abi/` is unchanged. A load-and-resolve check does not show the bridge *works* — `test_shader_gate.exe` is what exercises it functionally. `scripts/build-shims.sh` still verifies 17 PE32+ DLLs / 111 exact exports.
|
||||
- `scripts/audit/docs_hygiene.py` now validates Markdown link fragments (`#heading`) against the target file's headings, using GitHub's slug algorithm with duplicate-heading `-1`/`-2` suffixes and fenced-code-block exclusion. In-page `](#foo)` links are checked against the same file. External URLs and bare `#` links remain unchecked. Covered by the new `scripts/audit/test_docs_hygiene.py` (23 tests) (#537). Repeated heading bases now advance their numeric suffix past *any* slug already emitted, so a literal `# Foo-1` heading no longer lets a later `# Foo` reuse `foo-1`: headings `Foo`, `Foo-1`, `Foo` yield `foo`, `foo-1`, `foo-2`.
|
||||
- Corrected the stale shim-DLL counts in `AGENTS.md`, `README.md`, `docs/roadmap.md` and `docs/architecture/parallel-tracks.md` (#525). `scripts/build-shims.sh` verifies **17** PE32+ DLLs with **111** exact exports, not 16 with 102. The wording now distinguishes the **16 mingw-w64 C++ shims** (built by the CMake superbuild) from the **Rust `bx_shader_bridge.dll`** (built by `cargo` for `x86_64-pc-windows-gnu`, added by #484), rather than calling all 17 "cross-compiled C++ shims". `test_shim_exports.exe` still loads only the 16 C++ shims (25 checks); it does not load the bridge, which `test_shader_gate.exe` covers. The `docs/roadmap.md` M0 exit-gate text is a stale-count correction to a *recorded* gate (`#406`), not a re-opening of M0. Follow-up (not done here): `test_shim_exports` could also load `bx_shader_bridge.dll`.
|
||||
- `bx-cli`'s usage paths were exactly inverted, and are now right (#532). `--help` and `-h` were never matched, so they fell into the unknown-subcommand arm: usage text on **stderr** and exit **1**. Meanwhile a bare `bx-cli` with no arguments printed usage and returned **0**. `--help`/`-h`/`help` now print usage on **stdout** and exit **0**, so `bx-cli --help | less` and `bx-cli --help && ...` both work; a bare invocation is a usage error with text on **stderr** and exit **1**; an unknown subcommand still exits **1**. The choice is factored into a `Dispatch::classify` so it is testable without spawning a process. `launcher/crates/bx-cli/tests/usage.rs` runs the built binary and checks the real exit code and output stream for `--help`/`-h`/`help`, a bare invocation and an unknown subcommand.
|
||||
- **Tests:** `help_succeeds_on_stdout_and_a_bare_invocation_is_a_usage_error` (exit and stream for `--help`, `-h`, `help`, no arguments, a bogus subcommand, and that the five real subcommands are not usage errors) and `the_usage_text_names_every_subcommand`.
|
||||
- **Not run:** live CrossOver execution — no CLI path here reaches a guest. Synthetic evidence only.
|
||||
- `bx-cli run` now stages `GameInput.dll` into `system32` alongside `xgameruntime.dll` and safely replaces Wine's `"Wine builtin DLL"` placeholder stub after saving a one-time backup (`.gameinput.dll.wine-builtin.bak`), while continuing to refuse modifying any non-Wine foreign DLL or symbolic link (#482). Wine pre-populates `drive_c/windows/system32/gameinput.dll` with a fake builtin PE stub whose `GameInputCreate` returns `E_NOTIMPL`, shadowing `WINEPATH` and `LOAD_LIBRARY_SEARCH_SYSTEM32` loads even when `WINEDLLOVERRIDES` specifies native-first (`=n,b`). Also added lowercase aliases (`gameinput`, `xcrdapi`, `acphal`) to `SHIM_DLL_OVERRIDES` and expanded `test_system32_staging.exe` and `stage.rs` unit tests to cover `GameInput.dll` staging and Wine stub backup/refusal rules.
|
||||
- `bx-cli run` system32 shim staging (#474). Staging now records what it wrote in a `.bx-staged` manifest in the prefix's `system32` (one SHA-256 per file) and replaces only regular files that are listed there and still have the recorded hash. Any other same-named entry the bottle already had, including a symbolic link that points nowhere, or one changed since it was staged, is never modified or deleted: staging stops with an error naming it before anything is written. New files are installed without replacing anything, so an entry that appears after the checks is protected too. All temporary copies are written before the first file is put in place, and each installed file is recorded in the manifest before the next one is touched, so a failure part-way leaves the earlier files owned rather than orphaned. A byte-identical existing file is left alone and not claimed. For a named bottle, the prefix is resolved again after the run; if CrossOver launched the bottle elsewhere, the run fails only when the staged shims cannot be found with the same contents in that prefix's `system32` (a private stub of a managed bottle that links back to the managed prefix is accepted and reported). When prefix initialization uses the whole `--timeout`, the guest is no longer started and the message names initialization (exit 124). Copies staged by an earlier `bx-cli` have no manifest entry and are treated as the bottle's own, so after upgrading a changed shim needs that stale copy removed by hand once. Staged files are still not removed after a run. Covered by 15 new unit tests (32 `bx-cli` tests pass); twelve deliberate breakages each failed a test. A reviewer ran the first revision on CrossOver 26.3 with a managed-only bottle and found the false failure, dangling-link and partial-failure cases fixed here; this revision has not itself been run under CrossOver.
|
||||
- Fixed `bx-cli run --bottle` losing the shim DLL overrides: CrossOver's `bin/wine` discards `WINEDLLOVERRIDES`, so they are now passed with `--dll` (found by jelly013) (#408).
|
||||
|
||||
+43
-24
@@ -1,47 +1,66 @@
|
||||
# Contributing to BetterXen
|
||||
|
||||
BetterXen is a modular, CrossOver-based Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS. Contributions are organized into **6 parallel tracks** so 5–8+ human contributors and coding agents can work simultaneously without merge conflicts.
|
||||
BetterXen runs a project-authorized Xbox Series title on Apple Silicon Macs, through CrossOver, Rosetta 2 and D3DMetal plus BetterXen's own shims. Members work by pointing a coding agent at this repository and saying **"work"**; the agent follows [AGENTS.md](AGENTS.md). This page is the short version for a person joining.
|
||||
|
||||
## Active Work & Track Ownership
|
||||
## What you need
|
||||
|
||||
The single authoritative plan is [docs/roadmap.md](docs/roadmap.md) (Milestones M0–M6), supported by [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and the ready-to-claim Wave 1 issues in [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md). The earlier native-first workspace was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently at Git tag `native-first-final`.
|
||||
These are a **hard requirement**. Without every one of them you, and your agent, do not work on the repository:
|
||||
|
||||
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
|
||||
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**. 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>`.
|
||||
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
Then tell your agent **"work"**. If you work by hand, follow the same steps yourself: [AGENTS.md](AGENTS.md) Section 0.
|
||||
|
||||
## How work is organised
|
||||
|
||||
The full process is [AGENTS.md](AGENTS.md) Section 0 and [docs/process/working-method.md](docs/process/working-method.md); the stages are in [docs/roadmap.md](docs/roadmap.md). In short:
|
||||
|
||||
1. **Pick one thing**, in this order: your own pull requests that need attention; a review of someone else's; a `handoff` issue of the current stage (named on the pinned `ladder` issue); or the first thing the target build stops on.
|
||||
2. **Check for existing work first.** Before investigating any problem the game shows, search open and merged pull requests and open issues for it. If an open pull request covers it, check that branch out and work there.
|
||||
3. **Claim it with a draft pull request** titled `[<Stage>] <signature>`, before writing the fix. A draft with no push for 3 days may be taken over.
|
||||
4. **Evidence, smallest fix, test.** Every contract the fix introduces gets a conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row with it.
|
||||
5. **Verify** with [AGENTS.md](AGENTS.md) Section 8, fill in the five-part description (Blocker, Contract, Fix, Test, Proof), and mark it ready.
|
||||
|
||||
Something you can't finish goes into a `handoff` issue instead, with what you saw, tried and still don't know.
|
||||
|
||||
## Running the target build
|
||||
|
||||
Runs are made offline, inside a sandbox that blocks outbound network: [docs/testing/target-build-review.md](docs/testing/target-build-review.md) has the procedure and the diagnostic switches. Three switches matter for getting through the title unattended:
|
||||
|
||||
- `BX_INPUT_SCRIPT=A@40,A@50` presses buttons;
|
||||
- `BX_CONTINUE_ASSERTS=1` steps over the title's continuable asserts;
|
||||
- `BX_PRESENT_DUMP=<folder>` saves frames.
|
||||
|
||||
`bx-cli run` stages the GDK's texture libraries for the target build automatically ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)). `bx-cli report <log.jsonl>...` turns run logs into the report and the blocker signatures that pull requests are titled with.
|
||||
|
||||
## Licensing & Provenance Policy
|
||||
|
||||
- Use publicly accessible specifications, publicly licensed software, independently authored synthetic workloads, and project-authorized target builds only under every condition in [AGENTS.md](AGENTS.md) §6 (maintainer approval alone is not enough). Never obtain or use leaked or unauthorized material, and never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
- BetterXen is **not** a clean-room project (repository owner's decision, 2026-11-29, #650). Material the project is authorized to use, such as the Microsoft GDK and its compilers under the project's authorization, may be used by contributors, and facts derived from it (layouts, slot orders, flag values, binary conventions) may be committed. The material itself, and its outputs, are never committed. **Leaked or unauthorized material is still forbidden:** anyone who has used it for this work must not contribute what they learned from it. Do not post details of restricted material in issues or PRs.
|
||||
- Before incorporating third-party code, verify **per-file** license compatibility with `GPL-3.0-or-later`, record provenance in [docs/research/upstream-registry.md](docs/research/upstream-registry.md) and [docs/research/component-reuse-matrix.md](docs/research/component-reuse-matrix.md), preserve copyright notices, and update [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Public visibility or a GPL license does not clear code derived from leaked material.
|
||||
- Never bundle or redistribute proprietary components (CrossOver, D3DMetal, Rosetta 2).
|
||||
- Never claim Xbox hardware verification (BetterXen has no Xbox hardware access) or independent certification of your own work; classify evidence per [docs/claims.toml](docs/claims.toml).
|
||||
|
||||
|
||||
## 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
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -2,234 +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.**
|
||||
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml)
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml)
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||
-0969da)
|
||||

|
||||

|
||||
|
||||
</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]
|
||||
> **Clean-room and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
*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 the 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine. It does **not** load `bx_shader_bridge.dll`; the Rust bridge is exercised by `test_shader_gate.exe` instead.
|
||||
- **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.
|
||||
@@ -9,6 +9,7 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `G
|
||||
| Files | Origin | License |
|
||||
| --- | --- | --- |
|
||||
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
|
||||
| `shims/xg_xs/third_party/addrlib/` | AMD addrlib from Mesa `src/amd/addrlib`, tag `mesa-25.2.0`, commit `0b97dcdd9424fce130054e1972a610b765644003`, unmodified (#756). Provenance: [shims/xg_xs/third_party/addrlib/README.md](shims/xg_xs/third_party/addrlib/README.md). | MIT. 42 of 44 files carry `SPDX-License-Identifier: MIT`. `src/core/addrswizzler.cpp` and `src/core/addrswizzler.h` have the AMD 2024 copyright block and no SPDX line; `meson.build`, which lists them, is SPDX MIT. |
|
||||
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -15,3 +15,7 @@ EXPORTS
|
||||
XMemVirtualQuery
|
||||
bx_xmem_query_region
|
||||
bx_xmem_get_internal_stats
|
||||
bx_xmem_try_charge_external
|
||||
bx_xmem_release_charge_external
|
||||
bx_xmem_remap_guard_enter @18
|
||||
bx_xmem_remap_guard_leave @19
|
||||
@@ -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
|
||||
|
||||
@@ -33,9 +33,36 @@ typedef struct bx_xmem_stats {
|
||||
/* Query the XMem region covering `va`. Returns 1 if tracked, 0 otherwise. */
|
||||
int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info);
|
||||
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap. */
|
||||
/* Snapshot current XMem usage against the active Lockhart/Anaconda cap.
|
||||
* committed_virtual_bytes includes bytes admitted through
|
||||
* bx_xmem_try_charge_external(), so committed + physical is everything the
|
||||
* cap counts and peak_committed_bytes never exceeds what was reported. */
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
|
||||
|
||||
/* Admit `bytes` against the combined title cap, counting every owner.
|
||||
* Returns 1 on success, 0 when the cap would be exceeded or xmem's own
|
||||
* bookkeeping could not be refreshed (logged as external_charge). On success the
|
||||
* caller owns the charge and must release it exactly once with
|
||||
* bx_xmem_release_charge_external(). Never silently succeeds on failure. */
|
||||
int bx_xmem_try_charge_external(uint64_t bytes);
|
||||
|
||||
/* Release a charge previously admitted by bx_xmem_try_charge_external().
|
||||
* Releasing more than is outstanding is refused: the counter is left
|
||||
* unchanged and an external_charge error is logged. */
|
||||
void bx_xmem_release_charge_external(uint64_t bytes);
|
||||
|
||||
/* The remap guard protects BetterXen reads and writes to title memory while
|
||||
* XMemMapPhysicalPages, XMemMapPhysicalPagesScatter or XMemFreePhysicalPages
|
||||
* replaces mapped views. Those operations wait for active guards and block
|
||||
* new guards until the remap completes.
|
||||
*
|
||||
* Pair each enter with one leave on the same thread. Keep the guard short,
|
||||
* avoid nesting it, and release it before calling an XMem function.
|
||||
* Consumers that resolve the helpers dynamically must resolve both or
|
||||
* call neither. */
|
||||
void bx_xmem_remap_guard_enter(void);
|
||||
void bx_xmem_remap_guard_leave(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+11
-4
@@ -3,8 +3,9 @@
|
||||
## Getting Started & Architecture
|
||||
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan (Milestones M0–M6) and completion gates.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [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) — 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.
|
||||
@@ -16,21 +17,27 @@
|
||||
- [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
|
||||
|
||||
- [Target-Build Bring-Up: Development Cycle and Review](testing/target-build-review.md) — How contributors run a project-authorized target build offline, turn findings into single-track PRs, and review them independently without proprietary details.
|
||||
- [Hybrid Workloads & Measurement Protocol](testing/hybrid-workloads.md) — Original Windows workloads, receipt fields, timing conventions, and negative controls.
|
||||
- [CrossOver Licensing & Redistribution Boundaries](research/crossover-licensing.md) — Per-component license review for CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, D3DMetal, and Rosetta 2.
|
||||
- [Upstream Research Registry](research/upstream-registry.md) & [Component Reuse Matrix](research/component-reuse-matrix.md) — Public upstream evaluation and provenance screening.
|
||||
- [Primary-Source Verification (2026-11-25)](research/primary-source-verification-2026-11-25.md) & [Hybrid Backlog Research Record](research/hybrid-backlog-research-2026-11-25.md) — Vendor documentation verification notes.
|
||||
- [D3D12 Swapchain References under D3DMetal](research/d3dmetal-swapchain-references.md) — Swapchain lifetime results across two Apple Silicon hosts and CrossOver builds.
|
||||
- [gfx10-translate](../shader-transpiler/crates/gfx10-translate/README.md) — BetterXen's GFX10.3 console shader translator: container reader, decoder with an LLVM-generated opcode table, HLSL translation ported from the Python prototype, coverage over local shaders, and how to add an instruction.
|
||||
- [Shader Corpus](../shader-transpiler/corpus/README.md) — Phase 0 of the console shader translator: BetterXen-authored kernels built locally into console containers, Microsoft ISA listings and PC DXIL, with the derived `FSPX` code-section layout (#649).
|
||||
- [D3DMetal GPU Limits](research/d3dmetal-gpu-limits.md) — Constraints a shader translator targeting D3DMetal must handle, measured by the `test_d3dmetal_gpu_limits` fixture (`WaveSize(64)` and SM 6.6 64-bit atomics not run, bounded lock emulation), plus unverified reports kept separate as leads (#453).
|
||||
- [Console Compute Shader Entry ABI](research/console-shader-abi.md) — Wave size, root-argument registers, descriptor forms and binding metadata observed from the NewBE backend of Microsoft's Series X|S PIX shader compiler on project-authored probes (class U: an authorized, not yet independently reproduced observation; inferred register roles).
|
||||
- [Public Technical References](research/sources.md), [Xbox GDK Notes](research/xbox-gdk.md), [RDNA 2 Notes](research/rdna2.md), and [Shader Containers](research/shader-containers.md) — Public specification references for shim and shader work.
|
||||
|
||||
## Governance, Security & Legal
|
||||
|
||||
- [Engineering & Agent Rules](../AGENTS.md) (`CLAUDE.md` symlink) — Mandatory rules for human contributors and coding agents.
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, clean-room policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Evidence classification definitions (classes A–D, U).
|
||||
- [Contributing Guidelines](../CONTRIBUTING.md) — Claiming, verification, provenance policy, and DCO sign-off.
|
||||
- [Claims & Evidence Classes](claims.toml) — Scoped claims with an evidence-class legend (A, B, D, E, U); classes describe evidence type, not Xbox hardware verification.
|
||||
- [Legal Scope](legal.md), [Dependency Licensing](licenses.md), and [Third-Party Notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution boundaries.
|
||||
- [Threat Model](threat-model.md) & [Security Policy](../SECURITY.md) — Isolation boundaries and vulnerability reporting.
|
||||
@@ -64,9 +64,9 @@ Revisit this ADR in any of these cases:
|
||||
## Consequences
|
||||
|
||||
- **Pipeline creation:** `CreateComputePipelineState` and `CreateGraphicsPipelineState` now depend on `bx_shader_bridge.dll` for classification. Without it, they still work, refuse ACCC-only containers, and say so in the log.
|
||||
- **Stream PSOs (#576):** `ID3D12Device2::CreatePipelineState` stream descriptions are gated too. The stream is walked as 8-byte-aligned records (a 4-byte subobject type plus a type-dependent payload). Both the payload offset and the record size come from the compiler: `alignas(void*)` aligns the record, not the payload, so 4-byte-aligned payloads sit at offset 4, and `static_assert`s pin the measured values. Shader subobjects (`VS`, `PS`, `DS`, `HS`, `GS`, `CS`, `AS`, `MS`) go through `BxShaderGate::admit`; every other payload is copied verbatim. A subobject type at or above `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MAX_VALID` from the toolchain header (mingw-w64 `d3d12.h`: `0x1a`, immediately after `MS`), a duplicated subobject type, a payload that overruns `SizeInBytes`, or a bytecode length with a null pointer returns `E_INVALIDARG` before the host is called. The shim edits its own copy of the stream, so prepared DXIL can be substituted without writing to the caller's memory. `pso_stream` now reports `shaders_not_parsed=0` when it parsed, and each stream stage logs its own `shader_gate` record with `pso=stream`. The `--no-bridge` path also refuses ACCC-only through the stream. `test_shader_gate.exe` covers the stream form but was cross-compiled only, not run under CrossOver on the authoring host.
|
||||
- **Packaging:** `scripts/build-shims.sh` builds the bridge, links it with `abi/defs/bx_shader_bridge.def`, and stages it in `build-shims/bin` beside `d3d12_xs.dll` (#484).
|
||||
- **Not covered by the gate yet:**
|
||||
- **Stream PSOs:** `ID3D12Device2::CreatePipelineState` stream descriptions are still forwarded unparsed.
|
||||
- **Raw-buffer 64-bit atomics:** these cannot be flagged from `SFI0`; the DXIL bitcode would have to be read.
|
||||
- **Telemetry summary:** `bx-cli trace` now summarizes the gate's records (#496): per-decision, per-kind and per-stage counts for `shader_gate`, the `shader_d3dmetal_gap` list with its wave-width and 64-bit-atomic flags, and `shader_bridge_missing`. The summary only reflects records a run actually wrote; it adds no live run and no new compatibility claim.
|
||||
- **Observed `FSPX` tables:** the clean-room section-table layout does not describe the 29 containers embedded in the target workload's upscaler component. In the 2026-11-28 scan, `dxbc-accc` rejected them with `FspxSectionOutOfBounds` before any section body was read, so the current refusal is structural, not a measured D3DMetal incompatibility. The cause the scan recorded, a descriptor offset inside the region the layout reserves for the header and section table, is reported as `FspxLayoutMismatch` since #599, apart from a section past the payload end; the scan has not been re-run against that change. Over the C ABI both are still `BX_SHADER_ERR_INVALID_BLOB`. Extending the layout against measured containers is a Track D prerequisite for any D2 trial and a maintainer provenance decision, because no public format description exists.
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
# ADR 0009: Xbox-layout D3D12 objects in d3d12_xs
|
||||
|
||||
Status: **Proposed** (2026-11-28). Phase 1 is implemented with this ADR; the maintainers decide whether the direction stands. The evidence is from local Apple Silicon runs by the implementer and has not been independently reproduced.
|
||||
|
||||
## Context
|
||||
|
||||
`d3d12_xs.dll` handed titles PC D3D12 objects: C++ proxies (`proxy.h`, `proxy_generated.cpp`) whose vtables follow the PC `<d3d12.h>` order. A title built against the Xbox Series D3D12 header (`d3d12_xs.h`, part of the GDK material Microsoft authorized the project to use) calls through each object's **function table**, and that order is different:
|
||||
|
||||
| Interface | Xbox slots | PC slots | Orders agree up to |
|
||||
| --- | --- | --- | --- |
|
||||
| `ID3D12Device` | 83 | 44 | slot 43. Xbox then adds 39 methods (`CreatePlacedResourceX`, `CreateCommandQueueX`, ...) before `ID3D12Device1`. |
|
||||
| `ID3D12Device11` (chain) | 139 | — | `ID3D12Device11` is the interface a project-authorized target build asks for. |
|
||||
| `ID3D12GraphicsCommandList` | 107 | 60 | slot 27 |
|
||||
| `ID3D12CommandQueue` | 38 | 19 | slot 13 |
|
||||
|
||||
So every call past those slots reached the wrong PC method. On the target build, the first call on the device after `QueryInterface(ID3D12Device11)` jumped to address 0.
|
||||
|
||||
From the same header:
|
||||
- **Base layout:** every object starts with the table pointer, a 32-bit flags word and `m_RefCount`, 16 bytes in all.
|
||||
- **`ID3D12Device` fields:** a 64-bit null constant-buffer address at +16 and a 64-byte union at +24. The union's first byte, `m_OutOfLineFlags`, makes the two inline device helpers (`CopyDescriptorsSimple`, `CreateConstantBufferView`) call out through the table when it is non-zero. That holds unless a title is compiled with `D3DCOMPILE_NO_DEBUG`, in which case they write descriptors inline.
|
||||
- **Command lists:** they add a put buffer and CPU state. Of their 76 inline methods, 71 call the table. The other five write command packets directly when the next write fits below `m_Putter`'s limits, and call the table otherwise.
|
||||
- **IIDs:** the interface IDs of shared interfaces are the PC ones (`ID3D12Device` `189819f1-…`, `ID3D12Resource` `696442be-…`).
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Xbox-layout objects:** titles get `BxXboxObject`s (`xbox_facade.h`). They have the Xbox object layout, with `m_OutOfLineFlags` set, and an Xbox-order function table. Each object hosts a PC object, normally one of the existing proxies, so their logging, shader gate, heap hooks and wrapping stay in force.
|
||||
2. **Generated tables:** `tools/gen_xbox_tables.py` reads the Xbox header locally and the toolchain's `<d3d12.h>`, and writes `xbox_tables_generated.cpp`. It takes only slot order, names, IIDs and parameter types from the Xbox header. The header is never committed.
|
||||
- **Forwarders:** a slot whose Xbox and PC signatures are equivalent gets a typed forwarder written with the PC types. That includes the free-function versus member struct-return difference, so the compiler produces the right calling convention. Interface pointers passed in are unwrapped, and `(REFIID, void**)` results are wrapped.
|
||||
- **Stubs:** every other slot is a `BX_VTABLE_STUB_LOG` stub.
|
||||
- **Hand-written slots:** Xbox-only methods are implemented in `xbox_facade.cpp` as titles need them.
|
||||
3. **Who gets which layout:** titles set `Version` in the `D3D12XBOX_CREATE_DEVICE_PARAMETERS` block they pass to `D3D12XboxCreateDevice`, and the documentation requires it. Those calls get the Xbox layout. BetterXen's synthetic fixtures are PC-layout clients built against `<d3d12.h>`, pass a zeroed block, and keep the PC proxy. The log records which layout was chosen (`xbox_layout`).
|
||||
4. **Command lists (Phase 2):** command lists get an Xbox object whose zeroed put-buffer pointers fail every inline room check, so every call reaches the table.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Phase 1 (this change):**
|
||||
- The device chain up to `ID3D12Device11` is covered: 139 slots, 75 forwarded, 4 shared or hand-written, 60 stubs.
|
||||
- So are the objects it creates: resources, heaps, fences, descriptor heaps, root signatures, pipeline states, command allocators, query heaps, command signatures and command queues.
|
||||
- `CreateCommandQueueX` maps the Xbox queue description onto PC `CreateCommandQueue`. The engine and queue indices are logged and not used.
|
||||
- On the target build, the title now creates its device and four compute queues, and stops at `CreateCommandListX`, which is Phase 2.
|
||||
- **Phase 2:**
|
||||
- **Command lists:** `ID3D12GraphicsCommandList8`, 150 slots: 75 forwarded, 6 shared or hand-written, 69 stubs. They are created through `CreateCommandListX` and the PC `CreateCommandList`, and their Xbox field area is zeroed, so the five inline fast paths call through the table.
|
||||
- **Interface pointers inside structures:** `ResourceBarrier` and `CopyTextureRegion` unwrap them before the host call. The Xbox `ResourceBarrier` returns 0 actions.
|
||||
- **Frame pacing:** `SetFrameIntervalX`, `ScheduleFrameEventX` and `WaitFrameEventX` (`frame_pacing.cpp`) are emulated from the recorded interval by a host timer. It signals the origin, vblank and flip events and their ancillary handles, and gives out frame-pipeline tokens as documented.
|
||||
- **Generator fixes:** CRLF lines in parts of the header, a table definition whose end the boundary pattern ran past (it hid `ID3D12GraphicsCommandList1`), SAL annotations with nested parentheses, and `FLOAT`/`float`.
|
||||
- **Resources at title-chosen addresses** (`placed_x.cpp`), translation by copy:
|
||||
- `CreatePlacedResourceX` and `CreatePlacedResourceX1` create a host shadow resource. A buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's memory at creation; a texture gets a committed texture whose contents are not filled, which is logged.
|
||||
- The resource reports the title's address from `GetGPUVirtualAddress`.
|
||||
- Not yet done: keeping shadows in step with later CPU writes (planned: page-protection dirty tracking, copying at submit), copying GPU writes back, and translating title addresses in GPU calls.
|
||||
- **On the target build:** the title creates 581 command lists, sets a 30 Hz interval and schedules its origin and flip events. It then lays out its own descriptor memory with `xmem` placeholders (#643) and creates a 174 MB buffer at a title-chosen address through `CreatePlacedResourceX1`, now served by a shadow.
|
||||
- **Where it stops:** the title creates a descriptor heap and requires `GetCPUDescriptorHandleForHeapStart` to equal an address in its own descriptor memory. D3DMetal returns an opaque handle.
|
||||
- **What that needs:** BetterXen-owned descriptor heaps whose handles are addresses, translated to host descriptors when used. That is the descriptor-heap item under Consequences.
|
||||
- **Fixtures:** the existing fixtures are unaffected, since they use the PC layout. `tests/conformance/test_d3d12_xbox_layout` calls Xbox slots by number, with the expected results taken from a PC-layout device. It fails against the previous `d3d12_xs.dll`.
|
||||
- **What the fixture can and cannot show:** its slot numbers and object offsets are written by hand, but from the same header the generator reads. It shows that the generator and the fixture agree. It cannot show that either read the header correctly; only an independent re-derivation from the header, or a title running further, can.
|
||||
- **On a host without the forwarded interface** (vkd3d stops at `ID3D12Device9`): the Xbox-layout device is refused with `E_NOINTERFACE` and logged. The fixture verifies the refusal and skips (exit 77). `bx_xbox_wrap` refuses the same way for every wrapped family, so a title never gets a PC object where it expects an Xbox one.
|
||||
- **Frame pacing:** the emulated frame interval follows host `Sleep` and is not synchronised to the display. The pacing thread is detached and never exits, which is safe only while `d3d12_xs.dll` stays loaded for the life of the process.
|
||||
- **Descriptor heaps:** a title compiled with `D3DCOMPILE_NO_DEBUG` writes console-format descriptors straight into descriptor-heap memory and computes handles with Xbox descriptor sizes. Supporting that needs BetterXen-owned descriptor heaps translated at bind time, which is not part of this ADR.
|
||||
- **Identity:** QueryInterface on an Xbox object for another wrapped family returns that family's Xbox object over the same host. A host reached through another path, such as `GetDevice` returning the raw host device, may get a second Xbox object.
|
||||
- **Replacing the PC proxy:** this ADR supersedes the PC proxy for titles. Whether the PC proxy is eventually removed in favour of fixtures that use the Xbox layout is left open.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -1,4 +1,30 @@
|
||||
# Source review is distinct from a Xenora test run.
|
||||
#
|
||||
# Evidence classes (derived from existing usage; claim classes are unchanged):
|
||||
# A — Executed measurement on a named Apple Silicon host, with an independent
|
||||
# CPU/reference expectation. Valid only for the named host/software versions;
|
||||
# implementer-run unless independently reproduced. Never Xbox verification.
|
||||
# B — Source-derived semantics from a public vendor specification, scoped to the
|
||||
# documented target (e.g. desktop RDNA 2, public D3D12, Metal/MSL). May be
|
||||
# exercised by synthetic tests, but does not establish console applicability.
|
||||
# D — Public documentation or sample-source inspection (Microsoft/Xbox/Apple),
|
||||
# without console execution. Establishes only what the reviewed source states.
|
||||
# E — Public tool/format documentation or observed behavior of a public
|
||||
# software tool (e.g. LLVM's gfx1030 documentation, or its assembler/
|
||||
# disassembler accepting gfx1030 forms), scoped to the pinned tool version.
|
||||
# Documentation review and execution are distinct; the claim's test field
|
||||
# records which one applies.
|
||||
# U — Unknown/unestablished by the reviewed public sources: a bounded statement
|
||||
# about the evidence reviewed, not proof that no authorized source exists.
|
||||
#
|
||||
# Use B for semantics from a specification, D for a claim about what a public
|
||||
# document or sample says, and E for a claim about a tool or its format support.
|
||||
# The current registry does not assign class C.
|
||||
#
|
||||
# These are the repository's evidence classes. AGENTS.md §5 refers to this
|
||||
# file and does not define a second vocabulary; the longer VERIFIED /
|
||||
# REPRODUCED / SOURCE-DERIVED / ... vocabulary named in issue #549 is not
|
||||
# present in the in-tree AGENTS.md, so no mapping is invented here.
|
||||
schema_version = 1
|
||||
|
||||
[[claim]]
|
||||
@@ -242,3 +268,13 @@ retrieved = "2026-11-22"
|
||||
architecture = "Xbox Series X, Hot Chips 32 architectural presentation"
|
||||
test = "Read slides 12 and 13. No console execution."
|
||||
uncertainty = "The slides do not specify opcode semantics, an ABI or a command packet layout."
|
||||
|
||||
[[claim]]
|
||||
id = "CLAIM-XBOX-CS-ENTRY-ABI"
|
||||
class = "U"
|
||||
claim = "For project-authored compute shaders with explicit root signatures, the NewBE backend of Microsoft's Series X|S PIX shader compiler generated wave64 code that receives root data from s4 in root-parameter order (one SGPR per constant, two per root descriptor address, one per 32-bit table pointer), thread-group IDs after the root data, the root-data address in s0:s1 when the data overflows, and root buffer descriptors built inline with a record count of -1."
|
||||
sources = ["docs/research/console-shader-abi.md"]
|
||||
retrieved = "2026-11-28"
|
||||
architecture = "Xbox Series X|S compute shaders, as compiled by the GDK 2026.10 (10.0.26100.9661) Scarlett PIX shader compiler (NewBE) under CrossOver 26.3 (26.3.0.39832) on Apple M5, macOS 27.2.1"
|
||||
test = "Compiled eleven project-authored cs_6_5/cs_6_6 probes and read the compiler's assembly listings; the compiler and its outputs are used under Microsoft's authorization and are not in the repository."
|
||||
uncertainty = "Class U: no public source establishes this; it rests on an authorized reading of a non-public compiler's listings, which only a contributor with the same authorization can reproduce, and which has not been independently reproduced. Register roles are inferred from the generated code and the reported COMPUTE_PGM_RSRC2 fields. NewBE only: the ACO backend (xdxc), which produces ACCC code, generates different code and agrees so far only on the root UAV address in s[4:5]. One compiler build, compute only, no console execution, and the ACCC container layout is not covered."
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Clean-room scope
|
||||
# Legal scope
|
||||
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation, vendor documentation and tools the project is authorized to use (never committed; see [CONTRIBUTING](../CONTRIBUTING.md)), its own synthetic workloads and, under the conditions in [AGENTS.md](../AGENTS.md) §6, local observation of lawfully obtained target builds.
|
||||
|
||||
## User-provided game files
|
||||
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
# Working Method: Run, Fix, Pull Request
|
||||
|
||||
**Status: in effect since 2026-11-29** (#662), together with [AGENTS.md §0](../../AGENTS.md). The pinned ladder issue is #663.
|
||||
|
||||
BetterXen is built by collaborators who each have the project-authorized target build, the GDK and the target build's Ghidra results, and who work by pointing a coding agent at this repository and saying **"work"**. This document answers one question for an agent that has just been told to work: *what is the single most useful thing to do now, and how do I do it without colliding with the other agents?*
|
||||
|
||||
The short answer: run the build, fix the first thing it stops on, and open a pull request. The pull request is the unit of work. There are no meetings, no rotating roles and no backlog to interpret.
|
||||
|
||||
## What you must have
|
||||
|
||||
No agent works without all of these. `bx-cli preflight` checks them and fails if one is missing:
|
||||
|
||||
- an Apple Silicon Mac with CrossOver, D3DMetal and `mingw-w64`;
|
||||
- **the project-authorized target build**;
|
||||
- **the GDK**, headers and compilers, under the project's authorization;
|
||||
- **the Ghidra results of the target build**: the static-analysis run (`RUN_REPORT.md`, `exports/`, `decompiled/`) covering its executable;
|
||||
- at least 10 GiB of free disk space.
|
||||
|
||||
The target build, the GDK and the Ghidra results are a hard requirement: an agent that lacks even one of them does not work on the repository at all.
|
||||
|
||||
A collaborator only says "work". When preflight fails, the agent makes the machine ready itself: `bx-cli setup --find` searches the home folder, recognises the GDK by its header, the target build by its structure (never by name) and the Ghidra results by their layout and the program they cover, and saves all three in `~/.config/betterxen/local.conf`, outside the repository, where every worktree and agent session on that machine finds them. It installs missing build tools with Homebrew and frees disk space by removing its own scratch.
|
||||
|
||||
Work here is found by running the build, located in the Ghidra results and checked against the GDK. Without all three an agent can only guess, and a guess that looks like a fix costs a reviewer more than it saves. An agent stops only for what it cannot supply: the host is not an Apple Silicon Mac, CrossOver is not installed, the build, the GDK or the Ghidra results are not on the machine, or more than one distinct build is (the choice is the collaborator's). Then it says exactly which, and does not write fixes, tests or reviews "for someone else to verify".
|
||||
|
||||
## Why this shape
|
||||
|
||||
What the first target-build runs taught us:
|
||||
|
||||
- **The build finds what tests cannot.** With the start-up milestone verified complete, the build still stopped on a missing handle-duplication call, an instruction loop that trapped two million times and a page-remapping race. Nobody would have written an issue for any of them in advance.
|
||||
- **Guessing is expensive.** A stall was blamed on network polling for a day; a thread sample found the real cause in minutes.
|
||||
- **A helpful workaround can hide the real path.** Answering every pipeline call with success kept the frame loop alive and hid the build's fallback to shader containers.
|
||||
- **One run proves little.** The build takes different start-up paths from run to run. Two blockers looked like one "intermittent stop" until runs were counted.
|
||||
- **Agents left alone drift.** They wrote long documents, opened large stacked pull requests that nobody reviewed, investigated the same symptom twice, shared one game bottle and filled a disk.
|
||||
|
||||
So: the build decides what is next, the queue makes it unambiguous, and reviewing comes before new work.
|
||||
|
||||
## The stages
|
||||
|
||||
The [roadmap](../roadmap.md) is a ladder of stages the target build reaches: **Boot → Picture → Menus → World → Fidelity → Playable**. Exactly one stage is current. Its exit gate is a ten-run check anyone can repeat.
|
||||
|
||||
## Where the state lives
|
||||
|
||||
| What | Where |
|
||||
| --- | --- |
|
||||
| A blocker someone is fixing | An open pull request titled with its signature (a draft while in progress) |
|
||||
| A blocker someone found and could not finish | A **handoff issue** (label `handoff`, plus `stage: <name>`) |
|
||||
| The current stage and its latest gate result | The pinned **ladder issue** (label `ladder`) |
|
||||
| What needs a person | Label `needs-human` |
|
||||
| Rules | AGENTS.md and this document, changed by pull request |
|
||||
|
||||
Nothing about status is kept in files in the repository: agents editing one status file would conflict all day.
|
||||
|
||||
### Why a blocker gets a pull request and not an issue
|
||||
|
||||
An agent that runs the build and sees what it stops on usually knows the fix a few minutes later. Writing an issue, claiming it and then opening a pull request that closes it is three steps where one does the job. And an issue of the form "the build stops at X" is a fact about one run on one machine: the build takes different start-up paths from run to run, so another collaborator may never see it.
|
||||
|
||||
What holds on every machine is the **test**: "the console does X for this call, and this test fails without the fix". The run is why you looked; the test is the proof.
|
||||
|
||||
So:
|
||||
|
||||
- **You can fix it:** open a draft pull request titled with the signature, before writing the fix. The draft is the claim.
|
||||
- **You cannot fix it** (too large, out of session, needs a decision): file one handoff issue with what you saw, what you tried and what is unknown.
|
||||
|
||||
### Signatures
|
||||
|
||||
A signature is the fixed string `bx-cli report` prints for something a run stopped on: `unimplemented IXUser slot 3`, `fault in XCRDAPI.dll`, `exit status 5`. Pull requests and handoff issues are titled with it (`[Boot] unimplemented IXUser slot 3`), so searching open pull requests for a signature tells you whether someone is already on it.
|
||||
|
||||
## What an agent does when told "work"
|
||||
|
||||
AGENTS.md §0 has the binding version. In short, in strict order:
|
||||
|
||||
1. **Preflight.** `bx-cli preflight` must pass. If it does not, stop.
|
||||
2. **Your own pull requests first.** Requested changes, failing checks, conflicts, or a draft you have not finished.
|
||||
3. **Then review.** The oldest open, non-draft pull request from *another* person that has no current review. Merge it if it is approved, green and not your person's. Review comes before new work because unreviewed work is worth nothing to the next run.
|
||||
4. **Then a handoff issue** of the current stage that no pull request covers.
|
||||
5. **Then run the build** and fix the first thing it stops on that no open pull request covers.
|
||||
6. **If the run stops on nothing,** make the stage's ten-run gate check and post it on the ladder issue with `needs-human`.
|
||||
|
||||
An agent stops and labels `needs-human` whenever it meets a decision that is not its to make: a decision gate, a licence or provenance question, a rule change, or two sources of truth that disagree.
|
||||
|
||||
## Working one blocker
|
||||
|
||||
```text
|
||||
run → signature → draft pull request (the claim) → evidence → smallest fix + test → runs before and after → ready → someone else reviews and merges
|
||||
```
|
||||
|
||||
1. **Claim with a draft pull request.** Check open pull requests for the signature. If nobody has it, branch from `origin/main`, push, and open a draft titled `[<Stage>] <signature>`. A draft with no push for 3 days may be taken over.
|
||||
2. **Is it already someone's?** Before investigating any problem the game shows (the picked blocker or one met along the way), search open and merged pull requests and open issues for its log event, stub symbol, error code and the files a fix would touch. If an open pull request covers it, check that branch out, run with it and work there. If a merged one does, sync and run again. On 2026-11-30 a session fixed physical-page DirectStorage requests in parallel with an open pull request for the same problem (#707), and found the overlap only afterwards.
|
||||
3. **Evidence before code.** Find what the build asked for and what it got: the run report, then the diagnostics (thread sampler, fault context, call trace). Check the contract against the GDK where the GDK covers it. Do not guess a fix.
|
||||
4. **Smallest fix.** Only what removes this blocker. A new cross-DLL export still goes through an `[ABI]` pull request first.
|
||||
5. **A test for the contract.** It fails without the fix and passes twice in a row in the same bottle.
|
||||
6. **Proof.** Runs before and after on your machine, every run reported. Say which start-up path your runs took: another machine may take a different one.
|
||||
7. **Mark it ready** with the five-part description. Then stop: the next "work" starts from the top of the list.
|
||||
|
||||
If the blocker turns out to be more than you can finish, close the draft and file a handoff issue.
|
||||
|
||||
### Pull-request description
|
||||
|
||||
Five parts and nothing else:
|
||||
|
||||
1. **Blocker:** `Closes #<issue>` and one sentence on what the build did.
|
||||
2. **Contract:** what the console does, and which source says so (ranks below).
|
||||
3. **Fix:** what changed.
|
||||
4. **Test:** the conformance test, and that it fails without the fix.
|
||||
5. **Proof:** before and after over ten runs (for example "status-5 exits: 4/10 → 0/10"), with the machine and the `main` commit.
|
||||
|
||||
### Review
|
||||
|
||||
The reviewing agent checks out the branch, runs the Section 8 commands and the new test, confirms the test fails without the fix, and reads the proof. It does not repeat the ten runs unless the proof looks wrong.
|
||||
|
||||
**Deep review** — re-deriving the contract from its source, by an agent working for a different person than the author — is required only for:
|
||||
|
||||
- a change under `abi/`;
|
||||
- a new or changed translator instruction class;
|
||||
- a contract from source rank 4 or 5;
|
||||
- anything touching the sandbox, security or licensing.
|
||||
|
||||
**Merging.** The author's agent never merges its own person's pull request. Any other collaborator's agent merges once the pull request is approved and green. A pull request that is green and unreviewed after one working day gets the label `needs-human`.
|
||||
|
||||
**Stacks.** A pull request is based on `main`. One level of stacking is allowed when a fix truly needs an unmerged one; deeper stacks are not.
|
||||
|
||||
## Run protocol
|
||||
|
||||
A run counts only if it is made this way. The launcher does it; agents do not hand-roll it.
|
||||
|
||||
Until the launcher does, the offline-run procedure and the diagnostic switches are in [Target-Build Bring-Up: Development Cycle and Review](../testing/target-build-review.md). Where that document and this one differ on roles, the order of work or review, this one replaces it once accepted.
|
||||
|
||||
- **Build:** current `main`, or `main` plus exactly the one branch under test.
|
||||
- **Sandbox:** the offline runner, which refuses to start unless a probe confirms outbound network is blocked.
|
||||
- **Bottle:** one per agent session, created by the launcher and named for the session. Never a shared one.
|
||||
- **One game at a time per machine.** The launcher takes a machine-wide lock; a second run waits.
|
||||
- **Disk:** at least 10 GB free, checked before the run; the session's scratch bottle and build directory are removed afterwards.
|
||||
- **Count and length:** ten runs, each as long as the stage needs (five minutes for Boot).
|
||||
- **Machine:** the report states chip and memory. Gates are judged on 16 GB machines.
|
||||
|
||||
**The run report** is generated, not written. Per run:
|
||||
|
||||
- outcome: frames presented, clean timeout, early exit with its status, or hang;
|
||||
- the start-up path taken;
|
||||
- every unimplemented call reached, counted;
|
||||
- every fault inside a BetterXen module;
|
||||
- pipelines drawn with: translated, passed through, skipped;
|
||||
- on a stall: every thread's stack.
|
||||
|
||||
It ends with a ten-run summary and a list of **signatures**, the strings pull requests and handoff issues are titled with.
|
||||
|
||||
**What exists today** (#664): `bx-cli report <log.jsonl>...` produces the per-run report and the summary with signatures from run logs, and `bx-cli run` records how each run ended. Not yet in the launcher: the offline runner, per-session bottles, the machine-wide lock, thread stacks on a stall, and stall detection itself (frames are logged at powers of two, so a log cannot yet tell a stall from slow presentation).
|
||||
|
||||
## Order of lookup
|
||||
|
||||
The ranks below say how much a source can be trusted. They are not the order to look in. Look in the cheapest place that can answer first:
|
||||
|
||||
1. **The GDK** headers and documentation, for the contract itself.
|
||||
2. **The Ghidra results and the module's strings**, for how the build calls something, with what, and what it does with the answer: seconds, no GPU, no run. `bx-cli report` prints each unimplemented call's callers as `module+offset`; `bx-cli ghidra <module+offset>` names the function and its decompiled file.
|
||||
3. **A run**, only for what depends on run-time state: values, timing, which branch was taken. Prefer the cheapest run that answers, for example reading a module's own debug output, before writing new diagnostics.
|
||||
4. **New diagnostic code**, when nothing above can answer.
|
||||
|
||||
Runs take minutes each and share the machine's one GPU with every other session, so a question the Ghidra results answer is never a reason to run the build.
|
||||
|
||||
## Sources of truth
|
||||
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request. A rank says how far a source can be trusted, not where to look first ([Order of lookup](#order-of-lookup)).
|
||||
|
||||
| Rank | Source | Notes |
|
||||
| --- | --- | --- |
|
||||
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
|
||||
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
|
||||
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
|
||||
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | Consulted first for how the build calls something; ranked below observation because a run shows what actually happened. Local only. |
|
||||
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
|
||||
|
||||
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
|
||||
|
||||
## Evidence and references
|
||||
|
||||
- **Private evidence store.** Run logs, dumps, disassembly and captures go in a folder outside the repository on the collaborator's machine. Issues and pull requests carry counts, sizes, call shapes and the contract learned.
|
||||
- **Reference images** (needed from the Picture stage on): a collaborator's own capture from a real console running the same content, or published footage. They live in the private store; a pull request says "matches reference screen 3".
|
||||
|
||||
## Finding blockers once the game runs
|
||||
|
||||
From the Menus stage on, the build no longer stops by itself at the next missing piece: someone has to take it somewhere. Agents are poor players, so the method does not depend on an agent holding a controller. BetterXen owns both ends of the build's contact with the machine — input (`GameInput`) and graphics (`d3d12_xs`) — and records and replays both.
|
||||
|
||||
**1. People play; the launcher records.** A play session with recording on saves the input stream with timestamps and the save files it started from. A hotkey marks a moment ("texture wrong here", "audio cut out"). A crash or hang needs no mark: the run report has it.
|
||||
|
||||
**2. Agents replay routes.** A route is a starting save plus a short recorded input stream (about two minutes: load, walk somewhere, enter a vehicle). An agent replays it through the input shim and compares the run with the last good one. Replays drift, because the build is not deterministic, so routes stay short and start from a save. Each route is a regression test, run ten times like any gate.
|
||||
|
||||
**3. Frame capture and offline replay.** The graphics layer records every call the build makes for one frame, with the data it referenced. The frame is then redrawn without the build running, in seconds and identically every time. An agent fixing a picture bug replays that frame after each change instead of booting and travelling to the spot again.
|
||||
|
||||
**How a problem is recognised,** from most to least reliable without a person:
|
||||
|
||||
| Signal | Catches | Needs a person |
|
||||
| --- | --- | --- |
|
||||
| Crash, hang, early exit | Stability | No |
|
||||
| Run-report counters: skipped draws, stubbed shader instructions, unimplemented calls, failed storage requests | Missing pieces, even when the picture looks plausible | No |
|
||||
| Frame compared with the last good capture of the same route | Regressions | No |
|
||||
| Frame compared with a console reference image | Wrong rendering | To supply the reference |
|
||||
| An agent looking at a capture | Obvious breakage: black screen, missing geometry, garbage textures | No; subtle errors are missed |
|
||||
| A person's mark during play | Feel, audio sync, input lag, anything that "looks off" | Yes |
|
||||
|
||||
Findings become pull requests (or handoff issues, when they cannot be fixed at once) with signatures of the same kind: `route 7: crash at 1:40 (3/10)`, `capture 12: 340 draws skipped`, `capture 12: differs from reference in the sky`. The order of work does not change.
|
||||
|
||||
Whether the game is good to play is a question only people answer. Their time goes into playing and marking, never into reproducing or bisecting.
|
||||
|
||||
## What people do
|
||||
|
||||
People are needed for exactly four things, each marked `needs-human`:
|
||||
|
||||
1. confirming a stage change after a gate passes;
|
||||
2. deciding a decision gate (for example the graphics back end);
|
||||
3. licence, provenance and legal questions;
|
||||
4. changing these rules.
|
||||
|
||||
Everything else is the queue.
|
||||
|
||||
## The first handoffs
|
||||
|
||||
When this method started, the first target-build runs had already found more than could be fixed at once. Those were filed as issues #664–#680. The ones that were only "a blocker with a fix on the way" close as their pull requests merge; the ones that remain open as handoffs are the larger pieces: the run tooling, the D3DMetal capability checks, the translator, the reference images and the record-and-replay tools.
|
||||
@@ -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. |
|
||||
@@ -24,5 +25,6 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
|
||||
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
|
||||
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
|
||||
| Console texture swizzle layouts (`xg_xs`) | Mesa `src/amd/addrlib` at `0b97dcdd` (MIT) | **Vendor unmodified** (#756) | gfx10 layouts for a swizzle mode a title requests. The copy lives at `shims/xg_xs/third_party/addrlib`. Two files lack an SPDX line; see the registry and `THIRD_PARTY_NOTICES.md`. The GDK `xg_xs.dll` stays a local comparison reference and is not redistributed. |
|
||||
|
||||
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
|
||||
@@ -0,0 +1,128 @@
|
||||
# Console compute shader entry ABI (probe results)
|
||||
|
||||
Recorded 2026-11-28 (CLAIM-XBOX-CS-ENTRY-ABI). This page lists facts derived from the assembly listing of Microsoft's Series X|S PIX shader compiler (its NewBE code generator), used under an authorization Microsoft gave the project for its GDK material (see "Provenance"). The compiler, its output and the GDK files are not in this repository. No listing, binary or documentation text is reproduced. Only the observations below are. It complements [RDNA 2 notes](rdna2.md), which cover AMD's public ISA, and [Shader containers](shader-containers.md).
|
||||
|
||||
What this is:
|
||||
- **Measured:** what the compiler emitted for eleven compute shaders the project wrote (p00–p10 below), compiled on one host: Apple M5, macOS 27.2.1, CrossOver 26.3 (26.3.0.39832), GDK 2026.10 (10.0.26100.9661).
|
||||
- **Inferred:** what each register holds. The interpretations below are read from the generated code. They agree with the user-SGPR, thread-group-ID and thread-ID fields of AMD's publicly documented `COMPUTE_PGM_RSRC2` register, which the compiler reports for each shader.
|
||||
|
||||
What this is not: a console run, a description of the ACCC/FSPX container, a description of the ACO backend that produces the code in ACCC containers (see "Root buffer access"), or anything about graphics stages. The compiler used here writes plain DXIL objects. The console code appears only in its assembly listing, so how that code is stored in an ACCC container is still unknown (CLAIM-XBOX-ISA-ABI).
|
||||
|
||||
## Method
|
||||
|
||||
Each probe is a `cs_6_5` compute shader (`cs_6_6` for the 64-bit atomic) with an explicit `[RootSignature]`. The compiler needs a root signature to generate console code. It reported "GFX10" for the target. The probes change one thing at a time:
|
||||
|
||||
| Probe | Root signature | Shader |
|
||||
| --- | --- | --- |
|
||||
| p00 | `SRV(t0), SRV(t1), UAV(u0)` | `o[i] = a[i] + b[i]`, 64 threads |
|
||||
| p01 | `RootConstants(num32BitConstants=4, b0), UAV(u0)` | uses all four constants |
|
||||
| p02 | `CBV(b0), UAV(u0)` | reads two constants |
|
||||
| p03 | `DescriptorTable(SRV(t0, numDescriptors=2)), DescriptorTable(UAV(u0))` | p00 through tables |
|
||||
| p04 | `DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), UAV(u0)` | `Texture2D.SampleLevel` |
|
||||
| p05 | `UAV(u0), SRV(t0), SRV(t1)` | p00 with the parameters reordered |
|
||||
| p06 | `UAV(u0)` | `[numthreads(8,8,1)]`, writes group and thread IDs |
|
||||
| p07 | `SRV(t0), UAV(u0)` | `WaveActiveSum` |
|
||||
| p08 | `SRV(t0), UAV(u0)` | 256 bytes of `groupshared` and a barrier |
|
||||
| p09 | `UAV(u0)` | 64-bit `InterlockedAdd` |
|
||||
| p10 | `RootConstants(num32BitConstants=20, b0), UAV(u0)` | sums all 20 constants |
|
||||
|
||||
## Observations
|
||||
|
||||
**Wave size.** Every probe was compiled for 64-lane waves: the compiler reported wave32 as disabled. In p07 `WaveActiveSum` became a full 64-lane reduction that combines the two 32-lane halves and uses a 64-bit execution mask. D3DMetal 4.0b3, the version measured in [D3DMetal GPU limits](d3dmetal-gpu-limits.md), runs 32-lane waves only; D3DMetal 3.0 was not measured. None of the probes declares a wave size, so wave64 is what this compiler generates by default, and console-compiled compute code has to be treated as wave64 unless it declares otherwise, not only when a shader declares `WaveSize(64)`.
|
||||
|
||||
**Root arguments in registers.** Root-signature data starts at `s4`, in root-parameter order. p05 moves the registers with the parameters.
|
||||
- A root constant takes one SGPR (p01: `s4`–`s7`).
|
||||
- A root CBV, SRV or UAV takes two SGPRs, a 64-bit GPU address (p00: `s4:s5`, `s6:s7`, `s8:s9`).
|
||||
- A descriptor table takes one SGPR, a 32-bit pointer. The shader clears the upper half itself (p03, p04).
|
||||
- The thread-group IDs follow the root data, x before y (p00: `s10`; p06: `s6`, `s7`). Thread IDs arrive in `v0` (x) and `v1` (y), as the reported thread-ID count indicates.
|
||||
|
||||
**Overflow.** `s0`–`s3` come before the root data. When the root data does not fit in user SGPRs (p10: 20 constants and a UAV), only those four are passed, and `s0:s1` holds the address of the root data in memory. The shader loads the constants from offset 0 and the UAV address from offset `0x50`, which is root dword 20. Whether `s0:s1` points at the same data when the arguments also fit in registers was not tested.
|
||||
|
||||
**Root buffer access.** For a root SRV, UAV or CBV, the shader builds the buffer descriptor itself from the root address:
|
||||
- **Stride:** in word 1, the `STRIDE` field (bits 29:16 in the public GFX10 layout), taken from the element type: 4 bytes for `uint`, 8 for `uint64_t`, 16 for the root CBV.
|
||||
- **Record count:** `-1` (`NUM_RECORDS` = 0xFFFFFFFF). With the `OOB_SELECT` below, the only bounds check compares the index against `NUM_RECORDS`, so it never fires: accesses through root descriptors are effectively not bounds-checked.
|
||||
- **Word 3:** the constant `0x11014fac` in every probe. Decoded with the public GFX10 buffer-descriptor layout (Mesa `src/amd/common/ac_descriptors.c` / `gfx10-rsrc.json`, LLVM `SIDefines.h`): destination swizzle X, Y, Z, W; `FORMAT` 20 (`32_UINT`); `RESOURCE_LEVEL` 1; `OOB_SELECT` 1 (the index is checked against `NUM_RECORDS`); `TYPE` 0 (buffer). These observations describe the NewBE path only. The ACO path (`xdxc`), which produces the code in the ACCC containers titles ship, generates different code for the same HLSL: its word 3 is `0x31016fac`, which decodes the same way except `FORMAT` 22 (`32_FLOAT`) and `OOB_SELECT` 3 (raw), two bits apart (`0x20002000`). Of these probes' facts, only the root UAV address in `s[4:5]` has been checked to agree on ACO. That comparison is recorded in the shader corpus PR [#650](https://github.com/MacosPorters/betterxen/pull/650) (open); until it lands, treat ACO agreement beyond that as unverified.
|
||||
|
||||
**Descriptor tables.** Descriptors are loaded from the table address:
|
||||
- buffer descriptors 32 bytes apart (p03 loads at offsets `0` and `0x20`);
|
||||
- a texture descriptor of 32 bytes and a sampler descriptor of 16 bytes (p04).
|
||||
|
||||
For each such load, the compiler also reported the instruction offset and the HLSL binding it came from: class, register, space and resource kind.
|
||||
|
||||
**Other.** p08 uses LDS (`ds_write_b32`, `ds_read_b32`), and its size shows in the reported LDS allocation. p09 is a native `buffer_atomic_add_x2`. The shader hash from the container's `HASH` part is embedded at the start of the generated code.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Branch D2** ([ADR 0008](../adr/0008-m2-shader-format-gate.md)) gains a candidate compute entry ABI: where root constants, root descriptors, table pointers and IDs are, and how buffer descriptors are formed, as the NewBE path generates them. It is not accepted for D2 until it is reproduced independently, and checked against the ACO code that ACCC containers carry.
|
||||
- **Binding recovery** may not need data-flow analysis if ACCC containers carry the same per-load binding table. That depends on the container format, which is still unknown.
|
||||
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
|
||||
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
|
||||
|
||||
## 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:** 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.
|
||||
- **Overflow threshold:** the probes jump from 6 root dwords to 22. The exact cutoff, and whether overflow is always all-or-nothing, are unmeasured.
|
||||
- **`s0`–`s3`:** what they hold when root data fits in registers.
|
||||
- **One compiler build, one host:** a different GDK version may differ.
|
||||
|
||||
## Provenance
|
||||
|
||||
- **Source:** facts were read from listings that Microsoft's licensed Series X|S shader compiler produced for shaders the project wrote. That compiler is not public, so none of this can be checked against a public source, except the descriptor decode above.
|
||||
- **Authorization:** the maintainer (@atesahmet0) has stated that Microsoft's authorization for the project's use of its GDK material covers publishing derived observations like these in this repository. The material itself (the compiler, its listings and binaries, and the GDK documentation) is never committed. The authorization record is held privately (the process is proposed in [#661](https://github.com/MacosPorters/betterxen/pull/661)).
|
||||
- **Reproduction:** only a contributor with the same authorization can reproduce these observations. That reproduction has not happened yet, so the claim is recorded as class U: unestablished by public sources, with an authorized observation behind it.
|
||||
@@ -108,7 +108,7 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
|
||||
| Check | Outcome |
|
||||
| --- | --- |
|
||||
| `device.shader_model` | 6.6 (the fixture skips with exit 77 below 6.6) |
|
||||
| `device.shader_model` | 6.6 |
|
||||
| `wave.reported` | `WaveOps=1`, lane count min 32, max 32 |
|
||||
| `wave.control` | ran at width 32, lanes a permutation within each wave (required: pass) |
|
||||
| `wave.wavesize64` | created but not run (output still sentinel) |
|
||||
@@ -118,9 +118,35 @@ independently reproduced, not CrossOver 26.3, and not an Xbox hardware result.
|
||||
| `lock64.cap64` | 108, 96 and 108 of 512 updates dropped (values not compared) |
|
||||
| `lock64.cap1024` | 0 of 512 dropped, 16/16 values exact (required: pass) |
|
||||
|
||||
**Exit codes.** The fixture exits **0** with every required check passed, **1** on a failed
|
||||
required check, and **77** with a `SKIP: <reason>` line when `d3d12.dll`, its exports, device
|
||||
creation, or shader model 6.6 is unavailable. 77 is not a pass; see the exit-status section of
|
||||
[`tests/conformance/README.md`](../../tests/conformance/README.md#exit-status-pass-fail-and-unavailable)
|
||||
for a recording recipe. Through `bx-cli run` the guest status is returned unchanged.
|
||||
|
||||
Still to do for the issue's validation requirement: an independent run on CrossOver 26.3
|
||||
(D3DMetal 3.0) by another contributor.
|
||||
|
||||
## Capability checks for translated console shaders (#671)
|
||||
|
||||
A translator of console code needs four things from D3DMetal. Each has a synthetic check with
|
||||
one of three results: *runs correctly*, *workaround* (the translator can get the console's
|
||||
answer another way) or *blocked*. The checks talk to the host `d3d12.dll` directly, so they
|
||||
measure D3DMetal, not BetterXen. Expected values are computed on the CPU.
|
||||
|
||||
Machine: Apple M5 (32 GB), macOS 27.2.1, CrossOver 26.3, D3DMetal; each check run twice in a
|
||||
row with the same result.
|
||||
|
||||
| Need | Check | Result | What was measured |
|
||||
| --- | --- | --- | --- |
|
||||
| Descriptors fetched by index (SM 6.6 dynamic resources) | `test_d3dmetal_translator_caps` `heap_index` | **runs correctly** | Resource binding tier 3. A UAV, a raw SRV, a typed SRV, a texture and a sampler, all taken from the descriptor heaps by index (`ResourceDescriptorHeap`, `SamplerDescriptorHeap`, root signature flags `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED`): all 65 values correct. |
|
||||
| 64-lane waves | `test_d3dmetal_translator_caps` `wave64`, with `test_d3dmetal_gpu_limits` `wave` | **workaround** | The host runs 32-lane waves (`WaveLaneCountMin = Max = 32`), and a `[WaveSize(64)]` kernel is created but not run (above). A 64-thread group standing for one 64-lane wave gives the 64-lane ballot, exclusive prefix sum, read-lane and sum on all 64 lanes, both through groupshared memory and through the host's own wave operations merged across its two waves. |
|
||||
| 64-bit atomics on typed resources | `test_d3dmetal_gpu_limits` `atomic64`, `lock64` | **workaround** | D3DMetal reports `AtomicInt64OnTypedResourceSupported = 1` and `AtomicInt64OnDescriptorHeapResourceSupported = 1`, but kernels using 64-bit atomics, on typed and on raw resources, are created and not run: even their plain stores are missing. The per-texel lock over 32-bit words with a retry cap of 1024 is exact (0 of 512 updates dropped); with a cap of 64 it drops updates. A translator must not trust the reported support. |
|
||||
| Amplification and mesh shaders | `test_d3dmetal_translator_caps` `mesh` | **runs correctly** | `D3D12_MESH_SHADER_TIER_1` (enum value 10). An amplification shader passes a payload to two mesh groups through `DispatchMesh`; each draws half of a 4x4 target with a pixel shader: all 16 pixels correct. |
|
||||
|
||||
No need is *blocked*, so no ADR is required by #671. The shaders are regenerated with
|
||||
`tests/conformance/test_d3dmetal_translator_caps/shaders/compile.sh` (same DXC release as below).
|
||||
|
||||
## Unverified reports (not evidence)
|
||||
|
||||
Reported on #453 from local VIctory-macOS-based builds running a commercial title on one
|
||||
|
||||
@@ -84,3 +84,97 @@ Identification is not execution. `xenora shaders coverage` reports forms
|
||||
discovered in metadata against forms the semantic decoder accepts
|
||||
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
|
||||
per form remains in `docs/status.toml`.
|
||||
|
||||
## 64 KiB swizzle (`SW_64KB_S`) — public sources (#505)
|
||||
|
||||
`xg_xs.dll` implements `SW_64KB_S` tile addressing for `TEXTURE2D`, one array
|
||||
slice and one mip, over the element sizes the RB+ tables specify: 32-bpp RGBA8
|
||||
(4-byte elements) and the BC family — BC1/BC4 with 8-byte blocks and
|
||||
BC2/3/5/6H/7 with 16-byte blocks, where one "texel" element is a 4x4 block and
|
||||
`elemLog2 = log2(block_bytes)`. At 32 bpp the two public sources below agree
|
||||
bit-for-bit, which is why this is the mode implemented first; the 8- and 16-byte
|
||||
rows come from AddrLib alone.
|
||||
|
||||
**Microsoft, `D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE`** (public, no NDA):
|
||||
<https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_texture_layout>.
|
||||
The page gives the 32-bpp masks `xBytesMask = 0xAA8F` and `yMask = 0x5570`,
|
||||
combined with `_pdep_u32`. It states that tail-mip packing is **adapter-specific**,
|
||||
which is why only the single-mip case is implemented. It has no `D` or `R` variant.
|
||||
|
||||
**AMD AddrLib (MIT)** — the authoritative public implementation, in both
|
||||
[Mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib)
|
||||
and [AMD PAL](https://github.com/GPUOpen-Drivers/pal/tree/dev/src/core/imported/addrlib)
|
||||
(`SPDX-License-Identifier: MIT`, AMD copyright; PAL `LICENSE.txt` is MIT):
|
||||
|
||||
- `src/amd/addrlib/inc/addrtypes.h` — `AddrSwizzleMode`: `ADDR_SW_64KB_S` = 9,
|
||||
`_D` = 10, `_R` = 11 (Reserved on GFX10).
|
||||
- `src/amd/addrlib/src/gfx10/gfx10SwizzlePattern.h` — `GFX10_SW_64K_S_PATINFO`
|
||||
and `GFX10_SW_64K_S_RBPLUS_PATINFO`, plus the `GFX10_SW_PATTERN_NIBBLE01/2/3/4`
|
||||
tables. The RB+ variant is used because `gfx1030` is Navi2x.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.h` — `GetSwizzlePatternFromPatternInfo`,
|
||||
`IsInMipTail`.
|
||||
- `src/amd/addrlib/src/gfx10/gfx10addrlib.cpp` — `GetSwizzlePatternInfo`,
|
||||
`HwlComputeSurfaceAddrFromCoordTiled`, `ComputeSurfaceAddrFromCoordMacroTiled`.
|
||||
- `src/amd/addrlib/src/core/addrlib2.cpp` — `ComputeThinBlockDimension`,
|
||||
`Block256_2d`.
|
||||
|
||||
There is **no** standalone GPUOpen `addrlib` repository (404). The public
|
||||
[RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf)
|
||||
only names a 5-bit "SW mode" field in the T# descriptor (bits 120:116) and does
|
||||
not define the patterns.
|
||||
|
||||
### S versus D versus R
|
||||
|
||||
- **S and D are not interchangeable.** At 32 bpp RB+, D uses nibble01 index 39
|
||||
(`[0,0,X0,X1,Y0,Y1,X2,Y2]`) while S uses index 2
|
||||
(`[0,0,X0,X1,Y0,Y1,Y2,X2]`) — address bits 6 and 7 swapped.
|
||||
- **`SW_64KB_R` has no public GFX10 form.** Mesa's `SwizzleModeTable` marks
|
||||
`ADDR_SW_64KB_R` (enum 11) as Reserved; the render-target mode is
|
||||
`ADDR_SW_64KB_R_X`, whose pipe/packer XOR depends on the console
|
||||
`GB_ADDR_CONFIG`, which is not public.
|
||||
|
||||
### Xbox `XG` tile modes are NDA
|
||||
|
||||
`scarlett-tex-layouts` returns HTTP 200 with only the membership gate; all
|
||||
`/windows/win32/api/xg/*` paths 404. The numeric `XG_SWIZZLE_MODE` values are
|
||||
not public. BetterXen's earlier local `BX_XG_LAYOUT_*` constants and clean-room XG
|
||||
interface have been retired: `xg_xs.dll` now follows the documented XG contract
|
||||
titles call, with values from the authorized GDK documentation recorded as derived
|
||||
facts in `shims/xg_xs/xg_xbox.cpp`.
|
||||
|
||||
### Element sizes and the derived masks
|
||||
|
||||
For a 64 KiB tile the intra-tile byte offset of element (x, y) is
|
||||
`pdep(x, x_mask) | pdep(y, y_mask)`, where x and y are **block** indices (one
|
||||
4x4 block for BC, one texel for 32 bpp). The masks were expanded by hand from
|
||||
`GFX10_SW_PATTERN_NIBBLE01/2/3` at the patinfo indices
|
||||
`GFX10_SW_64K_S_RBPLUS_PATINFO` selects for each `elemLog2`:
|
||||
|
||||
| block bytes | formats | `elemLog2` | x mask | y mask | tile (blocks) |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 4 | R8G8B8A8_* | 2 | `0xAA8C` | `0x5570` | 128 x 128 |
|
||||
| 8 | BC1, BC4 | 3 | `0xAAC8` | `0x5530` | 128 x 64 |
|
||||
| 16 | BC2, BC3, BC5, BC6H, BC7 | 4 | `0xAAC0` | `0x5530` | 64 x 64 |
|
||||
|
||||
At 32 bpp the x mask `0xAA8C` is Microsoft's public `xBytesMask` `0xAA8F` with
|
||||
the two intra-texel byte bits cleared (`0xAA8F & ~0x3`), and the y mask matches
|
||||
`0x5570` exactly. The 8- and 16-byte rows have no D3D12 page to cross-check
|
||||
against; they are AddrLib-only, which is stated in the PR risks. All three rows
|
||||
were checked to be bijections over their 64 KiB tile (16384 / 8192 / 4096
|
||||
distinct offsets, each block-aligned and inside the tile).
|
||||
|
||||
### Verification
|
||||
|
||||
The three masks above were expanded and their bijectivity checked against an
|
||||
independently written `pdep` reference, outside the shim. `test_xg_xbox.exe`
|
||||
(which replaced the retired `test_xg_xs.exe`) does not read its expected values
|
||||
back from the shim:
|
||||
- at 32 bpp it compares every offset of a one-tile texture with the public D3D12
|
||||
standard swizzle, and checks the offset -> texel inverse and a copy round trip;
|
||||
- at 8 and 16 bytes per element (the 8-byte case as BC1 blocks) it checks that
|
||||
the offsets are a bijection of aligned slots inside the 64 KiB tile;
|
||||
- it checks that the 16 texels of a BC block share one byte offset.
|
||||
|
||||
Requested modes the shim does not implement (`SW_64KB_D`, multi-tile, multi-mip)
|
||||
are laid out linearly and reported as `LINEAR`. Synthetic evidence only; no
|
||||
Xbox-hardware claim.
|
||||
@@ -14,7 +14,9 @@ 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. |
|
||||
| Mesa addrlib | [mesa/mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/0b97dcdd9424fce130054e1972a610b765644003/src/amd/addrlib) | tag `mesa-25.2.0`, commit `0b97dcdd9424fce130054e1972a610b765644003` | MIT, per file, with the exception below | Vendored, unmodified, into `shims/xg_xs/third_party/addrlib` for console swizzle layouts (#756) | 42 of 44 files carry `SPDX-License-Identifier: MIT`. `src/core/addrswizzler.cpp` and `addrswizzler.h` carry an AMD 2024 copyright and "All rights reserved" and no SPDX line in this version; AMD added `SPDX-License-Identifier: MIT` to both upstream in Mesa commit `d778ede72` (2026-04-17, MR 40958). `meson.build` (SPDX MIT) compiles them, and gfx10 includes them, so they are kept unmodified. Accepted for this use by the task that vendors it; the two files without an SPDX line are called out in `THIRD_PARTY_NOTICES.md`. |
|
||||
|
||||
## Built and run for M1-D2 (#417)
|
||||
|
||||
@@ -24,7 +26,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)
|
||||
|
||||
|
||||
+85
-20
@@ -1,6 +1,6 @@
|
||||
# BetterXen Roadmap
|
||||
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). Track ownership and parallel workflow rules live in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); Wave 1 contributor issues live in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
**This is the single authoritative active roadmap.** Strategic decisions are recorded in [ADR 0005](adr/0005-crossover-hybrid-direction.md) (CrossOver-based hybrid direction) and [ADR 0006](adr/0006-retire-in-tree-native-workspace.md) (retiring the paused native-first workspace to Git tag `native-first-final`). How the team and its agents work is in [docs/process/working-method.md](process/working-method.md). Track (directory) ownership is in [docs/architecture/parallel-tracks.md](architecture/parallel-tracks.md); the completed Wave 1 issues are in [docs/issues/wave-1-backlog.md](issues/wave-1-backlog.md).
|
||||
|
||||
## Direction
|
||||
|
||||
@@ -19,7 +19,7 @@ External Foundation (user-installed, never bundled):
|
||||
Apple Silicon: ARM64, Metal, unified memory
|
||||
```
|
||||
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. Progress is measured strictly by reproducible synthetic conformance tests and recorded verification evidence — never by commit counts or unverified compatibility claims.
|
||||
This is an active engineering stack, **not a verified commercial Xbox game compatibility layer**. The product goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. From the Boot stage on, progress is measured by how far that build gets in repeated, recorded runs ([working method](process/working-method.md)); every contract a fix introduces is also pinned by a synthetic conformance test. Progress is never measured by commit counts or unverified compatibility claims.
|
||||
|
||||
Priorities, in order: practical compatibility, correctness, stability, observability, Apple Silicon performance, and long-term maintainability.
|
||||
|
||||
@@ -35,34 +35,99 @@ Priorities, in order: practical compatibility, correctness, stability, observabi
|
||||
|
||||
---
|
||||
|
||||
## Milestones (M0 → M6)
|
||||
## Foundation and stages
|
||||
|
||||
| Milestone | Objective | Exit Gate | Status |
|
||||
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests. They built the foundation, and they also showed the limit of that approach: with M1 verified complete, the target build still stopped at more than a dozen missing or wrong contracts that no synthetic test had asked for. From here on, the roadmap is a ladder of **stages the target build reaches**, observed in runs every collaborator can repeat. Synthetic conformance tests stay mandatory for every contract a fix introduces; they no longer define progress.
|
||||
|
||||
### Foundation (history)
|
||||
|
||||
| Milestone | What it established | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & cross-build** | Track layout, frozen `.def`/header contracts, env-isolated `bx-cli`, export verifier, live smoke tests | **Verified complete (#406)** |
|
||||
| **M1 — Startup shims to `D3D12XboxCreateDevice`** | Wave 1 shims across Tracks A–F and the combined synthetic boot fixture | **Verified complete (Milestone #17)** |
|
||||
| **M2 — Synthetic first frame & shader format gate** | `PresentX` through D3DMetal with pixel readback; Xbox-layout D3D12 objects (ADR 0009); the shader format question | **Closing.** Remaining: amend ADR 0008 to select Branch D2. The target build supplies console-compiled code only: shader containers whose `DXIL` part carries no bitcode, and serialized pipelines. |
|
||||
|
||||
### The stages
|
||||
|
||||
Every gate below is measured the same way ([working method](process/working-method.md#run-protocol)): the current `main`, the offline sandbox, a contributor's own bottle, **ten runs**, on a 16 GB Apple Silicon Mac. A gate that says "10/10" means ten of ten. Stages have names, not numbers: exactly one is current, and blocker issues carry its label (`stage: boot`, `stage: picture`, …).
|
||||
|
||||
| Stage | The target build… | Exit gate | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | Establish 6-track directory layout (`abi/`, `launcher/`, `shims/`, `shader-transpiler/`, `tests/conformance/`), frozen `.def`/header contracts, env-isolated `bx-cli`, strict PE Export Directory verifier, and live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb.exe`, `test_shim_exports.exe`) | ARM64 Rust checks green; all 17 PE32+ DLLs (16 mingw-w64 C++ shims + the Rust `bx_shader_bridge.dll`) pass strict export & zero-MinGW-dep verification; both synthetic EXEs pass live under CrossOver + Rosetta 2 | **Verified complete (`#406`)** |
|
||||
| **M1 — Startup Shims to `D3D12XboxCreateDevice`** | Complete Wave 1 parallel issues across Tracks A–F: full `clwb` + crash register VEH, `xmem` core + physical/scatter page engine + Lockhart cap, `XCRDAPI` async file I/O MVP, `d3d12_xs` auto-logging COM proxy over Wine `d3d12.dll`, `xg_xs` linear-compatible layout MVP, `dxbc-accc` C ABI hook + `d3dmetal-native` evaluation, offline `xgameruntime` + dynamic loader exports, non-blocking `AcpHal`/`xapu`/`chad` stubs, `GameInput` `@1`, supervised `bx-cli run`, ADR 0007, and combined synthetic integration boot fixture | All Wave 1 conformance binaries pass under CrossOver 26.3 + Rosetta 2; combined `test_integration_boot.exe` passes (19 pass, 2 ADR-0007 pending, 0 fail) | **Verified complete (Milestone #17, 16/16)** |
|
||||
| **M2 — First Rendered Frame & Shader Format Gate** | Clear dynamic GDK startup (`system32` staging + public GDK COM `QueryApiImpl` dispatch), implement `d3d12_xs` swapchain presentation (`PresentX` → `IDXGISwapChain3::Present`), integrate the shipped xmem-configured D3D12 placed heap (#464) into the first-frame fixture (#469), bridge `dxbc-accc` into Windows guests (`#445`), measure D3DMetal GPU limits (`#453`), and establish whether target runtime shader corpora use **DXIL (Branch D1)** or **console-compiled `ACCC`/`FSPX` RDNA 2 ISA (Branch D2)**. Measured translator constraints: [D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) | Synthetic D3D12 `PresentX` workload renders and verifies pixel readback through D3DMetal 3.0; M2 Gate ADR selects Branch D1 or Branch D2 | **In development (Milestone #18)** |
|
||||
| **M3 — Full Shaders, Streaming & Texture Correctness** | DirectStorage decompression, accurate RDNA 2 (`gfx1030`) `xg_xs` tile-addressing & deswizzling, full `d3d12_xs` command-list/barrier/GPUVA fidelity, and Branch D1 DXIL normalization or Branch D2 `ACCC`/`FSPX` → DXIL/MSL transpiler, within the [measured D3DMetal GPU limits](research/d3dmetal-gpu-limits.md#measured-constraints) (`WaveSize(64)` and SM 6.6 64-bit atomics not run; bounded lock emulation) | Synthetic textured/swizzled, compute, multi-queue, and compressed DirectStorage conformance suites pass | Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH4 & Upscaling** | Bridge `XboxBvhBuilder` / `ID3D12StateObject` ray tracing to D3DMetal 3.0 DXR (intercepting incompatible AMD BVH4 rehydration → live rebuild), provide PC FidelityFX / MetalFX upscaling shim, and wire full `GameInput` controller/KB/M input | Synthetic DXR + upscaled 3D scene and scripted `GameInput` conformance tests pass | Planned |
|
||||
| **M5 — Software Audio/DSP, Saves & Stability** | Replace `AcpHal`/`xapu`/`chad` stubs with software audio/DSP decoding + XAudio2_9/CoreAudio output, wire `PersistentLocalStorage`, and resolve concurrency/memory/GPU hang bugs under soak testing | Synthetic audio playback, save round-trip, and multi-hour soak benchmarks pass with bounded memory | Planned |
|
||||
| **M6 — Shader Cache, 16 GB Optimization & Polish** | Persistent disk PSO + translated-shader cache, Lockhart 16 GB unified memory pressure tuning, Metal System Trace optimization, and optional Swift launcher UI | Reproducible frame-pacing and memory-pressure receipts under [docs/testing/hybrid-workloads.md](testing/hybrid-workloads.md) | Planned |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | 10/10 runs present frames for 5 minutes; the run report lists no unimplemented call on the path taken, no fault in a BetterXen module, and no early exit | **Left** (repository owner's decision, 2026-11-30; the gate was not run under the run protocol) |
|
||||
| **Picture** | shows its first non-black screen, correctly | In 10/10 runs the first reference screen matches the reference image within the agreed tolerance; every pipeline drawn with is a translated pipeline, none is skipped | **Current** (since 2026-11-30) |
|
||||
| **Menus** | plays its opening sequence and menus with sound and input | A scripted input sequence goes from launch to the last menu before gameplay in 10/10 runs; audio is audible and in sync by the checklist; a save written in one run is read in the next | Planned |
|
||||
| **World** | loads into gameplay and keeps running | 10/10 runs enter gameplay and run 10 minutes with no crash, hang or early exit; streaming requests complete without error; memory stays inside the 16 GB profile | Planned |
|
||||
| **Fidelity** | draws its 3D scenes as the console does | The scene checklist (geometry, textures, lighting, effects, HUD) passes against the reference set at the fixed capture points; no draw or dispatch is skipped or stubbed | Planned |
|
||||
| **Playable** | is playable start to finish on every supported Mac | 30 fps or better at the tier's resolution for each chip tier; a 2-hour session with bounded memory and no hang; warm start uses the shader cache; controller and keyboard/mouse complete | Planned |
|
||||
|
||||
### Startup diagnosis
|
||||
"Reference image" and "reference set" are captures of the same content from a real console or from published footage, kept in the private evidence store, never in the repository ([working method](process/working-method.md#evidence-and-references)).
|
||||
|
||||
The product goal is to reach a frame presented by the target software. Under the current [contribution rules](../CONTRIBUTING.md), project runs use original synthetic workloads. Start with `test_integration_boot.exe` for startup and `test_veh_unhandled.exe` as a crash-logging control. Use a focused synthetic reproducer once a failing contract is identified.
|
||||
### Boot
|
||||
|
||||
Before treating either startup warning as causal, add diagnostics that record the requested DirectStorage factory IID and returned HRESULT (#483) and distinguish null, unrecognized and supported BetterXen virtual-memory configurations (#464 follow-up). On a pinned launcher, shim set and backend, repeat the synthetic case before and after a fix. Record normal exit, crash or timeout, the last completed checkpoint, and the exception thread and module offset when available. Progress means reaching the next named checkpoint in the same reproducer. Startup diagnosis and the budget fix proceed alongside the M2 exit gates.
|
||||
**Known work, all found by running the target build:**
|
||||
|
||||
### M2 first-frame acceptance and parallel memory work
|
||||
| Blocker | Effect | State |
|
||||
| --- | --- | --- |
|
||||
| `CLZERO` trapped once per 64 bytes | The frame loop stalls for tens of seconds while the build zeroes memory | Fix exists locally (the loop completes in one trap); needs a PR and a conformance test |
|
||||
| A storage worker writes into a page xmem is remapping | The build's own fault handler exits (status 5) | Bounded retry exists locally. The real fix is an atomic remap in `xmem` |
|
||||
| Missing runtime calls: `XUserDuplicateHandle`, `XAsyncRun`, `XTaskQueue` duplicate/port/composite, `XGameSaveGetContainerInfo` and its by-name variant | The build waits forever or exits (status 1) | Implemented locally; need PRs and tests |
|
||||
| Serialized-pipeline calls answered with success in null-render mode | The build never falls back to its shader containers | Decide and document: these calls fail (logged) until they are implemented |
|
||||
| One early exit (status 1) with nothing logged | 1 run in 5 | Open: needs the run report's exit capture |
|
||||
| Run tooling lives outside the repository | Nobody else can repeat a run or read its result the same way | Move the offline runner, the run report and the sampler into `launcher/` and `scripts/` |
|
||||
|
||||
- **First frame (#465, #469).** The synthetic placement criterion uses BetterXen's `BXVM` block to configure the separate D3D12-owned WRITE_BACK heap shipped in #486. On the recorded overlay, #494 copied the backbuffer before the flip, counted one host `Present`, then compared 256 RGBA8 pixels through the D3D12 mapping after waiting. The xmem sentinel shows that the original page remained separate. Visibility through the original xmem address remains an open compatibility question for M3, informed by #473. Displayed-image verification is outside this fixture's measurements. Record a single `main` commit containing the integrated presentation and fixture changes, confirm that the fixture executable built, and have someone who authored neither the fixture nor the presentation bridge verify the D3DMetal run and pixel-mismatch control. The shader gate still requires a recorded D1/D2 selection. [Fixture and receipts](https://github.com/MacosPorters/betterxen/pull/494) · [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Shader format gate (#466, ADR 0008).** D1 remains the only branch with end-to-end execution evidence, and the static scan gives it measured inputs in the target workload: 52 DXIL SM 6.5 compute containers with LLVM bitcode. The same scan makes D2 a concrete compatibility candidate rather than a hypothesis: the workload's FidelityFX upscaler component embeds 29 ACCC-only containers. Select D2 work only when a required pipeline-creation path refuses an ACCC-only container at runtime — if that refusal precedes the first presented frame, treat it as a first-frame blocker; if it appears only with upscaling enabled, track it under M4 upscaling. Two Track D parser prerequisites precede any D2 trial: extend the clean-room `FSPX` section-table layout to accept the observed tables (a maintainer provenance decision, since no public format description exists), and stop the classifier from treating a `NOBC` header-only program as executable DXIL. The first `shader_gate` record the target workload writes names the shader path its first pipeline creation actually submits. [ADR 0008](adr/0008-m2-shader-format-gate.md)
|
||||
- **Title budget (#550, #552).** Keep current allocation ownership and give xmem atomic admission authority through an ABI-first contract. The initial scope combines xmem usage with the existing charged `CreateHeap` path. Under a 512 MiB cap, an xmem allocation of 256 MiB followed by a 384 MiB heap was refused, while the reverse admitted 640 MiB. Test both orders, concurrent admission and rollback. Charge a backing allocation once across aliases. Accounting for `CreateHeap1`, committed and reserved resources, and internal buffers such as XCRDAPI staging remains an open scope decision. Placement and wrapper lifetime have separate checks (#554, #572). [Merged-base reproduction](https://github.com/MacosPorters/betterxen/pull/486#issuecomment-7209751182)
|
||||
- **M3 resource handling.** Keep explicit paths for fixed addresses, existing contents, pre-device allocations, sections/scatter and opaque textures. The draft eligibility analysis found no reliable end-to-end classifier. Resolve the `XMemVirtualAlloc` argument-count question (#518) before using graphics flags as evidence. A mapped-buffer trial is optional and opt-in, with the existing path as fallback. Require a known consumer before returning a pointer, verify its alignment and lifetime, and confirm completion on every participating queue before reusing memory for work BetterXen submits. #483 retains its DirectStorage interface scope. [Draft eligibility analysis](https://github.com/MacosPorters/betterxen/blob/7e0b515131150fec6b5117c9498b6c0faf0ca382/docs/architecture/proposals/001-unified-memory/appendix/eligibility.md)
|
||||
- **M6 optimization.** Compare the existing path with a candidate allocator or bounded pool on the same 16 GB host and backend. Check correct output for both paths across repeated matched workloads. Include cold setup, transfers, fragmentation, pending retirements, post-release footprint and whole-frame time. Require a repeatable workload benefit before choosing a default.
|
||||
**Not needed for the gate:** audio output, correct pictures, performance.
|
||||
|
||||
### Picture
|
||||
|
||||
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
|
||||
|
||||
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
|
||||
*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
|
||||
|
||||
Listed so lanes can prepare, not as a commitment to order. Each item is confirmed by a run before work starts on it.
|
||||
|
||||
| Stage | Known work | Main unknown |
|
||||
| --- | --- | --- |
|
||||
| **Menus** | XMA decoding and audio output through the audio coprocessor contract; `GameInput` devices; speech/accessibility provider; saves round trip | What the build waits for between sign-in and its first screen |
|
||||
| **World** | DirectStorage page destinations, BCPack and swizzle options; XG tiling modes beyond linear; atomic page remapping; the Series S memory profile as the 16 GB default | Streaming behaviour under memory pressure |
|
||||
| **Fidelity** | Mesh/amplification pipelines; indirect draws with console argument types; rectangle lists; the unimplemented command-list state calls; upscaler substitute (FSR 3.1 or plain scaling in place of the console's FSR 4); ray tracing: bridge it, or run the profile that does not use it | How much of the frame depends on the console's ray-tracing path |
|
||||
| **Playable** | Translated-shader and pipeline cache; memory copies removed where the host allows; frame pacing against the display; chip-tier matrix | Whether the base 16 GB tier reaches 30 fps, and at what resolution |
|
||||
|
||||
### Decision gates
|
||||
|
||||
A gate is a question answered by a measurement, with the options written down before the measurement is taken.
|
||||
|
||||
| Gate | When | Question | If the answer is no |
|
||||
| --- | --- | --- | --- |
|
||||
| **Back end** | Start of Picture | Does D3DMetal run what translated console shaders need? | ADR: translator-side lowering, another host back end, or a narrower shader profile |
|
||||
| **Reference** | Start of Picture | Do we have reference images for the first screens? | The Picture gate falls back to a written checklist per screen, agreed by two collaborators |
|
||||
| **Memory** | Start of World | Does the build load into gameplay inside the 16 GB profile? | Series S profile only; reduce copies before any other World work |
|
||||
| **Frame rate** | Start of Playable | Is the base tier within 2x of 30 fps? | Publish tiers honestly; lower the base tier's resolution before promising it |
|
||||
|
||||
### What counts as progress
|
||||
|
||||
A change belongs on `main` only if it passes the **step-forward test**. It must do one of these, and say which:
|
||||
|
||||
1. remove a blocker of the current stage (shown by the run report before and after);
|
||||
2. remove a blocker already confirmed for a later stage, when every blocker of the current stage is claimed;
|
||||
3. make a blocker faster to find (run tooling, diagnostics, a corpus test);
|
||||
4. retire a risk at a decision gate.
|
||||
|
||||
Work that does none of these waits: subsystems nobody has seen the build need, documentation about work not yet done, and optimisation before the Playable stage.
|
||||
|
||||
---
|
||||
|
||||
## How Progress Is Reported
|
||||
|
||||
Milestone status is one of: `Planned`, `In development`, `In validation`, `Verified complete`, or `Blocked`. A milestone reaches `Verified complete` only after independent verification of its exit gate per [AGENTS.md](../AGENTS.md).
|
||||
|
||||
For the stages, the pinned ladder issue carries the live status: the current stage, the latest ten-run result for its gate, and the open blocker issues with their claims. A gate result is reported with every run counted, the machine it ran on, and the `main` commit.
|
||||
@@ -0,0 +1,139 @@
|
||||
# Target-Build Bring-Up: Development Cycle and Review
|
||||
|
||||
This is how any number of contributors run a project-authorized target build on BetterXen, turn what they find into pull requests, and review each other's work. It applies [AGENTS.md](../../AGENTS.md) Sections 5–7, the clean-room and provenance rules in [CONTRIBUTING.md](../../CONTRIBUTING.md), and [docs/legal.md](../legal.md). It adds no new permissions.
|
||||
|
||||
## Authorization is recorded, not assumed
|
||||
|
||||
AGENTS.md §6 allows evidence from *project-authorized* target builds, but it does not define who authorizes a build or how. Until a governance change defines that, this procedure requires a **recorded authorization**:
|
||||
|
||||
- **Before any target-build work,** a contributor writes an authorization note in the team's private evidence store (see "Evidence"). The note covers:
|
||||
- the build;
|
||||
- the evidence class: target-build observation, or authorized SDK documentation;
|
||||
- the maintainer who approved it;
|
||||
- how the contributor obtained the build or documentation lawfully, under terms that permit the inspection;
|
||||
- the confirmation that the work needs no decryption or circumvention of security, DRM, licensing or activation controls.
|
||||
- **Maintainer approval alone is not enough** (CONTRIBUTING.md). If any of these points is unknown, the build is not used.
|
||||
- **The note's ID goes into every PR and every review** that relies on that evidence.
|
||||
|
||||
## Roles
|
||||
|
||||
- **Bring-up keeper.** One person keeps a running branch (for example `bringup/<topic>`). It merges the open fix branches, so the title can be run end to end. This branch is never proposed for `main`. The role can rotate.
|
||||
- **Author.** Turns one finding into one single-track PR.
|
||||
- **Reviewer.** Anyone other than the author whose own recorded authorization covers the same evidence class. The reviewer re-derives the contract from their own authorized source, never from the author's copies, notes or binaries. Someone who has accessed leaked or confidential material does not review (CONTRIBUTING.md).
|
||||
- **Merger.** A maintainer other than the original author (AGENTS.md §7).
|
||||
|
||||
Work is organised by **area**, not by person. Areas follow the tracks in [parallel-tracks.md](../architecture/parallel-tracks.md): memory and storage, D3D12, XG, runtime and audio, shaders, tests and tooling. Each contributor claims an issue in an area. As more people join, an area takes more claims, but its file scope stays the same.
|
||||
|
||||
## Cycle
|
||||
|
||||
1. **Measure on the bring-up branch.** Run the title only through the offline-run procedure below. Find the first blocker with BetterXen's own diagnostics.
|
||||
2. **Record the evidence privately,** under an evidence note ID.
|
||||
3. **Open an issue** for the blocker. Name the API or contract. Do not name the title.
|
||||
4. **Fix it on a track branch off `main`.** Stay within the issue's file scope. Add or update a synthetic conformance test for every contract the fix relies on.
|
||||
5. **Open a PR** using the template below. The bring-up keeper merges the branch into the bring-up branch so that later blockers can be found.
|
||||
6. **Review independently** (see "What a reviewer does").
|
||||
7. **Merge and re-sync.** After a merge, the bring-up keeper rebases the bring-up branch on `main`.
|
||||
|
||||
### Bring-up checkpoints
|
||||
|
||||
These checkpoints describe how far a target build gets. They are **not** milestone status: milestones, their exit gates and the status vocabulary are defined only in [docs/roadmap.md](../roadmap.md) (M0–M6). A checkpoint can serve as evidence for a roadmap exit gate only where that gate says so.
|
||||
|
||||
1. **Starts:** reaches its first graphics device.
|
||||
2. **Presents:** presents its first frame, whatever it contains.
|
||||
3. **Frame loop:** keeps presenting for a recorded duration.
|
||||
4. **Rendered content:** presents pixels produced by its own shaders (needs the M2/M3 shader work).
|
||||
5. **Interactive:** reaches a menu that accepts input.
|
||||
|
||||
Each PR states which checkpoint it affects, and the measured result before and after.
|
||||
|
||||
## PR description template
|
||||
|
||||
```text
|
||||
Contract: the derived facts (sizes, offsets, slot orders, flags, units, return values)
|
||||
Source: "authorized SDK documentation" and/or "target-build observation";
|
||||
never quote header or documentation text, never name the title or build
|
||||
Authorization: authorization note ID
|
||||
Evidence: evidence note ID(s)
|
||||
Reproduce: the BetterXen commit, bx-cli options, BX_* switches and log events a reviewer checks
|
||||
Test: the conformance test that asserts the contract, and how its expected
|
||||
values were derived independently of the implementation
|
||||
Checkpoint: the checkpoint this affects, with the measured result before and after
|
||||
```
|
||||
|
||||
## What a reviewer does
|
||||
|
||||
The reviewer re-derives the contract and does not rely on the PR's conclusions (AGENTS.md §5).
|
||||
|
||||
1. **Documentation facts.** Compile a local probe against their own authorized headers and print the sizes, offsets and constants. Probes and their output stay outside this repository.
|
||||
2. **Title behaviour.** If the fix depends on how the title uses an API (for example, units it stores or flags it passes), check this in their own analysis, under their own authorization.
|
||||
3. **Title run.** Run the PR branch merged into the bring-up branch, using the offline-run procedure, and confirm the stated before-and-after result.
|
||||
4. **Checks.** Run the AGENTS.md §8 checks. Confirm that the conformance test's expected values do not come from the code under test.
|
||||
5. **Post the review.** Say what was re-derived and what was run, without proprietary details, and cite the note IDs.
|
||||
|
||||
## Offline-run procedure
|
||||
|
||||
Every title run must be unable to reach the network, because some titles upload crash dumps. The run is wrapped in a macOS sandbox profile that denies outbound IP traffic. Apple marks `sandbox-exec` as deprecated, but it still enforces profiles on current macOS; if it stops working, do not run the title until a replacement is documented here.
|
||||
|
||||
Copy these commands, filling in the bracketed values. Record the BetterXen commit (`git rev-parse HEAD`) and these exact commands in the evidence note.
|
||||
|
||||
```sh
|
||||
CX=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver
|
||||
BOTTLE=<bottle name>
|
||||
PREFIX="$HOME/Library/Application Support/CrossOver/Bottles/$BOTTLE"
|
||||
PROFILE='(version 1)(allow default)(deny network-outbound (remote ip))'
|
||||
|
||||
# 1. Stop the bottle's wineserver. A wineserver started outside the sandbox would
|
||||
# serve the title outside it.
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -k
|
||||
env -i HOME="$HOME" PATH=/usr/bin:/bin WINEPREFIX="$PREFIX" "$CX/bin/wineserver" -w
|
||||
|
||||
# 2. Confirm the profile blocks outbound traffic. This must print BLOCKED; otherwise stop.
|
||||
sandbox-exec -p "$PROFILE" /usr/bin/curl -sS -m 5 https://example.com >/dev/null 2>&1 \
|
||||
&& echo REACHABLE || echo BLOCKED
|
||||
|
||||
# 3. Run the title inside the same profile. Every process it starts, including the new
|
||||
# wineserver, inherits the sandbox.
|
||||
env -i HOME="$HOME" USER="$USER" TMPDIR="$TMPDIR" PATH=/usr/bin:/bin:/usr/sbin:/sbin \
|
||||
BX_TRACE_D3D=0 BX_NULL_RENDER=1 BX_PRESENT_DUMP='Z:\<frames folder>' BX_INPUT_SCRIPT=A@40,A@50 \
|
||||
sandbox-exec -p "$PROFILE" target/debug/bx-cli run --inherit-env \
|
||||
--bottle "$BOTTLE" --backend d3dmetal --profile <profile> \
|
||||
--log <run>.jsonl --shims build-shims/bin --exe <path to the title executable>
|
||||
```
|
||||
|
||||
**Why `env -i` with `--inherit-env`:** `bx-cli run` normally clears the guest environment to a fixed allowlist (AGENTS.md §3), and that allowlist has no `BX_*` diagnostic switches. Here `env -i` builds an environment that contains only the listed variables, and `--inherit-env` passes exactly that to the guest. Host credentials and other variables still never reach it.
|
||||
|
||||
**Confirming that the title stayed offline.** Run a guest-side probe that tries an outbound connection the same way. It must fail inside the sandbox and succeed outside it. The probe and its output belong in the evidence note.
|
||||
|
||||
Everyone uses the same pinned environment: the BetterXen commit, the CrossOver version, the macOS version and the `bx-cli` profile. A result is reported together with that environment.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
All switches are off unless set, and none changes behaviour beyond what its row says. Only switches that exist on `main` are listed. Switches from open PRs are added here when those PRs merge.
|
||||
|
||||
| Switch | Where | Effect |
|
||||
| --- | --- | --- |
|
||||
| `BX_TRACE_D3D=1` | `d3d12_xs` | Logs every D3D12 call |
|
||||
| `BX_NULL_RENDER=1` | `d3d12_xs` | Pipelines that cannot be built become null pipelines; their draws and dispatches are skipped and logged |
|
||||
| `BX_PRESENT_DUMP=<folder>` | `d3d12_xs` | Writes presented frames as BMP files, every Nth present (`BX_PRESENT_DUMP_EVERY`, default 64) |
|
||||
| `BX_XMEM_TRACE=1` | `xmem` | Logs physical page allocations, frees and mappings |
|
||||
| `BX_INPUT_SCRIPT=<presses>` | `GameInput` | Scripted gamepad presses for unattended runs, without window focus: comma-separated `BUTTON@SECONDS` (`A@40,DOWN@50.5,A@52`), each held 300 ms, timed from the first gamepad reading. Buttons `MENU VIEW A B X Y UP DOWN LEFT RIGHT`. Each press is logged (`input_script`), and so is each entry that cannot be read |
|
||||
| `BX_CONTINUE_ASSERTS=1` | `bx_runtime_veh` | Steps over an `int3` in the title's own executable (a continuable assert) instead of letting it reach the title's crash reporter. Each address is logged once (`assert_continued`), so the report still lists every assert. Use it to get past a known assert to the next blocker, and say so in the evidence |
|
||||
|
||||
Their output can contain title addresses and file names, so it goes only into the private evidence store.
|
||||
|
||||
## Evidence
|
||||
|
||||
Logs, addresses, decompiled output, screenshots and authorization notes live in the team's private evidence store, outside this repository. PRs and reviews refer to them by note ID only.
|
||||
|
||||
## What never enters the repository
|
||||
|
||||
CONTRIBUTING.md (clean-room and provenance) and docs/legal.md set the rules. For target-build work in particular, never commit or post:
|
||||
|
||||
- SDK header or documentation text;
|
||||
- the title's name or file names;
|
||||
- identifiers derived from the title or build: its hashes, addresses or raw logs;
|
||||
- decompiled code or disassembly;
|
||||
- screenshots of the title;
|
||||
- personal paths.
|
||||
|
||||
Hashes that record the provenance of third-party code (`THIRD_PARTY_NOTICES.md`, `docs/research/upstream-registry.md`) are not affected. Contracts are recorded as derived facts only.
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -0,0 +1,548 @@
|
||||
//! Xbox title drive letters, linked in the prefix's `dosdevices` before launch.
|
||||
//!
|
||||
//! The project-authorized target title we traced reads its package from `G:` and writes
|
||||
//! temporary files such as crash logs to `T:`. That is an observation of one title at startup;
|
||||
//! that `G:` is the package root and `T:` temporary storage for Xbox titles in general is an
|
||||
//! inference. A Wine prefix has neither drive, so that title's first `G:\...` open fails with
|
||||
//! `STATUS_OBJECT_PATH_NOT_FOUND`. `bx-cli run` links `g:` to the executable's directory and
|
||||
//! `t:` to `drive_c/bx_temp`.
|
||||
//!
|
||||
//! As with system32 staging (#474), a drive letter the prefix already uses is not ours. A
|
||||
//! `.bx-drives` manifest in `dosdevices` records each link this tool made, and only a link that
|
||||
//! is listed and still points where it was pointed is replaced. Any other mapping to a
|
||||
//! different target is reported and left unchanged.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::ffi::{OsStrExt, OsStringExt};
|
||||
use std::os::unix::fs::{OpenOptionsExt, symlink};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MANIFEST: &str = ".bx-drives";
|
||||
const LOCK_FILE: &str = ".bx-drive-mapping.lock";
|
||||
|
||||
/// The prefix-relative target of `t:`, in the form Wine itself uses for `c:`.
|
||||
pub const TEMP_TARGET: &str = "../drive_c/bx_temp";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DriveMappingLock {
|
||||
_file: fs::File,
|
||||
}
|
||||
|
||||
/// Holds the prefix's drive mappings stable until the returned lock is dropped.
|
||||
pub fn lock_drive_mappings(prefix: &Path) -> Result<DriveMappingLock, String> {
|
||||
fs::create_dir_all(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot prepare prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let prefix = fs::canonicalize(prefix).map_err(|e| {
|
||||
format!(
|
||||
"cannot resolve prefix {} for drive lock: {e}",
|
||||
prefix.display()
|
||||
)
|
||||
})?;
|
||||
let path = prefix.join(LOCK_FILE);
|
||||
let file = fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.custom_flags(libc::O_NOFOLLOW)
|
||||
.open(&path)
|
||||
.map_err(|e| format!("cannot open drive lock {}: {e}", path.display()))?;
|
||||
|
||||
loop {
|
||||
// The open file descriptor stays alive in DriveMappingLock for the full launch.
|
||||
let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
|
||||
if result == 0 {
|
||||
return Ok(DriveMappingLock { _file: file });
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.kind() == io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
if error.kind() == io::ErrorKind::WouldBlock {
|
||||
return Err(format!(
|
||||
"another bx-cli run is active for prefix {}; refusing to launch with shared Xbox drive mappings",
|
||||
prefix.display()
|
||||
));
|
||||
}
|
||||
return Err(format!("cannot lock {}: {error}", path.display()));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Mapping {
|
||||
Created(char, PathBuf),
|
||||
/// A link this tool made earlier, pointed at a new target.
|
||||
Retargeted(char, PathBuf),
|
||||
Unchanged(char, PathBuf),
|
||||
/// A mapping this tool did not make, to a different target; left as it is.
|
||||
Foreign {
|
||||
letter: char,
|
||||
existing: String,
|
||||
wanted: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
impl Mapping {
|
||||
pub fn describe(&self) -> String {
|
||||
match self {
|
||||
Mapping::Created(l, t) => {
|
||||
format!("mapped {}: to {}", l.to_ascii_uppercase(), t.display())
|
||||
}
|
||||
Mapping::Retargeted(l, t) => {
|
||||
format!(
|
||||
"remapped own {}: to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Unchanged(l, t) => {
|
||||
format!(
|
||||
"{}: already maps to {}",
|
||||
l.to_ascii_uppercase(),
|
||||
t.display()
|
||||
)
|
||||
}
|
||||
Mapping::Foreign {
|
||||
letter,
|
||||
existing,
|
||||
wanted,
|
||||
} => format!(
|
||||
"warning: {}: already maps to {existing}, not {}; left unchanged, so the guest \
|
||||
may not find its files there",
|
||||
letter.to_ascii_uppercase(),
|
||||
wanted.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_manifest(dosdevices: &Path) -> Result<BTreeMap<char, PathBuf>, String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
let text = match fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
|
||||
};
|
||||
let mut owned = BTreeMap::new();
|
||||
for line in text.lines().filter(|l| !l.is_empty()) {
|
||||
let mut chars = line.chars();
|
||||
match (chars.next(), chars.next()) {
|
||||
(Some(letter), Some('\t')) if letter.is_ascii_lowercase() => {
|
||||
let encoded = chars.as_str();
|
||||
let target = match encoded.strip_prefix('@') {
|
||||
Some(hex) => decode_path(hex)
|
||||
.ok_or_else(|| format!("malformed path in {}: {line:?}", path.display()))?,
|
||||
None => PathBuf::from(encoded),
|
||||
};
|
||||
owned.insert(letter, target);
|
||||
}
|
||||
_ => return Err(format!("malformed line in {}: {line:?}", path.display())),
|
||||
}
|
||||
}
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
fn write_manifest(dosdevices: &Path, owned: &BTreeMap<char, PathBuf>) -> Result<(), String> {
|
||||
let path = dosdevices.join(MANIFEST);
|
||||
let mut text = String::new();
|
||||
for (letter, target) in owned {
|
||||
text.push_str(&format!("{letter}\t@{}\n", encode_path(target)));
|
||||
}
|
||||
// Written to a temporary file and renamed over the manifest, like `relink`, so an
|
||||
// interrupted write can never leave a truncated manifest that later runs refuse to parse.
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp)
|
||||
.map_err(|e| format!("cannot create {}: {e}", tmp.display()))?;
|
||||
let written = file.write_all(text.as_bytes()).and_then(|()| {
|
||||
drop(file);
|
||||
fs::rename(&tmp, &path)
|
||||
});
|
||||
if written.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
written.map_err(|e| format!("cannot write {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn encode_path(path: &Path) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let bytes = path.as_os_str().as_bytes();
|
||||
let mut encoded = String::with_capacity(bytes.len() * 2);
|
||||
for &byte in bytes {
|
||||
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
|
||||
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn decode_path(hex: &str) -> Option<PathBuf> {
|
||||
fn nibble(byte: u8) -> Option<u8> {
|
||||
match byte {
|
||||
b'0'..=b'9' => Some(byte - b'0'),
|
||||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = hex.as_bytes();
|
||||
if bytes.len() % 2 != 0 {
|
||||
return None;
|
||||
}
|
||||
let mut decoded = Vec::with_capacity(bytes.len() / 2);
|
||||
for pair in bytes.chunks_exact(2) {
|
||||
decoded.push((nibble(pair[0])? << 4) | nibble(pair[1])?);
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(decoded)))
|
||||
}
|
||||
|
||||
/// Points `link` at `target`, replacing what is there through a rename so the link never
|
||||
/// disappears in between.
|
||||
fn relink(dosdevices: &Path, link: &Path, target: &Path) -> io::Result<()> {
|
||||
let tmp = dosdevices.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
let _ = fs::remove_file(&tmp);
|
||||
symlink(target, &tmp)?;
|
||||
let result = fs::rename(&tmp, link);
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Links `g:` to `package_dir` and `t:` to [`TEMP_TARGET`] in `prefix`'s `dosdevices`.
|
||||
pub fn map_xbox_drives(prefix: &Path, package_dir: &Path) -> Result<Vec<Mapping>, String> {
|
||||
let dosdevices = prefix.join("dosdevices");
|
||||
if !dosdevices.is_dir() {
|
||||
return Err(format!(
|
||||
"{} does not exist (start the prefix once so Wine creates it)",
|
||||
dosdevices.display()
|
||||
));
|
||||
}
|
||||
let temp_dir = prefix.join("drive_c/bx_temp");
|
||||
fs::create_dir_all(&temp_dir)
|
||||
.map_err(|e| format!("cannot create {}: {e}", temp_dir.display()))?;
|
||||
|
||||
let mut owned = read_manifest(&dosdevices)?;
|
||||
let mut mappings = Vec::new();
|
||||
for (letter, target) in [
|
||||
('g', package_dir.to_path_buf()),
|
||||
('t', PathBuf::from(TEMP_TARGET)),
|
||||
] {
|
||||
let link = dosdevices.join(format!("{letter}:"));
|
||||
let current = match fs::symlink_metadata(&link) {
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
|
||||
Err(e) => return Err(format!("cannot inspect {}: {e}", link.display())),
|
||||
Ok(meta) if meta.file_type().is_symlink() => Some(
|
||||
fs::read_link(&link).map_err(|e| format!("cannot read {}: {e}", link.display()))?,
|
||||
),
|
||||
Ok(_) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: format!("a non-link entry {}", link.display()),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mapping = match current {
|
||||
None => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
relink(&dosdevices, &link, &target)
|
||||
.map_err(|e| format!("cannot create {}: {e}", link.display()))?;
|
||||
Mapping::Created(letter, target.clone())
|
||||
}
|
||||
Some(current) if current == target => Mapping::Unchanged(letter, target.clone()),
|
||||
Some(current) if owned.get(&letter) == Some(¤t) => {
|
||||
owned.insert(letter, target.clone());
|
||||
write_manifest(&dosdevices, &owned)?;
|
||||
if let Err(error) = relink(&dosdevices, &link, &target) {
|
||||
owned.insert(letter, current);
|
||||
let restore = write_manifest(&dosdevices, &owned);
|
||||
let detail = restore
|
||||
.err()
|
||||
.map(|e| format!("; also could not restore the drive manifest: {e}"))
|
||||
.unwrap_or_default();
|
||||
return Err(format!(
|
||||
"cannot replace {}: {error}{detail}",
|
||||
link.display()
|
||||
));
|
||||
}
|
||||
Mapping::Retargeted(letter, target.clone())
|
||||
}
|
||||
Some(current) => {
|
||||
mappings.push(Mapping::Foreign {
|
||||
letter,
|
||||
existing: current.display().to_string(),
|
||||
wanted: target,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
mappings.push(mapping);
|
||||
}
|
||||
Ok(mappings)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"bx-drives-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::thread::current().id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&p);
|
||||
fs::create_dir_all(p.join("prefix/dosdevices")).unwrap();
|
||||
fs::create_dir_all(p.join("game")).unwrap();
|
||||
TempDir(p)
|
||||
}
|
||||
fn prefix(&self) -> PathBuf {
|
||||
self.0.join("prefix")
|
||||
}
|
||||
fn game(&self) -> PathBuf {
|
||||
self.0.join("game")
|
||||
}
|
||||
fn link(&self, letter: char) -> PathBuf {
|
||||
self.0.join(format!("prefix/dosdevices/{letter}:"))
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_drives_are_created_and_resolve() {
|
||||
let t = TempDir::new("create");
|
||||
fs::write(t.game().join("package.bin"), b"pkg").unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Created('g', _), Mapping::Created('t', _)]
|
||||
));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
fs::read_link(t.link('t')).unwrap(),
|
||||
PathBuf::from(TEMP_TARGET)
|
||||
);
|
||||
// Both links resolve the way Wine resolves them, from inside dosdevices.
|
||||
assert_eq!(fs::read(t.link('g').join("package.bin")).unwrap(), b"pkg");
|
||||
assert!(t.link('t').is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_changes_nothing() {
|
||||
let t = TempDir::new("rerun");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(
|
||||
mappings[..],
|
||||
[Mapping::Unchanged('g', _), Mapping::Unchanged('t', _)]
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_follows_a_new_package_directory() {
|
||||
let t = TempDir::new("retarget");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(mappings[0], Mapping::Retargeted('g', _)));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), other);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_foreign_mapping_is_reported_and_kept() {
|
||||
let t = TempDir::new("foreign");
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert!(mappings[0].describe().starts_with("warning: G:"));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
// A link this tool did not record is never treated as its own on a later run.
|
||||
let again = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_own_link_changed_by_someone_else_becomes_foreign() {
|
||||
let t = TempDir::new("changed");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
fs::remove_file(t.link('g')).unwrap();
|
||||
let elsewhere = t.0.join("elsewhere");
|
||||
symlink(&elsewhere, t.link('g')).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
let mappings = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&mappings[0], Mapping::Foreign { letter: 'g', .. }));
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), elsewhere);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_link_entry_is_never_touched() {
|
||||
let t = TempDir::new("nonlink");
|
||||
fs::create_dir_all(t.link('t')).unwrap();
|
||||
let mappings = map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
assert!(matches!(&mappings[1], Mapping::Foreign { letter: 't', .. }));
|
||||
assert!(t.link('t').is_dir() && !fs::symlink_metadata(t.link('t')).unwrap().is_symlink());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_without_dosdevices_is_an_error() {
|
||||
let t = TempDir::new("nodos");
|
||||
fs::remove_dir_all(t.prefix().join("dosdevices")).unwrap();
|
||||
let e = map_xbox_drives(&t.prefix(), &t.game()).unwrap_err();
|
||||
assert!(e.contains("dosdevices"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_manifest_is_an_error_not_an_ownership_claim() {
|
||||
let t = TempDir::new("badmanifest");
|
||||
fs::write(t.prefix().join("dosdevices").join(MANIFEST), "g /x\n").unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_manifest_write_leaves_no_unrecorded_link() {
|
||||
let t = TempDir::new("orphan");
|
||||
// A directory where the manifest's temporary file goes makes the write fail.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &t.game()).is_err());
|
||||
assert!(
|
||||
fs::symlink_metadata(t.link('g')).is_err(),
|
||||
"g: must not be created before ownership is recorded"
|
||||
);
|
||||
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interrupted_manifest_write_keeps_the_previous_manifest() {
|
||||
let t = TempDir::new("atomic");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let manifest = t.prefix().join("dosdevices").join(MANIFEST);
|
||||
let before = fs::read(&manifest).unwrap();
|
||||
// Fail the next write after the new contents would have been produced: the old
|
||||
// manifest must survive whole, never truncated or half written.
|
||||
let tmp = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
fs::create_dir(&tmp).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(
|
||||
fs::read(&manifest).unwrap(),
|
||||
before,
|
||||
"previous manifest kept intact"
|
||||
);
|
||||
fs::remove_dir(&tmp).unwrap();
|
||||
// The intact manifest still proves ownership, so the retry re-points g:.
|
||||
let again = map_xbox_drives(&t.prefix(), &other).unwrap();
|
||||
assert!(matches!(&again[0], Mapping::Retargeted('g', _)));
|
||||
assert!(
|
||||
fs::read_dir(t.prefix().join("dosdevices"))
|
||||
.unwrap()
|
||||
.all(|e| !e.unwrap().file_name().to_string_lossy().contains(".tmp."))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_temp_does_not_follow_an_existing_symlink() {
|
||||
let t = TempDir::new("manifest-symlink");
|
||||
let dosdevices = t.prefix().join("dosdevices");
|
||||
let target = t.0.join("outside-manifest");
|
||||
fs::write(&target, b"unchanged").unwrap();
|
||||
let tmp = dosdevices.join(format!("{MANIFEST}.tmp.{}", std::process::id()));
|
||||
symlink(&target, &tmp).unwrap();
|
||||
|
||||
assert!(write_manifest(&dosdevices, &BTreeMap::new()).is_err());
|
||||
assert_eq!(fs::read(&target).unwrap(), b"unchanged");
|
||||
assert_eq!(fs::read_link(&tmp).unwrap(), target);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_retarget_restores_the_previous_manifest_and_link() {
|
||||
let t = TempDir::new("retarget-failure");
|
||||
map_xbox_drives(&t.prefix(), &t.game()).unwrap();
|
||||
let other = t.0.join("other-game");
|
||||
fs::create_dir_all(&other).unwrap();
|
||||
|
||||
let temp_link = t
|
||||
.prefix()
|
||||
.join("dosdevices")
|
||||
.join(format!(".bx-drive-tmp.{}", std::process::id()));
|
||||
fs::create_dir(&temp_link).unwrap();
|
||||
assert!(map_xbox_drives(&t.prefix(), &other).is_err());
|
||||
assert_eq!(fs::read_link(t.link('g')).unwrap(), t.game());
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
t.game()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_lock_rejects_another_launcher_until_released() {
|
||||
let t = TempDir::new("lock");
|
||||
let lock = lock_drive_mappings(&t.prefix()).unwrap();
|
||||
let error = lock_drive_mappings(&t.prefix()).unwrap_err();
|
||||
assert!(error.contains("another bx-cli run"), "{error}");
|
||||
|
||||
drop(lock);
|
||||
assert!(lock_drive_mappings(&t.prefix()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_utf8_target_round_trips_through_the_manifest() {
|
||||
let t = TempDir::new("non-utf8");
|
||||
let mut game_bytes = t.0.as_os_str().as_bytes().to_vec();
|
||||
game_bytes.extend_from_slice(b"/game-\xff");
|
||||
let game = PathBuf::from(std::ffi::OsString::from_vec(game_bytes));
|
||||
let owned = BTreeMap::from([('g', game.clone())]);
|
||||
write_manifest(&t.prefix().join("dosdevices"), &owned).unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
game
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_plain_text_target_still_reads() {
|
||||
let t = TempDir::new("legacy-manifest");
|
||||
let legacy_target = t.0.join("old-game");
|
||||
fs::write(
|
||||
t.prefix().join("dosdevices").join(MANIFEST),
|
||||
format!("g\t{}\n", legacy_target.display()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
read_manifest(&t.prefix().join("dosdevices")).unwrap()[&'g'],
|
||||
legacy_target
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+1955
-49
File diff suppressed because it is too large.
Load diff
@@ -433,6 +433,12 @@ where
|
||||
for (name, bytes, dst, result) in plan {
|
||||
if !matches!(result, Staged::Unchanged(_)) {
|
||||
let tmp = tmp_of(name);
|
||||
// Snapshot what the target holds now, before the rename, so a failed manifest
|
||||
// write can put the *old* bytes back (not the bytes just written).
|
||||
let previous: Option<Vec<u8>> = match result {
|
||||
Staged::Copied(_) => None,
|
||||
_ => fs::read(&dst).ok(),
|
||||
};
|
||||
let published = before_publish(name).and_then(|()| match result {
|
||||
// Nothing was there at step 1; refuse to replace whatever appeared since.
|
||||
Staged::Copied(_) => install_new(&tmp, &dst, &bytes).map_err(|e| {
|
||||
@@ -495,6 +501,19 @@ where
|
||||
let _ = fs::remove_file(&tmp);
|
||||
owned.insert(name.clone(), sha256_hex(&bytes));
|
||||
if let Err(e) = write_manifest(system32, &owned) {
|
||||
// The file is installed but the manifest on disk does not name it, so the
|
||||
// next run would call bx-cli's own copy foreign (#573). Roll the publish
|
||||
// back: a Copied file is removed, a Replaced one is restored from the bytes
|
||||
// it had before. The manifest is left exactly as it was, so the retry sees
|
||||
// the same state it would have seen had the publish never happened.
|
||||
match previous {
|
||||
None => {
|
||||
let _ = fs::remove_file(&dst);
|
||||
}
|
||||
Some(before) => {
|
||||
let _ = fs::write(&dst, before);
|
||||
}
|
||||
}
|
||||
discard(&pending);
|
||||
return Err(e);
|
||||
}
|
||||
@@ -875,6 +894,67 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_write_failure_leaves_no_unowned_file() {
|
||||
let (_t, shims, prefix) = setup("manifest");
|
||||
let sys = system32_dir(&prefix);
|
||||
// A directory where the manifest's temporary file has to go makes
|
||||
// `write_manifest` fail after the first shim has already been published.
|
||||
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
|
||||
fs::create_dir(&obstacle).unwrap();
|
||||
let err = stage(&shims, &sys).unwrap_err();
|
||||
assert!(err.contains("cannot write"), "{err}");
|
||||
assert!(
|
||||
!sys.join("bx_runtime_veh.dll").exists(),
|
||||
"the published file was rolled back, so the retry is not refused as foreign"
|
||||
);
|
||||
assert!(!sys.join(MANIFEST_NAME).exists());
|
||||
// Only the obstacle itself is left: no staged copy, no temporary file.
|
||||
let entries: Vec<String> = fs::read_dir(&sys)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
entries,
|
||||
vec![obstacle.file_name().unwrap().to_string_lossy().into_owned()],
|
||||
"system32 holds nothing but the obstacle that failed the manifest write"
|
||||
);
|
||||
fs::remove_dir(&obstacle).unwrap();
|
||||
// The retry installs everything fresh; nothing is reported as foreign.
|
||||
let retry = stage(&shims, &sys).unwrap();
|
||||
assert!(
|
||||
retry.iter().all(|s| matches!(s, Staged::Copied(_))),
|
||||
"{retry:?}"
|
||||
);
|
||||
// And a shim rebuilt later refreshes bx-cli's own copy rather than failing.
|
||||
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
|
||||
let update = stage(&shims, &sys).unwrap();
|
||||
assert!(update.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_write_failure_restores_the_previous_bytes() {
|
||||
let (_t, shims, prefix) = setup("restore");
|
||||
let sys = system32_dir(&prefix);
|
||||
stage(&shims, &sys).unwrap();
|
||||
// Rebuild the shim, then make the manifest write fail after the rename.
|
||||
fs::write(shims.join("bx_runtime_veh.dll"), b"veh v2").unwrap();
|
||||
let obstacle = sys.join(format!("{MANIFEST_NAME}.{}.bx-staging", std::process::id()));
|
||||
fs::create_dir(&obstacle).unwrap();
|
||||
assert!(stage(&shims, &sys).is_err());
|
||||
assert_eq!(
|
||||
fs::read(sys.join("bx_runtime_veh.dll")).unwrap(),
|
||||
b"veh v1",
|
||||
"the replaced file must be restored to the bytes it had before the rename"
|
||||
);
|
||||
// The manifest still names the old copy, so the retry refreshes it rather than
|
||||
// calling it foreign.
|
||||
fs::remove_dir(&obstacle).unwrap();
|
||||
let retry = stage(&shims, &sys).unwrap();
|
||||
assert!(retry.contains(&Staged::Replaced(sys.join("bx_runtime_veh.dll"))));
|
||||
assert_eq!(fs::read(sys.join("bx_runtime_veh.dll")).unwrap(), b"veh v2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_shims_reached_through_a_stub_prefix_count_as_visible() {
|
||||
let (t, shims, prefix) = setup("visible");
|
||||
|
||||
@@ -447,7 +447,7 @@ mod tests {
|
||||
std::fs::write(
|
||||
&server,
|
||||
format!(
|
||||
"#!/bin/sh\n/bin/ps -o pgid= -p $$ >> '{}'\n",
|
||||
"#!/bin/sh\n/usr/bin/perl -MPOSIX -e 'print getpgrp(), \"\\n\"' >> '{}'\n",
|
||||
seen.display()
|
||||
),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Runs the built `bx-cli` binary to check what `main` prints and returns for the
|
||||
//! usage paths (#532). The unit tests cover `Dispatch::classify`; these cover the
|
||||
//! mapping from that classification to the real exit code and output stream.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn run(args: &[&str]) -> std::process::Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_bx-cli"))
|
||||
.args(args)
|
||||
.env_clear()
|
||||
.output()
|
||||
.expect("bx-cli must start")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_prints_usage_on_stdout_and_succeeds() {
|
||||
for flag in ["--help", "-h", "help"] {
|
||||
let out = run(&[flag]);
|
||||
assert!(out.status.success(), "{flag}: {:?}", out.status);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(
|
||||
stdout.contains("bx-cli run --exe"),
|
||||
"{flag}: usage on stdout: {stdout}"
|
||||
);
|
||||
assert!(out.stderr.is_empty(), "{flag}: nothing on stderr");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_invocation_is_a_usage_error_on_stderr() {
|
||||
let out = run(&[]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_subcommand_is_a_usage_error_on_stderr() {
|
||||
let out = run(&["frobnicate"]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(out.stdout.is_empty(), "nothing on stdout");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("bx-cli run --exe"));
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub fn classify_dll(dll_name: &str) -> ShimTrack {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PeSummary {
|
||||
pub image_base: u64,
|
||||
pub size_of_image: u32,
|
||||
@@ -128,12 +128,21 @@ struct Section {
|
||||
}
|
||||
|
||||
fn rva_to_off(sections: &[Section], rva: u32) -> Option<usize> {
|
||||
rva_to_off_bounded(sections, rva).map(|(off, _)| off)
|
||||
}
|
||||
|
||||
/// Map an RVA to a file offset and report how many raw bytes remain in that
|
||||
/// section from the mapped offset. The bound lets callers walk a table without
|
||||
/// leaving the section that contains it.
|
||||
fn rva_to_off_bounded(sections: &[Section], rva: u32) -> Option<(usize, usize)> {
|
||||
for s in sections {
|
||||
let span = s.vsize.max(s.raw_size);
|
||||
if rva >= s.vaddr && rva < s.vaddr.saturating_add(span) {
|
||||
let delta = rva - s.vaddr;
|
||||
if delta < s.raw_size {
|
||||
return Some((s.raw_ptr + delta) as usize);
|
||||
let off = (s.raw_ptr as usize).checked_add(delta as usize)?;
|
||||
let remaining = (s.raw_size as usize).checked_sub(delta as usize)?;
|
||||
return Some((off, remaining));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,8 +176,36 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
let size_of_image = u32_le(bytes, opt + 56).ok_or(ProbeError::NotPe32Plus("size_of_image"))?;
|
||||
let num_rvas = u32_le(bytes, opt + 108).ok_or(ProbeError::NotPe32Plus("num_rvas"))?;
|
||||
|
||||
let mut sections = Vec::with_capacity(section_count as usize);
|
||||
// The import data directory is entry index 1, an 8-byte RVA/size pair at
|
||||
// optional-header offset 112 + 8. Microsoft's PE format requires probes to
|
||||
// honour both NumberOfRvaAndSizes and SizeOfOptionalHeader, so the entry is
|
||||
// validated while the optional header is read: a short optional header must
|
||||
// not let the read fall through into the section table.
|
||||
const IMPORT_DIR_INDEX: u32 = 1;
|
||||
const IMPORT_DIR_OFF: usize = 112 + 8;
|
||||
let mut import_dir: Option<(u32, u32)> = None;
|
||||
if num_rvas > IMPORT_DIR_INDEX {
|
||||
let entry = bytes
|
||||
.get(opt + IMPORT_DIR_OFF..opt + IMPORT_DIR_OFF + 8)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated import directory"))?;
|
||||
if IMPORT_DIR_OFF + 8 > opt_size {
|
||||
return Err(ProbeError::NotPe32Plus(
|
||||
"import directory outside SizeOfOptionalHeader",
|
||||
));
|
||||
}
|
||||
let rva = u32::from_le_bytes([entry[0], entry[1], entry[2], entry[3]]);
|
||||
let size = u32::from_le_bytes([entry[4], entry[5], entry[6], entry[7]]);
|
||||
import_dir = Some((rva, size));
|
||||
}
|
||||
|
||||
let sec_base = opt + opt_size;
|
||||
let section_table_size = (section_count as usize)
|
||||
.checked_mul(40)
|
||||
.ok_or(ProbeError::NotPe32Plus("section table size overflow"))?;
|
||||
bytes
|
||||
.get(sec_base..sec_base + section_table_size)
|
||||
.ok_or(ProbeError::NotPe32Plus("truncated section table"))?;
|
||||
let mut sections = Vec::with_capacity(section_count as usize);
|
||||
for i in 0..section_count as usize {
|
||||
let so = sec_base + i * 40;
|
||||
let vsize = u32_le(bytes, so + 8).ok_or(ProbeError::NotPe32Plus("sec vsize"))?;
|
||||
@@ -184,16 +221,22 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
}
|
||||
|
||||
let mut imports: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
if num_rvas > 1 {
|
||||
let imp_rva = u32_le(bytes, opt + 112 + 8).unwrap_or(0);
|
||||
if let Some((imp_rva, imp_size)) = import_dir {
|
||||
if imp_rva != 0
|
||||
&& let Some(mut desc_off) = rva_to_off(§ions, imp_rva)
|
||||
&& let Some((mut desc_off, section_bytes_left)) = rva_to_off_bounded(§ions, imp_rva)
|
||||
{
|
||||
while let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) {
|
||||
// Bound the 20-byte IMAGE_IMPORT_DESCRIPTOR walk by BOTH the
|
||||
// declared directory Size and the section's raw bytes, whichever
|
||||
// ends first, so descriptors past the directory are not reported.
|
||||
let mut desc_bytes_left = section_bytes_left.min(imp_size as usize);
|
||||
while desc_bytes_left >= 20 {
|
||||
let (Some(orig_thunk), Some(name_rva), Some(first_thunk)) = (
|
||||
u32_le(bytes, desc_off),
|
||||
u32_le(bytes, desc_off + 12),
|
||||
u32_le(bytes, desc_off + 16),
|
||||
) else {
|
||||
break;
|
||||
};
|
||||
if orig_thunk == 0 && name_rva == 0 && first_thunk == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -225,6 +268,7 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
imports.entry(dll).or_default().extend(syms);
|
||||
}
|
||||
desc_off += 20;
|
||||
desc_bytes_left -= 20;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +286,129 @@ pub fn probe_pe32_plus(bytes: &[u8]) -> Result<PeSummary, ProbeError> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PE_OFF: usize = 0x80;
|
||||
const COFF: usize = PE_OFF + 4;
|
||||
const OPT: usize = COFF + 20;
|
||||
const OPT_SIZE: usize = 0xF0;
|
||||
const SEC: usize = OPT + OPT_SIZE;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
const RAW_PTR: u32 = 0x200;
|
||||
|
||||
fn put_u16(bytes: &mut [u8], off: usize, value: u16) {
|
||||
bytes[off..off + 2].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u32(bytes: &mut [u8], off: usize, value: u32) {
|
||||
bytes[off..off + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn put_u64(bytes: &mut [u8], off: usize, value: u64) {
|
||||
bytes[off..off + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
fn write_section(bytes: &mut [u8], base: usize, rva: u32, raw_ptr: u32, raw_size: u32) {
|
||||
bytes[base..base + 8].copy_from_slice(b".rdata\0\0");
|
||||
put_u32(bytes, base + 8, raw_size);
|
||||
put_u32(bytes, base + 12, rva);
|
||||
put_u32(bytes, base + 16, raw_size);
|
||||
put_u32(bytes, base + 20, raw_ptr);
|
||||
}
|
||||
|
||||
fn minimal_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = vec![0u8; 0x400];
|
||||
bytes[0..2].copy_from_slice(b"MZ");
|
||||
put_u32(&mut bytes, 0x3C, PE_OFF as u32);
|
||||
bytes[PE_OFF..PE_OFF + 4].copy_from_slice(b"PE\0\0");
|
||||
put_u16(&mut bytes, COFF, 0x8664);
|
||||
put_u16(&mut bytes, COFF + 2, 1);
|
||||
put_u16(&mut bytes, COFF + 16, OPT_SIZE as u16);
|
||||
put_u16(&mut bytes, OPT, 0x020B);
|
||||
put_u32(&mut bytes, OPT + 16, 0x1234);
|
||||
put_u64(&mut bytes, OPT + 24, 0x0000_0001_4000_0000);
|
||||
put_u32(&mut bytes, OPT + 56, 0x2000);
|
||||
put_u32(&mut bytes, OPT + 108, 16);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 0x200);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn two_import_pe32_plus() -> Vec<u8> {
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
let import_rva = SECTION_RVA;
|
||||
put_u32(&mut bytes, OPT + 112 + 8, import_rva);
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 0x140);
|
||||
|
||||
// Two descriptors followed by the required all-zero terminator.
|
||||
put_u32(&mut bytes, RAW_PTR as usize, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 12, SECTION_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 16, SECTION_RVA + 0x80);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 20, SECTION_RVA + 0xA0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 32, SECTION_RVA + 0x50);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 36, SECTION_RVA + 0xA0);
|
||||
|
||||
bytes[RAW_PTR as usize + 0x40..RAW_PTR as usize + 0x4A].copy_from_slice(b"ALPHA.DLL\0");
|
||||
bytes[RAW_PTR as usize + 0x50..RAW_PTR as usize + 0x59].copy_from_slice(b"BETA.DLL\0");
|
||||
|
||||
put_u64(
|
||||
&mut bytes,
|
||||
RAW_PTR as usize + 0x80,
|
||||
u64::from(SECTION_RVA + 0x60),
|
||||
);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0x88, 0);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA0, (1u64 << 63) | 7);
|
||||
put_u64(&mut bytes, RAW_PTR as usize + 0xA8, 0);
|
||||
|
||||
put_u16(&mut bytes, RAW_PTR as usize + 0x60, 0x1234);
|
||||
bytes[RAW_PTR as usize + 0x62..RAW_PTR as usize + 0x6C].copy_from_slice(b"NamedFunc\0");
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Two sections: an import-descriptor section holding exactly two
|
||||
/// descriptors and no terminator, and a data section for names and thunks.
|
||||
/// Ellipsis bytes just past the descriptor section spell a third valid
|
||||
/// descriptor, so an unbounded walk reports a DLL that is not imported.
|
||||
fn import_table_without_terminator_pe32_plus() -> Vec<u8> {
|
||||
const DATA_RVA: u32 = SECTION_RVA + 0x1000;
|
||||
const DATA_PTR: u32 = 0x300;
|
||||
|
||||
let mut bytes = minimal_pe32_plus();
|
||||
put_u16(&mut bytes, COFF + 2, 2);
|
||||
write_section(&mut bytes, SEC, SECTION_RVA, RAW_PTR, 40);
|
||||
write_section(&mut bytes, SEC + 40, DATA_RVA, DATA_PTR, 0x100);
|
||||
put_u32(&mut bytes, OPT + 112 + 8, SECTION_RVA);
|
||||
// Declare the directory to cover the whole descriptor section, so the
|
||||
// section bound (not the Size) is what this fixture exercises.
|
||||
put_u32(&mut bytes, OPT + 112 + 12, 40);
|
||||
|
||||
for (base, dll_rva, thunk_rva) in [
|
||||
(RAW_PTR as usize, DATA_RVA, DATA_RVA + 0x80),
|
||||
(RAW_PTR as usize + 20, DATA_RVA + 0x20, DATA_RVA + 0xA0),
|
||||
] {
|
||||
put_u32(&mut bytes, base, thunk_rva);
|
||||
put_u32(&mut bytes, base + 12, dll_rva);
|
||||
put_u32(&mut bytes, base + 16, thunk_rva);
|
||||
}
|
||||
|
||||
// A third, entirely valid descriptor just past the section boundary.
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 40, DATA_RVA + 0xC0);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 52, DATA_RVA + 0x40);
|
||||
put_u32(&mut bytes, RAW_PTR as usize + 56, DATA_RVA + 0xC0);
|
||||
|
||||
for (delta, name) in [
|
||||
(0x00, &b"ONE.DLL\0"[..]),
|
||||
(0x20, &b"TWO.DLL\0"[..]),
|
||||
(0x40, &b"THREE.DLL\0"[..]),
|
||||
] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
bytes[off..off + name.len()].copy_from_slice(name);
|
||||
}
|
||||
for (delta, ordinal) in [(0x80, 1u64), (0xA0, 2), (0xC0, 3)] {
|
||||
let off = DATA_PTR as usize + delta;
|
||||
put_u64(&mut bytes, off, (1u64 << 63) | ordinal);
|
||||
put_u64(&mut bytes, off + 8, 0);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_tracks_accurately() {
|
||||
assert_eq!(classify_dll("d3d12_xs.dll"), ShimTrack::TrackCGraphics);
|
||||
@@ -263,4 +430,175 @@ mod tests {
|
||||
);
|
||||
assert_eq!(classify_dll("KERNEL32.dll"), ShimTrack::WineBuiltin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_minimal_pe32_plus_without_imports() {
|
||||
let summary = probe_pe32_plus(&minimal_pe32_plus()).unwrap();
|
||||
assert_eq!(summary.entry_point_rva, 0x1234);
|
||||
assert_eq!(summary.image_base, 0x0000_0001_4000_0000);
|
||||
assert_eq!(summary.size_of_image, 0x2000);
|
||||
assert_eq!(summary.section_count, 1);
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_named_and_ordinal_imports_from_two_dlls() {
|
||||
let summary = probe_pe32_plus(&two_import_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ALPHA.DLL".to_owned(), vec!["NamedFunc".to_owned()]),
|
||||
("BETA.DLL".to_owned(), vec!["ORDINAL:7".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncation_at_every_header_boundary() {
|
||||
let image = minimal_pe32_plus();
|
||||
for len in 0..=0x100 {
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image[..len]));
|
||||
assert!(result.is_ok(), "panic at truncation 0x{len:X}");
|
||||
assert!(result.unwrap().is_err(), "accepted truncation 0x{len:X}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_rva_mapping_that_would_wrap_u32() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, SECTION_RVA + 1);
|
||||
put_u32(&mut image, SEC + 20, u32::MAX);
|
||||
let result = std::panic::catch_unwind(|| probe_pe32_plus(&image));
|
||||
assert!(result.is_ok(), "raw pointer addition panicked");
|
||||
assert!(result.unwrap().unwrap().imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_section_count_larger_than_file() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, COFF + 2, u16::MAX);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated section table")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_pe32_magic() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u16(&mut image, OPT, 0x010B);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("not PE32+ (0x020B)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_outside_all_sections_is_safe() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 8, 0x8000);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_import_directory() {
|
||||
let mut image = minimal_pe32_plus();
|
||||
// An empty section table that fits, an optional header long enough to
|
||||
// declare the import entry, and a file cut after two of the entry's
|
||||
// RVA bytes.
|
||||
put_u16(&mut image, COFF + 2, 0);
|
||||
put_u16(&mut image, COFF + 16, 0xE0);
|
||||
image.truncate(OPT + 112 + 8 + 2);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("truncated import directory")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_unterminated_import_descriptor_walk() {
|
||||
let summary = probe_pe32_plus(&import_table_without_terminator_pe32_plus()).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
|
||||
/// (a) A short SizeOfOptionalHeader puts the import data-directory entry
|
||||
/// past the end of the optional header, so its 8 bytes would otherwise be
|
||||
/// read from the section table. The entry index is still within
|
||||
/// NumberOfRvaAndSizes, so only the SizeOfOptionalHeader check rejects it.
|
||||
#[test]
|
||||
fn rejects_import_directory_outside_short_optional_header() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
// Import entry spans optional-header offsets 120..128; declare the
|
||||
// optional header to end at 120, inside the entry.
|
||||
put_u16(&mut image, COFF + 16, 120);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// One byte short of the full 8-byte entry is still out of range.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 127);
|
||||
assert_eq!(
|
||||
probe_pe32_plus(&image).unwrap_err(),
|
||||
ProbeError::NotPe32Plus("import directory outside SizeOfOptionalHeader")
|
||||
);
|
||||
|
||||
// Exactly 128 bytes covers the whole entry, so the import directory is
|
||||
// read normally. The section table now starts at OPT + 128, so write it
|
||||
// there for this size.
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u16(&mut image, COFF + 16, 128);
|
||||
write_section(&mut image, OPT + 128, SECTION_RVA, RAW_PTR, 0x200);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.contains_key("ALPHA.DLL"));
|
||||
assert!(summary.imports.contains_key("BETA.DLL"));
|
||||
}
|
||||
|
||||
/// NumberOfRvaAndSizes == 1 means only entry 0 (export) is declared, so the
|
||||
/// import entry (index 1) must not be probed even though its bytes are
|
||||
/// present and inside SizeOfOptionalHeader.
|
||||
#[test]
|
||||
fn ignores_import_directory_beyond_number_of_rva_and_sizes() {
|
||||
let mut image = two_import_pe32_plus();
|
||||
put_u32(&mut image, OPT + 108, 1);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
assert!(summary.imports.is_empty());
|
||||
}
|
||||
|
||||
/// (b) The declared import directory Size is shorter than the containing
|
||||
/// section, so descriptors past the declared size must not be reported even
|
||||
/// though they are valid and inside the section's raw bytes.
|
||||
#[test]
|
||||
fn bounds_import_descriptor_walk_by_declared_directory_size() {
|
||||
// Size 40 covers exactly the two real descriptors; the third valid
|
||||
// descriptor at +40 lies outside the directory but inside the section.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 40);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([
|
||||
("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()]),
|
||||
("TWO.DLL".to_owned(), vec!["ORDINAL:2".to_owned()]),
|
||||
]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
assert!(!summary.imports.contains_key("THREE.DLL"));
|
||||
|
||||
// Size 20 reports only the first descriptor.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 20);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
|
||||
// A size that is not a multiple of 20 stops before the next descriptor
|
||||
// would exceed the directory.
|
||||
let mut image = import_table_without_terminator_pe32_plus();
|
||||
put_u32(&mut image, OPT + 112 + 12, 39);
|
||||
let summary = probe_pe32_plus(&image).unwrap();
|
||||
let expected = BTreeMap::from([("ONE.DLL".to_owned(), vec!["ORDINAL:1".to_owned()])]);
|
||||
assert_eq!(summary.imports, expected);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub mod report;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct TraceSummary {
|
||||
pub total_lines: usize,
|
||||
@@ -18,16 +20,54 @@ pub struct TraceSummary {
|
||||
pub amd_traps: BTreeMap<String, TrapCount>,
|
||||
pub adx_errors: usize,
|
||||
pub unhandled_exceptions: Vec<UnhandledException>,
|
||||
/// First-chance `breakpoint_exception` records (int3 and assertion failures), which a
|
||||
/// guest's own crash reporter would otherwise hide from `unhandled_exception`.
|
||||
pub breakpoint_exceptions: Vec<BreakpointException>,
|
||||
pub unimpl_apis: BTreeMap<String, usize>,
|
||||
pub unimpl_vtables: BTreeMap<String, usize>,
|
||||
/// Aggregated `shader_gate` records from `d3d12_xs.dll` (#496).
|
||||
pub shader_gate: ShaderGateSummary,
|
||||
/// `shader_d3dmetal_gap` records: pipelines D3DMetal creates but does not run (#453).
|
||||
pub shader_gaps: Vec<ShaderGap>,
|
||||
/// Those same gap records grouped by `(pso, stage)`, in first-seen order (#590).
|
||||
pub shader_gap_groups: Vec<ShaderGapGroup>,
|
||||
/// Gap records that carried no `pso` or no `stage` (or an empty value for one), so
|
||||
/// they are grouped under `unknown`. Counted here so the group counts reconcile
|
||||
/// with [`TraceSummary::shader_gaps`].
|
||||
pub shader_gaps_missing_identity: usize,
|
||||
/// Gap records that carried no `wave_lanes_min` or no `atomic64_flags` (or an empty
|
||||
/// value for one). Counted here rather than dropped or assumed.
|
||||
pub shader_gaps_missing_constraints: usize,
|
||||
/// `shader_bridge_missing` messages, in log order.
|
||||
pub shader_bridge_missing: Vec<String>,
|
||||
}
|
||||
|
||||
/// One `(pso, stage)` group of `shader_d3dmetal_gap` records (#590).
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapGroup {
|
||||
/// The emitted `pso=` value, or `None` when the record carried none (rendered as
|
||||
/// `unknown`).
|
||||
pub pso: Option<String>,
|
||||
/// The emitted `stage=` value, or `None` when the record carried none.
|
||||
pub stage: Option<String>,
|
||||
/// How many gap records this `(pso, stage)` pair covers.
|
||||
pub count: usize,
|
||||
/// The distinct `(wave_lanes_min, atomic64_flags)` pairs seen for this pair, in
|
||||
/// first-seen order. Two pipelines of the same kind and stage can need different
|
||||
/// wave widths or atomic features, so a group keeps each constraint set rather than
|
||||
/// reporting only the first and losing the rest.
|
||||
pub variants: Vec<ShaderGapVariant>,
|
||||
}
|
||||
|
||||
/// The constraints carried by one or more records of a [`ShaderGapGroup`].
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct ShaderGapVariant {
|
||||
pub wave_lanes_min: Option<String>,
|
||||
pub atomic64_flags: Option<String>,
|
||||
/// How many records in the group carried exactly these constraints.
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
/// Aggregated `shader_gate` records. Decisions, kinds and stages are keyed by
|
||||
/// their emitted string so unknown values are counted rather than dropped.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
@@ -147,6 +187,30 @@ pub struct UnhandledException {
|
||||
pub rip: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct BreakpointException {
|
||||
pub exception_code: Option<String>,
|
||||
pub module: Option<String>,
|
||||
pub module_base: Option<String>,
|
||||
pub rva: Option<String>,
|
||||
/// The faulting address, which locates a breakpoint outside any image (module `?`).
|
||||
pub address: Option<String>,
|
||||
/// 1-based index of this record and the per-process cap, so a reader can tell a run
|
||||
/// that hit the cap (later breakpoints not recorded) from one that stopped short of it.
|
||||
pub record: Option<u32>,
|
||||
pub limit: Option<u32>,
|
||||
}
|
||||
|
||||
fn extract_json_u32(line: &str, key: &str) -> Option<u32> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let digits: &str = &line[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
fn extract_json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
@@ -200,18 +264,77 @@ fn record_shader_gate(summary: &mut TraceSummary, detail: &str) {
|
||||
gate.records.push(record);
|
||||
}
|
||||
|
||||
/// A field value, treating an empty value (`pso= stage=CS`) as absent. The emitter
|
||||
/// always writes a value, so an empty one means the record is malformed, not that the
|
||||
/// pipeline is named "".
|
||||
fn non_empty(value: Option<String>) -> Option<String> {
|
||||
value.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
/// Adds one gap record to the per-`(pso, stage)` grouping, keeping first-seen order.
|
||||
///
|
||||
/// Nothing here panics: a record missing `pso`, `stage`, `wave_lanes_min` or
|
||||
/// `atomic64_flags` is grouped under `unknown` (and counted), never dropped or guessed.
|
||||
fn record_shader_gap_group(groups: &mut TraceSummary, gap: &ShaderGap) {
|
||||
let pso = non_empty(gap.pso.clone());
|
||||
let stage = non_empty(gap.stage.clone());
|
||||
let wave_lanes_min = non_empty(gap.wave_lanes_min.clone());
|
||||
let atomic64_flags = non_empty(gap.atomic64_flags.clone());
|
||||
if pso.is_none() || stage.is_none() {
|
||||
groups.shader_gaps_missing_identity += 1;
|
||||
}
|
||||
if wave_lanes_min.is_none() || atomic64_flags.is_none() {
|
||||
groups.shader_gaps_missing_constraints += 1;
|
||||
}
|
||||
|
||||
// The group list is small (one entry per affected pipeline stage), so a linear scan
|
||||
// keeps first-seen order without a second index to keep in sync.
|
||||
let group_index = match groups
|
||||
.shader_gap_groups
|
||||
.iter()
|
||||
.position(|g| g.pso == pso && g.stage == stage)
|
||||
{
|
||||
Some(index) => index,
|
||||
None => {
|
||||
groups.shader_gap_groups.push(ShaderGapGroup {
|
||||
pso,
|
||||
stage,
|
||||
count: 0,
|
||||
variants: Vec::new(),
|
||||
});
|
||||
groups.shader_gap_groups.len() - 1
|
||||
}
|
||||
};
|
||||
let group = &mut groups.shader_gap_groups[group_index];
|
||||
group.count += 1;
|
||||
match group
|
||||
.variants
|
||||
.iter()
|
||||
.position(|v| v.wave_lanes_min == wave_lanes_min && v.atomic64_flags == atomic64_flags)
|
||||
{
|
||||
Some(index) => group.variants[index].count += 1,
|
||||
None => group.variants.push(ShaderGapVariant {
|
||||
wave_lanes_min,
|
||||
atomic64_flags,
|
||||
count: 1,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_shader_gap(summary: &mut TraceSummary, detail: &str) {
|
||||
let pairs = parse_key_values(detail, true);
|
||||
// The emitter appends `: D3DMetal creates such pipelines ...` directly
|
||||
// after the flags value, so strip the trailing colon.
|
||||
let atomic64_flags = get_field(&pairs, "atomic64_flags")
|
||||
.map(|v| v.strip_suffix(':').map(str::to_owned).unwrap_or(v));
|
||||
summary.shader_gaps.push(ShaderGap {
|
||||
let gap = ShaderGap {
|
||||
pso: get_field(&pairs, "pso"),
|
||||
stage: get_field(&pairs, "stage"),
|
||||
wave_lanes_min: get_field(&pairs, "wave_lanes_min"),
|
||||
atomic64_flags,
|
||||
});
|
||||
};
|
||||
record_shader_gap_group(summary, &gap);
|
||||
summary.shader_gaps.push(gap);
|
||||
}
|
||||
|
||||
pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
@@ -250,6 +373,17 @@ pub fn summarize_jsonl(input: &str) -> TraceSummary {
|
||||
rip: extract_json_str(trimmed, "rip").map(str::to_owned),
|
||||
});
|
||||
}
|
||||
"breakpoint_exception" => {
|
||||
summary.breakpoint_exceptions.push(BreakpointException {
|
||||
exception_code: extract_json_str(trimmed, "exception_code").map(str::to_owned),
|
||||
module: extract_json_str(trimmed, "module").map(str::to_owned),
|
||||
module_base: extract_json_str(trimmed, "module_base").map(str::to_owned),
|
||||
rva: extract_json_str(trimmed, "rva").map(str::to_owned),
|
||||
address: extract_json_str(trimmed, "address").map(str::to_owned),
|
||||
record: extract_json_u32(trimmed, "record"),
|
||||
limit: extract_json_u32(trimmed, "limit"),
|
||||
});
|
||||
}
|
||||
"unimpl_api" => *summary.unimpl_apis.entry(detail.to_string()).or_insert(0) += 1,
|
||||
"unimpl_vtable" => {
|
||||
*summary
|
||||
@@ -326,6 +460,39 @@ mod tests {
|
||||
assert_eq!(summary.clwb_trap_lower_bound, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_breakpoint_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
{"ts_ms":5,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0x80000003","module":"title.exe","module_base":"0x0000000140000000","rva":"0x0000000002236178","address":"0x0000000142236178","record":1,"limit":16}
|
||||
{"ts_ms":6,"tid":7,"level":"WARN","sub":"runtime_veh","event":"breakpoint_exception","exception_code":"0xc0000420","module":"?","module_base":"0x0000000000000000","rva":"0x0000000000000000","address":"0x0000000000410000","record":2,"limit":16}
|
||||
"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert!(summary.unhandled_exceptions.is_empty());
|
||||
assert_eq!(
|
||||
summary.breakpoint_exceptions,
|
||||
[
|
||||
BreakpointException {
|
||||
exception_code: Some("0x80000003".into()),
|
||||
module: Some("title.exe".into()),
|
||||
module_base: Some("0x0000000140000000".into()),
|
||||
rva: Some("0x0000000002236178".into()),
|
||||
address: Some("0x0000000142236178".into()),
|
||||
record: Some(1),
|
||||
limit: Some(16),
|
||||
},
|
||||
BreakpointException {
|
||||
exception_code: Some("0xc0000420".into()),
|
||||
module: Some("?".into()),
|
||||
module_base: Some("0x0000000000000000".into()),
|
||||
rva: Some("0x0000000000000000".into()),
|
||||
address: Some("0x0000000000410000".into()),
|
||||
record: Some(2),
|
||||
limit: Some(16),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collects_unhandled_exceptions_in_log_order() {
|
||||
let log = r#"
|
||||
@@ -569,4 +736,179 @@ mod tests {
|
||||
assert_eq!(pairs.len(), 2);
|
||||
assert_eq!(pairs[1], ("stage", "pixel"));
|
||||
}
|
||||
|
||||
/// #590: two gaps on different stages must stay two groups, in first-seen order, each
|
||||
/// with its own wave width and 64-bit-atomic flags.
|
||||
#[test]
|
||||
fn groups_gaps_on_different_stages_separately_in_first_seen_order() {
|
||||
// Same pso, different stages: grouping on pso alone would collapse these, so the
|
||||
// test discriminates the (pso, stage) key rather than only the pso.
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=VS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 3);
|
||||
|
||||
let first = &summary.shader_gap_groups[0];
|
||||
assert_eq!(first.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(first.stage.as_deref(), Some("VS"));
|
||||
assert_eq!(first.count, 1);
|
||||
assert_eq!(
|
||||
first.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
|
||||
let second = &summary.shader_gap_groups[1];
|
||||
assert_eq!(second.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(second.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(second.count, 1);
|
||||
|
||||
// A second stage of the *same* pso stays its own group, which is what separates a
|
||||
// (pso, stage) key from a pso-only key.
|
||||
let third = &summary.shader_gap_groups[2];
|
||||
assert_eq!(third.pso.as_deref(), Some("graphics"));
|
||||
assert_eq!(third.stage.as_deref(), Some("PS"));
|
||||
assert_eq!(third.count, 1);
|
||||
}
|
||||
|
||||
/// #590: the same `(pso, stage)` twice is one group with a count of two, even when the
|
||||
/// identical records are not adjacent.
|
||||
#[test]
|
||||
fn groups_identical_gaps_together() {
|
||||
let record = r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let other = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=32 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let log = format!("{record}\n{other}\n{record}\n");
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 3);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 2);
|
||||
let compute = &summary.shader_gap_groups[0];
|
||||
assert_eq!(compute.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(compute.count, 2);
|
||||
assert_eq!(
|
||||
compute.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 2,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gap_groups[1].count, 1);
|
||||
// Every record is in exactly one group.
|
||||
let grouped: usize = summary.shader_gap_groups.iter().map(|g| g.count).sum();
|
||||
assert_eq!(grouped, summary.shader_gaps.len());
|
||||
}
|
||||
|
||||
/// #590: one pipeline kind and stage can need different wave widths or atomic
|
||||
/// features, so a group keeps every distinct constraint set, not only the first.
|
||||
#[test]
|
||||
fn one_group_keeps_each_distinct_constraint_set() {
|
||||
let log = r#"{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x400000: D3DMetal creates such pipelines but does not run them (#453)"}
|
||||
{"event":"shader_d3dmetal_gap","detail":"pso=graphics stage=PS wave_lanes_min=64 atomic64_flags=0x0: D3DMetal creates such pipelines but does not run them (#453)"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gap_groups.len(), 1);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 3);
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x0".into()),
|
||||
count: 2,
|
||||
},
|
||||
ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: Some("0x400000".into()),
|
||||
count: 1,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
|
||||
/// #590: a gap record with a missing or empty field must not panic. It is grouped
|
||||
/// under `unknown` and counted, never dropped or guessed.
|
||||
#[test]
|
||||
fn a_malformed_gap_record_is_grouped_under_unknown_and_counted() {
|
||||
for (detail, missing_identity, missing_constraints) in [
|
||||
("", 1, 1),
|
||||
("garbage", 1, 1),
|
||||
("pso=compute", 1, 1),
|
||||
("stage=CS", 1, 1),
|
||||
(
|
||||
"pso= stage=CS wave_lanes_min=64 atomic64_flags=0x400000",
|
||||
1,
|
||||
0,
|
||||
),
|
||||
("pso=compute stage=CS", 0, 1),
|
||||
(
|
||||
"pso=compute stage=CS wave_lanes_min=64 atomic64_flags=",
|
||||
0,
|
||||
1,
|
||||
),
|
||||
] {
|
||||
let log = format!(r#"{{"event":"shader_d3dmetal_gap","detail":"{detail}"}}"#);
|
||||
let summary = summarize_jsonl(&log);
|
||||
assert_eq!(summary.shader_gaps.len(), 1, "detail={detail:?}");
|
||||
assert_eq!(
|
||||
summary.shader_gap_groups.len(),
|
||||
1,
|
||||
"detail={detail:?} lost its record"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_identity, missing_identity,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
summary.shader_gaps_missing_constraints, missing_constraints,
|
||||
"detail={detail:?}"
|
||||
);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.count, 1, "detail={detail:?}");
|
||||
let recorded: usize = group.variants.iter().map(|v| v.count).sum();
|
||||
assert_eq!(recorded, 1, "detail={detail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #590: the fields a malformed record does carry are still reported.
|
||||
#[test]
|
||||
fn a_partly_malformed_gap_record_keeps_the_fields_it_has() {
|
||||
let log =
|
||||
r#"{"event":"shader_d3dmetal_gap","detail":"pso=compute stage=CS wave_lanes_min=64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
let group = &summary.shader_gap_groups[0];
|
||||
assert_eq!(group.pso.as_deref(), Some("compute"));
|
||||
assert_eq!(group.stage.as_deref(), Some("CS"));
|
||||
assert_eq!(
|
||||
group.variants,
|
||||
[ShaderGapVariant {
|
||||
wave_lanes_min: Some("64".into()),
|
||||
atomic64_flags: None,
|
||||
count: 1,
|
||||
}]
|
||||
);
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 1);
|
||||
}
|
||||
|
||||
/// #590: a run with no gap records produces no groups and no missing-field counts, so
|
||||
/// the trace renders as it did before the grouping existed.
|
||||
#[test]
|
||||
fn a_run_with_no_gaps_has_no_groups() {
|
||||
let log = r#"{"ts_ms":10,"tid":1,"level":"INFO","sub":"d3d12_xs","event":"shader_gate","detail":"pso=compute stage=CS decision=pass_dxil hr=0x00000000 kind=dxil shader_stage=5 sm=6.6 bytes=1234 dxil=800 accc=0 sfi0=0x4000 wave_ops=1 int64_ops=0 atomic64=typed, wave_lanes=64-64"}"#;
|
||||
let summary = summarize_jsonl(log);
|
||||
assert_eq!(summary.shader_gate.total, 1);
|
||||
assert!(summary.shader_gaps.is_empty());
|
||||
assert!(summary.shader_gap_groups.is_empty());
|
||||
assert_eq!(summary.shader_gaps_missing_identity, 0);
|
||||
assert_eq!(summary.shader_gaps_missing_constraints, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,667 @@
|
||||
//! Run reports for the blocker queue (docs/process/working-method.md, "Run protocol").
|
||||
//!
|
||||
//! One JSONL log is one run. [`report_run`] reduces it to what decides the next task: how the
|
||||
//! run ended, how far it got, and everything it stopped on. [`RunReport::signatures`] turns
|
||||
//! those into the fixed strings blocker issues are titled with, so two people who hit the
|
||||
//! same thing file the same issue. [`render_summary`] puts several runs side by side.
|
||||
//!
|
||||
//! What a log cannot show is said, not guessed: a run with no `run_end` record has an unknown
|
||||
//! outcome, and a stall cannot be told from slow presentation because frames are logged at
|
||||
//! powers of two.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// BetterXen's own guest modules. A fault whose innermost frame is in one of them is ours.
|
||||
const BETTERXEN_MODULES: &[&str] = &[
|
||||
"d3d12_xs.dll",
|
||||
"xmem.dll",
|
||||
"xcrdapi.dll",
|
||||
"xgameruntime.dll",
|
||||
"xg_xs.dll",
|
||||
"acphal.dll",
|
||||
"xapu.dll",
|
||||
"chad.dll",
|
||||
"gameinput.dll",
|
||||
"bx_runtime_veh.dll",
|
||||
"bx_shader_bridge.dll",
|
||||
"ffx_bvh_hooks.dll",
|
||||
];
|
||||
|
||||
/// How a run ended, from the launcher's `run_end` record.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
pub enum RunEnd {
|
||||
/// No `run_end` record: the launcher was killed, or the log predates the record.
|
||||
#[default]
|
||||
Unknown,
|
||||
/// The guest exited by itself with this status.
|
||||
Exited(i32),
|
||||
/// The launcher's `--timeout` stopped it: the run lasted as long as it was allowed to.
|
||||
TimedOut,
|
||||
/// A signal stopped the launcher.
|
||||
Signalled(i32),
|
||||
/// CrossOver could not be started.
|
||||
LaunchFailed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RunReport {
|
||||
pub events: u64,
|
||||
/// Guest clock span of the log, in milliseconds.
|
||||
pub span_ms: u64,
|
||||
pub end: RunEnd,
|
||||
/// The last power-of-two frame count logged: at least this many frames were presented.
|
||||
pub frames_at_least: Option<u64>,
|
||||
/// Unimplemented calls reached, by signature, with how often.
|
||||
pub unimplemented: BTreeMap<String, u64>,
|
||||
/// For each unimplemented signature, the distinct caller chains runtime_veh logged for it
|
||||
/// (`stub_caller`: `module+offset < module+offset < module+offset`, the stub first), at most
|
||||
/// [`MAX_CALLERS_SHOWN`] each, in the order first seen.
|
||||
pub callers: BTreeMap<String, Vec<String>>,
|
||||
/// Faults whose innermost frame is in a BetterXen module, by module.
|
||||
pub faults: BTreeMap<String, u64>,
|
||||
/// Exceptions nothing handled.
|
||||
pub unhandled_exceptions: u64,
|
||||
/// Pipeline stages that reached the shader gate, by "kind decision" (for example
|
||||
/// "stream reject_unclassified_dxil").
|
||||
pub shader_gate: BTreeMap<String, u64>,
|
||||
/// Refused pipeline creations by kind.
|
||||
pub pipelines_refused: BTreeMap<String, u64>,
|
||||
/// Draws and dispatches skipped with a null pipeline bound (a lower bound).
|
||||
pub skipped_work_at_least: Option<u64>,
|
||||
}
|
||||
|
||||
fn json_str<'a>(line: &'a str, key: &str) -> Option<&'a str> {
|
||||
let needle = format!("\"{key}\":\"");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let rest = &line[start..];
|
||||
// Details do not contain escaped quotes in practice; stop at the first unescaped one.
|
||||
let mut end = 0;
|
||||
let bytes = rest.as_bytes();
|
||||
while end < bytes.len() {
|
||||
if bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\') {
|
||||
return Some(&rest[..end]);
|
||||
}
|
||||
end += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn json_u64(line: &str, key: &str) -> Option<u64> {
|
||||
let needle = format!("\"{key}\":");
|
||||
let start = line.find(&needle)? + needle.len();
|
||||
let digits = &line[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
fn number_after(detail: &str, key: &str) -> Option<u64> {
|
||||
let start = detail.find(key)? + key.len();
|
||||
let digits = &detail[start..];
|
||||
let end = digits
|
||||
.find(|c: char| !c.is_ascii_digit())
|
||||
.unwrap_or(digits.len());
|
||||
digits[..end].parse().ok()
|
||||
}
|
||||
|
||||
/// `IXUser[3]::slot_3` -> `unimplemented IXUser slot 3`;
|
||||
/// `XboxDevice[81]::GetFrameStatisticsX` -> `unimplemented XboxDevice slot 81 (GetFrameStatisticsX)`.
|
||||
fn vtable_signature(detail: &str) -> String {
|
||||
let parsed = (|| {
|
||||
let open = detail.find('[')?;
|
||||
let close = detail[open..].find(']')? + open;
|
||||
let slot: u32 = detail[open + 1..close].parse().ok()?;
|
||||
let method = detail[close + 1..].strip_prefix("::")?;
|
||||
Some((&detail[..open], slot, method))
|
||||
})();
|
||||
match parsed {
|
||||
Some((interface, slot, method)) if method.starts_with("slot_") || method.is_empty() => {
|
||||
format!("unimplemented {interface} slot {slot}")
|
||||
}
|
||||
Some((interface, slot, method)) => {
|
||||
format!("unimplemented {interface} slot {slot} ({method})")
|
||||
}
|
||||
None => format!("unimplemented {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Caller chains kept per unimplemented signature.
|
||||
pub const MAX_CALLERS_SHOWN: usize = 4;
|
||||
|
||||
/// The report signature of a stub detail: `Iface[n]::Method` (a vtable slot) or `dll!Symbol`.
|
||||
fn stub_signature(detail: &str) -> String {
|
||||
if detail.contains("]::") {
|
||||
vtable_signature(detail)
|
||||
} else {
|
||||
format!("unimplemented {detail}")
|
||||
}
|
||||
}
|
||||
|
||||
/// The module of the innermost stack frame in an `av_context` detail (`... | stack: A.dll+12 B.dll+34`).
|
||||
fn fault_module(detail: &str) -> Option<&str> {
|
||||
let stack = detail.split("stack: ").nth(1)?;
|
||||
let frame = stack.split_whitespace().next()?;
|
||||
Some(frame.split('+').next().unwrap_or(frame))
|
||||
}
|
||||
|
||||
fn is_betterxen_module(module: &str) -> bool {
|
||||
BETTERXEN_MODULES
|
||||
.iter()
|
||||
.any(|m| m.eq_ignore_ascii_case(module))
|
||||
}
|
||||
|
||||
/// Reduces one run's JSONL log to its report.
|
||||
pub fn report_run(input: &str) -> RunReport {
|
||||
let mut report = RunReport::default();
|
||||
let mut first_ts = None;
|
||||
let mut last_ts = 0;
|
||||
for line in input.lines() {
|
||||
let line = line.trim();
|
||||
if !line.starts_with('{') {
|
||||
continue;
|
||||
}
|
||||
report.events += 1;
|
||||
let event = json_str(line, "event").unwrap_or("");
|
||||
let detail = json_str(line, "detail").unwrap_or("");
|
||||
if event == "run_end" {
|
||||
report.end = match detail {
|
||||
d if d.starts_with("outcome=exited") => {
|
||||
let status = d
|
||||
.split("status=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.trim().parse().ok());
|
||||
status.map_or(RunEnd::Unknown, RunEnd::Exited)
|
||||
}
|
||||
"outcome=timeout" => RunEnd::TimedOut,
|
||||
d if d.starts_with("outcome=signal") => {
|
||||
RunEnd::Signalled(number_after(d, "signal=").unwrap_or(0) as i32)
|
||||
}
|
||||
"outcome=launch_failed" => RunEnd::LaunchFailed,
|
||||
_ => RunEnd::Unknown,
|
||||
};
|
||||
continue; // the launcher's record carries no guest timestamp
|
||||
}
|
||||
if let Some(ts) = json_u64(line, "ts_ms") {
|
||||
first_ts.get_or_insert(ts);
|
||||
last_ts = last_ts.max(ts);
|
||||
}
|
||||
match event {
|
||||
"presentx_frames" => {
|
||||
if let Some(n) = number_after(detail, "presented=") {
|
||||
report.frames_at_least = Some(report.frames_at_least.unwrap_or(0).max(n));
|
||||
}
|
||||
}
|
||||
"unimpl_vtable" => {
|
||||
*report
|
||||
.unimplemented
|
||||
.entry(vtable_signature(detail))
|
||||
.or_default() += 1
|
||||
}
|
||||
"unimpl_api" => {
|
||||
*report
|
||||
.unimplemented
|
||||
.entry(format!("unimplemented {detail}"))
|
||||
.or_default() += 1
|
||||
}
|
||||
"stub_caller" => {
|
||||
if let Some((stub, chain)) = detail.split_once(" <- ") {
|
||||
let chains = report.callers.entry(stub_signature(stub)).or_default();
|
||||
if chains.len() < MAX_CALLERS_SHOWN && !chains.iter().any(|c| c == chain) {
|
||||
chains.push(chain.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
"av_context" => {
|
||||
if let Some(module) = fault_module(detail).filter(|m| is_betterxen_module(m)) {
|
||||
*report.faults.entry(module.to_owned()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
"unhandled_exception" => report.unhandled_exceptions += 1,
|
||||
"shader_gate" => {
|
||||
let kind = detail
|
||||
.split("pso=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split_whitespace().next());
|
||||
let decision = detail
|
||||
.split("decision=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split_whitespace().next());
|
||||
if let (Some(kind), Some(decision)) = (kind, decision) {
|
||||
*report
|
||||
.shader_gate
|
||||
.entry(format!("{kind} {decision}"))
|
||||
.or_default() += 1;
|
||||
}
|
||||
}
|
||||
"pipeline_refused" => {
|
||||
let kind = detail.split(" pipeline refused").next().unwrap_or(detail);
|
||||
*report.pipelines_refused.entry(kind.to_owned()).or_default() += 1;
|
||||
}
|
||||
"null_render_skip" => {
|
||||
if let Some(n) = number_after(detail, "total skipped=") {
|
||||
report.skipped_work_at_least =
|
||||
Some(report.skipped_work_at_least.unwrap_or(0).max(n));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
report.span_ms = first_ts.map_or(0, |first| last_ts.saturating_sub(first));
|
||||
report
|
||||
}
|
||||
|
||||
impl RunReport {
|
||||
/// The strings blocker issues are titled with (`[blocker] <signature>`), most severe first.
|
||||
pub fn signatures(&self) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
match self.end {
|
||||
RunEnd::Exited(status) if status != 0 => out.push(format!("exit status {status}")),
|
||||
RunEnd::LaunchFailed => out.push("launch failed".to_owned()),
|
||||
_ => {}
|
||||
}
|
||||
if self.unhandled_exceptions > 0 {
|
||||
out.push("unhandled exception".to_owned());
|
||||
}
|
||||
out.extend(
|
||||
self.faults
|
||||
.keys()
|
||||
.map(|module| format!("fault in {module}")),
|
||||
);
|
||||
out.extend(self.unimplemented.keys().cloned());
|
||||
if self.skipped_work_at_least.is_some() {
|
||||
out.push("draws or dispatches skipped with a null pipeline".to_owned());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// True when the run reached the frame loop and stopped on nothing: the Boot gate's
|
||||
/// per-run condition, except for its length, which the caller sets with `--timeout`.
|
||||
pub fn clean_boot(&self) -> bool {
|
||||
self.end == RunEnd::TimedOut
|
||||
&& self.frames_at_least.is_some()
|
||||
&& self.unimplemented.is_empty()
|
||||
&& self.faults.is_empty()
|
||||
&& self.unhandled_exceptions == 0
|
||||
}
|
||||
}
|
||||
|
||||
fn end_text(end: &RunEnd) -> String {
|
||||
match end {
|
||||
RunEnd::Unknown => "unknown (no run_end record)".to_owned(),
|
||||
RunEnd::Exited(status) => format!("exited by itself, status {status}"),
|
||||
RunEnd::TimedOut => "ran until the timeout".to_owned(),
|
||||
RunEnd::Signalled(signal) => format!("stopped by signal {signal}"),
|
||||
RunEnd::LaunchFailed => "launch failed".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The report of one run, as text.
|
||||
pub fn render_run(name: &str, report: &RunReport) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "Run {name}");
|
||||
let _ = writeln!(out, " outcome : {}", end_text(&report.end));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" frames presented : {}",
|
||||
report
|
||||
.frames_at_least
|
||||
.map_or("none".to_owned(), |n| format!("at least {n}"))
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" log span : {:.1} s, {} events",
|
||||
report.span_ms as f64 / 1000.0,
|
||||
report.events
|
||||
);
|
||||
if !report.unimplemented.is_empty() {
|
||||
let _ = writeln!(out, " unimplemented calls:");
|
||||
for (signature, count) in &report.unimplemented {
|
||||
let _ = writeln!(out, " {count:>7}x {signature}");
|
||||
for chain in report.callers.get(signature).into_iter().flatten() {
|
||||
let _ = writeln!(out, " from {chain}");
|
||||
}
|
||||
}
|
||||
if !report.callers.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" (look a caller up with `bx-cli ghidra <module> <offset>` before running again)"
|
||||
);
|
||||
}
|
||||
}
|
||||
if !report.faults.is_empty() || report.unhandled_exceptions > 0 {
|
||||
let _ = writeln!(out, " faults:");
|
||||
for (module, count) in &report.faults {
|
||||
let _ = writeln!(out, " {count:>7}x fault in {module}");
|
||||
}
|
||||
if report.unhandled_exceptions > 0 {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {:>7}x unhandled exception",
|
||||
report.unhandled_exceptions
|
||||
);
|
||||
}
|
||||
}
|
||||
if !report.shader_gate.is_empty() || !report.pipelines_refused.is_empty() {
|
||||
let _ = writeln!(out, " pipelines:");
|
||||
for (kind, count) in &report.shader_gate {
|
||||
let _ = writeln!(out, " {count:>7}x shader stage: {kind}");
|
||||
}
|
||||
for (kind, count) in &report.pipelines_refused {
|
||||
let _ = writeln!(out, " {count:>7}x refused: {kind}");
|
||||
}
|
||||
if let Some(skipped) = report.skipped_work_at_least {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" at least {skipped} draws or dispatches skipped (null pipeline)"
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Several runs side by side, then every signature with the number of runs that hit it.
|
||||
pub fn render_summary(runs: &[(String, RunReport)]) -> String {
|
||||
let mut out = String::new();
|
||||
let total = runs.len();
|
||||
let _ = writeln!(out, "Summary of {total} run(s)");
|
||||
for (name, report) in runs {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {name}: {}; frames {}; {}",
|
||||
end_text(&report.end),
|
||||
report
|
||||
.frames_at_least
|
||||
.map_or("none".to_owned(), |n| format!(">= {n}")),
|
||||
if report.clean_boot() {
|
||||
"clean"
|
||||
} else {
|
||||
"not clean"
|
||||
}
|
||||
);
|
||||
}
|
||||
let clean = runs.iter().filter(|(_, r)| r.clean_boot()).count();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): {clean} of {total}"
|
||||
);
|
||||
let mut hits: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for (_, report) in runs {
|
||||
for signature in report.signatures() {
|
||||
*hits.entry(signature).or_default() += 1;
|
||||
}
|
||||
}
|
||||
if hits.is_empty() {
|
||||
let _ = writeln!(out, "Signatures: none");
|
||||
} else {
|
||||
let _ = writeln!(out, "Signatures (runs that hit each):");
|
||||
let mut ordered: Vec<_> = hits.into_iter().collect();
|
||||
ordered.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||
for (signature, count) in ordered {
|
||||
let _ = writeln!(out, " {count} of {total} {signature}");
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn line(ts: u64, sub: &str, event: &str, detail: &str) -> String {
|
||||
format!(
|
||||
"{{\"ts_ms\":{ts},\"tid\":1,\"level\":\"INFO\",\"sub\":\"{sub}\",\"event\":\"{event}\",\"detail\":\"{detail}\"}}\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clean_run_reports_frames_span_and_no_signatures() {
|
||||
let log = line(
|
||||
1000,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=1 last hr=0x00000000",
|
||||
) + &line(
|
||||
4000,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=64 last hr=0x00000000",
|
||||
) + &line(0, "bx_cli", "run_end", "outcome=timeout");
|
||||
let report = report_run(&log);
|
||||
assert_eq!(report.frames_at_least, Some(64));
|
||||
assert_eq!(
|
||||
report.span_ms, 3000,
|
||||
"the launcher's record must not stretch the guest span"
|
||||
);
|
||||
assert_eq!(report.end, RunEnd::TimedOut);
|
||||
assert!(report.clean_boot());
|
||||
assert!(report.signatures().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stub_callers_are_listed_under_their_signature() {
|
||||
let log = line(
|
||||
1,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxPipelineState[11]::GetInformationX",
|
||||
) + &line(
|
||||
2,
|
||||
"stub",
|
||||
"stub_caller",
|
||||
"XboxPipelineState[11]::GetInformationX <- d3d12_xs.dll+1f00 < upscaler.dll+5c10 < upscaler.dll+e93e",
|
||||
) + &line(3, "stub", "unimpl_api", "chad.dll!XDspActivate")
|
||||
+ &line(
|
||||
4,
|
||||
"stub",
|
||||
"stub_caller",
|
||||
"chad.dll!XDspActivate <- chad.dll+10 < game.exe+20 < game.exe+30",
|
||||
)
|
||||
+ &line(
|
||||
5,
|
||||
"stub",
|
||||
"stub_caller",
|
||||
"chad.dll!XDspActivate <- chad.dll+10 < game.exe+20 < game.exe+30",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report
|
||||
.callers
|
||||
.get("unimplemented XboxPipelineState slot 11 (GetInformationX)"),
|
||||
Some(&vec![
|
||||
"d3d12_xs.dll+1f00 < upscaler.dll+5c10 < upscaler.dll+e93e".to_owned()
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
report
|
||||
.callers
|
||||
.get("unimplemented chad.dll!XDspActivate")
|
||||
.map(Vec::len),
|
||||
Some(1),
|
||||
"a repeated chain is kept once"
|
||||
);
|
||||
let text = render_run("run", &report);
|
||||
assert!(text.contains(" from chad.dll+10 < game.exe+20 < game.exe+30"));
|
||||
assert!(text.contains("bx-cli ghidra <module> <offset>"));
|
||||
assert_eq!(
|
||||
report.signatures().len(),
|
||||
2,
|
||||
"callers add no signatures of their own"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unimplemented_calls_become_stable_signatures() {
|
||||
let log = line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
|
||||
+ &line(
|
||||
2,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxDevice[81]::GetFrameStatisticsX",
|
||||
)
|
||||
+ &line(
|
||||
3,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxDevice[81]::GetFrameStatisticsX",
|
||||
)
|
||||
+ &line(
|
||||
4,
|
||||
"stub",
|
||||
"unimpl_api",
|
||||
"d3d12_xs.dll!CreatePlacedResourceX(texture contents)",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report.unimplemented.get("unimplemented IXUser slot 3"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(
|
||||
report
|
||||
.unimplemented
|
||||
.get("unimplemented XboxDevice slot 81 (GetFrameStatisticsX)"),
|
||||
Some(&2)
|
||||
);
|
||||
assert!(report.signatures().contains(
|
||||
&"unimplemented d3d12_xs.dll!CreatePlacedResourceX(texture contents)".to_owned()
|
||||
));
|
||||
assert!(
|
||||
!report.clean_boot(),
|
||||
"an unimplemented call is not a clean run"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_counts_only_when_its_innermost_frame_is_a_betterxen_module() {
|
||||
let ours = line(
|
||||
1,
|
||||
"runtime_veh",
|
||||
"av_context",
|
||||
"rip=1 fault=2 | stack: XCRDAPI.dll+9a51 ntdll.dll+10",
|
||||
);
|
||||
let theirs = line(
|
||||
2,
|
||||
"runtime_veh",
|
||||
"av_context",
|
||||
"rip=1 fault=2 | stack: title.exe+10 XCRDAPI.dll+9a51",
|
||||
);
|
||||
let report = report_run(&(ours + &theirs));
|
||||
assert_eq!(report.faults.get("XCRDAPI.dll"), Some(&1));
|
||||
assert_eq!(report.faults.len(), 1);
|
||||
assert_eq!(report.signatures(), vec!["fault in XCRDAPI.dll".to_owned()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_of_a_run_is_read_from_the_launcher_record() {
|
||||
let exited = report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=5"));
|
||||
assert_eq!(exited.end, RunEnd::Exited(5));
|
||||
assert_eq!(exited.signatures(), vec!["exit status 5".to_owned()]);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=exited status=0")).signatures(),
|
||||
Vec::<String>::new()
|
||||
);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=signal signal=15")).end,
|
||||
RunEnd::Signalled(15)
|
||||
);
|
||||
assert_eq!(
|
||||
report_run(&line(0, "bx_cli", "run_end", "outcome=launch_failed")).end,
|
||||
RunEnd::LaunchFailed
|
||||
);
|
||||
// No record: unknown, and never "clean".
|
||||
let unknown = report_run(&line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=8 last hr=0x0",
|
||||
));
|
||||
assert_eq!(unknown.end, RunEnd::Unknown);
|
||||
assert!(!unknown.clean_boot());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipelines_are_counted_by_kind() {
|
||||
let log = line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"shader_gate",
|
||||
"pso=stream stage=VS decision=reject_unclassified_dxil hr=0x80004001",
|
||||
) + &line(
|
||||
2,
|
||||
"d3d12_xs",
|
||||
"shader_gate",
|
||||
"pso=compute stage=CS decision=pass_dxil hr=0x00000000",
|
||||
) + &line(
|
||||
3,
|
||||
"d3d12_xs",
|
||||
"pipeline_refused",
|
||||
"deserialized graphics (console code) pipeline refused hr=0x80004001",
|
||||
) + &line(
|
||||
4,
|
||||
"d3d12_xs",
|
||||
"null_render_skip",
|
||||
"DrawInstanced with a null pipeline bound; total skipped=4",
|
||||
) + &line(
|
||||
5,
|
||||
"d3d12_xs",
|
||||
"null_render_skip",
|
||||
"DrawInstanced with a null pipeline bound; total skipped=8",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report.shader_gate.get("stream reject_unclassified_dxil"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(report.shader_gate.get("compute pass_dxil"), Some(&1));
|
||||
assert_eq!(
|
||||
report
|
||||
.pipelines_refused
|
||||
.get("deserialized graphics (console code)"),
|
||||
Some(&1)
|
||||
);
|
||||
assert_eq!(report.skipped_work_at_least, Some(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_summary_counts_runs_per_signature_and_clean_runs() {
|
||||
let clean = report_run(
|
||||
&(line(
|
||||
1,
|
||||
"d3d12_xs",
|
||||
"presentx_frames",
|
||||
"frames presented=16 last hr=0x0",
|
||||
) + &line(0, "bx_cli", "run_end", "outcome=timeout")),
|
||||
);
|
||||
let stopped = report_run(
|
||||
&(line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
|
||||
+ &line(0, "bx_cli", "run_end", "outcome=exited status=1")),
|
||||
);
|
||||
let text = render_summary(&[
|
||||
("a".to_owned(), clean),
|
||||
("b".to_owned(), stopped.clone()),
|
||||
("c".to_owned(), stopped),
|
||||
]);
|
||||
assert!(
|
||||
text.contains(
|
||||
"Clean runs (frame loop reached, nothing stopped on, ran to the timeout): 1 of 3"
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains(" 2 of 3 exit status 1\n"), "{text}");
|
||||
assert!(
|
||||
text.contains(" 2 of 3 unimplemented IXUser slot 3\n"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_that_are_not_json_records_are_ignored() {
|
||||
let report = report_run("warning: not a record\n\n{\"broken\n");
|
||||
assert_eq!(
|
||||
report.events, 1,
|
||||
"a line starting with a brace is counted even when malformed"
|
||||
);
|
||||
assert!(report.signatures().is_empty());
|
||||
}
|
||||
}
|
||||
+117
-21
@@ -4,11 +4,15 @@
|
||||
Checks only tracked files:
|
||||
1. no merge-conflict markers in tracked text files;
|
||||
2. every relative Markdown link points at a tracked file or directory;
|
||||
3. every workflow file under .github/workflows parses as YAML.
|
||||
3. every fragment (``#heading``) in a Markdown link resolves to a real
|
||||
heading in the target Markdown file, including in-page ``](#foo)``
|
||||
links validated against the same file's headings;
|
||||
4. every workflow file under .github/workflows parses as YAML.
|
||||
|
||||
External URLs and in-page anchors are not fetched or validated, so the result
|
||||
does not depend on the network. Exit status is 1 when a problem is found. Pass --require-yaml to fail, not skip,
|
||||
when PyYAML is missing.
|
||||
External URLs (http:, https:, mailto:, //) and bare ``#`` links are not
|
||||
fetched or validated, so the result does not depend on the network.
|
||||
Exit status is 1 when a problem is found. Pass --require-yaml to fail,
|
||||
not skip, when PyYAML is missing.
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
@@ -17,9 +21,16 @@ from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import unquote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MARKER = re.compile(r"^(<{7}( |$)|={7}$|>{7}( |$))")
|
||||
MARKER = re.compile(r"^(<{7}( |$)|\|{7}( |$)|={7}$|>{7}( |$))")
|
||||
LINK = re.compile(r"(?<!\!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
||||
FENCE = re.compile(r"^\s*(```|~~~)")
|
||||
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
|
||||
# GitHub slugs the rendered heading, so an inline link contributes only its
|
||||
# text: ``## See [ADR](x.md)`` slugs as ``see-adr``, not ``see-adrxmd``.
|
||||
# Link syntax inside a code span stays literal, so those spans are set aside
|
||||
# before substituting and put back afterwards.
|
||||
INLINE_LINK = re.compile(r"(?<!\!)\[([^\]]*)\]\([^)]*\)")
|
||||
CODE_SPAN = re.compile(r"(`+)(.+?)\1")
|
||||
|
||||
|
||||
def tracked():
|
||||
@@ -35,6 +46,63 @@ def text(path):
|
||||
return data.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def _slug(text):
|
||||
"""GitHub-style slug: lowercase, strip non-alnum/-/_/space, spaces -> -."""
|
||||
text = text.lower()
|
||||
text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE)
|
||||
return text.replace(" ", "-")
|
||||
|
||||
|
||||
def _heading_text(text):
|
||||
"""Rendered text of a heading: link text in, code spans left literal."""
|
||||
spans = []
|
||||
|
||||
def stash(match):
|
||||
spans.append(match.group(0))
|
||||
return "\x00%d\x00" % (len(spans) - 1)
|
||||
|
||||
stashed = CODE_SPAN.sub(stash, text)
|
||||
substituted = INLINE_LINK.sub(r"\1", stashed)
|
||||
for index, span in enumerate(spans):
|
||||
substituted = substituted.replace("\x00%d\x00" % index, span)
|
||||
return substituted
|
||||
|
||||
|
||||
def markdown_slugs(body):
|
||||
"""Return the set of GitHub-style heading slugs in a Markdown document.
|
||||
|
||||
Duplicate headings get ``-1``, ``-2``, ... suffixes. Headings inside
|
||||
fenced code blocks are ignored.
|
||||
"""
|
||||
slugs = set()
|
||||
seen = {}
|
||||
in_fence = False
|
||||
for line in body.splitlines():
|
||||
if FENCE.match(line):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
m = HEADING.match(line)
|
||||
if not m:
|
||||
continue
|
||||
base = _slug(_heading_text(m.group(2)))
|
||||
if not base:
|
||||
continue
|
||||
# Advance the numeric suffix until we find a slug that has not
|
||||
# already been emitted. Counting only identical bases is not
|
||||
# enough: a literal heading such as ``Foo-1`` may already own
|
||||
# ``foo-1``, so the next ``Foo`` must become ``foo-2``.
|
||||
count = seen.get(base, 0)
|
||||
slug = base if count == 0 else f"{base}-{count}"
|
||||
while slug in slugs:
|
||||
count += 1
|
||||
slug = f"{base}-{count}"
|
||||
seen[base] = count + 1
|
||||
slugs.add(slug)
|
||||
return slugs
|
||||
|
||||
|
||||
def check_markers(files, problems):
|
||||
for path in files:
|
||||
if path.endswith((".patch", ".diff")):
|
||||
@@ -47,9 +115,30 @@ def check_markers(files, problems):
|
||||
problems.append(f"{path}:{number}: merge conflict marker")
|
||||
|
||||
|
||||
def _resolve_link(path, target):
|
||||
"""Resolve a relative link target to a repo-root-relative POSIX path."""
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def check_links(files, problems):
|
||||
known = set(files)
|
||||
dirs = {str(d) for f in files for d in PurePosixPath(f).parents}
|
||||
slug_cache = {}
|
||||
|
||||
def slugs_for(md_path):
|
||||
if md_path not in slug_cache:
|
||||
slug_cache[md_path] = markdown_slugs(text(md_path) or "")
|
||||
return slug_cache[md_path]
|
||||
|
||||
for path in files:
|
||||
if not path.endswith(".md") or path.startswith(("artifacts/", "third_party/")):
|
||||
continue
|
||||
@@ -61,24 +150,31 @@ def check_links(files, problems):
|
||||
if in_fence:
|
||||
continue
|
||||
line = re.sub(r"`[^`]*`", "", line)
|
||||
for target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|#|//)", target, re.I):
|
||||
for raw_target in LINK.findall(line):
|
||||
if re.match(r"^([a-z][a-z0-9+.-]*:|//)", raw_target, re.I):
|
||||
continue
|
||||
target = unquote(target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target:
|
||||
if raw_target == "#":
|
||||
continue
|
||||
base = PurePosixPath(path).parent
|
||||
resolved = PurePosixPath(target.lstrip("/")) if target.startswith("/") else base / target
|
||||
parts = []
|
||||
for part in resolved.parts:
|
||||
if part == "..":
|
||||
if parts:
|
||||
parts.pop()
|
||||
elif part != ".":
|
||||
parts.append(part)
|
||||
norm = "/".join(parts)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
fragment = ""
|
||||
if "#" in raw_target:
|
||||
fragment = unquote(raw_target.split("#", 1)[1])
|
||||
target = unquote(raw_target.split("#", 1)[0].split("?", 1)[0])
|
||||
if not target and not fragment:
|
||||
continue
|
||||
if target:
|
||||
norm = _resolve_link(path, target)
|
||||
if norm and norm not in known and norm not in dirs:
|
||||
problems.append(f"{path}:{number}: broken relative link '{target}'")
|
||||
continue
|
||||
else:
|
||||
norm = path
|
||||
if fragment and norm.endswith(".md") and norm in known:
|
||||
if fragment not in slugs_for(norm):
|
||||
shown = raw_target
|
||||
problems.append(
|
||||
f"{path}:{number}: broken fragment '#{fragment}' "
|
||||
f"in link '{shown}' (heading not found)"
|
||||
)
|
||||
|
||||
|
||||
def check_workflows(files, problems, require_yaml):
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for scripts/audit/docs_hygiene.py anchor validation.
|
||||
|
||||
Run with:
|
||||
python3 -m unittest scripts/audit/test_docs_hygiene.py
|
||||
"""
|
||||
import importlib.util
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
_MODULE_PATH = Path(__file__).resolve().parent / "docs_hygiene.py"
|
||||
_spec = importlib.util.spec_from_file_location("docs_hygiene", _MODULE_PATH)
|
||||
docs_hygiene = importlib.util.module_from_spec(_spec)
|
||||
sys.modules["docs_hygiene"] = docs_hygiene
|
||||
_spec.loader.exec_module(docs_hygiene)
|
||||
|
||||
|
||||
class SlugTests(unittest.TestCase):
|
||||
def test_basic_slug(self):
|
||||
slugs = docs_hygiene.markdown_slugs("# Hello World\n")
|
||||
self.assertIn("hello-world", slugs)
|
||||
|
||||
def test_strips_punctuation(self):
|
||||
slugs = docs_hygiene.markdown_slugs("## What's new? (2024)\n")
|
||||
self.assertIn("whats-new-2024", slugs)
|
||||
|
||||
def test_keeps_underscore_and_hyphen(self):
|
||||
slugs = docs_hygiene.markdown_slugs("### foo_bar-baz\n")
|
||||
self.assertIn("foo_bar-baz", slugs)
|
||||
|
||||
def test_duplicate_headings(self):
|
||||
body = "# Setup\n\n# Setup\n\n# Setup\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("setup", slugs)
|
||||
self.assertIn("setup-1", slugs)
|
||||
self.assertIn("setup-2", slugs)
|
||||
|
||||
def test_suffix_skips_literal_heading_slug(self):
|
||||
# Regression: counting identical bases alone lets a generated
|
||||
# suffix collide with a literal heading slug, so the third `Foo`
|
||||
# also became `foo-1` and a link to the wrong heading validated.
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_suffix_skips_multiple_literal_heading_slugs(self):
|
||||
body = "# Foo\n\n# Foo-1\n\n# Foo-2\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2", "foo-3", "foo-4"})
|
||||
|
||||
def test_three_identical_headings(self):
|
||||
body = "# Foo\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo", "foo-1", "foo-2"})
|
||||
|
||||
def test_literal_slug_before_duplicates(self):
|
||||
body = "# Foo-1\n\n# Foo\n\n# Foo\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"foo-1", "foo", "foo-2"})
|
||||
|
||||
def test_heading_link_contributes_only_its_text(self):
|
||||
# GitHub slugs the rendered heading, where the link's URL is gone.
|
||||
# Slugging the raw source appended the URL and made the first real
|
||||
# link to the anchor look broken.
|
||||
slugs = docs_hygiene.markdown_slugs("## Setup [guide](other.md) notes\n")
|
||||
self.assertEqual(slugs, {"setup-guide-notes"})
|
||||
|
||||
def test_heading_link_matches_github_for_the_readme_heading(self):
|
||||
# The exact heading at README.md:53; GitHub renders
|
||||
# `#active-milestone--m2-first-rendered-frame--shader-format-gate`.
|
||||
body = ("### Active Milestone \u2014 [M2: First Rendered Frame & Shader "
|
||||
"Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)\n")
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(
|
||||
slugs, {"active-milestone--m2-first-rendered-frame--shader-format-gate"})
|
||||
|
||||
def test_heading_link_duplicate_still_gets_a_suffix(self):
|
||||
body = "## See [ADR](a.md) notes\n\n## See [ADR](b.md) notes\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertEqual(slugs, {"see-adr-notes", "see-adr-notes-1"})
|
||||
|
||||
def test_heading_link_inside_a_code_span_stays_literal(self):
|
||||
# GitHub keeps `[x](y)` literal inside a code span, so its URL stays in
|
||||
# the slug. Substituting links first made this `code-x-span`.
|
||||
slugs = docs_hygiene.markdown_slugs("## Code `[x](y)` span\n")
|
||||
self.assertEqual(slugs, {"code-xy-span"})
|
||||
|
||||
def test_heading_mixes_a_code_span_and_a_link(self):
|
||||
# Only the real link loses its URL; the code span keeps its text.
|
||||
slugs = docs_hygiene.markdown_slugs("## See `a` and [b](c.md)\n")
|
||||
self.assertEqual(slugs, {"see-a-and-b"})
|
||||
|
||||
def test_heading_double_backtick_code_span(self):
|
||||
# GitHub's own renderer gives `#use-a-b-cdmd-here` for this heading:
|
||||
# the inner single-backtick run closes the outer span early, so the
|
||||
# `[c](d.md)` after it is a real link and loses its URL. Asserting the
|
||||
# observed GitHub anchor keeps this honest rather than assuming the
|
||||
# "obvious" answer.
|
||||
slugs = docs_hygiene.markdown_slugs("## Use ``a `b` [c](d.md)`` here\n")
|
||||
self.assertEqual(slugs, {"use-a-b-cdmd-here"})
|
||||
|
||||
def test_heading_image_is_not_treated_as_a_link(self):
|
||||
# An image contributes its alt text through GitHub's rendering, but
|
||||
# the `(?<!\!)` guard must keep this path unchanged for now.
|
||||
slugs = docs_hygiene.markdown_slugs("##  caption\n")
|
||||
self.assertEqual(len(slugs), 1)
|
||||
|
||||
def test_fenced_code_block_ignored(self):
|
||||
body = "```\n# Not A Heading\n```\n\n# Real Heading\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertIn("real-heading", slugs)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_tilde_fence_ignored(self):
|
||||
body = "~~~\n# Not A Heading\n~~~\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
self.assertNotIn("not-a-heading", slugs)
|
||||
|
||||
def test_atx_levels(self):
|
||||
body = "# One\n## Two\n### Three\n#### Four\n##### Five\n###### Six\n"
|
||||
slugs = docs_hygiene.markdown_slugs(body)
|
||||
for s in ("one", "two", "three", "four", "five", "six"):
|
||||
self.assertIn(s, slugs)
|
||||
|
||||
|
||||
class CheckLinksTests(unittest.TestCase):
|
||||
"""Exercise check_links with a synthetic in-memory file set."""
|
||||
|
||||
def _run(self, files):
|
||||
"""files: dict mapping repo-relative path -> Markdown body."""
|
||||
problems = []
|
||||
original_text = docs_hygiene.text
|
||||
|
||||
def fake_text(path):
|
||||
return files.get(path)
|
||||
|
||||
docs_hygiene.text = fake_text
|
||||
try:
|
||||
docs_hygiene.check_links(list(files), problems)
|
||||
finally:
|
||||
docs_hygiene.text = original_text
|
||||
return problems
|
||||
|
||||
def test_existing_heading_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](b.md#hello-world)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_in_page_anchor_passes(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Hello World\n\n[link](#hello-world)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#no-such-heading)\n",
|
||||
"docs/b.md": "# Hello World\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#no-such-heading", problems[0])
|
||||
self.assertIn("heading not found", problems[0])
|
||||
|
||||
def test_in_page_nonexistent_heading_fails(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "# Real\n\n[link](#this-heading-does-not-exist)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#this-heading-does-not-exist", problems[0])
|
||||
|
||||
def test_duplicate_heading_addressable(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#setup-1)\n",
|
||||
"docs/b.md": "# Setup\n\n# Setup\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_fenced_heading_not_a_slug(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](b.md#not-a-heading)\n",
|
||||
"docs/b.md": "```\n# Not A Heading\n```\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("#not-a-heading", problems[0])
|
||||
|
||||
def test_external_url_with_fragment_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](https://example.com/page#nonexistent)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_mailto_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](mailto:foo@example.com#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_protocol_relative_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](//example.com/page#frag)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_bare_hash_skipped(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](#)\n",
|
||||
})
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
def test_missing_file_still_reported(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](nonexistent.md#foo)\n",
|
||||
})
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("broken relative link", problems[0])
|
||||
|
||||
def test_fragment_on_non_markdown_not_checked(self):
|
||||
problems = self._run({
|
||||
"docs/a.md": "[link](image.png#foo)\n",
|
||||
"docs/image.png": None,
|
||||
})
|
||||
# image.png is binary (text returns None) but it exists in the
|
||||
# file list, so the link itself resolves; fragment is not checked.
|
||||
self.assertEqual(problems, [])
|
||||
|
||||
|
||||
class MarkerTests(unittest.TestCase):
|
||||
"""The conflict-marker check must catch all four markers, including the diff3 one."""
|
||||
|
||||
def _markers(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / "f.md").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_markers({"f.md": text}, problems)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_every_marker_kind_is_reported(self):
|
||||
for line in ["<<<<<<< HEAD", "||||||| merged common ancestors", "=======", ">>>>>>> topic"]:
|
||||
problems = self._markers(line + "\n")
|
||||
self.assertEqual(len(problems), 1, f"{line!r} was not reported: {problems}")
|
||||
self.assertIn("f.md:1", problems[0])
|
||||
|
||||
def test_diff3_base_marker_is_reported(self):
|
||||
base = self._markers("||||||| merged common ancestors\n")
|
||||
self.assertEqual(len(base), 1, "the diff3 base marker must be reported")
|
||||
self.assertIn("conflict marker", base[0])
|
||||
|
||||
def test_a_diff3_block_reports_all_four_lines(self):
|
||||
block = "<<<<<<< HEAD\na\n||||||| merged common ancestors\nb\n=======\nc\n>>>>>>> topic\n"
|
||||
problems = self._markers(block)
|
||||
self.assertEqual(len(problems), 4, problems)
|
||||
|
||||
def test_ordinary_content_is_not_a_marker(self):
|
||||
for text in ["| a | b |\n", "||||||\n", "======\n", "prose with | pipes\n", "---\n"]:
|
||||
self.assertEqual(self._markers(text), [], f"{text!r} was wrongly reported")
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
"""check_workflows must reject unparseable YAML."""
|
||||
|
||||
def _check(self, text):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
(root / ".github" / "workflows").mkdir(parents=True)
|
||||
(root / ".github" / "workflows" / "a.yml").write_text(text, encoding="utf-8")
|
||||
previous = docs_hygiene.ROOT
|
||||
docs_hygiene.ROOT = root
|
||||
try:
|
||||
problems = []
|
||||
docs_hygiene.check_workflows({".github/workflows/a.yml": text}, problems, require_yaml=True)
|
||||
return problems
|
||||
finally:
|
||||
docs_hygiene.ROOT = previous
|
||||
|
||||
def test_parses_a_valid_workflow(self):
|
||||
self.assertEqual(self._check("on: push\njobs:\n b:\n runs-on: ubuntu-latest\n"), [])
|
||||
|
||||
def test_reports_invalid_yaml(self):
|
||||
problems = self._check("on: [push\n")
|
||||
self.assertEqual(len(problems), 1, problems)
|
||||
self.assertIn("a.yml", problems[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/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
|
||||
image_sample v3, [v4, v7], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D
|
||||
image_sample_lz v[0:2], [v4, v9, v2], s[8:15], s[16:19] dmask:0x7 dim:SQ_RSRC_IMG_3D
|
||||
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()
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Build the shader corpus (#649) locally. For every kernel in shader-transpiler/corpus/hlsl:
|
||||
# <name>.xs.cso / .xs.lst console container (DXIL + ACCC/FSPX) and listing, from xdxc
|
||||
# <name>.pix.lst console ISA listing with encodings, from the PIX compiler
|
||||
# <name>.pc.cso DXIL from the public PC DXC, for a D3DMetal reference run
|
||||
# <name>.code.bin / .aco.s console machine code extracted from the ACCC chunk, and its
|
||||
# llvm-mc gfx1030 disassembly
|
||||
# Outputs go to $OUT (default target/shader-corpus, which git ignores) and must not be
|
||||
# committed: they are compiler outputs from authorized GDK tools (see the corpus README).
|
||||
#
|
||||
# Required environment:
|
||||
# WINE a CrossOver/Wine loader that accepts --bottle (CrossOver's bin/wine)
|
||||
# BOTTLE a scratch bottle for the compilers (never a title's bottle)
|
||||
# XDXC the console xdxc.exe (GDK, xbox/bin/gen9)
|
||||
# PIX_DXC the console PIX dxc.exe (GDK, bin/Scarlett/pixsc)
|
||||
# DXC the PC dxc.exe from DXC release v1.9.2609
|
||||
# LLVM_MC llvm-mc built with the AMDGPU target
|
||||
set -euo pipefail
|
||||
|
||||
for var in WINE BOTTLE XDXC PIX_DXC DXC LLVM_MC; do
|
||||
if [ -z "${!var:-}" ]; then
|
||||
echo "error: set $var (see the header of $0)" >&2
|
||||
exit 2
|
||||
fi
|
||||
done
|
||||
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
src="$root/shader-transpiler/corpus/hlsl"
|
||||
out=${OUT:-$root/target/shader-corpus}
|
||||
mkdir -p "$out"
|
||||
|
||||
# Wine takes Windows paths; Z: maps the host root.
|
||||
win() { printf 'Z:%s' "$1"; }
|
||||
compile() { WINEDEBUG=-all "$WINE" --bottle "$BOTTLE" "$@"; }
|
||||
|
||||
failures=0
|
||||
for hlsl in "$src"/*.hlsl; do
|
||||
name=$(basename "$hlsl" .hlsl)
|
||||
log="$out/$name.log"
|
||||
: > "$log"
|
||||
if ! compile "$XDXC" -T cs_6_6 -E main -Fo "$(win "$out/$name.xs.cso")" -Fc "$(win "$out/$name.xs.lst")" \
|
||||
"$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: xdxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$PIX_DXC" -T cs_6_6 -E main -Fc "$(win "$out/$name.pix.lst")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PIX dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! compile "$DXC" -nologo -T cs_6_6 -E main -Fo "$(win "$out/$name.pc.cso")" "$(win "$hlsl")" >>"$log" 2>&1; then
|
||||
echo "FAIL $name: PC dxc (see $log)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
if ! python3 "$root/scripts/shader-corpus/extract_code.py" "$out/$name.xs.cso" \
|
||||
--bin "$out/$name.code.bin" --asm "$out/$name.aco.s" --llvm-mc "$LLVM_MC"; then
|
||||
echo "FAIL $name: code extraction or decode (see $out/$name.aco.s)"; failures=$((failures + 1)); continue
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$failures" -ne 0 ]; then
|
||||
echo "FAIL: shader corpus ($failures kernel(s) failed)"
|
||||
exit 1
|
||||
fi
|
||||
# Sums of the compiled inputs, so two people with the compilers can confirm they hold the same
|
||||
# corpus (README, "Reproducibility"). Local only, like every other output.
|
||||
(cd "$out" && shasum -a 256 ./*.xs.cso ./*.pc.cso > SHA256SUMS)
|
||||
echo "PASS: shader corpus built in $out"
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Extract the RDNA 2 code from a console-compiled DXBC container (#649).
|
||||
|
||||
The layout below was derived from containers the console compiler produced for BetterXen's own
|
||||
corpus kernels (shader-transpiler/corpus/README.md). Every assumption is checked; anything that
|
||||
does not match raises instead of guessing.
|
||||
|
||||
- DXBC: chunk count at byte 28, chunk offsets from byte 32; each chunk is a FourCC, a u32 size
|
||||
and the payload. The console code is in the `ACCC` chunk.
|
||||
- FSPX (the ACCC payload): a 16-byte header (magic `FSPX`, version, section count, total size),
|
||||
then one 16-byte entry per section: kind, offset, size, reserved (0). Offsets are relative to
|
||||
the start of the payload.
|
||||
- Section kind 6 holds the code. It starts with `v_nop_xbox_data` instructions that carry the
|
||||
shader hash, followed by gfx1030 machine code ending in `s_endpgm`. A `v_nop_xbox_data` is the
|
||||
public VOP3 `v_nop` opcode (top 16 bits of the first word 0xD580) whose third source operand is
|
||||
a 32-bit literal (operand value 255), which makes it 12 bytes; the public decoder rejects that
|
||||
form. A plain `v_nop` (8 bytes, no literal) is ordinary code and is not skipped.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
FSPX_MAGIC = b"FSPX"
|
||||
CODE_SECTION_KIND = 6
|
||||
XBOX_DATA_NOP_HIGH = 0xD580 # VOP3 v_nop, top 16 bits of the first word
|
||||
XBOX_DATA_NOP_BYTES = 12 # two VOP3 words and one 32-bit literal
|
||||
VOP3_SRC2_SHIFT = 18 # second word: src0 [8:0], src1 [17:9], src2 [26:18]
|
||||
VOP3_OPERAND_MASK = 0x1FF
|
||||
OPERAND_LITERAL = 255 # public gfx10 operand value for "a 32-bit literal follows"
|
||||
S_ENDPGM = 0xBF810000
|
||||
|
||||
|
||||
class LayoutError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def chunk(container, fourcc):
|
||||
if container[:4] != b"DXBC" or len(container) < 32:
|
||||
raise LayoutError("not a DXBC container")
|
||||
count = struct.unpack_from("<I", container, 28)[0]
|
||||
if 32 + 4 * count > len(container):
|
||||
raise LayoutError("chunk table overruns the container")
|
||||
for i in range(count):
|
||||
offset = struct.unpack_from("<I", container, 32 + 4 * i)[0]
|
||||
if offset + 8 > len(container):
|
||||
raise LayoutError(f"chunk {i} header overruns the container")
|
||||
size = struct.unpack_from("<I", container, offset + 4)[0]
|
||||
if container[offset:offset + 4] == fourcc:
|
||||
if offset + 8 + size > len(container):
|
||||
raise LayoutError(f"{fourcc.decode()} chunk overruns the container")
|
||||
return container[offset + 8:offset + 8 + size]
|
||||
raise LayoutError(f"no {fourcc.decode()} chunk")
|
||||
|
||||
|
||||
def sections(payload):
|
||||
if payload[:4] != FSPX_MAGIC or len(payload) < 16:
|
||||
raise LayoutError("ACCC payload does not start with FSPX")
|
||||
_version, count, total = struct.unpack_from("<III", payload, 4)
|
||||
if total != len(payload):
|
||||
raise LayoutError(f"FSPX total size {total} != payload size {len(payload)}")
|
||||
table_end = 16 + 16 * count
|
||||
if table_end > len(payload):
|
||||
raise LayoutError("FSPX section table overruns the payload")
|
||||
result = []
|
||||
for i in range(count):
|
||||
kind, offset, size, reserved = struct.unpack_from("<IIII", payload, 16 + 16 * i)
|
||||
if reserved != 0:
|
||||
raise LayoutError(f"FSPX section {i} reserved word is {reserved:#x}, not 0")
|
||||
if offset < table_end or offset + size > len(payload):
|
||||
raise LayoutError(f"FSPX section {i} [{offset}, {offset + size}) is out of bounds")
|
||||
result.append((kind, offset, size))
|
||||
return result
|
||||
|
||||
|
||||
def code_section(payload):
|
||||
matches = [(o, s) for k, o, s in sections(payload) if k == CODE_SECTION_KIND]
|
||||
if len(matches) != 1:
|
||||
raise LayoutError(f"expected one kind-{CODE_SECTION_KIND} section, found {len(matches)}")
|
||||
offset, size = matches[0]
|
||||
return payload[offset:offset + size]
|
||||
|
||||
|
||||
def is_xbox_data_nop(code):
|
||||
"""True when `code` starts with a v_nop whose third source operand is a literal."""
|
||||
if len(code) < XBOX_DATA_NOP_BYTES:
|
||||
return False
|
||||
first, second = struct.unpack_from("<II", code, 0)
|
||||
return (first >> 16 == XBOX_DATA_NOP_HIGH
|
||||
and (second >> VOP3_SRC2_SHIFT) & VOP3_OPERAND_MASK == OPERAND_LITERAL)
|
||||
|
||||
|
||||
def strip_xbox_data(code):
|
||||
"""Return (machine code, number of v_nop_xbox_data skipped)."""
|
||||
skipped = 0
|
||||
while is_xbox_data_nop(code):
|
||||
code = code[XBOX_DATA_NOP_BYTES:]
|
||||
skipped += 1
|
||||
return code, skipped
|
||||
|
||||
|
||||
def until_endpgm(code):
|
||||
"""Cut after the first dword-aligned s_endpgm. A literal that happens to equal it is not
|
||||
excluded here; the disassembler run is the authority on instruction boundaries."""
|
||||
for i in range(0, len(code) - 3, 4):
|
||||
if struct.unpack_from("<I", code, i)[0] == S_ENDPGM:
|
||||
return code[:i + 4]
|
||||
raise LayoutError("no s_endpgm in the code section")
|
||||
|
||||
|
||||
def extract(container):
|
||||
code, skipped = strip_xbox_data(code_section(chunk(container, b"ACCC")))
|
||||
return until_endpgm(code), skipped
|
||||
|
||||
|
||||
def disassemble(code, llvm_mc):
|
||||
text = " ".join(f"0x{b:02x}" for b in code)
|
||||
run = subprocess.run(
|
||||
[llvm_mc, "-arch=amdgcn", "-mcpu=gfx1030", "--disassemble", "-show-encoding"],
|
||||
input=text, capture_output=True, text=True, check=False,
|
||||
)
|
||||
lines = [ln.strip() for ln in run.stdout.splitlines() if ln.strip() and not ln.strip().startswith(".")]
|
||||
problems = [ln for ln in run.stderr.splitlines() if "invalid" in ln.lower() or "warning" in ln.lower()]
|
||||
return lines, problems
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("container", help="console-compiled .cso (DXBC with an ACCC chunk)")
|
||||
parser.add_argument("--bin", help="write the extracted machine code here")
|
||||
parser.add_argument("--asm", help="write the llvm-mc disassembly here (needs --llvm-mc)")
|
||||
parser.add_argument("--llvm-mc", help="path to llvm-mc with the AMDGPU target")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
code, skipped = extract(open(args.container, "rb").read())
|
||||
except LayoutError as error:
|
||||
print(f"error: {args.container}: {error}", file=sys.stderr)
|
||||
return 2
|
||||
if args.bin:
|
||||
open(args.bin, "wb").write(code)
|
||||
status = 0
|
||||
summary = f"{len(code)} code bytes, {skipped} v_nop_xbox_data skipped"
|
||||
if args.llvm_mc:
|
||||
lines, problems = disassemble(code, args.llvm_mc)
|
||||
summary += f", {len(lines)} instructions"
|
||||
if problems or not lines or "s_endpgm" not in lines[-1]:
|
||||
summary += ", DECODE PROBLEMS"
|
||||
status = 1
|
||||
if args.asm:
|
||||
open(args.asm, "w").write("\n".join(lines + problems) + "\n")
|
||||
print(f"{args.container}: {summary}")
|
||||
return status
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,106 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Unit tests for extract_code.py on synthetic containers (no GDK or compiler needed)."""
|
||||
|
||||
import importlib.util
|
||||
import struct
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location("extract_code", Path(__file__).with_name("extract_code.py"))
|
||||
ec = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(ec)
|
||||
|
||||
S_NOP = struct.pack("<I", 0xBF800000) # public gfx10 encoding of s_nop 0
|
||||
S_ENDPGM = struct.pack("<I", 0xBF810000)
|
||||
# Synthetic, not compiler output: the v_nop opcode with made-up low bits, a second word whose
|
||||
# third source operand is 255 (literal) with made-up low bits, and a made-up literal.
|
||||
XBOX_DATA = struct.pack("<III", 0xD5801111, 0x03FC2222, 0x33333333)
|
||||
# The public VOP3 encoding of a plain `v_nop` (llvm-mc -mcpu=gfx1030): 8 bytes, no literal.
|
||||
V_NOP_E64 = struct.pack("<II", 0xD5800000, 0x02010080)
|
||||
|
||||
|
||||
def fspx(sections, total=None):
|
||||
"""sections: list of (kind, bytes). Builds an FSPX payload with the parsed layout."""
|
||||
count = len(sections)
|
||||
offset = 16 + 16 * count
|
||||
table, body = b"", b""
|
||||
for kind, data in sections:
|
||||
table += struct.pack("<IIII", kind, offset + len(body), len(data), 0)
|
||||
body += data
|
||||
size = 16 + len(table) + len(body)
|
||||
return b"FSPX" + struct.pack("<III", 1, count, size if total is None else total) + table + body
|
||||
|
||||
|
||||
def dxbc(chunks):
|
||||
"""chunks: list of (fourcc, bytes)."""
|
||||
header = 32 + 4 * len(chunks)
|
||||
offsets, body = [], b""
|
||||
for fourcc, data in chunks:
|
||||
offsets.append(header + len(body))
|
||||
body += fourcc + struct.pack("<I", len(data)) + data
|
||||
total = header + len(body)
|
||||
head = b"DXBC" + b"\0" * 16 + struct.pack("<III", 1, total, len(chunks))
|
||||
return head + b"".join(struct.pack("<I", o) for o in offsets) + body
|
||||
|
||||
|
||||
class ExtractTests(unittest.TestCase):
|
||||
def test_extracts_code_after_xbox_data_nops(self):
|
||||
code = XBOX_DATA * 3 + S_NOP + S_ENDPGM + b"\0" * 8
|
||||
container = dxbc([(b"DXIL", b"x" * 12), (b"ACCC", fspx([(0, b"a" * 28), (6, code), (7, b"b" * 8)]))])
|
||||
extracted, skipped = ec.extract(container)
|
||||
self.assertEqual(skipped, 3)
|
||||
self.assertEqual(extracted, S_NOP + S_ENDPGM)
|
||||
|
||||
def test_plain_v_nop_is_code_not_xbox_data(self):
|
||||
# A plain v_nop at the start of the code must not be skipped as 12 bytes, which would
|
||||
# misalign everything after it.
|
||||
code = V_NOP_E64 + S_NOP + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (code, 0))
|
||||
|
||||
def test_plain_v_nop_after_xbox_data_is_kept(self):
|
||||
code = XBOX_DATA * 2 + V_NOP_E64 + S_ENDPGM
|
||||
container = dxbc([(b"ACCC", fspx([(6, code)]))])
|
||||
self.assertEqual(ec.extract(container), (V_NOP_E64 + S_ENDPGM, 2))
|
||||
|
||||
def test_no_xbox_data_nops(self):
|
||||
container = dxbc([(b"ACCC", fspx([(6, S_NOP + S_ENDPGM)]))])
|
||||
self.assertEqual(ec.extract(container), (S_NOP + S_ENDPGM, 0))
|
||||
|
||||
def test_missing_accc(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no ACCC chunk"):
|
||||
ec.extract(dxbc([(b"DXIL", b"x" * 4)]))
|
||||
|
||||
def test_not_fspx(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "does not start with FSPX"):
|
||||
ec.extract(dxbc([(b"ACCC", b"ABCD" + b"\0" * 12)]))
|
||||
|
||||
def test_total_size_mismatch(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "total size"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM)], total=999))]))
|
||||
|
||||
def test_section_inside_table_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 4, 4) # section offset points into the header
|
||||
with self.assertRaisesRegex(ec.LayoutError, "out of bounds"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_nonzero_reserved_word_is_rejected(self):
|
||||
payload = bytearray(fspx([(6, S_ENDPGM)]))
|
||||
struct.pack_into("<I", payload, 16 + 12, 1)
|
||||
with self.assertRaisesRegex(ec.LayoutError, "reserved word"):
|
||||
ec.extract(dxbc([(b"ACCC", bytes(payload))]))
|
||||
|
||||
def test_needs_exactly_one_code_section(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 0"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(0, S_ENDPGM)]))]))
|
||||
with self.assertRaisesRegex(ec.LayoutError, "found 2"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_ENDPGM), (6, S_ENDPGM)]))]))
|
||||
|
||||
def test_code_without_endpgm(self):
|
||||
with self.assertRaisesRegex(ec.LayoutError, "no s_endpgm"):
|
||||
ec.extract(dxbc([(b"ACCC", fspx([(6, S_NOP * 4)]))]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,110 @@
|
||||
# Shader corpus (Phase 0, #649)
|
||||
|
||||
A corpus of BetterXen-authored compute kernels compiled for the console, so the RDNA 2 shader
|
||||
translator ([ADR 0008](../../docs/adr/0008-m2-shader-format-gate.md), Branch D2) can be tested
|
||||
against inputs whose correct behaviour is known independently of the translator
|
||||
([AGENTS.md](../../AGENTS.md) §5).
|
||||
|
||||
For each kernel in [`hlsl/`](hlsl), three compilers produce:
|
||||
|
||||
- the **console container** a title would ship: DXBC with `DXIL` **and** an `ACCC` chunk whose
|
||||
payload is an `FSPX` package holding the RDNA 2 code;
|
||||
- **the console compiler's listing** of the RDNA 2 code for the same source, with encodings (compiler output, not
|
||||
Microsoft documentation);
|
||||
- **PC DXIL** from the public DXC, which runs on D3DMetal today and gives the reference result.
|
||||
|
||||
## What is committed and what is not
|
||||
|
||||
| Committed | Not committed |
|
||||
|---|---|
|
||||
| The HLSL kernels in `hlsl/` (original BetterXen code, GPL-3.0-or-later) | Every compiler output: containers, listings, extracted code and disassembly |
|
||||
| [`scripts/shader-corpus/build.sh`](../../scripts/shader-corpus/build.sh) and [`extract_code.py`](../../scripts/shader-corpus/extract_code.py) with its unit tests | The GDK, its compilers, and any file from it |
|
||||
| Layout facts derived from our own outputs (below) | |
|
||||
|
||||
The console compilers come from authorized GDK material and run on BetterXen's own HLSL only.
|
||||
Their outputs stay in `target/shader-corpus/` (git-ignored) and are never committed. Run the
|
||||
compilers in a scratch bottle, never in a title's bottle.
|
||||
|
||||
The layout facts below are derived from those outputs and **are** published in this file. On
|
||||
2026-11-29 the repository owner reported that the team had approved publishing them, and decided
|
||||
that BetterXen is no longer a clean-room project ([CONTRIBUTING](../../CONTRIBUTING.md), #650):
|
||||
contributors may use the GDK compilers and read this file. The compilers, their outputs and the
|
||||
GDK itself are still never committed.
|
||||
|
||||
## Reproducibility
|
||||
|
||||
The corpus can only be rebuilt by someone who has the GDK compilers. CI cannot rebuild it, and a
|
||||
contributor without the GDK cannot reproduce its inputs. That limits what the corpus proves: it
|
||||
checks a translator against shaders with known source, on the word of whoever built it.
|
||||
|
||||
To let two people with access confirm they hold the same inputs, `build.sh` writes
|
||||
`target/shader-corpus/SHA256SUMS` with the SHA-256 of every `.xs.cso` and `.pc.cso`. The sums are
|
||||
not listed here yet: they are worth committing only once two independent builds agree, which
|
||||
also shows whether the compilers' output is deterministic.
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
WINE=/Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin/wine \
|
||||
BOTTLE=<scratch bottle> \
|
||||
XDXC=<GDK>/…/xbox/bin/gen9/xdxc.exe \
|
||||
PIX_DXC=<GDK>/…/bin/Scarlett/pixsc/dxc.exe \
|
||||
DXC=<DXC v1.9.2609>/bin/x64/dxc.exe \
|
||||
LLVM_MC=$(brew --prefix llvm)/bin/llvm-mc \
|
||||
scripts/shader-corpus/build.sh
|
||||
```
|
||||
|
||||
All eight kernels currently build, and every kernel's console code extracts and decodes with
|
||||
LLVM's public `gfx1030` disassembler (2026-11-28, Apple Silicon, CrossOver 26.3):
|
||||
|
||||
| Kernel | What it exercises | Console instructions |
|
||||
|---|---|---|
|
||||
| `fill` | integer ALU | 11 |
|
||||
| `branch` | divergent if/else | 17 |
|
||||
| `loop` | per-lane trip count, early exit | 60 |
|
||||
| `lds` | groupshared memory, barriers, tree reduction | 58 |
|
||||
| `wave` | `WaveActiveSum`, `WavePrefixSum`, `WaveReadLaneFirst`, `WaveActiveBallot` | 47 |
|
||||
| `atomic` | global `InterlockedAdd` / `InterlockedMax` with returned values | 57 |
|
||||
| `floatmath` | `mad`, `sqrt`, `rcp`, float/uint conversion | 22 |
|
||||
| `groupid` | 2D groups, `SV_GroupID`, `SV_GroupThreadID`, `SV_GroupIndex` | 17 |
|
||||
|
||||
`extract_code.py`'s unit tests use synthetic containers and need no GDK:
|
||||
`python3 -m unittest scripts/shader-corpus/test_extract_code.py`.
|
||||
|
||||
## Layout facts (derived from our own outputs)
|
||||
|
||||
- **Container:** `xdxc` keeps the `DXIL` chunk and adds `ACCC`. Title containers can be `ACCC`-only;
|
||||
the `ACCC` format is the same. `bx-cli shader` rejects these containers with the same `FSPX`
|
||||
error as a title's console-only shaders, so the corpus is a faithful stand-in for that format.
|
||||
- **`FSPX`:** a 16-byte header (magic `FSPX`, version `1`, section count, total size equal to the
|
||||
payload size), then one 16-byte entry per section: kind, offset from the start of the payload,
|
||||
size, and a reserved `0`. The corpus containers have four sections, of kinds 0, 1, 6 and 7.
|
||||
- **Code:** section kind 6. It starts with `v_nop_xbox_data` instructions that carry the shader
|
||||
hash: the public VOP3 `v_nop` opcode (top 16 bits `0xD580`) with a literal as its third source
|
||||
operand, 12 bytes each, a form the public decoder rejects. A plain `v_nop` (8 bytes) is ordinary
|
||||
code. Every corpus kernel has three `v_nop_xbox_data`. They are followed by `gfx1030` machine code ending in `s_endpgm`, then
|
||||
padding.
|
||||
- **Two console backends.** `xdxc`'s `ACCC` code comes from its ACO step; the PIX compiler's
|
||||
listing comes from its NewBE step. They generate different code for the same source (for example,
|
||||
the inline buffer descriptor's word 3 is `0x31016fac` from ACO and `0x11014fac` from NewBE). The
|
||||
NewBE listing documents the console ABI (#638); the ACO code is what `ACCC` containers carry.
|
||||
Both use the root UAV address in `s[4:5]` here.
|
||||
|
||||
## Observations so far
|
||||
|
||||
- `wave` compiles to the cross-lane instructions that matter for running 64-wide waves on 32-wide
|
||||
Apple GPUs: DPP `row_shr` and `quad_perm`, `v_permlanex16`, `v_readlane` and `v_readfirstlane`.
|
||||
- **Open question:** in `wave`, LLVM decodes one instruction in the ballot sequence as
|
||||
`v_cmp_class_f16` with literal `0x7c01`, although the kernel has no half-precision code. Either
|
||||
ACO genuinely emits it there, or the console gives that opcode a meaning the public `gfx1030`
|
||||
decoder does not know. The reference runs below should tell.
|
||||
|
||||
## Next steps
|
||||
|
||||
1. A reference runner: dispatch each kernel's PC DXIL on D3DMetal with fixed inputs and record
|
||||
the output buffers as expected results, plus CPU-computed expectations where the result is a
|
||||
pure function of the inputs.
|
||||
2. The decoder (Phase 1), checked instruction by instruction against LLVM's disassembly and the
|
||||
NewBE listings.
|
||||
3. More kernels as the decoder grows: textures and samplers, structured control flow with nested
|
||||
loops, 64-bit atomics, and wave32 versus wave64 variants.
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Global atomics: add and max into shared counters, with returned old values.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint before;
|
||||
InterlockedAdd(output[0], x, before);
|
||||
InterlockedMax(output[1], x);
|
||||
output[2u + tid.x] = before;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Divergent control flow: lanes take different sides of an if/else.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint r;
|
||||
if ((x & 1u) != 0u) { r = x * 3u + 1u; } else { r = x >> 1; }
|
||||
output[tid.x] = r;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Integer ALU: multiply, shift, xor-add (no memory reads).
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint v = tid.x * 0x9e3779b1u;
|
||||
output[tid.x] = (v ^ (v >> 15)) + 0x01234567u;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Float ALU and conversions: fma, sqrt, rcp, float<->uint.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
float f = (float)input[tid.x] * asfloat(c0);
|
||||
float g = mad(f, 0.5f, 1.0f);
|
||||
float h = sqrt(abs(g)) + rcp(g + 2.0f);
|
||||
output[tid.x] = asuint(h) ^ (uint)floor(h * 256.0f);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// System values: group id, group thread id and flattened indices with a 2D group.
|
||||
[RootSignature(BX_RS)] [numthreads(8, 8, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID, uint gi : SV_GroupIndex) {
|
||||
uint idx = (gid.y * c0 + gid.x) * 64u + gi;
|
||||
output[idx] = (gtid.x << 24) | (gtid.y << 16) | (tid.x << 8) | tid.y;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Groupshared memory and barriers: a per-group tree reduction.
|
||||
groupshared uint scratch[64];
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID, uint3 gtid : SV_GroupThreadID, uint3 gid : SV_GroupID) {
|
||||
scratch[gtid.x] = input[tid.x];
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
for (uint s = 32u; s > 0u; s >>= 1) {
|
||||
if (gtid.x < s) { scratch[gtid.x] += scratch[gtid.x + s]; }
|
||||
GroupMemoryBarrierWithGroupSync();
|
||||
}
|
||||
if (gtid.x == 0u) { output[gid.x] = scratch[0]; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Loop with a per-lane, data-dependent trip count and an early exit.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint n = input[tid.x] % (c0 + 1u);
|
||||
uint acc = 0u;
|
||||
for (uint i = 0u; i < n; ++i) {
|
||||
acc += i * c1;
|
||||
if (acc > c2) { break; }
|
||||
}
|
||||
output[tid.x] = acc;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// BetterXen shader corpus (#649): original kernel, written for translator tests.
|
||||
// Shared layout: root constants b0 (4 x 32-bit), input SRV t0, output UAV u0.
|
||||
#define BX_RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u0)"
|
||||
cbuffer Root : register(b0) { uint c0; uint c1; uint c2; uint c3; };
|
||||
StructuredBuffer<uint> input : register(t0);
|
||||
RWStructuredBuffer<uint> output : register(u0);
|
||||
|
||||
// Cross-lane wave operations: the costly case when a 64-wide wave runs as two 32-wide halves.
|
||||
[RootSignature(BX_RS)] [numthreads(64, 1, 1)]
|
||||
void main(uint3 tid : SV_DispatchThreadID) {
|
||||
uint x = input[tid.x];
|
||||
uint sum = WaveActiveSum(x);
|
||||
uint prefix = WavePrefixSum(x);
|
||||
uint first = WaveReadLaneFirst(x);
|
||||
uint4 ballot = WaveActiveBallot((x & 1u) != 0u);
|
||||
output[tid.x * 4u + 0u] = sum;
|
||||
output[tid.x * 4u + 1u] = prefix;
|
||||
output[tid.x * 4u + 2u] = first;
|
||||
output[tid.x * 4u + 3u] = countbits(ballot.x) + countbits(ballot.y);
|
||||
}
|
||||
@@ -80,12 +80,14 @@ fn collect(rx: &Receiver<Event>, until: Instant) -> io::Result<(Vec<u8>, Vec<u8>
|
||||
Ok((stdout, stderr, true))
|
||||
}
|
||||
|
||||
fn wait_until(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
|
||||
/// `deadline: None` means the requested timeout is not representable on this clock, so the
|
||||
/// probe is allowed to run without one (#587).
|
||||
fn wait_until(child: &mut Child, deadline: Option<Instant>) -> io::Result<Option<ExitStatus>> {
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
if deadline.is_some_and(|at| Instant::now() >= at) {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
return Ok(None);
|
||||
@@ -112,7 +114,13 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
|
||||
command.env(key, value);
|
||||
}
|
||||
}
|
||||
let deadline = Instant::now() + timeout;
|
||||
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow, so a
|
||||
// huge value would abort the harness with exit 101 instead of one of its verdict codes
|
||||
// (#586). Saturate at the platform maximum instead: the probe then simply never times out.
|
||||
// `--timeout` takes any u64 seconds, and `Instant + Duration` panics on overflow. When the
|
||||
// requested timeout is not representable the probe simply has no deadline; representing
|
||||
// that as `None` avoids inventing a fallback duration that might also not fit (#587).
|
||||
let deadline = Instant::now().checked_add(timeout);
|
||||
let mut child = command.spawn()?;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
pump(
|
||||
@@ -126,8 +134,11 @@ pub fn run_probe(probe: &Path, framework_binary: &Path, timeout: Duration) -> io
|
||||
tx,
|
||||
);
|
||||
let status = wait_until(&mut child, deadline)?;
|
||||
let (stdout, stderr, output_complete) =
|
||||
collect(&rx, deadline.max(Instant::now() + DRAIN_GRACE))?;
|
||||
// With no deadline the probe has already exited, so draining still needs a bound.
|
||||
let drain_until = deadline
|
||||
.unwrap_or_else(Instant::now)
|
||||
.max(Instant::now() + DRAIN_GRACE);
|
||||
let (stdout, stderr, output_complete) = collect(&rx, drain_until)?;
|
||||
Ok(ProbeRun {
|
||||
status,
|
||||
stdout: String::from_utf8_lossy(&stdout).into_owned(),
|
||||
@@ -161,6 +172,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrepresentable_deadline_leaves_the_probe_without_a_timeout() {
|
||||
// `checked_add` returns None for a timeout the clock cannot represent; the runner
|
||||
// must then wait for the probe normally instead of inventing a fallback duration
|
||||
// that could itself overflow (#587).
|
||||
let script = Script::new("nodeadline", "sleep 0.2; exit 0");
|
||||
let run = run_probe(
|
||||
&script.0,
|
||||
std::path::Path::new("/nonexistent/framework"),
|
||||
Duration::from_secs(u64::MAX),
|
||||
)
|
||||
.expect("an unrepresentable deadline must not abort the run");
|
||||
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
|
||||
assert!(run.output_complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_overflowing_timeout_does_not_panic() {
|
||||
// u64::MAX seconds overflows `Instant + Duration`; before #586 this panicked.
|
||||
let script = Script::new("overflow", "exit 0");
|
||||
let run = run_probe(
|
||||
&script.0,
|
||||
std::path::Path::new("/nonexistent/framework"),
|
||||
Duration::from_secs(u64::MAX),
|
||||
);
|
||||
let run = run.expect("an overflowing timeout must still run the probe, not panic");
|
||||
assert_eq!(run.status.and_then(|s| s.code()), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_the_framework_and_only_allowlisted_environment() {
|
||||
let script = Script::new("env", "echo \"args=$*\"; env; echo oops >&2; exit 3");
|
||||
|
||||
@@ -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;
|
||||
}));
|
||||
}
|
||||
@@ -7,6 +7,19 @@
|
||||
//! verification. Section 6 is a byte range only; this module does not
|
||||
//! disassemble it.
|
||||
//!
|
||||
//! Version-1 entries are 12 or 16 bytes. The 12-byte form stays because this
|
||||
//! repository's own synthetic fixtures use it: the tests in this crate and
|
||||
//! `tests/conformance/test_shader_gate`. The 16-byte form `{id, offset, size, 0}`
|
||||
//! is used only when every entry's fourth word is 0 and the first section's
|
||||
//! offset equals `16 + count * 16`, so the first section begins where the
|
||||
//! header and the table end. Any other table keeps the 12-byte parse. For
|
||||
//! 16-byte tables, section 1 is treated as opaque (its bounds are validated and
|
||||
//! recorded in `sections`, while `stage_config` stays `None` and the stage
|
||||
//! remains unknown) rather than requiring the 12-byte synthetic stage layout.
|
||||
//! An offset inside the header plus the table of the stride in use is a layout
|
||||
//! mismatch, including a 16-byte table whose first section starts inside
|
||||
//! `16 + count * 16`.
|
||||
//!
|
||||
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
|
||||
//! count is rejected before any descriptor is compared with another, so
|
||||
//! inspection stays allocation-free and the pairwise check stays bounded.
|
||||
@@ -110,7 +123,14 @@ pub(crate) enum FspxError {
|
||||
}
|
||||
|
||||
const HEADER_LEN: usize = 16;
|
||||
/// 12-byte `{id, offset, size}`.
|
||||
///
|
||||
/// Kept because this repository's own synthetic fixtures use it: the tests
|
||||
/// in this crate and `tests/conformance/test_shader_gate`.
|
||||
const DESCRIPTOR_LEN: usize = 12;
|
||||
/// 16-byte `{id, offset, size, 0}`. Selected when every fourth word is 0 and
|
||||
/// the first section begins at `16 + count * 16`. Otherwise [`DESCRIPTOR_LEN`].
|
||||
const WIDE_DESCRIPTOR_LEN: usize = 16;
|
||||
const STAGE_CONFIG_LEN: usize = 12;
|
||||
|
||||
fn stage_from_abi(raw: u32) -> Option<ShaderStage> {
|
||||
@@ -160,13 +180,13 @@ fn stage_from_body(body: &[u8]) -> Result<(ShaderStage, u8, u8), FspxError> {
|
||||
Ok((stage, shader_model_major, shader_model_minor))
|
||||
}
|
||||
|
||||
fn descriptor_at(payload: &[u8], index: usize) -> Result<(u32, u32, u32), FspxError> {
|
||||
fn descriptor_at(
|
||||
payload: &[u8],
|
||||
index: usize,
|
||||
stride: usize,
|
||||
) -> Result<(u32, u32, u32), FspxError> {
|
||||
let at = HEADER_LEN
|
||||
.checked_add(
|
||||
index
|
||||
.checked_mul(DESCRIPTOR_LEN)
|
||||
.ok_or(FspxError::Truncated)?,
|
||||
)
|
||||
.checked_add(index.checked_mul(stride).ok_or(FspxError::Truncated)?)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
let id = read_u32_le(payload, at).ok_or(FspxError::Truncated)?;
|
||||
let offset = read_u32_le(payload, at + 4).ok_or(FspxError::Truncated)?;
|
||||
@@ -174,10 +194,49 @@ fn descriptor_at(payload: &[u8], index: usize) -> Result<(u32, u32, u32), FspxEr
|
||||
Ok((id, offset, size))
|
||||
}
|
||||
|
||||
/// 16-byte when the table itself says so; otherwise the 12-byte fixture stride.
|
||||
///
|
||||
/// Every entry's fourth `u32` must be 0, and the first section's offset must
|
||||
/// equal `16 + count * 16`. A table that fails either check keeps today's
|
||||
/// 12-byte parse, which still rejects an offset inside its own header and
|
||||
/// table. A 16-byte stride whose first section does start on that boundary
|
||||
/// still rejects a later entry that points inside it.
|
||||
fn descriptor_stride(payload: &[u8], count: usize) -> usize {
|
||||
let Some(wide_end) = count
|
||||
.checked_mul(WIDE_DESCRIPTOR_LEN)
|
||||
.and_then(|bytes| HEADER_LEN.checked_add(bytes))
|
||||
else {
|
||||
return DESCRIPTOR_LEN;
|
||||
};
|
||||
if count == 0 || wide_end > payload.len() {
|
||||
return DESCRIPTOR_LEN;
|
||||
}
|
||||
let Ok(wide_end_u32) = u32::try_from(wide_end) else {
|
||||
return DESCRIPTOR_LEN;
|
||||
};
|
||||
for index in 0..count {
|
||||
let Some(pad_at) = index
|
||||
.checked_mul(WIDE_DESCRIPTOR_LEN)
|
||||
.and_then(|bytes| HEADER_LEN.checked_add(bytes))
|
||||
.and_then(|start| start.checked_add(12))
|
||||
else {
|
||||
return DESCRIPTOR_LEN;
|
||||
};
|
||||
if read_u32_le(payload, pad_at) != Some(0) {
|
||||
return DESCRIPTOR_LEN;
|
||||
}
|
||||
}
|
||||
match read_u32_le(payload, HEADER_LEN + 4) {
|
||||
Some(offset) if offset == wide_end_u32 => WIDE_DESCRIPTOR_LEN,
|
||||
_ => DESCRIPTOR_LEN,
|
||||
}
|
||||
}
|
||||
|
||||
struct FspxHeader {
|
||||
version: u32,
|
||||
flags: u32,
|
||||
count: usize,
|
||||
stride: usize,
|
||||
table_end: usize,
|
||||
}
|
||||
|
||||
@@ -200,6 +259,7 @@ fn read_fspx_header(payload: &[u8]) -> Result<Option<FspxHeader>, FspxError> {
|
||||
version,
|
||||
flags,
|
||||
count: 0,
|
||||
stride: DESCRIPTOR_LEN,
|
||||
table_end: HEADER_LEN,
|
||||
}));
|
||||
}
|
||||
@@ -210,9 +270,8 @@ fn read_fspx_header(payload: &[u8]) -> Result<Option<FspxHeader>, FspxError> {
|
||||
if count > FSPX_MAX_SECTIONS {
|
||||
return Err(FspxError::TooManySections(section_count));
|
||||
}
|
||||
let table_bytes = count
|
||||
.checked_mul(DESCRIPTOR_LEN)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
let stride = descriptor_stride(payload, count);
|
||||
let table_bytes = count.checked_mul(stride).ok_or(FspxError::Truncated)?;
|
||||
let table_end = HEADER_LEN
|
||||
.checked_add(table_bytes)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
@@ -223,6 +282,7 @@ fn read_fspx_header(payload: &[u8]) -> Result<Option<FspxHeader>, FspxError> {
|
||||
version,
|
||||
flags,
|
||||
count,
|
||||
stride,
|
||||
table_end,
|
||||
}))
|
||||
}
|
||||
@@ -236,9 +296,9 @@ fn walk_sections(
|
||||
mut on_section: impl FnMut(FspxSection, &[u8]) -> Result<(), FspxError>,
|
||||
) -> Result<(), FspxError> {
|
||||
for index in 0..header.count {
|
||||
let (id, offset, size) = descriptor_at(payload, index)?;
|
||||
let (id, offset, size) = descriptor_at(payload, index, header.stride)?;
|
||||
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
|
||||
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
|
||||
// `table_end` is at most 16 + 64 * 16 bytes, so it fits in u32.
|
||||
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
|
||||
return Err(FspxError::LayoutMismatch {
|
||||
section_id: id,
|
||||
@@ -249,7 +309,7 @@ fn walk_sections(
|
||||
let end = section_end(offset, size, header.table_end, payload.len())
|
||||
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
|
||||
for prev in 0..index {
|
||||
let (prev_id, prev_off, prev_size) = descriptor_at(payload, prev)?;
|
||||
let (prev_id, prev_off, prev_size) = descriptor_at(payload, prev, header.stride)?;
|
||||
if prev_id == id {
|
||||
return Err(FspxError::DuplicateSection { section_id: id });
|
||||
}
|
||||
@@ -282,7 +342,7 @@ pub(crate) fn scan_fspx(payload: &[u8]) -> Result<Option<FspxStageScan>, FspxErr
|
||||
};
|
||||
let mut stage = None;
|
||||
walk_sections(payload, &header, |section, body| {
|
||||
if section.id == 1 {
|
||||
if section.id == 1 && header.stride == DESCRIPTOR_LEN {
|
||||
stage = Some(stage_from_body(body)?);
|
||||
}
|
||||
Ok(())
|
||||
@@ -307,7 +367,7 @@ pub(crate) fn parse_fspx(payload: &[u8]) -> Result<Option<FspxInfo>, FspxError>
|
||||
walk_sections(payload, &header, |section, body| {
|
||||
match section.id {
|
||||
0 => section0 = Some(section),
|
||||
1 => {
|
||||
1 if header.stride == DESCRIPTOR_LEN => {
|
||||
let (stage, shader_model_major, shader_model_minor) = stage_from_body(body)?;
|
||||
stage_config = Some(FspxStageConfig {
|
||||
offset: section.offset,
|
||||
|
||||
@@ -8,16 +8,20 @@
|
||||
//!
|
||||
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
|
||||
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
|
||||
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
|
||||
//! at most [`FSPX_MAX_SECTIONS`] descriptors, 12 bytes each for this
|
||||
//! repository's synthetic fixtures, or 16 bytes `{id, offset, size, 0}` when
|
||||
//! the table itself selects that stride. A larger count is
|
||||
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
|
||||
//! descriptor whose offset lands inside the header plus descriptor table is
|
||||
//! [`ParseError::FspxLayoutMismatch`], kept apart from
|
||||
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
|
||||
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
|
||||
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
|
||||
//! code byte range. The code bytes are not decoded. This layout is synthetic.
|
||||
//! Parsing it does not establish that a console compiler produced the blob
|
||||
//! and is not Xbox hardware verification.
|
||||
//! code byte range. The code bytes are not decoded. The 12-byte stride is
|
||||
//! this repository's synthetic fixture layout; the 16-byte stride is the
|
||||
//! additional `{id, offset, size, 0}` table. Parsing either one does not
|
||||
//! establish that a console compiler produced the blob and is not Xbox
|
||||
//! hardware verification.
|
||||
//!
|
||||
//! A `DXIL` chunk is a program only when its payload is a `DxilProgramHeader`
|
||||
//! from the public DirectXShaderCompiler layout
|
||||
@@ -29,13 +33,17 @@
|
||||
//! at least 16. `BitcodeSize` must be non-zero, and `8 + BitcodeOffset +
|
||||
//! BitcodeSize` must fit in `SizeInUint32 * 4`. A zero-length bitcode is
|
||||
//! [`ParseError::BadDxilHeader`], matching DXC's `IsValidDxilProgramHeader`,
|
||||
//! so preparation does not copy it.
|
||||
//! so preparation does not copy it. A bitcode payload starting with `NOBC`
|
||||
//! marks a header-only container (no executable bitcode), which keeps `DXIL`
|
||||
//! size and stage metadata but does not classify as executable `DXIL`.
|
||||
//!
|
||||
//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`.
|
||||
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
|
||||
//! copies `container_size` bytes when a `DXIL` chunk is present, including when
|
||||
//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only
|
||||
//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented.
|
||||
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
|
||||
//! including when an accompanying `FSPX` table is malformed, and logs only an
|
||||
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. `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;
|
||||
@@ -44,8 +52,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};
|
||||
|
||||
@@ -97,6 +107,55 @@ pub struct ShaderInspection {
|
||||
pub chunks: Vec<ChunkInfo>,
|
||||
}
|
||||
|
||||
impl ShaderInspection {
|
||||
/// Payload of the first chunk tagged `fourcc`, if present and fully
|
||||
/// inside the container. Returns `None` when absent, when the declared
|
||||
/// size would run past `container_size` or `container`, or when `offset`
|
||||
/// points into the DXBC header or chunk-offset table instead of a chunk
|
||||
/// header.
|
||||
///
|
||||
/// `container` must be the same bytes passed to [`inspect_dxbc`]; the
|
||||
/// inspection only stores chunk metadata, so the original container is
|
||||
/// required to slice out the payload. `ChunkInfo::offset` is relative to
|
||||
/// the start of the `DXBC` container and points at the 8-byte chunk
|
||||
/// header (fourcc + size), so the payload begins at `offset + 8`.
|
||||
///
|
||||
/// A zero-size chunk yields `Some(&[])`: the header is present and
|
||||
/// in-bounds, so an empty payload is a valid result rather than an
|
||||
/// absence. Callers that require a minimum size must check the returned
|
||||
/// slice length.
|
||||
///
|
||||
/// Only the already-parsed `self.chunks` table is consulted; the raw
|
||||
/// chunk table is not re-walked. When several chunks share `fourcc`,
|
||||
/// the first one in table order wins, matching the C++ `find_chunk`.
|
||||
pub fn chunk_payload<'a>(&self, container: &'a [u8], fourcc: &[u8; 4]) -> Option<&'a [u8]> {
|
||||
let chunk = self.chunks.iter().find(|c| &c.fourcc == fourcc)?;
|
||||
let table_bytes = u64::try_from(self.chunks.len()).ok()?.checked_mul(4)?;
|
||||
let table_end = 32u64.checked_add(table_bytes)?;
|
||||
if u64::from(chunk.offset) < table_end {
|
||||
return None;
|
||||
}
|
||||
let start = u64::from(chunk.offset).checked_add(8)?;
|
||||
let end = start.checked_add(u64::from(chunk.size))?;
|
||||
if end > u64::from(self.container_size) {
|
||||
return None;
|
||||
}
|
||||
let start = usize::try_from(start).ok()?;
|
||||
let end = usize::try_from(end).ok()?;
|
||||
if end > container.len() {
|
||||
return None;
|
||||
}
|
||||
container.get(start..end)
|
||||
}
|
||||
|
||||
/// True when a chunk header tagged `fourcc` exists, whatever its
|
||||
/// declared size. Mirrors the C++ `has_chunk_tag`: presence without
|
||||
/// trusting the size.
|
||||
pub fn has_chunk_tag(&self, fourcc: &[u8; 4]) -> bool {
|
||||
self.chunks.iter().any(|c| &c.fourcc == fourcc)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
TooShort,
|
||||
@@ -119,9 +178,9 @@ pub enum ParseError {
|
||||
section_id: u32,
|
||||
},
|
||||
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
|
||||
/// table (`table_end` bytes), which the synthetic layout reserves. The
|
||||
/// table does not follow BetterXen's clean-room layout; it is not reported
|
||||
/// as an out-of-bounds section. The container is still rejected.
|
||||
/// table (`table_end` bytes) reserved by the stride in use (12-byte
|
||||
/// synthetic fixtures, or 16-byte `{id, offset, size, 0}`). It is not
|
||||
/// reported as an out-of-bounds section. The container is still rejected.
|
||||
FspxLayoutMismatch {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
@@ -176,7 +235,7 @@ impl fmt::Display for ParseError {
|
||||
table_end,
|
||||
} => write!(
|
||||
f,
|
||||
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
|
||||
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the FSPX layout"
|
||||
),
|
||||
Self::FspxDuplicateSection { chunk, section_id } => {
|
||||
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
|
||||
@@ -264,14 +323,22 @@ fn record_fspx_stage(
|
||||
}
|
||||
}
|
||||
|
||||
enum DxilProgram {
|
||||
Executable((ShaderStage, u8, u8)),
|
||||
HeaderOnly((ShaderStage, u8, u8)),
|
||||
}
|
||||
|
||||
/// `DxilProgramHeader` check from the public DirectXShaderCompiler container.
|
||||
///
|
||||
/// `SizeInUint32 * 4` must cover the 24-byte header and fit in `payload`.
|
||||
/// `BitcodeOffset` is from the start of `DxilBitcodeHeader` at program byte 8
|
||||
/// and must be at least 16. `BitcodeSize` must be non-zero, and
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program. The
|
||||
/// bitcode bytes are not decoded.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
|
||||
/// `8 + BitcodeOffset + BitcodeSize` must fit in the declared program.
|
||||
///
|
||||
/// A bitcode payload beginning with `NOBC` is a header-only container (for
|
||||
/// example, reflection or signature metadata with bitcode stripped) and is
|
||||
/// reported as [`DxilProgram::HeaderOnly`] rather than executable DXIL.
|
||||
fn read_dxil_program(payload: &[u8]) -> Result<DxilProgram, ()> {
|
||||
const PROGRAM_PREFIX: u64 = 8;
|
||||
const BITCODE_HEADER: u64 = 16;
|
||||
const MIN_PROGRAM: u64 = PROGRAM_PREFIX + BITCODE_HEADER;
|
||||
@@ -300,7 +367,16 @@ fn read_dxil_program(payload: &[u8]) -> Result<(ShaderStage, u8, u8), ()> {
|
||||
if end > program_bytes {
|
||||
return Err(());
|
||||
}
|
||||
Ok(program_stage(program_version))
|
||||
let bitcode_start =
|
||||
usize::try_from(PROGRAM_PREFIX + u64::from(bitcode_offset)).map_err(|_| ())?;
|
||||
let bitcode_end = usize::try_from(end).map_err(|_| ())?;
|
||||
let bitcode = payload.get(bitcode_start..bitcode_end).ok_or(())?;
|
||||
let stage = program_stage(program_version);
|
||||
if bitcode.starts_with(b"NOBC") {
|
||||
Ok(DxilProgram::HeaderOnly(stage))
|
||||
} else {
|
||||
Ok(DxilProgram::Executable(stage))
|
||||
}
|
||||
}
|
||||
|
||||
struct ContainerLimit {
|
||||
@@ -407,6 +483,37 @@ fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKi
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DxilChunkState {
|
||||
has_executable: bool,
|
||||
size: u32,
|
||||
executable_stage: Option<(ShaderStage, u8, u8)>,
|
||||
header_only_stage: Option<(ShaderStage, u8, u8)>,
|
||||
}
|
||||
|
||||
impl DxilChunkState {
|
||||
/// Record a `DXIL` chunk, keeping executable metadata ahead of `NOBC`
|
||||
/// header-only placeholders regardless of chunk order.
|
||||
fn record(&mut self, chunk: usize, size: u32, payload: &[u8]) -> Result<(), ParseError> {
|
||||
match read_dxil_program(payload).map_err(|()| ParseError::BadDxilHeader { chunk })? {
|
||||
DxilProgram::Executable(stage) => {
|
||||
self.has_executable = true;
|
||||
self.size = size;
|
||||
self.executable_stage = Some(stage);
|
||||
}
|
||||
DxilProgram::HeaderOnly(stage) => {
|
||||
if !self.has_executable {
|
||||
self.size = size;
|
||||
}
|
||||
if self.header_only_stage.is_none() {
|
||||
self.header_only_stage = Some(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not
|
||||
/// keep chunk or section lists.
|
||||
pub(crate) struct DxbcSummary {
|
||||
@@ -425,24 +532,16 @@ pub(crate) struct DxbcSummary {
|
||||
///
|
||||
/// A malformed `FSPX` table is still [`Err`], so inspection can report it.
|
||||
pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
let mut has_dxil = false;
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -463,36 +562,40 @@ pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result<DxbcSummary, ParseError> {
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil_stage
|
||||
let (stage, shader_model_major, shader_model_minor) = dxil
|
||||
.executable_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
Ok(DxbcSummary {
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major,
|
||||
shader_model_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size,
|
||||
dxil_size: dxil.size,
|
||||
accc_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// `Ok(Some(container_size))` when the container is structurally valid and
|
||||
/// contains a `DXIL` chunk with a `DxilProgramHeader`. A malformed `FSPX`
|
||||
/// table does not hide that chunk. A `DXIL` fourcc whose payload is not that
|
||||
/// header is [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no `DXIL` chunk.
|
||||
/// contains a `DXIL` chunk with an executable `DxilProgramHeader` (not a
|
||||
/// `NOBC` header-only placeholder). A malformed `FSPX` table does not hide that
|
||||
/// chunk. A `DXIL` fourcc whose payload is not a valid `DxilProgramHeader` is
|
||||
/// [`ParseError::BadDxilHeader`]. `Ok(None)` means the container is
|
||||
/// structurally valid and has no executable `DXIL` chunk.
|
||||
pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError> {
|
||||
let mut has_dxil = false;
|
||||
let header = visit_chunks(bytes, |index, _offset, fourcc, _size, payload| {
|
||||
if &fourcc == b"DXIL" {
|
||||
if read_dxil_program(payload).is_err() {
|
||||
return Err(ParseError::BadDxilHeader { chunk: index });
|
||||
match read_dxil_program(payload) {
|
||||
Ok(DxilProgram::Executable(_)) => has_dxil = true,
|
||||
Ok(DxilProgram::HeaderOnly(_)) => {}
|
||||
Err(()) => return Err(ParseError::BadDxilHeader { chunk: index }),
|
||||
}
|
||||
has_dxil = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -512,27 +615,19 @@ pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result<Option<u32>, ParseError
|
||||
/// container through.
|
||||
pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
let mut chunks = Vec::new();
|
||||
let mut has_dxil = false;
|
||||
let mut dxil = DxilChunkState::default();
|
||||
let mut has_accc = false;
|
||||
let mut has_legacy = false;
|
||||
let mut has_root_signature = false;
|
||||
let mut dxil_size = 0u32;
|
||||
let mut accc_size = 0u32;
|
||||
let mut accc_is_fspx = false;
|
||||
let mut dxil_stage = None;
|
||||
let mut legacy_stage = None;
|
||||
let mut fspx_stage = None;
|
||||
let mut fspx = None;
|
||||
|
||||
let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| {
|
||||
match &fourcc {
|
||||
b"DXIL" => {
|
||||
let stage = read_dxil_program(payload)
|
||||
.map_err(|()| ParseError::BadDxilHeader { chunk: index })?;
|
||||
has_dxil = true;
|
||||
dxil_size = size;
|
||||
dxil_stage = Some(stage);
|
||||
}
|
||||
b"DXIL" => dxil.record(index, size, payload)?,
|
||||
b"ACCC" => {
|
||||
has_accc = true;
|
||||
accc_size = size;
|
||||
@@ -570,21 +665,22 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result<ShaderInspection, ParseError> {
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
let (stage, sm_major, sm_minor) =
|
||||
dxil_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
let (stage, sm_major, sm_minor) = dxil
|
||||
.executable_stage
|
||||
.or(legacy_stage)
|
||||
.or(fspx_stage)
|
||||
.or(dxil.header_only_stage)
|
||||
.unwrap_or((ShaderStage::Unknown, 0, 0));
|
||||
|
||||
Ok(ShaderInspection {
|
||||
kind: kind_from_flags(has_dxil, has_accc, has_legacy),
|
||||
kind: kind_from_flags(dxil.has_executable, has_accc, has_legacy),
|
||||
stage,
|
||||
shader_model_major: sm_major,
|
||||
shader_model_minor: sm_minor,
|
||||
container_size: header.container_size,
|
||||
digest: header.digest,
|
||||
has_root_signature,
|
||||
dxil_size,
|
||||
dxil_size: dxil.size,
|
||||
accc_size,
|
||||
accc_is_fspx,
|
||||
fspx,
|
||||
@@ -691,6 +787,23 @@ mod tests {
|
||||
payload
|
||||
}
|
||||
|
||||
/// Version-1 table of 16-byte `{id, offset, size, 0}` entries. The fourth
|
||||
/// word of each entry stays 0. Bytes past the table stay 0.
|
||||
fn fspx_wide_entries(entries: &[(u32, u32, u32)], len: usize) -> Vec<u8> {
|
||||
assert!(16 + entries.len() * 16 <= len);
|
||||
let mut payload = vec![0u8; len];
|
||||
payload[..4].copy_from_slice(b"FSPX");
|
||||
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
|
||||
payload[8..12].copy_from_slice(&(entries.len() as u32).to_le_bytes());
|
||||
for (index, (id, offset, size)) in entries.iter().enumerate() {
|
||||
let at = 16 + index * 16;
|
||||
payload[at..at + 4].copy_from_slice(&id.to_le_bytes());
|
||||
payload[at + 4..at + 8].copy_from_slice(&offset.to_le_bytes());
|
||||
payload[at + 8..at + 12].copy_from_slice(&size.to_le_bytes());
|
||||
}
|
||||
payload
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_synthetic_dxil_cs_6_6() {
|
||||
let blob = synthetic_dxil_blob();
|
||||
@@ -981,8 +1094,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn truncated_prefixes_do_not_panic() {
|
||||
let mut nobc_dxil = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc_dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let blobs = [
|
||||
synthetic_dxil_blob(),
|
||||
build_synthetic_dxbc(&[(b"DXIL", &nobc_dxil)]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]),
|
||||
build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(20))]),
|
||||
vec![0xFF; 64],
|
||||
@@ -990,6 +1106,8 @@ mod tests {
|
||||
for blob in blobs {
|
||||
for len in 0..=blob.len() {
|
||||
let _ = inspect_dxbc(&blob[..len]);
|
||||
let _ = summarize_dxbc(&blob[..len]);
|
||||
let _ = dxil_container_len(&blob[..len]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1006,9 +1124,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
|
||||
// Inside the 16-byte header, inside the first descriptor, inside the
|
||||
// descriptor itself, and the last reserved byte.
|
||||
for offset in [0u32, 8, 16, 28, 39] {
|
||||
// Inside the 16-byte header, the offset-1 case, inside the first
|
||||
// descriptor, inside the descriptor itself, and the last reserved byte.
|
||||
for offset in [0u32, 1, 8, 16, 28, 39] {
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
@@ -1031,6 +1149,8 @@ mod tests {
|
||||
}
|
||||
|
||||
// The first byte after the table is outside the reserved region.
|
||||
// 12-byte fixtures stay on that stride: this table's entries are 12
|
||||
// bytes, so the 16-byte rule does not apply.
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
|
||||
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
@@ -1038,6 +1158,202 @@ mod tests {
|
||||
assert!(summarize_dxbc(&blob).is_ok());
|
||||
}
|
||||
|
||||
/// Four 16-byte entries `{0, 1, 6, 7}`. Section 0 begins at byte 80, which
|
||||
/// is `16 + 4 * 16`. Section 1 is an opaque 20-byte section whose first
|
||||
/// word is not a synthetic stage enum, section 6 is the code range, and
|
||||
/// section 7 follows the code.
|
||||
fn synthetic_wide_fspx() -> Vec<u8> {
|
||||
let mut payload =
|
||||
fspx_wide_entries(&[(0, 80, 8), (1, 88, 20), (6, 108, 16), (7, 124, 4)], 128);
|
||||
payload[80..88].copy_from_slice(&[0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00]);
|
||||
payload[88..108].copy_from_slice(&[
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
]);
|
||||
payload[108..124].copy_from_slice(b"SYNTH_RDNA2_CODE");
|
||||
payload[124..128].copy_from_slice(&[0x01, 0x00, 0x00, 0x00]);
|
||||
payload
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_byte_fspx_classifies_as_accc_with_section_bounds() {
|
||||
let payload = synthetic_wide_fspx();
|
||||
assert_eq!(
|
||||
&payload[80..88],
|
||||
&[0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00]
|
||||
);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
let info =
|
||||
inspect_dxbc(&blob).expect("16-byte section table with opaque 20-byte section 1");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert!(info.accc_is_fspx);
|
||||
assert_eq!(info.dxil_size, 0);
|
||||
assert!(!info.chunks.iter().any(|chunk| &chunk.fourcc == b"DXIL"));
|
||||
assert_eq!(info.stage, ShaderStage::Unknown);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (0, 0));
|
||||
assert_eq!(info.accc_size, 128);
|
||||
|
||||
let fspx = info.fspx.expect("fspx table");
|
||||
assert_eq!(fspx.version, 1);
|
||||
assert_eq!(
|
||||
fspx.sections,
|
||||
vec![
|
||||
FspxSection {
|
||||
id: 0,
|
||||
offset: 80,
|
||||
size: 8
|
||||
},
|
||||
FspxSection {
|
||||
id: 1,
|
||||
offset: 88,
|
||||
size: 20
|
||||
},
|
||||
FspxSection {
|
||||
id: 6,
|
||||
offset: 108,
|
||||
size: 16
|
||||
},
|
||||
FspxSection {
|
||||
id: 7,
|
||||
offset: 124,
|
||||
size: 4
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
fspx.section0.map(|section| (section.offset, section.size)),
|
||||
Some((80, 8))
|
||||
);
|
||||
assert!(fspx.stage_config.is_none());
|
||||
let code = fspx.rdna_code.expect("section 6");
|
||||
assert_eq!((code.offset, code.size), (108, 16));
|
||||
assert_eq!(
|
||||
fspx.rdna_code_bytes(&payload),
|
||||
Some(b"SYNTH_RDNA2_CODE".as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
fspx.section7.map(|section| (section.offset, section.size)),
|
||||
Some((124, 4))
|
||||
);
|
||||
|
||||
let mut c_info = BxShaderInspection {
|
||||
kind: 99,
|
||||
..BxShaderInspection::default()
|
||||
};
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 3);
|
||||
assert_eq!(c_info.stage, 0);
|
||||
assert_eq!(c_info.shader_model_major, 0);
|
||||
assert_eq!(c_info.shader_model_minor, 0);
|
||||
assert_eq!(c_info.dxil_chunk_size, 0);
|
||||
assert_eq!(c_info.accc_chunk_size, 128);
|
||||
}
|
||||
|
||||
/// `bx-cli shader` prints this on `Ok` from `inspect_dxbc` and prints
|
||||
/// `error:` on `Err`. The 16-byte container must take the success path.
|
||||
#[test]
|
||||
fn bx_cli_shader_reports_accc_for_sixteen_byte_fspx() {
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &synthetic_wide_fspx())]);
|
||||
let info = inspect_dxbc(&blob).unwrap_or_else(|err| {
|
||||
panic!("bx-cli shader would fail with error: {err}");
|
||||
});
|
||||
let report = format!(
|
||||
"Kind : {:?}\nStage / SM : {:?} ({}.{})\nContainer size : {} bytes\nDXIL chunk : {} bytes\nACCC chunk : {} bytes (FSPX={})\nRoot signature : {}",
|
||||
info.kind,
|
||||
info.stage,
|
||||
info.shader_model_major,
|
||||
info.shader_model_minor,
|
||||
info.container_size,
|
||||
info.dxil_size,
|
||||
info.accc_size,
|
||||
info.accc_is_fspx,
|
||||
info.has_root_signature
|
||||
);
|
||||
assert!(
|
||||
report.starts_with("Kind : AcccOnly\n"),
|
||||
"{report}"
|
||||
);
|
||||
assert!(
|
||||
report.contains("ACCC chunk : 128 bytes (FSPX=true)"),
|
||||
"{report}"
|
||||
);
|
||||
assert!(!report.contains("error:"), "{report}");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_byte_fspx_offset_inside_table_is_layout_mismatch() {
|
||||
// Offset 1 on a 16-byte-shaped table. The first section does not begin
|
||||
// at 16 + 4 * 16, so today's 12-byte parse stays (table end 64) and
|
||||
// rejects it. The existing 12-byte offset-1 case is the loop in
|
||||
// `fspx_offset_inside_header_or_table_is_layout_mismatch`.
|
||||
let offset_one =
|
||||
fspx_wide_entries(&[(0, 1, 4), (1, 88, 12), (4, 100, 4), (6, 104, 16)], 120);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &offset_one)]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 0,
|
||||
offset: 1,
|
||||
table_end: 64,
|
||||
};
|
||||
assert_eq!(inspect_dxbc(&blob), Err(expected.clone()));
|
||||
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(expected));
|
||||
let mut c_info = BxShaderInspection {
|
||||
kind: 99,
|
||||
..BxShaderInspection::default()
|
||||
};
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert_eq!(c_info.kind, 0);
|
||||
|
||||
// Section 0's own offset is 70, inside 16 + 4 * 16 and past the
|
||||
// 12-byte table. The 12-byte reading then takes the next entry's id
|
||||
// as an offset and still reports offset 1.
|
||||
let inside_wide =
|
||||
fspx_wide_entries(&[(0, 70, 8), (1, 88, 12), (4, 100, 4), (6, 104, 16)], 120);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &inside_wide)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 0,
|
||||
offset: 1,
|
||||
table_end: 64,
|
||||
})
|
||||
);
|
||||
|
||||
// First section begins at 80, so the stride is 16 bytes, and a later
|
||||
// entry whose offset sits inside 16 + count * 16 is still rejected.
|
||||
let later_inside =
|
||||
fspx_wide_entries(&[(0, 80, 4), (1, 20, 12), (4, 100, 4), (6, 104, 4)], 120);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &later_inside)]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 1,
|
||||
offset: 20,
|
||||
table_end: 80,
|
||||
};
|
||||
assert_eq!(inspect_dxbc(&blob), Err(expected.clone()));
|
||||
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(expected));
|
||||
|
||||
// A non-zero fourth word is not the 16-byte table, even though the
|
||||
// first offset equals 16 + count * 16.
|
||||
let mut nonzero_pad =
|
||||
fspx_wide_entries(&[(0, 80, 8), (1, 88, 12), (4, 100, 4), (6, 104, 16)], 120);
|
||||
nonzero_pad[76..80].copy_from_slice(&1u32.to_le_bytes());
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &nonzero_pad)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 0,
|
||||
offset: 1,
|
||||
table_end: 64,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fspx_layout_mismatch_is_not_out_of_bounds() {
|
||||
// Past the payload end is still out of bounds, not a layout mismatch.
|
||||
@@ -1469,6 +1785,245 @@ mod tests {
|
||||
assert!(log[0].contains("sm_minor=0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_is_not_classified_as_executable_dxil() {
|
||||
clear_shader_log();
|
||||
// Pixel shader (0), SM 6.6, with the four-byte NOBC placeholder instead of LLVM bitcode.
|
||||
let mut payload = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("valid DXBC with NOBC header-only DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
assert_eq!(info.stage, ShaderStage::Pixel);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert!(info.has_root_signature);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 0); // BX_SHADER_UNKNOWN
|
||||
assert_eq!(c_info.stage, 1); // BX_STAGE_PIXEL
|
||||
assert_eq!(c_info.shader_model_major, 6);
|
||||
assert_eq!(c_info.shader_model_minor, 6);
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_accc_is_classified_as_accc_only_and_rejected() {
|
||||
clear_shader_log();
|
||||
let mut dxil = minimal_dxil_program((1u32 << 16) | (6u32 << 4) | 6u32);
|
||||
dxil[24..28].copy_from_slice(b"NOBC");
|
||||
let fspx = fspx_compute_stage();
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil), (b"ACCC", &fspx)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("NOBC + ACCC container");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
assert_eq!(info.accc_size, 40);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 3); // BX_SHADER_DXBC_ACCC
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
let log = shader_log_lines();
|
||||
assert_eq!(log.len(), 1);
|
||||
assert!(log[0].contains("kind=accc_only(3)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_padded_bitcode_is_still_header_only() {
|
||||
let mut payload = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
payload[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
payload[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[8..12].copy_from_slice(b"DXIL");
|
||||
payload[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
payload[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
payload[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
payload[24..28].copy_from_slice(b"NOBC");
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &payload)]);
|
||||
|
||||
let info = inspect_dxbc(&blob).expect("padded NOBC DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Unknown);
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_executable_and_nobc_dxil_preserves_executable_metadata() {
|
||||
let exec = minimal_dxil_program((5u32 << 16) | (6u32 << 4) | 5u32);
|
||||
let mut nobc = vec![0u8; 32];
|
||||
let prog = (6u32 << 4) | 6u32; // Pixel (0), SM 6.6
|
||||
nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
nobc[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[8..12].copy_from_slice(b"DXIL");
|
||||
nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
nobc[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
nobc[20..24].copy_from_slice(&8u32.to_le_bytes());
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
|
||||
// Executable first, NOBC second: executable stage and size must win.
|
||||
let blob_exec_first = build_synthetic_dxbc(&[(b"DXIL", &exec), (b"DXIL", &nobc)]);
|
||||
let info = inspect_dxbc(&blob_exec_first).expect("mixed DXIL");
|
||||
assert_eq!(info.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info.stage, ShaderStage::Compute);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 5));
|
||||
assert_eq!(info.dxil_size, 28);
|
||||
|
||||
let mut c_info = BxShaderInspection::default();
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
bx_shader_inspect(blob_exec_first.as_ptr(), blob_exec_first.len(), &mut c_info)
|
||||
},
|
||||
BX_SHADER_OK
|
||||
);
|
||||
assert_eq!(c_info.kind, 1); // BX_SHADER_DXBC_DXIL
|
||||
assert_eq!(c_info.stage, 6); // BX_STAGE_COMPUTE
|
||||
assert_eq!(c_info.dxil_chunk_size, 28);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob_exec_first),
|
||||
Ok(Some(blob_exec_first.len() as u32))
|
||||
);
|
||||
|
||||
// NOBC first, executable second: executable must still win.
|
||||
let blob_nobc_first = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"DXIL", &exec)]);
|
||||
let info2 = inspect_dxbc(&blob_nobc_first).expect("mixed DXIL reversed");
|
||||
assert_eq!(info2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(info2.stage, ShaderStage::Compute);
|
||||
assert_eq!((info2.shader_model_major, info2.shader_model_minor), (6, 5));
|
||||
assert_eq!(info2.dxil_size, 28);
|
||||
let summary2 = summarize_dxbc(&blob_nobc_first).expect("mixed DXIL summary");
|
||||
assert_eq!(summary2.kind, ShaderKind::Dxil);
|
||||
assert_eq!(summary2.stage, ShaderStage::Compute);
|
||||
assert_eq!(summary2.dxil_size, 28);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobc_dxil_with_malformed_fspx_returns_invalid_blob() {
|
||||
clear_shader_log();
|
||||
let mut nobc = minimal_dxil_program((6u32 << 4) | 6u32);
|
||||
nobc[24..28].copy_from_slice(b"NOBC");
|
||||
let bad_fspx = fspx_header(99, 0, &[], 16);
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &nobc), (b"ACCC", &bad_fspx)]);
|
||||
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxBadVersion {
|
||||
chunk: 1,
|
||||
version: 99,
|
||||
})
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob), Ok(None));
|
||||
|
||||
let mut out_ptr = ptr_sentinel();
|
||||
let mut out_len = 8usize;
|
||||
let status = unsafe {
|
||||
bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len)
|
||||
};
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(out_ptr.is_null());
|
||||
assert_eq!(out_len, 0);
|
||||
assert!(shader_log_lines().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxil_bitcode_bounds_and_offset_checks() {
|
||||
let prog = (5u32 << 16) | (6u32 << 4) | 6u32;
|
||||
|
||||
// Bitcode shorter than 4 bytes (`NOB`) must not misclassify as `NOBC` or read out of bounds.
|
||||
let mut short_bitcode = [0u8; 28];
|
||||
short_bitcode[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
short_bitcode[4..8].copy_from_slice(&7u32.to_le_bytes());
|
||||
short_bitcode[8..12].copy_from_slice(b"DXIL");
|
||||
short_bitcode[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
short_bitcode[16..20].copy_from_slice(&16u32.to_le_bytes());
|
||||
short_bitcode[20..24].copy_from_slice(&3u32.to_le_bytes());
|
||||
short_bitcode[24..27].copy_from_slice(b"NOB");
|
||||
let blob_short = build_synthetic_dxbc(&[(b"DXIL", &short_bitcode)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_short).expect("3-byte bitcode").kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// `NOBC` check follows `BitcodeOffset`, not a fixed offset 24.
|
||||
let mut shifted_nobc = vec![0u8; 36];
|
||||
shifted_nobc[0..4].copy_from_slice(&prog.to_le_bytes());
|
||||
shifted_nobc[4..8].copy_from_slice(&9u32.to_le_bytes());
|
||||
shifted_nobc[8..12].copy_from_slice(b"DXIL");
|
||||
shifted_nobc[12..16].copy_from_slice(&0x0100u32.to_le_bytes());
|
||||
shifted_nobc[16..20].copy_from_slice(&24u32.to_le_bytes());
|
||||
shifted_nobc[20..24].copy_from_slice(&4u32.to_le_bytes());
|
||||
shifted_nobc[32..36].copy_from_slice(b"NOBC");
|
||||
let blob_shifted_nobc = build_synthetic_dxbc(&[(b"DXIL", &shifted_nobc)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_nobc).expect("shifted NOBC").kind,
|
||||
ShaderKind::Unknown
|
||||
);
|
||||
assert_eq!(dxil_container_len(&blob_shifted_nobc), Ok(None));
|
||||
|
||||
// Bytes before `BitcodeOffset` containing `NOBC` do not make executable bitcode header-only.
|
||||
let mut shifted_exec = shifted_nobc;
|
||||
shifted_exec[24..28].copy_from_slice(b"NOBC");
|
||||
shifted_exec[32..36].copy_from_slice(&[0xD1, 0x11, 0xC0, 0xDE]);
|
||||
let blob_shifted_exec = build_synthetic_dxbc(&[(b"DXIL", &shifted_exec)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob_shifted_exec)
|
||||
.expect("shifted executable")
|
||||
.kind,
|
||||
ShaderKind::Dxil
|
||||
);
|
||||
|
||||
// Overflowing bitcode offset / size must reject cleanly as `BadDxilHeader`.
|
||||
for (bitcode_off, bitcode_sz) in [(16u32, u32::MAX), (u32::MAX - 4, 4u32)] {
|
||||
let mut overflow = minimal_dxil_program(prog);
|
||||
overflow[16..20].copy_from_slice(&bitcode_off.to_le_bytes());
|
||||
overflow[20..24].copy_from_slice(&bitcode_sz.to_le_bytes());
|
||||
let blob = build_synthetic_dxbc(&[(b"DXIL", &overflow)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
summarize_dxbc(&blob).map(|_| ()),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
assert_eq!(
|
||||
dxil_container_len(&blob),
|
||||
Err(ParseError::BadDxilHeader { chunk: 0 })
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn fspx_table_with_sections(count: u32) -> Vec<u8> {
|
||||
let count_usize = count as usize;
|
||||
let table_end = 16 + count_usize * 12;
|
||||
@@ -1503,4 +2058,99 @@ mod tests {
|
||||
fn ptr_sentinel() -> *mut u8 {
|
||||
std::ptr::dangling_mut()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_returns_sfi0_and_psv0_bytes() {
|
||||
let sfi0: [u8; 8] = [0x00, 0x40, 0, 0, 0, 0, 0, 0];
|
||||
let psv0: [u8; 28] = [
|
||||
24, 0, 0, 0, // info_size = 24
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, // lanes_min
|
||||
64, 0, 0, 0, // lanes_max
|
||||
];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &sfi0), (b"PSV0", &psv0)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid container");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(sfi0.as_slice()));
|
||||
assert_eq!(info.chunk_payload(&blob, b"PSV0"), Some(psv0.as_slice()));
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
assert!(info.has_chunk_tag(b"PSV0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_rejects_declared_size_past_container() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4])]);
|
||||
let mut info = inspect_dxbc(&blob).expect("valid container");
|
||||
|
||||
// A declared size that runs past container_size must yield None, not
|
||||
// a panic and not a slice clipped to the container.
|
||||
info.chunks[0].size = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
// Presence without trusting the size still holds.
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
|
||||
// A forged public ChunkInfo must not treat the DXBC header or offset
|
||||
// table as a chunk header.
|
||||
info.chunks[0].size = 4;
|
||||
info.chunks[0].offset = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A header offset past the container must also yield None.
|
||||
info.chunks[0].offset = u32::MAX;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
|
||||
// A chunk header that would end exactly one byte past the container.
|
||||
info.chunks[0].offset = info.container_size - 7;
|
||||
info.chunks[0].size = 0;
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_absent_fourcc() {
|
||||
let blob = synthetic_dxil_blob();
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), None);
|
||||
assert!(!info.has_chunk_tag(b"SFI0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_zero_size_returns_empty_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert!(info.has_chunk_tag(b"SFI0"));
|
||||
let payload = info.chunk_payload(&blob, b"SFI0");
|
||||
assert_eq!(payload, Some(&[][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_exact_fit_at_container_end() {
|
||||
let payload = [0xAA, 0xBB, 0xCC, 0xDD];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &payload)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// The chunk is the last thing in the container; payload ends exactly
|
||||
// at container_size.
|
||||
let chunk = &info.chunks[0];
|
||||
assert_eq!(
|
||||
u64::from(chunk.offset) + 8 + u64::from(chunk.size),
|
||||
u64::from(info.container_size)
|
||||
);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(payload.as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_truncated_container_slice() {
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &[1, 2, 3, 4, 5, 6, 7, 8])]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
// Pass a slice shorter than container_size.
|
||||
let short = &blob[..blob.len() - 4];
|
||||
assert_eq!(info.chunk_payload(short, b"SFI0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_payload_first_duplicate_wins() {
|
||||
let first = [0x11, 0x22];
|
||||
let second = [0x33, 0x44, 0x55];
|
||||
let blob = build_synthetic_dxbc(&[(b"SFI0", &first), (b"SFI0", &second)]);
|
||||
let info = inspect_dxbc(&blob).expect("valid");
|
||||
assert_eq!(info.chunks.len(), 2);
|
||||
assert_eq!(info.chunk_payload(&blob, b"SFI0"), Some(first.as_slice()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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(¬_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 on a 32-bit float result (`clamp`, `mul:`/`div:`) and input `abs`/`neg` are translated. `op_sel` on a 32-bit source, and `clamp` or `abs` on an integer instruction, are refused. `op_sel` on `v_fma_mix*` selects the half of an f16 source. SDWA and DPP forms are translated for the selectors and lane controls in `src/translate.rs`; a reserved selector or any other DPP control is refused.
|
||||
- `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,48 @@
|
||||
//! 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 (up to runs of
|
||||
//! spaces) and consume exactly those words.
|
||||
|
||||
use gfx10_translate::decode::decode_one;
|
||||
|
||||
/// The same text, up to runs of spaces.
|
||||
fn same_text(a: &str, b: &str) -> bool {
|
||||
a.split_whitespace().eq(b.split_whitespace())
|
||||
}
|
||||
|
||||
#[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()
|
||||
)),
|
||||
// llvm-mc prints two spaces after the mnemonic of an NSA image instruction.
|
||||
Ok(inst) if !same_text(&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,131 @@
|
||||
# @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
|
||||
f080010a 01250304 00000007 | image_sample v3, [v4, v7], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D
|
||||
f09c0712 00820004 00000209 | image_sample_lz v[0:2], [v4, v9, v2], s[8:15], s[16:19] dmask:0x7 dim:SQ_RSRC_IMG_3D
|
||||
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
|
||||
File diff suppressed because it is too large.
Load diff
+106
-16
@@ -1,29 +1,52 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
class AcpHal final : public IUnknown {
|
||||
LONG refs = 1;
|
||||
// IAcpHal (authorized GDK documentation; slot order derived from it): not a COM interface. Its
|
||||
// six methods are Connect(numCommands, numMessages), Disconnect(), SubmitCommand(command,
|
||||
// commandId, audioFrame, data, notification), PopMessage(ACP_MESSAGE*), GetNumMessages() and
|
||||
// Release(). BetterXen has no audio control processor: commands are accepted and logged once,
|
||||
// and no message ever arrives.
|
||||
class AcpHal {
|
||||
UINT32 commands_ = 0, messages_ = 0;
|
||||
bool connected_ = false;
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
virtual HRESULT WINAPI Connect(UINT32 num_commands, UINT32 num_messages) {
|
||||
if (connected_) return HRESULT_FROM_WIN32(ERROR_ALREADY_INITIALIZED);
|
||||
commands_ = num_commands;
|
||||
messages_ = num_messages;
|
||||
connected_ = true;
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "commands=%u messages=%u (no ACP processing)", num_commands, num_messages);
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "connect", detail);
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
|
||||
ULONG WINAPI Release() override {
|
||||
ULONG left = InterlockedDecrement(&refs);
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
virtual HRESULT WINAPI Disconnect() {
|
||||
connected_ = false;
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI SubmitCommand(UINT32 command, UINT64, UINT32, const void*, UINT32) {
|
||||
if (!connected_) return E_UNEXPECTED;
|
||||
static LONG logged = 0;
|
||||
if (InterlockedIncrement(&logged) == 1) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "first command type %u accepted; ACP commands are not processed", command);
|
||||
bx_log_emit(BX_LOG_WARN, "acphal", "submit_command", detail);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
virtual bool WINAPI PopMessage(void*) { return false; }
|
||||
virtual UINT32 WINAPI GetNumMessages() { return 0; }
|
||||
virtual void WINAPI Release() { delete this; }
|
||||
virtual ~AcpHal() = default;
|
||||
};
|
||||
|
||||
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
|
||||
@@ -47,19 +70,86 @@ HRESULT WINAPI AcpHalCreate(void** out) {
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
|
||||
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment);
|
||||
HRESULT WINAPI ApuFree(void* va);
|
||||
|
||||
// AcpHalAllocateShapeContexts(SHAPE_CONTEXTS*) / AcpHalReleaseShapeContexts() (authorized GDK
|
||||
// documentation; layout and element sizes derived from it, no header text): the caller fills six
|
||||
// counts, the call allocates each array from the APU heap and returns its CPU pointer and APU
|
||||
// address. Allocating twice without a release fails with ACP_E_ALREADY_ALLOCATED.
|
||||
struct ShapeContexts {
|
||||
uint32_t counts[6]; // SRC, EQ/Comp, Filt/Vol, DMA, XMA, PCM
|
||||
void* arrays[6]; // CPU pointers, same order
|
||||
uint32_t apu[6]; // APU addresses, same order
|
||||
};
|
||||
static_assert(sizeof(ShapeContexts) == 96, "SHAPE_CONTEXTS is 96 bytes");
|
||||
static_assert(offsetof(ShapeContexts, arrays) == 24 && offsetof(ShapeContexts, apu) == 72, "SHAPE_CONTEXTS layout");
|
||||
constexpr uint32_t kShapeElementBytes[6] = {32, 160, 32, 16, 64, 32};
|
||||
constexpr HRESULT kAcpAlreadyAllocated = static_cast<HRESULT>(0x8AC80001);
|
||||
constexpr uint32_t kDefaultApuHeapBytes = 64u << 20;
|
||||
|
||||
void* shape_arrays[6];
|
||||
bool shape_allocated = false;
|
||||
|
||||
HRESULT WINAPI AcpHalAllocateShapeContexts(void* argument) {
|
||||
auto* contexts = static_cast<ShapeContexts*>(argument);
|
||||
if (!contexts) return E_INVALIDARG;
|
||||
if (shape_allocated) return kAcpAlreadyAllocated;
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
if (contexts->counts[i] > (0xFFFFFFFFu / kShapeElementBytes[i])) return E_INVALIDARG;
|
||||
}
|
||||
{
|
||||
// The console has a default non-cached APU heap; create one when the title made none.
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (!heap_created) {
|
||||
capacity = kDefaultApuHeapBytes;
|
||||
used = 0;
|
||||
heap_created = true;
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "apu_default_heap", "no ApuCreateHeap before shape contexts: 64 MB default heap");
|
||||
}
|
||||
}
|
||||
void* arrays[6] = {};
|
||||
uint32_t apu[6] = {};
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
if (!contexts->counts[i]) continue;
|
||||
const uint32_t bytes = contexts->counts[i] * kShapeElementBytes[i];
|
||||
const HRESULT hr = ApuAlloc(&arrays[i], &apu[i], bytes, 64);
|
||||
if (FAILED(hr)) {
|
||||
for (int j = 0; j < i; ++j) ApuFree(arrays[j]);
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
std::memset(arrays[i], 0, bytes);
|
||||
}
|
||||
for (int i = 0; i < 6; ++i) {
|
||||
contexts->arrays[i] = arrays[i];
|
||||
contexts->apu[i] = apu[i];
|
||||
shape_arrays[i] = arrays[i];
|
||||
}
|
||||
shape_allocated = true;
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "src=%u eqcomp=%u filtvol=%u dma=%u xma=%u pcm=%u", contexts->counts[0],
|
||||
contexts->counts[1], contexts->counts[2], contexts->counts[3], contexts->counts[4], contexts->counts[5]);
|
||||
bx_log_emit(BX_LOG_INFO, "acphal", "shape_contexts_allocated", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
|
||||
BX_STUB_LOG("AcpHal.dll", "AcpHalReleaseShapeContexts");
|
||||
if (!shape_allocated) return S_OK;
|
||||
for (void*& array : shape_arrays) {
|
||||
ApuFree(array);
|
||||
array = nullptr;
|
||||
}
|
||||
shape_allocated = false;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
|
||||
std::lock_guard guard(heap_lock);
|
||||
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
// A zero-capacity heap must not report S_OK: it can never satisfy an
|
||||
// allocation, so creating it is a caller error (#580). ApuAlloc already
|
||||
// refused such requests with E_OUTOFMEMORY.
|
||||
if (uint64_t(cached) + non_cached == 0) return E_INVALIDARG;
|
||||
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
|
||||
used = 0;
|
||||
capacity = uint64_t(cached) + non_cached;
|
||||
|
||||
+85
-31
@@ -1,41 +1,95 @@
|
||||
#define BX_DSP_CONNECTIONS
|
||||
#include "command_ring.h"
|
||||
/*
|
||||
* chad.dll: the XDSP (convolution/DSP hardware) client API, with the prototypes of the authorized
|
||||
* GDK header xdspaudio.h (#776):
|
||||
*
|
||||
* XDspConnectWithMaximumStreamLimit(float* baseBuffer, uint32_t baseBufferLength,
|
||||
* uint32_t aggregateImpulseResponseInSeconds, uint32_t maximumStreamCount,
|
||||
* uint32_t maximumChannelCount, XDspClientHandle* handle)
|
||||
* XDspDisconnect(XDspClientHandle)
|
||||
* XDspActivate(XDspClientHandle, XDspActivationParameters*, XDspStatus** status,
|
||||
* XDspStreamHandle* streamHandle)
|
||||
* XDspDeactivate(XDspStreamHandle)
|
||||
* XDspSubmitCommand(XDspStreamHandle, XDspCommand*, uint32_t* commandSequence)
|
||||
*
|
||||
* BetterXen does not model the DSP. A title asserts when connecting fails (the target build stops
|
||||
* a few seconds after a refused connect), so connecting succeeds: the client handle is a
|
||||
* placeholder that stands for "connected, nothing modelled", and the call is logged with
|
||||
* BX_STUB_LOG so `bx-cli trace` still lists it. Activating a stream on it is refused with
|
||||
* E_NOTIMPL, the documented outputs set to NULL. No stream handle can exist, so Deactivate and
|
||||
* SubmitCommand answer E_HANDLE with their outputs cleared. XDspDisconnect accepts the placeholder
|
||||
* while a connection is open. Nothing else of the caller's memory is written. The earlier exports
|
||||
* had a BetterXen-defined shape ((max_streams, out) for connect); called with the documented
|
||||
* argument list, connect wrote its handle to the address given by baseBufferLength.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <atomic>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
struct XDspClient; // XDspClientHandle: opaque in the GDK header
|
||||
struct XDspStream; // XDspStreamHandle: opaque in the GDK header
|
||||
struct XDspStatus; // only ever handed out as NULL here
|
||||
|
||||
namespace {
|
||||
// The placeholder client handle: its address is all that is handed out.
|
||||
struct XDspClientPlaceholder {
|
||||
uint32_t unused;
|
||||
} g_client;
|
||||
std::atomic<long> g_connections{0};
|
||||
|
||||
XDspClient* placeholder_client() { return reinterpret_cast<XDspClient*>(&g_client); }
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
// Validate and record the caller's stream limit; the synthetic command ring
|
||||
// holds a fixed 32-packet backlog independent of stream count.
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t max_streams, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!max_streams) return E_INVALIDARG;
|
||||
return connect(out, max_streams);
|
||||
}
|
||||
HRESULT WINAPI XDspDisconnect(void* handle) { return disconnect(handle); }
|
||||
|
||||
HRESULT WINAPI XDspActivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = true;
|
||||
// chad has no result export. Active DSP commands complete synchronously.
|
||||
while (c->queue.count) c->queue.pop();
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(float* base_buffer, uint32_t base_buffer_length,
|
||||
uint32_t aggregate_impulse_response_seconds,
|
||||
uint32_t maximum_stream_count, uint32_t maximum_channel_count,
|
||||
XDspClient** handle) {
|
||||
if (!handle) return E_POINTER;
|
||||
*handle = placeholder_client();
|
||||
const long open = ++g_connections;
|
||||
char detail[224];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"connected without a DSP model (streams are refused): base_buffer=%s length=%u "
|
||||
"impulse_response_s=%u max_streams=%u max_channels=%u open=%ld",
|
||||
base_buffer ? "set" : "null", base_buffer_length, aggregate_impulse_response_seconds,
|
||||
maximum_stream_count, maximum_channel_count, open);
|
||||
bx_log_emit(BX_LOG_WARN, "chad", "XDspConnectWithMaximumStreamLimit", detail);
|
||||
BX_STUB_LOG("chad.dll", "XDspConnectWithMaximumStreamLimit");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspDeactivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = false;
|
||||
return S_OK;
|
||||
HRESULT WINAPI XDspDisconnect(XDspClient* client) {
|
||||
BX_STUB_LOG("chad.dll", "XDspDisconnect");
|
||||
if (client != placeholder_client()) return E_HANDLE;
|
||||
long open = g_connections.load();
|
||||
while (open > 0 && !g_connections.compare_exchange_weak(open, open - 1)) {
|
||||
}
|
||||
return open > 0 ? S_OK : E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspSubmitCommand(void* handle, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
const HRESULT hr = c->queue.push(cmd, size);
|
||||
if (SUCCEEDED(hr) && c->active) c->queue.pop();
|
||||
return hr;
|
||||
HRESULT WINAPI XDspActivate(XDspClient* client, const void* /*XDspActivationParameters*/, XDspStatus** status,
|
||||
XDspStream** stream_handle) {
|
||||
if (status) *status = nullptr;
|
||||
if (stream_handle) *stream_handle = nullptr;
|
||||
BX_STUB_LOG("chad.dll", "XDspActivate");
|
||||
if (client != placeholder_client() || g_connections.load() <= 0) return E_HANDLE;
|
||||
return E_NOTIMPL; // streams are not modelled
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspDeactivate(XDspStream*) {
|
||||
BX_STUB_LOG("chad.dll", "XDspDeactivate");
|
||||
return E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspSubmitCommand(XDspStream*, const void* /*XDspCommand*/, uint32_t* command_sequence) {
|
||||
if (command_sequence) *command_sequence = 0;
|
||||
BX_STUB_LOG("chad.dll", "XDspSubmitCommand");
|
||||
return E_HANDLE;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
+116
-70
@@ -1,96 +1,142 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include "xapu_layout.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
namespace {
|
||||
// A synthetic command completes by returning its opaque bytes unchanged.
|
||||
struct CommandRing {
|
||||
struct Packet {
|
||||
uint32_t size;
|
||||
unsigned char bytes[1024];
|
||||
};
|
||||
std::array<Packet, 32> packets;
|
||||
unsigned head = 0, count = 0;
|
||||
|
||||
HRESULT push(const void* data, uint32_t size) {
|
||||
if (!data || !size || size > sizeof(Packet::bytes)) return E_INVALIDARG;
|
||||
if (count == packets.size()) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
auto& packet = packets[(head + count) % packets.size()];
|
||||
packet.size = size;
|
||||
std::memcpy(packet.bytes, data, size);
|
||||
++count;
|
||||
return S_OK;
|
||||
}
|
||||
void pop() {
|
||||
head = (head + 1) % packets.size();
|
||||
--count;
|
||||
}
|
||||
HRESULT read(void* data, uint32_t size) {
|
||||
if (!data) return E_POINTER;
|
||||
if (!count) return S_FALSE;
|
||||
const auto& packet = packets[head];
|
||||
if (size < packet.size) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
std::memcpy(data, packet.bytes, packet.size);
|
||||
pop();
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* One connection's command queue. A submitted XApuCommandId becomes an
|
||||
* XApuResult that carries the same id. A Process command is the 64-byte
|
||||
* XApuDecodeConvertCommand: its result also carries that command's
|
||||
* inputDataLength, inputData and outputData. outputFrameCount and
|
||||
* outputDataLength stay 0, and errorCode stays S_OK, because nothing was
|
||||
* decoded. The ring is FIFO, which is the default xapu.h ordering. Capacity is
|
||||
* maxStreamCount * maxQueuedCommandsPerStream,
|
||||
* and each stream accepts at most maxQueuedCommandsPerStream commands that
|
||||
* have not been dequeued yet (XAPU_E_QUEUE_FULL). An empty dequeue is
|
||||
* XAPU_E_PENDING_RESULTS. Identifiers are odd and are never reused, so a
|
||||
* disconnected handle stays invalid if the allocator reuses the address.
|
||||
*/
|
||||
struct Connection {
|
||||
uintptr_t id;
|
||||
Connection* next;
|
||||
CommandRing queue;
|
||||
uintptr_t id = 0;
|
||||
Connection* next = nullptr;
|
||||
void* base_data = nullptr;
|
||||
HANDLE result_event = nullptr;
|
||||
uint32_t max_streams = 0;
|
||||
bool active = false;
|
||||
uint32_t max_queued = 0;
|
||||
uint32_t total_commands = 0;
|
||||
uint32_t total_results = 0;
|
||||
uint32_t head = 0;
|
||||
uint32_t count = 0;
|
||||
uint32_t capacity = 0;
|
||||
uint32_t* pending = nullptr;
|
||||
XApuResult* slots = nullptr;
|
||||
};
|
||||
|
||||
// Each DLL owns its registry. An ID stays invalid after disconnect, including
|
||||
// when the allocator subsequently reuses the same Connection address.
|
||||
std::mutex connections_lock;
|
||||
Connection* connections;
|
||||
#ifdef BX_DSP_CONNECTIONS
|
||||
uintptr_t next_id = 2;
|
||||
#else
|
||||
Connection* connections = nullptr;
|
||||
uintptr_t next_id = 1;
|
||||
#endif
|
||||
|
||||
HRESULT connect(void** out, uint32_t max_streams = 0) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
std::lock_guard guard(connections_lock);
|
||||
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
|
||||
auto* c = new (std::nothrow) Connection;
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
c->id = next_id;
|
||||
c->max_streams = max_streams;
|
||||
next_id += 2;
|
||||
c->next = connections;
|
||||
connections = c;
|
||||
*out = reinterpret_cast<void*>(c->id);
|
||||
return S_OK;
|
||||
void release_connection(Connection* c) {
|
||||
if (!c) return;
|
||||
if (c->base_data) VirtualFree(c->base_data, 0, MEM_RELEASE);
|
||||
if (c->result_event) CloseHandle(c->result_event);
|
||||
delete[] c->pending;
|
||||
delete[] c->slots;
|
||||
delete c;
|
||||
}
|
||||
|
||||
// Caller holds connections_lock through the operation.
|
||||
Connection* lookup(void* handle) {
|
||||
for (auto* c = connections; c; c = c->next)
|
||||
if (c->id == reinterpret_cast<uintptr_t>(handle)) return c;
|
||||
const auto id = reinterpret_cast<uintptr_t>(handle);
|
||||
for (Connection* c = connections; c; c = c->next)
|
||||
if (c->id == id) return c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HRESULT disconnect(void* handle) {
|
||||
/* Caller has filled every field except id and next. On failure the caller frees c. */
|
||||
HRESULT publish_connection(Connection* c, uintptr_t* out_id) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
for (auto** link = &connections; *link; link = &(*link)->next) {
|
||||
auto* c = *link;
|
||||
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
|
||||
c->id = next_id;
|
||||
next_id += 2;
|
||||
c->next = connections;
|
||||
connections = c;
|
||||
*out_id = c->id;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT enqueue_command(void* handle, const XApuCommandId* command, uint32_t* total) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
Connection* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
if (command->streamIndex >= c->max_streams) {
|
||||
if (total) *total = c->total_commands;
|
||||
return XAPU_E_INVALID_STREAM_INDEX;
|
||||
}
|
||||
if (c->pending[command->streamIndex] >= c->max_queued || c->count >= c->capacity) {
|
||||
if (total) *total = c->total_commands;
|
||||
return XAPU_E_QUEUE_FULL;
|
||||
}
|
||||
XApuResult result{};
|
||||
std::memcpy(&result.id, command, sizeof(result.id));
|
||||
result.errorCode = S_OK;
|
||||
if (command->type == kXApuCommandProcess) {
|
||||
XApuDecodeConvertCommand decode{};
|
||||
std::memcpy(&decode, command, sizeof(decode));
|
||||
result.inputDataLength = decode.inputDataLength;
|
||||
result.inputData = decode.inputData;
|
||||
result.outputData = decode.outputData;
|
||||
}
|
||||
const uint32_t slot = (c->head + c->count) % c->capacity;
|
||||
std::memcpy(&c->slots[slot], &result, sizeof(result));
|
||||
++c->count;
|
||||
++c->pending[command->streamIndex];
|
||||
++c->total_commands;
|
||||
++c->total_results;
|
||||
if (total) *total = c->total_commands;
|
||||
if (c->result_event && (command->options & kXApuSignalOnCompletion) != 0) SetEvent(c->result_event);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT dequeue_result(void* handle, XApuResult* command_result) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
Connection* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
if (c->count == 0) return XAPU_E_PENDING_RESULTS;
|
||||
XApuResult result{};
|
||||
std::memcpy(&result, &c->slots[c->head], sizeof(result));
|
||||
c->head = (c->head + 1) % c->capacity;
|
||||
--c->count;
|
||||
if (result.id.streamIndex < c->max_streams && c->pending[result.id.streamIndex] > 0)
|
||||
--c->pending[result.id.streamIndex];
|
||||
std::memcpy(command_result, &result, sizeof(*command_result));
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
uint32_t result_count(void* handle, uint32_t* total) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
Connection* c = lookup(handle);
|
||||
if (!c) {
|
||||
if (total) *total = 0;
|
||||
return 0;
|
||||
}
|
||||
if (total) *total = c->total_results;
|
||||
return c->count;
|
||||
}
|
||||
|
||||
HRESULT disconnect_connection(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
for (Connection** link = &connections; *link; link = &(*link)->next) {
|
||||
Connection* c = *link;
|
||||
if (c->id != reinterpret_cast<uintptr_t>(handle)) continue;
|
||||
*link = c->next;
|
||||
delete c;
|
||||
return S_OK;
|
||||
const bool pending = c->count > 0;
|
||||
release_connection(c);
|
||||
return pending ? XAPU_E_PENDING_RESULTS : S_OK;
|
||||
}
|
||||
return E_HANDLE;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
+135
-14
@@ -1,24 +1,145 @@
|
||||
/*
|
||||
* xapu.dll: the XAPU client API, with the prototypes of the authorized GDK header xapu.h (#777):
|
||||
*
|
||||
* XApuConnect(XApuConnectInputParameters* params, XApuConnectOutputParameters* data,
|
||||
* XApuHandle* handle)
|
||||
* XApuDisconnect(XApuHandle)
|
||||
* XApuEnqueueCommand(XApuHandle, XApuCommandId* command, uint32_t* totalCommandCount)
|
||||
* XApuDequeueResult(XApuHandle, XApuResult* commandResult)
|
||||
* XApuGetResultCount(XApuHandle, uint32_t* totalResultCount) -> uint32_t
|
||||
*
|
||||
* BetterXen does not model the APU device. Connecting still succeeds and is logged with
|
||||
* BX_STUB_LOG: a refused connect changes a title's audio init. On success the call writes
|
||||
* *handle and XApuConnectOutputParameters — baseData, and resultReadyEvent when
|
||||
* XApuConnectOptions::EnableResultReadyEvent is set — and nothing else. baseData is freed
|
||||
* and the event is closed on XApuDisconnect. Commands are queued per connection (see
|
||||
* command_ring.h) and come back as XApuResult records that carry the same XApuCommandId.
|
||||
* A Process command's result also carries that command's inputDataLength, inputData and
|
||||
* outputData. outputFrameCount and outputDataLength stay 0, and errorCode is S_OK, because
|
||||
* the command was not processed (BX_STUB_LOG). totalCommandCount and totalResultCount
|
||||
* advance when their pointers are non-null and do not reset. Hardware processing, the
|
||||
* result-ready timer, and pitch conversion are not modelled. The earlier exports took a
|
||||
* byte blob plus a size, and XApuConnect wrote its
|
||||
* handle through the first argument, which is the input parameter block.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "command_ring.h"
|
||||
|
||||
namespace {
|
||||
bool connect_params_ok(const XApuConnectInputParameters* params) {
|
||||
return params->maxStreamCount >= 1 && params->maxStreamCount <= kXApuMaxStreamCount &&
|
||||
params->maxQueuedCommandsPerStream >= 1 &&
|
||||
params->maxQueuedCommandsPerStream <= kXApuMaxQueuedPerStream && params->baseDataLength > 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI XApuConnect(void** out) { return connect(out); }
|
||||
HRESULT WINAPI XApuDisconnect(void* conn) { return disconnect(conn); }
|
||||
|
||||
HRESULT WINAPI XApuEnqueueCommand(void* conn, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.push(cmd, size) : E_HANDLE;
|
||||
HRESULT WINAPI XApuConnect(XApuConnectInputParameters* params, XApuConnectOutputParameters* data, XApu** handle) {
|
||||
if (!params || !data || !handle) return E_POINTER;
|
||||
if (!connect_params_ok(params)) {
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuConnect", "rejected parameters outside the xapu.h limits");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
void* base = VirtualAlloc(nullptr, params->baseDataLength, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
if (!base) {
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "baseData allocation failed");
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
HANDLE event = nullptr;
|
||||
if ((params->options & kXApuEnableResultReadyEvent) != 0) {
|
||||
event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event) {
|
||||
const DWORD err = GetLastError();
|
||||
VirtualFree(base, 0, MEM_RELEASE);
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "resultReadyEvent creation failed");
|
||||
return err ? HRESULT_FROM_WIN32(err) : E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
const uint32_t streams = params->maxStreamCount;
|
||||
const uint32_t queued = params->maxQueuedCommandsPerStream;
|
||||
const uint32_t capacity = streams * queued;
|
||||
auto* pending = new (std::nothrow) uint32_t[streams];
|
||||
auto* slots = new (std::nothrow) XApuResult[capacity];
|
||||
auto* connection = new (std::nothrow) Connection{};
|
||||
if (!pending || !slots || !connection) {
|
||||
delete[] pending;
|
||||
delete[] slots;
|
||||
delete connection;
|
||||
if (event) CloseHandle(event);
|
||||
VirtualFree(base, 0, MEM_RELEASE);
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "connection allocation failed");
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
std::memset(pending, 0, sizeof(uint32_t) * streams);
|
||||
connection->base_data = base;
|
||||
connection->result_event = event;
|
||||
connection->max_streams = streams;
|
||||
connection->max_queued = queued;
|
||||
connection->capacity = capacity;
|
||||
connection->pending = pending;
|
||||
connection->slots = slots;
|
||||
|
||||
uintptr_t id = 0;
|
||||
if (const HRESULT hr = publish_connection(connection, &id); FAILED(hr)) {
|
||||
release_connection(connection);
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "connection id space exhausted");
|
||||
return hr;
|
||||
}
|
||||
|
||||
data->baseData = base;
|
||||
data->resultReadyEvent = event;
|
||||
*handle = reinterpret_cast<XApu*>(id);
|
||||
|
||||
char detail[288];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"connected without an APU device (commands are queued, not processed): "
|
||||
"process=%u streams=%u queued_per_stream=%u base_bytes=%u event=%s",
|
||||
params->processType, streams, queued, params->baseDataLength, event ? "set" : "null");
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuConnect", detail);
|
||||
BX_STUB_LOG("xapu.dll", "XApuConnect");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDequeueResult(void* conn, void* result, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.read(result, size) : E_HANDLE;
|
||||
HRESULT WINAPI XApuDisconnect(XApu* handle) {
|
||||
const HRESULT hr = disconnect_connection(handle);
|
||||
if (hr == XAPU_E_PENDING_RESULTS) {
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuDisconnect",
|
||||
"disconnected with results still queued; no APU device is modelled");
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
uint32_t WINAPI XApuGetResultCount(void* conn) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.count : 0;
|
||||
HRESULT WINAPI XApuEnqueueCommand(XApu* handle, XApuCommandId* command, uint32_t* total_command_count) {
|
||||
if (!command) return E_POINTER;
|
||||
const HRESULT hr = enqueue_command(handle, command, total_command_count);
|
||||
if (hr == S_OK) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.exchange(1) == 0) {
|
||||
BX_STUB_LOG("xapu.dll", "XApuEnqueueCommand");
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuEnqueueCommand",
|
||||
"command queued and not processed; the result echoes the command id and Process buffers, with no decoded PCM");
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDequeueResult(XApu* handle, XApuResult* command_result) {
|
||||
if (!command_result) return E_POINTER;
|
||||
return dequeue_result(handle, command_result);
|
||||
}
|
||||
|
||||
uint32_t WINAPI XApuGetResultCount(XApu* handle, uint32_t* total_result_count) {
|
||||
return result_count(handle, total_result_count);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,115 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* Field layout of the xapu.h structures the xapu.dll exports pass through.
|
||||
* The shim does not include the GDK header. Names match that header; the
|
||||
* pack is 1, as xapu.h packs these structures.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#pragma pack(push, 1)
|
||||
|
||||
struct XApuConnectInputParameters {
|
||||
uint32_t processType;
|
||||
uint32_t maxStreamCount;
|
||||
uint32_t maxQueuedCommandsPerStream;
|
||||
uint32_t baseDataLength;
|
||||
uint32_t maxFrameCountPerOutput;
|
||||
uint32_t options;
|
||||
};
|
||||
|
||||
struct XApuConnectOutputParameters {
|
||||
void* baseData;
|
||||
HANDLE resultReadyEvent;
|
||||
};
|
||||
|
||||
struct XApuCommandId {
|
||||
uint32_t type;
|
||||
uint32_t streamIndex;
|
||||
uint32_t sequence;
|
||||
uint32_t options;
|
||||
void* context;
|
||||
};
|
||||
|
||||
/* Process (XApuCommandType::Process) is this packed command, not the 24-byte id alone. */
|
||||
struct XApuDecodeConvertCommand {
|
||||
XApuCommandId id;
|
||||
float pitchRampRate;
|
||||
float targetPitch;
|
||||
uint32_t firstFrameIndex;
|
||||
uint32_t frameCount;
|
||||
uint32_t inputDataLength;
|
||||
void* inputData;
|
||||
uint32_t maxOutputDataLength;
|
||||
void* outputData;
|
||||
};
|
||||
|
||||
struct XApuResult {
|
||||
XApuCommandId id;
|
||||
uint32_t state;
|
||||
uint64_t stateData;
|
||||
uint64_t totalExecutionTime;
|
||||
HRESULT errorCode;
|
||||
uint32_t outputFrameCount;
|
||||
uint32_t outputDataLength;
|
||||
void* outputData;
|
||||
float currentPitch;
|
||||
uint32_t inputDataLength;
|
||||
void* inputData;
|
||||
};
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
struct XApu; /* XApuHandle in xapu.h: an opaque pointer */
|
||||
|
||||
/* XApuConnectOptions::EnableResultReadyEvent and XApuCommandOptions::SignalOnCompletion. */
|
||||
constexpr uint32_t kXApuEnableResultReadyEvent = 8u;
|
||||
constexpr uint32_t kXApuSignalOnCompletion = 1u;
|
||||
|
||||
/* XApuCommandType::Process. The submitted object is XApuDecodeConvertCommand. */
|
||||
constexpr uint32_t kXApuCommandProcess = 3u;
|
||||
|
||||
/* Limits xapu.h states for maxStreamCount and maxQueuedCommandsPerStream. */
|
||||
constexpr uint32_t kXApuMaxStreamCount = 500u;
|
||||
constexpr uint32_t kXApuMaxQueuedPerStream = 16u;
|
||||
|
||||
/*
|
||||
* Error codes named in xapu.h (XAPU_E_QUEUE_FULL, XAPU_E_PENDING_RESULTS,
|
||||
* XAPU_E_INVALID_STREAM_INDEX).
|
||||
*/
|
||||
#define XAPU_E_QUEUE_FULL MAKE_HRESULT(SEVERITY_ERROR, 0xAC8, 0x1000)
|
||||
#define XAPU_E_PENDING_RESULTS MAKE_HRESULT(SEVERITY_ERROR, 0xAC8, 0x1001)
|
||||
#define XAPU_E_INVALID_STREAM_INDEX MAKE_HRESULT(SEVERITY_ERROR, 0xAC8, 0x1003)
|
||||
|
||||
static_assert(sizeof(void*) == 8, "xapu handles and baseData are 8-byte pointers");
|
||||
static_assert(alignof(XApuConnectInputParameters) == 1 && sizeof(XApuConnectInputParameters) == 24,
|
||||
"XApuConnectInputParameters");
|
||||
static_assert(sizeof(XApuConnectOutputParameters) == 16, "XApuConnectOutputParameters");
|
||||
static_assert(offsetof(XApuCommandId, context) == 16 && sizeof(XApuCommandId) == 24, "XApuCommandId");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, id) == 0, "XApuDecodeConvertCommand.id");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, pitchRampRate) == 24, "XApuDecodeConvertCommand.pitchRampRate");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, targetPitch) == 28, "XApuDecodeConvertCommand.targetPitch");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, firstFrameIndex) == 32, "XApuDecodeConvertCommand.firstFrameIndex");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, frameCount) == 36, "XApuDecodeConvertCommand.frameCount");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, inputDataLength) == 40, "XApuDecodeConvertCommand.inputDataLength");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, inputData) == 44, "XApuDecodeConvertCommand.inputData");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, maxOutputDataLength) == 52, "XApuDecodeConvertCommand.maxOutputDataLength");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, outputData) == 56, "XApuDecodeConvertCommand.outputData");
|
||||
static_assert(sizeof(XApuDecodeConvertCommand) == 64, "XApuDecodeConvertCommand");
|
||||
static_assert(alignof(XApuResult) == 1 && sizeof(XApuResult) == 80, "XApuResult");
|
||||
static_assert(offsetof(XApuResult, state) == 24, "XApuResult.state");
|
||||
static_assert(offsetof(XApuResult, stateData) == 28, "XApuResult.stateData");
|
||||
static_assert(offsetof(XApuResult, totalExecutionTime) == 36, "XApuResult.totalExecutionTime");
|
||||
static_assert(offsetof(XApuResult, errorCode) == 44, "XApuResult.errorCode");
|
||||
static_assert(offsetof(XApuResult, outputFrameCount) == 48, "XApuResult.outputFrameCount");
|
||||
static_assert(offsetof(XApuResult, outputDataLength) == 52, "XApuResult.outputDataLength");
|
||||
static_assert(offsetof(XApuResult, outputData) == 56, "XApuResult.outputData");
|
||||
static_assert(offsetof(XApuResult, currentPitch) == 64, "XApuResult.currentPitch");
|
||||
static_assert(offsetof(XApuResult, inputDataLength) == 68, "XApuResult.inputDataLength");
|
||||
static_assert(offsetof(XApuResult, inputData) == 72, "XApuResult.inputData");
|
||||
static_assert(static_cast<uint32_t>(XAPU_E_QUEUE_FULL) == 0x8AC81000u, "XAPU_E_QUEUE_FULL");
|
||||
static_assert(static_cast<uint32_t>(XAPU_E_PENDING_RESULTS) == 0x8AC81001u, "XAPU_E_PENDING_RESULTS");
|
||||
static_assert(static_cast<uint32_t>(XAPU_E_INVALID_STREAM_INDEX) == 0x8AC81003u, "XAPU_E_INVALID_STREAM_INDEX");
|
||||
@@ -1,8 +1,26 @@
|
||||
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
d3d12_xs.cpp
|
||||
vmem.cpp
|
||||
presentx.cpp
|
||||
proxy.cpp
|
||||
proxy_generated.cpp
|
||||
shader_gate.cpp
|
||||
xbox_facade.cpp
|
||||
frame_pacing.cpp
|
||||
placed_x.cpp
|
||||
gdk_xg.cpp
|
||||
descriptor_heaps.cpp
|
||||
committed.cpp
|
||||
console_formats.cpp
|
||||
pipelines.cpp
|
||||
console_pipelines.cpp
|
||||
console_descriptors.cpp
|
||||
rect_list.cpp
|
||||
gpu_writes.cpp
|
||||
fences.cpp
|
||||
presentx_xbox.cpp
|
||||
page_mappings.cpp
|
||||
title_memory.cpp
|
||||
xbox_tables_generated.cpp
|
||||
)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32 user32 dxguid)
|
||||
@@ -0,0 +1,205 @@
|
||||
/*
|
||||
* Committed resources with title-visible memory (ADR 0009).
|
||||
*
|
||||
* On the console the D3D12 runtime allocates a committed resource's memory through XMemAlloc
|
||||
* with AllocatorId eXALLOCAllocatorId_D3D (128) and ObjectType Resource (4) (authorized GDK
|
||||
* documentation, "Direct3D 12 XMemAlloc object types"). Titles hook XMemAlloc to place that
|
||||
* memory themselves, and some check afterwards how much of their own pool those requests used.
|
||||
*
|
||||
* Here the host committed resource holds the contents. The resource also gets the same
|
||||
* XMemAlloc request, and its GPU virtual address is the address that request returned, so title
|
||||
* hooks and title address checks see what they would see on the console. The page size the
|
||||
* console runtime requests is not documented: this layer asks for 2 MB pages for allocations of
|
||||
* at least 2 MB and 64 KB pages otherwise (measured against one title; logged per resource).
|
||||
*
|
||||
* The size of that request is the console's, not the host's, where the console layout is known:
|
||||
* a 2D render-target or unordered-access texture with one mip and one sample is laid out by the
|
||||
* console in 64 KB tiles (swizzle mode 64KB_R_X for every size; authorized GDK XG library). A
|
||||
* title that sizes its pool for those requests and checks what is left over sees the amount it
|
||||
* expects. The compression metadata XG adds after the tiles of a render target (8 KB to 96 KB in
|
||||
* the cases measured) is not included; every other resource keeps the host's size.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "console_formats.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" __declspec(dllimport) PVOID WINAPI XMemAlloc(SIZE_T size, ULONGLONG attributes);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr ULONGLONG kObjectTypeResource = 4;
|
||||
constexpr ULONGLONG kAllocatorIdD3D = 128ull << 16; // XALLOC_ATTRIBUTES.AllocatorId, bits 16-23
|
||||
constexpr ULONGLONG kPageSize64K = 1ull << 14; // XALLOC_ATTRIBUTES.PageSize, bits 14-15
|
||||
constexpr ULONGLONG kPageSize2M = 2ull << 14;
|
||||
constexpr UINT64 k2M = 2ull << 20;
|
||||
|
||||
constexpr UINT64 k64K = 64ull << 10;
|
||||
|
||||
// Bytes per element of an uncompressed colour format, 0 for anything else (depth, block
|
||||
// compressed, video, 96-bit). Formats 116, 117, 189 and 190 are console-only (GDK DXGI_FORMAT).
|
||||
UINT colour_element_bytes(DXGI_FORMAT f) {
|
||||
const UINT v = static_cast<UINT>(f);
|
||||
if (v >= DXGI_FORMAT_R32G32B32A32_TYPELESS && v <= DXGI_FORMAT_R32G32B32A32_SINT) return 16;
|
||||
if (v >= DXGI_FORMAT_R16G16B16A16_TYPELESS && v <= DXGI_FORMAT_R32G32_SINT) return 8;
|
||||
if (v >= DXGI_FORMAT_R10G10B10A2_TYPELESS && v <= DXGI_FORMAT_R32_SINT) return v == DXGI_FORMAT_D32_FLOAT ? 0 : 4;
|
||||
if (v >= DXGI_FORMAT_R8G8_TYPELESS && v <= DXGI_FORMAT_R16_SINT) return v == DXGI_FORMAT_D16_UNORM ? 0 : 2;
|
||||
if (v >= DXGI_FORMAT_R8_TYPELESS && v <= DXGI_FORMAT_A8_UNORM) return 1;
|
||||
if (v >= DXGI_FORMAT_B8G8R8A8_UNORM && v <= DXGI_FORMAT_B8G8R8X8_UNORM_SRGB) return 4;
|
||||
if (v == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM || v == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) return 4;
|
||||
if (v >= DXGI_FORMAT_B5G6R5_UNORM && v <= DXGI_FORMAT_B5G5R5A1_UNORM) return 2;
|
||||
if (v == DXGI_FORMAT_B4G4R4A4_UNORM) return 2;
|
||||
if (v == 116 || v == 117 || v == 189) return 4; // R10G10B10_7E3_A2_FLOAT, _6E4_A2_FLOAT, _SNORM_A2_UNORM
|
||||
if (v == 190) return 1; // R4G4_UNORM
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The console's size for `desc` (the host's geometry, the title's format) where its layout is
|
||||
// known, else 0. The tile of a 64 KB swizzle holds 64 KB of elements: 256x256 at 1 byte,
|
||||
// 256x128 at 2, 128x128 at 4, 128x64 at 8 and 64x64 at 16 (authorized GDK XG library: these
|
||||
// tile counts match its sizes exactly, before the metadata of a render target).
|
||||
UINT64 console_tiled_size(const D3D12_RESOURCE_DESC& desc, DXGI_FORMAT title_format) {
|
||||
constexpr UINT kTargets = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN ||
|
||||
desc.MipLevels != 1 || desc.SampleDesc.Count != 1 || !(desc.Flags & kTargets) ||
|
||||
(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
|
||||
return 0;
|
||||
}
|
||||
UINT tile_w = 0, tile_h = 0;
|
||||
switch (colour_element_bytes(title_format)) {
|
||||
case 1: tile_w = 256; tile_h = 256; break;
|
||||
case 2: tile_w = 256; tile_h = 128; break;
|
||||
case 4: tile_w = 128; tile_h = 128; break;
|
||||
case 8: tile_w = 128; tile_h = 64; break;
|
||||
case 16: tile_w = 64; tile_h = 64; break;
|
||||
default: return 0;
|
||||
}
|
||||
const UINT64 across = (desc.Width + tile_w - 1) / tile_w;
|
||||
const UINT64 down = (static_cast<UINT64>(desc.Height) + tile_h - 1) / tile_h;
|
||||
return across * down * desc.DepthOrArraySize * k64K;
|
||||
}
|
||||
|
||||
HRESULT finish(ID3D12Device* device, HRESULT hr, REFIID riid, void** ppv, const char* method,
|
||||
DXGI_FORMAT title_format) {
|
||||
if (FAILED(hr) || !ppv || !*ppv) return hr;
|
||||
// *ppv is the host resource as `riid`; every ID3D12Resource* interface pointer is the object.
|
||||
auto* resource = static_cast<ID3D12Resource*>(*ppv);
|
||||
const D3D12_RESOURCE_DESC desc = resource->GetDesc();
|
||||
const D3D12_RESOURCE_ALLOCATION_INFO info = device->GetResourceAllocationInfo(0, 1, &desc);
|
||||
const UINT64 host_size = info.SizeInBytes ? info.SizeInBytes : desc.Width;
|
||||
const UINT64 console_size = console_tiled_size(desc, title_format);
|
||||
const UINT64 size = console_size ? console_size : host_size;
|
||||
const ULONGLONG attributes = kObjectTypeResource | kAllocatorIdD3D | (size >= k2M ? kPageSize2M : kPageSize64K);
|
||||
void* title = XMemAlloc(static_cast<SIZE_T>(size), attributes);
|
||||
char detail[240];
|
||||
std::snprintf(detail, sizeof(detail), "%s dim=%d size=%llu (%s, host %llu) page=%s title_va=%p", method,
|
||||
static_cast<int>(desc.Dimension), static_cast<unsigned long long>(size),
|
||||
console_size ? "console 64 KB tiles" : "host", static_cast<unsigned long long>(host_size),
|
||||
size >= k2M ? "2MB" : "64KB", title);
|
||||
bx_log_emit(title ? BX_LOG_INFO : BX_LOG_WARN, "d3d12_xs", "committed_title_memory", detail);
|
||||
if (!title || !bx_xbox_title_memory_attach(resource, reinterpret_cast<uint64_t>(title), size, attributes)) {
|
||||
resource->Release();
|
||||
*ppv = nullptr;
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource");
|
||||
auto* device = bx_xbox_host<ID3D12Device>(self);
|
||||
return finish(device, device->CreateCommittedResource(heap, flags, desc, state, clear, riid, ppv), riid, ppv,
|
||||
"CreateCommittedResource", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource1(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource1");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource1");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource1");
|
||||
auto* device = bx_xbox_host<ID3D12Device4>(self);
|
||||
return finish(device, device->CreateCommittedResource1(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource1", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource2(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource2");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource2");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource2");
|
||||
auto* device = bx_xbox_host<ID3D12Device8>(self);
|
||||
return finish(device, device->CreateCommittedResource2(heap, flags, desc, state, clear, bx_xbox_unwrap_as(session), riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource2", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource3(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const D3D12_RESOURCE_DESC1* desc,
|
||||
D3D12_BARRIER_LAYOUT layout, const D3D12_CLEAR_VALUE* clear,
|
||||
ID3D12ProtectedResourceSession* session, UINT32 formats,
|
||||
DXGI_FORMAT* castable, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResource3");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC1> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
const DXGI_FORMAT title_format = desc ? desc->Format : DXGI_FORMAT_UNKNOWN;
|
||||
desc = host_desc.of_resource(desc, "CreateCommittedResource3");
|
||||
clear = host_clear.of(clear, "CreateCommittedResource3");
|
||||
auto* device = bx_xbox_host<ID3D12Device10>(self);
|
||||
return finish(device,
|
||||
device->CreateCommittedResource3(heap, flags, desc, layout, clear, bx_xbox_unwrap_as(session), formats,
|
||||
castable, riid, ppv),
|
||||
riid, ppv, "CreateCommittedResource3", title_format);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_committed_resource_x(void* self, const D3D12_HEAP_PROPERTIES* heap,
|
||||
D3D12_HEAP_FLAGS flags, const void* xbox_desc,
|
||||
D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid,
|
||||
void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommittedResourceX");
|
||||
if (!xbox_desc) return E_INVALIDARG;
|
||||
// D3D12XBOX_RESOURCE_DESC begins with the PC description; DccOptions follows it. DccOptions is
|
||||
// a struct of two 32-bit enums, CompressionLevel and ColorTransform; every value of either
|
||||
// selects some form of colour compression (CompressionLevel 0 is 64B, not "none").
|
||||
D3D12_RESOURCE_DESC desc{};
|
||||
std::memcpy(&desc, xbox_desc, sizeof(desc));
|
||||
UINT32 dcc[2] = {};
|
||||
std::memcpy(dcc, static_cast<const char*>(xbox_desc) + sizeof(desc), sizeof(dcc));
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 8) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"DccOptions CompressionLevel=%u ColorTransform=%u ignored (no colour compression on the host)",
|
||||
dcc[0], dcc[1]);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "CreateCommittedResourceX", detail);
|
||||
}
|
||||
return bx_xbox_device_create_committed_resource(self, heap, flags, &desc, state, clear, riid, ppv);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,393 @@
|
||||
/*
|
||||
* 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 until the shim releases it
|
||||
* (placed_x.cpp releases implicit shadows the title has replaced; their markers then resolve to null
|
||||
* views); 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 "title_memory.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::vector<std::string> g_view_keys(1);
|
||||
std::unordered_map<std::string, uint32_t> g_view_ids;
|
||||
std::unordered_map<const ID3D12Resource*, std::vector<uint32_t>> g_views_of; // resource -> ids of its views
|
||||
|
||||
/* `owner`: the resource the view depends on, when the shim may release it early; an SRV's own
|
||||
resource otherwise. */
|
||||
uint32_t intern(const std::string& key, const View& view, ID3D12Resource* owner = nullptr) {
|
||||
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);
|
||||
g_view_keys.push_back(key);
|
||||
if (view.resource) view.resource->AddRef();
|
||||
if (const ID3D12Resource* index = owner ? owner : view.resource) g_views_of[index].push_back(id);
|
||||
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) {
|
||||
return bx_title_memory_present(address, size);
|
||||
}
|
||||
|
||||
/* 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, BxTextureUploads* uploads) {
|
||||
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]];
|
||||
// Held for this resolve: bx_console_forget_resource may drop the registry's reference.
|
||||
if (ok && view.resource) view.resource->AddRef();
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE host = bx_xbox_host_cpu_handle({static_cast<SIZE_T>(entry)});
|
||||
uint64_t total = 0;
|
||||
// A view whose resource the shim has released (an implicit shadow the title replaced) resolves
|
||||
// to a null view: never to memory that is gone.
|
||||
const bool released = ok && view.texture && !view.resource;
|
||||
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, or a
|
||||
// null view when the buffer behind it has been released.
|
||||
if (constant_copy(device, view.title_va, view.cbv.SizeInBytes, ©)) {
|
||||
device->CreateConstantBufferView(©, host);
|
||||
} else {
|
||||
device->CreateConstantBufferView(view.cbv.BufferLocation ? &view.cbv : nullptr, host);
|
||||
}
|
||||
++g_resolved;
|
||||
} else if (ok && use.texture && view.texture && !(released && !view.has_srv_desc)) {
|
||||
// A texture placed in title memory is read through a copy of its contents (#745).
|
||||
ID3D12Resource* contents = released ? nullptr : bx_xbox_texture_contents(view.resource, uploads);
|
||||
device->CreateShaderResourceView(contents, 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()));
|
||||
}
|
||||
if (ok && view.resource) view.resource->Release();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_mark_cbv_of(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc,
|
||||
ID3D12Resource* owner) {
|
||||
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, owner));
|
||||
}
|
||||
|
||||
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc) {
|
||||
bx_console_mark_cbv_of(title_handle, title_va, host_desc, nullptr);
|
||||
}
|
||||
|
||||
void bx_console_forget_resource(ID3D12Resource* resource) {
|
||||
if (!resource) return;
|
||||
std::vector<ID3D12Resource*> references;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_view_lock);
|
||||
auto it = g_views_of.find(resource);
|
||||
if (it == g_views_of.end()) return;
|
||||
for (const uint32_t id : it->second) {
|
||||
View& v = g_views[id];
|
||||
if (v.resource == resource) {
|
||||
references.push_back(resource);
|
||||
v.resource = nullptr;
|
||||
}
|
||||
if (!v.texture) v.cbv.BufferLocation = 0; // the fallback lay in the released buffer
|
||||
// A new view made later with the same description gets a new id.
|
||||
auto key = g_view_ids.find(g_view_keys[id]);
|
||||
if (key != g_view_ids.end() && key->second == id) g_view_ids.erase(key);
|
||||
}
|
||||
g_views_of.erase(it);
|
||||
}
|
||||
for (ID3D12Resource* r : references) r->Release();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* Per queue: a list of the shim's own that uploads texture contents (placed_x.cpp) ahead of the
|
||||
title's lists, its allocators in turn, and a fence for both (#745). */
|
||||
struct UploadContext {
|
||||
static constexpr UINT kTurns = 4;
|
||||
std::mutex lock;
|
||||
ID3D12CommandAllocator* allocators[kTurns] = {};
|
||||
UINT64 allocator_values[kTurns] = {};
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
HANDLE event = nullptr;
|
||||
UINT64 next = 1;
|
||||
UINT turn = 0;
|
||||
bool failed = false;
|
||||
};
|
||||
std::mutex g_upload_lock;
|
||||
std::unordered_map<const void*, std::unique_ptr<UploadContext>> g_uploads;
|
||||
|
||||
UploadContext* upload_context(ID3D12CommandQueue* queue) {
|
||||
UploadContext* ctx = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_upload_lock);
|
||||
auto& slot = g_uploads[queue];
|
||||
if (!slot) slot = std::make_unique<UploadContext>();
|
||||
ctx = slot.get();
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(ctx->lock);
|
||||
if (ctx->list || ctx->failed) return ctx->failed ? nullptr : ctx;
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
const D3D12_COMMAND_LIST_TYPE type = queue->GetDesc().Type;
|
||||
for (UINT i = 0; SUCCEEDED(hr) && i < UploadContext::kTurns; ++i) {
|
||||
hr = device->CreateCommandAllocator(type, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&ctx->allocators[i]));
|
||||
}
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommandList(0, type, ctx->allocators[0], nullptr, __uuidof(ID3D12GraphicsCommandList),
|
||||
reinterpret_cast<void**>(&ctx->list));
|
||||
}
|
||||
if (SUCCEEDED(hr)) hr = ctx->list->Close();
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&ctx->fence));
|
||||
if (device) device->Release();
|
||||
ctx->event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (FAILED(hr) || !ctx->event) {
|
||||
ctx->failed = true;
|
||||
log(BX_LOG_WARN, "texture_upload", "no upload list for this queue (hr=0x%08lx); texture contents are not uploaded on it",
|
||||
static_cast<unsigned long>(FAILED(hr) ? hr : E_OUTOFMEMORY));
|
||||
return nullptr;
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_submit(ID3D12CommandQueue* queue, 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());
|
||||
}
|
||||
}
|
||||
if (draws.empty()) return;
|
||||
UploadContext* ctx = queue ? upload_context(queue) : nullptr;
|
||||
std::unique_lock<std::mutex> held;
|
||||
BxTextureUploads uploads{nullptr, nullptr, 0, false};
|
||||
UINT turn = 0;
|
||||
if (ctx) {
|
||||
held = std::unique_lock<std::mutex>(ctx->lock);
|
||||
turn = ctx->turn % UploadContext::kTurns;
|
||||
if (ctx->fence->GetCompletedValue() < ctx->allocator_values[turn]) {
|
||||
ctx->fence->SetEventOnCompletion(ctx->allocator_values[turn], ctx->event);
|
||||
WaitForSingleObject(ctx->event, 2000);
|
||||
}
|
||||
if (SUCCEEDED(ctx->allocators[turn]->Reset()) && SUCCEEDED(ctx->list->Reset(ctx->allocators[turn], nullptr))) {
|
||||
uploads = BxTextureUploads{ctx->list, ctx->fence, ctx->next, false};
|
||||
}
|
||||
}
|
||||
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, uploads.list ? &uploads : nullptr);
|
||||
}
|
||||
}
|
||||
if (uploads.list) {
|
||||
ctx->list->Close();
|
||||
if (uploads.recorded) {
|
||||
ID3D12CommandList* lists[] = {ctx->list};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
queue->Signal(ctx->fence, uploads.value);
|
||||
ctx->allocator_values[turn] = uploads.value;
|
||||
++ctx->next;
|
||||
++ctx->turn;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/*
|
||||
* Console-only DXGI formats and console-only view combinations: the Xbox-layout device entry
|
||||
* points that carry a format to the host and are otherwise plain forwarders. See
|
||||
* console_formats.h for the formats and the reason.
|
||||
*
|
||||
* Covered here: the three GetResourceAllocationInfo forms, CreatePlacedResource,
|
||||
* CreateReservedResource and the four view-creation methods. Committed resources and the placed
|
||||
* (X) resources and views translate in committed.cpp and placed_x.cpp. Pipeline-state formats are
|
||||
* not translated yet: no console pipeline is created on the host so far.
|
||||
*/
|
||||
#include "console_formats.h"
|
||||
|
||||
#include "xbox_facade.h"
|
||||
#include "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);
|
||||
const uint32_t bit = 1u << (f >= 189 ? f - 189 + 8 : f - 116);
|
||||
if (noted.fetch_or(bit) & bit) return;
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"console-only format %d is translated for the host (view and clear format %d, resource format %d; first seen in %s)",
|
||||
f, static_cast<int>(bx_host_format(format)), static_cast<int>(bx_host_resource_format(format)), where);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_format", detail);
|
||||
}
|
||||
|
||||
/* The console allows D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL together with ALLOW_UNORDERED_ACCESS,
|
||||
* and a title writes the depth plane from a compute shader through an R32_FLOAT unordered-access
|
||||
* view. PC Direct3D 12 forbids the combination. D3DMetal accepts the resource, answers the view
|
||||
* with a Metal texture view that Metal refuses ("texture view pixelFormat
|
||||
* (MTLPixelFormatDepth32Float) not castable"), and Metal aborts the process.
|
||||
*
|
||||
* Until that write path is emulated, such a descriptor gets a null view of the same description
|
||||
* (Direct3D 12 defines it: reads return zero, writes are discarded) and the call is logged as
|
||||
* unimplemented, so the gap is visible in every run report instead of ending the process. */
|
||||
void bx_xbox_create_host_uav(ID3D12Device* device, ID3D12Resource* host, ID3D12Resource* counter,
|
||||
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE host_dest,
|
||||
const char* method) {
|
||||
BxHostFormat<D3D12_UNORDERED_ACCESS_VIEW_DESC> translated;
|
||||
desc = translated.of(desc, method);
|
||||
if (host && (host->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "CreateUnorderedAccessView(depth-stencil resource)");
|
||||
// A null view needs a description; without one the descriptor is left as it was.
|
||||
if (desc) device->CreateUnorderedAccessView(nullptr, nullptr, desc, host_dest);
|
||||
return;
|
||||
}
|
||||
device->CreateUnorderedAccessView(host, counter, desc, host_dest);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* An array of resource descriptions as the host must see it. */
|
||||
template <typename Desc>
|
||||
class HostDescs {
|
||||
public:
|
||||
HostDescs(const Desc* in, UINT count, const char* where) : descs_(in) {
|
||||
if (!in) return;
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
if (!bx_is_console_only_format(in[i].Format)) continue;
|
||||
if (copy_.empty()) copy_.assign(in, in + count);
|
||||
bx_note_console_format(in[i].Format, where);
|
||||
copy_[i].Format = bx_host_resource_format(in[i].Format);
|
||||
}
|
||||
if (!copy_.empty()) descs_ = copy_.data();
|
||||
}
|
||||
const Desc* get() const { return descs_; }
|
||||
|
||||
private:
|
||||
const Desc* descs_;
|
||||
std::vector<Desc> copy_;
|
||||
};
|
||||
|
||||
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC& d) { return d; }
|
||||
D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC1& d) {
|
||||
D3D12_RESOURCE_DESC out{};
|
||||
out.Dimension = d.Dimension;
|
||||
out.Alignment = d.Alignment;
|
||||
out.Width = d.Width;
|
||||
out.Height = d.Height;
|
||||
out.DepthOrArraySize = d.DepthOrArraySize;
|
||||
out.MipLevels = d.MipLevels;
|
||||
out.Format = d.Format;
|
||||
out.SampleDesc = d.SampleDesc;
|
||||
out.Layout = d.Layout;
|
||||
out.Flags = d.Flags;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Descriptions the GDK's XG answers: an explicit console layout, or a texture left at
|
||||
D3D12_TEXTURE_LAYOUT_UNKNOWN, which selects the console's default tiling. A title sizes its loads
|
||||
from these answers (#708: a 128x4 RGBA16 texture is 16 KB in 4 KB tiles; the host's 4 KB answer
|
||||
made it request a quarter of the compressed chunk). Buffers and the PC layouts (row major,
|
||||
64 KB swizzles) keep the host's answer. */
|
||||
bool xg_sized(const D3D12_RESOURCE_DESC& desc) {
|
||||
return bx_is_console_texture_layout(desc) || bx_is_console_default_texture(desc);
|
||||
}
|
||||
|
||||
/* Allocation info for descriptions that include a console texture (xg_sized). 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 is a console texture
|
||||
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 = xg_sized(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 (!xg_sized(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
|
||||
D3D12_RESOURCE_DESC host = desc;
|
||||
if (bx_is_console_only_format(host.Format)) host.Format = bx_host_resource_format(host.Format);
|
||||
if (bx_is_console_texture_layout(host)) host.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
D3D12_RESOURCE_ALLOCATION_INFO one{};
|
||||
device->GetResourceAllocationInfo(&one, mask, 1, &host);
|
||||
size = one.SizeInBytes;
|
||||
alignment = one.Alignment;
|
||||
} else {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) < 24) {
|
||||
char detail[192];
|
||||
std::snprintf(detail, sizeof(detail), "%s %llux%ux%u mips=%u format=%d layout=0x%x: console size %llu, alignment %llu",
|
||||
method, static_cast<unsigned long long>(desc.Width), desc.Height, desc.DepthOrArraySize, desc.MipLevels,
|
||||
static_cast<int>(desc.Format), static_cast<UINT>(desc.Layout), static_cast<unsigned long long>(size),
|
||||
static_cast<unsigned long long>(alignment));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_allocation", detail);
|
||||
}
|
||||
}
|
||||
if (size == UINT64_MAX || !alignment) return false;
|
||||
offset = (offset + alignment - 1) / alignment * alignment;
|
||||
if (each) each[i] = D3D12_RESOURCE_ALLOCATION_INFO1{offset, alignment, size};
|
||||
offset += size;
|
||||
if (alignment > max_alignment) max_alignment = alignment;
|
||||
}
|
||||
total->SizeInBytes = offset;
|
||||
total->Alignment = max_alignment;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info(void* self, UINT mask, UINT count,
|
||||
const D3D12_RESOURCE_DESC* descs) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, nullptr, "GetResourceAllocationInfo")) {
|
||||
return result;
|
||||
}
|
||||
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo");
|
||||
bx_xbox_host<ID3D12Device>(self)->GetResourceAllocationInfo(&result, mask, count, host.get());
|
||||
return result;
|
||||
}
|
||||
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info1(
|
||||
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo1");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo1")) {
|
||||
return result;
|
||||
}
|
||||
const HostDescs<D3D12_RESOURCE_DESC> host(descs, count, "GetResourceAllocationInfo1");
|
||||
bx_xbox_host<ID3D12Device4>(self)->GetResourceAllocationInfo1(&result, mask, count, host.get(), each);
|
||||
return result;
|
||||
}
|
||||
|
||||
D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE bx_xbox_device_get_resource_allocation_info2(
|
||||
void* self, UINT mask, UINT count, const D3D12_RESOURCE_DESC1* descs, D3D12_RESOURCE_ALLOCATION_INFO1* each) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetResourceAllocationInfo2");
|
||||
D3D12_RESOURCE_ALLOCATION_INFO result{};
|
||||
if (console_allocation(bx_xbox_host<ID3D12Device>(self), mask, count, descs, &result, each, "GetResourceAllocationInfo2")) {
|
||||
return result;
|
||||
}
|
||||
const HostDescs<D3D12_RESOURCE_DESC1> host(descs, count, "GetResourceAllocationInfo2");
|
||||
bx_xbox_host<ID3D12Device8>(self)->GetResourceAllocationInfo2(&result, mask, count, host.get(), each);
|
||||
return result;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_placed_resource(void* self, ID3D12Heap* heap, UINT64 offset,
|
||||
const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state,
|
||||
const D3D12_CLEAR_VALUE* clear, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreatePlacedResource");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreatePlacedResource(
|
||||
bx_xbox_unwrap_as<ID3D12Heap>(heap), offset, host_desc.of_resource(desc, "CreatePlacedResource"), state,
|
||||
host_clear.of(clear, "CreatePlacedResource"), riid, ppv);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreatePlacedResource", hr);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_reserved_resource(void* self, const D3D12_RESOURCE_DESC* desc,
|
||||
D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateReservedResource");
|
||||
BxHostFormat<D3D12_RESOURCE_DESC> host_desc;
|
||||
BxHostFormat<D3D12_CLEAR_VALUE> host_clear;
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateReservedResource(
|
||||
host_desc.of_resource(desc, "CreateReservedResource"), state, host_clear.of(clear, "CreateReservedResource"), riid, ppv);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateReservedResource", hr);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_SHADER_RESOURCE_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
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,
|
||||
const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateUnorderedAccessView");
|
||||
bx_xbox_create_host_uav(bx_xbox_host<ID3D12Device>(self), bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
bx_xbox_unwrap_as<ID3D12Resource>(counter), desc, bx_xbox_host_cpu_handle(dest),
|
||||
"CreateUnorderedAccessView");
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D12Resource* resource,
|
||||
const D3D12_RENDER_TARGET_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
|
||||
BxHostFormat<D3D12_RENDER_TARGET_VIEW_DESC> host;
|
||||
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,
|
||||
const D3D12_DEPTH_STENCIL_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
|
||||
BxHostFormat<D3D12_DEPTH_STENCIL_VIEW_DESC> host;
|
||||
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"
|
||||
Loaded 100 of 349 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user