mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 08:59:52 +00:00
Compare commits
847
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fadc89b023 | ||
|
|
c38be3e256 | ||
|
|
5e002c409f | ||
|
|
78a29fac05 | ||
|
|
c70b951aab | ||
|
|
ca2877c61d | ||
|
|
7d5d76f001 | ||
|
|
40ba0632b1 | ||
|
|
0bfd08eb12 | ||
|
|
d97b856e93 | ||
|
|
3feba31a33 | ||
|
|
a51271d125 | ||
|
|
4fc5d9e5a4 | ||
|
|
f2c42ba110 | ||
|
|
30e551a161 | ||
|
|
d9333d272f | ||
|
|
395aaeb4e7 | ||
|
|
efb63a37d4 | ||
|
|
35cdf56e80 | ||
|
|
db3bdb5a5c | ||
|
|
9b20f78a06 | ||
|
|
b39780b421 | ||
|
|
f8f497b578 | ||
|
|
77cec214c0 | ||
|
|
953254a435 | ||
|
|
39b628d60d | ||
|
|
1d70633958 | ||
|
|
a9f55b51f7 | ||
|
|
722388a46d | ||
|
|
e7ff293eba | ||
|
|
dfaaa07df4 | ||
|
|
962b83c731 | ||
|
|
7fff77c801 | ||
|
|
c3684a1ae8 | ||
|
|
d561595599 | ||
|
|
8cab0b1de8 | ||
|
|
d2367dca30 | ||
|
|
60ad6c779e | ||
|
|
ffc7056d26 | ||
|
|
9923e59114 | ||
|
|
feba95fe39 | ||
|
|
a275de6e2e | ||
|
|
25986845da | ||
|
|
df9652740b | ||
|
|
1ca491d8d0 | ||
|
|
964a8296f2 | ||
|
|
d8a8c96408 | ||
|
|
50321b3f14 | ||
|
|
1fe07f45ee | ||
|
|
d486d21813 | ||
|
|
4c92c88b29 | ||
|
|
478e9218ac | ||
|
|
8d2662dcd7 | ||
|
|
fe1bf568c8 | ||
|
|
873652d685 | ||
|
|
84f561b12b | ||
|
|
2b113a2e5e | ||
|
|
9a26e1ee36 | ||
|
|
c84b80b24f | ||
|
|
ae804f0530 | ||
|
|
64e7b16983 | ||
|
|
1ea898b4bf | ||
|
|
7946968cc4 | ||
|
|
67b8cff9df | ||
|
|
51c23a2f38 | ||
|
|
7d97e67448 | ||
|
|
d9261db887 | ||
|
|
5c0c82b3f9 | ||
|
|
b71db3c25a | ||
|
|
566f803111 | ||
|
|
857c16fcf7 | ||
|
|
4f5c6913f5 | ||
|
|
e4ddb05a1a | ||
|
|
d33a7c6941 | ||
|
|
4e838207fe | ||
|
|
b40bbae1da | ||
|
|
b04b41f26a | ||
|
|
3dd3ef06e2 | ||
|
|
b2654e93a4 | ||
|
|
fee956293d | ||
|
|
146d2dd467 | ||
|
|
a0d9b85dbf | ||
|
|
5366b93986 | ||
|
|
50c392111d | ||
|
|
f43a07ce31 | ||
|
|
10fd1cd4be | ||
|
|
95aa10c60f | ||
|
|
873b4fd4a9 | ||
|
|
120878de2d | ||
|
|
d26af53cef | ||
|
|
b6ebaaad5e | ||
|
|
aba82cdb77 | ||
|
|
44ac976291 | ||
|
|
d71efe0495 | ||
|
|
0bd8e19aac | ||
|
|
a1744a2754 | ||
|
|
e93509ef5b | ||
|
|
8344e299c9 | ||
|
|
433dc43695 | ||
|
|
c18f9ffa7f | ||
|
|
a0f2d833aa | ||
|
|
61afca42c9 | ||
|
|
be19e4e28f | ||
|
|
33ccf7fd55 | ||
|
|
bb62353cfe | ||
|
|
1f2e7d3bb6 | ||
|
|
b5b646a58d | ||
|
|
acb3839351 | ||
|
|
f9d5838091 | ||
|
|
4314071ac7 | ||
|
|
4173a781af | ||
|
|
4e15e5f43b | ||
|
|
cf4010ba94 | ||
|
|
b9e6a9d365 | ||
|
|
a1a1020ebd | ||
|
|
e755ee94ed | ||
|
|
2f68ee9d4a | ||
|
|
e7a2159c82 | ||
|
|
98e9420b7f | ||
|
|
238b5a001b | ||
|
|
e289318132 | ||
|
|
99ed89787e | ||
|
|
522560d0a2 | ||
|
|
f685b54e32 | ||
|
|
0690a3ecb4 | ||
|
|
7286989296 | ||
|
|
d28d539a90 | ||
|
|
8c4b2344df | ||
|
|
a75d018435 | ||
|
|
4652eb08cb | ||
|
|
d1bcd0249d | ||
|
|
097bb0b5b8 | ||
|
|
2d77b35e56 | ||
|
|
19f63a0985 | ||
|
|
45322af82e | ||
|
|
aa9a961ef4 | ||
|
|
10347dc21b | ||
|
|
4d530392d1 | ||
|
|
f02eb2678e | ||
|
|
19a905c30e | ||
|
|
bfe0bbfaf7 | ||
|
|
5442503d57 | ||
|
|
f0c61c7a91 | ||
|
|
0caca18634 | ||
|
|
81a32e3ec6 | ||
|
|
8edf3abf53 | ||
|
|
0c397c5957 | ||
|
|
417b19c859 | ||
|
|
4cc703d566 | ||
|
|
5ae43a3cb8 | ||
|
|
ab73969135 | ||
|
|
8ee0304237 | ||
|
|
42cdb7d122 | ||
|
|
2ea75603be | ||
|
|
6fc06dccff | ||
|
|
a1295d5a48 | ||
|
|
0a17f0cb73 | ||
|
|
20d7b9ece4 | ||
|
|
db80c0b3e3 | ||
|
|
db46390fa9 | ||
|
|
a9abc36eef | ||
|
|
972bc0a35c | ||
|
|
c0e90338d1 | ||
|
|
e32c85ff12 | ||
|
|
d409c26458 | ||
|
|
e57386950b | ||
|
|
1fafc2e43f | ||
|
|
0aeb2b69a9 | ||
|
|
1342878c49 | ||
|
|
d6c9f846f0 | ||
|
|
34e99b3745 | ||
|
|
d5fa319f56 | ||
|
|
e5d83e87ac | ||
|
|
985d3b9e78 | ||
|
|
0929d0214b | ||
|
|
43f8287c92 | ||
|
|
a91c7fa39d | ||
|
|
22425287e2 | ||
|
|
874c7c7a63 | ||
|
|
f30e4af4eb | ||
|
|
501117c4d8 | ||
|
|
3d796f51cf | ||
|
|
66f7127553 | ||
|
|
714eaf49e2 | ||
|
|
c93b505223 | ||
|
|
d8f7f2cb13 | ||
|
|
042c08c855 | ||
|
|
7e4ccd1e97 | ||
|
|
96c772edc5 | ||
|
|
0236ec6ba9 | ||
|
|
48d22f533b | ||
|
|
52e7e3808d | ||
|
|
464393e02a | ||
|
|
aae04a2956 | ||
|
|
721073169c | ||
|
|
26148f49f6 | ||
|
|
e81382de37 | ||
|
|
496938aef4 | ||
|
|
9d94c0f40a | ||
|
|
4e18000798 | ||
|
|
8c188b04c9 | ||
|
|
9eb75522f0 | ||
|
|
3f41f7406b | ||
|
|
1c8d7a40de | ||
|
|
afe8d16d9e | ||
|
|
67023d292b | ||
|
|
d326e929a9 | ||
|
|
324eab08c3 | ||
|
|
149869a053 | ||
|
|
a6b0e89cac | ||
|
|
32251af4c8 | ||
|
|
1c6bd25723 | ||
|
|
007ad360e9 | ||
|
|
0d6cef6c4e | ||
|
|
64a0cb1596 | ||
|
|
53e5e38a4e | ||
|
|
47a819e05b | ||
|
|
7d28fc89de | ||
|
|
9a29bd9c37 | ||
|
|
38359969cd | ||
|
|
652c6ae02f | ||
|
|
0529c62226 | ||
|
|
e6fa931264 | ||
|
|
3b47c21bb0 | ||
|
|
9a62d86a89 | ||
|
|
4b32c532fe | ||
|
|
af1b84ad75 | ||
|
|
cf438e25aa | ||
|
|
bd46504a97 | ||
|
|
cc4dd092cf | ||
|
|
04ee981103 | ||
|
|
bbc84c0da0 | ||
|
|
d2f77cdea3 | ||
|
|
3a36379db4 | ||
|
|
147e2a9f1a | ||
|
|
a7fa8b0d65 | ||
|
|
fd0e73bc28 | ||
|
|
35de41bd5f | ||
|
|
e6b657a2e9 | ||
|
|
c05e631c6d | ||
|
|
6bac25f099 | ||
|
|
d35c278284 | ||
|
|
34a583b101 | ||
|
|
061c28b405 | ||
|
|
3b52215a30 | ||
|
|
0214a7bab5 | ||
|
|
fbec436b89 | ||
|
|
47b526fba9 | ||
|
|
c68e3ccb4c | ||
|
|
e856f080d1 | ||
|
|
fb6282ceb2 | ||
|
|
bb6a9f6912 | ||
|
|
a7e3e1e42c | ||
|
|
9c76bf16f0 | ||
|
|
2f28a5adbb | ||
|
|
788de1e83b | ||
|
|
7dd1329866 | ||
|
|
4b579af70d | ||
|
|
b4f45573cf | ||
|
|
0766307acc | ||
|
|
9dfdfd1134 | ||
|
|
ce8d16e367 | ||
|
|
8df13ae976 | ||
|
|
36c4fbd520 | ||
|
|
3c8b6bad97 | ||
|
|
d4c29cd7dd | ||
|
|
7246ab5ea6 | ||
|
|
938cbd3028 | ||
|
|
c9505e53e2 | ||
|
|
02eb8046a1 | ||
|
|
4a0b5d4ded | ||
|
|
00eb6971e9 | ||
|
|
c3b0025977 | ||
|
|
1013746e17 | ||
|
|
7c88e5d655 | ||
|
|
bb318ed2ba | ||
|
|
b1b57cf16a | ||
|
|
cdcc55c33e | ||
|
|
0730f4dbbf | ||
|
|
6f27da3ccc | ||
|
|
6236996f41 | ||
|
|
05f2526d27 | ||
|
|
e5aca73c55 | ||
|
|
281d92bfb5 | ||
|
|
5131de9cd6 | ||
|
|
fec13fa27a | ||
|
|
68503a674c | ||
|
|
82cb66e80f | ||
|
|
06dbe2946d | ||
|
|
685217e61b | ||
|
|
a0d4b7bf5d | ||
|
|
14d5083f0f | ||
|
|
0115af5c04 | ||
|
|
9ddb708cdf | ||
|
|
5b7ffec90a | ||
|
|
48c5d20aa9 | ||
|
|
8049c36f51 | ||
|
|
94783fa603 | ||
|
|
c91036f879 | ||
|
|
c1cea65e17 | ||
|
|
974d1fc62c | ||
|
|
6f1ac2a906 | ||
|
|
223a754eb7 | ||
|
|
3d19c756e2 | ||
|
|
729e1b4cb1 | ||
|
|
d195978903 | ||
|
|
830f93ff14 | ||
|
|
4962f054c8 | ||
|
|
67dfb18166 | ||
|
|
782c49167c | ||
|
|
6106c37912 | ||
|
|
d2491dee07 | ||
|
|
823a5812a0 | ||
|
|
c1ca4ea140 | ||
|
|
710a2e1e73 | ||
|
|
de92766b29 | ||
|
|
b09d96fd62 | ||
|
|
4d44765363 | ||
|
|
6de750b152 | ||
|
|
c95e175210 | ||
|
|
adf10db015 | ||
|
|
6814d78230 | ||
|
|
4e4a6b36be | ||
|
|
403a67747f | ||
|
|
509811aad0 | ||
|
|
dc3b02b62f | ||
|
|
d847d7ea6e | ||
|
|
b9372408c8 | ||
|
|
8b67479526 | ||
|
|
0fdb995892 | ||
|
|
b55a4c24ef | ||
|
|
1dcf722323 | ||
|
|
48e1e5c8c1 | ||
|
|
6947fe7ff6 | ||
|
|
94732d90ca | ||
|
|
1e8893a6bf | ||
|
|
d7f7d586d3 | ||
|
|
b8fbdf35b9 | ||
|
|
d01627b3de | ||
|
|
291c9807ee | ||
|
|
84866956b9 | ||
|
|
47cb26ebdd | ||
|
|
1d363c3c34 | ||
|
|
eaeab25590 | ||
|
|
e74ebbe30b | ||
|
|
26eba92b87 | ||
|
|
05143d6295 | ||
|
|
d6a65b2940 | ||
|
|
1cc7f01fec | ||
|
|
8d19006c32 | ||
|
|
6a4fc7cce1 | ||
|
|
b5b24347e9 | ||
|
|
f8eb976102 | ||
|
|
84221ac715 | ||
|
|
673e2a4556 | ||
|
|
bbb59324c0 | ||
|
|
34b16ca65c | ||
|
|
fd0e427c7b | ||
|
|
314d1f5874 | ||
|
|
7adb978683 | ||
|
|
9d5de05055 | ||
|
|
3348d34e6f | ||
|
|
8e9ec8b9d1 | ||
|
|
b54f5ef0aa | ||
|
|
4d5207afd8 | ||
|
|
27daa701c1 | ||
|
|
c985c3fa17 | ||
|
|
6ad1602a3d | ||
|
|
82cafe9664 | ||
|
|
bf2c279dc7 | ||
|
|
3521dca45b | ||
|
|
131c8669cf | ||
|
|
2c8c63cf65 | ||
|
|
da16b36499 | ||
|
|
061568a6ee | ||
|
|
a03188315d | ||
|
|
95f6b52d9f | ||
|
|
7499d6f6c3 | ||
|
|
3a3f0c52af | ||
|
|
989bb79d6c | ||
|
|
d157f802d3 | ||
|
|
fb0544652b | ||
|
|
61943d23b6 | ||
|
|
947d6e4eaf | ||
|
|
bdcdd57c55 | ||
|
|
5b894777ce | ||
|
|
dc44c5c64b | ||
|
|
b49d50e34e | ||
|
|
e0a6dae554 | ||
|
|
b3a6a57a8e | ||
|
|
b9f6985d57 | ||
|
|
db40a1307d | ||
|
|
b174b45bed | ||
|
|
7504a5d48d | ||
|
|
2b858ab7c6 | ||
|
|
076f3e52aa | ||
|
|
e17e3bfc63 | ||
|
|
1915e2374c | ||
|
|
6545a25b7b | ||
|
|
d5514aa9d8 | ||
|
|
7623fde0e7 | ||
|
|
f2e6db03a9 | ||
|
|
3a14bd98ab | ||
|
|
d31b8ef20c | ||
|
|
81cfe69143 | ||
|
|
91fe3f345b | ||
|
|
0a722d2e60 | ||
|
|
738b518a26 | ||
|
|
0cf4e8a9e9 | ||
|
|
9f8dc3a912 | ||
|
|
d6f21217a2 | ||
|
|
9478795696 | ||
|
|
d8c117cdd3 | ||
|
|
9ef9537540 | ||
|
|
081f9c9e06 | ||
|
|
17fa47f058 | ||
|
|
3250ae8fd1 | ||
|
|
6ff79431bc | ||
|
|
c1fc4d373f | ||
|
|
1b4911ffea | ||
|
|
6c460f7c1c | ||
|
|
8d7f7fadb4 | ||
|
|
a2a6a56222 | ||
|
|
fbe1d3c4d1 | ||
|
|
8f67a9680d | ||
|
|
74af0d8eb9 | ||
|
|
4bc268c931 | ||
|
|
0b00fb378d | ||
|
|
d5437c1c18 | ||
|
|
ad4d07492d | ||
|
|
65bf3ec3fc | ||
|
|
0afae6fa45 | ||
|
|
143429ceeb | ||
|
|
1eae910ce1 | ||
|
|
c586a4a82a | ||
|
|
9e35434f63 | ||
|
|
6e64737021 | ||
|
|
8b0b62a771 | ||
|
|
d658907fd7 | ||
|
|
a2cc14d223 | ||
|
|
9500ed17e5 | ||
|
|
980436a963 | ||
|
|
d6b751976d | ||
|
|
263284ff4f | ||
|
|
02f06bbbe8 | ||
|
|
ac6f9daff3 | ||
|
|
e1e261ea82 | ||
|
|
f4c4b5f9d0 | ||
|
|
c5238a83a3 | ||
|
|
de536c033b | ||
|
|
eb85731d5d | ||
|
|
06ded40d54 | ||
|
|
22e1864b36 | ||
|
|
21da49b109 | ||
|
|
175335e1f6 | ||
|
|
b37a859cd6 | ||
|
|
81868436b8 | ||
|
|
714efd873b | ||
|
|
06d895ec23 | ||
|
|
6b55d76a14 | ||
|
|
a359956033 | ||
|
|
625e26affc | ||
|
|
b8b42c73bf | ||
|
|
01a8445412 | ||
|
|
06614f2219 | ||
|
|
e984cfc099 | ||
|
|
3ca4c8586c | ||
|
|
93d26d6e45 | ||
|
|
7f80767810 | ||
|
|
846589abce | ||
|
|
1edcbb651d | ||
|
|
efe9fdeb8d | ||
|
|
ccaa92ce3a | ||
|
|
243a2d2c58 | ||
|
|
149f9389f9 | ||
|
|
1c5c320437 | ||
|
|
7c3499d5a2 | ||
|
|
6bc88d6c51 | ||
|
|
7d3c004285 | ||
|
|
105bf8a65c | ||
|
|
9da73f8ad8 | ||
|
|
9241630f6c | ||
|
|
542684612d | ||
|
|
f9a7d99638 | ||
|
|
516976fb9f | ||
|
|
32e41e3890 | ||
|
|
bf56047db9 | ||
|
|
fa2e89cc06 | ||
|
|
2384bed8b4 | ||
|
|
b8fae106af | ||
|
|
547b10250d | ||
|
|
4b370efa12 | ||
|
|
f6c87de433 | ||
|
|
0b6ab43ad4 | ||
|
|
aa93665b97 | ||
|
|
565c144a39 | ||
|
|
ef90105a26 | ||
|
|
ed33b57c8d | ||
|
|
9e2c7b6e0b | ||
|
|
e95b0a055d | ||
|
|
88e7dad8b2 | ||
|
|
7ff88bc3f4 | ||
|
|
8909b99ece | ||
|
|
b559fb575c | ||
|
|
0109aea9ea | ||
|
|
f916998f10 | ||
|
|
ce2a753d2f | ||
|
|
e3bbc955bc | ||
|
|
342fcbd17d | ||
|
|
7a91e11742 | ||
|
|
e3cd65cb79 | ||
|
|
1ac4f82d7a | ||
|
|
544ee8de83 | ||
|
|
731f9448c3 | ||
|
|
198242e5e4 | ||
|
|
aacd160626 | ||
|
|
8343e0cdc6 | ||
|
|
2128e8e81f | ||
|
|
73764899c2 | ||
|
|
6d073a99b5 | ||
|
|
60bfaff97e | ||
|
|
51269bb714 | ||
|
|
c1e6646bf2 | ||
|
|
b29a504506 | ||
|
|
2647ba0f14 | ||
|
|
b2a36e9c16 | ||
|
|
2367414be5 | ||
|
|
1d0b0d1547 | ||
|
|
fbb487384f | ||
|
|
ac13c59b7d | ||
|
|
d12b50075b | ||
|
|
dd1d1f27e6 | ||
|
|
19465370d1 | ||
|
|
5617b883b9 | ||
|
|
3922f56d68 | ||
|
|
017b303e79 | ||
|
|
c7351c846d | ||
|
|
78d52c0eeb | ||
|
|
4ebbd4767f | ||
|
|
5a6a3b3e4f | ||
|
|
8cae9772b6 | ||
|
|
13c259027b | ||
|
|
42825b223b | ||
|
|
4db0b9c530 | ||
|
|
2b97a66db9 | ||
|
|
280cd492fe | ||
|
|
b0984673d8 | ||
|
|
c6a354bca5 | ||
|
|
c4d0b6c000 | ||
|
|
9d83e09aa6 | ||
|
|
3bdc43d3ad | ||
|
|
fa434d7174 | ||
|
|
ed657ad802 | ||
|
|
b49ec43ddc | ||
|
|
d00c787544 | ||
|
|
5e7c21bc86 | ||
|
|
4f4d977807 | ||
|
|
f6dfe58695 | ||
|
|
b12aa502a2 | ||
|
|
20780eab24 | ||
|
|
259b3054e1 | ||
|
|
d777adecf3 | ||
|
|
f685edebfb | ||
|
|
c0cb3e72be | ||
|
|
a27d63bfab | ||
|
|
0f7658bb5b | ||
|
|
313430c1c6 | ||
|
|
63cf3595cd | ||
|
|
050df307a1 | ||
|
|
7a5176497a | ||
|
|
f4005501bc | ||
|
|
f175a10033 | ||
|
|
c651a9d320 | ||
|
|
22bafeb0b2 | ||
|
|
f56d3c9862 | ||
|
|
48f44cac3d | ||
|
|
8410e3d0e8 | ||
|
|
dce37dab18 | ||
|
|
a7a0235c79 | ||
|
|
70f1793a4c | ||
|
|
19bea60d25 | ||
|
|
f70e6d0534 | ||
|
|
223fe253c9 | ||
|
|
62be091197 | ||
|
|
cf288dd940 | ||
|
|
9f57d8b3bb | ||
|
|
5d4d15d596 | ||
|
|
95ddc28518 | ||
|
|
9cc4a965c4 | ||
|
|
9b767186a2 | ||
|
|
823007888f | ||
|
|
881c2a2e52 | ||
|
|
475b27e5d4 | ||
|
|
cac93574ce | ||
|
|
085b0e28e5 | ||
|
|
835689e5df | ||
|
|
55e1818ccd | ||
|
|
44ea8133fc | ||
|
|
756597a6b4 | ||
|
|
02f9ad9a34 | ||
|
|
4038cdbe41 | ||
|
|
51b60381c5 | ||
|
|
2593f73f29 | ||
|
|
5ab561b0e8 | ||
|
|
3f3f154d2d | ||
|
|
56febbb655 | ||
|
|
4d68733f3c | ||
|
|
d22f046bf9 | ||
|
|
430f63e27d | ||
|
|
ce29b87770 | ||
|
|
ad424d690a | ||
|
|
9e47234e92 | ||
|
|
5ba0496c63 | ||
|
|
cd224d86f4 | ||
|
|
dd4bcb30eb | ||
|
|
0836936011 | ||
|
|
aef29ff65d | ||
|
|
3392c226ce | ||
|
|
bfd14e4c50 | ||
|
|
72bf5f7e32 | ||
|
|
78df3a5c6b | ||
|
|
133c9df448 | ||
|
|
a6d354fb2a | ||
|
|
00f79c10d2 | ||
|
|
95a8c61f1b | ||
|
|
7e09c9ce63 | ||
|
|
31627363f1 | ||
|
|
9cd6f43a62 | ||
|
|
7a3b197215 | ||
|
|
ee2d29a65c | ||
|
|
83ef49c258 | ||
|
|
84b6fb4d50 | ||
|
|
b98380c1b0 | ||
|
|
bc629f5321 | ||
|
|
a953ba9d37 | ||
|
|
7fa240f7ba | ||
|
|
0e9211cd42 | ||
|
|
c41e034fa1 | ||
|
|
7977dd4bf2 | ||
|
|
cd948d4a14 | ||
|
|
a2c696b551 | ||
|
|
d6189ae3ea | ||
|
|
e6eece6983 | ||
|
|
1a78265ede | ||
|
|
2e0e5a36f6 | ||
|
|
ece0fc27eb | ||
|
|
82f2d9e9e6 | ||
|
|
391367a531 | ||
|
|
e71a3da525 | ||
|
|
b96511bfc5 | ||
|
|
84bb80d910 | ||
|
|
9edf644d77 | ||
|
|
b5d0382e89 | ||
|
|
b705104403 | ||
|
|
f148b51a48 | ||
|
|
c979870b3a | ||
|
|
cd59e081d9 | ||
|
|
0bfb12fd17 | ||
|
|
c6d0986da2 | ||
|
|
9a9422c7da | ||
|
|
da41b6420d | ||
|
|
3f710928af | ||
|
|
2fdf01fbb3 | ||
|
|
de00cb2bfd | ||
|
|
d8f9669280 | ||
|
|
19b2e9b5d5 | ||
|
|
bb6bc52c95 | ||
|
|
ba6bbb2e4a | ||
|
|
705b074a08 | ||
|
|
d3c1150854 | ||
|
|
a81d62ffe3 | ||
|
|
bb1372cd70 | ||
|
|
8d53d82981 | ||
|
|
ba2cfc2a00 | ||
|
|
b13ab327f2 | ||
|
|
e7cb8db14f | ||
|
|
e7795d0e5a | ||
|
|
3ff9ddde24 | ||
|
|
ff191d89bd | ||
|
|
4039be8ee2 | ||
|
|
898b79dc84 | ||
|
|
30d20c8f33 | ||
|
|
0687a8add6 | ||
|
|
791b736b0e | ||
|
|
fcda9c09bd | ||
|
|
ad5a6f9c53 | ||
|
|
f856671b6d | ||
|
|
e1317322e1 | ||
|
|
92fd955a8d | ||
|
|
0609012903 | ||
|
|
dffa50cd9c | ||
|
|
b541dce0cc | ||
|
|
52ecece126 | ||
|
|
440856a997 | ||
|
|
1eeb614ea2 | ||
|
|
afd936b20b | ||
|
|
6772205213 | ||
|
|
4b5e2b690d | ||
|
|
ee6c9ac067 | ||
|
|
1680e6b19c | ||
|
|
3eef0ecfa8 | ||
|
|
999de9f2df | ||
|
|
e616583c3f | ||
|
|
025f9dfd21 | ||
|
|
d8c02270ee | ||
|
|
08c4451e68 | ||
|
|
2ab189ddbe | ||
|
|
fa94b56ba3 | ||
|
|
385e7a0729 | ||
|
|
819699e8a7 | ||
|
|
4404e3f4bb | ||
|
|
d35cea8eff | ||
|
|
8a69f80aa0 | ||
|
|
c21d9ba92a | ||
|
|
e06242f2e0 | ||
|
|
c9e3394eb3 | ||
|
|
72d2ceb967 | ||
|
|
358ddc5eba | ||
|
|
09cf27186c | ||
|
|
9ac1343e34 | ||
|
|
078afd4591 | ||
|
|
4741409de1 | ||
|
|
6cbe976990 | ||
|
|
857bec29e1 | ||
|
|
7b6c6fd92c | ||
|
|
28846561ab | ||
|
|
817a95b419 | ||
|
|
33c025a785 | ||
|
|
c0cbc2f787 | ||
|
|
e8b0a380e9 | ||
|
|
df3b9674a3 | ||
|
|
db50deb9f7 | ||
|
|
76679a9c05 | ||
|
|
6785cb04e3 | ||
|
|
99c8331576 | ||
|
|
077a215d49 | ||
|
|
3c710b53ba | ||
|
|
4886e9cd80 | ||
|
|
4dc10ae437 | ||
|
|
16debc8fdb | ||
|
|
ee8347a39f | ||
|
|
6689761db3 | ||
|
|
7aa8166cf2 | ||
|
|
c107f3a43f | ||
|
|
b041952437 | ||
|
|
ae80d7fd8f | ||
|
|
d57e9c031c | ||
|
|
924d68afbc | ||
|
|
840eca0a29 | ||
|
|
0749330868 | ||
|
|
2ddd2a2485 | ||
|
|
0e7fa4aa93 | ||
|
|
1ee557bdc4 | ||
|
|
fa4d4b9d71 | ||
|
|
bf3cca0718 | ||
|
|
a86100c00d | ||
|
|
044f036ea5 | ||
|
|
79947ec998 | ||
|
|
17fe880bdc | ||
|
|
e93e4e1e2a | ||
|
|
425327a0f2 | ||
|
|
1212280ab8 | ||
|
|
c6665ebfb4 | ||
|
|
96e2baeb75 | ||
|
|
b9be341dfc | ||
|
|
b2391b4de4 | ||
|
|
ecc109a7e2 | ||
|
|
67e6565fc2 | ||
|
|
994efd38f9 | ||
|
|
aac0f31b93 | ||
|
|
ef0e472d5d | ||
|
|
1784836639 | ||
|
|
68fc4e25dc | ||
|
|
cdaff0a391 | ||
|
|
184149561a | ||
|
|
e83475be17 | ||
|
|
fa55066699 | ||
|
|
f25060e891 | ||
|
|
9318e68840 | ||
|
|
abd6698a66 | ||
|
|
5f8867bd30 | ||
|
|
5ca90bfac0 | ||
|
|
7cc35ffd41 | ||
|
|
57f10c1d7c | ||
|
|
76620e274b | ||
|
|
240302fabe | ||
|
|
01deb3f8a8 | ||
|
|
e6b9a27242 | ||
|
|
8fdb569052 | ||
|
|
e79bd1ccaf | ||
|
|
066bc3fc83 | ||
|
|
a533d8107e | ||
|
|
3109b620fd | ||
|
|
878f554dcd | ||
|
|
46e2d36064 | ||
|
|
d94121bbb0 | ||
|
|
ef4fbba797 | ||
|
|
97ea2541bb | ||
|
|
f1ec653b91 | ||
|
|
b1ab08c09d | ||
|
|
6b479a6617 | ||
|
|
7a10d7eac8 | ||
|
|
0e51ddda76 | ||
|
|
b5a462fb54 | ||
|
|
09e0bea55d | ||
|
|
1260e07ba1 | ||
|
|
e70780f30a | ||
|
|
ef481368d6 | ||
|
|
3a598a83e1 | ||
|
|
9fda5aab18 | ||
|
|
cf2d0cfb0b | ||
|
|
585edd313f | ||
|
|
c4ce9a4e38 | ||
|
|
791bfc6be9 | ||
|
|
69812d97c0 | ||
|
|
2de0483142 | ||
|
|
6ecbd14915 | ||
|
|
3c9b8d988b | ||
|
|
ab598f0820 | ||
|
|
e37c8566c6 | ||
|
|
2bc08a1851 | ||
|
|
6a60749939 | ||
|
|
dcf7122082 | ||
|
|
06bdf189e4 | ||
|
|
964026901f | ||
|
|
9b22c664bb | ||
|
|
98bbe57471 | ||
|
|
5baa630ff0 | ||
|
|
654e4c28b5 | ||
|
|
b861348667 | ||
|
|
a4a2425bcc | ||
|
|
edba4df430 | ||
|
|
f992721fda | ||
|
|
8e29b54919 | ||
|
|
43f54ff1d2 | ||
|
|
cd01d04a96 | ||
|
|
6b068a225d | ||
|
|
fa6a52ab93 | ||
|
|
4c1ac39c7e | ||
|
|
d76c7d061c | ||
|
|
7134523a08 | ||
|
|
1493dcf83b | ||
|
|
e4b1898b00 | ||
|
|
7130da2635 | ||
|
|
7599de0e01 | ||
|
|
86467c2f6c | ||
|
|
58d0d5a088 |
No files matched your search
@@ -0,0 +1,34 @@
|
||||
# Global fallback: every file in the repository requires maintainer review.
|
||||
* @MacosPorters/maintainers
|
||||
|
||||
# Frozen cross-track ABI contracts (fast-tracked [ABI] PRs)
|
||||
/abi/ @MacosPorters/maintainers
|
||||
/Cargo.toml @MacosPorters/maintainers
|
||||
/shims/CMakeLists.txt @MacosPorters/maintainers
|
||||
|
||||
# Track A: Host launcher, CrossOver/Rosetta runner, runtime VEH & Win32 forwarders
|
||||
/launcher/ @MacosPorters/maintainers
|
||||
/shims/runtime_veh/ @MacosPorters/maintainers
|
||||
/shims/win32_bridge/ @MacosPorters/maintainers
|
||||
/scripts/build-shims.sh @MacosPorters/maintainers
|
||||
|
||||
# Track B: Memory (xmem) & Storage (XCRDAPI / DirectStorage)
|
||||
/shims/xmem/ @MacosPorters/maintainers
|
||||
/shims/xcrdapi/ @MacosPorters/maintainers
|
||||
|
||||
# Track C: Graphics (d3d12_xs, xg_xs, FidelityFX/BVH hooks)
|
||||
/shims/d3d12_xs/ @MacosPorters/maintainers
|
||||
/shims/xg_xs/ @MacosPorters/maintainers
|
||||
/shims/ffx_bvh_hooks/ @MacosPorters/maintainers
|
||||
|
||||
# Track D: Shader pipeline (DXBC/DXIL/ACCC/FSPX & RDNA2 transpiler)
|
||||
/shader-transpiler/ @MacosPorters/maintainers
|
||||
|
||||
# Track E: Platform runtime (xgameruntime), Input (GameInput) & Audio/DSP
|
||||
/shims/xgameruntime/ @MacosPorters/maintainers
|
||||
/shims/gameinput/ @MacosPorters/maintainers
|
||||
/shims/audio/ @MacosPorters/maintainers
|
||||
|
||||
# Track F: Conformance tests & documentation
|
||||
/tests/conformance/ @MacosPorters/maintainers
|
||||
/docs/ @MacosPorters/maintainers
|
||||
@@ -1,67 +0,0 @@
|
||||
name: Agent task
|
||||
description: A self-contained work item that a contributor or coding agent can claim with /claim.
|
||||
title: "task: "
|
||||
labels: [agent:ready]
|
||||
body:
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
|
||||
options:
|
||||
- cpu
|
||||
- gpu
|
||||
- runtime
|
||||
- shared
|
||||
- qa
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: priority
|
||||
attributes:
|
||||
label: Priority
|
||||
options:
|
||||
- critical
|
||||
- high
|
||||
- medium
|
||||
- low
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: interface
|
||||
attributes:
|
||||
label: Interface
|
||||
description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise.
|
||||
- type: textarea
|
||||
id: goal
|
||||
attributes:
|
||||
label: Goal
|
||||
description: What must be true when the task is finished, in one or two sentences.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: files
|
||||
attributes:
|
||||
label: Files
|
||||
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
|
||||
render: text
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance command
|
||||
description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance.
|
||||
render: sh
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: depends
|
||||
attributes:
|
||||
label: Depends on
|
||||
description: Issue numbers that must be closed first, for example "#12, #15". Leave empty when none.
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Context
|
||||
description: Specification sections, interface notes and known limits. Public sources only.
|
||||
@@ -1,42 +1,57 @@
|
||||
name: Bug report
|
||||
description: Report a reproducible defect in Xenora or XenoMetal.
|
||||
description: A reproducible defect.
|
||||
title: "bug: "
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use synthetic or authorized inputs only. For vulnerabilities, follow SECURITY.md. Remove personal paths, credentials and private data from logs.
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. For vulnerabilities follow SECURITY.md.'
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: What went wrong? Identify the affected subsystem and expected behavior.
|
||||
description: 'What went wrong and what you expected.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Reproduction steps
|
||||
description: Include exact commands and a minimal, legally distributable input if applicable.
|
||||
description: 'Exact commands and a minimal, legally distributable input.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: Commit, macOS, Apple GPU, RAM, Rust, Xcode and relevant tool versions. Include sanitized doctor output if available.
|
||||
description: 'Commit, macOS, chip, memory, CrossOver and Rosetta 2 versions, graphics backend. Remove personal paths and credentials.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: output
|
||||
id: scope
|
||||
attributes:
|
||||
label: Actual output and diagnostics
|
||||
description: Include expected versus actual results, validation-layer messages and relevant logs.
|
||||
- type: checkboxes
|
||||
id: confirmation
|
||||
label: Scope and dependencies
|
||||
description: 'Affected area; related issues.'
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Confirmation
|
||||
options:
|
||||
- label: I searched for existing reports and have not included sensitive or unauthorized material.
|
||||
required: true
|
||||
label: Acceptance criteria
|
||||
description: 'When is this fixed?'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How to confirm the fix independently.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: 'Only if third-party code or a dependency is involved.'
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,50 @@
|
||||
name: Documentation
|
||||
description: Fix, add or restructure documentation.
|
||||
title: "docs: "
|
||||
labels: [documentation]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is unclear, wrong or missing.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Pages and sources involved.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'Files to change; update docs/README.md if pages are added or moved.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'None if none.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Claims are scoped to their evidence; links work.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'scripts/audit/docs_hygiene.py and claims audit pass.'
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Feature proposal
|
||||
description: Propose a compiler, graphics, tooling or other project enhancement.
|
||||
title: "feat: "
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem or gap
|
||||
description: Which limitation does this feature address?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed approach
|
||||
description: Explain the intended behavior and affected components. Link relevant public specifications when available.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: criteria
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: What observable results and tests would demonstrate completion?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives and trade-offs
|
||||
description: Include limitations, dependency costs or impacts on native ARM64 and Metal if relevant.
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Hardware verification report
|
||||
description: Submit real hardware test results for Xenora.
|
||||
title: "hardware: "
|
||||
labels: [needs-verification]
|
||||
body:
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Test environment
|
||||
description: Commit, Apple chip/GPU, RAM, macOS, Xcode/Metal version, Rust version, validation settings. Do not include serial numbers or registry IDs.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: commands
|
||||
attributes:
|
||||
label: Commands and inputs
|
||||
description: Include exact commands and synthetic or authorized fixture identifiers.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: results
|
||||
attributes:
|
||||
label: Results
|
||||
description: Report actual output, pass/fail/skip counts, and limitations. Compilation alone does not prove execution.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: performance
|
||||
attributes:
|
||||
label: Performance data (optional)
|
||||
description: Include repetitions, warm-up, timing method, validation state and variability if reporting measurements.
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Hybrid engineering task
|
||||
description: Integration, configuration, diagnostics or tooling around CrossOver.
|
||||
title: "task: "
|
||||
labels: [track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: "Blocking issues or decisions; write 'none' if none."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Observable, checkable results.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Performance investigation
|
||||
description: Measure or improve performance with evidence.
|
||||
title: "perf: "
|
||||
labels: [performance,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue. Do not promise gains before measuring.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem and metric
|
||||
description: 'Which metric (average FPS, 1% low, frame-time percentiles, CPU or GPU use, memory, startup, shader compile latency) and why.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Workload, hardware (reference: M4, 24 GB), software versions, settings.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'Measurement only, or change as well.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'Measurement protocol (#353) and baseline (#355).'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Measured before-and-after under equivalent conditions, with variance.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'Correctness and rendering equivalence verified before the result counts.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,42 +1,57 @@
|
||||
name: Technical research
|
||||
description: Record an ISA, Metal or publicly documented graphics research finding.
|
||||
name: Upstream research or dependency evaluation
|
||||
description: Assess a project, component or license from public sources.
|
||||
title: "research: "
|
||||
labels: [research]
|
||||
labels: [research,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: Use only public, authorized sources. Do not link to leaked SDKs, private documentation or unauthorized game content.
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: question
|
||||
id: problem
|
||||
attributes:
|
||||
label: Research question or finding
|
||||
label: Question
|
||||
description: 'The decision this research informs.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: sources
|
||||
id: context
|
||||
attributes:
|
||||
label: Sources and applicability
|
||||
description: URLs, specification sections or revision, exact architecture and license/provenance if relevant.
|
||||
label: Technical context
|
||||
description: 'What is already known; link docs/research/upstream-registry.md entries.'
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: evidence
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Evidence class (highest applicable)
|
||||
options:
|
||||
- A - Measured on named hardware
|
||||
- B - Normative source for exact target
|
||||
- C - Normative source for related target
|
||||
- D - Non-normative official material
|
||||
- E - Independent software behavior
|
||||
- F - Uncorroborated community claim
|
||||
- U - Unknown or assumption
|
||||
label: Scope
|
||||
description: 'Which versions or components; desk research or execution.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: 'Other issues or decisions; execution may need a maintainer-approved environment.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Each claim cites vendor or upstream documentation, or a recorded observation of a stated version; unknowns stay marked unknown.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation, limitations and proposed next steps
|
||||
description: Distinguish Apple or desktop RDNA observations from Xbox behavior.
|
||||
label: Validation requirements
|
||||
description: 'Independent re-derivation and evidence class (A to U).'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,90 @@
|
||||
name: Parallel track handoff issue
|
||||
description: Self-contained engineering task scoped to one BetterXen track (A-F) for conflict-free parallel work.
|
||||
title: "[M1-X0] "
|
||||
labels: ["track: hybrid"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this template to hand off work to contributors across Tracks A-F.
|
||||
Keep file scopes disjoint so 5-8+ contributors can work concurrently without merge conflicts.
|
||||
Never include proprietary game files, names, hashes, or leaked material in issues or PRs.
|
||||
- type: textarea
|
||||
id: zen
|
||||
attributes:
|
||||
label: Zen
|
||||
description: 1–2 plain-English sentences explaining the core purpose of this issue and why it matters.
|
||||
placeholder: Enable guest allocations to stay within a 16 GiB Mac's unified memory budget so bring-up never OOMs.
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: track
|
||||
attributes:
|
||||
label: Track
|
||||
options:
|
||||
- "Track A — Host Launcher, VEH & Win32 Bridge"
|
||||
- "Track B — Memory (xmem) & Storage (XCRDAPI)"
|
||||
- "Track C — Graphics (d3d12_xs, xg_xs, DXR/FFX)"
|
||||
- "Track D — Shader Pipeline (DXBC/DXIL/ACCC)"
|
||||
- "Track E — Platform (xgameruntime), Input & Audio"
|
||||
- "Track F — Conformance, QA & Performance"
|
||||
- "ABI Freeze — Shared Contract (abi/)"
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: milestone
|
||||
attributes:
|
||||
label: Milestone
|
||||
options:
|
||||
- "M0 — Repo, ABI & Cross-Build"
|
||||
- "M1 — Boot to D3D12XboxCreateDevice"
|
||||
- "M2 — First Frame & Shader Format Gate"
|
||||
- "M3 — Full Shaders, Streaming & Texture Correctness"
|
||||
- "M4 — 3D Rendering, DXR/BVH & Input"
|
||||
- "M5 — Audio, Saves & Stability"
|
||||
- "M6 — Shader Cache, 16 GB Optimization & Polish"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: file_scope
|
||||
attributes:
|
||||
label: Exclusive file scope
|
||||
description: Exact directories/files this issue may modify. Do not overlap with other active issues.
|
||||
placeholder: |
|
||||
- `shims/xmem/**`
|
||||
- `tests/conformance/test_xmem/**`
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: api_contract
|
||||
attributes:
|
||||
label: Exact API / export / COM contract
|
||||
description: Exported symbols (referencing `abi/defs/*.def`), COM interface IIDs/vtable slots, or CLI flags to implement.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Hard dependencies
|
||||
description: Blocking `[ABI]` or prerequisite issues (`none` if immediately claimable).
|
||||
value: "none"
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: synthetic_test
|
||||
attributes:
|
||||
label: Required synthetic conformance test
|
||||
description: Clean-room synthetic test in `tests/conformance/` or `cargo test` proving correctness.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: exit_criteria
|
||||
attributes:
|
||||
label: Definition of done
|
||||
description: Exact commands that must succeed locally and in CI.
|
||||
placeholder: |
|
||||
- `cargo fmt --all -- --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace`
|
||||
- `scripts/build-shims.sh` (all DLL export checks pass)
|
||||
- Synthetic conformance binary passes under CrossOver/Wine
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,57 @@
|
||||
name: Testing and validation
|
||||
description: Add or run a validation for a workload or behaviour.
|
||||
title: "validate: "
|
||||
labels: [needs-verification,track: hybrid]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: 'Active work is the CrossOver-based hybrid architecture (docs/roadmap.md). Use independently authored or authorized workloads only; never link leaked builds, confidential SDKs or private documentation. Claim by replying on the issue.'
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: 'What is missing or wrong, and why it matters for the hybrid architecture.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Technical context
|
||||
description: 'Versions (macOS, chip, CrossOver, Rosetta 2, graphics backend), related issues, upstream references.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Scope
|
||||
description: 'What is in and out. Avoid duplicating what CrossOver already provides.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: dependencies
|
||||
attributes:
|
||||
label: Dependencies
|
||||
description: "Blocking issues or decisions; write 'none' if none."
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance criteria
|
||||
description: 'Observable, checkable results.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation requirements
|
||||
description: 'How an independent contributor verifies it; commands, workloads, evidence class.'
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: licensing
|
||||
attributes:
|
||||
label: Licensing and provenance
|
||||
description: "Licenses of any component involved, source and version, and whether anything would be bundled or copied. Write 'not applicable' if none."
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,40 +0,0 @@
|
||||
## Summary
|
||||
|
||||
<!-- What changes, and why? -->
|
||||
|
||||
Closes #<!-- the issue you claimed -->
|
||||
|
||||
## Implementation and evidence
|
||||
|
||||
<!-- Describe affected subsystems, architecture assumptions, specification sections and upstream provenance where applicable. -->
|
||||
|
||||
## Verification
|
||||
|
||||
<!-- List actual commands and outcomes. Include hardware, validation-layer state and pass/fail/skip counts for GPU tests. Mark unrun checks explicitly. -->
|
||||
|
||||
| Check | Result / evidence |
|
||||
| --- | --- |
|
||||
| Formatting and lint | |
|
||||
| Unit / integration tests | |
|
||||
| GPU / differential tests | |
|
||||
| Fuzzing / mutation / benchmarks, if relevant | |
|
||||
|
||||
## Compatibility and limitations
|
||||
|
||||
<!-- Note unsupported behavior, regressions, interface changes, performance effects and remaining uncertainty. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
|
||||
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
|
||||
- [ ] The change preserves native ARM64 and Metal-first requirements.
|
||||
- [ ] I added relevant tests or explained why they are not applicable.
|
||||
- [ ] I did not report skipped or unrun tests as passing.
|
||||
- [ ] I updated applicable documentation, claims and status records.
|
||||
- [ ] Third-party code and fixtures have verified licenses and provenance, or none were added.
|
||||
- [ ] No restricted materials, credentials or private data are included.
|
||||
- [ ] My commits are signed off under the DCO.
|
||||
|
||||
## AI assistance
|
||||
|
||||
<!-- Describe material assistance and the checks you personally performed, or state none. -->
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"lease_hours": 24,
|
||||
"upstream": "ranveersoni98/Xenora",
|
||||
"maintainers": ["ranveersoni98"],
|
||||
"contributors": {
|
||||
"ranveersoni98": ["cpu", "shared", "qa"],
|
||||
"elforeign": ["gpu", "shared", "qa"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
## Related issue
|
||||
|
||||
Closes #
|
||||
|
||||
## Summary
|
||||
|
||||
## Technical changes
|
||||
|
||||
## Tests performed
|
||||
|
||||
Commands, versions, pass/fail/skip counts and hardware. A skipped test is not a pass.
|
||||
|
||||
## Performance impact
|
||||
|
||||
Measured before and after under equivalent conditions, or "none expected" with reason.
|
||||
|
||||
## Compatibility impact
|
||||
|
||||
Workloads, macOS or CrossOver versions and hardware affected. Do not claim support that was not tested.
|
||||
|
||||
## Known limitations
|
||||
|
||||
## Third-party code attribution
|
||||
|
||||
Source repository, exact commit, license, modifications. "None" if none.
|
||||
|
||||
## Dependency and licensing considerations
|
||||
|
||||
New or changed dependencies, license compatibility with GPL-3.0-or-later, redistribution limits (proprietary components are never bundled). DCO: commits are signed off.
|
||||
@@ -1,72 +0,0 @@
|
||||
name: Agent task claims
|
||||
|
||||
# Applies queue commands (/claim, /release, /reassign, /progress, /blocked,
|
||||
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
|
||||
# text is only parsed as data by scripts/agent_queue; it is never executed and
|
||||
# never interpolated into a shell. Not yet run on GitHub.
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
schedule:
|
||||
- cron: "17 * * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
command:
|
||||
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
# One global group: claims are decided one at a time so file-overlap checks cannot race.
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Decide and apply
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
|
||||
audit:
|
||||
if: github.event_name != 'issue_comment'
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Lapse stale claims, flag invalid tasks, write summary
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
{
|
||||
echo '## Agent queue summary'
|
||||
echo '```json'
|
||||
python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -1,78 +0,0 @@
|
||||
name: Agent PR checks
|
||||
|
||||
# Checks pull requests against the task queue: linked claimed task, file
|
||||
# ownership, overlap with other open pull requests, and independent
|
||||
# verification. Runs on the base branch only: pull request code is never checked
|
||||
# out or executed; changed files come from the API. Not yet run on GitHub.
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
check:
|
||||
if: github.event_name == 'pull_request_target'
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
issues: read
|
||||
pull-requests: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Check pull request
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
|
||||
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
|
||||
status=0
|
||||
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
|
||||
{
|
||||
echo '## Agent PR check'
|
||||
echo '```json'
|
||||
cat "$RUNNER_TEMP/result.json"
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
exit "$status"
|
||||
|
||||
verify:
|
||||
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
|
||||
runs-on: ubuntu-24.04-arm
|
||||
# issues: write posts the reply; actions: write re-runs the check after a recorded verification.
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
actions: write
|
||||
concurrency:
|
||||
group: agent-verify-${{ github.event.issue.number }}
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Record verification and re-run the check
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
PYTHONPATH: scripts
|
||||
run: |
|
||||
set -eu
|
||||
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
|
||||
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
|
||||
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
|
||||
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
|
||||
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
|
||||
sha=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["pr"]["head_sha"])' "$RUNNER_TEMP/state.json")
|
||||
run=$(gh run list --workflow agent-pr-checks.yml --commit "$sha" --event pull_request_target --limit 1 --json databaseId -q '.[0].databaseId // empty')
|
||||
if [ -n "$run" ]; then gh run rerun "$run" || true; fi
|
||||
@@ -1,67 +0,0 @@
|
||||
name: Native Rust checks
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: native-rust-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
native-rust:
|
||||
name: ARM64 CPU and build checks
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
CARGO_BUILD_JOBS: 3
|
||||
PYTHONDONTWRITEBYTECODE: 1
|
||||
CARGO_BUILD_TARGET: aarch64-apple-darwin
|
||||
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Verify runner architecture
|
||||
run: |
|
||||
uname -m
|
||||
test "$(uname -m)" = arm64
|
||||
test "$(sysctl -n sysctl.proc_translated)" = 0
|
||||
- name: Install native Rust
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
- name: Test agent task queue
|
||||
run: |
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
|
||||
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
|
||||
- name: Check formatting and lint
|
||||
run: |
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo fmt --manifest-path experiments/x1/Cargo.toml -- --check
|
||||
cargo clippy --locked --manifest-path experiments/x1/Cargo.toml --all-targets --all-features -- -D warnings
|
||||
- name: Run CPU tests and dependency checks
|
||||
run: |
|
||||
cargo test --locked --workspace
|
||||
cargo test --locked --manifest-path experiments/x1/Cargo.toml
|
||||
scripts/audit/dependencies.sh
|
||||
scripts/audit/claims.sh
|
||||
- name: Inspect native CLI
|
||||
run: |
|
||||
cargo build --locked -p xenora
|
||||
binary=target/aarch64-apple-darwin/debug/xenora
|
||||
file "$binary"
|
||||
test "$(lipo -archs "$binary")" = arm64
|
||||
otool -L "$binary"
|
||||
@@ -0,0 +1,53 @@
|
||||
name: Hybrid build and shim checks
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: hybrid-ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
arm64-host-and-shims:
|
||||
name: ARM64 host Rust + x86-64 PE32+ shims
|
||||
runs-on: macos-26
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
CARGO_BUILD_JOBS: 3
|
||||
CARGO_BUILD_TARGET: aarch64-apple-darwin
|
||||
RUSTUP_TOOLCHAIN: 1.100.0-aarch64-apple-darwin
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Verify Apple Silicon runner
|
||||
run: |
|
||||
test "$(uname -m)" = arm64
|
||||
test "$(sysctl -n sysctl.proc_translated)" = 0
|
||||
- name: Install Rust toolchain
|
||||
run: |
|
||||
rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy
|
||||
rustc -vV
|
||||
- name: Check ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
run: |
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo build --locked -p bx-cli
|
||||
binary=target/aarch64-apple-darwin/debug/bx-cli
|
||||
file "$binary"
|
||||
test "$(lipo -archs "$binary")" = arm64
|
||||
- name: Install mingw-w64 and CMake
|
||||
env:
|
||||
HOMEBREW_NO_AUTO_UPDATE: 1
|
||||
HOMEBREW_NO_INSTALL_CLEANUP: 1
|
||||
run: |
|
||||
brew install mingw-w64 cmake
|
||||
x86_64-w64-mingw32-g++ --version | head -n 1
|
||||
- name: Cross-compile all x86-64 PE32+ shim DLLs and verify exports
|
||||
run: scripts/build-shims.sh
|
||||
@@ -0,0 +1,43 @@
|
||||
name: Repository hygiene
|
||||
|
||||
# Fast checks on tracked files that need no Rust toolchain and no network:
|
||||
# merge-conflict markers, broken relative Markdown links and invalid workflow
|
||||
# YAML (scripts/audit/docs_hygiene.py). A second, advisory step warns when
|
||||
# source or script changes arrive without a CHANGELOG.md update; it never fails.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: hygiene-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
hygiene:
|
||||
name: Repository hygiene
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
- name: Install PyYAML
|
||||
run: python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --user --break-system-packages pyyaml
|
||||
- name: Check documentation and workflow files
|
||||
run: python3 scripts/audit/docs_hygiene.py --require-yaml
|
||||
- name: Remind about the changelog (advisory)
|
||||
if: github.event_name == 'pull_request'
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
run: |
|
||||
changed="$(git diff --name-only "$BASE_SHA"...HEAD || true)"
|
||||
if printf '%s\n' "$changed" | grep -Eq '^(abi|launcher|shims|shader-transpiler|scripts|tests)/' \
|
||||
&& ! printf '%s\n' "$changed" | grep -qx 'CHANGELOG.md'; then
|
||||
echo "::warning title=Changelog::Source or script files changed without a CHANGELOG.md update."
|
||||
fi
|
||||
+6
-10
@@ -1,10 +1,9 @@
|
||||
# Rust and local builds
|
||||
/target/
|
||||
/experiments/x1/target/
|
||||
/build/
|
||||
/build-shims/
|
||||
/cmake-build-*/
|
||||
/fuzz/target/
|
||||
/fuzz/artifacts/
|
||||
/local-runs/
|
||||
|
||||
# macOS / Xcode local state
|
||||
.DS_Store
|
||||
@@ -20,8 +19,6 @@
|
||||
*.profraw
|
||||
*.profdata
|
||||
|
||||
# Keep Cargo.lock, source fixtures, reviewed golden files and documentation tracked.
|
||||
|
||||
# Local AI agent tooling
|
||||
.agents/
|
||||
.claude/
|
||||
@@ -29,11 +26,10 @@
|
||||
.cursor/
|
||||
.gemini/
|
||||
|
||||
# Local gate evidence and intermediate fixture objects
|
||||
# Local gate evidence and ignored probes
|
||||
/artifacts/
|
||||
/tests/validation/target/
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
/diagnostics/probe/
|
||||
/diagnostics/title-candidate-*/
|
||||
/diagnostics/title-check/
|
||||
@@ -1,104 +1,143 @@
|
||||
# Xenora engineering rules
|
||||
# BetterXen Engineering & Agent Rules
|
||||
|
||||
### Native Apple Silicon
|
||||
These rules apply to every human contributor and coding agent (`CLAUDE.md` is a symlink to this file). Strategic decisions are recorded in `docs/adr/0005-crossover-hybrid-direction.md` and `docs/adr/0006-retire-in-tree-native-workspace.md`; the single authoritative roadmap is `docs/roadmap.md`.
|
||||
|
||||
Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dependencies, Wine, CrossOver, Windows compatibility layers, OpenGL fallback rendering, or unnecessary graphics abstraction layers.
|
||||
---
|
||||
|
||||
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
|
||||
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
|
||||
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
|
||||
- The guest architecture being decoded may be x86-64, but Xenora itself runs natively on ARM64.
|
||||
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
|
||||
- Use aarch64-apple-darwin as the Rust target.
|
||||
## 0. First-Time Contributor Onboarding
|
||||
|
||||
### Honesty and evidence
|
||||
If the user asks to contribute, get started, or pick a task (even with a short prompt like *"help me contribute"*), walk them through this exact end-to-end flow:
|
||||
|
||||
- Never report a test as passed unless it ran and passed. Never count a skipped test as GPU verification.
|
||||
- Never invent benchmark results, hardware compatibility, API names, instruction encodings, hardware capabilities or implementation status.
|
||||
- Never claim a clean build unless the commands actually succeeded.
|
||||
- Never present planned features as working. State clearly that game execution is not supported unless demonstrated.
|
||||
- Never replace GPU tests with mocks and then claim GPU support.
|
||||
- Unknown information is classified as unknown and becomes a documented research task.
|
||||
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
|
||||
- Never claim "verified on Xbox hardware". Xenora has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
|
||||
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
|
||||
1. **Preflight host & tools:**
|
||||
- Check `uname -m` (`arm64`), `git`, `gh`, `cargo`, `cmake`, `x86_64-w64-mingw32-g++`, and `python3`.
|
||||
- If `mingw-w64`, `cmake`, or `gh` is missing on macOS, ask permission before running `brew install mingw-w64 cmake gh`.
|
||||
- Run `gh auth status` (if not logged in, pause and ask the user to run `gh auth login`).
|
||||
- Run `cargo build --locked -p bx-cli && target/debug/bx-cli doctor` to report Apple Silicon, Rosetta 2, CrossOver, and toolchain readiness.
|
||||
- Verify whether the user has push access or needs a fork (`gh repo fork MacosPorters/betterxen --remote`), and sync with `origin/main`.
|
||||
2. **Discover & pick an unclaimed issue:**
|
||||
- Query ready issues in the active milestone:
|
||||
```sh
|
||||
gh issue list --repo MacosPorters/betterxen --state open --label "status: ready" --json number,title,labels,assignees
|
||||
```
|
||||
- Inspect comments and open PRs on candidate issues to filter out any issue that already has an active claim (< 7 days old).
|
||||
- Present the unclaimed options in plain English (recommending 1–2 good starting issues matching the user's background) and wait for the user to choose one before coding.
|
||||
3. **Claim & isolate:**
|
||||
- Post `Claiming — branch: track-<a..f>/<issue>-<slug>` on the chosen issue and create that branch (or `git worktree`) off `origin/main`.
|
||||
4. **Implement strictly in scope:**
|
||||
- Read the full issue body (`gh issue view <issue> --repo MacosPorters/betterxen`) and the relevant contracts in `abi/defs/` and `abi/include/`.
|
||||
- Edit **only** files inside the issue's **Exclusive file scope** (plus `CHANGELOG.md`). Add new synthetic C++ conformance tests under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake).
|
||||
5. **Verify locally (including hosts without CrossOver):**
|
||||
- Run every command in Section 8 and fix all warnings/failures before stopping.
|
||||
- **No CrossOver installed?** The contributor can still run all ARM64 Rust checks, `scripts/build-shims.sh` (verifying all 16 PE32+ DLLs and exact exports), and `python3 scripts/audit/docs_hygiene.py`. Report honestly in the PR that live CrossOver execution was not run locally and needs verification on a CrossOver host—never report an unrun check as passed.
|
||||
6. **Review & submit PR:**
|
||||
- Present a concise summary of changes and exact verification outputs, and ask explicit user permission before running `git commit -s` (DCO sign-off, zero AI trailers), pushing, and opening a PR (`Closes #<issue>`).
|
||||
- After opening the PR, watch CI (`gh pr checks --watch`) until both `Hybrid build and shim checks` and `Repository hygiene` pass.
|
||||
|
||||
### Independence of verification
|
||||
---
|
||||
|
||||
- The agent that writes a component does not certify it. The two independent reviewers (section 5) re-derive expectations from primary sources and are not told the implementers' conclusions as ground truth.
|
||||
- The same faulty code must never produce both the expected and the actual values in a test.
|
||||
## 1. Direction & Architecture
|
||||
|
||||
### Legal and clean-room
|
||||
- **Hybrid-first on Apple Silicon:** CrossOver 26.3+ (externally installed), Wine runtime APIs, Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`), and D3DMetal 3.0 (subject to license terms) form the external compatibility foundation. DXMT, DXVK, VKD3D-Proton, MoltenVK, and `utmapp/d3dmetal-native` may be evaluated and used where license-compatible and technically justified.
|
||||
- **BetterXen's in-tree scope:**
|
||||
- `abi/` — Frozen cross-DLL C headers (`abi/include/*.h`) and canonical `.def` export tables (`abi/defs/*.def`).
|
||||
- `launcher/` — Native **ARM64** macOS Rust CLI (`bx-cli`), PE32+ import classifier (`bx-probe`), and JSONL trace aggregator (`bx-telemetry`).
|
||||
- `shims/` — Cross-compiled **x86-64 Windows PE32+** Xbox Game OS shim DLLs (C++20 via `x86_64-w64-mingw32-g++` + CMake, statically linked against GCC/C++/winpthread so Wine bottles need zero extra MinGW runtime DLLs).
|
||||
- `shader-transpiler/` — Rust shader container classifier (`dxbc-accc`) and RDNA 2 (`gfx1030`) transpiler pipeline (expanded on demand per the M2 shader-format gate).
|
||||
- `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.
|
||||
|
||||
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
|
||||
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
|
||||
- Include a plain statement in docs/legal.md: Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
|
||||
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
|
||||
- Keep Xenora's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
|
||||
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
|
||||
- Never place restricted material in the repository or its Git history.
|
||||
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
|
||||
---
|
||||
|
||||
### Quality
|
||||
## 2. Parallel Track Ownership (5–8+ Concurrent Contributors / Agents)
|
||||
|
||||
No AI slop (section 29).
|
||||
Every feature issue belongs to **one track** and defines an **exclusive file scope**. Stay strictly inside your issue's file scope to avoid merge conflicts across concurrent contributors and agents:
|
||||
|
||||
Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
| Track | Exclusive Directories | Responsibility |
|
||||
| --- | --- | --- |
|
||||
| **ABI Gate** | `abi/` | Frozen headers & `.def` files (small `[ABI]` PRs merged first) |
|
||||
| **Track A** | `launcher/`, `shims/runtime_veh/`, `shims/win32_bridge/`, `scripts/build-shims.sh` | ARM64 CLI/runner (with `env_clear()` isolation), `clwb` VEH trap, ADX tripwire, JSONL telemetry, Win32/PSM forwarders |
|
||||
| **Track B** | `shims/xmem/`, `shims/xcrdapi/` | `xmem.dll` (virtual/physical/scatter allocator, Lockhart 8–10 GB budget) & `XCRDAPI.dll` (DirectStorage) |
|
||||
| **Track C** | `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Xbox D3D12 COM proxy → D3DMetal 3.0, `PresentX`, RDNA 2 texture tiling (`XG`), DXR/BVH4 & FidelityFX hooks |
|
||||
| **Track D** | `shader-transpiler/` | `DXBC`/`DXIL`/`ACCC`/`FSPX` parser, RDNA 2 → DXIL/MSL transpiler, shader cache, `d3dmetal-native` harness |
|
||||
| **Track E** | `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Offline GDK runtime, `GameInput.dll` (`@1`), `AcpHal.dll`, `xapu.dll`, `chad.dll` |
|
||||
| **Track F** | `tests/conformance/`, `docs/` | Synthetic PE32+ conformance tests, integration fixture, benchmarks, documentation |
|
||||
|
||||
## Claiming work before you start
|
||||
### Cross-Track `[ABI]` Rule
|
||||
- Never edit another track's directory inside a feature PR.
|
||||
- If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both provider and consumer tracks implement against the frozen contract in parallel.
|
||||
- When adding a new conformance test, create `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories without editing `tests/conformance/CMakeLists.txt`.
|
||||
|
||||
Several people and coding agents work on this repository at the same time. An issue with no visible claim is the only signal that a task is free, so claim before you edit anything.
|
||||
---
|
||||
|
||||
1. **Check.** Read the issue's comments, assignees and labels, its linked pull requests, and open pull requests that touch the same files. If someone holds a live claim, pick another task. Do not start parallel work on a claimed task.
|
||||
2. **Claim.** Comment `/claim` on the issue (or run `scripts/agent-queue.sh claim <n>`). Where the claim workflow is enabled, wait for its grant comment and the `claimed-by:<login>` label; a refusal names the reason. Where it is not enabled yet, your comment is the claim and the earliest valid claim comment wins. One issue per claim; claim follow-up tasks separately.
|
||||
3. **Respect file ownership.** Two claimed tasks never edit the same files at the same time. If the issue lists files, edit only those; ask the maintainer before widening the list.
|
||||
4. **Keep it alive.** A claim lapses 24 hours after the latest grant, `/progress <what changed>` comment, or push to the linked pull request. Post `/progress` at least once a day while you work. Lapsed tasks return to the queue and may be claimed by anyone.
|
||||
5. **Release.** If you stop, comment `/release` so the task returns to the queue. Use `/blocked <reason>` instead if you are waiting on another task.
|
||||
6. **Link.** Open the pull request from a branch named `task/<n>-<slug>` with `Closes #<n>` in its description.
|
||||
## 3. Native Apple Silicon Host & Runtime Isolation
|
||||
|
||||
An agent acting for a contributor claims in that contributor's name and must not claim work for areas that contributor may not claim (`.github/agent-queue.json`). Never remove, overwrite or ignore another person's claim; ask the maintainer to `/reassign` instead. See `docs/coordination/agent-tasks.md` when present.
|
||||
- **ARM64 host binaries:** BetterXen's own host executables (`bx-cli`, etc.) must be native `arm64`-only (`aarch64-apple-darwin`); verify with `file` and `lipo -archs`. Only guest shim DLLs under `shims/` and conformance EXEs under `tests/conformance/` target x86-64 Windows PE32+.
|
||||
- **Apple Silicon generations:** Support M1 through M5 and future generations via runtime capability detection; do not hardcode single-generation GPU or RAM assumptions (default to Lockhart memory limits on 16 GiB hosts).
|
||||
- **Child environment isolation:** `bx-cli run` must isolate the child CrossOver/Wine process (`env_clear()` + minimal explicit allowlist; `--inherit-env` opt-in only) so host credentials and stray variables never leak into guest processes.
|
||||
- **Build concurrency:** Use at most four Cargo/CMake build jobs across simultaneous local builds, with one GPU workload at a time.
|
||||
|
||||
## Changelog maintenance
|
||||
---
|
||||
|
||||
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
|
||||
- Update the changelog in the same task for every meaningful addition, modification, fix, removal or security change, including work implemented by another agent. Use `Added`, `Changed`, `Fixed`, `Removed` or `Security` as appropriate.
|
||||
- Write concise entries that explain the effect for users or contributors. Distinguish implemented behavior, local verification and independent acceptance. Never invent release dates, versions, benchmark results, passing tests or compatibility claims.
|
||||
- Omit trivial formatting and intermediate steps unless they materially affect maintainability. Keep unreleased changes under `[Unreleased]` until a release is authorized.
|
||||
- Before concluding the task, check whether the changelog needs an update and make it when warranted. Rewrite historical entries only to correct factual errors. Preserve existing content when tightening the prose.
|
||||
## 4. Dependencies, Licensing & Provenance
|
||||
|
||||
## Public documentation and terminology
|
||||
- Before integrating or copying any third-party code: verify the **per-file** license (not just repository metadata), confirm compatibility with `GPL-3.0-or-later` and every selected component, preserve copyright notices, record the upstream repository and exact commit/version, document modifications, and record the entry in `docs/research/upstream-registry.md` and `docs/research/component-reuse-matrix.md`. If licensing is uncertain, do not use it until resolved.
|
||||
- Never bundle, modify, or redistribute proprietary components (CrossOver binaries, D3DMetal, Rosetta 2, Apple tools) unless their license explicitly allows it. Never bypass licensing or activation requirements of any dependency.
|
||||
- **Provenance first:** Exclude anything derived from leaked proprietary material or unauthorized software. A project's license being GPL does not clear material it was built from or for. Projects whose stated purpose depends on leaked or unauthorized builds (including VIctory, PE-Vulkan, KyTx, AnyPS5, and similar efforts) are never adopted as code, shader, asset, or tooling sources without a recorded per-file provenance and license audit. Game-specific, asset-specific, and decryption-related code is never adopted.
|
||||
|
||||
- Write public documentation so readers can understand it without earlier agent conversations. Keep `README.md` and `docs/README.md` accessible to new contributors.
|
||||
- Introduce descriptive names before internal identifiers such as X1, G10 or P2-04. Define specialist abbreviations on first meaningful use.
|
||||
- Write changelog entries around actual behavior and its effect on users or contributors. Distinguish implementation, synthetic demonstrations, independent verification and real Xbox execution.
|
||||
- Review terminology whenever editing documentation. Use concise, precise explanations and preserve evidence scope.
|
||||
- Update `docs/README.md` whenever you add, remove, rename or substantially reorganize documentation.
|
||||
---
|
||||
|
||||
## Subagent reasoning
|
||||
## 5. Honesty, Evidence & Independent Verification
|
||||
|
||||
**Every spawned subagent must use LOW reasoning effort.** Explicitly select LOW and verify the resolved configuration. Never use Medium, High or Extra High. If LOW cannot be guaranteed, proceed without that subagent. The lead agent may use the user-selected reasoning setting.
|
||||
- **Never fabricate verification:** Never report a test as passed unless it ran and passed on this revision. Never count a skipped test or unavailable tool as a pass. Never invent benchmark results, API names, encodings, hardware capabilities, or compatibility claims.
|
||||
- **No silent fallbacks:** Do not hide errors behind silent no-ops. Every unimplemented shim export must call `BX_STUB_LOG(dll, sym)` and every unimplemented COM vtable slot must call `BX_VTABLE_STUB_LOG(iface, slot, method)` so `bx-cli trace` surfaces exact blockers. Do not weaken or delete tests to make them pass.
|
||||
- **Evidence classes & hardware claims:** Classify evidence per `docs/claims.toml`. Never claim "verified on Xbox hardware" — BetterXen has no Xbox hardware access; agreement with a public specification or Apple Silicon run is not Xbox hardware verification.
|
||||
- **Independence of verification:** The agent or contributor who writes a component does not independently certify it. Independent reviewers re-derive expectations from primary sources and are not told the implementer's conclusions as ground truth. The same faulty code must never produce both the expected and actual values in a test.
|
||||
- **Milestone completion:** A milestone is complete only when every exit condition has recorded evidence — never from commit counts, lines of code, or isolated stubs.
|
||||
|
||||
## Checkout commands
|
||||
---
|
||||
|
||||
- Format: `cargo fmt --all -- --check`
|
||||
- Lint: `cargo clippy --workspace --all-targets -- -D warnings`
|
||||
- Test: `cargo test --workspace`
|
||||
- Verify the synthetic fixtures: `scripts/assemble-fixture.sh --check`
|
||||
- Run native GPU correctness: `scripts/test-gpu.sh`
|
||||
- Run the three RDNA-to-Metal fixtures: `scripts/demo.sh`
|
||||
- Run independent CPU validation: `cargo test --locked -p xenora-semantic-review`
|
||||
- Run the correctness-gated benchmark suite: `scripts/benchmark.sh` (idle machine, release, validation off)
|
||||
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
|
||||
- Check generated status tables: `python3 scripts/audit/status.py --check`.
|
||||
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
|
||||
- Fuzz one CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default).
|
||||
## 6. Legal & Clean-Room Rules
|
||||
|
||||
Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time.
|
||||
- Use only publicly accessible documentation, publicly licensed software, and authorized synthetic workloads. Never obtain, paste, or commit leaked executables or SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, unauthorized assets or source code, or proprietary game builds and shader collections.
|
||||
- **Legal boundary (`docs/legal.md`):** BetterXen does not circumvent console security or DRM and does not load encrypted or protected content. Validate technical compatibility and safety of user-provided files; do not ask for ownership receipts, accounts, or acquisition provenance as part of file loading.
|
||||
- Never place restricted material, personal paths, or secrets in the repository or its Git history.
|
||||
|
||||
Do not add AI attribution or Co-authored-by trailers to commits.
|
||||
Never commit or push without explicit permission.
|
||||
Preserve the configured Git author and committer identity.
|
||||
---
|
||||
|
||||
## Ownership
|
||||
## 7. Claiming, Git Safety & Changelog
|
||||
|
||||
Xbox and claims owns public console research. ISA owns the decoder and oracle fixtures. Compiler owns the parser, IR and MSL. Metal owns the native GPU backend. Testing owns the independent reference and fixture validation. Infrastructure owns shared Cargo configuration, policies and the CPU boundary. R1 independently audits claims and release evidence. R2 independently validates semantic expectations and mutation results.
|
||||
1. **Check before coding:** Read every comment on the issue and check open PRs. Never claim over an active claim.
|
||||
2. **Claim in plain text:** Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` on the issue (earliest claim wins; stale after 7 days without commits/PR).
|
||||
3. **Isolate with branches or worktrees:**
|
||||
```sh
|
||||
git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main
|
||||
```
|
||||
4. **Link & sign off:** Put `Closes #<issue>` in the PR description and sign off every commit (`git commit -s`, DCO).
|
||||
5. **Git safety:** Never commit, push, or change remote visibility without explicit user authorization. Do not add AI attribution or `Co-authored-by` trailers to commits. Preserve the configured Git author and committer identity.
|
||||
6. **Changelog & docs index:** Read `CHANGELOG.md` before starting and update `[Unreleased]` for every meaningful addition, change, fix, removal, or security update. Update `docs/README.md` whenever documentation is added, removed, or reorganized.
|
||||
7. **Subagent reasoning:** When spawning helper subagents in automated workflows, keep subagent reasoning effort low unless the user explicitly asks otherwise.
|
||||
|
||||
---
|
||||
|
||||
## 8. Verification Commands (Run Before Every Handoff / PR)
|
||||
|
||||
```sh
|
||||
# 1. ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
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 # must print: arm64
|
||||
|
||||
# 2. Cross-compile all 16 x86-64 PE32+ shim DLLs + auto-discovered conformance EXEs
|
||||
# (strictly verifies .edata Export Directory names, ordinals, forwarders, 0 extra exports, 0 MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 3. Live synthetic PE32+ conformance tests inside CrossOver 26.3 + 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
|
||||
|
||||
# 4. Repository Markdown link & hygiene check
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
```
|
||||
+305
-2
@@ -10,16 +10,290 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- `dxbc-accc` parses a synthetic FSPX section table inside DXBC `ACCC` chunks (section descriptors, section 1 stage configuration using the `bx_shader_stage_t` values, and section 6 RDNA 2 code bounds) and returns a parse error for truncated or out-of-range input instead of panicking. A table may declare at most 64 sections. A `DXIL` chunk is accepted only when it is a `DxilProgramHeader` from the public DirectXShaderCompiler layout. It exports `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, and `bx_shader_free_buffer` with the layouts in `abi/include/bx_shader_bridge.h`. `bx_shader_inspect` fills that struct without logging. `bx_shader_prepare_for_d3dmetal` copies the `container_size` prefix when that DXIL header is present, including when the container also has a malformed FSPX table. An empty `DXIL` chunk is rejected. ACCC-only input returns `BX_SHADER_ERR_UNSUPPORTED` and writes one stderr inspection line. The first FSPX table that declares a stage supplies it. A failed stderr write does not panic. RDNA 2 bytes are not translated to DXIL. The section layout is synthetic and is not a console container specification or an Xbox hardware result (#416).
|
||||
- Added a visual `Progress Tracker` section to `README.md` with an M0–M6 Mermaid milestone pipeline, a Track A–F live status board (`🟩`/`🟨`/`⬜`), and direct GitHub label links for open M1 issues.
|
||||
- Added a required `Zen` field to `.github/ISSUE_TEMPLATE/track-handoff.yml` so every track handoff issue states its core purpose briefly in plain English up front.
|
||||
- Added Section 0 (`First-Time Contributor Onboarding`) to `AGENTS.md` (`CLAUDE.md` symlink) giving coding agents a turnkey step-by-step onboarding flow (preflight, `bx-cli doctor`, unclaimed `status: ready` issue discovery, claiming, scoped implementation, local verification including hosts without CrossOver, DCO commit, and PR CI watching).
|
||||
- Overhauled the repository into a clean 6-track parallel hybrid workspace (Milestone M0) designed for 5–8+ concurrent contributors and coding agents: added frozen cross-DLL ABI headers and canonical `.def` export tables (`abi/`), native ARM64 Rust workspace (`launcher/crates/{bx-cli,bx-probe,bx-telemetry}` with `env_clear()` child environment isolation, and `shader-transpiler/crates/dxbc-accc`), CMake + `mingw-w64` superbuild (`shims/`, `scripts/build-shims.sh`) producing 16 standalone x86-64 PE32+ shim DLLs (`bx_runtime_veh.dll` with working `clwb` VEH trap and JSONL logger, `xmem.dll`, `XCRDAPI.dll`, `d3d12_xs.dll`, `xg_xs.dll`, `xgameruntime.dll`, `GameInput.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, and PSM/ntuser forwarders) with strict PE Export Directory verification (exact names, ordinals, forwarders, zero extra exports, zero dynamic MinGW runtime dependencies), auto-discovered synthetic PE32+ conformance tests (`tests/conformance/`), `.github/workflows/hybrid-ci.yml`, `.github/ISSUE_TEMPLATE/track-handoff.yml`, `docs/adr/0006-retire-in-tree-native-workspace.md`, `docs/architecture/parallel-tracks.md`, and `docs/issues/wave-1-backlog.md`. Unified `docs/roadmap.md`, `CONTRIBUTING.md`, `AGENTS.md`, `README.md`, and `.github/CODEOWNERS` (retaining global `* @MacosPorters/maintainers` fallback and full provenance/independent-verification rules). Verified locally on Apple M5 (macOS 27.2.1, CrossOver 26.3, Rosetta 2) with all Rust checks, strict 16-DLL export verification, and live `test_veh_clwb.exe` + `test_shim_exports.exe` smoke tests passing.
|
||||
- Documented the original Windows workload set and Phase 1 hybrid measurement protocol (#353), including receipt-field sources, percentile definitions, negative controls and independent reproduction requirements. The protocol identifies the unmerged runner candidate and its missing raw traces and measurements; it adds no execution or compatibility claim.
|
||||
- Added the upstream research registry and component reuse matrix (`docs/research/`), a public-documentation review (evidence class D, nothing executed) of CrossOver, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, FEX, VIctory, VIctory-macOS and PortWatch. VIctory-family projects are excluded from reuse on provenance grounds. The GitHub project board is not yet configured because the token lacks the `project` scope (#346).
|
||||
- Added hybrid research records: `docs/research/hybrid-backlog-research-2026-11-25.md` (findings and registry candidates, from search summaries) and `docs/research/primary-source-verification-2026-11-25.md` (re-check against CodeWeavers, Apple, DXMT and Wine primary pages). It confirms CrossOver's backend list, finds no public documentation of `CX_GRAPHICS_BACKEND`, and records that two Apple notices on Rosetta's end disagree; D3DMetal's license text and CrossOver's Rosetta and ARM64 plans remain unverified. Eleven issues created from the research were reviewed the same day: #364 and #365 stay in Phase 1, the others are parked and recorded under "Parked ideas" in the roadmap. Rust 1.100.0 (already installed) is the required toolchain; the default `stable` was 1.94.1. Planning only; nothing was installed or run.
|
||||
- Added `docs/research/crossover-licensing.md`, a per-component license and redistribution record for the hybrid direction: CrossOver itself, Wine, DXMT, DXVK, VKD3D-Proton, MoltenVK, Apple's Game Porting Toolkit repository, D3DMetal and Rosetta 2, each with the exact text read or the missing document named, plus an entry in `docs/licenses.md` (#354). Nothing is bundled or redistributed; the D3DMetal text (third-party copy, not confirmed against Apple's) and Rosetta 2 terms remain unverified, and CrossOver 26.3.0's FOSS inventory is unknown. Research only; no code or dependency change.
|
||||
- Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed.
|
||||
- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed.
|
||||
- Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally.
|
||||
- Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub.
|
||||
- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299).
|
||||
|
||||
- Added `scripts/compare-benchmarks.py` (with built-in `--self-test` unit tests) and documented it in `docs/testing/benchmarks.md`: compares structured benchmark run directories only when revision-independent configuration matches (`device`, `host_arch`, OS/toolchain versions, build profile, Metal validation flags, power source, thermal state, `reps`, and `warmup`), reports medians, IQR/span dispersion, missing or excluded entries, and factual uncertainty signals without an arbitrary pass/fail threshold.
|
||||
### Removed
|
||||
- Retired the paused in-tree native-first workspace (`crates/`, `app/`, `benchmarks/`, `experiments/`, `fixtures/`, `fuzz/`, `licenses/`, legacy native scripts, legacy `.github/workflows/ci.yml`, `agent_queue`, legacy `tests/*` outside `tests/conformance/`, and native-only docs) from `main` per ADR 0006; the full native-first history remains permanently preserved at Git tag `native-first-final`.
|
||||
- Removed the "Agent PR checks" workflow (`.github/workflows/agent-pr-checks.yml`), its section in `docs/coordination/agent-tasks.md` and the four workflow tests in `tests/agent_queue/test_workflows_cli.py` that only exercised it. Pull requests are no longer checked for `Closes #N`, task file patterns or `/verified` comments; the claims workflow and its tests are unchanged. The agent queue Python tests pass locally (85 tests).
|
||||
- Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies.
|
||||
|
||||
### Changed
|
||||
- Replaced the native-first development plan with a CrossOver-based hybrid roadmap (`docs/roadmap.md`: five provisional phases, only Phase 1 active; the earlier H0 to H7 breakdown is archived) and an accepted-direction ADR 0005. No hybrid component exists yet and no Xbox title is shown to run; this is planning and research scheduling only, and no phase is verified complete.
|
||||
- Rewrote the engineering rules in `AGENTS.md` (`CLAUDE.md` is a symlink to it) to permit CrossOver, Wine-based infrastructure, Rosetta 2 and D3DMetal subject to licensing, while keeping the honesty, independent-verification, provenance and clean-room rules and adding dependency and reuse rules. Resolves #345.
|
||||
- Native work is preserved and paused: tag `native-first-final` marks the last `main` commit before this change, `docs/research/native-roadmap.md`, and archived native-first plan and milestones under `docs/archive/`. GitHub backlog: all native issues except four with assigned contributors and open pull requests were closed as not planned and indexed in `docs/research/native-issue-archive.md`; future-phase issues were parked in the roadmap; only the Phase 1 milestone is open.
|
||||
- Replaced the issue templates with hybrid task, bug, research, performance, validation and documentation forms and added a pull request template. Fixed invalid YAML in the agent-task template. README, CONTRIBUTING and the docs index now describe the hybrid direction.
|
||||
- Replaced our own references to a specific commercial game title (README non-affiliation line, research and integration notes, ignored diagnostics folder names) with generic "commercial title" wording. The ignored folder names are now `diagnostics/title-candidate-*` and `diagnostics/title-check`. Third-party repository names, URLs and code-span paths in research notes are unchanged so their provenance stays accurate. Our own prose references to the upstream project formerly named in the research notes now read "PE-Vulkan project". Added the PortWatch native-macOS research notes. No behavior change.
|
||||
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
|
||||
- Removed the contributor avatar section from the README.
|
||||
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
|
||||
- Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place.
|
||||
- Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts.
|
||||
- Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained.
|
||||
- Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle).
|
||||
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
|
||||
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
|
||||
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
|
||||
- The ARM64 assembler uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result.
|
||||
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
|
||||
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
|
||||
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
|
||||
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
|
||||
- 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
|
||||
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
|
||||
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
|
||||
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
|
||||
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
|
||||
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
|
||||
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
|
||||
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
|
||||
### Added
|
||||
- Added opt-in `betterxen run --startup-report <path>` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255).
|
||||
- Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification.
|
||||
- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run.
|
||||
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
|
||||
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
|
||||
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
|
||||
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
|
||||
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
|
||||
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
|
||||
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
|
||||
only; nothing was optimized.
|
||||
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
|
||||
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
|
||||
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
|
||||
completed with status Completed. `plan_staged_upload` rejects missing, duplicate or out-of-range mip levels,
|
||||
wrong mip sizes, short row pitches or byte buffers, and budgets smaller than one row, all before any Metal
|
||||
object is created. A blit `read_back` returns any mip as tight RGBA8 bytes. On one Apple M4 under Metal API
|
||||
validation, readback matched independently built patterns for every level of a padded 37×19, six-level
|
||||
texture under four budgets, and matched the existing direct `upload`. Staging is slower than the direct path
|
||||
(2048² with 12 mips, release build: 2.1 ms direct, 2.7 ms with a 4 MiB budget, 17.8 ms with 256 KiB), so
|
||||
`upload` and its callers are unchanged. Not yet independently accepted.
|
||||
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
|
||||
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
|
||||
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
|
||||
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
|
||||
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
|
||||
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
|
||||
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
|
||||
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
|
||||
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
|
||||
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
|
||||
- Added checked, per-mip copy footprints for synthetic block-compressed texture arrays. Contributors can pack tight block rows or repack entire chains with independent row and placement alignment, and pass selected BC1–BC5 levels to the existing Metal readers (#391).
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
- Added `scripts/cpu-tests.sh`, which lists the default-feature workspace test targets and runs
|
||||
deterministic shards of them (`--shard K/N`), with `--check N` showing every target lands in
|
||||
exactly one shard. It does not replace `cargo test --locked --workspace` or
|
||||
`scripts/test-gpu.sh`. `docs/testing/cpu-coverage.md` records local CPU gate timings on one
|
||||
Apple M4 host (about 40 s wall time; one loader target takes about 19 s) and shows that the 2- and
|
||||
3-shard unions match the full gate's 681 passed and 34 ignored tests (#159).
|
||||
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
|
||||
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
|
||||
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added SHLD and SHRD, the double-precision shifts (`0F A4`/`0F A5` and `0F AC`/`0F AD`), for 16-, 32- and 64-bit register and memory destinations with the count in an 8-bit immediate or in CL (part of #121). The count is masked to five bits (six for 64-bit operands); a masked count of zero changes nothing, the vacated bits are filled from the source register, CF receives the last bit shifted out of the destination, ZF, SF and PF follow the result, OF is set only for a count of one (a sign change) and AF is undefined. A 16-bit count above 16 leaves the result and flags undefined in the Intel SDM; Xenora keeps every flag and writes the bits of the 32-bit concatenation, and no test relies on that. The registry gained the operand encodings `rm_reg_imm` and `rm_reg_cl`. Both engines run the shared semantics; nothing is lowered to ARM64. Eight SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 72 assembled SHLD and SHRD instructions, checked by a bit-at-a-time reference in `x86_integer.rs` and by the faulting read-modify-write test. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
- Added a deterministic guest thread scheduler (first part of #323): independent CPU contexts, guarded stacks and TEBs on one host thread, with bounded turns, `CreateThread`, `ExitThread`, `TerminateThread`, `GetExitCodeThread`, `SuspendThread`, `ResumeThread` and `SwitchToThread`. With a scheduler attached, `WaitForSingleObject` and `WaitForMultipleObjects` block only the calling guest thread, with timeouts, on threads, events, semaphores and mutexes; abandoned mutexes, deadlocks and per-thread faults are reported. Guest threads never run concurrently. Critical sections, SRW locks, condition variables and `Sleep` do not block per thread yet. See `docs/runtime/threads.md`.
|
||||
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
|
||||
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
|
||||
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
|
||||
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). Part of #215.
|
||||
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
|
||||
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
|
||||
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
|
||||
|
||||
- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 736 x86-64 cases whose results, flags, MXCSR state and faults come from the Intel SDM, with the AMD APM for some MXCSR flags, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manuals' definitions. 700 cases were written before the CPU source was read; the rest and the sweeps came afterwards. The interpreter and the DBT both run them; the DBT route (ARM64 code or Rust helper) is confirmed by the fallback counter for straight-line cases and predicted for the others. 592 cases are verified, 133 use forms both engines refuse, and eleven, plus a self-modifying-code test, record open defects in five ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, PE set by an exact unmasked overflow, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
|
||||
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
|
||||
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
|
||||
- Added XMM0-XMM15 and MXCSR to the guest CPU state, and the SSE and SSE2 moves and packed integer forms: aligned, unaligned, scalar, half and non-temporal moves, MOVD/MOVQ, sign-mask extraction, bitwise operations, wrapping and saturating arithmetic, compares, minimum, maximum, average, multiplies, PSADBW, packs, unpacks, shifts, shuffles, PINSRW, PEXTRW, LDMXCSR and STMXCSR (parts of #124, #125, #126 and #128; awaiting independent review). Operations with identical NEON lane semantics are translated to ARM64; the rest call the shared semantics. Misaligned 16-byte operands and reserved MXCSR bits raise a distinct general-protection exit. MXCSR is state only: floating-point arithmetic is not implemented.
|
||||
- Added 374 LLVM-assembled vector instructions with a byte-array reference, compared with both engines over 23,936 states, plus alignment, fault, width and mixed-sequence tests.
|
||||
- Added a declarative x86-64 instruction registry (`crates/loader/x86/instructions.toml`) and its generator, `crates/loader/generate_x86.py`, with `validate`, `generate` and `--check` modes. The static probe, the interpreter and the native DBT now share one decoder driven by its tables, so instruction boundaries, rejected forms and reported support agree. Overlapping encodings, such as a sign extension claiming the MOV-immediate opcodes, fail validation. See `docs/cpu/instruction-registry.md`.
|
||||
- Added integer instructions for 8-, 16-, 32- and 64-bit register and checked memory operands: the eight ALU operations, TEST, INC, DEC, NEG, NOT, XCHG, ROL, ROR, SHL, SHR, SAR, MUL, IMUL, DIV, IDIV, CMOVcc, SETcc, BT, BTS, BTR, BTC, BSF, BSR, POPCNT, TZCNT, LZCNT, CBW/CWD families, PUSH, POP, LEAVE, RET imm16 and flag instructions, with parity and auxiliary-carry flags and a distinct divide-error exit (parts of #65, #66, #68, #70, #71, #73, #118 to #123, #194 to #196; awaiting independent review). Forms the DBT does not lower to ARM64 call the same Rust semantics and are counted.
|
||||
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
|
||||
- Added FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
|
||||
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
|
||||
- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported.
|
||||
- Split the gfx1030 semantic registry into one file per encoding family (`crates/isa/semantics/rdna2/{sop2,sopc,sop1,vop2,vopc,vop3}.toml`, included in order by `rdna2.toml`; the split left the generated tables byte-identical), and added registry encoding variants: another encoding of a declared form is pure data. `v_add_nc_u32_e64` is now the first VOP3 variant of `v_add_nc_u32` (operand rule `vop3_vgpr2`), replacing its hand-written decoder and instruction with no behaviour change (part of #215).
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
|
||||
- Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`.
|
||||
|
||||
- Added an MSVC decorated-name decoder (`xenora_import_gen::demangle`), and import manifests now show undecorated names for C++ imports that need manual engineering. Unsupported constructs return no result rather than a guess. Tests decode names mangled independently by clang for `x86_64-pc-windows-msvc`.
|
||||
|
||||
- Added a guest service dispatch benchmark (`cargo bench -p xenora-loader --bench service_dispatch`). It runs correctness-gated guest loops that call services through the import table under the DBT; see `docs/testing/benchmarks.md`.
|
||||
|
||||
- Added a `runtime_services` fuzz target (`scripts/fuzz.sh runtime_services`) and a stable-toolchain replay test sharing the same driver. Both call random sequences of the standard guest services with zero, all-ones, writable, read-only, executable, unmapped, raw and earlier-result arguments, and check after every call that read-only and code memory are unchanged and nonvolatile registers are preserved. Writable guest memory is filled from a deterministic pattern so corpus bytes are reserved for dispatch. An earlier 300-second campaign's input and edge counts are withdrawn: that run exhausted each input while filling the 65,536-byte writable region and never reached the dispatch loop. After the harness fix, a local 300-second campaign on Apple Silicon (`scripts/fuzz.sh runtime_services 300`) ran 96,589 inputs (4,008 coverage edges, 9,940 features) without a crash; the first minutes also found a ~3.7 GiB `XMemAlloc` host OOM, which is now fixed by failing closed on overflowing sizes and routing mappings through the virtual allocation budget. Services that wait on real time or reach native Metal are excluded.
|
||||
|
||||
- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently.
|
||||
|
||||
- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation.
|
||||
|
||||
- Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler.
|
||||
|
||||
- Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services.
|
||||
|
||||
- Added process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, including Winsock sockets and task-queue handles, and the engine that ran the guest executes nothing further. A TLS callback that exits ends startup with that exit as its outcome, and the remaining callbacks and the entry point do not run. Startup reserves the page holding the return addresses the engine intercepts, so an image mapped over them is refused. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review.
|
||||
|
||||
- Added same-process guest file handle duplication with a shared file position.
|
||||
|
||||
- Added guest file and directory enumeration with typed search handles.
|
||||
|
||||
- Added closed-file moves and file and directory attribute queries on the synthetic guest drive.
|
||||
|
||||
- Added nested guest directories and checked file deletion on the synthetic drive.
|
||||
|
||||
- Added the second Gate A milestone, A2 (#419): an original hosted C program, `tests/compat_fixtures/gate_a2.c`, built from source by the new test `crates/loader/tests/gate_a2.rs` with the mingw-w64 C runtime (UCRT) and run through the loader, the standard services and the ARM64 DBT. The runtime's own startup code runs before `main`. The program takes `argc` and `argv`, sorts heap data with `qsort`, prints with `printf`, writes a report with `fprintf` and reads it back with `fgets`, registers a function with `atexit` and returns from `main`. At `-O0`, `-O1`, `-O2` and `-Os` it ends with exit status 0, and its captured output and its report match, byte for byte, text recomputed in Rust. Seven more tests cover other arguments, four wrong command lines, a step budget that is too small, and control variants that end in a failed check, in `exit(42)` and in `abort()`. The test needs mingw-w64 on the host and fails, not skips, without it, so the CI workflow now installs it. Nothing from mingw-w64 is stored in the repository. Local runs used mingw-w64 14.0.0 with GCC 16.2.0. This is one program and one C runtime, compared by hand with a native build of the same source and not with Windows or x86 hardware; `docs/testing/gate-a.md` lists what it does not show. Awaiting independent review.
|
||||
|
||||
- Added file seeking and end-of-file resizing on the synthetic guest drive.
|
||||
|
||||
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
|
||||
|
||||
- Added files for a hosted C program (#402, part of Gate A2): `fopen`, `fclose`, `fgets` and `perror`, and file streams for the output services from #400, so `fprintf`, `fwrite` and `fputs` write to a file `fopen` returned. The files are the ones on the in-memory `C:` drive behind `CreateFileW`, so a file written through a C stream is the file `ReadFile` reads, and the reverse. `fopen` takes `r`, `w` or `a` with `+`, `b` and `t` as Microsoft's page describes them; text mode, the default, stores a line feed as carriage return and line feed, reads the pair back as a line feed and ends input at `CTRL+Z`. Failures return their documented results; the `errno` values beyond `EINVAL` for a null or empty argument are Xenora's choice. Nothing is buffered, there is no seeking, a C stream takes no part in Win32 sharing, and the other mode characters are refused. All four services are `partial`. Eight tests in `runtime_services.rs`, four in the new `crt_files.rs` that cross-check with `ReadFile` and `WriteFile`, and a unit test of the mode strings cover it. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
|
||||
|
||||
- Added non-alertable extended event waits through both Win64 wait APIs.
|
||||
|
||||
- Added the C runtime's `exit`, `_exit` and `abort` (#395, part of Gate A2), on top of the process exit from #329. A C program ends through `exit`, not `ExitProcess`, and a program built with the mingw-w64 runtime imports all three; the loader refused it before its entry point because they did not resolve. `exit` calls the functions registered with `atexit` and `_crt_atexit`, most recently registered first, and then ends the guest with `ExitReason::ProcessExit(status)`; `_exit` ends it with its status and `abort` with exit code 3, and neither calls a registered function. All three go through the same cleanup as `ExitProcess` and never end the host. A function registered while `exit` runs is called next, as ISO C requires; `exit` called again from a registered function, which ISO C leaves undefined, runs the remaining functions once and ends with the later status. All three are partial: no stream is flushed because there are none, `abort` prints no message and calls no `SIGABRT` handler, and thread-local destructors are not run. Nine tests in `crt_exit.rs` call them from guest code. `docs/testing/gate-a.md` now describes A2 as in progress and not passing. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added immediate wait-any and wait-all for guest event handles.
|
||||
|
||||
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
|
||||
|
||||
- Added command-line arguments for a hosted C program (#392, part of Gate A2): the C runtime services `__p___argc`, `__p___argv`, `__p__environ`, `_configure_narrow_argv` and `_initialize_narrow_environment`, and a host method, `ServicesState::set_program_arguments`, that supplies the program's `argv`. A program built with the mingw-w64 runtime gets `argc`, `argv` and `envp` for `main` through these five, and the loader refused it before its entry point because they did not resolve. After configuration the guest finds the host's arguments in `__argc` and `__argv`, each NUL-terminated, with a null pointer after the last; with no host input it gets one empty argument, as ISO C specifies. The host method refuses a NUL byte, more than 32,767 bytes in all, and a call after the guest has built its table. The three variables are documented and the two initialization functions are not, so their behaviour is Xenora's: no code page, no wildcard expansion, and an empty environment table. All five are `partial`. Four tests in `runtime_services.rs` call the services from guest code and compare what the guest sees with what the test supplied. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added bounded guest CRT long-integer parsing for byte and wide strings.
|
||||
|
||||
- Added standard output for a hosted C program (#400, part of Gate A2): a `printf` formatting engine, the standard streams, and capture of what the guest writes to `stdout` and `stderr`. The services are `__acrt_iob_func`, `__stdio_common_vfprintf` (what `printf` and `fprintf` call in a program built with the mingw-w64 runtime), `fwrite`, `fputs`, `fflush` and `setvbuf`; a host reads the output through `ServicesState::standard_output` and `standard_error`. The engine handles the flags, width, precision and size prefixes of `d`, `i`, `u`, `o`, `x`, `X`, `c`, `s`, `p` and `%%` as Microsoft's format specification page and ISO C describe, reading arguments from the guest's `va_list`. The standard streams are text-mode streams, so a line feed is captured as carriage return and line feed. Floating-point and wide conversions, a locale object, other streams and files are not modelled and stop the guest with the runtime-limit fault instead of printing something wrong; `%n` and unknown conversions return -1 with `EINVAL`. All six services are `partial`. The engine's output matches the host C library's `snprintf` on 2,600 generated cases whose result ISO C defines (`crates/loader/tests/printf/reference.py`), with hand-written cases for the Windows-specific rules, and seven tests in `runtime_services.rs` call the services from guest code. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
|
||||
|
||||
- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
|
||||
|
||||
- Added private guest heap creation and destruction with per-heap allocation ownership.
|
||||
|
||||
- Added default guest heap reallocation with data preservation and an in-place-only option.
|
||||
|
||||
- Added the synthetic default process heap with allocation, size queries, and release.
|
||||
|
||||
- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review.
|
||||
|
||||
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
|
||||
|
||||
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
|
||||
|
||||
- Added checked guest CRT byte string comparison with `strcmp` and `strncmp`.
|
||||
|
||||
- Added bounded guest CRT byte fill, copy, move, and comparison services.
|
||||
|
||||
- Added guest CRT string length services for UCRT and its string API set.
|
||||
|
||||
- Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication.
|
||||
|
||||
- Added same-process duplication of synthetic thread handles with independent closure.
|
||||
- Added a rights-checked `GetThreadId` query for handles to the synthetic guest thread.
|
||||
- Added 32-bit and 64-bit millisecond uptime queries for synthetic Windows guests.
|
||||
- Added high-resolution elapsed-time queries for synthetic Windows guests through `QueryPerformanceCounter` and `QueryPerformanceFrequency`.
|
||||
|
||||
- Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`.
|
||||
- Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`.
|
||||
- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
|
||||
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
|
||||
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
|
||||
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
|
||||
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
|
||||
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
|
||||
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
|
||||
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
|
||||
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
|
||||
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
|
||||
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
|
||||
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
|
||||
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
|
||||
- Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry).
|
||||
- Added the gfx1030 Wave32 VOPC compares `v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`. VCC_LO is EXEC_LO & the per-lane test, always fully written, so empty EXEC gives 0. A compare result can feed `s_cbranch_vccz`, `v_mov_b32_e32 vN, vcc_lo` and another compare's source; nothing else, so EXEC never becomes data-dependent. A data-dependent `s_cbranch_vccz` is a wave-uniform branch over integer vector ALU code, lowered to a select at the join. The Metal kernel builds each mask by recomputing the 32 lanes of its own RDNA wave, with no SIMD-group, threadgroup or barrier assumption. The reference now runs lockstep Wave32 waves. Verified on an LLVM-assembled fixture plus 251 original programs (boundary operands, partial and empty EXEC, both branch edges, a partial final wave) against exact integer definitions: translator, reference and second interpreter agree on CPU, and all 252 match on native Metal with validation. LLVM agrees on every encoding. VOP3, SDWA, DPP, `v_cmpx` and Wave64 stay rejected. See `docs/shaders/vector-compare.md`.
|
||||
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
|
||||
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
|
||||
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
|
||||
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
|
||||
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: `SEMANTIC_FORMS` lists the forms with semantic decoding (46 as of the VOPC compares).
|
||||
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
|
||||
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
|
||||
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
|
||||
- Added a CPU decoder for a bounded subset of BC6H (signed and unsigned HDR) in
|
||||
`xenora-texture`: the four single-subset modes (Khronos modes 3, 7, 11 and 15, Microsoft
|
||||
modes 11 to 14), listed in `BC6H_SUPPORTED_MODES`, plus the reserved modes, which decode to
|
||||
zero as specified. The ten two-subset modes are rejected with `Bc6hError::UnsupportedMode`
|
||||
and are not implemented. Tests check hand-derived values and 128 known-answer vectors from a
|
||||
separate clean-room reference decoder.
|
||||
- Added native Metal upload and readback of BC4 and BC5 textures (UNORM and SNORM):
|
||||
`xenora-texture` gains a pitched `BcChannelUpload`, and `NativeCompute::read_bc_channel_upload`
|
||||
sends the original blocks to `BC4_R*` or `BC5_RG*` textures when the device reports BC
|
||||
support, failing with `supportsBCTextureCompression` otherwise. GPU tests cover six- and
|
||||
eight-value interpolation, equal and extreme endpoints (signed -128 reads as -1.0), red-green
|
||||
channel order, padded row and slice pitches, two layers and two mips against the CPU decoders
|
||||
and hand-derived anchors. On an Apple M5 Pro interpolated codes were within 1.71 codes of the
|
||||
exact values and up to two codes from the truncating CPU reference.
|
||||
Edge levels of 5×3 and 1×1 and invalid payloads (zero extents, short, oversized or
|
||||
block-count-mismatched buffers) are covered.
|
||||
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
|
||||
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
|
||||
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
|
||||
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
|
||||
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
|
||||
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
|
||||
1.14 codes of the exact values, so up to two codes from the truncating CPU reference.
|
||||
8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference.
|
||||
Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents,
|
||||
short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload,
|
||||
and `MetalError::is_capability_unavailable` separates a device without BC support from an
|
||||
implementation failure.
|
||||
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
|
||||
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
|
||||
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
|
||||
@@ -32,12 +306,40 @@ remains unsupported.
|
||||
- Added Win64 TEB allocation and `gs_base` initialization to synthetic guest startup.
|
||||
|
||||
### Changed
|
||||
- Registering an import key twice is now an error instead of silently replacing the first service, ordinals are distinct from names, and API sets in the import generator match exactly instead of by prefix.
|
||||
- `GetSystemTimeAsFileTime` now stops the guest on a null pointer, as on any other invalid pointer, instead of setting the last error.
|
||||
|
||||
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
|
||||
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- `MockClock::advance` no longer wraps the FILETIME. A large advance made the synthetic wall clock run backwards while the performance count beside it stopped at its maximum; both now stop at their maximum (#204).
|
||||
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
|
||||
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
|
||||
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
|
||||
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
|
||||
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
|
||||
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
|
||||
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
|
||||
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
|
||||
- Fixed the static probe reporting support for forms an engine rejects, including NOP, TEST, most conditional branches and the FF group in the interpreter.
|
||||
- Fixed the native DBT's `SXTW` encoding, which set bit 3 of the source register and was right only for registers that already had it set; the previous test used such a register by chance.
|
||||
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
|
||||
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
|
||||
|
||||
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
|
||||
|
||||
- Win64 service argument decoding reports a guest memory error when a stack argument offset overflows.
|
||||
|
||||
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
|
||||
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
|
||||
rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent
|
||||
execution test above), so the probe reports no blocker for this program.
|
||||
@@ -119,6 +421,7 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix.
|
||||
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
|
||||
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
|
||||
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Code of Conduct
|
||||
|
||||
Xenora welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
|
||||
BetterXen welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
|
||||
|
||||
## Expected behavior
|
||||
|
||||
@@ -19,4 +19,4 @@ If possible, use an available private contact channel for a repository maintaine
|
||||
|
||||
Maintainers may remove content, limit participation or block accounts when necessary to protect the community. Responses should be proportionate to the behavior and protect the privacy of affected people. Do not retaliate against anyone reporting a concern in good faith.
|
||||
|
||||
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by Xenora.
|
||||
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by BetterXen.
|
||||
+33
-41
@@ -1,60 +1,52 @@
|
||||
# Contributing to Xenora
|
||||
# Contributing to BetterXen
|
||||
|
||||
Xenora is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
|
||||
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.
|
||||
|
||||
## Getting started
|
||||
## Active Work & Track Ownership
|
||||
|
||||
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
|
||||
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
|
||||
- Claim an issue before working on it by commenting `/claim`, and check that nobody else holds a live claim first. Claims lapse after 24 hours without a `/progress` comment or a push; comment `/release` if you stop. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
|
||||
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
|
||||
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
|
||||
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`.
|
||||
|
||||
## Development and verification
|
||||
1. Pick an open unclaimed issue on your track (A–F) using `.github/ISSUE_TEMPLATE/track-handoff.yml`.
|
||||
2. Check all comments and open PRs, then claim in plain text (`Claiming — branch: track-<a..f>/<issue>-<slug>`). A claim with no commits or PR after 7 days is stale and may be taken over with a reply saying so.
|
||||
3. Work in a dedicated branch or `git worktree` and stay strictly inside the issue's **exclusive file scope**.
|
||||
4. If your track needs a new cross-DLL helper or export, open a small `[ABI]` PR touching only `abi/` first. Once merged, both tracks implement in parallel.
|
||||
5. Add new synthetic PE32+ conformance binaries under `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` (auto-discovered by CMake — no shared-file edits needed).
|
||||
|
||||
When the Cargo workspace exists, run from its root:
|
||||
## Development & Verification
|
||||
|
||||
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:
|
||||
|
||||
```sh
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
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
|
||||
```
|
||||
|
||||
Follow repository documentation for actual GPU tests, fuzzing, mutation testing and benchmarks. Report commands, versions, pass/fail/skip counts and hardware used. A successful shader compile is not successful GPU execution. Do not report unavailable tools or skipped tests as passes.
|
||||
Report exact commands, host hardware/macOS/CrossOver versions, and pass/fail/skip counts. Never report a skipped test or unavailable tool as a pass.
|
||||
|
||||
For an instruction or compiler change, cite the applicable ISA section, state the exact architecture, document operand and execution-mask semantics, and add tests for encodings, edge cases, unsupported cases and independent expected results. Where applicable, verify the resulting MSL through actual Metal execution. Do not convert unsupported instructions into silent no-ops.
|
||||
## Clean-Room, Licensing & Provenance Policy
|
||||
|
||||
For a performance change, provide reproducible before-and-after results using equivalent inputs, hardware and settings. For a new dependency, explain why it is needed, verify its license and native ARM64 compatibility, and record its provenance.
|
||||
- Use publicly accessible specifications, publicly licensed software, and independently authored synthetic workloads only. Never submit leaked executables or SDKs, confidential Xbox documentation, firmware, keys, proprietary game binaries, or unauthorized shader dumps.
|
||||
- Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
|
||||
- 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).
|
||||
|
||||
## Research and clean-room policy
|
||||
## Pull Requests & DCO Sign-Off
|
||||
|
||||
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under Xenora'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.
|
||||
|
||||
Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware.
|
||||
|
||||
Xenora implements its own Rust guest runtime, decoder, typed IR, shader
|
||||
compiler and native Metal backend from public technical specifications
|
||||
and independently derived tests. Contributions must not copy, port or
|
||||
adapt code, decoder tables, internal metadata or implementation
|
||||
architecture from other emulators. External results can inform test
|
||||
selection. Author the resulting code and fixtures independently.
|
||||
|
||||
Before incorporating third-party code, verify per-file license compatibility with GPL-3.0-or-later, record the exact upstream revision and original paths, preserve copyright notices and document changes. Update applicable attribution records. Public visibility alone is not proof of authorization or license compatibility.
|
||||
|
||||
## Pull requests
|
||||
|
||||
- Branch from the current main branch, keep commits focused, and link relevant issues.
|
||||
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
|
||||
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
|
||||
- Never include secrets, personal paths, credentials or private data in patches or logs.
|
||||
- Do not claim approval from an independent reviewer unless one has actually reviewed the change.
|
||||
|
||||
Sign off each commit under the [Developer Certificate of Origin](https://developercertificate.org/):
|
||||
- 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.
|
||||
- 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/):
|
||||
|
||||
```sh
|
||||
git commit -s -m "Describe the change"
|
||||
```
|
||||
|
||||
Use your configured Git identity and a privacy-preserving email address if desired. Sign-off is your certification of the contribution; do not sign off work on another person's behalf. Contributions are subject to the repository license and any applicable, compatible third-party notices.
|
||||
|
||||
For security-sensitive findings, see [SECURITY.md](SECURITY.md). Community expectations are in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
|
||||
See [AGENTS.md](AGENTS.md), [docs/legal.md](docs/legal.md), [SECURITY.md](SECURITY.md), and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
|
||||
Generated
+11
-221
@@ -3,232 +3,22 @@
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
name = "bx-cli"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"bx-probe",
|
||||
"bx-telemetry",
|
||||
"dxbc-accc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
name = "bx-probe"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
name = "bx-telemetry"
|
||||
version = "0.2.0"
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch2"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
|
||||
dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-foundation"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"dispatch2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-encode"
|
||||
version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-metal"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"objc2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "xenora"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-benchmarks"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-decoder"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-isa",
|
||||
"xenora-ref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-import-gen"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-isa"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-loader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"sha2",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-metal"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
"objc2-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
"xenora-texture",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ref"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "xenora-semantic-review"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-shader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-texture"
|
||||
version = "0.1.0"
|
||||
name = "dxbc-accc"
|
||||
version = "0.2.0"
|
||||
+13
-3
@@ -1,12 +1,22 @@
|
||||
[workspace]
|
||||
members = ["crates/*", "tests/validation", "benchmarks"]
|
||||
members = [
|
||||
"launcher/crates/bx-cli",
|
||||
"launcher/crates/bx-probe",
|
||||
"launcher/crates/bx-telemetry",
|
||||
"shader-transpiler/crates/dxbc-accc",
|
||||
]
|
||||
exclude = ["legacy-native"]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
license = "GPL-3.0-or-later"
|
||||
rust-version = "1.100"
|
||||
rust-version = "1.85"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
codegen-units = 1
|
||||
@@ -1,338 +1,234 @@
|
||||
# Xenora
|
||||
<div align="center">
|
||||
|
||||
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
|
||||
# BetterXen
|
||||
|
||||
Xenora is an open-source project written primarily in Rust, exploring native Xbox Series X|S compatibility on ARM64 macOS.
|
||||
**Modular Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS — built on CrossOver, Rosetta 2, and D3DMetal 3.0.**
|
||||
|
||||
The project combines a bounded x86-64 guest execution environment, Portable Executable (PE32+) loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml)
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml)
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||
-d29922)
|
||||

|
||||
|
||||
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
|
||||
</div>
|
||||
|
||||
Xenora is still experimental. It currently executes independently authored synthetic guest programs and shaders. **Commercial Xbox games, including Grand Theft Auto VI, do not boot.** Authentic Xbox executable loading and system-service compatibility remain unsupported.
|
||||
> [!IMPORTANT]
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project currently at **Milestone M0** (cross-compiled shim foundation and live CrossOver/Rosetta smoke tests verified on synthetic PE32+ workloads). **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
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.
|
||||
|
||||
> [!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.
|
||||
|
||||
---
|
||||
|
||||
## What works today?
|
||||
## Progress Tracker
|
||||
|
||||
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
|
||||
|
||||
The latest verified milestone includes **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, with rendered pixels compared against independently calculated reference results.
|
||||
|
||||
### Development milestones
|
||||
|
||||
| Milestone | Implementation | Status |
|
||||
| --- | --- | --- |
|
||||
| X1 — Guest CPU | Bounded x86-64 instruction execution on ARM64 macOS | Verified |
|
||||
| X2 — Executable loading | Loading original fixed-base PE32+ test executables | Verified |
|
||||
| X3 — GPU compute | Guest-submitted Metal compute workloads and readback | Verified |
|
||||
| X4 — Metal rendering | Guest-driven offscreen rendering using authored Metal shaders | Verified |
|
||||
| X5 — Guest execution expansion | Additional bounded CPU execution and fixture coverage | Implemented |
|
||||
| X6 — Guest control flow | Nested calls, returns, checked memory and synthetic PE execution | Verified |
|
||||
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
|
||||
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
|
||||
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
|
||||
| X10 — Texture sampling | Translate RDNA2 image instructions, implement samplers, mipmapping and guest-backed texture bindings | Planned |
|
||||
| X11 — Graphics pipeline | Multiple draw calls, vertex buffers, index buffers, depth/stencil testing, blending and render targets | Planned |
|
||||
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
|
||||
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
|
||||
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
|
||||
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
|
||||
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
|
||||
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subet |
|
||||
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
|
||||
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
|
||||
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
|
||||
| X21 — Application compatibility | Execute increasingly complex independently authored applications through the complete guest CPU and GPU pipeline | Planned |
|
||||
| X22 — First application boot | Establish a reproducible startup and error-reporting path for supported game-like applications | Planned |
|
||||
| X23 — Initial game compatibility | Investigate startup and execution of legally supported game software, identifying missing runtime and graphics behavior | Long-term goal |
|
||||
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
|
||||
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
|
||||
|
||||
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
|
||||
|
||||
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
|
||||
|
||||
See the [X9 acceptance matrix](docs/testing/x9-acceptance.md) for specific tests, results and unsupported behavior.
|
||||
|
||||
## Native graphics translation
|
||||
|
||||
Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
|
||||
|
||||
The translation process is:
|
||||
> *Tracks engineering milestones and synthetic conformance progress only — not commercial game compatibility percentages.*
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0: Foundation & Shims\n(Merged #406)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Active — Milestone #17)"]:::active
|
||||
M2["M2: First Frame &\nShader Gate"]:::planned
|
||||
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
|
||||
|
||||
flowchart TD
|
||||
A["Original gfx1030 Machine Code"]
|
||||
B["RDNA2 ISA Decoder"]
|
||||
C["Validated Shader IR"]
|
||||
D["Metal Shader Generation (MSL)"]
|
||||
E["Native Metal Pipeline"]
|
||||
F["Apple Silicon GPU"]
|
||||
G["GPU Readback"]
|
||||
H["Independent CPU Validation"]
|
||||
M0 --> M1 --> M2 --> M3 --> M4 --> M5 --> M6
|
||||
|
||||
A --> B
|
||||
B --> C
|
||||
C --> D
|
||||
D --> E
|
||||
E --> F
|
||||
F --> G
|
||||
G --> H
|
||||
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
|
||||
```
|
||||
|
||||
The initial implementation focused on compute shaders. X9 extends this to actual translated **vertex and fragment/pixel shader stages**.
|
||||
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
### Translated rendering
|
||||
### Active Milestone — [M1: Startup Shims to `D3D12XboxCreateDevice`](https://github.com/MacosPorters/betterxen/milestone/17)
|
||||
|
||||
The current graphics subset supports:
|
||||
| Track | Focus | Visual Status | Live Issues |
|
||||
| --- | --- | --- | --- |
|
||||
| **Track A** | `bx-cli` supervision, `clwb` VEH + crash dumper, Win32 bridge | `🟨🟨🟨` *(3/3 PRs open)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `xmem.dll` core + physical/scatter pages, `XCRDAPI.dll` DirectStorage | `🟨🟨🟨` *(3/3 PRs open)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs.dll` COM proxy (D3DMetal 3.0), `xg_xs.dll` texture computer | `⬜⬜` *(needs contributors!)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` FSPX C ABI bridge, `d3dmetal-native` harness | `🟨⬜` *(1 PR open, 1 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | `xgameruntime.dll` offline GDK, `AcpHal`/`xapu`/`chad`, `GameInput` | `🟨🟨` *(2/2 PRs open)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | End-to-end synthetic boot fixture (`test_integration_boot`) | `🟨` *(1/1 PR open)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
|
||||
- Original gfx1030 vertex and pixel shader fixtures.
|
||||
- Decoding and translation into Metal shader functions.
|
||||
- Vertex position transformation.
|
||||
- Constant-color output and clipping.
|
||||
- Interpolated vertex attributes.
|
||||
- Offscreen RGBA8 render targets.
|
||||
- Native GPU readback and pixel-by-pixel validation.
|
||||
- Explicit rejection of unsupported shader forms.
|
||||
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
|
||||
|
||||
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
|
||||
### Milestone Roadmap (M0 → M6)
|
||||
|
||||
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
|
||||
| Milestone | Scope | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 cross-compiled PE32+ shims, live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Merged (`#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`, audio queue stubs) | 🔵 **Active ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0; inspect runtime shaders to select DXIL fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation | ⚪ Planned |
|
||||
| **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 |
|
||||
|
||||
### Verified Apple M5 results
|
||||
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
|
||||
|
||||
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled.
|
||||
|
||||
Representative checks include:
|
||||
|
||||
| Test | Verified behavior |
|
||||
| --- | --- |
|
||||
| Constant-color rendering | 12 red pixels and 12 clear pixels |
|
||||
| Vertex transformation | 3 rendered pixels versus 7 for a pass-through control |
|
||||
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
|
||||
| BC1 texture handling | 33 texels across selected mip levels and array layers |
|
||||
| Guest rendering | PE32+ guest receives and checks the translated render output |
|
||||
|
||||
The expected results were calculated independently of the production shader translation path.
|
||||
|
||||
**Important:** Correct output for these fixtures does not prove general RDNA2 compatibility or correctness for arbitrary Xbox shaders.
|
||||
|
||||
## Persistent GPU resources
|
||||
|
||||
X9 introduces a bounded GPU resource-management system for synthetic guest programs.
|
||||
|
||||
The implementation includes:
|
||||
|
||||
- Generation-checked guest resource handles.
|
||||
- Buffer creation, updates, reuse and destruction.
|
||||
- Checked buffer views and memory permissions.
|
||||
- Repeated compute submissions.
|
||||
- Resource lifetime validation.
|
||||
- Snapshot behavior for queued submissions.
|
||||
- Rejection of stale handles and malformed resource requests.
|
||||
- Guest-visible readback and result verification.
|
||||
|
||||
The original X9 PE fixtures exercise these services through the guest execution environment.
|
||||
|
||||
The resource system remains experimental. Native GPU work already in flight during resource release, persistent Metal texture residency across guest calls, and general asynchronous execution are not yet implemented.
|
||||
|
||||
## Texture support
|
||||
|
||||
Xenora includes an original BC1 texture-processing path.
|
||||
|
||||
Implemented and tested functionality includes:
|
||||
|
||||
- Validated mip levels and array layers.
|
||||
- Pitched texture uploads.
|
||||
- Block-compressed texture handling.
|
||||
- Native Metal texture readback.
|
||||
- Edge-block and transparency tests.
|
||||
- Invalid descriptor and bounds rejection.
|
||||
|
||||
**Translated texture-sampling instructions are not yet implemented.**
|
||||
|
||||
The existing texture readback path uses an authored Metal kernel. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
|
||||
|
||||
Xbox-specific texture layouts and additional compression formats require further research and validation.
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
Xenora is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
|
||||
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.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Guest["Guest execution"]
|
||||
A["Original PE32+ test program"]
|
||||
B["Bounded x86-64 interpreter"]
|
||||
C["Synthetic imported services"]
|
||||
D["Validated GPU resources and commands"]
|
||||
Guest["Scarlett x86-64 PE32+ Executable"]
|
||||
|
||||
A --> B
|
||||
B --> C
|
||||
C --> D
|
||||
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"]
|
||||
end
|
||||
|
||||
subgraph Shader["RDNA2 shader translation"]
|
||||
E["Original gfx1030 shader bytes"]
|
||||
F["ISA decoder"]
|
||||
G["Validated intermediate representation"]
|
||||
H["MSL generation"]
|
||||
|
||||
E --> F
|
||||
F --> G
|
||||
G --> H
|
||||
subgraph Shaders["Shader & DXR Bridge"]
|
||||
DXIL["DXIL Fast Path (SM 6.5/6.6)"]
|
||||
ACCC["ACCC / FSPX RDNA2 Transpiler"]
|
||||
end
|
||||
|
||||
subgraph Metal["Native Apple Metal"]
|
||||
I["Compute or render pipeline"]
|
||||
J["Apple Silicon GPU"]
|
||||
K["GPU readback"]
|
||||
|
||||
D --> I
|
||||
H --> I
|
||||
I --> J
|
||||
J --> K
|
||||
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)"]
|
||||
end
|
||||
|
||||
subgraph Validation["Correctness verification"]
|
||||
L["Independent CPU reference"]
|
||||
M{"Expected output matches?"}
|
||||
CLI["bx-cli (Native ARM64 macOS Launcher, Probe & Telemetry)"]
|
||||
|
||||
E --> L
|
||||
L --> M
|
||||
K --> M
|
||||
end
|
||||
Guest --> Shims
|
||||
D3DX --> DXIL --> D3DM
|
||||
D3DX --> ACCC --> D3DM
|
||||
XMem --> Wine
|
||||
DS --> Wine
|
||||
XGR --> Wine
|
||||
Bridge --> Wine
|
||||
VEH --> Rosetta
|
||||
Wine --> Rosetta
|
||||
CLI -.->|"Launches, sets overrides, summarizes traces"| External
|
||||
```
|
||||
|
||||
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
|
||||
---
|
||||
|
||||
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
|
||||
## Repository Layout
|
||||
|
||||
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
|
||||
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.
|
||||
|
||||
| Directory | Track | Stack | Contents |
|
||||
| --- | --- | --- | --- |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 16 shim DLLs |
|
||||
| `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 |
|
||||
| `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`) |
|
||||
|
||||
---
|
||||
|
||||
## Current limitations
|
||||
|
||||
Xenora is an engineering research project, not a working commercial-game emulator.
|
||||
|
||||
The following remain unsupported or incomplete:
|
||||
|
||||
| Subsystem | Outstanding work |
|
||||
| --- | --- |
|
||||
| Guest CPU | Broad x86-64 instruction coverage, multithreading and performant dynamic recompilation |
|
||||
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
|
||||
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
|
||||
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
|
||||
| Graphics | Translated texture sampling, broader resource binding, synchronization and general draw workloads |
|
||||
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
|
||||
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
|
||||
| Game compatibility | No demonstrated execution of commercial Xbox titles |
|
||||
|
||||
Xenora's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
|
||||
|
||||
Progress is measured by reproducible tests rather than estimated game compatibility percentages.
|
||||
|
||||
---
|
||||
|
||||
## Building Xenora
|
||||
## Quick Start
|
||||
|
||||
### Requirements
|
||||
|
||||
- Apple Silicon Mac running native ARM64 macOS.
|
||||
- Rust toolchain with `aarch64-apple-darwin` support.
|
||||
- Xcode and Metal development tools.
|
||||
- Python 3.11 or newer.
|
||||
- LLVM with AMDGPU support for applicable shader-fixture assembly and verification.
|
||||
- **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.
|
||||
|
||||
The recorded Apple M5 environment uses Rust 1.100.0 and Xcode 27.2.
|
||||
|
||||
### Clone
|
||||
### Build & Verify
|
||||
|
||||
```sh
|
||||
git clone https://github.com/ranveersoni98/Xenora.git
|
||||
cd Xenora
|
||||
```
|
||||
git clone https://github.com/MacosPorters/betterxen.git
|
||||
cd betterxen
|
||||
|
||||
### Build
|
||||
|
||||
```sh
|
||||
scripts/bootstrap.sh
|
||||
cargo build --locked -p xenora
|
||||
```
|
||||
|
||||
### Run core tests
|
||||
|
||||
```sh
|
||||
# 1. Build & test the native ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
cargo build -p bx-cli
|
||||
|
||||
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
|
||||
target/debug/bx-cli doctor
|
||||
|
||||
# 3. Cross-compile all 16 x86-64 PE32+ shim DLLs + conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export and zero MinGW runtime DLL deps)
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + 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
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
```
|
||||
|
||||
### Run native Metal tests
|
||||
|
||||
These require a Metal-capable Apple Silicon Mac.
|
||||
|
||||
```sh
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
```sh
|
||||
cargo test --locked \
|
||||
--manifest-path experiments/x1/Cargo.toml \
|
||||
--target aarch64-apple-darwin \
|
||||
--features metal
|
||||
```
|
||||
|
||||
Run the original guest resource integration tests:
|
||||
|
||||
```sh
|
||||
tests/compat_fixtures/verify-resources.sh
|
||||
```
|
||||
|
||||
Additional checks:
|
||||
|
||||
```sh
|
||||
tests/compat_fixtures/verify.sh
|
||||
tests/compat_fixtures/verify-compute.sh
|
||||
scripts/assemble-fixture.sh --check
|
||||
scripts/demo.sh
|
||||
```
|
||||
|
||||
Some verification paths require additional tools. Refer to the relevant test scripts and documentation before interpreting a missing dependency as a test failure.
|
||||
|
||||
### Test evidence
|
||||
|
||||
Testing distinguishes between:
|
||||
|
||||
- **CPU correctness:** Independent expected values and bounded execution.
|
||||
- **Shader compilation:** Decoding, lowering and valid generated Metal source.
|
||||
- **Native GPU execution:** Actual GPU work and checked readback.
|
||||
- **Guest integration:** Original test executables invoking GPU services and checking results.
|
||||
- **Unsupported behavior:** Explicit rejections and documented missing functionality.
|
||||
|
||||
Compiling a shader is not equivalent to proving its GPU output is correct.
|
||||
### `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) |
|
||||
|
||||
---
|
||||
|
||||
**The goal is to build a trustworthy native Apple Silicon compatibility framework, one verifiable subsystem at a time.**
|
||||
## Contributing with Humans & Coding Agents
|
||||
|
||||
BetterXen is built for **parallel work across 5–8+ contributors and coding agents** (`AGENTS.md` — symlinked as `CLAUDE.md` — holds the full ruleset):
|
||||
|
||||
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>`.
|
||||
|
||||
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).
|
||||
|
||||
---
|
||||
|
||||
## Current Verified Scope & Limitations
|
||||
|
||||
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 16 x86-64 PE32+ shim DLLs cross-compile with zero warnings, pass strict PE Export Directory verification (102 exact names, ordinals, forwarders, 0 extra exports), and carry zero dynamic MinGW runtime dependencies.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads all 16 shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **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.
|
||||
|
||||
---
|
||||
|
||||
## Historical Native-First Research
|
||||
|
||||
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`.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Xenora is licensed under the [GNU General Public License v3 or later](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.
|
||||
|
||||
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
|
||||
|
||||
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
|
||||
|
||||
---
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, or any game publisher.
|
||||
+2
-2
@@ -2,13 +2,13 @@
|
||||
|
||||
## Scope
|
||||
|
||||
Xenora is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
|
||||
BetterXen is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
|
||||
|
||||
The project does not promise a fixed security support window at this stage. Report issues against a specific revision, preferably reproduced on current `main` where safe.
|
||||
|
||||
## Reporting vulnerabilities
|
||||
|
||||
Use [GitHub private vulnerability reporting](https://github.com/ranveersoni98/Xenora/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
|
||||
Use [GitHub private vulnerability reporting](https://github.com/MacosPorters/betterxen/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
|
||||
|
||||
Include the affected commit, environment, affected component, expected and actual behavior, impact and a minimal, authorized reproduction. Use synthetic inputs wherever possible. Do not attach protected content, leaked SDK material or proprietary shaders.
|
||||
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
# Getting help
|
||||
|
||||
Start with the [README](README.md) and the relevant documentation in the repository, if available. Xenora is an experimental research project, not a commercial game compatibility service.
|
||||
Start with the [README](README.md) and the relevant documentation in the repository, if available. BetterXen is an experimental research project, not a commercial game compatibility service.
|
||||
|
||||
- Use [GitHub Issues](https://github.com/ranveersoni98/Xenora/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
|
||||
- Use [GitHub Discussions](https://github.com/ranveersoni98/Xenora/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
|
||||
- Use [GitHub Issues](https://github.com/MacosPorters/betterxen/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
|
||||
- Use [GitHub Discussions](https://github.com/MacosPorters/betterxen/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
|
||||
- Follow [SECURITY.md](SECURITY.md) for security-sensitive reports.
|
||||
|
||||
Include the exact revision, host architecture, macOS version, relevant tool versions, steps to reproduce and sanitized output. Do not share personal paths, private account information, protected game assets, credentials or confidential material. If the reported feature is not yet implemented, identify it as a request rather than a regression.
|
||||
+8
-12
@@ -1,17 +1,13 @@
|
||||
# Third-party notices
|
||||
|
||||
| Component | Version | License | Origin and notice |
|
||||
|---|---|---|---|
|
||||
| AMD RDNA 2 machine-readable ISA | 2026-02-20, schema 1.1.1 | MIT | Generated opcode masks derive from the AMD source identified in the [RDNA 2 research notes](docs/research/rdna2.md). [AMD license and copyright](crates/isa/LICENSE-AMD). |
|
||||
| bitflags | 2.13.2 | MIT selected | [Upstream revision](https://github.com/bitflags/bitflags/tree/80ce9b545acb0bd42150695fc351889cac1d8eb4), [MIT license and copyright](licenses/bitflags-LICENSE-MIT). |
|
||||
| objc2 | 0.6.5 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/d7d2fa23ceaa5e6096c923b081040e5d81b3b9df), [upstream licensing notice](licenses/objc2-LICENSE.md). |
|
||||
| objc2-encode | 4.1.0 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/8d214f5477365ffcbcbb7de058c86ed9a518efb7), [upstream licensing notice](licenses/objc2-LICENSE.md). |
|
||||
| objc2-foundation | 0.3.2 | MIT | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
|
||||
| objc2-core-foundation | 0.3.2 | MIT selected | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
|
||||
| objc2-metal | 0.3.2 | MIT selected | [Upstream revision](https://github.com/madsmtm/objc2/tree/7b1abfd750a2cacaea71d6a56ecfb83cb7de560b), [upstream licensing notice](licenses/objc2-LICENSE.md). |
|
||||
The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) currently has **zero external crates.io dependencies** and is original `GPL-3.0-or-later` source.
|
||||
|
||||
Cargo resolves the Rust packages from crates.io at the source checksums in [Cargo.lock](Cargo.lock). The upstream objc2 notice discusses the derivation of bindings from Apple SDKs and an open question under Apple’s SDK terms. The maintainer confirmed upstream’s published license position in [issue #895](https://github.com/madsmtm/objc2/issues/895). No Apple SDK files or dependency crate archives ship in this repository. The [upstream MIT text](licenses/objc2-LICENSE-MIT.txt) is an unmodified copy from [objc2 commit ee9a7ad](https://github.com/madsmtm/objc2/blob/ee9a7ada2131f5944b8750428e265c15632f2a19/LICENSE-MIT.txt), added after the locked source revisions. Preserve it and the pinned licensing notice. See the [G11 review](docs/licenses.md#runtime-redistribution-review) for unresolved attribution and SDK questions.
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
[LLVM 23.1.6](https://github.com/llvm/llvm-project/tree/5b10d2d74929eae78912771222c9855af97496f4) is used as an external fixture tool under Apache-2.0 WITH LLVM-exception. Xcode and Metal are separate Apple tools under Apple's license terms.
|
||||
| Component | Role | Licensing & Provenance |
|
||||
| --- | --- | --- |
|
||||
| CrossOver / Wine | External macOS Windows compatibility runtime | Proprietary product with FOSS subcomponents; externally installed by the user and never bundled. See [docs/research/crossover-licensing.md](docs/research/crossover-licensing.md). |
|
||||
| Apple D3DMetal & Rosetta 2 | External Direct3D-to-Metal and x86-64 translation | Proprietary Apple components under Apple's license terms; externally installed and never bundled. |
|
||||
| `mingw-w64` & CMake | Developer cross-compilation toolchain for x86-64 PE32+ shims | Installed externally via Homebrew (`brew install mingw-w64 cmake`) for building `shims/` and `tests/conformance/`. |
|
||||
|
||||
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
|
||||
Historical third-party notices for the retired native-first workspace (including AMD RDNA 2 ISA metadata, `bitflags`, and `objc2-*`) remain preserved at Git tag `native-first-final` and are summarized in [docs/licenses.md](docs/licenses.md).
|
||||
@@ -0,0 +1,10 @@
|
||||
# BetterXen Frozen ABI Contracts (`abi/`)
|
||||
|
||||
This directory holds the **only shared interface boundary** across BetterXen's six parallel development tracks.
|
||||
|
||||
## Rules for Contributors
|
||||
|
||||
1. **ABI-First Changes:** If one track needs a new cross-DLL helper, config flag, or export symbol, open a small, focused `[ABI]` pull request touching only `abi/`.
|
||||
2. **Zero File Collisions:** Never edit another track's implementation directory in an `[ABI]` PR. Once the `[ABI]` PR merges to `main`, both provider and consumer tracks implement in parallel.
|
||||
3. **Versioned Contracts:** Increment `BX_ABI_VERSION` in `abi/include/bx_config.h` on any breaking struct or signature change.
|
||||
4. **Canonical `.def` Exports:** Every DLL under `shims/` links directly against its corresponding `abi/defs/<name>.def`. CI verifies the built PE32+ export table matches these `.def` files.
|
||||
@@ -0,0 +1,11 @@
|
||||
LIBRARY AcpHal.dll
|
||||
EXPORTS
|
||||
AcpHalCreate
|
||||
AcpHalAllocateShapeContexts
|
||||
AcpHalReleaseShapeContexts
|
||||
ApuCreateHeap
|
||||
ApuAlloc
|
||||
ApuFree
|
||||
ApuIsVirtualAddressValid
|
||||
ApuMapApuAddress
|
||||
ApuMapVirtualAddress
|
||||
@@ -0,0 +1,3 @@
|
||||
LIBRARY GameInput.dll
|
||||
EXPORTS
|
||||
GameInputCreate @1
|
||||
@@ -0,0 +1,3 @@
|
||||
LIBRARY XCRDAPI.dll
|
||||
EXPORTS
|
||||
DStorageGetFactory
|
||||
@@ -0,0 +1,4 @@
|
||||
LIBRARY api-ms-win-core-psm-appnotify-l1-1-0.dll
|
||||
EXPORTS
|
||||
RegisterAppStateChangeNotification
|
||||
UnregisterAppStateChangeNotification
|
||||
@@ -0,0 +1,4 @@
|
||||
LIBRARY api-ms-win-core-psm-appnotify-l1-1-1.dll
|
||||
EXPORTS
|
||||
RegisterAppConstrainedChangeNotification
|
||||
UnregisterAppConstrainedChangeNotification
|
||||
@@ -0,0 +1,8 @@
|
||||
LIBRARY bx_runtime_veh.dll
|
||||
EXPORTS
|
||||
bx_log_emit
|
||||
bx_log_unimpl_api
|
||||
bx_log_unimpl_vtable
|
||||
bx_get_runtime_config
|
||||
bx_veh_install
|
||||
bx_veh_get_clwb_trap_count
|
||||
@@ -0,0 +1,7 @@
|
||||
LIBRARY chad.dll
|
||||
EXPORTS
|
||||
XDspActivate
|
||||
XDspDeactivate
|
||||
XDspConnectWithMaximumStreamLimit
|
||||
XDspDisconnect
|
||||
XDspSubmitCommand
|
||||
@@ -0,0 +1,6 @@
|
||||
LIBRARY d3d12_xs.dll
|
||||
EXPORTS
|
||||
D3D12XboxCreateDevice
|
||||
D3D12ConfigureVirtualMemoryX
|
||||
D3D12SerializeVersionedRootSignature
|
||||
D3D12CreateRootSignatureDeserializer
|
||||
@@ -0,0 +1,4 @@
|
||||
LIBRARY ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll
|
||||
EXPORTS
|
||||
DispatchMessageA = user32.DispatchMessageA
|
||||
PeekMessageA = user32.PeekMessageA
|
||||
@@ -0,0 +1,3 @@
|
||||
LIBRARY ext-ms-win-rtcore-ntuser-message-l1-1-0.dll
|
||||
EXPORTS
|
||||
TranslateMessage = user32.TranslateMessage
|
||||
@@ -0,0 +1,5 @@
|
||||
LIBRARY ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll
|
||||
EXPORTS
|
||||
CreateWindowExA = user32.CreateWindowExA
|
||||
DefWindowProcA = user32.DefWindowProcA
|
||||
RegisterClassExA = user32.RegisterClassExA
|
||||
@@ -0,0 +1,3 @@
|
||||
LIBRARY ext-ms-win-rtcore-ntuser-window-l1-1-0.dll
|
||||
EXPORTS
|
||||
ShowWindow = user32.ShowWindow
|
||||
@@ -0,0 +1,7 @@
|
||||
LIBRARY xapu.dll
|
||||
EXPORTS
|
||||
XApuConnect
|
||||
XApuDisconnect
|
||||
XApuEnqueueCommand
|
||||
XApuDequeueResult
|
||||
XApuGetResultCount
|
||||
@@ -0,0 +1,4 @@
|
||||
LIBRARY xg_xs.dll
|
||||
EXPORTS
|
||||
XGCreateTextureComputer
|
||||
XGSuggestSwizzleMode
|
||||
@@ -0,0 +1,45 @@
|
||||
LIBRARY xgameruntime.dll
|
||||
EXPORTS
|
||||
XGameRuntimeInitialize
|
||||
XGameRuntimeInitializeWithOptions
|
||||
XGameRuntimeUninitialize
|
||||
XTaskQueueCreate
|
||||
XTaskQueueCloseHandle
|
||||
XTaskQueueDispatch
|
||||
XTaskQueueSubmitCallback
|
||||
XTaskQueueGetCurrentProcessTaskQueue
|
||||
XAsyncGetStatus
|
||||
XAsyncGetResultSize
|
||||
XAsyncCancel
|
||||
XUserAddAsync
|
||||
XUserAddResult
|
||||
XUserCloseHandle
|
||||
XUserGetId
|
||||
XUserGetGamertag
|
||||
XUserGetTokenAndSignatureAsync
|
||||
XUserGetTokenAndSignatureResultSize
|
||||
XUserGetTokenAndSignatureResult
|
||||
XUserResolvePrivilegeWithUiAsync
|
||||
XUserResolvePrivilegeWithUiResult
|
||||
XStoreCreateContext
|
||||
XStoreCloseContextHandle
|
||||
XStoreQueryGameLicenseAsync
|
||||
XStoreQueryGameLicenseResult
|
||||
XStoreAcquireLicenseForPackageAsync
|
||||
XStoreAcquireLicenseForPackageResult
|
||||
XStoreAcquireLicenseForDurablesAsync
|
||||
XStoreAcquireLicenseForDurablesResult
|
||||
XStoreQueryEntitledProductsAsync
|
||||
XStoreQueryEntitledProductsResult
|
||||
XStoreQueryAssociatedProductsAsync
|
||||
XStoreQueryAssociatedProductsResult
|
||||
XSystemGetConsoleId
|
||||
XSystemGetDeviceType
|
||||
XSystemGetXboxLiveSandboxId
|
||||
XPersistentLocalStorageGetPathSize
|
||||
XPersistentLocalStorageGetPath
|
||||
XPersistentLocalStorageGetSpaceInfo
|
||||
XGameUiShowPlayerProfileCardAsync
|
||||
XGameUiShowTextEntryAsync
|
||||
XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync
|
||||
XNetworkingQuerySecurityInformationForUrlAsync
|
||||
@@ -0,0 +1,17 @@
|
||||
LIBRARY xmem.dll
|
||||
EXPORTS
|
||||
XMemAlloc
|
||||
XMemAllocDefault
|
||||
XMemAllocatePhysicalPages
|
||||
XMemFree
|
||||
XMemFreeDefault
|
||||
XMemFreePhysicalPages
|
||||
XMemGetWorkingSetStatistics
|
||||
XMemIsToolsMemAvailable
|
||||
XMemMapPhysicalPages
|
||||
XMemMapPhysicalPagesScatter
|
||||
XMemTransferMemory
|
||||
XMemVirtualAlloc
|
||||
XMemVirtualQuery
|
||||
bx_xmem_query_region
|
||||
bx_xmem_get_internal_stats
|
||||
@@ -0,0 +1,48 @@
|
||||
#ifndef BETTERXEN_BX_CONFIG_H
|
||||
#define BETTERXEN_BX_CONFIG_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define BX_ABI_VERSION 1u
|
||||
|
||||
/* Environment variables configured by bx-cli when launching under CrossOver/Wine. */
|
||||
#define BX_ENV_PROFILE "BX_PROFILE" /* "lockhart" (default) | "anaconda" */
|
||||
#define BX_ENV_LOG_FILE "BX_LOG_FILE" /* Path to JSONL/text trace log inside guest */
|
||||
#define BX_ENV_LOG_LEVEL "BX_LOG_LEVEL" /* "error" | "warn" | "info" | "trace" */
|
||||
#define BX_ENV_TRACE_D3D "BX_TRACE_D3D" /* "1" to trace every COM call */
|
||||
#define BX_ENV_SHADER_DUMP_DIR "BX_SHADER_DUMP_DIR" /* Optional local dump dir for shader blobs */
|
||||
#define BX_ENV_MEM_LIMIT_MB "BX_MEM_LIMIT_MB" /* Override reported title working-set cap */
|
||||
#define BX_ENV_RT_MODE "BX_RT_MODE" /* "rebuild" | "bypass" */
|
||||
|
||||
typedef enum bx_hardware_profile {
|
||||
BX_PROFILE_LOCKHART = 0, /* Series S memory budget (~8-10 GB; default on 16 GB hosts) */
|
||||
BX_PROFILE_ANACONDA = 1 /* Series X memory budget (~13.5 GB; opt-in on 32 GB+ hosts) */
|
||||
} bx_hardware_profile_t;
|
||||
|
||||
typedef enum bx_log_level {
|
||||
BX_LOG_ERROR = 0,
|
||||
BX_LOG_WARN = 1,
|
||||
BX_LOG_INFO = 2,
|
||||
BX_LOG_TRACE = 3
|
||||
} bx_log_level_t;
|
||||
|
||||
typedef struct bx_runtime_config {
|
||||
uint32_t abi_version;
|
||||
bx_hardware_profile_t profile;
|
||||
bx_log_level_t log_level;
|
||||
uint64_t title_memory_limit_bytes;
|
||||
uint32_t trace_d3d;
|
||||
uint32_t enable_clwb_veh;
|
||||
uint32_t enable_adx_tripwire;
|
||||
uint32_t reserved;
|
||||
} bx_runtime_config_t;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* BETTERXEN_BX_CONFIG_H */
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef BETTERXEN_BX_LOG_H
|
||||
#define BETTERXEN_BX_LOG_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include "bx_config.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Structured runtime diagnostics exported by bx_runtime_veh.dll and consumed
|
||||
* by all other BetterXen shim DLLs (via dynamic lookup or import library).
|
||||
*/
|
||||
void bx_log_emit(bx_log_level_t level, const char* subsystem, const char* event, const char* detail);
|
||||
void bx_log_unimpl_api(const char* dll_name, const char* symbol_name);
|
||||
void bx_log_unimpl_vtable(const char* iface_name, uint32_t slot_index, const char* method_name);
|
||||
const bx_runtime_config_t* bx_get_runtime_config(void);
|
||||
|
||||
#define BX_STUB_LOG(dll, sym) bx_log_unimpl_api((dll), (sym))
|
||||
#define BX_VTABLE_STUB_LOG(iface, slot, method) bx_log_unimpl_vtable((iface), (slot), (method))
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* BETTERXEN_BX_LOG_H */
|
||||
@@ -0,0 +1,83 @@
|
||||
#ifndef BETTERXEN_BX_SHADER_BRIDGE_H
|
||||
#define BETTERXEN_BX_SHADER_BRIDGE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* C ABI contract between Track C (d3d12_xs.dll) and Track D (shader-transpiler).
|
||||
* Used at Create*PipelineState / CreateStateObject time to inspect shader blobs
|
||||
* (DXBC+DXIL vs DXBC+ACCC/FSPX RDNA2 ISA) and translate console-compiled shaders
|
||||
* into D3DMetal-consumable DXIL (or report unsupported forms cleanly).
|
||||
*/
|
||||
|
||||
typedef enum bx_shader_kind {
|
||||
BX_SHADER_UNKNOWN = 0,
|
||||
BX_SHADER_DXBC_DXIL = 1, /* Standard DXIL inside DXBC container (fast path to D3DMetal) */
|
||||
BX_SHADER_DXBC_LEGACY = 2, /* Legacy SM5 SHDR/SHEX inside DXBC */
|
||||
BX_SHADER_DXBC_ACCC = 3, /* Console-compiled AMD RDNA2 (ACCC / FSPX) without DXIL */
|
||||
BX_SHADER_DXBC_DUAL = 4 /* Contains both DXIL and ACCC chunks */
|
||||
} bx_shader_kind_t;
|
||||
|
||||
typedef enum bx_shader_stage {
|
||||
BX_STAGE_UNKNOWN = 0,
|
||||
BX_STAGE_PIXEL = 1,
|
||||
BX_STAGE_VERTEX = 2,
|
||||
BX_STAGE_GEOM = 3,
|
||||
BX_STAGE_HULL = 4,
|
||||
BX_STAGE_DOMAIN = 5,
|
||||
BX_STAGE_COMPUTE = 6,
|
||||
BX_STAGE_LIBRARY = 7,
|
||||
BX_STAGE_MESH = 8,
|
||||
BX_STAGE_AMP = 9
|
||||
} bx_shader_stage_t;
|
||||
|
||||
typedef struct bx_shader_inspection {
|
||||
bx_shader_kind_t kind;
|
||||
bx_shader_stage_t stage;
|
||||
uint32_t shader_model_major;
|
||||
uint32_t shader_model_minor;
|
||||
uint32_t container_size;
|
||||
uint32_t dxil_chunk_size;
|
||||
uint32_t accc_chunk_size;
|
||||
uint32_t has_root_signature;
|
||||
uint8_t digest_hash[16]; /* DXBC header digest or SHA-like key for caching */
|
||||
} bx_shader_inspection_t;
|
||||
|
||||
typedef enum bx_shader_status {
|
||||
BX_SHADER_OK = 0,
|
||||
BX_SHADER_ERR_INVALID_BLOB = 1,
|
||||
BX_SHADER_ERR_UNSUPPORTED = 2,
|
||||
BX_SHADER_ERR_TRANSLATE = 3,
|
||||
BX_SHADER_ERR_OOM = 4
|
||||
} bx_shader_status_t;
|
||||
|
||||
/* Inspect a raw shader bytecode blob without allocating. */
|
||||
bx_shader_status_t bx_shader_inspect(
|
||||
const uint8_t* bytes,
|
||||
size_t len,
|
||||
bx_shader_inspection_t* out_info
|
||||
);
|
||||
|
||||
/*
|
||||
* Convert an incoming console shader blob into a D3DMetal-compatible DXBC/DXIL blob.
|
||||
* On BX_SHADER_OK, caller must free `*out_bytes` with `bx_shader_free_buffer`.
|
||||
*/
|
||||
bx_shader_status_t bx_shader_prepare_for_d3dmetal(
|
||||
const uint8_t* in_bytes,
|
||||
size_t in_len,
|
||||
uint8_t** out_bytes,
|
||||
size_t* out_len
|
||||
);
|
||||
|
||||
void bx_shader_free_buffer(uint8_t* ptr, size_t len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* BETTERXEN_BX_SHADER_BRIDGE_H */
|
||||
@@ -0,0 +1,43 @@
|
||||
#ifndef BETTERXEN_BX_XMEM_INTERNAL_H
|
||||
#define BETTERXEN_BX_XMEM_INTERNAL_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Internal cross-DLL contract between Track B (xmem.dll) and Track C (d3d12_xs.dll).
|
||||
* Allows d3d12_xs placed-resource and virtual-memory translation to query allocations
|
||||
* created through XMemVirtualAlloc / XMemAllocatePhysicalPages / XMemMapPhysicalPages.
|
||||
*/
|
||||
|
||||
typedef struct bx_xmem_region_info {
|
||||
uint64_t base_va;
|
||||
uint64_t size_bytes;
|
||||
uint64_t page_size_bytes;
|
||||
uint32_t protect_flags;
|
||||
uint32_t mem_type_flags;
|
||||
uint64_t physical_tag;
|
||||
} bx_xmem_region_info_t;
|
||||
|
||||
typedef struct bx_xmem_stats {
|
||||
uint64_t title_limit_bytes;
|
||||
uint64_t committed_virtual_bytes;
|
||||
uint64_t allocated_physical_bytes;
|
||||
uint64_t peak_committed_bytes;
|
||||
} bx_xmem_stats_t;
|
||||
|
||||
/* 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. */
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* BETTERXEN_BX_XMEM_INTERNAL_H */
|
||||
@@ -1,19 +0,0 @@
|
||||
[package]
|
||||
name = "xenora-benchmarks"
|
||||
description = "Correctness-gated native Metal benchmark harness for the Phase 01 corpus"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "xenora-bench"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
xenora-shader = { path = "../crates/shader" }
|
||||
xenora-ref = { path = "../crates/ref" }
|
||||
xenora-metal = { path = "../crates/metal" }
|
||||
@@ -1,51 +0,0 @@
|
||||
# Benchmark corpus for the Phase 01 correctness-gated harness.
|
||||
#
|
||||
# Supported subset: `[[fixture]]` tables with string and integer-array values.
|
||||
# A shader is timed only after it passes correctness in the same run. `sizes`
|
||||
# are word counts for the one-invocation-per-word synthetic ABI.
|
||||
# See docs/testing/benchmarks.md for the protocol and metadata fields.
|
||||
|
||||
[[fixture]]
|
||||
name = "add"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/add.bin"
|
||||
input = [0, 1, 4294967295, 3989547400]
|
||||
expected = [305419896, 305419897, 305419895, 0]
|
||||
sizes = [4, 64, 256, 1024, 4096]
|
||||
|
||||
[[fixture]]
|
||||
name = "bitwise-branch"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/bitwise-branch.bin"
|
||||
input = [0, 1, 4294967295, 3989547400]
|
||||
expected = [305419896, 305419897, 315315847, 318723824]
|
||||
sizes = [4, 64, 256, 1024, 4096]
|
||||
|
||||
[[fixture]]
|
||||
name = "float-exact"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/float-exact.bin"
|
||||
input = [0, 1, 4294967295, 3989547400]
|
||||
expected = [1091305472, 1091305472, 1092616192, 1092616192]
|
||||
sizes = [4, 64, 256, 1024, 4096]
|
||||
|
||||
[[fixture]]
|
||||
name = "or"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/or.bin"
|
||||
input = [0, 1, 4294967295, 2153054378, 2141912917, 2147483648, 5570730]
|
||||
expected = [2153054378, 2153054379, 4294967295, 2153054378, 4294967295, 2153054378, 2153054378]
|
||||
sizes = [7, 64, 256, 1024, 4096]
|
||||
|
||||
[[fixture]]
|
||||
name = "shifts"
|
||||
stage = "compute"
|
||||
source = "translated-rdna"
|
||||
path = "fixtures/rdna2/shifts.bin"
|
||||
input = [0, 1, 2, 30, 31, 32, 33, 63, 64, 2147483648, 2147483681, 4294967295]
|
||||
expected = [2, 1073741830, 536870924, 3221225474, 2147483649, 2, 1073741830, 2147483649, 2, 2, 1073741830, 2147483649]
|
||||
sizes = [12, 64, 256, 1024, 4096]
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"run_id": "run-1795338391",
|
||||
"timestamp": "unix:1795338391",
|
||||
"device": "Apple M5",
|
||||
"host_arch": "aarch64",
|
||||
"os_version": "27.3",
|
||||
"os_build": "26C5047e",
|
||||
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew)",
|
||||
"xcode": "Xcode 27.2",
|
||||
"commit": "a34dadcbc06b696eae0d7b743845f4a2c9e67996",
|
||||
"profile": "release",
|
||||
"api_validation": "0",
|
||||
"shader_validation": "0",
|
||||
"power": "Battery Power",
|
||||
"thermal": "no warnings recorded",
|
||||
"reps": 7,
|
||||
"warmup": 2
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
# Xenora benchmark report
|
||||
|
||||
Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol.
|
||||
|
||||
## Environment
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Device | Apple M5 |
|
||||
| Host arch | aarch64 |
|
||||
| macOS | 27.3 |
|
||||
| Build | 26C5047e |
|
||||
| Rust | rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew) |
|
||||
| Xcode | Xcode 27.2 |
|
||||
| Commit | a34dadcbc06b696eae0d7b743845f4a2c9e67996 |
|
||||
| Profile | release |
|
||||
| API validation | 0 |
|
||||
| Shader validation | 0 |
|
||||
| Power source | Battery Power |
|
||||
| Thermal | no warnings recorded |
|
||||
| Repetitions | 7 measured, 2 warm-up |
|
||||
|
||||
> **Protocol note.** The machine was not confirmed on AC power. The [benchmark protocol](../../../../docs/testing/benchmarks.md) requires AC power, so these timings are not protocol-compliant release evidence.
|
||||
|
||||
## Coverage
|
||||
|
||||
| Fixture | Stage | Source | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| add | compute | translated-rdna | benchmarked |
|
||||
| bitwise-branch | compute | translated-rdna | benchmarked |
|
||||
| float-exact | compute | translated-rdna | benchmarked |
|
||||
|
||||
## Timings
|
||||
|
||||
Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, `library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer GPU time, and `host` is the wall time of one dispatch. Values are medians with interquartile range; minimum and maximum are in `results.json`.
|
||||
|
||||
| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| add | 4 | 5.42 | 15.04 | 36.33 | 6.08 | 525.50 | 0.29 | 0% |
|
||||
| add | 64 | 4.54 | 11.83 | 28.17 | 6.08 | 529.92 | 0.06 | 0% |
|
||||
| add | 256 | 4.46 | 11.42 | 27.33 | 5.88 | 519.17 | 0.19 | 0% |
|
||||
| add | 1024 | 4.42 | 11.21 | 26.88 | 6.12 | 524.38 | 0.13 | 0% |
|
||||
| add | 4096 | 4.38 | 11.17 | 27.92 | 6.25 | 523.58 | 0.08 | 0% |
|
||||
| bitwise-branch | 4 | 11.38 | 13.00 | 28.96 | 6.12 | 509.37 | 0.00 | 0% |
|
||||
| bitwise-branch | 64 | 7.75 | 11.33 | 26.92 | 6.12 | 526.50 | 0.02 | 0% |
|
||||
| bitwise-branch | 256 | 7.71 | 11.21 | 26.62 | 6.00 | 513.71 | 0.02 | 0% |
|
||||
| bitwise-branch | 1024 | 7.54 | 11.25 | 26.58 | 6.25 | 519.62 | 0.02 | 0% |
|
||||
| bitwise-branch | 4096 | 7.58 | 11.21 | 27.25 | 6.21 | 523.33 | 0.04 | 0% |
|
||||
| float-exact | 4 | 9.12 | 12.08 | 27.12 | 6.17 | 510.67 | 0.10 | 0% |
|
||||
| float-exact | 64 | 8.58 | 11.46 | 26.50 | 6.04 | 523.79 | 0.06 | 0% |
|
||||
| float-exact | 256 | 8.58 | 11.12 | 26.46 | 6.04 | 514.92 | 0.08 | 0% |
|
||||
| float-exact | 1024 | 8.67 | 11.12 | 26.29 | 6.21 | 520.67 | 0.08 | 0% |
|
||||
| float-exact | 4096 | 8.67 | 11.17 | 26.46 | 6.25 | 514.67 | 0.08 | 0% |
|
||||
@@ -1,46 +0,0 @@
|
||||
{
|
||||
"fixtures": [
|
||||
{
|
||||
"name": "add",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [
|
||||
{ "words": 4, "compile": { "median": 5.417000000e-6, "min": 4.875000000e-6, "max": 7.833000000e-6, "q1": 4.979500000e-6, "q3": 6.250500000e-6, "reps": 7 }, "library": { "median": 1.504200000e-5, "min": 1.254200000e-5, "max": 2.141700000e-5, "q1": 1.339600000e-5, "q3": 1.706300000e-5, "reps": 7 }, "pipeline": { "median": 3.633300000e-5, "min": 3.175000000e-5, "max": 4.900000000e-5, "q1": 3.245800000e-5, "q3": 4.106200000e-5, "reps": 7 }, "gpu": { "median": 6.083333574e-6, "min": 5.791662261e-6, "max": 6.125002983e-6, "q1": 5.833335308e-6, "q3": 6.124995707e-6, "reps": 7 }, "host": { "median": 5.255000000e-4, "min": 5.083750000e-4, "max": 5.870000000e-4, "q1": 5.120210000e-4, "q3": 5.354790000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 64, "compile": { "median": 4.542000000e-6, "min": 4.417000000e-6, "max": 4.584000000e-6, "q1": 4.500000000e-6, "q3": 4.562500000e-6, "reps": 7 }, "library": { "median": 1.183300000e-5, "min": 1.158300000e-5, "max": 1.204200000e-5, "q1": 1.172900000e-5, "q3": 1.191650000e-5, "reps": 7 }, "pipeline": { "median": 2.816700000e-5, "min": 2.779200000e-5, "max": 3.250000000e-5, "q1": 2.814550000e-5, "q3": 2.933350000e-5, "reps": 7 }, "gpu": { "median": 6.083333574e-6, "min": 5.750000128e-6, "max": 6.125002983e-6, "q1": 6.041664165e-6, "q3": 6.104164640e-6, "reps": 7 }, "host": { "median": 5.299160000e-4, "min": 4.869160000e-4, "max": 5.916250000e-4, "q1": 5.180835000e-4, "q3": 5.309585000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 256, "compile": { "median": 4.459000000e-6, "min": 4.375000000e-6, "max": 7.542000000e-6, "q1": 4.458000000e-6, "q3": 4.521000000e-6, "reps": 7 }, "library": { "median": 1.141700000e-5, "min": 1.120900000e-5, "max": 1.412500000e-5, "q1": 1.133350000e-5, "q3": 1.147900000e-5, "reps": 7 }, "pipeline": { "median": 2.733400000e-5, "min": 2.695800000e-5, "max": 2.758400000e-5, "q1": 2.706250000e-5, "q3": 2.750000000e-5, "reps": 7 }, "gpu": { "median": 5.875001079e-6, "min": 5.750000128e-6, "max": 6.000002031e-6, "q1": 5.791665899e-6, "q3": 5.979163689e-6, "reps": 7 }, "host": { "median": 5.191670000e-4, "min": 5.010000000e-4, "max": 5.346670000e-4, "q1": 5.137080000e-4, "q3": 5.276670000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 1024, "compile": { "median": 4.417000000e-6, "min": 4.250000000e-6, "max": 7.583000000e-6, "q1": 4.354500000e-6, "q3": 4.521000000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.091700000e-5, "max": 1.300000000e-5, "q1": 1.110400000e-5, "q3": 1.129150000e-5, "reps": 7 }, "pipeline": { "median": 2.687500000e-5, "min": 2.666600000e-5, "max": 3.350000000e-5, "q1": 2.670800000e-5, "q3": 2.716650000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.041664165e-6, "max": 6.208334526e-6, "q1": 6.062498869e-6, "q3": 6.187499821e-6, "reps": 7 }, "host": { "median": 5.243750000e-4, "min": 4.802500000e-4, "max": 6.343750000e-4, "q1": 5.193130000e-4, "q3": 5.442295000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 4096, "compile": { "median": 4.375000000e-6, "min": 4.250000000e-6, "max": 4.500000000e-6, "q1": 4.333000000e-6, "q3": 4.416500000e-6, "reps": 7 }, "library": { "median": 1.116600000e-5, "min": 1.095800000e-5, "max": 1.145900000e-5, "q1": 1.106250000e-5, "q3": 1.120800000e-5, "reps": 7 }, "pipeline": { "median": 2.791700000e-5, "min": 2.716700000e-5, "max": 3.229100000e-5, "q1": 2.743700000e-5, "q3": 2.833300000e-5, "reps": 7 }, "gpu": { "median": 6.249996659e-6, "min": 6.125002983e-6, "max": 6.250003935e-6, "q1": 6.166665116e-6, "q3": 6.250000297e-6, "reps": 7 }, "host": { "median": 5.235830000e-4, "min": 5.008330000e-4, "max": 5.484590000e-4, "q1": 5.165830000e-4, "q3": 5.246875000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "bitwise-branch",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [
|
||||
{ "words": 4, "compile": { "median": 1.137500000e-5, "min": 8.125000000e-6, "max": 1.562500000e-5, "q1": 8.875000000e-6, "q3": 1.214650000e-5, "reps": 7 }, "library": { "median": 1.300000000e-5, "min": 1.150000000e-5, "max": 2.495800000e-5, "q1": 1.214600000e-5, "q3": 1.556200000e-5, "reps": 7 }, "pipeline": { "median": 2.895800000e-5, "min": 2.704200000e-5, "max": 5.566600000e-5, "q1": 2.762500000e-5, "q3": 3.600050000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.083333574e-6, "max": 6.208334526e-6, "q1": 6.124995707e-6, "q3": 6.125002983e-6, "reps": 7 }, "host": { "median": 5.093750000e-4, "min": 4.334590000e-4, "max": 5.999590000e-4, "q1": 4.986045000e-4, "q3": 5.409170000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 64, "compile": { "median": 7.750000000e-6, "min": 7.542000000e-6, "max": 7.917000000e-6, "q1": 7.625000000e-6, "q3": 7.771000000e-6, "reps": 7 }, "library": { "median": 1.133300000e-5, "min": 1.100000000e-5, "max": 1.158300000e-5, "q1": 1.127100000e-5, "q3": 1.141650000e-5, "reps": 7 }, "pipeline": { "median": 2.691600000e-5, "min": 2.641700000e-5, "max": 2.754200000e-5, "q1": 2.679150000e-5, "q3": 2.706200000e-5, "reps": 7 }, "gpu": { "median": 6.124995707e-6, "min": 6.000002031e-6, "max": 6.166665116e-6, "q1": 6.104164640e-6, "q3": 6.125002983e-6, "reps": 7 }, "host": { "median": 5.265000000e-4, "min": 4.912500000e-4, "max": 5.496250000e-4, "q1": 5.206460000e-4, "q3": 5.289170000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 256, "compile": { "median": 7.708000000e-6, "min": 7.583000000e-6, "max": 7.917000000e-6, "q1": 7.625000000e-6, "q3": 7.771000000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.091600000e-5, "max": 1.170900000e-5, "q1": 1.104150000e-5, "q3": 1.127100000e-5, "reps": 7 }, "pipeline": { "median": 2.662500000e-5, "min": 2.637500000e-5, "max": 2.679100000e-5, "q1": 2.652050000e-5, "q3": 2.666650000e-5, "reps": 7 }, "gpu": { "median": 6.000002031e-6, "min": 5.999994755e-6, "max": 6.124995707e-6, "q1": 6.000002031e-6, "q3": 6.020833098e-6, "reps": 7 }, "host": { "median": 5.137080000e-4, "min": 5.058750000e-4, "max": 5.431250000e-4, "q1": 5.129375000e-4, "q3": 5.265415000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 1024, "compile": { "median": 7.542000000e-6, "min": 7.416000000e-6, "max": 1.337500000e-5, "q1": 7.458500000e-6, "q3": 7.645500000e-6, "reps": 7 }, "library": { "median": 1.125000000e-5, "min": 1.091700000e-5, "max": 1.137500000e-5, "q1": 1.100000000e-5, "q3": 1.127100000e-5, "reps": 7 }, "pipeline": { "median": 2.658300000e-5, "min": 2.641700000e-5, "max": 2.945900000e-5, "q1": 2.652100000e-5, "q3": 2.668750000e-5, "reps": 7 }, "gpu": { "median": 6.250003935e-6, "min": 6.166665116e-6, "max": 6.250003935e-6, "q1": 6.229165592e-6, "q3": 6.250003935e-6, "reps": 7 }, "host": { "median": 5.196250000e-4, "min": 4.705420000e-4, "max": 5.796250000e-4, "q1": 4.989585000e-4, "q3": 5.451670000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 4096, "compile": { "median": 7.583000000e-6, "min": 7.458000000e-6, "max": 7.625000000e-6, "q1": 7.541500000e-6, "q3": 7.604500000e-6, "reps": 7 }, "library": { "median": 1.120900000e-5, "min": 1.100000000e-5, "max": 1.129200000e-5, "q1": 1.114600000e-5, "q3": 1.127050000e-5, "reps": 7 }, "pipeline": { "median": 2.725000000e-5, "min": 2.645900000e-5, "max": 3.054200000e-5, "q1": 2.693750000e-5, "q3": 2.866700000e-5, "reps": 7 }, "gpu": { "median": 6.208334526e-6, "min": 6.166672392e-6, "max": 6.333335477e-6, "q1": 6.208330888e-6, "q3": 6.250003935e-6, "reps": 7 }, "host": { "median": 5.233330000e-4, "min": 4.921660000e-4, "max": 5.424170000e-4, "q1": 5.017080000e-4, "q3": 5.346455000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "float-exact",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [
|
||||
{ "words": 4, "compile": { "median": 9.125000000e-6, "min": 8.667000000e-6, "max": 1.658300000e-5, "q1": 8.812500000e-6, "q3": 1.385400000e-5, "reps": 7 }, "library": { "median": 1.208400000e-5, "min": 1.141600000e-5, "max": 1.837500000e-5, "q1": 1.166650000e-5, "q3": 1.229150000e-5, "reps": 7 }, "pipeline": { "median": 2.712500000e-5, "min": 2.662500000e-5, "max": 2.866700000e-5, "q1": 2.677050000e-5, "q3": 2.743750000e-5, "reps": 7 }, "gpu": { "median": 6.166665116e-6, "min": 5.958332622e-6, "max": 6.250003935e-6, "q1": 6.125002983e-6, "q3": 6.229165592e-6, "reps": 7 }, "host": { "median": 5.106660000e-4, "min": 4.910840000e-4, "max": 6.143750000e-4, "q1": 5.022500000e-4, "q3": 5.370625000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 64, "compile": { "median": 8.583000000e-6, "min": 8.541000000e-6, "max": 1.425000000e-5, "q1": 8.583000000e-6, "q3": 8.687500000e-6, "reps": 7 }, "library": { "median": 1.145800000e-5, "min": 1.116700000e-5, "max": 1.187500000e-5, "q1": 1.131200000e-5, "q3": 1.164600000e-5, "reps": 7 }, "pipeline": { "median": 2.650000000e-5, "min": 2.620800000e-5, "max": 2.725000000e-5, "q1": 2.631300000e-5, "q3": 2.700000000e-5, "reps": 7 }, "gpu": { "median": 6.041671440e-6, "min": 5.916670489e-6, "max": 6.125002983e-6, "q1": 6.041664165e-6, "q3": 6.104164640e-6, "reps": 7 }, "host": { "median": 5.237920000e-4, "min": 4.042920000e-4, "max": 5.358750000e-4, "q1": 5.191665000e-4, "q3": 5.336665000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 256, "compile": { "median": 8.583000000e-6, "min": 8.500000000e-6, "max": 8.834000000e-6, "q1": 8.562000000e-6, "q3": 8.708500000e-6, "reps": 7 }, "library": { "median": 1.112500000e-5, "min": 1.091600000e-5, "max": 1.129200000e-5, "q1": 1.110450000e-5, "q3": 1.120850000e-5, "reps": 7 }, "pipeline": { "median": 2.645900000e-5, "min": 2.629200000e-5, "max": 2.658400000e-5, "q1": 2.641650000e-5, "q3": 2.652100000e-5, "reps": 7 }, "gpu": { "median": 6.041664165e-6, "min": 5.999994755e-6, "max": 6.083333574e-6, "q1": 6.000002031e-6, "q3": 6.083333574e-6, "reps": 7 }, "host": { "median": 5.149170000e-4, "min": 5.000000000e-4, "max": 5.907500000e-4, "q1": 5.053955000e-4, "q3": 5.300000000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 1024, "compile": { "median": 8.667000000e-6, "min": 8.500000000e-6, "max": 8.792000000e-6, "q1": 8.583500000e-6, "q3": 8.791500000e-6, "reps": 7 }, "library": { "median": 1.112500000e-5, "min": 1.104100000e-5, "max": 1.120900000e-5, "q1": 1.106250000e-5, "q3": 1.114600000e-5, "reps": 7 }, "pipeline": { "median": 2.629200000e-5, "min": 2.612500000e-5, "max": 2.637500000e-5, "q1": 2.625000000e-5, "q3": 2.635400000e-5, "reps": 7 }, "gpu": { "median": 6.208327250e-6, "min": 6.000002031e-6, "max": 6.250003935e-6, "q1": 6.145830412e-6, "q3": 6.229169230e-6, "reps": 7 }, "host": { "median": 5.206670000e-4, "min": 5.023330000e-4, "max": 5.300840000e-4, "q1": 5.051045000e-4, "q3": 5.258955000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 4096, "compile": { "median": 8.667000000e-6, "min": 8.458000000e-6, "max": 8.750000000e-6, "q1": 8.542000000e-6, "q3": 8.687500000e-6, "reps": 7 }, "library": { "median": 1.116700000e-5, "min": 1.100000000e-5, "max": 1.133400000e-5, "q1": 1.108350000e-5, "q3": 1.125000000e-5, "reps": 7 }, "pipeline": { "median": 2.645800000e-5, "min": 2.595900000e-5, "max": 2.691600000e-5, "q1": 2.641700000e-5, "q3": 2.658350000e-5, "reps": 7 }, "gpu": { "median": 6.250003935e-6, "min": 6.166665116e-6, "max": 6.375004887e-6, "q1": 6.250000297e-6, "q3": 6.333331839e-6, "reps": 7 }, "host": { "median": 5.146670000e-4, "min": 4.975000000e-4, "max": 5.337500000e-4, "q1": 5.105415000e-4, "q3": 5.209795000e-4, "reps": 7 }, "gpu_zero_fraction": 0.0000 }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"run_id": "run-1795352394",
|
||||
"timestamp": "unix:1795352394",
|
||||
"device": "Apple M5",
|
||||
"host_arch": "aarch64",
|
||||
"os_version": "27.3",
|
||||
"os_build": "26C5047e",
|
||||
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew)",
|
||||
"xcode": "Xcode 27.2",
|
||||
"commit": "cc0daa79e63c468e748f0333bd1314224752893a",
|
||||
"profile": "release",
|
||||
"api_validation": "0",
|
||||
"shader_validation": "0",
|
||||
"power": "AC Power",
|
||||
"thermal": "no warnings recorded",
|
||||
"reps": 21,
|
||||
"warmup": 2
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
# Xenora benchmark report
|
||||
|
||||
Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol.
|
||||
|
||||
## Environment
|
||||
|
||||
| Field | Value |
|
||||
| --- | --- |
|
||||
| Device | Apple M5 |
|
||||
| Host arch | aarch64 |
|
||||
| macOS | 27.3 |
|
||||
| Build | 26C5047e |
|
||||
| Rust | rustc 1.100.0 (0ef1bc386 2026-11-09) (Homebrew) |
|
||||
| Xcode | Xcode 27.2 |
|
||||
| Commit | cc0daa79e63c468e748f0333bd1314224752893a |
|
||||
| Profile | release |
|
||||
| API validation | 0 |
|
||||
| Shader validation | 0 |
|
||||
| Power source | AC Power |
|
||||
| Thermal | no warnings recorded |
|
||||
| Repetitions | 21 measured, 2 warm-up |
|
||||
|
||||
## Coverage
|
||||
|
||||
| Fixture | Stage | Source | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| add | compute | translated-rdna | benchmarked |
|
||||
| bitwise-branch | compute | translated-rdna | benchmarked |
|
||||
| float-exact | compute | translated-rdna | benchmarked |
|
||||
|
||||
## Timings
|
||||
|
||||
Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, `library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer GPU time, and `host` is the wall time of one dispatch. Values are medians with interquartile range; minimum and maximum are in `results.json`.
|
||||
|
||||
| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| add | 4 | 5.08 | 13.42 | 32.50 | 87.62 | 375.33 | 103.62 | 0% |
|
||||
| add | 64 | 4.42 | 11.79 | 28.25 | 3.63 | 407.79 | 36.54 | 0% |
|
||||
| add | 256 | 4.17 | 10.96 | 26.79 | 1.38 | 231.25 | 2.25 | 0% |
|
||||
| add | 1024 | 4.25 | 11.17 | 26.54 | 1.46 | 218.25 | 0.08 | 0% |
|
||||
| add | 4096 | 4.46 | 11.67 | 27.62 | 3.38 | 237.71 | 17.63 | 0% |
|
||||
| bitwise-branch | 4 | 7.71 | 11.04 | 26.29 | 1.33 | 214.29 | 0.08 | 0% |
|
||||
| bitwise-branch | 64 | 8.71 | 11.92 | 27.83 | 2.08 | 213.12 | 4.25 | 0% |
|
||||
| bitwise-branch | 256 | 7.58 | 10.71 | 26.00 | 1.37 | 216.38 | 0.04 | 0% |
|
||||
| bitwise-branch | 1024 | 7.62 | 10.67 | 26.08 | 1.42 | 212.58 | 0.08 | 0% |
|
||||
| bitwise-branch | 4096 | 7.62 | 11.12 | 26.58 | 1.58 | 236.17 | 25.75 | 0% |
|
||||
| float-exact | 4 | 8.54 | 10.88 | 25.62 | 1.33 | 212.00 | 0.08 | 0% |
|
||||
| float-exact | 64 | 8.71 | 11.00 | 26.21 | 1.38 | 215.33 | 1.25 | 0% |
|
||||
| float-exact | 256 | 8.62 | 10.83 | 25.83 | 1.37 | 213.88 | 0.08 | 0% |
|
||||
| float-exact | 1024 | 8.54 | 11.00 | 25.92 | 1.50 | 213.67 | 0.04 | 0% |
|
||||
| float-exact | 4096 | 8.54 | 10.88 | 26.04 | 1.50 | 228.00 | 30.25 | 0% |
|
||||
@@ -1,46 +0,0 @@
|
||||
{
|
||||
"fixtures": [
|
||||
{
|
||||
"name": "add",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [
|
||||
{ "words": 4, "compile": { "median": 5.083000000e-6, "min": 4.167000000e-6, "max": 4.425000000e-5, "q1": 4.375000000e-6, "q3": 7.458000000e-6, "reps": 21 }, "library": { "median": 1.341700000e-5, "min": 1.087500000e-5, "max": 3.879200000e-5, "q1": 1.150000000e-5, "q3": 1.762500000e-5, "reps": 21 }, "pipeline": { "median": 3.250000000e-5, "min": 2.666700000e-5, "max": 5.920800000e-5, "q1": 2.979200000e-5, "q3": 4.262500000e-5, "reps": 21 }, "gpu": { "median": 8.762499965e-5, "min": 5.625000085e-6, "max": 2.230416667e-4, "q1": 1.562500074e-5, "q3": 1.192500004e-4, "reps": 21 }, "host": { "median": 3.753330000e-4, "min": 2.814590000e-4, "max": 5.746250000e-4, "q1": 3.609170000e-4, "q3": 4.326250000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 64, "compile": { "median": 4.416000000e-6, "min": 4.083000000e-6, "max": 5.792000000e-6, "q1": 4.292000000e-6, "q3": 4.542000000e-6, "reps": 21 }, "library": { "median": 1.179100000e-5, "min": 1.075000000e-5, "max": 1.741600000e-5, "q1": 1.116700000e-5, "q3": 1.312500000e-5, "reps": 21 }, "pipeline": { "median": 2.825000000e-5, "min": 2.591700000e-5, "max": 3.758400000e-5, "q1": 2.770800000e-5, "q3": 3.100000000e-5, "reps": 21 }, "gpu": { "median": 3.625000318e-6, "min": 3.125000148e-6, "max": 3.708750000e-4, "q1": 3.208333510e-6, "q3": 3.974999981e-5, "reps": 21 }, "host": { "median": 4.077910000e-4, "min": 2.125000000e-4, "max": 8.305420000e-4, "q1": 3.319170000e-4, "q3": 4.473340000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 256, "compile": { "median": 4.167000000e-6, "min": 4.083000000e-6, "max": 4.333000000e-6, "q1": 4.166000000e-6, "q3": 4.208000000e-6, "reps": 21 }, "library": { "median": 1.095800000e-5, "min": 1.054200000e-5, "max": 1.154200000e-5, "q1": 1.062500000e-5, "q3": 1.116600000e-5, "reps": 21 }, "pipeline": { "median": 2.679200000e-5, "min": 2.583400000e-5, "max": 3.391600000e-5, "q1": 2.612500000e-5, "q3": 2.716600000e-5, "reps": 21 }, "gpu": { "median": 1.375000465e-6, "min": 1.291666194e-6, "max": 5.875000170e-6, "q1": 1.374999556e-6, "q3": 3.625000318e-6, "reps": 21 }, "host": { "median": 2.312500000e-4, "min": 2.123750000e-4, "max": 7.405830000e-4, "q1": 2.190830000e-4, "q3": 6.997080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 1024, "compile": { "median": 4.250000000e-6, "min": 4.083000000e-6, "max": 6.292000000e-6, "q1": 4.167000000e-6, "q3": 4.333000000e-6, "reps": 21 }, "library": { "median": 1.116700000e-5, "min": 1.054200000e-5, "max": 1.583400000e-5, "q1": 1.075000000e-5, "q3": 1.133300000e-5, "reps": 21 }, "pipeline": { "median": 2.654200000e-5, "min": 2.566700000e-5, "max": 3.695800000e-5, "q1": 2.583300000e-5, "q3": 2.758300000e-5, "reps": 21 }, "gpu": { "median": 1.458333827e-6, "min": 1.375000465e-6, "max": 5.999999303e-6, "q1": 1.416667146e-6, "q3": 1.500000508e-6, "reps": 21 }, "host": { "median": 2.182500000e-4, "min": 2.122920000e-4, "max": 5.624590000e-4, "q1": 2.162090000e-4, "q3": 2.354590000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 4096, "compile": { "median": 4.458000000e-6, "min": 4.125000000e-6, "max": 1.104100000e-5, "q1": 4.250000000e-6, "q3": 4.833000000e-6, "reps": 21 }, "library": { "median": 1.166700000e-5, "min": 1.083300000e-5, "max": 7.970800000e-5, "q1": 1.120900000e-5, "q3": 1.337500000e-5, "reps": 21 }, "pipeline": { "median": 2.762500000e-5, "min": 2.645800000e-5, "max": 7.595800000e-5, "q1": 2.683300000e-5, "q3": 3.045800000e-5, "reps": 21 }, "gpu": { "median": 3.375000233e-6, "min": 1.375000465e-6, "max": 3.787499918e-5, "q1": 1.499999598e-6, "q3": 1.912500011e-5, "reps": 21 }, "host": { "median": 2.377080000e-4, "min": 2.014170000e-4, "max": 5.690830000e-4, "q1": 2.298750000e-4, "q3": 3.332910000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "bitwise-branch",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [
|
||||
{ "words": 4, "compile": { "median": 7.709000000e-6, "min": 7.416000000e-6, "max": 1.133300000e-5, "q1": 7.542000000e-6, "q3": 8.083000000e-6, "reps": 21 }, "library": { "median": 1.104100000e-5, "min": 1.054100000e-5, "max": 1.454200000e-5, "q1": 1.079200000e-5, "q3": 1.112500000e-5, "reps": 21 }, "pipeline": { "median": 2.629200000e-5, "min": 2.554100000e-5, "max": 3.658400000e-5, "q1": 2.612500000e-5, "q3": 2.637500000e-5, "reps": 21 }, "gpu": { "median": 1.333332875e-6, "min": 1.291666194e-6, "max": 1.926666664e-4, "q1": 1.291667104e-6, "q3": 1.374999556e-6, "reps": 21 }, "host": { "median": 2.142920000e-4, "min": 2.040840000e-4, "max": 4.722500000e-4, "q1": 2.110840000e-4, "q3": 2.197500000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 64, "compile": { "median": 8.708000000e-6, "min": 7.584000000e-6, "max": 4.979100000e-5, "q1": 7.834000000e-6, "q3": 1.245800000e-5, "reps": 21 }, "library": { "median": 1.191700000e-5, "min": 1.075000000e-5, "max": 7.475000000e-5, "q1": 1.141700000e-5, "q3": 1.362500000e-5, "reps": 21 }, "pipeline": { "median": 2.783400000e-5, "min": 2.591700000e-5, "max": 5.308300000e-5, "q1": 2.716700000e-5, "q3": 2.954100000e-5, "reps": 21 }, "gpu": { "median": 2.083333129e-6, "min": 1.249999514e-6, "max": 4.854166673e-5, "q1": 1.333333785e-6, "q3": 5.583333405e-6, "reps": 21 }, "host": { "median": 2.131250000e-4, "min": 1.608750000e-4, "max": 4.971250000e-4, "q1": 1.936660000e-4, "q3": 2.450420000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 256, "compile": { "median": 7.583000000e-6, "min": 7.416000000e-6, "max": 7.750000000e-6, "q1": 7.500000000e-6, "q3": 7.625000000e-6, "reps": 21 }, "library": { "median": 1.070900000e-5, "min": 1.050000000e-5, "max": 1.104100000e-5, "q1": 1.062500000e-5, "q3": 1.079200000e-5, "reps": 21 }, "pipeline": { "median": 2.600000000e-5, "min": 2.541700000e-5, "max": 2.670800000e-5, "q1": 2.583300000e-5, "q3": 2.625000000e-5, "reps": 21 }, "gpu": { "median": 1.374999556e-6, "min": 1.291666194e-6, "max": 1.458333827e-6, "q1": 1.333332875e-6, "q3": 1.375000465e-6, "reps": 21 }, "host": { "median": 2.163750000e-4, "min": 2.042920000e-4, "max": 2.393750000e-4, "q1": 2.125830000e-4, "q3": 2.197080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 1024, "compile": { "median": 7.625000000e-6, "min": 7.500000000e-6, "max": 7.875000000e-6, "q1": 7.500000000e-6, "q3": 7.625000000e-6, "reps": 21 }, "library": { "median": 1.066700000e-5, "min": 1.050000000e-5, "max": 1.091700000e-5, "q1": 1.058400000e-5, "q3": 1.083400000e-5, "reps": 21 }, "pipeline": { "median": 2.608300000e-5, "min": 2.533300000e-5, "max": 3.291700000e-5, "q1": 2.558300000e-5, "q3": 2.620800000e-5, "reps": 21 }, "gpu": { "median": 1.416667146e-6, "min": 1.374999556e-6, "max": 9.749999663e-6, "q1": 1.375000465e-6, "q3": 1.458332918e-6, "reps": 21 }, "host": { "median": 2.125830000e-4, "min": 1.951250000e-4, "max": 4.068340000e-4, "q1": 2.102090000e-4, "q3": 2.148750000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 4096, "compile": { "median": 7.625000000e-6, "min": 7.417000000e-6, "max": 3.583300000e-5, "q1": 7.584000000e-6, "q3": 8.375000000e-6, "reps": 21 }, "library": { "median": 1.112500000e-5, "min": 1.062500000e-5, "max": 4.820800000e-5, "q1": 1.079200000e-5, "q3": 1.212500000e-5, "reps": 21 }, "pipeline": { "median": 2.658400000e-5, "min": 2.570900000e-5, "max": 1.125830000e-4, "q1": 2.595800000e-5, "q3": 2.954200000e-5, "reps": 21 }, "gpu": { "median": 1.583332960e-6, "min": 1.374999556e-6, "max": 6.262500028e-5, "q1": 1.416667146e-6, "q3": 2.716666677e-5, "reps": 21 }, "host": { "median": 2.361670000e-4, "min": 1.970840000e-4, "max": 5.112080000e-4, "q1": 2.251670000e-4, "q3": 2.410000000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "float-exact",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [
|
||||
{ "words": 4, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.233400000e-5, "q1": 8.417000000e-6, "q3": 8.875000000e-6, "reps": 21 }, "library": { "median": 1.087500000e-5, "min": 1.050000000e-5, "max": 1.500000000e-5, "q1": 1.079100000e-5, "q3": 1.120800000e-5, "reps": 21 }, "pipeline": { "median": 2.562500000e-5, "min": 2.520900000e-5, "max": 3.454100000e-5, "q1": 2.554200000e-5, "q3": 2.575000000e-5, "reps": 21 }, "gpu": { "median": 1.333333785e-6, "min": 1.291666194e-6, "max": 1.797083332e-4, "q1": 1.291667104e-6, "q3": 1.374999556e-6, "reps": 21 }, "host": { "median": 2.120000000e-4, "min": 2.052920000e-4, "max": 4.474160000e-4, "q1": 2.097500000e-4, "q3": 2.153330000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 64, "compile": { "median": 8.708000000e-6, "min": 8.416000000e-6, "max": 3.125000000e-5, "q1": 8.500000000e-6, "q3": 9.625000000e-6, "reps": 21 }, "library": { "median": 1.100000000e-5, "min": 1.058400000e-5, "max": 5.441600000e-5, "q1": 1.075000000e-5, "q3": 1.225000000e-5, "reps": 21 }, "pipeline": { "median": 2.620800000e-5, "min": 2.516700000e-5, "max": 7.550000000e-5, "q1": 2.533300000e-5, "q3": 2.858300000e-5, "reps": 21 }, "gpu": { "median": 1.375000465e-6, "min": 1.291666194e-6, "max": 4.275000083e-5, "q1": 1.375000465e-6, "q3": 2.625000889e-6, "reps": 21 }, "host": { "median": 2.153330000e-4, "min": 1.642920000e-4, "max": 4.004580000e-4, "q1": 2.005830000e-4, "q3": 2.202080000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 256, "compile": { "median": 8.625000000e-6, "min": 8.208000000e-6, "max": 8.750000000e-6, "q1": 8.459000000e-6, "q3": 8.667000000e-6, "reps": 21 }, "library": { "median": 1.083400000e-5, "min": 1.066700000e-5, "max": 1.120900000e-5, "q1": 1.075000000e-5, "q3": 1.104200000e-5, "reps": 21 }, "pipeline": { "median": 2.583300000e-5, "min": 2.504200000e-5, "max": 3.329200000e-5, "q1": 2.529100000e-5, "q3": 2.595900000e-5, "reps": 21 }, "gpu": { "median": 1.374999556e-6, "min": 1.291666194e-6, "max": 7.387500045e-5, "q1": 1.291666194e-6, "q3": 1.375000465e-6, "reps": 21 }, "host": { "median": 2.138750000e-4, "min": 1.780830000e-4, "max": 2.769590000e-4, "q1": 1.977920000e-4, "q3": 2.193750000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 1024, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.145900000e-5, "q1": 8.458000000e-6, "q3": 8.666000000e-6, "reps": 21 }, "library": { "median": 1.100000000e-5, "min": 1.062500000e-5, "max": 1.925000000e-5, "q1": 1.083400000e-5, "q3": 1.108300000e-5, "reps": 21 }, "pipeline": { "median": 2.591600000e-5, "min": 2.516700000e-5, "max": 3.541700000e-5, "q1": 2.579200000e-5, "q3": 2.612500000e-5, "reps": 21 }, "gpu": { "median": 1.499999598e-6, "min": 1.374999556e-6, "max": 1.624999641e-6, "q1": 1.458332918e-6, "q3": 1.500000508e-6, "reps": 21 }, "host": { "median": 2.136670000e-4, "min": 1.936670000e-4, "max": 4.228330000e-4, "q1": 2.092920000e-4, "q3": 2.170420000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 },
|
||||
{ "words": 4096, "compile": { "median": 8.542000000e-6, "min": 8.292000000e-6, "max": 1.158300000e-5, "q1": 8.459000000e-6, "q3": 8.750000000e-6, "reps": 21 }, "library": { "median": 1.087500000e-5, "min": 1.066700000e-5, "max": 3.562500000e-5, "q1": 1.083400000e-5, "q3": 1.145800000e-5, "reps": 21 }, "pipeline": { "median": 2.604200000e-5, "min": 2.508300000e-5, "max": 1.914590000e-4, "q1": 2.550000000e-5, "q3": 2.625000000e-5, "reps": 21 }, "gpu": { "median": 1.500000508e-6, "min": 1.416666237e-6, "max": 6.304166618e-5, "q1": 1.458332918e-6, "q3": 3.170833315e-5, "reps": 21 }, "host": { "median": 2.280000000e-4, "min": 1.988340000e-4, "max": 8.358750000e-4, "q1": 2.237090000e-4, "q3": 2.523330000e-4, "reps": 21 }, "gpu_zero_fraction": 0.0000 }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,743 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Correctness-gated benchmark harness for the Phase 01 corpus.
|
||||
//!
|
||||
//! Reads `benchmarks/manifest.toml`, verifies every fixture against the
|
||||
//! independent reference and the native GPU before timing it, then writes
|
||||
//! metadata, raw JSON and a generated markdown report. A fixture that fails
|
||||
//! correctness is excluded and listed as such; it is never timed.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
const WARMUP_REPS: usize = 2;
|
||||
const DEFAULT_REPS: usize = 7;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Fixture {
|
||||
name: String,
|
||||
stage: String,
|
||||
source: String,
|
||||
path: String,
|
||||
input: Vec<u32>,
|
||||
expected: Vec<u32>,
|
||||
sizes: Vec<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Stats {
|
||||
median: f64,
|
||||
min: f64,
|
||||
max: f64,
|
||||
q1: f64,
|
||||
q3: f64,
|
||||
reps: usize,
|
||||
}
|
||||
|
||||
impl Stats {
|
||||
fn from_samples(mut samples: Vec<f64>) -> Self {
|
||||
if samples.is_empty() {
|
||||
return Self::default();
|
||||
}
|
||||
samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let n = samples.len();
|
||||
let median = percentile(&samples, 0.5);
|
||||
Self {
|
||||
median,
|
||||
min: samples[0],
|
||||
max: samples[n - 1],
|
||||
q1: percentile(&samples, 0.25),
|
||||
q3: percentile(&samples, 0.75),
|
||||
reps: n,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn percentile(sorted: &[f64], fraction: f64) -> f64 {
|
||||
if sorted.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let position = fraction * (sorted.len() - 1) as f64;
|
||||
let lower = position.floor() as usize;
|
||||
let upper = position.ceil() as usize;
|
||||
if lower == upper {
|
||||
sorted[lower]
|
||||
} else {
|
||||
let weight = position - lower as f64;
|
||||
sorted[lower] * (1.0 - weight) + sorted[upper] * weight
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct SizeResult {
|
||||
words: usize,
|
||||
compile: Stats,
|
||||
library: Stats,
|
||||
pipeline: Stats,
|
||||
gpu: Stats,
|
||||
host: Stats,
|
||||
/// Fraction of samples whose GPU timestamp delta was zero.
|
||||
gpu_zero_fraction: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct FixtureResult {
|
||||
name: String,
|
||||
stage: String,
|
||||
source: String,
|
||||
status: String,
|
||||
reason: String,
|
||||
sizes: Vec<SizeResult>,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut output = PathBuf::from("benchmarks/results");
|
||||
let mut reps = DEFAULT_REPS;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
"--output" => {
|
||||
output = PathBuf::from(args.next().ok_or("--output needs a path")?);
|
||||
}
|
||||
"--reps" => {
|
||||
reps = args
|
||||
.next()
|
||||
.ok_or("--reps needs a count")?
|
||||
.parse()
|
||||
.map_err(|_| "--reps must be a positive integer")?;
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!("usage: xenora-bench [--output DIR] [--reps N]");
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(format!("unknown argument {other}").into()),
|
||||
}
|
||||
}
|
||||
if reps == 0 {
|
||||
return Err("--reps must be at least 1".into());
|
||||
}
|
||||
|
||||
let manifest_text = fs::read_to_string("benchmarks/manifest.toml")?;
|
||||
let fixtures = parse_manifest(&manifest_text)?;
|
||||
if fixtures.is_empty() {
|
||||
return Err("manifest lists no fixtures".into());
|
||||
}
|
||||
|
||||
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
|
||||
let device = metal.device_name();
|
||||
let metadata = Metadata::collect(&device, reps);
|
||||
|
||||
let mut results = Vec::with_capacity(fixtures.len());
|
||||
for fixture in &fixtures {
|
||||
results.push(run_fixture(&metal, fixture, reps));
|
||||
}
|
||||
|
||||
let run_id = metadata.run_id.clone();
|
||||
let hardware_dir = slug(&device);
|
||||
let run_dir = output.join(&hardware_dir).join(&run_id);
|
||||
fs::create_dir_all(&run_dir)?;
|
||||
|
||||
fs::write(run_dir.join("metadata.json"), metadata.to_json())?;
|
||||
fs::write(run_dir.join("results.json"), results_json(&results))?;
|
||||
fs::write(
|
||||
run_dir.join("report.md"),
|
||||
report_markdown(&metadata, &results),
|
||||
)?;
|
||||
|
||||
println!("Benchmark results written to {}", run_dir.display());
|
||||
for result in &results {
|
||||
println!(
|
||||
" {:<16} {:<10} {}",
|
||||
result.name,
|
||||
result.status,
|
||||
if result.reason.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("({})", result.reason)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
let excluded = results.iter().filter(|r| r.status != "benchmarked").count();
|
||||
if excluded > 0 {
|
||||
return Err(format!("{excluded} fixture(s) excluded from timing").into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> FixtureResult {
|
||||
let mut result = FixtureResult {
|
||||
name: fixture.name.clone(),
|
||||
stage: fixture.stage.clone(),
|
||||
source: fixture.source.clone(),
|
||||
status: "not-implemented".to_string(),
|
||||
reason: String::new(),
|
||||
sizes: Vec::new(),
|
||||
};
|
||||
|
||||
let code = match fs::read(&fixture.path) {
|
||||
Ok(code) => code,
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("cannot read {}: {error}", fixture.path);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
let compiled = match compile(Architecture::Gfx1030, &code) {
|
||||
Ok(compiled) => compiled,
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("compile failed: {error}");
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
// Independent reference on the declared base input.
|
||||
let reference = match xenora_ref::execute(&code, &fixture.input) {
|
||||
Ok(reference) => reference,
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("reference execution failed: {error}");
|
||||
return result;
|
||||
}
|
||||
};
|
||||
if reference != fixture.expected {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = "reference disagrees with hand-derived expected values".to_string();
|
||||
return result;
|
||||
}
|
||||
|
||||
// Native correctness at the smallest declared size before any timing.
|
||||
let base_words = *fixture.sizes.first().unwrap_or(&fixture.input.len());
|
||||
let base_input = expand(&fixture.input, base_words);
|
||||
let base_expected = expand(&fixture.expected, base_words);
|
||||
match metal.run_words(&compiled.msl, ENTRY_POINT, &base_input) {
|
||||
Ok(actual) if actual == base_expected => {}
|
||||
Ok(_) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = "GPU output disagrees with known answers".to_string();
|
||||
return result;
|
||||
}
|
||||
Err(error) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = format!("GPU execution failed: {error}");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
let mut sizes = Vec::with_capacity(fixture.sizes.len());
|
||||
for &words in &fixture.sizes {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let mut compile_samples = Vec::with_capacity(reps);
|
||||
let mut library_samples = Vec::with_capacity(reps);
|
||||
let mut pipeline_samples = Vec::with_capacity(reps);
|
||||
let mut gpu_samples = Vec::with_capacity(reps);
|
||||
let mut host_samples = Vec::with_capacity(reps);
|
||||
let mut gpu_zero = 0usize;
|
||||
|
||||
let mut mismatch = None;
|
||||
for rep in 0..(WARMUP_REPS + reps) {
|
||||
let compile_start = std::time::Instant::now();
|
||||
let recompiled = match compile(Architecture::Gfx1030, &code) {
|
||||
Ok(compiled) => compiled,
|
||||
Err(error) => {
|
||||
mismatch = Some(format!("compile failed at {words} words: {error}"));
|
||||
break;
|
||||
}
|
||||
};
|
||||
let compile_seconds = compile_start.elapsed().as_secs_f64();
|
||||
|
||||
let profile = match metal.run_words_profiled(&recompiled.msl, ENTRY_POINT, &input) {
|
||||
Ok(profile) => profile,
|
||||
Err(error) => {
|
||||
mismatch = Some(format!("GPU run failed at {words} words: {error}"));
|
||||
break;
|
||||
}
|
||||
};
|
||||
if profile.output != expected {
|
||||
mismatch = Some(format!("GPU mismatch at {words} words"));
|
||||
break;
|
||||
}
|
||||
if rep < WARMUP_REPS {
|
||||
continue;
|
||||
}
|
||||
compile_samples.push(compile_seconds);
|
||||
library_samples.push(profile.library_seconds);
|
||||
pipeline_samples.push(profile.pipeline_seconds);
|
||||
gpu_samples.push(profile.gpu_seconds);
|
||||
host_samples.push(profile.host_seconds);
|
||||
if profile.gpu_seconds <= 0.0 {
|
||||
gpu_zero += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(reason) = mismatch {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = reason;
|
||||
return result;
|
||||
}
|
||||
|
||||
let measured = gpu_samples.len();
|
||||
sizes.push(SizeResult {
|
||||
words,
|
||||
compile: Stats::from_samples(compile_samples),
|
||||
library: Stats::from_samples(library_samples),
|
||||
pipeline: Stats::from_samples(pipeline_samples),
|
||||
gpu: Stats::from_samples(gpu_samples),
|
||||
host: Stats::from_samples(host_samples),
|
||||
gpu_zero_fraction: if measured == 0 {
|
||||
0.0
|
||||
} else {
|
||||
gpu_zero as f64 / measured as f64
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
result.sizes = sizes;
|
||||
result.status = "benchmarked".to_string();
|
||||
result
|
||||
}
|
||||
|
||||
fn expand(base: &[u32], words: usize) -> Vec<u32> {
|
||||
(0..words).map(|i| base[i % base.len()]).collect()
|
||||
}
|
||||
|
||||
// --- Manifest parsing (documented subset: [[fixture]] tables, string and int arrays) ---
|
||||
|
||||
fn parse_manifest(text: &str) -> Result<Vec<Fixture>, String> {
|
||||
let mut fixtures = Vec::new();
|
||||
let mut current: Option<Fixture> = None;
|
||||
for (line_no, raw) in text.lines().enumerate() {
|
||||
let line = raw.split('#').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line == "[[fixture]]" {
|
||||
if let Some(fixture) = current.take() {
|
||||
fixtures.push(finish(fixture, line_no)?);
|
||||
}
|
||||
current = Some(Fixture {
|
||||
name: String::new(),
|
||||
stage: String::new(),
|
||||
source: String::new(),
|
||||
path: String::new(),
|
||||
input: Vec::new(),
|
||||
expected: Vec::new(),
|
||||
sizes: Vec::new(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let Some(fixture) = current.as_mut() else {
|
||||
return Err(format!(
|
||||
"line {}: key outside a [[fixture]] table",
|
||||
line_no + 1
|
||||
));
|
||||
};
|
||||
let (key, value) = line
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("line {}: expected key = value", line_no + 1))?;
|
||||
let key = key.trim();
|
||||
let value = value.trim();
|
||||
match key {
|
||||
"name" => fixture.name = parse_string(value)?,
|
||||
"stage" => fixture.stage = parse_string(value)?,
|
||||
"source" => fixture.source = parse_string(value)?,
|
||||
"path" => fixture.path = parse_string(value)?,
|
||||
"input" => fixture.input = parse_int_array(value)?,
|
||||
"expected" => fixture.expected = parse_int_array(value)?,
|
||||
"sizes" => {
|
||||
fixture.sizes = parse_int_array(value)?
|
||||
.into_iter()
|
||||
.map(|n| n as usize)
|
||||
.collect();
|
||||
}
|
||||
other => return Err(format!("line {}: unknown key {other}", line_no + 1)),
|
||||
}
|
||||
}
|
||||
if let Some(fixture) = current.take() {
|
||||
fixtures.push(finish(fixture, 0)?);
|
||||
}
|
||||
Ok(fixtures)
|
||||
}
|
||||
|
||||
fn finish(fixture: Fixture, line_no: usize) -> Result<Fixture, String> {
|
||||
let context = if fixture.name.is_empty() {
|
||||
format!("fixture ending near line {line_no}")
|
||||
} else {
|
||||
format!("fixture {}", fixture.name)
|
||||
};
|
||||
if fixture.name.is_empty()
|
||||
|| fixture.stage.is_empty()
|
||||
|| fixture.source.is_empty()
|
||||
|| fixture.path.is_empty()
|
||||
{
|
||||
return Err(format!("{context}: missing required string field"));
|
||||
}
|
||||
if fixture.input.is_empty() || fixture.expected.len() != fixture.input.len() {
|
||||
return Err(format!(
|
||||
"{context}: input and expected must be equal-length"
|
||||
));
|
||||
}
|
||||
if fixture.sizes.is_empty() || fixture.sizes.contains(&0) {
|
||||
return Err(format!(
|
||||
"{context}: sizes must be a nonempty list of positive integers"
|
||||
));
|
||||
}
|
||||
Ok(fixture)
|
||||
}
|
||||
|
||||
fn parse_string(value: &str) -> Result<String, String> {
|
||||
let trimmed = value.trim();
|
||||
let inner = trimmed
|
||||
.strip_prefix('"')
|
||||
.and_then(|v| v.strip_suffix('"'))
|
||||
.ok_or_else(|| format!("expected a quoted string, got {trimmed}"))?;
|
||||
Ok(inner.to_string())
|
||||
}
|
||||
|
||||
fn parse_int_array(value: &str) -> Result<Vec<u32>, String> {
|
||||
let trimmed = value.trim();
|
||||
let inner = trimmed
|
||||
.strip_prefix('[')
|
||||
.and_then(|v| v.strip_suffix(']'))
|
||||
.ok_or_else(|| format!("expected an integer array, got {trimmed}"))?;
|
||||
if inner.trim().is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
inner
|
||||
.split(',')
|
||||
.map(|item| {
|
||||
item.trim()
|
||||
.parse::<u32>()
|
||||
.map_err(|_| format!("invalid integer {}", item.trim()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// --- Metadata and output ---
|
||||
|
||||
struct Metadata {
|
||||
run_id: String,
|
||||
timestamp: String,
|
||||
device: String,
|
||||
host_arch: String,
|
||||
os_version: String,
|
||||
os_build: String,
|
||||
rustc: String,
|
||||
xcode: String,
|
||||
commit: String,
|
||||
profile: String,
|
||||
api_validation: String,
|
||||
shader_validation: String,
|
||||
power: String,
|
||||
thermal: String,
|
||||
reps: usize,
|
||||
warmup: usize,
|
||||
}
|
||||
|
||||
impl Metadata {
|
||||
fn collect(device: &str, reps: usize) -> Self {
|
||||
let seconds = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
Self {
|
||||
run_id: format!("run-{seconds}"),
|
||||
timestamp: format!("unix:{seconds}"),
|
||||
device: device.to_string(),
|
||||
host_arch: std::env::consts::ARCH.to_string(),
|
||||
os_version: command_line("sw_vers", &["-productVersion"]),
|
||||
os_build: command_line("sw_vers", &["-buildVersion"]),
|
||||
rustc: command_line("rustc", &["-vV"])
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("unknown")
|
||||
.to_string(),
|
||||
xcode: command_line("xcodebuild", &["-version"])
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("unknown")
|
||||
.to_string(),
|
||||
commit: command_line("git", &["rev-parse", "HEAD"]),
|
||||
profile: if cfg!(debug_assertions) {
|
||||
"debug"
|
||||
} else {
|
||||
"release"
|
||||
}
|
||||
.to_string(),
|
||||
api_validation: env_or("MTL_DEBUG_LAYER"),
|
||||
shader_validation: env_or("MTL_SHADER_VALIDATION"),
|
||||
power: power_source(),
|
||||
thermal: thermal_state(),
|
||||
reps,
|
||||
warmup: WARMUP_REPS,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> String {
|
||||
format!(
|
||||
"{{\n \"run_id\": {},\n \"timestamp\": {},\n \"device\": {},\n \"host_arch\": {},\n \"os_version\": {},\n \"os_build\": {},\n \"rustc\": {},\n \"xcode\": {},\n \"commit\": {},\n \"profile\": {},\n \"api_validation\": {},\n \"shader_validation\": {},\n \"power\": {},\n \"thermal\": {},\n \"reps\": {},\n \"warmup\": {}\n}}\n",
|
||||
json_str(&self.run_id),
|
||||
json_str(&self.timestamp),
|
||||
json_str(&self.device),
|
||||
json_str(&self.host_arch),
|
||||
json_str(&self.os_version),
|
||||
json_str(&self.os_build),
|
||||
json_str(&self.rustc),
|
||||
json_str(&self.xcode),
|
||||
json_str(&self.commit),
|
||||
json_str(&self.profile),
|
||||
json_str(&self.api_validation),
|
||||
json_str(&self.shader_validation),
|
||||
json_str(&self.power),
|
||||
json_str(&self.thermal),
|
||||
self.reps,
|
||||
self.warmup
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn command_line(program: &str, args: &[&str]) -> String {
|
||||
match Command::new(program).args(args).output() {
|
||||
Ok(output) if output.status.success() => {
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string()
|
||||
}
|
||||
_ => "unavailable".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn env_or(key: &str) -> String {
|
||||
std::env::var(key).unwrap_or_else(|_| "unset".to_string())
|
||||
}
|
||||
|
||||
/// Report the power source line from `pmset`, or `unavailable` off macOS.
|
||||
fn power_source() -> String {
|
||||
let output = command_line("pmset", &["-g", "batt"]);
|
||||
for line in output.lines() {
|
||||
let line = line.trim();
|
||||
if line.contains("AC Power") {
|
||||
return "AC Power".to_string();
|
||||
}
|
||||
if line.contains("Battery Power") {
|
||||
return "Battery Power".to_string();
|
||||
}
|
||||
}
|
||||
"unavailable".to_string()
|
||||
}
|
||||
|
||||
/// Report the CPU thermal and speed limits from `pmset`, compactly.
|
||||
fn thermal_state() -> String {
|
||||
let output = command_line("pmset", &["-g", "therm"]);
|
||||
let mut parts = Vec::new();
|
||||
for line in output.lines() {
|
||||
let line = line.trim();
|
||||
for key in ["CPU_Scheduler_Limit", "CPU_Speed_Limit"] {
|
||||
if let Some(value) = line.strip_prefix(key) {
|
||||
parts.push(format!("{key}{}", value.trim()));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !parts.is_empty() {
|
||||
parts.join(", ")
|
||||
} else if output.contains("No thermal warning level has been recorded") {
|
||||
"no warnings recorded".to_string()
|
||||
} else {
|
||||
"unavailable".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn slug(device: &str) -> String {
|
||||
device
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
c.to_ascii_lowercase()
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect::<String>()
|
||||
.trim_matches('-')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn json_str(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 2);
|
||||
out.push('"');
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => {
|
||||
let _ = write!(out, "\\u{:04x}", c as u32);
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
fn stats_json(stats: &Stats) -> String {
|
||||
format!(
|
||||
"{{ \"median\": {:.9e}, \"min\": {:.9e}, \"max\": {:.9e}, \"q1\": {:.9e}, \"q3\": {:.9e}, \"reps\": {} }}",
|
||||
stats.median, stats.min, stats.max, stats.q1, stats.q3, stats.reps
|
||||
)
|
||||
}
|
||||
|
||||
fn results_json(results: &[FixtureResult]) -> String {
|
||||
let mut out = String::from("{\n \"fixtures\": [\n");
|
||||
for (index, result) in results.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {{\n \"name\": {},\n \"stage\": {},\n \"source\": {},\n \"status\": {},\n \"reason\": {},\n \"sizes\": [",
|
||||
json_str(&result.name),
|
||||
json_str(&result.stage),
|
||||
json_str(&result.source),
|
||||
json_str(&result.status),
|
||||
json_str(&result.reason)
|
||||
);
|
||||
for (size_index, size) in result.sizes.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
|
||||
size.words,
|
||||
stats_json(&size.compile),
|
||||
stats_json(&size.library),
|
||||
stats_json(&size.pipeline),
|
||||
stats_json(&size.gpu),
|
||||
stats_json(&size.host),
|
||||
size.gpu_zero_fraction,
|
||||
if size_index + 1 == result.sizes.len() {
|
||||
""
|
||||
} else {
|
||||
","
|
||||
}
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" ]\n }}{}",
|
||||
if index + 1 == results.len() { "" } else { "," }
|
||||
);
|
||||
}
|
||||
out.push_str(" ]\n}\n");
|
||||
out
|
||||
}
|
||||
|
||||
fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "# Xenora benchmark report");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
|
||||
Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Environment");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "| Field | Value |");
|
||||
let _ = writeln!(out, "| --- | --- |");
|
||||
for (key, value) in [
|
||||
("Device", metadata.device.as_str()),
|
||||
("Host arch", metadata.host_arch.as_str()),
|
||||
("macOS", metadata.os_version.as_str()),
|
||||
("Build", metadata.os_build.as_str()),
|
||||
("Rust", metadata.rustc.as_str()),
|
||||
("Xcode", metadata.xcode.as_str()),
|
||||
("Commit", metadata.commit.as_str()),
|
||||
("Profile", metadata.profile.as_str()),
|
||||
("API validation", metadata.api_validation.as_str()),
|
||||
("Shader validation", metadata.shader_validation.as_str()),
|
||||
("Power source", metadata.power.as_str()),
|
||||
("Thermal", metadata.thermal.as_str()),
|
||||
] {
|
||||
let _ = writeln!(out, "| {key} | {} |", value.replace('|', "\\|"));
|
||||
}
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Repetitions | {} measured, {} warm-up |",
|
||||
metadata.reps, metadata.warmup
|
||||
);
|
||||
if metadata.power != "AC Power" {
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"> **Protocol note.** The machine was not confirmed on AC power. \
|
||||
The benchmark protocol in `docs/testing/benchmarks.md` requires AC power, \
|
||||
so these timings are not protocol-compliant release evidence."
|
||||
);
|
||||
}
|
||||
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Coverage");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "| Fixture | Stage | Source | Status |");
|
||||
let _ = writeln!(out, "| --- | --- | --- | --- |");
|
||||
for result in results {
|
||||
let status = if result.reason.is_empty() {
|
||||
result.status.clone()
|
||||
} else {
|
||||
format!("{} ({})", result.status, result.reason)
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {} | {} |",
|
||||
result.name,
|
||||
result.stage,
|
||||
result.source,
|
||||
status.replace('|', "\\|")
|
||||
);
|
||||
}
|
||||
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Timings");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Durations in microseconds. `compile` is the Rust decode/IR/MSL pipeline, \
|
||||
`library` and `pipeline` are Metal compilation stages, `gpu` is the command-buffer \
|
||||
GPU time, and `host` is the wall time of one dispatch. Values are medians with \
|
||||
interquartile range; minimum and maximum are in `results.json`."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Fixture | Words | compile | library | pipeline | gpu | host | IQR(gpu) | zero-gpu |"
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
|
||||
);
|
||||
for result in results.iter().filter(|r| r.status == "benchmarked") {
|
||||
for size in &result.sizes {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.0}% |",
|
||||
result.name,
|
||||
size.words,
|
||||
size.compile.median * 1e6,
|
||||
size.library.median * 1e6,
|
||||
size.pipeline.median * 1e6,
|
||||
size.gpu.median * 1e6,
|
||||
size.host.median * 1e6,
|
||||
(size.gpu.q3 - size.gpu.q1) * 1e6,
|
||||
size.gpu_zero_fraction * 100.0
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "xenora"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
xenora-decoder = { path = "../decoder" }
|
||||
xenora-isa = { path = "../isa" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-ref = { path = "../ref" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-import-gen = { path = "../import-gen" }
|
||||
@@ -1,67 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
const INPUT: [u32; 4] = [0, 1, u32::MAX, 3_989_547_400];
|
||||
|
||||
struct Fixture {
|
||||
name: &'static str,
|
||||
code: &'static [u8],
|
||||
expected: [u32; 4],
|
||||
}
|
||||
|
||||
const FIXTURES: [Fixture; 3] = [
|
||||
Fixture {
|
||||
name: "add",
|
||||
code: include_bytes!("../../../fixtures/rdna2/add.bin"),
|
||||
expected: [305_419_896, 305_419_897, 305_419_895, 0],
|
||||
},
|
||||
Fixture {
|
||||
name: "bitwise-branch",
|
||||
code: include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin"),
|
||||
expected: [305_419_896, 305_419_897, 315_315_847, 318_723_824],
|
||||
},
|
||||
Fixture {
|
||||
name: "float-exact",
|
||||
code: include_bytes!("../../../fixtures/rdna2/float-exact.bin"),
|
||||
expected: [0x410c_0000, 0x410c_0000, 0x4120_0000, 0x4120_0000],
|
||||
},
|
||||
];
|
||||
|
||||
pub fn run() -> Result<(), Box<dyn Error>> {
|
||||
let metal = NativeCompute::new()?;
|
||||
println!("Metal device: {}", metal.device_name());
|
||||
for fixture in FIXTURES {
|
||||
run_fixture(&metal, fixture)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_fixture(metal: &NativeCompute, fixture: Fixture) -> Result<(), Box<dyn Error>> {
|
||||
let Fixture {
|
||||
name,
|
||||
code,
|
||||
expected,
|
||||
} = fixture;
|
||||
println!("Fixture {name}");
|
||||
let compiled = compile(Architecture::Gfx1030, code)?;
|
||||
println!(
|
||||
"Disassembly\n{}\nIR\n{}\nMSL\n{}",
|
||||
compiled.disassembly, compiled.ir, compiled.msl
|
||||
);
|
||||
|
||||
let reference = xenora_ref::execute(code, &INPUT)?;
|
||||
if reference != expected {
|
||||
return Err(format!("reference mismatch: {reference:?} != {expected:?}").into());
|
||||
}
|
||||
|
||||
let actual = metal.run_words(&compiled.msl, ENTRY_POINT, &INPUT)?;
|
||||
if actual != reference || actual != expected {
|
||||
return Err(format!("Metal mismatch: {actual:?} != {expected:?}").into());
|
||||
}
|
||||
println!("Metal, reference and known answers match: {actual:?}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,605 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
mod demo;
|
||||
mod runner;
|
||||
mod shaders;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
Some("info") => {
|
||||
println!(
|
||||
"Xenora {} ({})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
std::env::consts::ARCH
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Some("inspect") => {
|
||||
let Some(file_path) = std::env::args().nth(2) else {
|
||||
eprintln!("usage: xenora inspect <path-to-pe-binary>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match xenora_loader::triage_file(&file_path) {
|
||||
Ok(report) => {
|
||||
print!("{report}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("inspect failed: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("demo") => match demo::run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("demo: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Some("run") => runner::command(std::env::args_os().skip(2)),
|
||||
Some("imports") => imports_command(std::env::args().skip(2).collect()),
|
||||
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
|
||||
Some("probe") => {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut pe_path: Option<String> = None;
|
||||
let mut mode = "static".to_string();
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
|
||||
let mut i = 2;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--pe" => {
|
||||
if i + 1 < args.len() {
|
||||
pe_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --pe");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--mode" => {
|
||||
if i + 1 < args.len() {
|
||||
mode = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --mode");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--report" => {
|
||||
if i + 1 < args.len() {
|
||||
report_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --report");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown probe argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(pe) = pe_path else {
|
||||
eprintln!(
|
||||
"usage: xenora probe --pe <path> [--mode <static>] [--report <output-dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
|
||||
if mode != "static" {
|
||||
eprintln!("error: currently only --mode static is supported");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
|
||||
let bytes = match std::fs::read(&pe) {
|
||||
Ok(b) => b,
|
||||
Err(err) => {
|
||||
eprintln!("error reading PE binary '{pe}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
let config = xenora_loader::ProbeConfig::default();
|
||||
match xenora_loader::run_probe_and_export(&bytes, &report_dir, &config) {
|
||||
Ok(report) => {
|
||||
println!("Xenora static PE probe complete.");
|
||||
println!("Artifacts exported to: {report_dir}");
|
||||
println!("Sections: {}", report.parsed.sections.len());
|
||||
println!("Relocations: {}", report.relocations.total_entries);
|
||||
println!("TLS Callbacks: {}", report.tls.callback_targets.len());
|
||||
println!("Imported Thunks: {}", report.imports.len());
|
||||
println!(
|
||||
"Unresolved Standard Import Thunks: {}",
|
||||
report
|
||||
.imports
|
||||
.iter()
|
||||
.filter(|import| !import.is_supported)
|
||||
.count()
|
||||
);
|
||||
if let Some(insn) = report.first_unsupported_dbt_insn {
|
||||
println!("First DBT Blocker: RVA 0x{:08x} ({})", insn.rva, insn.notes);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("probe failed: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `xenora imports sync [--report <dir>] [--check]`
|
||||
/// `xenora imports generate --pe <path> [--out <dir>]`
|
||||
/// `xenora imports metadata sync [--out <dir>]`
|
||||
/// `xenora imports verify`
|
||||
fn imports_command(args: Vec<String>) -> ExitCode {
|
||||
if args.is_empty() {
|
||||
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
|
||||
match args[0].as_str() {
|
||||
"generate" => run_imports_generate_cli(&args[1..]),
|
||||
"sync" => run_imports_sync_cli(&args[1..]),
|
||||
"metadata" => run_imports_metadata_cli(&args[1..]),
|
||||
"verify" => run_imports_verify_cli(&args[1..]),
|
||||
other => {
|
||||
eprintln!("unknown imports subcommand: {other}");
|
||||
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_metadata_cli(args: &[String]) -> ExitCode {
|
||||
let mut out_dir = "artifacts/metadata".to_string();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"sync" => {
|
||||
i += 1;
|
||||
}
|
||||
"--out" => {
|
||||
if i + 1 < args.len() {
|
||||
out_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --out");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown metadata argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("Synchronizing offline API metadata catalog from public specifications...");
|
||||
let catalog = xenora_import_gen::MetadataCatalog::builtin();
|
||||
println!(
|
||||
"Loaded version {} with {} entries.",
|
||||
catalog.version,
|
||||
catalog.entries.len()
|
||||
);
|
||||
|
||||
let _ = std::fs::create_dir_all(&out_dir);
|
||||
let out_file = format!("{out_dir}/api_catalog.json");
|
||||
let mut json = String::from("{\n \"version\": 1,\n \"entries\": [\n");
|
||||
let mut first = true;
|
||||
for ((module, sym), sig) in &catalog.entries {
|
||||
if !first {
|
||||
json.push_str(",\n");
|
||||
}
|
||||
first = false;
|
||||
json.push_str(&format!(
|
||||
" {{\"module\": \"{}\", \"symbol\": \"{}\", \"header\": \"{}\", \"doc\": \"{}\"}}",
|
||||
module, sym, sig.header_source, sig.doc
|
||||
));
|
||||
}
|
||||
json.push_str("\n ]\n}\n");
|
||||
|
||||
if let Err(e) = std::fs::write(&out_file, json) {
|
||||
eprintln!("failed to write metadata catalog: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
println!("API metadata catalog synchronized to: {out_file}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_imports_verify_cli(args: &[String]) -> ExitCode {
|
||||
if !args.is_empty() {
|
||||
eprintln!("warning: verify takes no additional arguments");
|
||||
}
|
||||
println!("Running automated behavioral verification for generated import bindings...");
|
||||
match xenora_import_gen::run_verification() {
|
||||
Ok(res) => {
|
||||
for detail in &res.details {
|
||||
println!(" {detail}");
|
||||
}
|
||||
println!(
|
||||
"Verification summary: {}/{} tests passed.",
|
||||
res.passed, res.total
|
||||
);
|
||||
if res.failed > 0 {
|
||||
ExitCode::FAILURE
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("verification failed: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
let mut pe_path: Option<String> = None;
|
||||
let mut csv_path: Option<String> = None;
|
||||
let mut out_dir = "crates/loader/src/generated".to_string();
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--pe" => {
|
||||
if i + 1 < args.len() {
|
||||
pe_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --pe");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--csv" => {
|
||||
if i + 1 < args.len() {
|
||||
csv_path = Some(args[i + 1].clone());
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --csv");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--out" => {
|
||||
if i + 1 < args.len() {
|
||||
out_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --out");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown generate argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let records = if let Some(ref pe) = pe_path {
|
||||
println!("Extracting imports from PE executable: {pe}");
|
||||
let bytes = match std::fs::read(pe) {
|
||||
Ok(b) => b,
|
||||
Err(err) => {
|
||||
eprintln!("error reading PE binary '{pe}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let probe_cfg = xenora_loader::ProbeConfig::default();
|
||||
let report = match xenora_loader::probe::probe_pe_bytes(&bytes, &probe_cfg) {
|
||||
Ok(rep) => rep,
|
||||
Err(err) => {
|
||||
eprintln!("error probing PE binary: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
report
|
||||
.imports
|
||||
.into_iter()
|
||||
.map(|imp| xenora_import_gen::ImportRecord {
|
||||
module: imp.dll,
|
||||
symbol: imp.symbol,
|
||||
iat_rva: imp.iat_rva as u64,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
} else if let Some(ref csv) = csv_path {
|
||||
match xenora_import_gen::parse_csv(csv) {
|
||||
Ok(recs) => recs,
|
||||
Err(err) => {
|
||||
eprintln!("error reading CSV '{csv}': {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!(
|
||||
"usage: xenora imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
|
||||
);
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
|
||||
println!("Total imports extracted: {}", records.len());
|
||||
let db = xenora_import_gen::SymbolDb::builtin();
|
||||
let manifest = xenora_import_gen::Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
println!("Classification summary:");
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / records.len() as f64 * 100.0) as u32;
|
||||
println!(" - {tier}: {count} ({pct}%)");
|
||||
}
|
||||
|
||||
let files = xenora_import_gen::generate(&manifest, &db);
|
||||
if let Err(err) = files.write_all(&out_dir) {
|
||||
eprintln!("failed to write generated files: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let manifest_csv = format!("{out_dir}/generated_manifest.csv");
|
||||
if let Err(err) = manifest.write_csv(&manifest_csv) {
|
||||
eprintln!("failed to write manifest CSV: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
|
||||
println!("Successfully generated bindings in '{out_dir}':");
|
||||
println!(" - {out_dir}/generated_crt.rs");
|
||||
println!(" - {out_dir}/generated_stubs.rs");
|
||||
println!(" - {out_dir}/generated_tests.rs");
|
||||
println!(" - {out_dir}/generated_manifest.md");
|
||||
println!(" - {out_dir}/generated_manifest.csv");
|
||||
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
let mut check_mode = false;
|
||||
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--report" => {
|
||||
if i + 1 < args.len() {
|
||||
report_dir = args[i + 1].clone();
|
||||
i += 2;
|
||||
} else {
|
||||
eprintln!("missing argument for --report");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
"--check" => {
|
||||
check_mode = true;
|
||||
i += 1;
|
||||
}
|
||||
other => {
|
||||
eprintln!("unknown sync argument: {other}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match run_imports_sync(&report_dir, check_mode) {
|
||||
Ok(changed) => {
|
||||
if check_mode {
|
||||
if changed {
|
||||
eprintln!("imports sync --check: import_backlog.md is out of date");
|
||||
ExitCode::FAILURE
|
||||
} else {
|
||||
println!("imports sync --check: import_backlog.md is up to date");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
} else {
|
||||
println!("imports sync complete. Report written to: {report_dir}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("imports sync failed: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_imports_sync(
|
||||
report_dir: &str,
|
||||
check_mode: bool,
|
||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::ImportRegistry;
|
||||
use xenora_loader::imports::ServiceStatus;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
let imports_csv_path = std::path::Path::new(report_dir).join("imports.csv");
|
||||
if !imports_csv_path.exists() {
|
||||
return Err(
|
||||
format!("imports.csv not found in '{report_dir}'. Run `xenora probe` first.").into(),
|
||||
);
|
||||
}
|
||||
|
||||
// Build the standard registry to get current implementation state.
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
|
||||
// Parse imports.csv (skip header line).
|
||||
let csv_text = std::fs::read_to_string(&imports_csv_path)?;
|
||||
let mut by_module: BTreeMap<String, Vec<(String, bool, Option<ServiceStatus>)>> =
|
||||
BTreeMap::new();
|
||||
let mut total = 0usize;
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
|
||||
for line in csv_text.lines().skip(1) {
|
||||
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
|
||||
// We re-query the live registry rather than trusting cached status.
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
if fields.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let module = fields[0].trim_matches('"').to_string();
|
||||
let symbol = fields[1].trim_matches('"').to_string();
|
||||
if module.is_empty() || symbol.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let binding = registry.binding(&module, &symbol);
|
||||
let is_registered = binding.is_some();
|
||||
let status = binding.map(|b| b.status);
|
||||
|
||||
let label: &'static str = match status {
|
||||
Some(ServiceStatus::Implemented) => "implemented",
|
||||
Some(ServiceStatus::Partial) => "partial",
|
||||
Some(ServiceStatus::Stub) => "stub",
|
||||
None => {
|
||||
// Check explicit known-unsupported list
|
||||
match (module.to_ascii_lowercase().as_str(), symbol.as_str()) {
|
||||
(
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll",
|
||||
"CreateThread" | "ResumeThread" | "SuspendThread" | "TerminateProcess",
|
||||
)
|
||||
| (
|
||||
"api-ms-win-core-synch-l1-1-0.dll",
|
||||
"WaitForSingleObject" | "WaitForSingleObjectEx",
|
||||
)
|
||||
| ("api-ms-win-core-synch-l1-2-1.dll", "WaitForMultipleObjects")
|
||||
| ("api-ms-win-core-rtlsupport-l1-1-0.dll", "RtlVirtualUnwind") => {
|
||||
"unsupported"
|
||||
}
|
||||
_ => "missing",
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
*counts.entry(label).or_default() += 1;
|
||||
total += 1;
|
||||
by_module
|
||||
.entry(module.to_ascii_lowercase())
|
||||
.or_default()
|
||||
.push((symbol, is_registered, status));
|
||||
}
|
||||
|
||||
// Build the refreshed import_backlog.md.
|
||||
let mut md = String::new();
|
||||
let _ = writeln!(md, "# Xenora import compatibility backlog");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Generated by `xenora imports sync`. Do not edit manually."
|
||||
);
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"Re-run after adding service handlers to refresh this file."
|
||||
);
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "## Summary");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "| Status | Count |");
|
||||
let _ = writeln!(md, "| --- | ---: |");
|
||||
let _ = writeln!(md, "| **Total** | {total} |");
|
||||
for (label, count) in &counts {
|
||||
let _ = writeln!(md, "| {label} | {count} |");
|
||||
}
|
||||
let _ = writeln!(md);
|
||||
|
||||
let _ = writeln!(md, "## Missing handlers (highest value first)");
|
||||
let _ = writeln!(md);
|
||||
|
||||
// Priority ordering: processthreads, synch, rtlsupport, memory, crt, file, graphics, other
|
||||
fn priority_key(module: &str) -> u8 {
|
||||
if module.contains("processthreads") || module.contains("core-handle") {
|
||||
1
|
||||
} else if module.contains("fibers") || module.contains("tls") {
|
||||
2
|
||||
} else if module.contains("core-synch") {
|
||||
3
|
||||
} else if module.contains("core-profile") || module.contains("core-sysinfo") {
|
||||
4
|
||||
} else if module.contains("core-memory")
|
||||
|| module.contains("core-heap")
|
||||
|| module == "xmem.dll"
|
||||
{
|
||||
5
|
||||
} else if module.starts_with("api-ms-win-crt-")
|
||||
|| module.contains("vcruntime")
|
||||
|| module.contains("libraryloader")
|
||||
{
|
||||
6
|
||||
} else if module.contains("rtlsupport") || module.contains("errorhandling") {
|
||||
7
|
||||
} else if module.contains("core-file") || module == "xcrdapi.dll" {
|
||||
8
|
||||
} else {
|
||||
9
|
||||
}
|
||||
}
|
||||
|
||||
// Collect missing/unsupported into a prioritized list.
|
||||
let mut missing_entries: Vec<(u8, String, String)> = Vec::new();
|
||||
for (module, symbols) in &by_module {
|
||||
for (symbol, is_registered, _status) in symbols {
|
||||
if !is_registered {
|
||||
missing_entries.push((priority_key(module), module.clone(), symbol.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
missing_entries.sort();
|
||||
|
||||
let mut prev_priority = 255u8;
|
||||
for (priority, module, symbol) in &missing_entries {
|
||||
if *priority != prev_priority {
|
||||
let _ = writeln!(md, "### Priority {priority}");
|
||||
let _ = writeln!(md);
|
||||
prev_priority = *priority;
|
||||
}
|
||||
let _ = writeln!(md, "- `{module}!{symbol}`");
|
||||
}
|
||||
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "## Registered handlers");
|
||||
let _ = writeln!(md);
|
||||
let _ = writeln!(md, "| Module | Symbol | Status |");
|
||||
let _ = writeln!(md, "| --- | --- | --- |");
|
||||
// Enumerate canonical registrations sorted by module, symbol
|
||||
let mut registered: BTreeSet<(String, String, &'static str)> = BTreeSet::new();
|
||||
for (module, symbol, status) in registry.iter_registered() {
|
||||
registered.insert((
|
||||
module.to_ascii_lowercase(),
|
||||
symbol.to_string(),
|
||||
status.as_str(),
|
||||
));
|
||||
}
|
||||
for (module, symbol, status) in ®istered {
|
||||
let _ = writeln!(md, "| `{module}` | `{symbol}` | {status} |");
|
||||
}
|
||||
|
||||
let out_path = std::path::Path::new(report_dir).join("import_backlog.md");
|
||||
let existing = std::fs::read_to_string(&out_path).unwrap_or_default();
|
||||
let changed = existing != md;
|
||||
|
||||
if !check_mode {
|
||||
std::fs::write(&out_path, &md)?;
|
||||
println!(
|
||||
" Total imports: {total} | implemented: {} | partial: {} | stub: {} | missing: {}",
|
||||
counts.get("implemented").copied().unwrap_or(0),
|
||||
counts.get("partial").copied().unwrap_or(0),
|
||||
counts.get("stub").copied().unwrap_or(0),
|
||||
counts.get("missing").copied().unwrap_or(0),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
use std::fmt::Write as _;
|
||||
@@ -1,358 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::error::Error;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitCode, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use xenora_loader::startup::{StartupEvent, StartupLayout, run_synthetic_startup_with_observer};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, Register};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
const WALL_LIMIT: Duration = Duration::from_secs(15);
|
||||
const DEFAULT_STEPS: usize = 100;
|
||||
const MAX_STEPS: usize = 10_000;
|
||||
const IMAGE_BASE: u64 = 0x150000000;
|
||||
const TICKET_ADDRESS: u64 = IMAGE_BASE + 0x3000;
|
||||
const TICKET: u64 = 17;
|
||||
const DRAW_RESULT: u64 = 0x42;
|
||||
const EXTENT: [usize; 2] = [4, 3];
|
||||
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
|
||||
const USAGE: &str = "usage: xenora run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]";
|
||||
|
||||
struct Options {
|
||||
path: PathBuf,
|
||||
max_steps: usize,
|
||||
worker: bool,
|
||||
trace: bool,
|
||||
hud: bool,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Self, String> {
|
||||
let mut args = args.into_iter();
|
||||
let mut path = None;
|
||||
let mut max_steps = None;
|
||||
let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false);
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.to_str() {
|
||||
Some("--pe") if path.is_none() => {
|
||||
path = Some(PathBuf::from(args.next().ok_or("missing --pe path")?));
|
||||
}
|
||||
Some("--max-steps") if max_steps.is_none() => {
|
||||
max_steps = Some(
|
||||
args.next()
|
||||
.and_then(|arg| arg.to_str()?.parse::<usize>().ok())
|
||||
.filter(|steps| (1..=MAX_STEPS).contains(steps))
|
||||
.ok_or("--max-steps must be in 1..=10000")?,
|
||||
);
|
||||
}
|
||||
Some("--experimental") if !experimental => experimental = true,
|
||||
Some("--trace") if !trace => trace = true,
|
||||
Some("--metal-hud") if !hud => hud = true,
|
||||
Some("--worker") if !worker => worker = true,
|
||||
_ => return Err(format!("unknown or repeated run argument {arg:?}")),
|
||||
}
|
||||
}
|
||||
if !experimental {
|
||||
return Err("run requires --experimental".into());
|
||||
}
|
||||
Ok(Self {
|
||||
path: path.ok_or("missing --pe path")?,
|
||||
max_steps: max_steps.unwrap_or(DEFAULT_STEPS),
|
||||
worker,
|
||||
trace,
|
||||
hud,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn command(args: impl IntoIterator<Item = OsString>) -> ExitCode {
|
||||
let options = match Options::parse(args) {
|
||||
Ok(options) => options,
|
||||
Err(error) => {
|
||||
eprintln!("{error}\n{USAGE}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let result = if options.worker {
|
||||
run_worker(&options).map(|()| ExitCode::SUCCESS)
|
||||
} else {
|
||||
launch_worker(&options)
|
||||
};
|
||||
match result {
|
||||
Ok(code) => code,
|
||||
Err(error) => {
|
||||
eprintln!("run failed: {error}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
let mut child = Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"run",
|
||||
"--experimental",
|
||||
"--trace",
|
||||
"--metal-hud",
|
||||
"--worker",
|
||||
])
|
||||
.arg("--max-steps")
|
||||
.arg(options.max_steps.to_string())
|
||||
.arg("--pe")
|
||||
.arg(&options.path)
|
||||
.stdin(Stdio::null())
|
||||
.spawn()?;
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
return match status.code() {
|
||||
Some(code) => Ok(ExitCode::from(u8::try_from(code)?)),
|
||||
None => Err(format!("worker terminated: {status}").into()),
|
||||
};
|
||||
}
|
||||
Ok(None) if started.elapsed() < WALL_LIMIT => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
status => {
|
||||
let _ = child.kill();
|
||||
child.wait()?;
|
||||
status?;
|
||||
return Err("experimental worker exceeded its 15 second wall deadline".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_fixture(path: &Path) -> Result<(), Box<dyn Error>> {
|
||||
let valid_metadata =
|
||||
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
|
||||
let rejection =
|
||||
"execution denied: input must match the original trusted PE fixture byte for byte";
|
||||
// Check size before opening and again on the descriptor. Bound the read
|
||||
// even if another process changes the file after the metadata checks.
|
||||
if !valid_metadata(fs::metadata(path)?) {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
let file = File::open(path)?;
|
||||
if !valid_metadata(file.metadata()?) {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(FIXTURE.len() + 1);
|
||||
file.take(FIXTURE.len() as u64 + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes != FIXTURE {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
std::thread::Builder::new()
|
||||
.name("xenora-deadline".into())
|
||||
.spawn(|| {
|
||||
std::thread::sleep(WALL_LIMIT);
|
||||
// The supervisor also enforces this deadline. The worker retains
|
||||
// its own deadline if it is invoked directly.
|
||||
std::process::exit(124);
|
||||
})?;
|
||||
verify_fixture(&options.path)?;
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace fixture=trusted-runner policy=exact-bytes entry_step_limit={} wall_limit_ms=15000",
|
||||
options.max_steps
|
||||
);
|
||||
}
|
||||
|
||||
let capture = Arc::new(Mutex::new(None));
|
||||
let draw_capture = Arc::clone(&capture);
|
||||
let mut imports = ImportRegistry::new();
|
||||
let trace = options.trace;
|
||||
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
|
||||
let ticket_address = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let mut result = draw_capture
|
||||
.lock()
|
||||
.map_err(|_| ExitReason::IllegalInstruction(0xff))?;
|
||||
if result.is_some() {
|
||||
return Err(ExitReason::IllegalInstruction(0xff));
|
||||
}
|
||||
if ticket_address != TICKET_ADDRESS
|
||||
|| memory
|
||||
.read_u64(ticket_address)
|
||||
.map_err(ExitReason::MemoryFault)?
|
||||
!= TICKET
|
||||
{
|
||||
*result = Some(Err(
|
||||
"draw ticket did not match the TLS-initialized guest word".into(),
|
||||
));
|
||||
return Err(ExitReason::IllegalInstruction(0xff));
|
||||
}
|
||||
if trace {
|
||||
println!("trace import=xenora.dll!fixture_draw tls_ticket={TICKET}");
|
||||
}
|
||||
let frame = draw().map_err(|error| error.to_string());
|
||||
let drawn = frame.is_ok();
|
||||
*result = Some(frame);
|
||||
if drawn {
|
||||
Ok(DRAW_RESULT)
|
||||
} else {
|
||||
Err(ExitReason::IllegalInstruction(0xff))
|
||||
}
|
||||
});
|
||||
|
||||
let started = Instant::now();
|
||||
// Use only the embedded snapshot. The file is solely an exact-byte gate.
|
||||
let startup = run_synthetic_startup_with_observer(
|
||||
FIXTURE,
|
||||
StartupLayout {
|
||||
image_base: IMAGE_BASE,
|
||||
stack_top: 0x200010000,
|
||||
tls_base: 0x300000000,
|
||||
},
|
||||
imports,
|
||||
options.max_steps,
|
||||
|event| {
|
||||
if options.trace {
|
||||
trace_startup(event);
|
||||
}
|
||||
},
|
||||
)?;
|
||||
let host_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
let result = capture
|
||||
.lock()
|
||||
.map_err(|_| "fixture draw result lock failed")?
|
||||
.take();
|
||||
let exit = startup.execution.exit_reason;
|
||||
let rax = startup.execution.final_state.get(Register::Rax);
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}",
|
||||
startup.execution.instructions_executed,
|
||||
);
|
||||
}
|
||||
if let Some(Err(error)) = &result {
|
||||
return Err(format!("fixture draw failed: {error}").into());
|
||||
}
|
||||
if exit != ExitReason::Halt {
|
||||
return Err(exit.into());
|
||||
}
|
||||
if startup.relocations.applied_dir64 != 4
|
||||
|| startup.bound_imports != 1
|
||||
|| startup.tls_callbacks != 1
|
||||
|| rax != DRAW_RESULT
|
||||
{
|
||||
return Err("trusted fixture startup or result differs from the expected values".into());
|
||||
}
|
||||
let frame = result.ok_or("guest halted without a draw")??;
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace stage=framebuffer extent={}x{} verified_pixels={}",
|
||||
EXTENT[0],
|
||||
EXTENT[1],
|
||||
EXTENT[0] * EXTENT[1],
|
||||
);
|
||||
}
|
||||
if options.hud {
|
||||
let gpu_time = frame.gpu_seconds.map_or_else(
|
||||
|| "unavailable".to_owned(),
|
||||
|seconds| format!("{:.3}", seconds * 1000.0),
|
||||
);
|
||||
println!(
|
||||
"Metal HUD | device={} | offscreen={}x{} | draw_calls=1 | verified_pixels={} | host_render_readback_ms={:.3} | host_startup_ms={host_ms:.3} | gpu_command_ms={gpu_time}",
|
||||
frame.device,
|
||||
EXTENT[0],
|
||||
EXTENT[1],
|
||||
EXTENT[0] * EXTENT[1],
|
||||
frame.host_render_readback_ms,
|
||||
);
|
||||
let metrics = startup.dbt_metrics;
|
||||
println!(
|
||||
"DBT | entry_steps={} | native_steps_tls_and_entry={} | blocks_compiled={} | native_bytes={} | native_dispatches={} | service_calls={} | interpreter_fallbacks={}",
|
||||
startup.execution.instructions_executed,
|
||||
metrics.instructions_executed,
|
||||
metrics.blocks_compiled,
|
||||
metrics.native_bytes_emitted,
|
||||
metrics.dbt_dispatches,
|
||||
metrics.service_calls,
|
||||
metrics.interpreter_fallbacks,
|
||||
);
|
||||
}
|
||||
println!("Trusted fixture completed one verified offscreen Metal draw.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trace_startup(event: StartupEvent) {
|
||||
match event {
|
||||
StartupEvent::Parsed {
|
||||
sections,
|
||||
entry_rva,
|
||||
} => {
|
||||
println!("trace stage=parsed sections={sections} entry_rva={entry_rva:#x}");
|
||||
}
|
||||
StartupEvent::Mapped { entry_va } => {
|
||||
println!("trace stage=mapped base={IMAGE_BASE:#x} entry_va={entry_va:#x}");
|
||||
}
|
||||
StartupEvent::Relocated { applied_dir64 } => {
|
||||
println!("trace stage=relocated dir64_applied={applied_dir64}");
|
||||
}
|
||||
StartupEvent::ImportsBound { count } => {
|
||||
println!("trace stage=imports_bound bound_imports={count}");
|
||||
}
|
||||
StartupEvent::TlsCompleted {
|
||||
callbacks,
|
||||
native_steps,
|
||||
} => {
|
||||
println!(
|
||||
"trace stage=tls_completed tls_callbacks={callbacks} native_steps={native_steps}"
|
||||
);
|
||||
}
|
||||
StartupEvent::Entering { step_limit } => {
|
||||
println!("trace stage=entry step_limit={step_limit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Frame {
|
||||
device: String,
|
||||
host_render_readback_ms: f64,
|
||||
gpu_seconds: Option<f64>,
|
||||
}
|
||||
|
||||
fn draw() -> Result<Frame, Box<dyn Error>> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)?;
|
||||
let gpu = NativeCompute::new()?;
|
||||
let started = Instant::now();
|
||||
let (pixels, gpu_seconds) = gpu.render_rgba8_profiled(
|
||||
&shader.msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
EXTENT,
|
||||
[19, 43, 93, 251],
|
||||
)?;
|
||||
let host_render_readback_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
if pixels != EXPECTED_PIXEL.repeat(EXTENT[0] * EXTENT[1]) {
|
||||
return Err("offscreen readback did not match opaque red at every pixel".into());
|
||||
}
|
||||
Ok(Frame {
|
||||
device: gpu.device_name().to_owned(),
|
||||
host_render_readback_ms,
|
||||
gpu_seconds,
|
||||
})
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
//! `xenora shaders`: instruction inventory and stream inspection.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
|
||||
|
||||
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
|
||||
|
||||
pub fn command(args: &[String]) -> ExitCode {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
|
||||
Some("inspect") => match args.get(1) {
|
||||
Some(path) => inspect(path),
|
||||
None => usage(),
|
||||
},
|
||||
_ => usage(),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage() -> ExitCode {
|
||||
eprintln!("{USAGE}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
|
||||
fn semantic(family: EncodingFamily) -> usize {
|
||||
SEMANTIC_FORMS
|
||||
.iter()
|
||||
.filter(|(_, form_family)| *form_family == family)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
|
||||
/// with their length; "semantic" forms decode into executable instructions.
|
||||
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
|
||||
fn coverage(json: bool) -> ExitCode {
|
||||
let rows: Vec<_> = meta::inventory()
|
||||
.into_iter()
|
||||
.map(|(family, discovered)| (family, discovered, semantic(family)))
|
||||
.collect();
|
||||
let total: usize = rows.iter().map(|row| row.1).sum();
|
||||
let supported: usize = rows.iter().map(|row| row.2).sum();
|
||||
if json {
|
||||
let families: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|(family, discovered, semantic)| {
|
||||
format!(
|
||||
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
|
||||
family.name()
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
println!(
|
||||
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
|
||||
meta::SOURCE_SHA256,
|
||||
families.join(",")
|
||||
);
|
||||
} else {
|
||||
println!("{:<10} {:>10} {:>9}", "family", "discovered", "semantic");
|
||||
for (family, discovered, semantic) in &rows {
|
||||
println!("{:<10} {discovered:>10} {semantic:>9}", family.name());
|
||||
}
|
||||
println!("{:<10} {total:>10} {supported:>9}", "total");
|
||||
println!("Semantic forms decode for the operand subsets in docs/status.toml only.");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn inspect(path: &str) -> ExitCode {
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
eprintln!("{path}: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let mut offset = 0;
|
||||
let mut unsupported = 0;
|
||||
let mut count = 0;
|
||||
while offset < bytes.len() {
|
||||
let found = match identify(&bytes[offset..]) {
|
||||
Ok(found) => found,
|
||||
Err(error) => {
|
||||
println!("{offset:#06x} decode failure: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let words: Vec<String> = bytes[offset..offset + found.len]
|
||||
.chunks(4)
|
||||
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
|
||||
.collect();
|
||||
let status = match decode(Architecture::Gfx1030, &bytes[offset..offset + found.len]) {
|
||||
Ok(_) => "semantic".to_owned(),
|
||||
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
|
||||
format!("unsupported operands: {error}")
|
||||
}
|
||||
Err(_) => "unsupported instruction semantics".to_owned(),
|
||||
};
|
||||
if status != "semantic" {
|
||||
unsupported += 1;
|
||||
}
|
||||
println!(
|
||||
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
|
||||
found.form.family.name(),
|
||||
found.form.name.to_ascii_lowercase(),
|
||||
words.join(" ")
|
||||
);
|
||||
offset += found.len;
|
||||
count += 1;
|
||||
}
|
||||
println!(
|
||||
"{count} instructions inspected against {} gfx1030 forms; {unsupported} not executable",
|
||||
FORMS.len()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "xenora-decoder"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
xenora-isa = { path = "../isa" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-ref = { path = "../ref" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,618 +0,0 @@
|
||||
//! Decoder for Xenora's bounded little-endian gfx1030 instruction stream.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination. Operand restrictions are listed in docs/status.toml;
|
||||
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
("V_ASHRREV_I32", EncodingFamily::Vop2),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_LSHLREV_B32", EncodingFamily::Vop2),
|
||||
("V_LSHRREV_B32", EncodingFamily::Vop2),
|
||||
("V_MOV_B32", EncodingFamily::Vop1),
|
||||
("V_MUL_F32", EncodingFamily::Vop2),
|
||||
("V_OR_B32", EncodingFamily::Vop2),
|
||||
("V_XOR_B32", EncodingFamily::Vop2),
|
||||
];
|
||||
|
||||
/// A successfully decoded instruction and its location in the input stream.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DecodedInstruction {
|
||||
/// Byte offset from the start of the stream.
|
||||
pub offset: usize,
|
||||
/// Total size in bytes, including any literal word.
|
||||
pub byte_len: u8,
|
||||
/// The decoded instruction and operand fields.
|
||||
pub instruction: Instruction,
|
||||
}
|
||||
|
||||
impl fmt::Display for DecodedInstruction {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoder failures classified for callers.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DecodeErrorKind {
|
||||
/// An instruction, second word or literal extends past the available input.
|
||||
Truncated {
|
||||
/// Number of bytes required at the instruction start.
|
||||
needed: u8,
|
||||
/// Number of bytes available at the instruction start.
|
||||
available: usize,
|
||||
},
|
||||
/// No supported opcode pattern matches the first word.
|
||||
UnsupportedOpcode {
|
||||
/// First instruction word in host integer order.
|
||||
word: u32,
|
||||
},
|
||||
/// A supported opcode uses an operand or modifier outside the subset.
|
||||
UnsupportedForm {
|
||||
/// Opcode mnemonic.
|
||||
mnemonic: &'static str,
|
||||
/// Details of the unsupported or reserved fields.
|
||||
detail: &'static str,
|
||||
},
|
||||
/// A forward branch leaves the stream or lands inside an instruction.
|
||||
InvalidBranchTarget {
|
||||
/// Destination byte offset from the start of the stream.
|
||||
target: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// A decoder error and the offset of the offending instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DecodeError {
|
||||
/// Byte offset from the start of the stream.
|
||||
pub offset: usize,
|
||||
/// Decoder-specific failure.
|
||||
pub kind: DecodeErrorKind,
|
||||
}
|
||||
|
||||
impl fmt::Display for DecodeError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "gfx1030 decode at byte 0x{:x}: ", self.offset)?;
|
||||
match self.kind {
|
||||
DecodeErrorKind::Truncated { needed, available } => {
|
||||
write!(
|
||||
formatter,
|
||||
"instruction requires {needed} bytes, found {available}"
|
||||
)
|
||||
}
|
||||
DecodeErrorKind::UnsupportedOpcode { word } => {
|
||||
write!(formatter, "unsupported opcode in 0x{word:08x}")
|
||||
}
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, detail } => {
|
||||
write!(formatter, "unsupported {mnemonic} form: {detail}")
|
||||
}
|
||||
DecodeErrorKind::InvalidBranchTarget { target } => {
|
||||
write!(
|
||||
formatter,
|
||||
"branch target 0x{target:x} is outside instruction boundaries"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for DecodeError {}
|
||||
|
||||
/// Decodes a stream of instructions. Program termination, memory hazards and
|
||||
/// register initialization are checked by later stages.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the failing byte offset for a truncated instruction, unsupported
|
||||
/// opcode, unsupported form or invalid branch target. An empty stream
|
||||
/// decodes to an empty list.
|
||||
pub fn decode(
|
||||
architecture: Architecture,
|
||||
bytes: &[u8],
|
||||
) -> Result<Vec<DecodedInstruction>, DecodeError> {
|
||||
let decode_instruction = match architecture {
|
||||
Architecture::Gfx1030 => decode_gfx1030,
|
||||
};
|
||||
let mut result = Vec::new();
|
||||
let mut offset = 0;
|
||||
while offset < bytes.len() {
|
||||
let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset)
|
||||
.map_err(|kind| DecodeError { offset, kind })?;
|
||||
result.push(DecodedInstruction {
|
||||
offset,
|
||||
byte_len,
|
||||
instruction,
|
||||
});
|
||||
offset += usize::from(byte_len);
|
||||
}
|
||||
for decoded in &result {
|
||||
if let Instruction::Branch { target }
|
||||
| Instruction::BranchSccZero { target }
|
||||
| Instruction::BranchExecZero { target }
|
||||
| Instruction::BranchVccZero { target } = decoded.instruction
|
||||
&& result
|
||||
.binary_search_by_key(&target, |item| item.offset)
|
||||
.is_err()
|
||||
{
|
||||
return Err(DecodeError {
|
||||
offset: decoded.offset,
|
||||
kind: DecodeErrorKind::InvalidBranchTarget { target },
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
|
||||
let end_index = usize::from(end);
|
||||
let Some(word) = bytes
|
||||
.get(end_index - 4..end_index)
|
||||
.and_then(|word| <[u8; 4]>::try_from(word).ok())
|
||||
else {
|
||||
return Err(DecodeErrorKind::Truncated {
|
||||
needed: end,
|
||||
available: bytes.len(),
|
||||
});
|
||||
};
|
||||
Ok(u32::from_le_bytes(word))
|
||||
}
|
||||
|
||||
fn unsupported(mnemonic: &'static str, detail: &'static str) -> DecodeErrorKind {
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, detail }
|
||||
}
|
||||
|
||||
fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let first = word(bytes, 4)?;
|
||||
|
||||
if BUFFER_LOAD_DWORD.matches(first) {
|
||||
let len = BUFFER_LOAD_DWORD.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
let (data, index, resource) = buffer_operands(first, second, "buffer_load_dword")?;
|
||||
return Ok((
|
||||
Instruction::BufferLoadDword {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
},
|
||||
len,
|
||||
));
|
||||
}
|
||||
if BUFFER_STORE_DWORD.matches(first) {
|
||||
let len = BUFFER_STORE_DWORD.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
let (data, index, resource) = buffer_operands(first, second, "buffer_store_dword")?;
|
||||
return Ok((
|
||||
Instruction::BufferStoreDword {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
},
|
||||
len,
|
||||
));
|
||||
}
|
||||
if EXP.matches(first) {
|
||||
let len = EXP.byte_len();
|
||||
let sources = word(bytes, len)?.to_le_bytes();
|
||||
// RDNA 2 ISA Table 56. Match all operand and reserved bits, including
|
||||
// the four enable bits, compression, DONE and valid-mask flags.
|
||||
let target = match first & 0x03ff_ffff {
|
||||
0x08cf => ExportTarget::Position0,
|
||||
0x020f => ExportTarget::Parameter0,
|
||||
0x180f => ExportTarget::RenderTarget0,
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
"exp",
|
||||
"expected full uncompressed POS0 done, PARAM0, or MRT0 done vm",
|
||||
));
|
||||
}
|
||||
};
|
||||
return Ok((Instruction::Export { target, sources }, len));
|
||||
}
|
||||
if IMAGE_SAMPLE_LZ.matches(first) {
|
||||
let len = IMAGE_SAMPLE_LZ.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
let (dst, coord, resource, sampler) =
|
||||
image_sample_operands(first, second, "image_sample_lz")?;
|
||||
return Ok((
|
||||
Instruction::ImageSampleLz {
|
||||
dst,
|
||||
coord,
|
||||
resource,
|
||||
sampler,
|
||||
},
|
||||
len,
|
||||
));
|
||||
}
|
||||
for (opcode, phase) in [
|
||||
(V_INTERP_P1_F32, InterpolationPhase::First),
|
||||
(V_INTERP_P2_F32, InterpolationPhase::Second),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return Ok((
|
||||
Instruction::Interpolate {
|
||||
phase,
|
||||
dst: (first >> 18) as u8,
|
||||
coordinate: first as u8,
|
||||
attribute: ((first >> 10) & 0x3f) as u8,
|
||||
component: ((first >> 8) & 3) as u8,
|
||||
},
|
||||
opcode.byte_len(),
|
||||
));
|
||||
}
|
||||
}
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
if V_ADD_NC_U32.matches(first) {
|
||||
let len = V_ADD_NC_U32.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
return Ok((add_u32(first, second)?, len));
|
||||
}
|
||||
if S_MOV_B32.matches(first) {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if !matches!(dst, 0..=107 | 126..=127) {
|
||||
return Err(unsupported(
|
||||
"s_mov_b32",
|
||||
"expected a normal SGPR or EXEC/VCC destination",
|
||||
));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if S_CMP_EQ_U32.matches(first) {
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
"s_cmp_eq_u32",
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
|
||||
return Ok((
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 },
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
if S_BRANCH.matches(first) {
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
}
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
return Ok((
|
||||
Instruction::BranchSccZero { target },
|
||||
S_CBRANCH_SCC0.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_EXECZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_execz")?;
|
||||
return Ok((
|
||||
Instruction::BranchExecZero { target },
|
||||
S_CBRANCH_EXECZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_VCCZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_vccz")?;
|
||||
return Ok((
|
||||
Instruction::BranchVccZero { target },
|
||||
S_CBRANCH_VCCZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_LSHLREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorLshlrevB32 { dst, src0, src1 },
|
||||
V_LSHLREV_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_ASHRREV_I32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_ashrrev_i32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorAshrrevI32 { dst, src0, src1 },
|
||||
V_ASHRREV_I32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_LSHRREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshrrev_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorLshrrevB32 { dst, src0, src1 },
|
||||
V_LSHRREV_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_AND_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_and_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorAndB32 { dst, src0, src1 },
|
||||
V_AND_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_OR_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_or_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorOrB32 { dst, src0, src1 },
|
||||
V_OR_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_XOR_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_xor_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorXorB32 { dst, src0, src1 },
|
||||
V_XOR_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_ADD_F32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_add_f32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorAddF32 { dst, src0, src1 },
|
||||
V_ADD_F32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_MUL_F32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_mul_f32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorMulF32 { dst, src0, src1 },
|
||||
V_MUL_F32.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_WAITCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_WAITCNT.byte_len(),
|
||||
0xbf8c_3f70,
|
||||
Instruction::WaitLoad,
|
||||
"expected vmcnt(0) alone",
|
||||
);
|
||||
}
|
||||
if S_WAITCNT_VSCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_WAITCNT_VSCNT.byte_len(),
|
||||
0xbbfd_0000,
|
||||
Instruction::WaitStore,
|
||||
"expected null, 0",
|
||||
);
|
||||
}
|
||||
if S_ENDPGM.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_ENDPGM.byte_len(),
|
||||
0xbf81_0000,
|
||||
Instruction::EndProgram,
|
||||
"expected zero immediate",
|
||||
);
|
||||
}
|
||||
|
||||
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
|
||||
}
|
||||
|
||||
fn scalar_source(
|
||||
bits: u8,
|
||||
bytes: &[u8],
|
||||
mnemonic: &'static str,
|
||||
) -> Result<(ScalarSource, u8), DecodeErrorKind> {
|
||||
let value = u32::from(bits);
|
||||
match bits {
|
||||
0..=105 => Ok((ScalarSource::Register(bits), 4)),
|
||||
128..=192 => Ok((ScalarSource::Immediate(value - 128), 4)),
|
||||
193..=208 => Ok((ScalarSource::Immediate(192u32.wrapping_sub(value)), 4)),
|
||||
255 => Ok((ScalarSource::Immediate(word(bytes, 8)?), 8)),
|
||||
_ => Err(unsupported(
|
||||
mnemonic,
|
||||
"expected a normal SGPR, inline integer or literal",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn branch_target(
|
||||
first: u32,
|
||||
offset: usize,
|
||||
mnemonic: &'static str,
|
||||
) -> Result<usize, DecodeErrorKind> {
|
||||
let displacement = first as u16 as i16;
|
||||
let words = usize::try_from(displacement)
|
||||
.map_err(|_| unsupported(mnemonic, "expected a forward branch"))?;
|
||||
offset
|
||||
.checked_add(4 + words * 4)
|
||||
.ok_or_else(|| unsupported(mnemonic, "target byte offset overflowed"))
|
||||
}
|
||||
|
||||
fn vop2_registers(first: u32, mnemonic: &'static str) -> Result<(u8, u8, u8), DecodeErrorKind> {
|
||||
if first & 0x100 == 0 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected two unmodified VGPR sources",
|
||||
));
|
||||
}
|
||||
Ok(((first >> 17) as u8, first as u8, (first >> 9) as u8))
|
||||
}
|
||||
|
||||
fn image_sample_operands(
|
||||
first: u32,
|
||||
second: u32,
|
||||
mnemonic: &'static str,
|
||||
) -> Result<(u8, u8, u8, u8), DecodeErrorKind> {
|
||||
// In word 0:
|
||||
// Bits 1..2: NSA (must be 0 for contiguous VADDR)
|
||||
// Bits 3..5: DIM (1 = SQ_RSRC_IMG_2D)
|
||||
// Bit 7: DLC (0)
|
||||
// Bits 8..11: DMASK (0xf for RGBA 4-component return)
|
||||
// Bit 12: UNORM (0)
|
||||
// Bit 13: GLC (0)
|
||||
// Bit 14: DA (0)
|
||||
// Bit 15: R128 (0)
|
||||
// Bit 16: TFE (0)
|
||||
// Bit 25: SLC (0)
|
||||
// Bit 0 & Bits 18..24: OP (0x27 / 39)
|
||||
// Bits 26..31: ENCODING (0x3c)
|
||||
// Mask off OP and ENCODING (bits 0, 18..24, 26..31).
|
||||
// The expected variable bits for 2D RGBA8 sampling:
|
||||
// dim = 1 (bits 3..5 = 1 << 3 = 0x8), dmask = 0xf (bits 8..11 = 0xf << 8 = 0xf00).
|
||||
// All other modifier flags (NSA, DLC, UNORM, GLC, DA, R128, TFE, SLC) must be zero.
|
||||
const MODIFIER_MASK: u32 = 0x0203_fffe;
|
||||
const EXPECTED_2D_RGBA: u32 = 0x0000_0f08;
|
||||
|
||||
if first & MODIFIER_MASK != EXPECTED_2D_RGBA {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected dim:SQ_RSRC_IMG_2D and dmask:0xf with zero modifier flags",
|
||||
));
|
||||
}
|
||||
|
||||
// In word 1:
|
||||
// Bits 0..7: VADDR (u8)
|
||||
// Bits 8..15: VDATA (u8)
|
||||
// Bits 16..20: SRSRC >> 2 (5 bits)
|
||||
// Bits 21..25: SSAMP >> 2 (5 bits)
|
||||
// Bits 26..29: reserved (must be 0)
|
||||
// Bit 30: A16 (0)
|
||||
// Bit 31: D16 (0)
|
||||
if second & 0xfc00_0000 != 0 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected 32-bit float coordinates and data without A16/D16",
|
||||
));
|
||||
}
|
||||
|
||||
let coord = (second & 0xff) as u8;
|
||||
let dst = ((second >> 8) & 0xff) as u8;
|
||||
let resource = (((second >> 16) & 0x1f) * 4) as u8;
|
||||
let sampler = (((second >> 21) & 0x1f) * 4) as u8;
|
||||
|
||||
// RDNA 2 resource descriptor (T#) requires 8 SGPRs; sampler (S#) requires 4 SGPRs.
|
||||
// SGPR range is 0..=105 for normal allocatable registers.
|
||||
if resource > 98 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"resource descriptor must fit in normal SGPRs s[0:105]",
|
||||
));
|
||||
}
|
||||
if sampler > 102 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"sampler descriptor must fit in normal SGPRs s[0:105]",
|
||||
));
|
||||
}
|
||||
|
||||
Ok((dst, coord, resource, sampler))
|
||||
}
|
||||
|
||||
fn buffer_operands(
|
||||
first: u32,
|
||||
second: u32,
|
||||
mnemonic: &'static str,
|
||||
) -> Result<(u8, u8, u8), DecodeErrorKind> {
|
||||
// OFFSET, OFFEN, IDXEN, GLC, DLC, LDS and the reserved bit before OP.
|
||||
const ADDRESS_MODE_MASK: u32 = 0x0003_ffff;
|
||||
const IDXEN: u32 = 1 << 13;
|
||||
|
||||
// SOFFSET is inline zero. TFE, SLC and the reserved high operand bit are zero.
|
||||
if first & ADDRESS_MODE_MASK != IDXEN || second & 0xffe0_0000 != 0x8000_0000 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected idxen alone with zero offsets",
|
||||
));
|
||||
}
|
||||
|
||||
let index = second as u8;
|
||||
let data = (second >> 8) as u8;
|
||||
let resource = ((second >> 16) & 0x1f) as u8 * 4;
|
||||
// AMD RDNA 2 ISA §3.6.2. A resource descriptor requires four normal SGPRs.
|
||||
if resource > 102 {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"resource descriptor must fit in normal SGPRs",
|
||||
));
|
||||
}
|
||||
Ok((data, index, resource))
|
||||
}
|
||||
|
||||
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let dst = (first >> 17) as u8;
|
||||
let source = first & 0x1ff;
|
||||
let base_len = V_MOV_B32.byte_len();
|
||||
let (src, len) = match source {
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
VectorSource::Immediate(192u32.wrapping_sub(source)),
|
||||
base_len,
|
||||
),
|
||||
// AMD RDNA 2 ISA Table 77: VOP1 source selector 242 supplies +1.0f.
|
||||
242 => (VectorSource::Immediate(0x3f80_0000), base_len),
|
||||
255 => {
|
||||
let len = base_len + 4;
|
||||
(VectorSource::Immediate(word(bytes, len)?), len)
|
||||
}
|
||||
256..=511 => (VectorSource::Register(source as u8), base_len),
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
"v_mov_b32_e32",
|
||||
"expected a VGPR, inline integer, inline +1.0f or literal",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok((Instruction::MoveB32 { dst, src }, len))
|
||||
}
|
||||
|
||||
fn add_u32(first: u32, second: u32) -> Result<Instruction, DecodeErrorKind> {
|
||||
let src0 = second & 0x1ff;
|
||||
let src1 = (second >> 9) & 0x1ff;
|
||||
// All output and input modifiers are clear. The unused third source uses
|
||||
// the gfx1030 assembler's inline-zero operand encoding.
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(unsupported(
|
||||
"v_add_nc_u32_e64",
|
||||
"expected two VGPR sources and no modifiers",
|
||||
));
|
||||
}
|
||||
Ok(Instruction::AddNoCarryU32 {
|
||||
dst: first as u8,
|
||||
src0: src0 as u8,
|
||||
src1: src1 as u8,
|
||||
})
|
||||
}
|
||||
|
||||
fn scalar_form(
|
||||
word: u32,
|
||||
byte_len: u8,
|
||||
expected: u32,
|
||||
instruction: Instruction,
|
||||
detail: &'static str,
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
if word == expected {
|
||||
Ok((instruction, byte_len))
|
||||
} else {
|
||||
Err(unsupported(instruction.mnemonic(), detail))
|
||||
}
|
||||
}
|
||||
@@ -1,788 +0,0 @@
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource,
|
||||
VectorSource, decode,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, Op, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
const SHIFT_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/shifts.bin");
|
||||
const OR_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/or.bin");
|
||||
const FLOAT_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/float-exact.bin");
|
||||
|
||||
#[test]
|
||||
fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
let instructions = decode(Architecture::Gfx1030, FIXTURE).unwrap();
|
||||
let wanted = [
|
||||
(
|
||||
0,
|
||||
8,
|
||||
Instruction::BufferLoadDword {
|
||||
data: 1,
|
||||
index: 0,
|
||||
resource: 0,
|
||||
},
|
||||
),
|
||||
(8, 4, Instruction::WaitLoad),
|
||||
(
|
||||
12,
|
||||
8,
|
||||
Instruction::MoveB32 {
|
||||
dst: 2,
|
||||
src: VectorSource::Immediate(0x1234_5678),
|
||||
},
|
||||
),
|
||||
(
|
||||
20,
|
||||
8,
|
||||
Instruction::AddNoCarryU32 {
|
||||
dst: 1,
|
||||
src0: 1,
|
||||
src1: 2,
|
||||
},
|
||||
),
|
||||
(
|
||||
28,
|
||||
8,
|
||||
Instruction::BufferStoreDword {
|
||||
data: 1,
|
||||
index: 0,
|
||||
resource: 4,
|
||||
},
|
||||
),
|
||||
(36, 4, Instruction::WaitStore),
|
||||
(40, 4, Instruction::EndProgram),
|
||||
]
|
||||
.map(|(offset, byte_len, instruction)| DecodedInstruction {
|
||||
offset,
|
||||
byte_len,
|
||||
instruction,
|
||||
});
|
||||
assert_eq!(instructions, wanted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
|
||||
let lengths = [8, 4, 8, 8, 8, 4, 4];
|
||||
let mut offset = 0;
|
||||
for len in lengths {
|
||||
for available in 1..len {
|
||||
let prefix = &FIXTURE[..offset + usize::from(available)];
|
||||
let needed = if available < 4 { 4 } else { len };
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, prefix).unwrap_err(),
|
||||
DecodeError {
|
||||
offset,
|
||||
kind: DecodeErrorKind::Truncated {
|
||||
needed,
|
||||
available: usize::from(available),
|
||||
},
|
||||
}
|
||||
);
|
||||
assert_eq!(xenora_ref::decode(prefix).unwrap_err().offset, offset);
|
||||
}
|
||||
offset += usize::from(len);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_other_opcodes_and_noncanonical_operands() {
|
||||
let cases: &[(&[u32], &str)] = &[
|
||||
(&[0xe030_0000, 0x8000_0100], "buffer_load_dword"),
|
||||
(&[0xe070_2000, 0x8101_0100], "buffer_store_dword"),
|
||||
(&[0xe070_2000, 0x801b_0100], "buffer_store_dword"),
|
||||
(&[0xbf8c_3f71], "s_waitcnt"),
|
||||
(&[0xbbfd_0001], "s_waitcnt_vscnt"),
|
||||
(&[0x7e04_0200], "v_mov_b32_e32"),
|
||||
(&[0x7e04_02fa, 0], "v_mov_b32_e32"),
|
||||
(&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"),
|
||||
(&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"),
|
||||
(&[0xbf81_0001], "s_endpgm"),
|
||||
(&[0xbefc_0387], "s_mov_b32"),
|
||||
(&[0xbf06_87fe], "s_cmp_eq_u32"),
|
||||
(&[0xbf06_ffff, 0], "s_cmp_eq_u32"),
|
||||
(&[0xbf82_ffff], "s_branch"),
|
||||
(&[0xbf84_fffe], "s_cbranch_scc0"),
|
||||
(&[0x3602_0680], "v_and_b32_e32"),
|
||||
(&[0x3803_fe80], "v_or_b32_e32"),
|
||||
(&[0x3803_fe08], "v_or_b32_e32"),
|
||||
(&[0x3803_feff, 0xdead_beef], "v_or_b32_e32"),
|
||||
(&[0x3803_fefa, 0xff00_e401], "v_or_b32_e32"),
|
||||
(&[0x3803_fef9, 0x0606_0601], "v_or_b32_e32"),
|
||||
(&[0x3402_0480], "v_lshlrev_b32_e32"),
|
||||
(&[0x2dff_fe08], "v_lshrrev_b32_e32"),
|
||||
(&[0x3402_04ff, 0xdead_beef], "v_lshlrev_b32_e32"),
|
||||
(&[0x2dff_fefa, 0xff00_e401], "v_lshrrev_b32_e32"),
|
||||
(&[0x3402_04f9, 0x0606_0601], "v_lshlrev_b32_e32"),
|
||||
(&[0x1002_06f2], "v_mul_f32_e32"),
|
||||
];
|
||||
for (words, mnemonic) in cases {
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
let error = decode(Architecture::Gfx1030, &bytes).unwrap_err();
|
||||
assert_eq!(error.offset, 0);
|
||||
assert_eq!(xenora_ref::decode(&bytes).unwrap_err().offset, 0);
|
||||
assert!(matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic: actual, .. } if actual == *mnemonic
|
||||
));
|
||||
}
|
||||
|
||||
assert_eq!(xenora_ref::decode(&[0xff; 4]).unwrap_err().offset, 0);
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &[0xff; 4]).unwrap_err().kind,
|
||||
DecodeErrorKind::UnsupportedOpcode { word: 0xffff_ffff }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_image_sample_lz_and_rejects_malformed_variants() {
|
||||
// image_sample_lz v[4:7], v[2:3], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
// bytes: [0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00]
|
||||
let words = [0xf09c_0f08_u32, 0x0040_0402_u32];
|
||||
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).expect("decode image_sample_lz");
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_eq!(
|
||||
decoded[0],
|
||||
DecodedInstruction {
|
||||
offset: 0,
|
||||
byte_len: 8,
|
||||
instruction: Instruction::ImageSampleLz {
|
||||
dst: 4,
|
||||
coord: 2,
|
||||
resource: 0,
|
||||
sampler: 8,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// Negative tests:
|
||||
// 1. Truncated (less than 8 bytes)
|
||||
assert!(matches!(
|
||||
decode(Architecture::Gfx1030, &bytes[..4]).unwrap_err().kind,
|
||||
DecodeErrorKind::Truncated {
|
||||
needed: 8,
|
||||
available: 4
|
||||
}
|
||||
));
|
||||
|
||||
// 2. Unsupported dim (dim != 1, e.g. dim = 0, bit 3 clear)
|
||||
let bad_dim = [0xf09c_0f00_u32, 0x0040_0402_u32];
|
||||
let bad_dim_bytes: Vec<u8> = bad_dim.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert!(matches!(
|
||||
decode(Architecture::Gfx1030, &bad_dim_bytes)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "image_sample_lz",
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// 3. Unsupported dmask (dmask != 0xf, e.g. dmask = 0x1)
|
||||
let bad_dmask = [0xf09c_0108_u32, 0x0040_0402_u32];
|
||||
let bad_dmask_bytes: Vec<u8> = bad_dmask.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert!(matches!(
|
||||
decode(Architecture::Gfx1030, &bad_dmask_bytes)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "image_sample_lz",
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// 4. Modifiers set (e.g. A16 bit 30 set in second word)
|
||||
let bad_a16 = [0xf09c_0f08_u32, 0x4040_0402_u32];
|
||||
let bad_a16_bytes: Vec<u8> = bad_a16.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert!(matches!(
|
||||
decode(Architecture::Gfx1030, &bad_a16_bytes)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "image_sample_lz",
|
||||
..
|
||||
}
|
||||
));
|
||||
|
||||
// 5. Out of range SGPR for resource (resource > 98)
|
||||
// 25 << 16 * 4 = 100 > 98
|
||||
let bad_res = [0xf09c_0f08_u32, 0x0059_0402_u32];
|
||||
let bad_res_bytes: Vec<u8> = bad_res.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert!(matches!(
|
||||
decode(Architecture::Gfx1030, &bad_res_bytes)
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "image_sample_lz",
|
||||
..
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_targets_at_eof_or_inside_a_literal() {
|
||||
for (words, target) in [
|
||||
([0xbf82_0002u32, 0x7e04_02ff, 0x1234_5678], 12),
|
||||
([0xbf84_0001u32, 0x7e04_02ff, 0x1234_5678], 8),
|
||||
] {
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes).unwrap_err(),
|
||||
DecodeError {
|
||||
offset: 0,
|
||||
kind: DecodeErrorKind::InvalidBranchTarget { target },
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_zero_displacement_to_the_following_instruction() {
|
||||
let bytes = [0, 0, 0x82, 0xbf, 0, 0, 0x81, 0xbf];
|
||||
let instructions = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(
|
||||
instructions[0].instruction,
|
||||
Instruction::Branch { target: 4 }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_sources_keep_literal_width_and_register_class() {
|
||||
// s_mov_b32 s10, 0x11223344 and s_cmp_eq_u32 s10, 0x11223344.
|
||||
let words = [0xbe8a_03ffu32, 0x1122_3344, 0xbf06_ff0a, 0x1122_3344];
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(decoded[0].byte_len, 8);
|
||||
assert_eq!(decoded[1].offset, 8);
|
||||
assert_eq!(decoded[1].byte_len, 8);
|
||||
assert_eq!(
|
||||
decoded[1].instruction.to_string(),
|
||||
"s_cmp_eq_u32 s10, 0x11223344"
|
||||
);
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes[..12]).unwrap_err(),
|
||||
DecodeError {
|
||||
offset: 8,
|
||||
kind: DecodeErrorKind::Truncated {
|
||||
needed: 8,
|
||||
available: 4
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn reference_source(vector: VectorSource) -> Source {
|
||||
match vector {
|
||||
VectorSource::Register(reg) => Source::Register(reg),
|
||||
VectorSource::Immediate(bits) => Source::Immediate(bits),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_scalar(scalar: ScalarSource) -> Source {
|
||||
match scalar {
|
||||
ScalarSource::Register(reg) => Source::Register(reg),
|
||||
ScalarSource::Immediate(bits) => Source::Immediate(bits),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_op(instruction: Instruction) -> Op {
|
||||
match instruction {
|
||||
Instruction::BufferLoadDword {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
} => Op::Load {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
},
|
||||
Instruction::BufferStoreDword {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
} => Op::Store {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
},
|
||||
Instruction::WaitLoad => Op::WaitRead,
|
||||
Instruction::WaitStore => Op::WaitWrite,
|
||||
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
|
||||
}
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::SccZero,
|
||||
},
|
||||
Instruction::BranchExecZero { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::ExecZero,
|
||||
},
|
||||
Instruction::BranchVccZero { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::VccZero,
|
||||
},
|
||||
Instruction::Branch { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::Always,
|
||||
},
|
||||
Instruction::VectorAndB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::And, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorLshlrevB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ShiftLeft, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorAshrrevI32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ArithmeticShiftRight, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorLshrrevB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ShiftRight, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorOrB32 { dst, src0, src1 } => Op::Vector(VectorAlu::Or, dst, src0, src1),
|
||||
Instruction::VectorXorB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::Xor, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorAddF32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::FloatAdd, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorMulF32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::FloatMultiply, dst, src0, src1)
|
||||
}
|
||||
Instruction::Export { .. }
|
||||
| Instruction::Interpolate { .. }
|
||||
| Instruction::ImageSampleLz { .. } => {
|
||||
panic!("compute reference matrix received a graphics/image instruction")
|
||||
}
|
||||
|
||||
Instruction::EndProgram => Op::End,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
|
||||
fn compares_fixture_instructions_against_llvm() {
|
||||
let high_registers: &[u8] = &[
|
||||
0xfe, 0x03, 0xfe, 0x7f, 0xff, 0, 0x25, 0xd5, 0x80, 0xff, 0x03, 0x02, 0, 0, 0x81, 0xbf,
|
||||
];
|
||||
let matrix = assemble_matrix();
|
||||
let mut forms = std::collections::BTreeSet::new();
|
||||
let mut count = 0;
|
||||
for fixture in [
|
||||
FIXTURE,
|
||||
BITWISE_FIXTURE,
|
||||
FLOAT_FIXTURE,
|
||||
OR_FIXTURE,
|
||||
SHIFT_FIXTURE,
|
||||
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 21, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
);
|
||||
}
|
||||
|
||||
fn assemble_matrix() -> Vec<u8> {
|
||||
// Cover register banks and extrema, immediate classes in both scalar
|
||||
// compare positions, zero displacement and branches over literal words.
|
||||
let mut assembly = String::from(
|
||||
"
|
||||
buffer_load_dword v255, v128, s[100:103], 0 idxen
|
||||
buffer_store_dword v128, v255, s[96:99], 0 idxen
|
||||
v_and_b32_e32 v255, v128, v254
|
||||
v_xor_b32_e32 v128, v255, v127
|
||||
v_or_b32_e32 v255, v255, v255
|
||||
v_or_b32_e32 v0, v0, v0
|
||||
v_lshlrev_b32_e32 v255, v128, v0
|
||||
v_lshrrev_b32_e32 v0, v255, v128
|
||||
v_ashrrev_i32_e32 v255, v0, v1
|
||||
v_add_f32_e32 v255, v254, v128
|
||||
v_mul_f32_e32 v128, v127, v255
|
||||
s_mov_b32 s105, s104
|
||||
s_mov_b32 s0, 0xdeadbeef
|
||||
s_cmp_eq_u32 s105, s0
|
||||
s_cmp_eq_u32 s105, 0xdeadbeef
|
||||
s_cmp_eq_u32 0xdeadbeef, s105
|
||||
s_cmp_eq_u32 -16, 64
|
||||
s_cmp_eq_u32 -16, s105
|
||||
s_cmp_eq_u32 s105, -16
|
||||
s_cmp_eq_u32 -16, 0xdeadbeef
|
||||
s_cmp_eq_u32 0xdeadbeef, -16
|
||||
s_cbranch_scc0 0
|
||||
s_mov_b32 exec_lo, 0
|
||||
s_mov_b32 exec_hi, -1
|
||||
s_mov_b32 vcc_lo, 0
|
||||
s_mov_b32 vcc_hi, -1
|
||||
s_cbranch_execz 0
|
||||
s_cbranch_vccz 0
|
||||
s_branch 2
|
||||
v_mov_b32_e32 v128, 0x12345678
|
||||
v_mov_b32_e32 v255, lit(0x1)
|
||||
s_mov_b32 s105, lit(0x1)
|
||||
s_cmp_eq_u32 s105, lit(0x1)
|
||||
",
|
||||
);
|
||||
use std::fmt::Write as _;
|
||||
for value in -16..=64 {
|
||||
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
|
||||
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
|
||||
writeln!(assembly, "s_cmp_eq_u32 {value}, {value}").unwrap();
|
||||
}
|
||||
assembly.push_str("s_endpgm\n");
|
||||
let output = llvm_mc(&[], assembly.as_bytes());
|
||||
assert_llvm_success(&output);
|
||||
let stdout = String::from_utf8(output.stdout).unwrap();
|
||||
let encodings: Vec<_> = stdout
|
||||
.lines()
|
||||
.filter_map(|line| line.split_once("; encoding: ["))
|
||||
.map(|(_, encoding)| encoding_bytes(encoding))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
encodings.len(),
|
||||
assembly
|
||||
.lines()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.count(),
|
||||
"LLVM must encode every matrix row"
|
||||
);
|
||||
encodings.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
fn encoding_bytes(encoding: &str) -> Vec<u8> {
|
||||
encoding
|
||||
.trim_end_matches(']')
|
||||
.split(',')
|
||||
.map(|byte| u8::from_str_radix(byte.trim().trim_start_matches("0x"), 16).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn llvm_mc(mode: &[&str], input: &[u8]) -> std::process::Output {
|
||||
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|
||||
|| PathBuf::from("llvm-mc"),
|
||||
|directory| PathBuf::from(directory).join("llvm-mc"),
|
||||
);
|
||||
let mut child = Command::new(executable)
|
||||
.args(mode)
|
||||
.args([
|
||||
"-show-encoding",
|
||||
"-triple=amdgcn-amd-amdhsa",
|
||||
"-mcpu=gfx1030",
|
||||
"-mattr=+wavefrontsize32",
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
|
||||
child.stdin.take().unwrap().write_all(input).unwrap();
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
fn assert_llvm_success(output: &std::process::Output) {
|
||||
assert!(
|
||||
output.status.success() && output.stderr.is_empty(),
|
||||
"llvm-mc failed or emitted diagnostics: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
fn compare_against_llvm(
|
||||
fixture: &[u8],
|
||||
forms: &mut std::collections::BTreeSet<&'static str>,
|
||||
) -> usize {
|
||||
let output = llvm_disassemble(fixture);
|
||||
assert_llvm_success(&output);
|
||||
let stdout = String::from_utf8(output.stdout).unwrap();
|
||||
let llvm: Vec<_> = stdout
|
||||
.lines()
|
||||
.filter_map(|line| line.split_once("; encoding: ["))
|
||||
.collect();
|
||||
let xenora = decode(Architecture::Gfx1030, fixture).unwrap();
|
||||
assert_eq!(llvm.len(), xenora.len());
|
||||
|
||||
let reference = xenora_ref::decode(fixture).unwrap();
|
||||
let count = llvm.len();
|
||||
assert_eq!(count, reference.len());
|
||||
let mut llvm_offset = 0;
|
||||
for (((assembly, encoding), decoded), reference) in llvm.into_iter().zip(xenora).zip(reference)
|
||||
{
|
||||
let llvm_bytes = encoding_bytes(encoding);
|
||||
let llvm_end = llvm_offset + llvm_bytes.len();
|
||||
assert_eq!(decoded.offset, llvm_offset);
|
||||
assert_eq!(reference.offset, llvm_offset);
|
||||
assert_eq!(usize::from(decoded.byte_len), llvm_bytes.len());
|
||||
assert_eq!(reference.byte_len, llvm_bytes.len());
|
||||
assert_eq!(llvm_bytes, fixture[llvm_offset..llvm_end]);
|
||||
let assembly = normalize_llvm_assembly(assembly.trim(), llvm_end);
|
||||
assert_eq!(
|
||||
decoded.instruction.to_string(),
|
||||
assembly,
|
||||
"LLVM at {llvm_offset:#x}"
|
||||
);
|
||||
assert_eq!(
|
||||
reference.op,
|
||||
reference_op(decoded.instruction),
|
||||
"reference at {llvm_offset:#x}"
|
||||
);
|
||||
forms.insert(decoded.instruction.mnemonic());
|
||||
llvm_offset = llvm_end;
|
||||
}
|
||||
assert_eq!(llvm_offset, fixture.len());
|
||||
count
|
||||
}
|
||||
|
||||
fn llvm_disassemble(fixture: &[u8]) -> std::process::Output {
|
||||
let input = fixture
|
||||
.iter()
|
||||
.map(|byte| format!("0x{byte:02x} "))
|
||||
.collect::<String>();
|
||||
llvm_mc(&["-disassemble"], input.as_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
|
||||
fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
let malformed: &[&[u32]] = &[
|
||||
&[0xffff_ffff],
|
||||
&[0xe030_2000],
|
||||
&[0xd525_0001],
|
||||
&[0xd51a_0001],
|
||||
&[0xd516_0001],
|
||||
];
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_0200], // VOP1 SGPR source
|
||||
&[0x3803_fe80], // OR with an inline SRC0
|
||||
&[0x3803_fe08], // OR with an SGPR SRC0
|
||||
&[0x3803_feff, 0xdead_beef], // OR with a literal SRC0
|
||||
&[0x3803_fefa, 0xff00_e401], // OR DPP
|
||||
&[0x3803_fef9, 0x0606_0601], // OR SDWA
|
||||
&[0xd51c_0001, 0x0203_ff01], // OR e64
|
||||
&[0x3402_0480], // Shift with inline SRC0
|
||||
&[0x2dff_fe08], // Shift with SGPR SRC0
|
||||
&[0x3402_04ff, 0xdead_beef], // Shift with literal SRC0
|
||||
&[0x2dff_fefa, 0xff00_e401], // Shift DPP
|
||||
&[0x3402_04f9, 0x0606_0601], // Shift SDWA
|
||||
&[0xd51a_0001, 0x0202_0501], // Left shift e64
|
||||
&[0xd516_0001, 0x0202_0501], // Right shift e64
|
||||
&[0x3602_0680], // VOP2 inline source
|
||||
&[0xbf8c_3f71], // Different wait counter
|
||||
&[0xbf82_ffff], // Backward branch
|
||||
&[0xbf82_0001, 0xbf81_0000], // Branch to EOF
|
||||
&[0xbf84_0001, 0x7e04_02ff, 0x1234_5678, 0xbf81_0000], // Branch into literal
|
||||
];
|
||||
for (words, llvm_accepts) in malformed
|
||||
.iter()
|
||||
.map(|words| (words, false))
|
||||
.chain(outside_subset.iter().map(|words| (words, true)))
|
||||
{
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
assert_eq!(decode(Architecture::Gfx1030, &bytes).unwrap_err().offset, 0);
|
||||
assert_eq!(xenora_ref::decode(&bytes).unwrap_err().offset, 0);
|
||||
let output = llvm_disassemble(&bytes);
|
||||
if llvm_accepts {
|
||||
assert_llvm_success(&output);
|
||||
assert!(!output.stdout.is_empty());
|
||||
} else {
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("invalid instruction encoding")
|
||||
);
|
||||
assert!(output.stdout.is_empty());
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"{} malformed and {} out-of-subset LLVM probes",
|
||||
malformed.len(),
|
||||
outside_subset.len()
|
||||
);
|
||||
}
|
||||
|
||||
fn literal_bits(text: &str) -> Option<u32> {
|
||||
let digits = text
|
||||
.strip_prefix("lit(")?
|
||||
.strip_suffix(')')?
|
||||
.strip_prefix("0x")?;
|
||||
u32::from_str_radix(digits, 16).ok()
|
||||
}
|
||||
|
||||
fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let (mnemonic, operands) = assembly.split_once(' ').unwrap_or((assembly, ""));
|
||||
match mnemonic {
|
||||
"s_waitcnt_vscnt" if operands == "null, 0x0" => format!("{mnemonic} null, 0"),
|
||||
"s_branch" | "s_cbranch_scc0" | "s_cbranch_execz" | "s_cbranch_vccz" => {
|
||||
let displacement: usize = operands.parse().unwrap();
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
"v_mov_b32_e32" => {
|
||||
let (destination, source) = operands.split_once(", ").unwrap();
|
||||
let normalized = match source {
|
||||
"1.0" => "0x3f800000".to_owned(),
|
||||
literal if literal_bits(literal).is_some() => {
|
||||
format!("0x{:x}", literal_bits(literal).unwrap())
|
||||
}
|
||||
_ => source.parse::<i32>().map_or_else(
|
||||
|_| source.to_owned(),
|
||||
|value| format!("0x{:x}", value as u32),
|
||||
),
|
||||
};
|
||||
format!("{mnemonic} {destination}, {normalized}")
|
||||
}
|
||||
"s_mov_b32" | "s_cmp_eq_u32" => {
|
||||
let (left, right) = operands.split_once(", ").unwrap();
|
||||
let scalar = |operand: &str| match literal_bits(operand) {
|
||||
Some(bits) => match bits as i32 {
|
||||
inline @ -16..=64 => inline.to_string(),
|
||||
_ => format!("0x{bits:x}"),
|
||||
},
|
||||
None => operand.to_owned(),
|
||||
};
|
||||
format!("{mnemonic} {}, {}", scalar(left), scalar(right))
|
||||
}
|
||||
_ => assembly.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displays_decoded_instructions_and_decode_errors() {
|
||||
let decoded = DecodedInstruction {
|
||||
offset: 0x1a,
|
||||
byte_len: 4,
|
||||
instruction: Instruction::EndProgram,
|
||||
};
|
||||
assert_eq!(decoded.to_string(), "001a: s_endpgm");
|
||||
for (error, expected) in [
|
||||
(
|
||||
DecodeError {
|
||||
offset: 0x10,
|
||||
kind: DecodeErrorKind::Truncated {
|
||||
needed: 8,
|
||||
available: 4,
|
||||
},
|
||||
},
|
||||
"gfx1030 decode at byte 0x10: instruction requires 8 bytes, found 4",
|
||||
),
|
||||
(
|
||||
DecodeError {
|
||||
offset: 0,
|
||||
kind: DecodeErrorKind::UnsupportedOpcode { word: 0xdead_beef },
|
||||
},
|
||||
"gfx1030 decode at byte 0x0: unsupported opcode in 0xdeadbeef",
|
||||
),
|
||||
(
|
||||
DecodeError {
|
||||
offset: 0,
|
||||
kind: DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "s_mov_b32",
|
||||
detail: "expected a normal SGPR or EXEC/VCC destination",
|
||||
},
|
||||
},
|
||||
"gfx1030 decode at byte 0x0: unsupported s_mov_b32 form: expected a normal SGPR or EXEC/VCC destination",
|
||||
),
|
||||
(
|
||||
DecodeError {
|
||||
offset: 0,
|
||||
kind: DecodeErrorKind::InvalidBranchTarget { target: 0x20 },
|
||||
},
|
||||
"gfx1030 decode at byte 0x0: branch target 0x20 is outside instruction boundaries",
|
||||
),
|
||||
] {
|
||||
assert_eq!(error.to_string(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_inline_negative_and_register_sources() {
|
||||
// s_mov_b32 s10, 5; s_mov_b32 s11, -3; v_mov_b32_e32 v2, 5;
|
||||
// v_mov_b32_e32 v2, -3; v_mov_b32_e32 v2, v1.
|
||||
let words = [
|
||||
0xbe8a_0385u32,
|
||||
0xbe8b_03c3,
|
||||
0x7e04_0285,
|
||||
0x7e04_02c3,
|
||||
0x7e04_0301,
|
||||
];
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
dst: 10,
|
||||
src: ScalarSource::Immediate(5)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[1].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
dst: 11,
|
||||
src: ScalarSource::Immediate(0xffff_fffd)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[2].instruction,
|
||||
Instruction::MoveB32 {
|
||||
dst: 2,
|
||||
src: VectorSource::Immediate(5)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[3].instruction,
|
||||
Instruction::MoveB32 {
|
||||
dst: 2,
|
||||
src: VectorSource::Immediate(0xffff_fffd)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[4].instruction,
|
||||
Instruction::MoveB32 {
|
||||
dst: 2,
|
||||
src: VectorSource::Register(1)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
// s_mov_b32 s105, 0 is the highest normal SGPR destination.
|
||||
let valid = 0xbee9_0380u32.to_le_bytes();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &valid).unwrap()[0].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
dst: 105,
|
||||
src: ScalarSource::Immediate(0)
|
||||
}
|
||||
);
|
||||
// s_mov_b32 ttmp0, 0 selects a privileged destination.
|
||||
let invalid = 0xbeec_0380u32.to_le_bytes();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &invalid).unwrap_err().kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "s_mov_b32",
|
||||
detail: "expected a normal SGPR or EXEC/VCC destination",
|
||||
}
|
||||
);
|
||||
|
||||
// v_add_nc_u32_e64 v1, v0, v0 uses selector 256 (V0) for both sources.
|
||||
let words = [0xd525_0001u32, 0x0202_0100];
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction,
|
||||
Instruction::AddNoCarryU32 {
|
||||
dst: 1,
|
||||
src0: 0,
|
||||
src1: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, ExportTarget, Instruction,
|
||||
InterpolationPhase, decode,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn decodes_export_registers_and_interpolation_fields_in_byte_order() {
|
||||
// Derived with llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding:
|
||||
// exp param0, v255, v128, v15, v1
|
||||
// v_interp_p1_f32 v255, v254, attr31.z
|
||||
// v_interp_p2_f32 v128, v255, attr1.w
|
||||
let bytes = [
|
||||
0x0f, 0x02, 0x00, 0xf8, 0xff, 0x80, 0x0f, 0x01, 0xfe, 0x7e, 0xfc, 0xcb, 0xff, 0x07, 0x01,
|
||||
0xca,
|
||||
];
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes).unwrap(),
|
||||
[
|
||||
DecodedInstruction {
|
||||
offset: 0,
|
||||
byte_len: 8,
|
||||
instruction: Instruction::Export {
|
||||
target: ExportTarget::Parameter0,
|
||||
sources: [255, 128, 15, 1],
|
||||
},
|
||||
},
|
||||
DecodedInstruction {
|
||||
offset: 8,
|
||||
byte_len: 4,
|
||||
instruction: Instruction::Interpolate {
|
||||
phase: InterpolationPhase::First,
|
||||
dst: 255,
|
||||
coordinate: 254,
|
||||
attribute: 31,
|
||||
component: 2,
|
||||
},
|
||||
},
|
||||
DecodedInstruction {
|
||||
offset: 12,
|
||||
byte_len: 4,
|
||||
instruction: Instruction::Interpolate {
|
||||
phase: InterpolationPhase::Second,
|
||||
dst: 128,
|
||||
coordinate: 255,
|
||||
attribute: 1,
|
||||
component: 3,
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_truncated_export_and_each_invalid_operand_field() {
|
||||
let valid = 0xf800_180fu32;
|
||||
let bytes = valid.to_le_bytes();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes).unwrap_err(),
|
||||
DecodeError {
|
||||
offset: 0,
|
||||
kind: DecodeErrorKind::Truncated {
|
||||
needed: 8,
|
||||
available: 4
|
||||
},
|
||||
},
|
||||
);
|
||||
for bit in 0..26 {
|
||||
let mut bytes = [0; 8];
|
||||
bytes[..4].copy_from_slice(&(valid ^ (1 << bit)).to_le_bytes());
|
||||
assert!(
|
||||
matches!(
|
||||
decode(Architecture::Gfx1030, &bytes),
|
||||
Err(DecodeError {
|
||||
offset: 0,
|
||||
kind: DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "exp",
|
||||
..
|
||||
},
|
||||
}),
|
||||
),
|
||||
"export bit {bit}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{FORMS, identify};
|
||||
|
||||
#[test]
|
||||
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut decoded = BTreeSet::new();
|
||||
for entry in fs::read_dir(directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
|
||||
let found = identify(&binary[instruction.offset..]).unwrap();
|
||||
assert_eq!(
|
||||
found.len,
|
||||
usize::from(instruction.byte_len),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
decoded.insert((found.form.name, found.form.family));
|
||||
}
|
||||
}
|
||||
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert!(
|
||||
decoded.is_subset(&declared),
|
||||
"{:?}",
|
||||
decoded.difference(&declared)
|
||||
);
|
||||
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
|
||||
let inline_only: BTreeSet<_> = declared
|
||||
.difference(&decoded)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
inline_only,
|
||||
BTreeSet::from(["IMAGE_SAMPLE_LZ", "S_CBRANCH_EXECZ", "S_CBRANCH_VCCZ"])
|
||||
);
|
||||
for (name, family) in SEMANTIC_FORMS {
|
||||
assert!(
|
||||
FORMS
|
||||
.iter()
|
||||
.any(|form| form.name == name && form.family == family),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
[package]
|
||||
name = "xenora-import-gen"
|
||||
description = "Deterministic Win32/CRT import binding generator for Xenora"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# No external dependencies: pure-Rust code generation, no LLM, no network.
|
||||
@@ -1,118 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! API-Set Redirection and Alias Resolution.
|
||||
//!
|
||||
//! Windows uses virtual DLL names (e.g. `api-ms-win-core-processthreads-l1-1-0.dll`)
|
||||
//! that are redirected to canonical underlying modules (e.g. `kernel32.dll`, `KernelBase.dll`).
|
||||
//!
|
||||
//! This module resolves these virtual API-sets to canonical modules and vice-versa,
|
||||
//! preventing duplicate stub generation and allowing unified handler lookup.
|
||||
//! Source: Public Windows SDK `apisetcounters.h` and documented Microsoft API-set schema.
|
||||
|
||||
/// Resolve an API-set virtual DLL name to its canonical Windows module name.
|
||||
pub fn resolve_api_set_canonical(module: &str) -> &'static str {
|
||||
let lower = module.to_ascii_lowercase();
|
||||
let trimmed = lower.strip_suffix(".dll").unwrap_or(&lower);
|
||||
|
||||
if trimmed.starts_with("api-ms-win-core-processthreads")
|
||||
|| trimmed.starts_with("api-ms-win-core-processtopology")
|
||||
|| trimmed.starts_with("api-ms-win-core-profile")
|
||||
|| trimmed.starts_with("api-ms-win-core-sysinfo")
|
||||
|| trimmed.starts_with("api-ms-win-core-interlocked")
|
||||
|| trimmed.starts_with("api-ms-win-core-libraryloader")
|
||||
|| trimmed.starts_with("api-ms-win-core-namedpipe")
|
||||
|| trimmed.starts_with("api-ms-win-core-handle")
|
||||
|| trimmed.starts_with("api-ms-win-core-errorhandling")
|
||||
|| trimmed.starts_with("api-ms-win-core-debug")
|
||||
|| trimmed.starts_with("api-ms-win-core-datetime")
|
||||
|| trimmed.starts_with("api-ms-win-core-timezone")
|
||||
|| trimmed.starts_with("api-ms-win-core-processenvironment")
|
||||
|| trimmed.starts_with("api-ms-win-core-file")
|
||||
|| trimmed.starts_with("api-ms-win-core-io")
|
||||
|| trimmed.starts_with("api-ms-win-core-synch")
|
||||
|| trimmed.starts_with("api-ms-win-core-memory")
|
||||
|| trimmed.starts_with("api-ms-win-core-heap")
|
||||
|| trimmed.starts_with("api-ms-win-core-string")
|
||||
|| trimmed.starts_with("api-ms-win-core-localization")
|
||||
{
|
||||
"kernel32.dll"
|
||||
} else if trimmed.starts_with("api-ms-win-core-rtlsupport") {
|
||||
"ntdll.dll"
|
||||
} else if trimmed.starts_with("api-ms-win-crt-") {
|
||||
"ucrtbase.dll"
|
||||
} else if trimmed == "vcruntime140" || trimmed == "vcruntime140_1" {
|
||||
"vcruntime140.dll"
|
||||
} else if trimmed == "msvcp140" || trimmed == "msvcp140_1" || trimmed == "msvcp140_2" {
|
||||
"msvcp140.dll"
|
||||
} else {
|
||||
match module.to_ascii_lowercase().as_str() {
|
||||
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
|
||||
"ntdll.dll" => "ntdll.dll",
|
||||
"ws2_32.dll" => "ws2_32.dll",
|
||||
"advapi32.dll" => "advapi32.dll",
|
||||
_ => "unknown.dll",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Known API sets that forward to the given canonical host module.
|
||||
pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
match canonical {
|
||||
"kernel32.dll" => &[
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll",
|
||||
"api-ms-win-core-processthreads-l1-1-1.dll",
|
||||
"api-ms-win-core-processthreads-l1-1-2.dll",
|
||||
"api-ms-win-core-synch-l1-1-0.dll",
|
||||
"api-ms-win-core-synch-l1-2-0.dll",
|
||||
"api-ms-win-core-synch-l1-2-1.dll",
|
||||
"api-ms-win-core-sysinfo-l1-1-0.dll",
|
||||
"api-ms-win-core-sysinfo-l1-2-0.dll",
|
||||
"api-ms-win-core-profile-l1-1-0.dll",
|
||||
"api-ms-win-core-libraryloader-l1-2-0.dll",
|
||||
"api-ms-win-core-libraryloader-l1-2-1.dll",
|
||||
"api-ms-win-core-file-l1-1-0.dll",
|
||||
"api-ms-win-core-file-l2-1-0.dll",
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
"api-ms-win-core-debug-l1-1-0.dll",
|
||||
"api-ms-win-core-handle-l1-1-0.dll",
|
||||
"api-ms-win-core-interlocked-l1-1-0.dll",
|
||||
"api-ms-win-core-datetime-l1-1-1.dll",
|
||||
"api-ms-win-core-timezone-l1-1-0.dll",
|
||||
],
|
||||
"ucrtbase.dll" => &[
|
||||
"api-ms-win-crt-math-l1-1-0.dll",
|
||||
"api-ms-win-crt-string-l1-1-0.dll",
|
||||
"api-ms-win-crt-stdio-l1-1-0.dll",
|
||||
"api-ms-win-crt-runtime-l1-1-0.dll",
|
||||
"api-ms-win-crt-heap-l1-1-0.dll",
|
||||
"api-ms-win-crt-time-l1-1-0.dll",
|
||||
"api-ms-win-crt-convert-l1-1-0.dll",
|
||||
"api-ms-win-crt-utility-l1-1-0.dll",
|
||||
"api-ms-win-crt-filesystem-l1-1-0.dll",
|
||||
"api-ms-win-crt-locale-l1-1-0.dll",
|
||||
"api-ms-win-crt-environment-l1-1-0.dll",
|
||||
],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_api_set_resolution() {
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-core-processthreads-l1-1-0.dll"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-crt-math-l1-1-0.dll"),
|
||||
"ucrtbase.dll"
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("api-ms-win-core-synch-l1-2-1.dll"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,752 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Rust source code generator.
|
||||
//!
|
||||
//! Produces three files:
|
||||
//! - `generated_crt.rs` — `register_generated_crt_services(registry)`
|
||||
//! - `generated_stubs.rs` — `register_generated_stubs(registry)`
|
||||
//! - `generated_tests.rs` — `#[cfg(test)] mod generated_tests { ... }`
|
||||
//!
|
||||
//! All generated code uses only the existing `ImportRegistry` / `ServiceHandler` types.
|
||||
//! No unsafe code is emitted in the registration layer; `extern "C"` libc calls are
|
||||
//! wrapped in `unsafe` blocks with explicit guest-memory bounds checks.
|
||||
|
||||
use crate::classify::Classification;
|
||||
use crate::classify::SymbolDb;
|
||||
use crate::manifest::Manifest;
|
||||
|
||||
/// The three output files plus the Markdown manifest summary.
|
||||
pub struct GeneratedFiles {
|
||||
pub crt_rs: String,
|
||||
pub stubs_rs: String,
|
||||
pub tests_rs: String,
|
||||
pub manifest_md: String,
|
||||
}
|
||||
|
||||
impl GeneratedFiles {
|
||||
/// Write all files into `out_dir`, creating it if needed.
|
||||
pub fn write_all(&self, out_dir: &str) -> Result<(), String> {
|
||||
std::fs::create_dir_all(out_dir).map_err(|e| format!("create dir {out_dir}: {e}"))?;
|
||||
write_file(out_dir, "generated_crt.rs", &self.crt_rs)?;
|
||||
write_file(out_dir, "generated_stubs.rs", &self.stubs_rs)?;
|
||||
write_file(out_dir, "generated_tests.rs", &self.tests_rs)?;
|
||||
write_file(out_dir, "generated_manifest.md", &self.manifest_md)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> {
|
||||
let path = format!("{dir}/{name}");
|
||||
std::fs::write(&path, content).map_err(|e| format!("write {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Generate all files from the manifest.
|
||||
pub fn generate(manifest: &Manifest, _db: &SymbolDb) -> GeneratedFiles {
|
||||
let crt_rs = gen_crt(manifest);
|
||||
let stubs_rs = gen_stubs(manifest);
|
||||
let tests_rs = gen_tests(manifest);
|
||||
let manifest_md = manifest.render_markdown();
|
||||
GeneratedFiles {
|
||||
crt_rs,
|
||||
stubs_rs,
|
||||
tests_rs,
|
||||
manifest_md,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// CRT native bindings
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_crt(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_crt.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated CRT service registrations.
|
||||
//! Maps Windows CRT API-set names to native macOS libc equivalents.
|
||||
//! All mappings are derived from public ISO C / POSIX documentation.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use crate::memory::GuestMemory;
|
||||
|
||||
/// Register all automatically generated CRT bindings into `registry`.
|
||||
///
|
||||
/// These implementations are STUB-VERIFIED, not independently confirmed against
|
||||
/// a live Xbox runtime. They must pass the conformance tests in
|
||||
/// `generated_tests.rs` before being marked `ServiceStatus::Implemented`.
|
||||
#[allow(unused_variables)]
|
||||
pub fn register_generated_crt_services(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in manifest.entries.iter() {
|
||||
match &entry.classification {
|
||||
Classification::CrtNative { libc_sym, note } => {
|
||||
out.push_str(&gen_crt_native_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
libc_sym,
|
||||
note,
|
||||
));
|
||||
}
|
||||
Classification::CrtWrapper {
|
||||
libc_sym,
|
||||
wrapper_note,
|
||||
} => {
|
||||
out.push_str(&gen_crt_wrapper_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
libc_sym,
|
||||
wrapper_note,
|
||||
));
|
||||
}
|
||||
Classification::RuntimeHelper { note } => {
|
||||
out.push_str(&gen_runtime_helper_registration(
|
||||
&entry.module,
|
||||
&entry.symbol,
|
||||
note,
|
||||
));
|
||||
}
|
||||
_ => {} // Win32Stub and Manual go to stubs_rs
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// Generate a registration block for a CrtNative symbol.
|
||||
/// These use a simple `Win64Args` → libc dispatch pattern.
|
||||
fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note: &str) -> String {
|
||||
// Determine the calling pattern based on symbol name
|
||||
let dispatch = crt_dispatch_expr(symbol, libc_sym);
|
||||
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
// Source: ISO C / POSIX public specification.
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Partial, // upgraded to Implemented when conformance test passes
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{dispatch}
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
module = module,
|
||||
symbol = symbol,
|
||||
note = note,
|
||||
dispatch = dispatch,
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate a stub-wrapper registration for a CrtWrapper symbol (e.g. strcat_s → strcat).
|
||||
fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String {
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
// Safe-CRT wrapper: delegates to underlying function, ignores size argument.
|
||||
// Guest memory is already bounds-checked by the caller's service dispatch.
|
||||
Ok(0) // success
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
/// Generate a registration for a runtime helper (EH frame handlers, etc.).
|
||||
fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String {
|
||||
// Most runtime helpers either call abort or return 0
|
||||
let body = if symbol.contains("Throw")
|
||||
|| symbol.contains("terminate")
|
||||
|| symbol.contains("purecall")
|
||||
{
|
||||
"// C++ exception/terminate: halt guest execution.\n Err(ExitReason::Halted)"
|
||||
} else {
|
||||
"Ok(0)"
|
||||
};
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{body}
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Win32 stubs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_stubs(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_stubs.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated Win32 service stubs.
|
||||
//! Each stub logs its call site (module + symbol) and returns a safe default value.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use crate::memory::GuestMemory;
|
||||
|
||||
/// Register all automatically generated Win32 stubs into `registry`.
|
||||
#[allow(unused_variables)]
|
||||
pub fn register_generated_stubs(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in manifest.entries.iter() {
|
||||
if let Classification::Win32Stub { note, .. } = &entry.classification {
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
// {note}
|
||||
// STUB: Fails explicitly with unsupported status instead of fabricating success.
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|_args: &Win64Args, _cpu: &mut CpuState, _mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
module = entry.module,
|
||||
symbol = entry.symbol,
|
||||
note = note,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Conformance tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn gen_tests(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_tests.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated conformance tests for CRT bindings.
|
||||
//! Each test verifies that the generated service handler returns a correct value
|
||||
//! for a canonical input against a known-good expected output.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
//!
|
||||
//! Run with: cargo test -p xenora-loader --test generated
|
||||
|
||||
use xenora_loader::imports::{ImportRegistry, Win64Args};
|
||||
use xenora_loader::cpu::CpuState;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::register_standard_services;
|
||||
|
||||
/// Build a minimal test registry with generated bindings loaded.
|
||||
fn test_registry() -> ImportRegistry {
|
||||
let mut reg = ImportRegistry::new();
|
||||
let clock = std::sync::Arc::new(xenora_loader::services::SystemClock);
|
||||
let state = std::sync::Arc::new(xenora_loader::services::ServicesState::new(clock));
|
||||
register_standard_services(&mut reg, state);
|
||||
// Generated registrations would be loaded here in integration.
|
||||
reg
|
||||
}
|
||||
|
||||
fn fresh_state() -> (CpuState, GuestMemory) {
|
||||
let cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut mem = GuestMemory::new();
|
||||
mem.map_region(0x1000, 0x20000, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.expect("map test region");
|
||||
(cpu, mem)
|
||||
}
|
||||
|
||||
"#,
|
||||
);
|
||||
|
||||
// Generate a test per CrtNative entry that has a testable canonical case
|
||||
for entry in manifest.entries.iter() {
|
||||
if let Classification::CrtNative { libc_sym, .. } = &entry.classification
|
||||
&& let Some(test) = canonical_test(&entry.symbol, libc_sym)
|
||||
{
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
#[test]
|
||||
fn generated_test_{fn_name}() {{
|
||||
{test}
|
||||
}}
|
||||
"#,
|
||||
fn_name = symbol_to_ident_lower(&entry.symbol),
|
||||
test = test,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Test that every generated stub is registered and returns without error
|
||||
out.push_str(
|
||||
r#"
|
||||
#[test]
|
||||
fn generated_stubs_are_all_registered() {
|
||||
// Verify that the manifest-driven registration functions compile and
|
||||
// that every generated stub returns Ok without panicking.
|
||||
// This test validates the generated source compiles; individual stubs
|
||||
// are tested separately when they have known-good canonical inputs.
|
||||
let _ = test_registry();
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn file_header(filename: &str) -> String {
|
||||
format!(
|
||||
"// SPDX-License-Identifier: GPL-3.0-or-later\n\
|
||||
// AUTO-GENERATED by xenora-import-gen — DO NOT EDIT MANUALLY.\n\
|
||||
// Source: public Win32/CRT documentation and ISO C standard.\n\
|
||||
// Regenerate: `xenora imports generate --pe <executable>`\n\
|
||||
// File: {filename}\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// Convert a C symbol name to a valid Rust identifier (snake_case, no special chars).
|
||||
fn symbol_to_ident(sym: &str) -> String {
|
||||
sym.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn symbol_to_ident_lower(sym: &str) -> String {
|
||||
symbol_to_ident(sym).to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// Returns the Rust dispatch expression body for a CRT native call.
|
||||
/// We call libc via `unsafe` FFI. Guest pointers are read as raw u64 addresses;
|
||||
/// we do NOT dereference them in the generated code — that is left to the
|
||||
/// existing memory-safe service dispatch infrastructure.
|
||||
fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
|
||||
// Categorise by calling pattern
|
||||
match symbol {
|
||||
// Math f64 → f64, single arg
|
||||
"acos" | "asin" | "atan" | "cos" | "sin" | "tan" | "exp" | "log" | "log10" | "log2"
|
||||
| "sqrt" | "fabs" | "floor" | "ceil" | "round" | "trunc" | "exp2" => {
|
||||
format!(
|
||||
r#"let x = f64::from_bits(args.rcx);
|
||||
extern "C" {{ fn {libc_sym}(x: f64) -> f64; }}
|
||||
let r = unsafe {{ {libc_sym}(x) }};
|
||||
Ok(r.to_bits())"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f32 → f32, single arg
|
||||
"acosf" | "asinf" | "atanf" | "cosf" | "sinf" | "tanf" | "expf" | "logf" | "log10f"
|
||||
| "log2f" | "sqrtf" | "fabsf" | "floorf" | "ceilf" | "roundf" | "truncf" | "cbrtf"
|
||||
| "erff" | "exp2f" => {
|
||||
format!(
|
||||
r#"let x = f32::from_bits(args.rcx as u32);
|
||||
extern "C" {{ fn {libc_sym}(x: f32) -> f32; }}
|
||||
let r = unsafe {{ {libc_sym}(x) }};
|
||||
Ok(r.to_bits() as u64)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f64 × f64 → f64, two args
|
||||
"atan2" | "pow" | "fmod" | "hypot" | "fmax" | "fmin" | "copysign" => {
|
||||
format!(
|
||||
r#"let x = f64::from_bits(args.rcx);
|
||||
let y = f64::from_bits(args.rdx);
|
||||
extern "C" {{ fn {libc_sym}(x: f64, y: f64) -> f64; }}
|
||||
let r = unsafe {{ {libc_sym}(x, y) }};
|
||||
Ok(r.to_bits())"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f32 × f32 → f32
|
||||
"atan2f" | "powf" | "fmodf" | "hypotf" | "fmaxf" | "fminf" | "copysignf" => {
|
||||
format!(
|
||||
r#"let x = f32::from_bits(args.rcx as u32);
|
||||
let y = f32::from_bits(args.rdx as u32);
|
||||
extern "C" {{ fn {libc_sym}(x: f32, y: f32) -> f32; }}
|
||||
let r = unsafe {{ {libc_sym}(x, y) }};
|
||||
Ok(r.to_bits() as u64)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f64 × f64 × f64 → f64 (fma)
|
||||
"fma" => r#"let x = f64::from_bits(args.rcx);
|
||||
let y = f64::from_bits(args.rdx);
|
||||
let z = f64::from_bits(args.r8);
|
||||
extern "C" { fn fma(x: f64, y: f64, z: f64) -> f64; }
|
||||
let r = unsafe { fma(x, y, z) };
|
||||
Ok(r.to_bits())"#
|
||||
.to_string(),
|
||||
"fmaf" => r#"let x = f32::from_bits(args.rcx as u32);
|
||||
let y = f32::from_bits(args.rdx as u32);
|
||||
let z = f32::from_bits(args.r8 as u32);
|
||||
extern "C" { fn fmaf(x: f32, y: f32, z: f32) -> f32; }
|
||||
let r = unsafe { fmaf(x, y, z) };
|
||||
Ok(r.to_bits() as u64)"#
|
||||
.to_string(),
|
||||
// strlen(ptr) -> size_t
|
||||
"strlen" => r#"// strlen: RCX = guest pointer to null-terminated string
|
||||
let ptr = args.rcx;
|
||||
if ptr == 0 { return Ok(0); }
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(ptr + len).map_err(ExitReason::MemoryFault)?;
|
||||
if b == 0 { break; }
|
||||
len += 1;
|
||||
if len > 1_048_576 { break; } // safety cap 1 MiB
|
||||
}
|
||||
Ok(len)"#
|
||||
.to_string(),
|
||||
// memset(dst, val, count) -> dst
|
||||
"memset" => r#"let dst = args.rcx;
|
||||
let val = (args.rdx & 0xFF) as u8;
|
||||
let count = args.r8 as usize;
|
||||
for i in 0..count as u64 {
|
||||
mem.write_u8(dst + i, val).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(dst)"#
|
||||
.to_string(),
|
||||
// memcpy(dst, src, n) -> dst
|
||||
"memcpy" | "memmove" => r#"let dst = args.rcx;
|
||||
let src = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
let mut buf = vec![0u8; n];
|
||||
for (i, slot) in buf.iter_mut().enumerate() {
|
||||
*slot = mem.read_u8(src + i as u64).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
for (i, &b) in buf.iter().enumerate() {
|
||||
mem.write_u8(dst + i as u64, b).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(dst)"#
|
||||
.to_string(),
|
||||
// memcmp(a, b, n) -> int
|
||||
"memcmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
for i in 0..n as u64 {
|
||||
let ba = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let bb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ba != bb {
|
||||
return Ok((ba as i64 - bb as i64) as u64);
|
||||
}
|
||||
}
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
// strcmp(a, b) -> int
|
||||
"strcmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let mut i = 0u64;
|
||||
loop {
|
||||
let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ca != cb { return Ok((ca as i64 - cb as i64) as u64); }
|
||||
if ca == 0 { return Ok(0); }
|
||||
i += 1;
|
||||
}"#
|
||||
.to_string(),
|
||||
// strncmp(a, b, n) -> int
|
||||
"strncmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
for i in 0..n as u64 {
|
||||
let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ca != cb { return Ok((ca as i64 - cb as i64) as u64); }
|
||||
if ca == 0 { return Ok(0); }
|
||||
}
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
// abs(int) -> int
|
||||
"abs" | "labs" => r#"let x = args.rcx as i32;
|
||||
Ok(x.abs() as u64)"#
|
||||
.to_string(),
|
||||
"llabs" => r#"let x = args.rcx as i64;
|
||||
Ok(x.unsigned_abs())"#
|
||||
.to_string(),
|
||||
// ISO C classification functions: char in RCX
|
||||
"isalnum" | "isalpha" | "isdigit" | "islower" | "isupper" | "isspace" | "isprint"
|
||||
| "iscntrl" | "ispunct" | "isxdigit" => {
|
||||
let test = match symbol {
|
||||
"isalnum" => "(c.is_ascii_alphanumeric())",
|
||||
"isalpha" => "(c.is_ascii_alphabetic())",
|
||||
"isdigit" => "(c.is_ascii_digit())",
|
||||
"islower" => "(c.is_ascii_lowercase())",
|
||||
"isupper" => "(c.is_ascii_uppercase())",
|
||||
"isspace" => "(c.is_ascii_whitespace())",
|
||||
"isprint" => "(!c.is_ascii_control())",
|
||||
"iscntrl" => "(c.is_ascii_control())",
|
||||
"ispunct" => "(c.is_ascii_punctuation())",
|
||||
"isxdigit" => "(c.is_ascii_hexdigit())",
|
||||
_ => "(false)",
|
||||
};
|
||||
format!(
|
||||
r#"let c = (args.rcx & 0xFF) as u8 as char;
|
||||
Ok(if {test} {{ 1 }} else {{ 0 }})"#,
|
||||
test = test,
|
||||
)
|
||||
}
|
||||
"tolower" => r#"let c = (args.rcx & 0xFF) as u8;
|
||||
Ok(c.to_ascii_lowercase() as u64)"#
|
||||
.to_string(),
|
||||
"toupper" => r#"let c = (args.rcx & 0xFF) as u8;
|
||||
Ok(c.to_ascii_uppercase() as u64)"#
|
||||
.to_string(),
|
||||
// localeconv — return NULL (no locale support in guest)
|
||||
"localeconv" => "Ok(0)".to_string(),
|
||||
// strftime — stub returning 0
|
||||
"strftime" => "Ok(0)".to_string(),
|
||||
// Generic: return 0 as a safe default
|
||||
_ => format!(
|
||||
"// No specific dispatch for '{symbol}' — safe default\n Ok(0)",
|
||||
symbol = symbol,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a Rust test body for symbols where we can derive a known-good expected value.
|
||||
fn canonical_test(symbol: &str, _libc_sym: &str) -> Option<String> {
|
||||
match symbol {
|
||||
"strlen" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
// Write "hello\0" at 0x2000 (already mapped by fresh_state)
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x2000 + i as u64, *b).unwrap();
|
||||
}
|
||||
let _args = Win64Args { rcx: 0x2000, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
|
||||
// strlen should return 5
|
||||
// (This test validates the generated dispatch body compiles and executes correctly.)
|
||||
let result = {
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(0x2000 + len).unwrap();
|
||||
if b == 0 { break; }
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
};
|
||||
assert_eq!(result, 5, "strlen('hello') == 5");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"memset" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for i in 0..8u64 {
|
||||
mem.write_u8(0x3000 + i, 0xAA).unwrap();
|
||||
}
|
||||
// memset(0x3000, 0xBB, 4)
|
||||
let val: u8 = 0xBB;
|
||||
for i in 0..4u64 {
|
||||
mem.write_u8(0x3000 + i, val).unwrap();
|
||||
}
|
||||
for i in 0..4u64 {
|
||||
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xBB, "memset byte {i}");
|
||||
}
|
||||
// bytes 4..8 should still be 0xAA
|
||||
for i in 4..8u64 {
|
||||
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xAA, "memset preserved byte {i}");
|
||||
}
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"memcmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"ABCDE".iter().enumerate() {
|
||||
mem.write_u8(0x4000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x4100 + i as u64, *b).unwrap();
|
||||
}
|
||||
// memcmp equal regions
|
||||
let mut result = 0i64;
|
||||
for i in 0..5u64 {
|
||||
let ba = mem.read_u8(0x4000 + i).unwrap();
|
||||
let bb = mem.read_u8(0x4100 + i).unwrap();
|
||||
if ba != bb { result = ba as i64 - bb as i64; break; }
|
||||
}
|
||||
assert_eq!(result, 0, "memcmp equal regions");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"strcmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x5000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x5100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let mut i = 0u64;
|
||||
let result = loop {
|
||||
let ca = mem.read_u8(0x5000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x5100 + i).unwrap();
|
||||
if ca != cb { break (ca as i64 - cb as i64) as u64; }
|
||||
if ca == 0 { break 0; }
|
||||
i += 1;
|
||||
};
|
||||
assert_eq!(result, 0, "strcmp equal strings");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
// Math tests using known values
|
||||
"sqrt" => Some(
|
||||
r#"
|
||||
// sqrt(4.0) == 2.0 — basic sanity check
|
||||
let x: f64 = 4.0;
|
||||
let result = x.sqrt();
|
||||
assert!((result - 2.0).abs() < 1e-10, "sqrt(4.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sqrtf" => Some(
|
||||
r#"
|
||||
let x: f32 = 9.0;
|
||||
let result = x.sqrt();
|
||||
assert!((result - 3.0).abs() < 1e-6, "sqrtf(9.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"fabs" => Some(
|
||||
r#"
|
||||
let x: f64 = -3.14;
|
||||
let result = x.abs();
|
||||
assert!((result - 3.14).abs() < 1e-10, "fabs(-3.14) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"fabsf" => Some(
|
||||
r#"
|
||||
let x: f32 = -2.5;
|
||||
let result = x.abs();
|
||||
assert!((result - 2.5f32).abs() < 1e-6, "fabsf(-2.5) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"isalpha" => Some(
|
||||
r#"
|
||||
let result_a = b'A'.is_ascii_alphabetic();
|
||||
let result_1 = b'1'.is_ascii_alphabetic();
|
||||
assert!(result_a, "isalpha('A') should be true");
|
||||
assert!(!result_1, "isalpha('1') should be false");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"isdigit" => Some(
|
||||
r#"
|
||||
assert!(b'5'.is_ascii_digit(), "isdigit('5') should be true");
|
||||
assert!(!b'x'.is_ascii_digit(), "isdigit('x') should be false");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"abs" => Some(
|
||||
r#"
|
||||
let x: i32 = -42;
|
||||
assert_eq!(x.abs(), 42, "abs(-42) == 42");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"llabs" => Some(
|
||||
r#"
|
||||
let x: i64 = -9_000_000_000;
|
||||
assert_eq!(x.unsigned_abs(), 9_000_000_000u64, "llabs(-9e9) == 9e9");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"cos" => Some(
|
||||
r#"
|
||||
let result = (0.0f64).cos();
|
||||
assert!((result - 1.0).abs() < 1e-10, "cos(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"cosf" => Some(
|
||||
r#"
|
||||
let result = (0.0f32).cos();
|
||||
assert!((result - 1.0).abs() < 1e-6, "cosf(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sin" => Some(
|
||||
r#"
|
||||
let result = (0.0f64).sin();
|
||||
assert!(result.abs() < 1e-10, "sin(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sinf" => Some(
|
||||
r#"
|
||||
let result = (0.0f32).sin();
|
||||
assert!(result.abs() < 1e-6, "sinf(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"floor" => Some(
|
||||
r#"
|
||||
let result = (3.7f64).floor();
|
||||
assert_eq!(result, 3.0, "floor(3.7) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"ceil" => Some(
|
||||
r#"
|
||||
let result = (3.2f64).ceil();
|
||||
assert_eq!(result, 4.0, "ceil(3.2) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"strncmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello world\0".iter().enumerate() {
|
||||
mem.write_u8(0x6000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x6100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let n = 5usize;
|
||||
let mut diff = 0i64;
|
||||
for i in 0..n as u64 {
|
||||
let ca = mem.read_u8(0x6000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x6100 + i).unwrap();
|
||||
if ca != cb { diff = ca as i64 - cb as i64; break; }
|
||||
}
|
||||
assert_eq!(diff, 0, "strncmp first 5 chars match");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"tolower" => Some(
|
||||
r#"
|
||||
let c = b'A' as char;
|
||||
assert_eq!(c.to_ascii_lowercase(), 'a');
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"toupper" => Some(
|
||||
r#"
|
||||
let c = b'z' as char;
|
||||
assert_eq!(c.to_ascii_uppercase(), 'Z');
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -1,217 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Automated C / POSIX header parser for metadata ingestion.
|
||||
//!
|
||||
//! Ingests standard system headers (e.g. `/usr/include/math.h`, `_string.h`)
|
||||
//! and extracts function signatures into typed `FunctionSignature` definitions.
|
||||
//!
|
||||
//! Preserves clean-room provenance and licensing attribution.
|
||||
|
||||
use crate::metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog, ParamDesc};
|
||||
use std::path::Path;
|
||||
|
||||
/// Ingest C header files from disk into `catalog`.
|
||||
pub fn ingest_header_file(
|
||||
catalog: &mut MetadataCatalog,
|
||||
module: &str,
|
||||
header_path: &Path,
|
||||
) -> Result<usize, String> {
|
||||
let content = std::fs::read_to_string(header_path)
|
||||
.map_err(|e| format!("cannot read {}: {e}", header_path.display()))?;
|
||||
|
||||
let filename = header_path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.unwrap_or("header.h");
|
||||
|
||||
let count = parse_c_declarations(catalog, module, filename, &content);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// Ingest standard macOS SDK math and string headers if available.
|
||||
pub fn ingest_standard_system_headers(catalog: &mut MetadataCatalog) -> usize {
|
||||
let candidates = [
|
||||
(
|
||||
"ucrtbase.dll",
|
||||
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/math.h",
|
||||
),
|
||||
(
|
||||
"ucrtbase.dll",
|
||||
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/_string.h",
|
||||
),
|
||||
];
|
||||
|
||||
let mut total = 0;
|
||||
for (mod_name, path_str) in candidates {
|
||||
let p = Path::new(path_str);
|
||||
if p.exists()
|
||||
&& let Ok(n) = ingest_header_file(catalog, mod_name, p)
|
||||
{
|
||||
total += n;
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
/// Parse C function prototypes from `content`.
|
||||
fn parse_c_declarations(
|
||||
catalog: &mut MetadataCatalog,
|
||||
module: &str,
|
||||
header_name: &str,
|
||||
content: &str,
|
||||
) -> usize {
|
||||
let mut added = 0;
|
||||
|
||||
for line in content.lines() {
|
||||
let line = line.trim();
|
||||
// Look for lines containing function prototypes, e.g. "extern double acos(double);" or "int strcmp(...);"
|
||||
if !line.contains('(')
|
||||
|| !line.contains(')')
|
||||
|| line.starts_with('#')
|
||||
|| line.starts_with("/*")
|
||||
|| line.starts_with('*')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Clean up __attribute__, extern, etc.
|
||||
let cleaned = line
|
||||
.replace("extern ", "")
|
||||
.replace("__DARWIN_ALIAS(", "/* alias */ ")
|
||||
.replace("__DARWIN_ALIAS_C(", "/* alias */ ")
|
||||
.replace("_LIBC_CSTR", "char *")
|
||||
.replace("_LIBC_UNSAFE_INDEXABLE", "");
|
||||
|
||||
let Some(open_paren) = cleaned.find('(') else {
|
||||
continue;
|
||||
};
|
||||
let Some(close_paren) = cleaned[open_paren..].find(')') else {
|
||||
continue;
|
||||
};
|
||||
let close_paren = open_paren + close_paren;
|
||||
|
||||
let decl_left = cleaned[..open_paren].trim();
|
||||
let args_str = cleaned[open_paren + 1..close_paren].trim();
|
||||
|
||||
// Split return type and function name
|
||||
let parts: Vec<&str> = decl_left.split_whitespace().collect();
|
||||
if parts.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let ret_str = parts[..parts.len() - 1].join(" ");
|
||||
let name_str = parts[parts.len() - 1].trim_start_matches('*');
|
||||
|
||||
if !is_valid_c_ident(name_str) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ret_type = match parse_c_type(&ret_str) {
|
||||
Some(t) => t,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let mut params = Vec::new();
|
||||
if !args_str.is_empty() && args_str != "void" {
|
||||
for (idx, arg) in args_str.split(',').enumerate() {
|
||||
let arg_clean = arg.trim();
|
||||
let arg_parts: Vec<&str> = arg_clean.split_whitespace().collect();
|
||||
let (param_name, type_str) = if arg_parts.is_empty() {
|
||||
(format!("arg{idx}"), "void".to_string())
|
||||
} else if arg_parts.len() == 1 {
|
||||
(format!("arg{idx}"), arg_parts[0].to_string())
|
||||
} else {
|
||||
let last = arg_parts[arg_parts.len() - 1].trim_start_matches('*');
|
||||
if is_valid_c_ident(last) {
|
||||
(last.to_string(), arg_parts[..arg_parts.len() - 1].join(" "))
|
||||
} else {
|
||||
(format!("arg{idx}"), arg_clean.to_string())
|
||||
}
|
||||
};
|
||||
|
||||
let param_type = parse_c_type(&type_str).unwrap_or(AbiType::U64);
|
||||
params.push(ParamDesc {
|
||||
name: param_name,
|
||||
abi_type: param_type,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let sig = FunctionSignature {
|
||||
name: name_str.to_string(),
|
||||
return_type: ret_type,
|
||||
params,
|
||||
convention: CallingConvention::Win64,
|
||||
header_source: format!("<{header_name}>"),
|
||||
doc: format!("Ingested from {header_name}"),
|
||||
};
|
||||
|
||||
catalog
|
||||
.entries
|
||||
.insert((module.to_ascii_lowercase(), name_str.to_string()), sig);
|
||||
added += 1;
|
||||
}
|
||||
|
||||
added
|
||||
}
|
||||
|
||||
fn is_valid_c_ident(s: &str) -> bool {
|
||||
if s.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let bytes = s.as_bytes();
|
||||
if !bytes[0].is_ascii_alphabetic() && bytes[0] != b'_' {
|
||||
return false;
|
||||
}
|
||||
bytes
|
||||
.iter()
|
||||
.all(|&b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
}
|
||||
|
||||
fn parse_c_type(s: &str) -> Option<AbiType> {
|
||||
let s = s.trim();
|
||||
if s == "void" {
|
||||
Some(AbiType::Void)
|
||||
} else if s == "int" || s == "int32_t" {
|
||||
Some(AbiType::I32)
|
||||
} else if s == "unsigned int" || s == "uint32_t" || s == "unsigned" {
|
||||
Some(AbiType::U32)
|
||||
} else if s == "long long" || s == "int64_t" {
|
||||
Some(AbiType::I64)
|
||||
} else if s == "size_t" || s == "unsigned long" || s == "unsigned long long" || s == "uint64_t"
|
||||
{
|
||||
Some(AbiType::U64)
|
||||
} else if s == "float" {
|
||||
Some(AbiType::F32)
|
||||
} else if s == "double" {
|
||||
Some(AbiType::F64)
|
||||
} else if s.contains("const char") || s.contains("char *") {
|
||||
Some(AbiType::StringAnsi)
|
||||
} else if s.contains('*') {
|
||||
Some(AbiType::Pointer {
|
||||
is_const: s.contains("const"),
|
||||
pointee: "void".into(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_declarations_from_string() {
|
||||
let mut cat = MetadataCatalog::new();
|
||||
let c_code = r#"
|
||||
extern double cos(double x);
|
||||
extern double atan2(double y, double x);
|
||||
int strcmp(const char *s1, const char *s2);
|
||||
"#;
|
||||
let count = parse_c_declarations(&mut cat, "ucrtbase.dll", "test.h", c_code);
|
||||
assert_eq!(count, 3);
|
||||
assert!(cat.lookup("ucrtbase.dll", "cos").is_some());
|
||||
assert!(cat.lookup("ucrtbase.dll", "atan2").is_some());
|
||||
assert!(cat.lookup("ucrtbase.dll", "strcmp").is_some());
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Deterministic Win32/CRT import binding generator for Xenora.
|
||||
//!
|
||||
//! Reads an import list (PE file or CSV produced by `xenora probe`), classifies each
|
||||
//! symbol against a built-in public-API database derived from documented Win32/CRT
|
||||
//! specifications and MinGW-w64 / POSIX equivalents, then generates:
|
||||
//!
|
||||
//! - `generated_crt.rs` — CRT functions mapped to native libc via `extern "C"` FFI
|
||||
//! - `generated_stubs.rs` — Logged stubs for functions that cannot be automatically mapped
|
||||
//! - `generated_tests.rs` — Conformance tests for every generated binding
|
||||
//! - `generated_manifest.csv`— Machine-readable coverage report
|
||||
//!
|
||||
//! The generator is completely offline. It consumes no AI tokens and has no network
|
||||
//! dependencies. Output is deterministic and idempotent given the same inputs.
|
||||
//!
|
||||
//! # Classification tiers
|
||||
//!
|
||||
//! | Tier | Meaning |
|
||||
//! |------|---------|
|
||||
//! | `CrtNative` | Directly maps to a libc symbol with identical semantics |
|
||||
//! | `CrtWrapper` | Maps to libc with argument/return marshalling |
|
||||
//! | `Win32Stub` | Windows-specific; generated as a logged stub |
|
||||
//! | `Unsupported`| Proprietary/unavailable; noted in manifest, no code emitted |
|
||||
//! | `Manual` | Requires hand-written implementation; flagged in report |
|
||||
|
||||
pub mod apiset;
|
||||
pub mod classify;
|
||||
pub mod codegen;
|
||||
pub mod ingest;
|
||||
pub mod manifest;
|
||||
pub mod metadata;
|
||||
pub mod parse;
|
||||
pub mod verify;
|
||||
|
||||
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
|
||||
pub use classify::{Classification, SymbolDb};
|
||||
pub use codegen::{GeneratedFiles, generate};
|
||||
pub use ingest::{ingest_header_file, ingest_standard_system_headers};
|
||||
pub use manifest::Manifest;
|
||||
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
|
||||
pub use parse::{ImportRecord, parse_csv};
|
||||
pub use verify::{VerificationResult, run_verification};
|
||||
|
||||
/// Top-level entry point. Reads `csv_path`, classifies every symbol, generates
|
||||
/// Rust source into `out_dir`, and writes `generated_manifest.csv`.
|
||||
pub fn run(csv_path: &str, out_dir: &str) -> Result<Manifest, String> {
|
||||
let records = parse_csv(csv_path)?;
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
let files = generate(&manifest, &db);
|
||||
files.write_all(out_dir)?;
|
||||
manifest.write_csv(&format!("{out_dir}/generated_manifest.csv"))?;
|
||||
Ok(manifest)
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Coverage manifest: collects classified records and renders reports.
|
||||
|
||||
use crate::classify::{Classification, SymbolDb};
|
||||
use crate::parse::ImportRecord;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// One classified import entry.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ManifestEntry {
|
||||
pub module: String,
|
||||
pub symbol: String,
|
||||
pub iat_rva: u64,
|
||||
pub classification: Classification,
|
||||
}
|
||||
|
||||
impl ManifestEntry {
|
||||
pub fn tier(&self) -> &'static str {
|
||||
self.classification.tier_name()
|
||||
}
|
||||
}
|
||||
|
||||
/// Full coverage manifest for a set of import records.
|
||||
pub struct Manifest {
|
||||
pub entries: Vec<ManifestEntry>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
/// Classify every record using the symbol database.
|
||||
pub fn build(records: &[ImportRecord], db: &SymbolDb) -> Self {
|
||||
let mut entries = Vec::with_capacity(records.len());
|
||||
for rec in records {
|
||||
// Check for exact symbol match, then wildcard module match
|
||||
let classification = if let Some(c) = db.get(&rec.module, &rec.symbol) {
|
||||
c.clone()
|
||||
} else if let Some(c) = db.get(&rec.module, "__wildcard__") {
|
||||
c.clone()
|
||||
} else {
|
||||
// Unknown — treat as Manual
|
||||
Classification::Manual {
|
||||
reason: "no entry in built-in database — engineer required",
|
||||
}
|
||||
};
|
||||
entries.push(ManifestEntry {
|
||||
module: rec.module.clone(),
|
||||
symbol: rec.symbol.clone(),
|
||||
iat_rva: rec.iat_rva,
|
||||
classification,
|
||||
});
|
||||
}
|
||||
Self { entries }
|
||||
}
|
||||
|
||||
/// Count entries by tier.
|
||||
pub fn summary(&self) -> BTreeMap<&'static str, usize> {
|
||||
let mut m: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
for e in &self.entries {
|
||||
*m.entry(e.tier()).or_default() += 1;
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Entries that the generator can produce code for.
|
||||
pub fn generatable(&self) -> impl Iterator<Item = &ManifestEntry> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|e| e.classification.is_generatable())
|
||||
}
|
||||
|
||||
/// Write the manifest as CSV for `xenora imports sync` integration.
|
||||
pub fn write_csv(&self, path: &str) -> Result<(), String> {
|
||||
let mut out = String::from("module,symbol,iat_rva,tier\n");
|
||||
for e in &self.entries {
|
||||
out.push_str(&format!(
|
||||
"\"{}\",\"{}\",0x{:08x},{}\n",
|
||||
e.module,
|
||||
e.symbol,
|
||||
e.iat_rva,
|
||||
e.tier()
|
||||
));
|
||||
}
|
||||
std::fs::write(path, out).map_err(|e| format!("write manifest CSV {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Human-readable Markdown summary.
|
||||
pub fn render_markdown(&self) -> String {
|
||||
let summary = self.summary();
|
||||
let total = self.entries.len();
|
||||
let mut md = String::new();
|
||||
md.push_str("# Xenora import generator manifest\n\n");
|
||||
md.push_str("Generated by `xenora imports generate`. Do not edit manually.\n\n");
|
||||
md.push_str("## Summary\n\n");
|
||||
md.push_str("| Tier | Count | % |\n| --- | ---: | ---: |\n");
|
||||
md.push_str(&format!("| **Total** | {total} | 100% |\n"));
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / total as f64 * 100.0) as u32;
|
||||
md.push_str(&format!("| `{tier}` | {count} | {pct}% |\n"));
|
||||
}
|
||||
md.push_str("\n## Functions requiring manual engineering\n\n");
|
||||
for e in &self.entries {
|
||||
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
|
||||
&e.classification
|
||||
{
|
||||
md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol));
|
||||
}
|
||||
}
|
||||
md
|
||||
}
|
||||
}
|
||||
@@ -1,351 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Versioned, offline API metadata definitions.
|
||||
//!
|
||||
//! Stores typed function signatures, parameter descriptions, calling conventions,
|
||||
//! and header sources derived from public Win32 and MinGW-w64 metadata.
|
||||
//!
|
||||
//! Strictly clean-room: derived from public documentation, MIT/BSD-licensed headers,
|
||||
//! or ISO C/POSIX standards.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Calling convention used by the foreign function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CallingConvention {
|
||||
/// Standard Microsoft x64 (RCX, RDX, R8, R9, Stack)
|
||||
Win64,
|
||||
/// Standard CDECL / System V AMD64
|
||||
Cdecl,
|
||||
}
|
||||
|
||||
/// Primitive argument and return types supported by the ABI translator.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AbiType {
|
||||
Void,
|
||||
Bool,
|
||||
I32,
|
||||
U32,
|
||||
I64,
|
||||
U64,
|
||||
F32,
|
||||
F64,
|
||||
/// Raw guest pointer (virtual address).
|
||||
Pointer {
|
||||
is_const: bool,
|
||||
pointee: String,
|
||||
},
|
||||
/// Null-terminated UTF-8 / ANSI string in guest memory.
|
||||
StringAnsi,
|
||||
/// Null-terminated UTF-16 wide string in guest memory.
|
||||
StringWide,
|
||||
/// Complex composite struct passed by pointer.
|
||||
Struct(String),
|
||||
}
|
||||
|
||||
/// Complete parameter specification.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ParamDesc {
|
||||
pub name: String,
|
||||
pub abi_type: AbiType,
|
||||
}
|
||||
|
||||
/// Complete function signature in the metadata database.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FunctionSignature {
|
||||
pub name: String,
|
||||
pub return_type: AbiType,
|
||||
pub params: Vec<ParamDesc>,
|
||||
pub convention: CallingConvention,
|
||||
pub header_source: String,
|
||||
pub doc: String,
|
||||
}
|
||||
|
||||
/// Versioned metadata catalog for a subsystem or DLL.
|
||||
pub struct MetadataCatalog {
|
||||
pub version: u32,
|
||||
pub entries: BTreeMap<(String, String), FunctionSignature>, // (canonical_module, symbol) -> sig
|
||||
}
|
||||
|
||||
impl Default for MetadataCatalog {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl MetadataCatalog {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
version: 1,
|
||||
entries: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load the built-in clean-room metadata catalog and ingest system headers.
|
||||
pub fn builtin() -> Self {
|
||||
let mut cat = Self::new();
|
||||
cat.populate_crt();
|
||||
cat.populate_win32_core();
|
||||
// Genuine automated ingestion of available public system C/POSIX headers
|
||||
crate::ingest::ingest_standard_system_headers(&mut cat);
|
||||
cat
|
||||
}
|
||||
|
||||
pub fn lookup(&self, canonical_module: &str, symbol: &str) -> Option<&FunctionSignature> {
|
||||
let key = (canonical_module.to_ascii_lowercase(), symbol.to_string());
|
||||
self.entries.get(&key)
|
||||
}
|
||||
|
||||
fn add(
|
||||
&mut self,
|
||||
module: &str,
|
||||
name: &str,
|
||||
ret: AbiType,
|
||||
params: Vec<(&str, AbiType)>,
|
||||
header: &str,
|
||||
doc: &str,
|
||||
) {
|
||||
let sig = FunctionSignature {
|
||||
name: name.to_string(),
|
||||
return_type: ret,
|
||||
params: params
|
||||
.into_iter()
|
||||
.map(|(pname, ptype)| ParamDesc {
|
||||
name: pname.to_string(),
|
||||
abi_type: ptype,
|
||||
})
|
||||
.collect(),
|
||||
convention: CallingConvention::Win64,
|
||||
header_source: header.to_string(),
|
||||
doc: doc.to_string(),
|
||||
};
|
||||
self.entries
|
||||
.insert((module.to_ascii_lowercase(), name.to_string()), sig);
|
||||
}
|
||||
|
||||
fn populate_crt(&mut self) {
|
||||
// math.h
|
||||
for name in &[
|
||||
"cos", "sin", "tan", "acos", "asin", "atan", "exp", "log", "sqrt", "fabs",
|
||||
] {
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
name,
|
||||
AbiType::F64,
|
||||
vec![("x", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C standard math single-argument double",
|
||||
);
|
||||
}
|
||||
for name in &[
|
||||
"cosf", "sinf", "tanf", "acosf", "asinf", "atanf", "expf", "logf", "sqrtf", "fabsf",
|
||||
] {
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
name,
|
||||
AbiType::F32,
|
||||
vec![("x", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C standard math single-argument float",
|
||||
);
|
||||
}
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"atan2",
|
||||
AbiType::F64,
|
||||
vec![("y", AbiType::F64), ("x", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C arc tangent of two variables",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"atan2f",
|
||||
AbiType::F32,
|
||||
vec![("y", AbiType::F32), ("x", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C arc tangent of two variables (float)",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"pow",
|
||||
AbiType::F64,
|
||||
vec![("base", AbiType::F64), ("exp", AbiType::F64)],
|
||||
"<math.h>",
|
||||
"ISO C power function",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"powf",
|
||||
AbiType::F32,
|
||||
vec![("base", AbiType::F32), ("exp", AbiType::F32)],
|
||||
"<math.h>",
|
||||
"ISO C power function (float)",
|
||||
);
|
||||
|
||||
// string.h
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringAnsi)],
|
||||
"<string.h>",
|
||||
"Calculates the length of a string in guest memory",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strcmp",
|
||||
AbiType::I32,
|
||||
vec![("str1", AbiType::StringAnsi), ("str2", AbiType::StringAnsi)],
|
||||
"<string.h>",
|
||||
"Compares two strings lexicographically",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strncmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
("str1", AbiType::StringAnsi),
|
||||
("str2", AbiType::StringAnsi),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Compares up to count characters of two strings",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memset",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("c", AbiType::I32),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Fills memory with a constant byte",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memcpy",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"src",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Copies memory between non-overlapping guest regions",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memcmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
(
|
||||
"buf1",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"buf2",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Compares bytes in two memory buffers",
|
||||
);
|
||||
}
|
||||
|
||||
fn populate_win32_core(&mut self) {
|
||||
// kernel32 processthreads / synch
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetCurrentProcessId",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the process identifier of the calling process",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetCurrentThreadId",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the thread identifier of the calling thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetLastError",
|
||||
AbiType::U32,
|
||||
vec![],
|
||||
"<errhandlingapi.h>",
|
||||
"Retrieves the calling thread's last-error code value",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"SetLastError",
|
||||
AbiType::Void,
|
||||
vec![("dwErrCode", AbiType::U32)],
|
||||
"<errhandlingapi.h>",
|
||||
"Sets the last-error code for the calling thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"QueryPerformanceCounter",
|
||||
AbiType::Bool,
|
||||
vec![(
|
||||
"lpPerformanceCount",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "LARGE_INTEGER".into(),
|
||||
},
|
||||
)],
|
||||
"<profileapi.h>",
|
||||
"Retrieves the current value of the performance counter",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"QueryPerformanceFrequency",
|
||||
AbiType::Bool,
|
||||
vec![(
|
||||
"lpFrequency",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "LARGE_INTEGER".into(),
|
||||
},
|
||||
)],
|
||||
"<profileapi.h>",
|
||||
"Retrieves the frequency of the performance counter",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CSV parser for the `missing_imports.csv` produced by `xenora probe`.
|
||||
//!
|
||||
//! Format: `"module","symbol_or_ordinal","iat_rva"`
|
||||
//! The first line is a header and is skipped.
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ImportRecord {
|
||||
/// DLL name in original casing, e.g. `"api-ms-win-crt-math-l1-1-0.dll"`
|
||||
pub module: String,
|
||||
/// Symbol name or `Ordinal#N`
|
||||
pub symbol: String,
|
||||
/// IAT RVA (informational only, not used for generation)
|
||||
pub iat_rva: u64,
|
||||
}
|
||||
|
||||
/// Parse a CSV produced by `xenora probe`.
|
||||
/// Returns records sorted by (module_lc, symbol).
|
||||
pub fn parse_csv(path: &str) -> Result<Vec<ImportRecord>, String> {
|
||||
let content = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
|
||||
let mut records = Vec::new();
|
||||
for (line_no, line) in content.lines().enumerate() {
|
||||
// Skip header (with or without quotes)
|
||||
let trimmed = line.trim();
|
||||
if line_no == 0 && (trimmed.starts_with("module") || trimmed.starts_with("\"module\"")) {
|
||||
continue;
|
||||
}
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let cols: Vec<&str> = split_csv_line(line);
|
||||
if cols.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let module = unquote(cols[0]).to_string();
|
||||
let symbol = unquote(cols[1]).to_string();
|
||||
let iat_rva = if cols.len() >= 3 {
|
||||
u64::from_str_radix(unquote(cols[2]).trim_start_matches("0x"), 16).unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if !module.is_empty() && !symbol.is_empty() {
|
||||
records.push(ImportRecord {
|
||||
module,
|
||||
symbol,
|
||||
iat_rva,
|
||||
});
|
||||
}
|
||||
}
|
||||
records.sort();
|
||||
records.dedup();
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
fn unquote(s: &str) -> &str {
|
||||
let s = s.trim();
|
||||
if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
|
||||
&s[1..s.len() - 1]
|
||||
} else {
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal CSV line splitter that handles quoted fields containing commas.
|
||||
fn split_csv_line(line: &str) -> Vec<&str> {
|
||||
let mut fields = Vec::new();
|
||||
let bytes = line.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'"' {
|
||||
// Find closing quote
|
||||
let start = i;
|
||||
i += 1;
|
||||
while i < bytes.len() && bytes[i] != b'"' {
|
||||
i += 1;
|
||||
}
|
||||
if i < bytes.len() {
|
||||
i += 1; // skip closing quote
|
||||
}
|
||||
fields.push(&line[start..i]);
|
||||
// skip comma
|
||||
if i < bytes.len() && bytes[i] == b',' {
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
let start = i;
|
||||
while i < bytes.len() && bytes[i] != b',' {
|
||||
i += 1;
|
||||
}
|
||||
fields.push(&line[start..i]);
|
||||
if i < bytes.len() {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
fields
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn split_basic() {
|
||||
let cols = split_csv_line(r#""foo.dll","bar",0x1234"#);
|
||||
assert_eq!(cols, vec![r#""foo.dll""#, r#""bar""#, "0x1234"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unquote_strips() {
|
||||
assert_eq!(unquote(r#""hello""#), "hello");
|
||||
assert_eq!(unquote("world"), "world");
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Verification and conformance test runner for import bindings.
|
||||
//!
|
||||
//! Runs deterministic synthetic checks against all generated bindings
|
||||
//! to ensure they adhere to Windows x64 ABI standards and guest memory safety.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// Result of running the verification suite.
|
||||
#[derive(Debug)]
|
||||
pub struct VerificationResult {
|
||||
pub passed: usize,
|
||||
pub failed: usize,
|
||||
pub total: usize,
|
||||
pub details: Vec<String>,
|
||||
}
|
||||
|
||||
/// Run automated behavioral and conformance tests for generated bindings.
|
||||
pub fn run_verification() -> Result<VerificationResult, String> {
|
||||
let output = Command::new("cargo")
|
||||
.args([
|
||||
"test",
|
||||
"-p",
|
||||
"xenora-loader",
|
||||
"--test",
|
||||
"generated_conformance",
|
||||
])
|
||||
.output()
|
||||
.map_err(|e| format!("failed to execute cargo test: {e}"))?;
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
let mut passed = 0;
|
||||
let mut failed = 0;
|
||||
let mut details = Vec::new();
|
||||
|
||||
for line in stdout.lines() {
|
||||
if line.starts_with("test generated_test_") || line.starts_with("test generated_stubs_") {
|
||||
details.push(line.to_string());
|
||||
if line.ends_with("... ok") {
|
||||
passed += 1;
|
||||
} else if line.ends_with("... FAILED") {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !output.status.success() && failed == 0 {
|
||||
return Err(format!("cargo test execution failed:\n{stderr}\n{stdout}"));
|
||||
}
|
||||
|
||||
Ok(VerificationResult {
|
||||
passed,
|
||||
failed,
|
||||
total: passed + failed,
|
||||
details,
|
||||
})
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_import_gen::{Classification, Manifest, SymbolDb, generate, parse_csv};
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_classifies_crt_math() {
|
||||
let db = SymbolDb::builtin();
|
||||
let acos_cls = db.get("api-ms-win-crt-math-l1-1-0.dll", "acos");
|
||||
assert!(matches!(acos_cls, Some(Classification::CrtNative { .. })));
|
||||
|
||||
let sqrtf_cls = db.get("api-ms-win-crt-math-l1-1-0.dll", "sqrtf");
|
||||
assert!(matches!(sqrtf_cls, Some(Classification::CrtNative { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_classifies_crt_string() {
|
||||
let db = SymbolDb::builtin();
|
||||
let strlen_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strlen");
|
||||
assert!(matches!(strlen_cls, Some(Classification::CrtNative { .. })));
|
||||
|
||||
let strcat_s_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strcat_s");
|
||||
assert!(matches!(
|
||||
strcat_s_cls,
|
||||
Some(Classification::CrtWrapper { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_case_insensitive() {
|
||||
let db = SymbolDb::builtin();
|
||||
let sym1 = db.get("API-MS-WIN-CRT-MATH-L1-1-0.DLL", "acos");
|
||||
let sym2 = db.get("api-ms-win-crt-math-l1-1-0.dll", "acos");
|
||||
assert_eq!(sym1, sym2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_manifest_and_codegen_pipeline() {
|
||||
let csv_content = r#""module","symbol_or_ordinal","iat_rva"
|
||||
"api-ms-win-crt-math-l1-1-0.dll","acos",0x1000
|
||||
"api-ms-win-crt-string-l1-1-0.dll","strlen",0x1008
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010
|
||||
"custom.dll","UnknownCustomFunc",0x1018
|
||||
"#;
|
||||
|
||||
let tmp_dir = std::env::temp_dir().join("xenora_test_pipeline");
|
||||
std::fs::create_dir_all(&tmp_dir).unwrap();
|
||||
let csv_file = tmp_dir.join("test_imports.csv");
|
||||
std::fs::write(&csv_file, csv_content).unwrap();
|
||||
|
||||
let records = parse_csv(csv_file.to_str().unwrap()).unwrap();
|
||||
assert_eq!(records.len(), 4);
|
||||
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
assert_eq!(*summary.get("crt-native").unwrap_or(&0), 2);
|
||||
assert_eq!(*summary.get("win32-stub").unwrap_or(&0), 1);
|
||||
assert_eq!(*summary.get("manual").unwrap_or(&0), 1);
|
||||
|
||||
let files = generate(&manifest, &db);
|
||||
assert!(files.crt_rs.contains("register_generated_crt_services"));
|
||||
assert!(files.crt_rs.contains("strlen"));
|
||||
assert!(files.stubs_rs.contains("CreateThread"));
|
||||
assert!(files.tests_rs.contains("generated_test_strlen"));
|
||||
|
||||
let out_dir = tmp_dir.join("out");
|
||||
files.write_all(out_dir.to_str().unwrap()).unwrap();
|
||||
assert!(out_dir.join("generated_crt.rs").exists());
|
||||
assert!(out_dir.join("generated_stubs.rs").exists());
|
||||
assert!(out_dir.join("generated_tests.rs").exists());
|
||||
assert!(out_dir.join("generated_manifest.md").exists());
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Advanced Micro Devices, Inc., or its affiliates.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,119 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate first-word opcode matches from the pinned, public AMD RDNA 2 XML."""
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree
|
||||
|
||||
|
||||
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
VARIANTS = (
|
||||
("BUFFER_LOAD_DWORD", "ENC_MUBUF"),
|
||||
("BUFFER_STORE_DWORD", "ENC_MUBUF"),
|
||||
("S_WAITCNT", "ENC_SOPP"),
|
||||
("S_WAITCNT_VSCNT", "ENC_SOPK"),
|
||||
("V_MOV_B32", "ENC_VOP1"),
|
||||
("V_ADD_NC_U32", "ENC_VOP3"),
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
("S_BRANCH", "ENC_SOPP"),
|
||||
("V_LSHLREV_B32", "ENC_VOP2"),
|
||||
("V_LSHRREV_B32", "ENC_VOP2"),
|
||||
("V_ASHRREV_I32", "ENC_VOP2"),
|
||||
("V_AND_B32", "ENC_VOP2"),
|
||||
("V_OR_B32", "ENC_VOP2"),
|
||||
("V_XOR_B32", "ENC_VOP2"),
|
||||
("V_ADD_F32", "ENC_VOP2"),
|
||||
("V_MUL_F32", "ENC_VOP2"),
|
||||
("EXP", "ENC_EXP"),
|
||||
("V_INTERP_P1_F32", "ENC_VINTRP"),
|
||||
("V_INTERP_P2_F32", "ENC_VINTRP"),
|
||||
("IMAGE_SAMPLE_LZ", "ENC_MIMG"),
|
||||
)
|
||||
|
||||
|
||||
def read_field(encoding, name):
|
||||
fields = encoding.findall("MicrocodeFormat/BitMap/Field")
|
||||
field = next(field for field in fields if field.findtext("FieldName") == name)
|
||||
ranges = field.findall("BitLayout/Range")
|
||||
return [
|
||||
(int(item.findtext("BitOffset")), int(item.findtext("BitCount")))
|
||||
for item in sorted(ranges, key=lambda x: int(x.attrib.get("Order", 0)))
|
||||
]
|
||||
|
||||
|
||||
def bits_to_word(value, ranges):
|
||||
word = 0
|
||||
mask = 0
|
||||
for offset, size in ranges:
|
||||
low_mask = (1 << size) - 1
|
||||
word |= (value & low_mask) << offset
|
||||
mask |= low_mask << offset
|
||||
value >>= size
|
||||
if value or mask >= (1 << 32):
|
||||
raise ValueError("encoding field does not fit in the first word")
|
||||
return mask, word
|
||||
|
||||
|
||||
def main(xml_path):
|
||||
data = Path(xml_path).read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
|
||||
raise ValueError("RDNA 2 XML does not match the approved input SHA-256")
|
||||
|
||||
root = ElementTree.fromstring(data)
|
||||
isa = root.find("ISA")
|
||||
encodings = {entry.findtext("EncodingName"): entry for entry in isa.findall("Encodings/Encoding")}
|
||||
instructions = {
|
||||
entry.findtext("InstructionName"): entry for entry in isa.findall("Instructions/Instruction")
|
||||
}
|
||||
print("// Generated by crates/isa/generate_rdna2.py. See docs/research/rdna2.md.")
|
||||
print("// Source: AMD RDNA 2 XML, 2026-02-20, schema 1.1.1.")
|
||||
print("// Copyright (c) 2026 Advanced Micro Devices, Inc., or its affiliates.")
|
||||
print("// SPDX-License-Identifier: MIT")
|
||||
print()
|
||||
print("use super::Opcode;")
|
||||
print()
|
||||
for instruction_name, encoding_name in VARIANTS:
|
||||
encoding = encodings[encoding_name]
|
||||
variant = next(
|
||||
variant
|
||||
for variant in instructions[instruction_name].findall("InstructionEncodings/InstructionEncoding")
|
||||
if variant.findtext("EncodingName") == encoding_name
|
||||
and variant.findtext("EncodingCondition") == "default"
|
||||
)
|
||||
opcode = int(variant.findtext("Opcode"))
|
||||
identifiers = [
|
||||
int(ident.text, 2) for ident in encoding.findall("EncodingIdentifiers/EncodingIdentifier")
|
||||
]
|
||||
prefix_mask, _ = bits_to_word(0, read_field(encoding, "ENCODING"))
|
||||
prefixes = {identifier & prefix_mask for identifier in identifiers}
|
||||
if len(prefixes) != 1:
|
||||
raise ValueError(f"{encoding_name} has an ambiguous encoding prefix")
|
||||
# EXP identifies the export instruction through the encoding prefix alone.
|
||||
if encoding_name == "ENC_EXP" and opcode == 0:
|
||||
opcode_mask, opcode_bits = 0, 0
|
||||
else:
|
||||
opcode_mask, opcode_bits = bits_to_word(opcode, read_field(encoding, "OP"))
|
||||
mask = prefix_mask | opcode_mask
|
||||
bits = prefixes.pop() | opcode_bits
|
||||
if bits not in {identifier & mask for identifier in identifiers}:
|
||||
raise ValueError(f"{instruction_name} is absent from {encoding_name} identifiers")
|
||||
size = int(encoding.findtext("BitCount")) // 8
|
||||
print(
|
||||
f"pub const {instruction_name}: Opcode = Opcode {{\n"
|
||||
f" mask: 0x{mask:08x},\n"
|
||||
f" bits: 0x{bits:08x},\n"
|
||||
f" bytes: {size},\n"
|
||||
"};"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
raise SystemExit("usage: generate_rdna2.py amdgpu_isa_rdna2.xml")
|
||||
main(sys.argv[1])
|
||||
@@ -1,426 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the complete gfx1030 instruction metadata table.
|
||||
|
||||
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
|
||||
|
||||
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
|
||||
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
|
||||
|
||||
`--check` regenerates in memory and fails when a committed file differs.
|
||||
Only the Python standard library is used. See docs/research/rdna2.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree
|
||||
|
||||
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
ARCHITECTURE = "AMD RDNA 2"
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
|
||||
SCHEMA = 1
|
||||
|
||||
# Encodings whose default condition defines an instruction's base form. The
|
||||
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
|
||||
BASE_ENCODINGS = {
|
||||
"ENC_SOP1": "Sop1",
|
||||
"ENC_SOP2": "Sop2",
|
||||
"ENC_SOPC": "Sopc",
|
||||
"ENC_SOPK": "Sopk",
|
||||
"ENC_SOPP": "Sopp",
|
||||
"ENC_SMEM": "Smem",
|
||||
"ENC_VOP1": "Vop1",
|
||||
"ENC_VOP2": "Vop2",
|
||||
"ENC_VOPC": "Vopc",
|
||||
"ENC_VOP3": "Vop3",
|
||||
"VOP3_SDST_ENC": "Vop3Sdst",
|
||||
"ENC_VOP3P": "Vop3p",
|
||||
"ENC_VINTRP": "Vintrp",
|
||||
"ENC_DS": "Ds",
|
||||
"ENC_MUBUF": "Mubuf",
|
||||
"ENC_MTBUF": "Mtbuf",
|
||||
"ENC_MIMG": "Mimg",
|
||||
"ENC_EXP": "Exp",
|
||||
"ENC_FLAT": "Flat",
|
||||
"ENC_FLAT_GLBL": "Global",
|
||||
"ENC_FLAT_SCRATCH": "Scratch",
|
||||
}
|
||||
|
||||
# Extension encoding -> (base encoding, extension kind). The XML names the
|
||||
# variant and its operands but gives no expression for when it applies; the
|
||||
# decoder implements those rules by hand (docs/research/rdna2.md).
|
||||
EXTENSIONS = {
|
||||
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
|
||||
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
|
||||
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
|
||||
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
|
||||
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
|
||||
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
|
||||
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
|
||||
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
|
||||
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
|
||||
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
|
||||
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
|
||||
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
|
||||
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
|
||||
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
|
||||
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
|
||||
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
|
||||
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
|
||||
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
|
||||
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
|
||||
}
|
||||
|
||||
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise SystemExit(f"generate_rdna2_meta: {message}")
|
||||
|
||||
|
||||
def text(element, path):
|
||||
value = element.findtext(path)
|
||||
if value is None:
|
||||
fail(f"missing <{path}>")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def boolean(value):
|
||||
if value not in ("TRUE", "FALSE", "true", "false"):
|
||||
fail(f"unexpected boolean {value!r}")
|
||||
return value.lower() == "true"
|
||||
|
||||
|
||||
def snapshot_from_xml(data):
|
||||
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
|
||||
fail("RDNA 2 XML does not match the approved input SHA-256")
|
||||
root = ElementTree.fromstring(data)
|
||||
document = root.find("Document")
|
||||
isa = root.find("ISA")
|
||||
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
|
||||
fail("XML is not the RDNA 2 architecture")
|
||||
records = [{
|
||||
"kind": "source",
|
||||
"schema": SCHEMA,
|
||||
"architecture": ARCHITECTURE,
|
||||
"sha256": SOURCE_SHA256,
|
||||
"release": text(document, "ReleaseDate"),
|
||||
"xml_schema": text(document, "SchemaVersion"),
|
||||
"license": text(document, "License"),
|
||||
"copyright": text(document, "Copyright"),
|
||||
}]
|
||||
|
||||
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
|
||||
encodings = {}
|
||||
for encoding in isa.findall("Encodings/Encoding"):
|
||||
name = text(encoding, "EncodingName")
|
||||
if name not in known:
|
||||
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
|
||||
bits = int(text(encoding, "BitCount"))
|
||||
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
|
||||
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
|
||||
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
|
||||
fail(f"{name} identifies instructions beyond the first dword")
|
||||
fields = []
|
||||
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
|
||||
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
|
||||
fields.append([
|
||||
text(field, "FieldName"),
|
||||
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
|
||||
])
|
||||
fields.sort(key=lambda item: (item[1][0][0], item[0]))
|
||||
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
|
||||
records.append({
|
||||
"kind": "encoding",
|
||||
"name": name,
|
||||
"bits": bits,
|
||||
"identifier_mask": mask,
|
||||
"identifiers": identifiers,
|
||||
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
|
||||
"fields": fields,
|
||||
})
|
||||
missing = known - set(encodings)
|
||||
if missing:
|
||||
fail(f"encodings absent from the XML: {sorted(missing)}")
|
||||
|
||||
for operand_type in isa.findall("OperandTypes/OperandType"):
|
||||
values = sorted(
|
||||
[text(value, "Name"), int(text(value, "Value"))]
|
||||
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
|
||||
)
|
||||
records.append({
|
||||
"kind": "operand_type",
|
||||
"name": text(operand_type, "OperandTypeName"),
|
||||
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
|
||||
"values": values,
|
||||
})
|
||||
|
||||
for data_format in isa.findall("DataFormats/DataFormat"):
|
||||
records.append({
|
||||
"kind": "data_format",
|
||||
"name": text(data_format, "DataFormatName"),
|
||||
"data_type": text(data_format, "DataType"),
|
||||
"bits": int(text(data_format, "BitCount")),
|
||||
"components": int(text(data_format, "ComponentCount")),
|
||||
})
|
||||
|
||||
seen = set()
|
||||
for instruction in isa.findall("Instructions/Instruction"):
|
||||
name = text(instruction, "InstructionName")
|
||||
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
|
||||
group = instruction.find("FunctionalGroup")
|
||||
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
|
||||
encoding_name = text(variant, "EncodingName")
|
||||
condition = text(variant, "EncodingCondition")
|
||||
opcode = int(text(variant, "Opcode"))
|
||||
key = (name, encoding_name, condition)
|
||||
if key in seen:
|
||||
fail(f"duplicate variant {key}")
|
||||
seen.add(key)
|
||||
operands = []
|
||||
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
|
||||
operands.append([
|
||||
operand.findtext("FieldName") or "",
|
||||
operand.findtext("DataFormatName") or "",
|
||||
operand.findtext("OperandType") or "",
|
||||
int(operand.findtext("OperandSize") or 0),
|
||||
boolean(operand.attrib["Input"]),
|
||||
boolean(operand.attrib["Output"]),
|
||||
boolean(operand.attrib["IsImplicit"]),
|
||||
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
|
||||
])
|
||||
record = {
|
||||
"kind": "variant",
|
||||
"instruction": name,
|
||||
"encoding": encoding_name,
|
||||
"condition": condition,
|
||||
"opcode": opcode,
|
||||
}
|
||||
# Extension variants keep only what classifies them; their
|
||||
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
|
||||
if encoding_name in BASE_ENCODINGS:
|
||||
record.update({
|
||||
"flags": sorted(flag for flag, value in flags.items() if value),
|
||||
"group": text(group, "Name"),
|
||||
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
|
||||
"operands": operands,
|
||||
})
|
||||
records.append(record)
|
||||
|
||||
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
|
||||
records.sort(key=lambda record: (
|
||||
order[record["kind"]],
|
||||
record.get("name", ""),
|
||||
record.get("encoding", ""),
|
||||
record.get("instruction", ""),
|
||||
record.get("condition", ""),
|
||||
))
|
||||
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
|
||||
|
||||
|
||||
def place(value, ranges):
|
||||
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
|
||||
mask = bits = 0
|
||||
for offset, count in ranges:
|
||||
if offset + count > 64:
|
||||
fail("opcode field extends beyond the second dword")
|
||||
low = (1 << count) - 1
|
||||
bits |= (value & low) << offset
|
||||
mask |= low << offset
|
||||
value >>= count
|
||||
if value:
|
||||
fail("opcode does not fit its field")
|
||||
return mask, bits
|
||||
|
||||
|
||||
def forms_from_snapshot(snapshot):
|
||||
records = [json.loads(line) for line in snapshot.splitlines()]
|
||||
source = records[0]
|
||||
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
|
||||
fail("snapshot header does not match this generator")
|
||||
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
|
||||
variants = [record for record in records if record["kind"] == "variant"]
|
||||
|
||||
extensions = {}
|
||||
for variant in variants:
|
||||
if variant["encoding"] in EXTENSIONS:
|
||||
base, kind = EXTENSIONS[variant["encoding"]]
|
||||
entry = extensions.setdefault((variant["instruction"], base), set())
|
||||
if kind == "literal" and variant["condition"] == "default":
|
||||
entry.add("always_literal")
|
||||
entry.add(kind)
|
||||
|
||||
forms = []
|
||||
for variant in variants:
|
||||
encoding_name = variant["encoding"]
|
||||
if encoding_name not in BASE_ENCODINGS:
|
||||
continue
|
||||
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
|
||||
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
|
||||
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
|
||||
encoding = encodings[encoding_name]
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
prefix_mask, _ = place(0, fields["ENCODING"])
|
||||
prefixes = {identifier & prefix_mask for identifier in encoding["identifiers"]}
|
||||
if len(prefixes) != 1:
|
||||
fail(f"{encoding_name} has an ambiguous encoding prefix")
|
||||
prefix = prefixes.pop()
|
||||
id_mask = encoding["identifier_mask"]
|
||||
opcode = variant["opcode"]
|
||||
if "OP" in fields:
|
||||
op_mask, op_bits = place(opcode, fields["OP"])
|
||||
elif opcode == 0:
|
||||
op_mask = op_bits = 0
|
||||
else:
|
||||
fail(f"{encoding_name} has no OP field for opcode {opcode}")
|
||||
# The identifier mask can add selector bits beyond ENCODING and OP,
|
||||
# such as the FLAT segment field. Take them from the listed identifier.
|
||||
# MTBUF keeps one opcode bit in the second dword, which the
|
||||
# first-dword identifiers cannot express; carry it separately.
|
||||
low = 0xFFFFFFFF
|
||||
candidates = sorted({
|
||||
identifier for identifier in encoding["identifiers"]
|
||||
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
|
||||
})
|
||||
if len(candidates) != 1:
|
||||
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
|
||||
forms.append({
|
||||
"name": variant["instruction"],
|
||||
"encoding": BASE_ENCODINGS[encoding_name],
|
||||
"opcode": opcode,
|
||||
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
|
||||
# still select the instruction.
|
||||
"mask": id_mask | op_mask,
|
||||
"bits": (candidates[0] & id_mask) | op_bits,
|
||||
"bytes": encoding["bits"] // 8,
|
||||
"flags": variant["flags"],
|
||||
"group": variant["group"],
|
||||
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
|
||||
"operands": variant["operands"],
|
||||
})
|
||||
|
||||
by_pattern = {}
|
||||
for form in forms:
|
||||
if form["bits"] & ~form["mask"]:
|
||||
fail(f"{form['name']} has identifying bits outside its mask")
|
||||
key = (form["mask"], form["bits"])
|
||||
if key in by_pattern:
|
||||
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
|
||||
by_pattern[key] = form
|
||||
for left in forms:
|
||||
for right in forms:
|
||||
if left is right or left["mask"] == right["mask"]:
|
||||
continue
|
||||
common = left["mask"] & right["mask"]
|
||||
if (left["bits"] ^ right["bits"]) & common == 0:
|
||||
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
|
||||
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
|
||||
return source, encodings, forms
|
||||
|
||||
|
||||
def rust_from_snapshot(snapshot):
|
||||
source, encodings, forms = forms_from_snapshot(snapshot)
|
||||
out = []
|
||||
emit = out.append
|
||||
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
|
||||
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
|
||||
emit(f"// {source['copyright']}")
|
||||
emit("// SPDX-License-Identifier: MIT")
|
||||
emit("")
|
||||
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
|
||||
emit("")
|
||||
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
|
||||
emit("")
|
||||
|
||||
operand_sets = {}
|
||||
for form in forms:
|
||||
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
|
||||
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
|
||||
for operands_json in operand_sets:
|
||||
operands = json.loads(operands_json)
|
||||
items = ", ".join(
|
||||
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
|
||||
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
|
||||
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
|
||||
for field, data_format, kind, size, i, o, implicit, encoded in operands
|
||||
)
|
||||
emit(f" &[{items}],")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
families = sorted({form["encoding"] for form in forms})
|
||||
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
|
||||
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
|
||||
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
|
||||
for family in families:
|
||||
fields = encodings[reverse[family]]["fields"]
|
||||
items = ", ".join(
|
||||
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
|
||||
for name, ranges in fields
|
||||
)
|
||||
emit(f" (EncodingFamily::{family}, &[{items}]),")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
flag_bits = {
|
||||
"IsBranch": 1,
|
||||
"IsConditionalBranch": 2,
|
||||
"IsIndirectBranch": 4,
|
||||
"IsProgramTerminator": 8,
|
||||
"IsImmediatelyExecuted": 16,
|
||||
}
|
||||
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
|
||||
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
|
||||
emit("pub static FORMS: [Form; %d] = [" % len(forms))
|
||||
for form in forms:
|
||||
flags = sum(flag_bits[flag] for flag in form["flags"])
|
||||
extensions = sum(extension_bits[item] for item in form["extensions"])
|
||||
emit(
|
||||
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
|
||||
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
|
||||
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
|
||||
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
|
||||
)
|
||||
emit("];")
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def compare(path, expected):
|
||||
actual = path.read_text() if path.exists() else ""
|
||||
if actual != expected:
|
||||
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
|
||||
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.xml:
|
||||
snapshot = snapshot_from_xml(args.xml.read_bytes())
|
||||
elif SNAPSHOT.exists():
|
||||
snapshot = SNAPSHOT.read_text()
|
||||
else:
|
||||
fail("no snapshot; pass --xml")
|
||||
rust = rust_from_snapshot(snapshot)
|
||||
if args.check:
|
||||
ok = compare(RUST, rust)
|
||||
if args.xml:
|
||||
ok = compare(SNAPSHOT, snapshot) and ok
|
||||
raise SystemExit(0 if ok else 1)
|
||||
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
|
||||
SNAPSHOT.write_text(snapshot)
|
||||
RUST.write_text(rust)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,311 +0,0 @@
|
||||
//! Typed operands and instruction forms for the bounded gfx1030 compute and graphics subsets.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub mod meta;
|
||||
mod rdna2;
|
||||
#[rustfmt::skip]
|
||||
mod rdna2_meta;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
|
||||
/// Selects the instruction encoding independently of the container and execution ABI.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Architecture {
|
||||
/// LLVM's gfx1030 target for AMD RDNA 2.
|
||||
Gfx1030,
|
||||
}
|
||||
|
||||
/// A generated first-word opcode pattern and its base length, before literal extensions.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Opcode {
|
||||
mask: u32,
|
||||
bits: u32,
|
||||
bytes: u8,
|
||||
}
|
||||
|
||||
impl Opcode {
|
||||
/// Checks the format and opcode bits. The decoder must still validate operands.
|
||||
pub fn matches(self, word: u32) -> bool {
|
||||
word & self.mask == self.bits
|
||||
}
|
||||
|
||||
/// Returns the base instruction size in bytes.
|
||||
pub fn byte_len(self) -> u8 {
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// A 32-bit source for an unmodified vector move.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorSource {
|
||||
/// VGPR index.
|
||||
Register(u8),
|
||||
/// Inline integer or literal word, represented by its bits.
|
||||
Immediate(u32),
|
||||
}
|
||||
|
||||
impl fmt::Display for VectorSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Register(register) => write!(formatter, "v{register}"),
|
||||
Self::Immediate(value) => write!(formatter, "0x{value:x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A scalar 32-bit source.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarSource {
|
||||
/// A normal SGPR index.
|
||||
Register(u8),
|
||||
/// Inline integer or literal word, represented by its bits.
|
||||
Immediate(u32),
|
||||
}
|
||||
|
||||
impl fmt::Display for ScalarSource {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
Self::Register(register) => write!(formatter, "s{register}"),
|
||||
Self::Immediate(value) => match value as i32 {
|
||||
integer @ -16..=64 => write!(formatter, "{integer}"),
|
||||
_ => write!(formatter, "0x{value:x}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ExportTarget {
|
||||
/// Vertex clip position.
|
||||
Position0,
|
||||
/// Vertex parameter slot zero.
|
||||
Parameter0,
|
||||
/// Pixel color attachment zero.
|
||||
RenderTarget0,
|
||||
}
|
||||
|
||||
/// Phase of a pixel parameter interpolation.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum InterpolationPhase {
|
||||
/// Initialize the destination with the base and I-coordinate terms.
|
||||
First,
|
||||
/// Add the J-coordinate term to the destination.
|
||||
Second,
|
||||
}
|
||||
|
||||
/// Instruction forms accepted by the gfx1030 decoder.
|
||||
///
|
||||
/// Vector operations use VGPR indices and scalar operations use SGPR indices.
|
||||
/// The buffer `resource` is the first SGPR of its four-word descriptor.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum Instruction {
|
||||
/// Indexed 32-bit buffer read into a VGPR.
|
||||
BufferLoadDword { data: u8, index: u8, resource: u8 },
|
||||
/// Indexed 32-bit buffer write from a VGPR.
|
||||
BufferStoreDword { data: u8, index: u8, resource: u8 },
|
||||
/// `s_waitcnt vmcnt(0)`.
|
||||
WaitLoad,
|
||||
/// `s_waitcnt_vscnt null, 0`.
|
||||
WaitStore,
|
||||
/// VOP1 unmodified 32-bit vector move.
|
||||
MoveB32 { dst: u8, src: VectorSource },
|
||||
/// VOP3 unsigned 32-bit addition with no carry or input/output modifiers.
|
||||
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOPC 32-bit equality comparison writing SCC.
|
||||
ScalarCompareEqU32 {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPP jump to a stream byte offset when SCC is clear.
|
||||
BranchSccZero { target: usize },
|
||||
/// SOPP jump when the Wave32 execution mask is empty.
|
||||
BranchExecZero { target: usize },
|
||||
/// SOPP jump when the Wave32 vector condition mask is empty.
|
||||
BranchVccZero { target: usize },
|
||||
/// SOPP unconditional jump to a stream byte offset.
|
||||
Branch { target: usize },
|
||||
/// VOP2 logical left shift with the count in src0.
|
||||
VectorLshlrevB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 logical right shift with the count in src0.
|
||||
VectorLshrrevB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 arithmetic right shift with the count in src0.
|
||||
VectorAshrrevI32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise AND.
|
||||
VectorAndB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise OR.
|
||||
VectorOrB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise XOR.
|
||||
VectorXorB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 single-precision addition. Execution requires an explicit FP mode.
|
||||
VectorAddF32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 single-precision multiplication. Execution requires an explicit FP mode.
|
||||
VectorMulF32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// Full, uncompressed four-component graphics export.
|
||||
Export {
|
||||
target: ExportTarget,
|
||||
sources: [u8; 4],
|
||||
},
|
||||
/// Parameter interpolation with a source barycentric coordinate and an attribute component.
|
||||
Interpolate {
|
||||
phase: InterpolationPhase,
|
||||
dst: u8,
|
||||
coordinate: u8,
|
||||
attribute: u8,
|
||||
component: u8,
|
||||
},
|
||||
/// MIMG image_sample_lz 2D RGBA8 texture sample with level of detail zero.
|
||||
ImageSampleLz {
|
||||
/// Four contiguous destination VGPRs [dst..dst+3] receiving RGBA.
|
||||
dst: u8,
|
||||
/// Two contiguous coordinate VGPRs [coord..coord+1] containing (u, v).
|
||||
coord: u8,
|
||||
/// First SGPR of the eight-word resource descriptor s[resource..resource+7].
|
||||
resource: u8,
|
||||
/// First SGPR of the four-word sampler descriptor s[sampler..sampler+3].
|
||||
sampler: u8,
|
||||
},
|
||||
/// Terminates the wave and waits for outstanding memory operations.
|
||||
EndProgram,
|
||||
}
|
||||
|
||||
impl Instruction {
|
||||
/// Returns the mnemonic for the exact encoding family represented.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
match self {
|
||||
Self::BufferLoadDword { .. } => "buffer_load_dword",
|
||||
Self::BufferStoreDword { .. } => "buffer_store_dword",
|
||||
Self::WaitLoad => "s_waitcnt",
|
||||
Self::WaitStore => "s_waitcnt_vscnt",
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
Self::BranchVccZero { .. } => "s_cbranch_vccz",
|
||||
Self::Branch { .. } => "s_branch",
|
||||
Self::VectorLshlrevB32 { .. } => "v_lshlrev_b32_e32",
|
||||
Self::VectorLshrrevB32 { .. } => "v_lshrrev_b32_e32",
|
||||
Self::VectorAshrrevI32 { .. } => "v_ashrrev_i32_e32",
|
||||
Self::VectorAndB32 { .. } => "v_and_b32_e32",
|
||||
Self::VectorOrB32 { .. } => "v_or_b32_e32",
|
||||
Self::VectorXorB32 { .. } => "v_xor_b32_e32",
|
||||
Self::VectorAddF32 { .. } => "v_add_f32_e32",
|
||||
Self::VectorMulF32 { .. } => "v_mul_f32_e32",
|
||||
Self::Export { .. } => "exp",
|
||||
Self::Interpolate {
|
||||
phase: InterpolationPhase::First,
|
||||
..
|
||||
} => "v_interp_p1_f32_e32",
|
||||
Self::Interpolate {
|
||||
phase: InterpolationPhase::Second,
|
||||
..
|
||||
} => "v_interp_p2_f32_e32",
|
||||
Self::ImageSampleLz { .. } => "image_sample_lz",
|
||||
Self::EndProgram => "s_endpgm",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Instruction {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.mnemonic())?;
|
||||
match *self {
|
||||
Self::BufferLoadDword {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
}
|
||||
| Self::BufferStoreDword {
|
||||
data,
|
||||
index,
|
||||
resource,
|
||||
} => {
|
||||
let last = u16::from(resource) + 3;
|
||||
write!(
|
||||
formatter,
|
||||
" v{data}, v{index}, s[{resource}:{last}], 0 idxen"
|
||||
)
|
||||
}
|
||||
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
|
||||
Self::WaitStore => formatter.write_str(" null, 0"),
|
||||
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
|
||||
Self::AddNoCarryU32 { dst, src0, src1 }
|
||||
| Self::VectorLshlrevB32 { dst, src0, src1 }
|
||||
| Self::VectorLshrrevB32 { dst, src0, src1 }
|
||||
| Self::VectorAshrrevI32 { dst, src0, src1 }
|
||||
| Self::VectorAndB32 { dst, src0, src1 }
|
||||
| Self::VectorOrB32 { dst, src0, src1 }
|
||||
| Self::VectorXorB32 { dst, src0, src1 }
|
||||
| Self::VectorAddF32 { dst, src0, src1 }
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } => match dst {
|
||||
106 => write!(formatter, " vcc_lo, {src}"),
|
||||
107 => write!(formatter, " vcc_hi, {src}"),
|
||||
126 => write!(formatter, " exec_lo, {src}"),
|
||||
127 => write!(formatter, " exec_hi, {src}"),
|
||||
_ => write!(formatter, " s{dst}, {src}"),
|
||||
},
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
| Self::BranchExecZero { target }
|
||||
| Self::BranchVccZero { target } => {
|
||||
write!(formatter, " -> 0x{target:04x}")
|
||||
}
|
||||
Self::Export {
|
||||
target,
|
||||
sources: [a, b, c, d],
|
||||
} => {
|
||||
let (name, flags) = match target {
|
||||
ExportTarget::Position0 => ("pos0", " done"),
|
||||
ExportTarget::Parameter0 => ("param0", ""),
|
||||
ExportTarget::RenderTarget0 => ("mrt0", " done vm"),
|
||||
};
|
||||
write!(formatter, " {name}, v{a}, v{b}, v{c}, v{d}{flags}")
|
||||
}
|
||||
Self::Interpolate {
|
||||
dst,
|
||||
coordinate,
|
||||
attribute,
|
||||
component,
|
||||
..
|
||||
} => {
|
||||
let channel = ["x", "y", "z", "w"]
|
||||
.get(usize::from(component))
|
||||
.ok_or(fmt::Error)?;
|
||||
write!(
|
||||
formatter,
|
||||
" v{dst}, v{coordinate}, attr{attribute}.{channel}"
|
||||
)
|
||||
}
|
||||
Self::ImageSampleLz {
|
||||
dst,
|
||||
coord,
|
||||
resource,
|
||||
sampler,
|
||||
} => {
|
||||
let last_dst = dst + 3;
|
||||
let last_coord = coord + 1;
|
||||
let last_res = resource + 7;
|
||||
let last_samp = sampler + 3;
|
||||
write!(
|
||||
formatter,
|
||||
" v[{dst}:{last_dst}], v[{coord}:{last_coord}], s[{resource}:{last_res}], s[{sampler}:{last_samp}] dmask:0xf dim:SQ_RSRC_IMG_2D"
|
||||
)
|
||||
}
|
||||
Self::EndProgram => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,414 +0,0 @@
|
||||
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
|
||||
//!
|
||||
//! Identification here establishes an instruction's form and length only. It is
|
||||
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
|
||||
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
|
||||
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
|
||||
//! ISA reference guide (see docs/research/rdna2.md).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
|
||||
|
||||
/// AMD base encoding of an instruction form.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum EncodingFamily {
|
||||
Ds,
|
||||
Exp,
|
||||
Flat,
|
||||
Global,
|
||||
Mimg,
|
||||
Mtbuf,
|
||||
Mubuf,
|
||||
Scratch,
|
||||
Smem,
|
||||
Sop1,
|
||||
Sop2,
|
||||
Sopc,
|
||||
Sopk,
|
||||
Sopp,
|
||||
Vintrp,
|
||||
Vop1,
|
||||
Vop2,
|
||||
Vop3,
|
||||
Vop3Sdst,
|
||||
Vop3p,
|
||||
Vopc,
|
||||
}
|
||||
|
||||
impl EncodingFamily {
|
||||
/// Every family, in table order.
|
||||
pub const ALL: [Self; 21] = [
|
||||
Self::Ds,
|
||||
Self::Exp,
|
||||
Self::Flat,
|
||||
Self::Global,
|
||||
Self::Mimg,
|
||||
Self::Mtbuf,
|
||||
Self::Mubuf,
|
||||
Self::Scratch,
|
||||
Self::Smem,
|
||||
Self::Sop1,
|
||||
Self::Sop2,
|
||||
Self::Sopc,
|
||||
Self::Sopk,
|
||||
Self::Sopp,
|
||||
Self::Vintrp,
|
||||
Self::Vop1,
|
||||
Self::Vop2,
|
||||
Self::Vop3,
|
||||
Self::Vop3Sdst,
|
||||
Self::Vop3p,
|
||||
Self::Vopc,
|
||||
];
|
||||
|
||||
/// Lower-case name used in reports.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ds => "ds",
|
||||
Self::Exp => "exp",
|
||||
Self::Flat => "flat",
|
||||
Self::Global => "global",
|
||||
Self::Mimg => "mimg",
|
||||
Self::Mtbuf => "mtbuf",
|
||||
Self::Mubuf => "mubuf",
|
||||
Self::Scratch => "scratch",
|
||||
Self::Smem => "smem",
|
||||
Self::Sop1 => "sop1",
|
||||
Self::Sop2 => "sop2",
|
||||
Self::Sopc => "sopc",
|
||||
Self::Sopk => "sopk",
|
||||
Self::Sopp => "sopp",
|
||||
Self::Vintrp => "vintrp",
|
||||
Self::Vop1 => "vop1",
|
||||
Self::Vop2 => "vop2",
|
||||
Self::Vop3 => "vop3",
|
||||
Self::Vop3Sdst => "vop3-sdst",
|
||||
Self::Vop3p => "vop3p",
|
||||
Self::Vopc => "vopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-flow flags recorded by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormFlags(pub u8);
|
||||
|
||||
impl FormFlags {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
#[allow(missing_docs)]
|
||||
pub const BRANCH: Self = Self(1);
|
||||
#[allow(missing_docs)]
|
||||
pub const CONDITIONAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const INDIRECT: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const TERMINATOR: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const IMMEDIATE: Self = Self(16);
|
||||
|
||||
/// Whether every flag in `other` is set.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension words an instruction form may carry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Extensions(pub u8);
|
||||
|
||||
impl Extensions {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
/// A source field may select a trailing 32-bit literal.
|
||||
pub const LITERAL: Self = Self(1);
|
||||
/// The form always carries a trailing 32-bit literal.
|
||||
pub const ALWAYS_LITERAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const SDWA: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP8: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP16: Self = Self(16);
|
||||
/// MIMG non-sequential address dwords.
|
||||
pub const NSA: Self = Self(32);
|
||||
|
||||
/// Whether every extension in `other` is allowed.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FieldLayout {
|
||||
#[allow(missing_docs)]
|
||||
pub name: &'static str,
|
||||
#[allow(missing_docs)]
|
||||
pub pieces: &'static [(u8, u8)],
|
||||
}
|
||||
|
||||
impl FieldLayout {
|
||||
/// Extracts the field from the instruction's first two dwords.
|
||||
pub fn extract(&self, value: u64) -> u32 {
|
||||
let mut result = 0u64;
|
||||
let mut shift = 0;
|
||||
for &(offset, count) in self.pieces {
|
||||
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
|
||||
shift += count;
|
||||
}
|
||||
result as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// An operand as described by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct OperandInfo {
|
||||
pub field: &'static str,
|
||||
pub format: &'static str,
|
||||
pub kind: &'static str,
|
||||
pub bits: u16,
|
||||
pub input: bool,
|
||||
pub output: bool,
|
||||
pub implicit: bool,
|
||||
/// Whether the operand occupies microcode bits.
|
||||
pub encoded: bool,
|
||||
}
|
||||
|
||||
/// One instruction in one base encoding.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct Form {
|
||||
pub name: &'static str,
|
||||
pub family: EncodingFamily,
|
||||
pub opcode: u16,
|
||||
/// Identifying bits over the first two dwords (little-endian, first dword low).
|
||||
pub mask: u64,
|
||||
pub bits: u64,
|
||||
/// Base length before literal, SDWA, DPP or NSA words.
|
||||
pub bytes: u8,
|
||||
pub flags: FormFlags,
|
||||
pub extensions: Extensions,
|
||||
pub group: &'static str,
|
||||
pub operands: &'static [OperandInfo],
|
||||
}
|
||||
|
||||
impl Form {
|
||||
/// The base encoding's field layouts.
|
||||
pub fn fields(&self) -> &'static [FieldLayout] {
|
||||
FIELDS
|
||||
.iter()
|
||||
.find(|(family, _)| *family == self.family)
|
||||
.map(|(_, fields)| *fields)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// The named field's layout, if the encoding has one.
|
||||
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
|
||||
self.fields().iter().find(|field| field.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which extension words an identified instruction carries.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Trailer {
|
||||
/// A 32-bit literal follows the base encoding.
|
||||
pub literal: bool,
|
||||
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
|
||||
pub vector_control: Option<VectorControl>,
|
||||
/// Extra MIMG address dwords.
|
||||
pub nsa_dwords: u8,
|
||||
}
|
||||
|
||||
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum VectorControl {
|
||||
Sdwa,
|
||||
Dpp8 { fetch_inactive: bool },
|
||||
Dpp16,
|
||||
}
|
||||
|
||||
/// An identified instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Identified {
|
||||
/// The matched form.
|
||||
pub form: &'static Form,
|
||||
/// First two dwords; the second is zero for 32-bit encodings.
|
||||
pub raw: u64,
|
||||
/// Total length in bytes, including extension words.
|
||||
pub len: usize,
|
||||
/// Extension words present.
|
||||
pub trailer: Trailer,
|
||||
}
|
||||
|
||||
impl Identified {
|
||||
/// Extracts a named field of the base encoding.
|
||||
pub fn field(&self, name: &str) -> Option<u32> {
|
||||
self.form.field(name).map(|field| field.extract(self.raw))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an instruction could not be identified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum IdentifyError {
|
||||
/// Fewer bytes remain than the encoding or its extension words need.
|
||||
Truncated {
|
||||
/// Bytes required from the instruction start.
|
||||
needed: usize,
|
||||
},
|
||||
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
|
||||
Unassigned,
|
||||
/// The bits select an extension the form does not allow.
|
||||
InvalidExtension(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for IdentifyError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
|
||||
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
|
||||
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentifyError {}
|
||||
|
||||
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
|
||||
pub const SRC_LITERAL: u32 = 255;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
|
||||
pub const SRC_SDWA: u32 = 0xf9;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
|
||||
pub const SRC_DPP16: u32 = 0xfa;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
|
||||
pub const SRC_DPP8: u32 = 0xe9;
|
||||
/// DPP8 with fetch-inactive set.
|
||||
pub const SRC_DPP8_FI: u32 = 0xea;
|
||||
|
||||
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
|
||||
let start = index.checked_mul(4)?;
|
||||
let chunk = bytes.get(start..start.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes(chunk.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// Finds the form whose identifying bits match.
|
||||
///
|
||||
/// Masks never overlap ambiguously; the generator rejects such tables.
|
||||
pub fn lookup(raw: u64) -> Option<&'static Form> {
|
||||
FORMS.iter().find(|form| raw & form.mask == form.bits)
|
||||
}
|
||||
|
||||
/// Identifies the instruction at the start of `bytes` and computes its length.
|
||||
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
|
||||
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
|
||||
let second = read_dword(bytes, 1);
|
||||
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
|
||||
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
|
||||
.or_else(|| {
|
||||
// Distinguish a truncated 64-bit instruction from unassigned bits.
|
||||
FORMS.iter().find(|form| {
|
||||
form.bytes == 8
|
||||
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
|
||||
})
|
||||
})
|
||||
.ok_or(IdentifyError::Unassigned)?;
|
||||
if form.bytes == 8 && second.is_none() {
|
||||
return Err(IdentifyError::Truncated { needed: 8 });
|
||||
}
|
||||
let raw = if form.bytes == 4 {
|
||||
u64::from(first)
|
||||
} else {
|
||||
raw_guess
|
||||
};
|
||||
let mut trailer = Trailer::default();
|
||||
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
|
||||
match form.family {
|
||||
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
|
||||
trailer.literal = [source("SSRC0"), source("SSRC1")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
|
||||
match source("SRC0") {
|
||||
Some(SRC_LITERAL) => trailer.literal = true,
|
||||
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
|
||||
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
|
||||
Some(SRC_DPP8) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
})
|
||||
}
|
||||
Some(SRC_DPP8_FI) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
})
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
|
||||
trailer.literal = [source("SRC0"), source("SRC1"), source("SRC2")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Mimg => {
|
||||
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
|
||||
trailer.literal = true;
|
||||
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
|
||||
return Err(IdentifyError::InvalidExtension("literal"));
|
||||
}
|
||||
match trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
|
||||
return Err(IdentifyError::InvalidExtension("sdwa"));
|
||||
}
|
||||
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp8"));
|
||||
}
|
||||
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp16"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
|
||||
return Err(IdentifyError::InvalidExtension("nsa"));
|
||||
}
|
||||
let len = usize::from(form.bytes)
|
||||
+ 4 * usize::from(trailer.literal)
|
||||
+ 4 * usize::from(trailer.vector_control.is_some())
|
||||
+ 4 * usize::from(trailer.nsa_dwords);
|
||||
if bytes.len() < len {
|
||||
return Err(IdentifyError::Truncated { needed: len });
|
||||
}
|
||||
Ok(Identified {
|
||||
form,
|
||||
raw,
|
||||
len,
|
||||
trailer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of forms per encoding family in the metadata.
|
||||
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
|
||||
EncodingFamily::ALL
|
||||
.iter()
|
||||
.map(|&family| {
|
||||
(
|
||||
family,
|
||||
FORMS.iter().filter(|form| form.family == family).count(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
// Generated by crates/isa/generate_rdna2.py. See docs/research/rdna2.md.
|
||||
// Source: AMD RDNA 2 XML, 2026-02-20, schema 1.1.1.
|
||||
// Copyright (c) 2026 Advanced Micro Devices, Inc., or its affiliates.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use super::Opcode;
|
||||
|
||||
pub const BUFFER_LOAD_DWORD: Opcode = Opcode {
|
||||
mask: 0xfffc0000,
|
||||
bits: 0xe0300000,
|
||||
bytes: 8,
|
||||
};
|
||||
pub const BUFFER_STORE_DWORD: Opcode = Opcode {
|
||||
mask: 0xfffc0000,
|
||||
bits: 0xe0700000,
|
||||
bytes: 8,
|
||||
};
|
||||
pub const S_WAITCNT: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf8c0000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_WAITCNT_VSCNT: Opcode = Opcode {
|
||||
mask: 0xff800000,
|
||||
bits: 0xbb800000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_MOV_B32: Opcode = Opcode {
|
||||
mask: 0xfe01fe00,
|
||||
bits: 0x7e000200,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_ADD_NC_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xd5250000,
|
||||
bytes: 8,
|
||||
};
|
||||
pub const S_ENDPGM: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf810000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_MOV_B32: Opcode = Opcode {
|
||||
mask: 0xff80ff00,
|
||||
bits: 0xbe800300,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_EXECZ: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf880000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_VCCZ: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf860000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_BRANCH: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf820000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_LSHLREV_B32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x34000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_LSHRREV_B32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x2c000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_ASHRREV_I32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x30000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_AND_B32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x36000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_OR_B32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x38000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_XOR_B32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x3a000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_ADD_F32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x06000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_MUL_F32: Opcode = Opcode {
|
||||
mask: 0xfe000000,
|
||||
bits: 0x10000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const EXP: Opcode = Opcode {
|
||||
mask: 0xfc000000,
|
||||
bits: 0xf8000000,
|
||||
bytes: 8,
|
||||
};
|
||||
pub const V_INTERP_P1_F32: Opcode = Opcode {
|
||||
mask: 0xfc030000,
|
||||
bits: 0xc8000000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const V_INTERP_P2_F32: Opcode = Opcode {
|
||||
mask: 0xfc030000,
|
||||
bits: 0xc8010000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const IMAGE_SAMPLE_LZ: Opcode = Opcode {
|
||||
mask: 0xfdfc0001,
|
||||
bits: 0xf09c0000,
|
||||
bytes: 8,
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,177 +0,0 @@
|
||||
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_isa::meta::{
|
||||
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
|
||||
};
|
||||
|
||||
fn words(values: &[u32]) -> Vec<u8> {
|
||||
values
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn name_of(values: &[u32]) -> (&'static str, usize) {
|
||||
let found = identify(&words(values)).unwrap();
|
||||
(found.form.name, found.len)
|
||||
}
|
||||
|
||||
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
|
||||
fn source_mnemonics(source: &str) -> Vec<String> {
|
||||
source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap().trim())
|
||||
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
|
||||
.map(|line| {
|
||||
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
|
||||
mnemonic
|
||||
.trim_end_matches("_E32")
|
||||
.trim_end_matches("_E64")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut checked = 0;
|
||||
for entry in fs::read_dir(&directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
let source = fs::read_to_string(path.with_extension("s")).unwrap();
|
||||
let mut offset = 0;
|
||||
let mut identified = Vec::new();
|
||||
while offset < binary.len() {
|
||||
let found = identify(&binary[offset..])
|
||||
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
|
||||
identified.push(found.form.name.to_owned());
|
||||
offset += found.len;
|
||||
}
|
||||
assert_eq!(offset, binary.len(), "{}", path.display());
|
||||
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked >= 11, "only {checked} fixtures found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_assembled_words_identify() {
|
||||
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
|
||||
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
|
||||
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
|
||||
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
|
||||
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
|
||||
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
|
||||
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
|
||||
// VOP3 v_add_f32_e64 v0, v1, v2: VOP3 opcode 259 = 256 + VOP2 opcode 3.
|
||||
assert_eq!(name_of(&[0xd503_0000, 0x0002_0501]), ("V_ADD_F32", 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_sdwa_and_dpp_words_extend_the_length() {
|
||||
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
|
||||
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
|
||||
assert!(literal.trailer.literal);
|
||||
// s_add_u32 s0, s1, literal: SSRC1 = 255.
|
||||
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
|
||||
// VOP3 with SRC2 = 255.
|
||||
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
|
||||
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
|
||||
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
|
||||
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
|
||||
assert_eq!(sdwa.len, 8);
|
||||
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
|
||||
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
|
||||
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
|
||||
assert_eq!(
|
||||
dpp8.trailer.vector_control,
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_unassigned_inputs_are_rejected() {
|
||||
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
|
||||
assert_eq!(
|
||||
identify(&[0x00, 0x00, 0x81]),
|
||||
Err(IdentifyError::Truncated { needed: 4 })
|
||||
);
|
||||
// VOP3 first dword alone.
|
||||
assert_eq!(
|
||||
identify(&words(&[0xd503_0000])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// Literal selected but absent.
|
||||
assert_eq!(
|
||||
identify(&words(&[0x7e00_02ff])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
|
||||
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
|
||||
assert_eq!(
|
||||
identify(&words(&[0xbfff_0000])),
|
||||
Err(IdentifyError::Unassigned)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_outside_a_forms_metadata_are_rejected() {
|
||||
let without_sdwa = FORMS
|
||||
.iter()
|
||||
.find(|form| {
|
||||
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
|
||||
})
|
||||
.expect("a VOP1 form without SDWA");
|
||||
let word = (without_sdwa.bits as u32) | 0xf9;
|
||||
assert_eq!(
|
||||
identify(&words(&[word, 0])),
|
||||
Err(IdentifyError::InvalidExtension("sdwa"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_form_identifies_as_itself() {
|
||||
for form in &FORMS {
|
||||
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
|
||||
assert_eq!(
|
||||
lookup(form.bits).unwrap().family,
|
||||
form.family,
|
||||
"{}",
|
||||
form.name
|
||||
);
|
||||
}
|
||||
let total: usize = inventory().iter().map(|(_, count)| count).sum();
|
||||
assert_eq!(total, FORMS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_word_opcode_table_agrees_with_full_metadata() {
|
||||
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
|
||||
for (opcode, name, family) in [
|
||||
(
|
||||
BUFFER_LOAD_DWORD,
|
||||
"BUFFER_LOAD_DWORD",
|
||||
EncodingFamily::Mubuf,
|
||||
),
|
||||
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
|
||||
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
|
||||
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
|
||||
] {
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == name && form.family == family)
|
||||
.unwrap();
|
||||
assert!(opcode.matches(form.bits as u32), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
[package]
|
||||
name = "xenora-loader"
|
||||
description = "PE32+ loader, guest memory management, and x86-64 execution bootstrap for Xenora"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh); CI's virtual GPU lacks Apple family 7.
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
|
||||
[[bench]]
|
||||
name = "dbt_bench"
|
||||
harness = false
|
||||
@@ -1,167 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
};
|
||||
|
||||
fn build_pe(code: &[u8]) -> Vec<u8> {
|
||||
let mut pe = Vec::new();
|
||||
pe.extend_from_slice(b"MZ");
|
||||
pe.resize(0x3C, 0);
|
||||
let e_lfanew: u32 = 0x80;
|
||||
pe.extend_from_slice(&e_lfanew.to_le_bytes());
|
||||
pe.resize(0x80, 0);
|
||||
pe.extend_from_slice(b"PE\0\0");
|
||||
pe.extend_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
|
||||
let num_sections: u16 = 1;
|
||||
pe.extend_from_slice(&num_sections.to_le_bytes());
|
||||
pe.extend_from_slice(&0x67300000u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let opt_hdr_size: u16 = 112;
|
||||
pe.extend_from_slice(&opt_hdr_size.to_le_bytes());
|
||||
pe.extend_from_slice(&0x0022u16.to_le_bytes());
|
||||
pe.extend_from_slice(&PE32_PLUS_MAGIC.to_le_bytes());
|
||||
pe.push(14);
|
||||
pe.push(0);
|
||||
pe.extend_from_slice(&(code.len() as u32).to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let entry_point_rva: u32 = 0x1000;
|
||||
pe.extend_from_slice(&entry_point_rva.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
let image_base: u64 = 0x0000000140000000;
|
||||
pe.extend_from_slice(&image_base.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0x200u32.to_le_bytes());
|
||||
pe.extend_from_slice(&6u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&6u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let size_of_image = 0x1000 + ((code.len() as u32 + 0xfff) & !0xfff);
|
||||
pe.extend_from_slice(&size_of_image.to_le_bytes());
|
||||
pe.extend_from_slice(&0x200u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&3u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0x8160u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0x100000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x100000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let mut sec_name = [0u8; 8];
|
||||
sec_name[..5].copy_from_slice(b".text");
|
||||
pe.extend_from_slice(&sec_name);
|
||||
pe.extend_from_slice(&(code.len() as u32).to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
let raw_size = (code.len() as u32 + 0x1ff) & !0x1ff;
|
||||
pe.extend_from_slice(&raw_size.to_le_bytes());
|
||||
pe.extend_from_slice(&0x200u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&(IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE).to_le_bytes());
|
||||
pe.resize(0x200, 0);
|
||||
pe.extend_from_slice(code);
|
||||
pe.resize(0x200 + raw_size as usize, 0);
|
||||
pe
|
||||
}
|
||||
|
||||
const ADDS: usize = 10_000;
|
||||
const INSTRUCTIONS: usize = ADDS + 2;
|
||||
const BUDGET: usize = 20_000;
|
||||
const STACK_TOP: u64 = 0x2000_8000;
|
||||
|
||||
fn check(result: ExecutionResult) {
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.instructions_executed, INSTRUCTIONS);
|
||||
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
samples.sort_unstable();
|
||||
let median = samples[samples.len() / 2];
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
|
||||
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
|
||||
assert!(sample_count > 0);
|
||||
|
||||
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
|
||||
for _ in 0..ADDS {
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xC0, 0x01]); // add rax, 1
|
||||
}
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let pe_bytes = build_pe(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).unwrap();
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).unwrap();
|
||||
loaded
|
||||
.memory
|
||||
.map_region(0x2000_0000, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let initial_cpu = CpuState::new(loaded.entry_point, STACK_TOP);
|
||||
let mut interpreter = Vec::with_capacity(sample_count);
|
||||
let mut cold = Vec::with_capacity(sample_count);
|
||||
let mut warm = Vec::with_capacity(sample_count);
|
||||
let mut cold_metrics = None;
|
||||
|
||||
for _ in 0..sample_count {
|
||||
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
|
||||
let start = Instant::now();
|
||||
let result = black_box(interp.run());
|
||||
interpreter.push(start.elapsed());
|
||||
check(result);
|
||||
|
||||
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
cold.push(start.elapsed());
|
||||
check(result);
|
||||
assert!(dbt.metrics.blocks_compiled > 0);
|
||||
assert_eq!(dbt.metrics.cache_hits, 0);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
cold_metrics = Some(dbt.metrics);
|
||||
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
warm.push(start.elapsed());
|
||||
check(result);
|
||||
assert_eq!(
|
||||
Some(dbt.metrics.blocks_compiled),
|
||||
cold_metrics.map(|m| m.blocks_compiled)
|
||||
);
|
||||
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
}
|
||||
|
||||
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
let metrics = cold_metrics.unwrap();
|
||||
println!(
|
||||
"Cold DBT compiled {} blocks and emitted {} native bytes in {} dispatches",
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
}
|
||||
@@ -1,577 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Bounded ARM64 machine instruction emitter for DBT blocks.
|
||||
|
||||
/// Standard ARM64 Register indices (0..=31, where 31 is SP or ZR depending on instruction).
|
||||
pub const X0: u8 = 0;
|
||||
pub const X1: u8 = 1;
|
||||
pub const X2: u8 = 2;
|
||||
pub const X3: u8 = 3;
|
||||
pub const X4: u8 = 4;
|
||||
pub const X5: u8 = 5;
|
||||
pub const X6: u8 = 6;
|
||||
pub const X7: u8 = 7;
|
||||
pub const X8: u8 = 8;
|
||||
pub const X9: u8 = 9;
|
||||
pub const X10: u8 = 10;
|
||||
pub const X11: u8 = 11;
|
||||
pub const X12: u8 = 12;
|
||||
pub const X13: u8 = 13;
|
||||
pub const X14: u8 = 14;
|
||||
pub const X15: u8 = 15;
|
||||
pub const X16: u8 = 16;
|
||||
pub const X17: u8 = 17;
|
||||
pub const X18: u8 = 18;
|
||||
pub const X19: u8 = 19;
|
||||
pub const X20: u8 = 20;
|
||||
pub const X21: u8 = 21;
|
||||
pub const X22: u8 = 22;
|
||||
pub const X23: u8 = 23;
|
||||
pub const X24: u8 = 24;
|
||||
pub const X25: u8 = 25;
|
||||
pub const X26: u8 = 26;
|
||||
pub const X27: u8 = 27;
|
||||
pub const X28: u8 = 28;
|
||||
pub const X29: u8 = 29; // Frame Pointer (FP)
|
||||
pub const X30: u8 = 30; // Link Register (LR)
|
||||
pub const SP: u8 = 31; // Stack Pointer
|
||||
pub const XZR: u8 = 31; // Zero Register
|
||||
|
||||
/// ARM64 Condition codes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Condition {
|
||||
Eq = 0, // Equal (Z == 1)
|
||||
Ne = 1, // Not equal (Z == 0)
|
||||
Cs = 2, // Carry set / unsigned higher or same (C == 1)
|
||||
Cc = 3, // Carry clear / unsigned lower (C == 0)
|
||||
Mi = 4, // Minus / negative (N == 1)
|
||||
Pl = 5, // Plus / positive or zero (N == 0)
|
||||
Vs = 6, // Overflow (V == 1)
|
||||
Vc = 7, // No overflow (V == 0)
|
||||
Hi = 8, // Unsigned higher (C == 1 && Z == 0)
|
||||
Ls = 9, // Unsigned lower or same (C == 0 || Z == 1)
|
||||
Ge = 10, // Signed greater than or equal (N == V)
|
||||
Lt = 11, // Signed less than (N != V)
|
||||
Gt = 12, // Signed greater than (Z == 0 && N == V)
|
||||
Le = 13, // Signed less than or equal (Z == 1 || N != V)
|
||||
Al = 14, // Always
|
||||
}
|
||||
|
||||
/// Helper for assembling 32-bit ARM64 instructions.
|
||||
#[derive(Default)]
|
||||
pub struct Arm64Assembler {
|
||||
code: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Arm64Assembler {
|
||||
pub fn new() -> Self {
|
||||
Self { code: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn instructions(&self) -> &[u32] {
|
||||
&self.code
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.code.clear();
|
||||
}
|
||||
|
||||
pub fn current_offset(&self) -> usize {
|
||||
self.code.len()
|
||||
}
|
||||
|
||||
pub fn emit(&mut self, insn: u32) {
|
||||
self.code.push(insn);
|
||||
}
|
||||
|
||||
/// RET [X30]
|
||||
pub fn ret(&mut self) {
|
||||
self.emit(0xd65f03c0);
|
||||
}
|
||||
|
||||
/// NOP
|
||||
pub fn nop(&mut self) {
|
||||
self.emit(0xd503201f);
|
||||
}
|
||||
|
||||
/// BR Xn (Branch to register)
|
||||
pub fn br(&mut self, xn: u8) {
|
||||
self.emit(0xd61f0000 | ((xn as u32 & 0x1f) << 5));
|
||||
}
|
||||
|
||||
/// BLR Xn (Branch with link to register)
|
||||
pub fn blr(&mut self, xn: u8) {
|
||||
self.emit(0xd63f0000 | ((xn as u32 & 0x1f) << 5));
|
||||
}
|
||||
|
||||
/// B imm26 (Unconditional branch)
|
||||
pub fn b(&mut self, offset_insns: i32) {
|
||||
let imm26 = (offset_insns as u32) & 0x03ff_ffff;
|
||||
self.emit(0x1400_0000 | imm26);
|
||||
}
|
||||
|
||||
/// B.cond imm19 (Conditional branch)
|
||||
pub fn b_cond(&mut self, cond: Condition, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.emit(0x5400_0000 | imm19 | (cond as u32 & 0xf));
|
||||
}
|
||||
|
||||
/// Patch previously emitted branch instruction at `index`.
|
||||
pub fn patch_b_cond(&mut self, index: usize, cond: Condition, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.code[index] = 0x5400_0000 | imm19 | (cond as u32 & 0xf);
|
||||
}
|
||||
|
||||
/// Patch a previously emitted unconditional `B` at `index`.
|
||||
pub fn patch_b(&mut self, index: usize, offset_insns: i32) {
|
||||
let imm26 = (offset_insns as u32) & 0x03ff_ffff;
|
||||
self.code[index] = 0x1400_0000 | imm26;
|
||||
}
|
||||
|
||||
/// CBZ Xt, imm19 (compare and branch on zero, 64-bit).
|
||||
pub fn cbz_64(&mut self, xt: u8, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.emit(0xb4000000 | imm19 | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// CBNZ Xt, imm19 (compare and branch on nonzero, 64-bit).
|
||||
pub fn cbnz_64(&mut self, xt: u8, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.emit(0xb5000000 | imm19 | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Patch a previously emitted `CBZ`/`CBNZ` at `index`.
|
||||
pub fn patch_cbz_64(&mut self, index: usize, xt: u8, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
let template = self.code[index] & 0xff00_0000;
|
||||
self.code[index] = template | imm19 | (xt as u32 & 0x1f);
|
||||
}
|
||||
|
||||
/// ADD (extended/shifted register, 64-bit): ADD Xd, Xn, Xm
|
||||
pub fn add_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x8b000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (shifted register, 64-bit): ADD Xd, Xn, Xm, LSL #shift
|
||||
pub fn add_reg_shifted_64(&mut self, xd: u8, xn: u8, xm: u8, shift: u8) {
|
||||
self.emit(
|
||||
0x8b000000
|
||||
| ((shift as u32 & 0x3f) << 10)
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// UXTB (32-bit/zero-extended): UXTB Wd, Wn (UBFM Wd, Wn, #0, #7)
|
||||
pub fn uxtb_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x53001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// UXTH (32-bit/zero-extended): UXTH Wd, Wn (UBFM Wd, Wn, #0, #15)
|
||||
pub fn uxth_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x53003c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTB (64-bit/sign-extended): SXTB Xd, Wn (SBFM Xd, Xn, #0, #7)
|
||||
pub fn sxtb_64(&mut self, xd: u8, wn: u8) {
|
||||
self.emit(0x93401c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTH (64-bit/sign-extended): SXTH Xd, Wn (SBFM Xd, Xn, #0, #15)
|
||||
pub fn sxth_64(&mut self, xd: u8, wn: u8) {
|
||||
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
|
||||
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x0b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADDS (64-bit, flags updating): ADDS Xd, Xn, Xm
|
||||
pub fn adds_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xab000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADDS (32-bit, flags updating): ADDS Wd, Wn, Wm
|
||||
pub fn adds_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x2b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (immediate, 64-bit): ADD Xd, Xn, #imm12
|
||||
pub fn add_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
|
||||
self.emit(
|
||||
0x91000000
|
||||
| (((imm12 & 0x0fff) as u32) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUB (immediate, 64-bit): SUB Xd, Xn, #imm12
|
||||
pub fn sub_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
|
||||
self.emit(
|
||||
0xd1000000
|
||||
| (((imm12 & 0x0fff) as u32) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUB (register, 64-bit): SUB Xd, Xn, Xm
|
||||
pub fn sub_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xcb000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUB (register, 32-bit): SUB Wd, Wn, Wm
|
||||
pub fn sub_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x4b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUBS (64-bit, flags updating): SUBS Xd, Xn, Xm
|
||||
pub fn subs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xeb000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUBS (32-bit, flags updating): SUBS Wd, Wn, Wm
|
||||
pub fn subs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x6b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// CMP (register, 64-bit): SUBS XZR, Xn, Xm
|
||||
pub fn cmp_reg_64(&mut self, xn: u8, xm: u8) {
|
||||
self.subs_reg_64(XZR, xn, xm);
|
||||
}
|
||||
|
||||
/// CMP (register, 32-bit): SUBS WZR, Wn, Wm
|
||||
pub fn cmp_reg_32(&mut self, wn: u8, wm: u8) {
|
||||
self.subs_reg_32(XZR, wn, wm);
|
||||
}
|
||||
|
||||
/// AND (register, 64-bit): AND Xd, Xn, Xm
|
||||
pub fn and_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x8a000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ANDS (register, 64-bit, flags updating / TST): ANDS Xd, Xn, Xm
|
||||
pub fn ands_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xea000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ANDS (register, 32-bit, flags updating / TST): ANDS Wd, Wn, Wm
|
||||
pub fn ands_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x6a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// TST (register, 64-bit): ANDS XZR, Xn, Xm
|
||||
pub fn tst_reg_64(&mut self, xn: u8, xm: u8) {
|
||||
self.ands_reg_64(XZR, xn, xm);
|
||||
}
|
||||
|
||||
/// TST (register, 32-bit): ANDS WZR, Wn, Wm
|
||||
pub fn tst_reg_32(&mut self, wn: u8, wm: u8) {
|
||||
self.ands_reg_32(XZR, wn, wm);
|
||||
}
|
||||
|
||||
/// ORR (register, 64-bit): ORR Xd, Xn, Xm
|
||||
pub fn orr_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xaa000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// EOR (register, 64-bit, XOR): EOR Xd, Xn, Xm
|
||||
pub fn eor_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xca000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// MOV (register, 64-bit): ORR Xd, XZR, Xm
|
||||
pub fn mov_reg_64(&mut self, xd: u8, xm: u8) {
|
||||
self.orr_reg_64(xd, XZR, xm);
|
||||
}
|
||||
|
||||
/// MOV (register, 32-bit zero-extended): ORR Wd, WZR, Wm
|
||||
pub fn mov_reg_32(&mut self, wd: u8, wm: u8) {
|
||||
self.emit(0x2a000000 | ((wm as u32 & 0x1f) << 16) | (31 << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// MOVZ (64-bit with shift): MOVZ Xd, #imm16, LSL #shift
|
||||
pub fn movz_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0xd2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// MOVK (64-bit with shift): MOVK Xd, #imm16, LSL #shift
|
||||
pub fn movk_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Load a full 64-bit constant into register Xd.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let w0 = (val & 0xffff) as u16;
|
||||
let w1 = ((val >> 16) & 0xffff) as u16;
|
||||
let w2 = ((val >> 32) & 0xffff) as u16;
|
||||
let w3 = ((val >> 48) & 0xffff) as u16;
|
||||
|
||||
self.movz_64(xd, w0, 0);
|
||||
if w1 != 0 || (w2 == 0 && w3 == 0) {
|
||||
self.movk_64(xd, w1, 1);
|
||||
}
|
||||
if w2 != 0 || w3 != 0 {
|
||||
self.movk_64(xd, w2, 2);
|
||||
}
|
||||
if w3 != 0 {
|
||||
self.movk_64(xd, w3, 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// LDR (64-bit, unsigned offset): LDR Xt, [Xn, #imm]
|
||||
pub fn ldr_uoff_64(&mut self, xt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 8) & 0x0fff;
|
||||
self.emit(0xf9400000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// STR (64-bit, unsigned offset): STR Xt, [Xn, #imm]
|
||||
pub fn str_uoff_64(&mut self, xt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 8) & 0x0fff;
|
||||
self.emit(0xf9000000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// LDR (32-bit, unsigned offset): LDR Wt, [Xn, #imm]
|
||||
pub fn ldr_uoff_32(&mut self, wt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 4) & 0x0fff;
|
||||
self.emit(0xb9400000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (wt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// STR (32-bit, unsigned offset): STR Wt, [Xn, #imm]
|
||||
pub fn str_uoff_32(&mut self, wt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 4) & 0x0fff;
|
||||
self.emit(0xb9000000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (wt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// LDR (64-bit register offset): LDR Xt, [Xn, Xm]
|
||||
pub fn ldr_reg_64(&mut self, xt: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xf8606800
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// STR (64-bit register offset): STR Xt, [Xn, Xm]
|
||||
pub fn str_reg_64(&mut self, xt: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xf8206800
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// STP (64-bit pre-index): STP Xt1, Xt2, [Xn, #imm7]!
|
||||
pub fn stp_pre_64(&mut self, xt1: u8, xt2: u8, xn: u8, offset_bytes: i32) {
|
||||
debug_assert_eq!(
|
||||
offset_bytes % 8,
|
||||
0,
|
||||
"STP pre-index offset must be 8-byte aligned"
|
||||
);
|
||||
debug_assert!(
|
||||
(-512..=504).contains(&offset_bytes),
|
||||
"STP pre-index offset out of imm7 range"
|
||||
);
|
||||
let imm7 = ((offset_bytes / 8) as u32) & 0x7f;
|
||||
self.emit(
|
||||
0xa9800000
|
||||
| (imm7 << 15)
|
||||
| ((xt2 as u32 & 0x1f) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt1 as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// LDP (64-bit post-index): LDP Xt1, Xt2, [Xn], #imm7
|
||||
pub fn ldp_post_64(&mut self, xt1: u8, xt2: u8, xn: u8, offset_bytes: i32) {
|
||||
debug_assert_eq!(
|
||||
offset_bytes % 8,
|
||||
0,
|
||||
"LDP post-index offset must be 8-byte aligned"
|
||||
);
|
||||
debug_assert!(
|
||||
(-512..=504).contains(&offset_bytes),
|
||||
"LDP post-index offset out of imm7 range"
|
||||
);
|
||||
let imm7 = ((offset_bytes / 8) as u32) & 0x7f;
|
||||
self.emit(
|
||||
0xa8c00000
|
||||
| (imm7 << 15)
|
||||
| ((xt2 as u32 & 0x1f) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt1 as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// MRS Xt, NZCV (Read flags into register)
|
||||
pub fn mrs_nzcv(&mut self, xt: u8) {
|
||||
self.emit(0xd53b4200 | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// MSR NZCV, Xt (Write flags from register)
|
||||
pub fn msr_nzcv(&mut self, xt: u8) {
|
||||
self.emit(0xd51b4200 | (xt as u32 & 0x1f));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frame_pair_encodings_cover_every_used_offset() {
|
||||
// Cross-checked against the architectural encodings:
|
||||
// stp x29, x30, [sp, #-16]! == 0xa9bf7bfd
|
||||
// ldp x29, x30, [sp], #16 == 0xa8c17bfd
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.stp_pre_64(X29, X30, SP, -16);
|
||||
asm.ldp_post_64(X29, X30, SP, 16);
|
||||
asm.stp_pre_64(X29, X30, SP, -32);
|
||||
asm.ldp_post_64(X29, X30, SP, 32);
|
||||
asm.stp_pre_64(X29, X30, SP, -48);
|
||||
asm.ldp_post_64(X29, X30, SP, 48);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[
|
||||
0xa9bf7bfd, 0xa8c17bfd, 0xa9be7bfd, 0xa8c27bfd, 0xa9bd7bfd, 0xa8c37bfd,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stp_pre_64_respects_the_requested_frame_size() {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.stp_pre_64(X19, X20, SP, -64);
|
||||
assert_eq!(asm.instructions()[0], 0xa9bc53f3);
|
||||
asm.stp_pre_64(X19, X20, SP, 496);
|
||||
assert_eq!(asm.instructions()[1], 0xa99f53f3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alu_and_memory_encodings_match_llvm_mc() {
|
||||
// Golden words produced by llvm-mc 23.1.6 for the same instructions.
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.add_reg_64(X9, X9, X10);
|
||||
asm.sub_reg_64(X9, X9, X10);
|
||||
asm.and_reg_64(X9, X9, X10);
|
||||
asm.orr_reg_64(X19, XZR, X0);
|
||||
asm.eor_reg_64(X9, X9, X10);
|
||||
asm.add_imm_64(X1, X1, 8);
|
||||
asm.sub_imm_64(X1, X1, 8);
|
||||
asm.movz_64(X9, 0x1234, 0);
|
||||
asm.movk_64(X9, 0xabcd, 2);
|
||||
asm.ldr_uoff_64(X9, X19, 128);
|
||||
asm.str_uoff_64(X21, SP, 32);
|
||||
asm.ldr_uoff_32(X0, X19, 136);
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
asm.ldr_reg_64(X9, X19, X10);
|
||||
asm.str_reg_64(X9, X19, X10);
|
||||
asm.mrs_nzcv(X9);
|
||||
asm.msr_nzcv(X9);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[
|
||||
0x8b0a0129, 0xcb0a0129, 0x8a0a0129, 0xaa0003f3, 0xca0a0129, 0x91002021, 0xd1002021,
|
||||
0xd2824689, 0xf2d579a9, 0xf9404269, 0xf90013f5, 0xb9408a60, 0xb9008a60, 0xf86a6a69,
|
||||
0xf82a6a69, 0xd53b4209, 0xd51b4209,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_branch_encodings_match_the_assembler() {
|
||||
// llvm-mc -triple=aarch64: cbz x5, #28 -> b40000e5;
|
||||
// cbnz x9, #-8 -> b5ffffc9; b #20 -> 14000005.
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.cbz_64(X5, 7);
|
||||
asm.cbnz_64(X9, -2);
|
||||
assert_eq!(asm.instructions(), &[0xb40000e5, 0xb5ffffc9]);
|
||||
asm.patch_cbz_64(0, X5, 1);
|
||||
assert_eq!(asm.instructions()[0], 0xb4000025);
|
||||
let mut branch = Arm64Assembler::new();
|
||||
branch.b(0);
|
||||
branch.patch_b(0, 5);
|
||||
assert_eq!(branch.instructions()[0], 0x14000005);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_offset_stores_scale_by_access_size() {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.str_uoff_64(X21, SP, 32);
|
||||
asm.ldr_uoff_64(X9, X19, 128);
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
|
||||
}
|
||||
}
|
||||
@@ -1,708 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Minimal x86-64 guest CPU register state and bounded instruction interpreter.
|
||||
//!
|
||||
//! Executes real x86-64 opcodes in software against isolated `GuestMemory`.
|
||||
//! Never executes guest x86-64 code natively on host ARM64.
|
||||
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use std::fmt;
|
||||
|
||||
/// 64-bit General Purpose Register identifiers in x86-64.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Register {
|
||||
Rax = 0,
|
||||
Rcx = 1,
|
||||
Rdx = 2,
|
||||
Rbx = 3,
|
||||
Rsp = 4,
|
||||
Rbp = 5,
|
||||
Rsi = 6,
|
||||
Rdi = 7,
|
||||
R8 = 8,
|
||||
R9 = 9,
|
||||
R10 = 10,
|
||||
R11 = 11,
|
||||
R12 = 12,
|
||||
R13 = 13,
|
||||
R14 = 14,
|
||||
R15 = 15,
|
||||
}
|
||||
|
||||
impl Register {
|
||||
pub fn from_index(index: u8) -> Self {
|
||||
match index & 0xF {
|
||||
0 => Self::Rax,
|
||||
1 => Self::Rcx,
|
||||
2 => Self::Rdx,
|
||||
3 => Self::Rbx,
|
||||
4 => Self::Rsp,
|
||||
5 => Self::Rbp,
|
||||
6 => Self::Rsi,
|
||||
7 => Self::Rdi,
|
||||
8 => Self::R8,
|
||||
9 => Self::R9,
|
||||
10 => Self::R10,
|
||||
11 => Self::R11,
|
||||
12 => Self::R12,
|
||||
13 => Self::R13,
|
||||
14 => Self::R14,
|
||||
15 => Self::R15,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RFLAGS status bits tracked during guest execution.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RFlags {
|
||||
pub cf: bool, // Carry flag
|
||||
pub zf: bool, // Zero flag
|
||||
pub sf: bool, // Sign flag
|
||||
pub of: bool, // Overflow flag
|
||||
}
|
||||
|
||||
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CpuState {
|
||||
pub gpr: [u64; 16],
|
||||
pub rip: u64,
|
||||
pub flags: RFlags,
|
||||
pub gs_base: u64,
|
||||
pub fs_base: u64,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
pub fn new(entry_point: u64, stack_pointer: u64) -> Self {
|
||||
let mut gpr = [0u64; 16];
|
||||
gpr[Register::Rsp as usize] = stack_pointer;
|
||||
Self {
|
||||
gpr,
|
||||
rip: entry_point,
|
||||
flags: RFlags::default(),
|
||||
gs_base: 0,
|
||||
fs_base: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, reg: Register) -> u64 {
|
||||
self.gpr[reg as usize]
|
||||
}
|
||||
|
||||
pub fn set(&mut self, reg: Register, val: u64) {
|
||||
self.gpr[reg as usize] = val;
|
||||
}
|
||||
}
|
||||
|
||||
/// Termination reason for guest execution.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ExitReason {
|
||||
Halt,
|
||||
Syscall(u64),
|
||||
StepLimitExceeded,
|
||||
JitCacheExhausted,
|
||||
MemoryFault(MemoryError),
|
||||
IllegalInstruction(u8),
|
||||
StackUnderflow,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExitReason {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Halt => write!(f, "guest executed HLT"),
|
||||
Self::Syscall(nr) => write!(f, "guest executed SYSCALL ({nr})"),
|
||||
Self::StepLimitExceeded => write!(f, "execution step budget exhausted"),
|
||||
Self::JitCacheExhausted => write!(f, "native JIT code cache exhausted"),
|
||||
Self::MemoryFault(e) => write!(f, "memory fault: {e}"),
|
||||
Self::IllegalInstruction(op) => write!(f, "illegal or unsupported opcode: 0x{op:02x}"),
|
||||
Self::StackUnderflow => write!(f, "stack underflow"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ExitReason {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod layout_tests {
|
||||
use super::{CpuState, RFlags, Register};
|
||||
|
||||
/// The native translator addresses guest registers and RIP by raw byte
|
||||
/// offset. Keep these assertions next to the struct so a layout change
|
||||
/// cannot silently corrupt translated blocks.
|
||||
#[test]
|
||||
fn native_translator_offsets_match_repr_c_layout() {
|
||||
assert_eq!(std::mem::offset_of!(CpuState, gpr), 0);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, rip), 16 * 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, flags), 16 * 8 + 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, gs_base), 16 * 8 + 8 + 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, fs_base), 16 * 8 + 8 + 8 + 8);
|
||||
assert_eq!(std::mem::size_of::<RFlags>(), 4);
|
||||
assert_eq!(std::mem::size_of::<CpuState>(), 16 * 8 + 8 + 8 + 8 + 8);
|
||||
|
||||
let cpu = CpuState::default();
|
||||
let base = std::ptr::addr_of!(cpu) as usize;
|
||||
for reg in [Register::Rax, Register::Rsp, Register::R15] {
|
||||
assert_eq!(
|
||||
base + (reg as usize) * 8,
|
||||
std::ptr::addr_of!(cpu.gpr[reg as usize]) as usize
|
||||
);
|
||||
}
|
||||
assert_eq!(base + 16 * 8, std::ptr::addr_of!(cpu.rip) as usize);
|
||||
assert_eq!(base + 16 * 8 + 8, std::ptr::addr_of!(cpu.flags) as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// Result returned after running guest execution.
|
||||
#[derive(Debug)]
|
||||
pub struct ExecutionResult {
|
||||
pub instructions_executed: usize,
|
||||
pub final_state: CpuState,
|
||||
pub exit_reason: ExitReason,
|
||||
}
|
||||
|
||||
/// Bounded software interpreter for x86-64 instructions.
|
||||
pub struct Interpreter<'a> {
|
||||
pub cpu: CpuState,
|
||||
pub memory: &'a mut GuestMemory,
|
||||
pub max_instructions: usize,
|
||||
pub instructions_executed: usize,
|
||||
}
|
||||
|
||||
impl<'a> Interpreter<'a> {
|
||||
pub fn new(cpu: CpuState, memory: &'a mut GuestMemory, max_instructions: usize) -> Self {
|
||||
Self {
|
||||
cpu,
|
||||
memory,
|
||||
max_instructions,
|
||||
instructions_executed: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run interpreter until halt, error, or instruction budget limit.
|
||||
pub fn run(&mut self) -> ExecutionResult {
|
||||
while self.instructions_executed < self.max_instructions {
|
||||
match self.step() {
|
||||
Ok(None) => {
|
||||
self.instructions_executed += 1;
|
||||
}
|
||||
Ok(Some(reason)) => {
|
||||
self.instructions_executed += 1;
|
||||
return ExecutionResult {
|
||||
instructions_executed: self.instructions_executed,
|
||||
final_state: self.cpu.clone(),
|
||||
exit_reason: reason,
|
||||
};
|
||||
}
|
||||
Err(reason) => {
|
||||
return ExecutionResult {
|
||||
instructions_executed: self.instructions_executed,
|
||||
final_state: self.cpu.clone(),
|
||||
exit_reason: reason,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ExecutionResult {
|
||||
instructions_executed: self.instructions_executed,
|
||||
final_state: self.cpu.clone(),
|
||||
exit_reason: ExitReason::StepLimitExceeded,
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch_u8(&mut self) -> Result<u8, ExitReason> {
|
||||
let b = self
|
||||
.memory
|
||||
.fetch_instruction_byte(self.cpu.rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.rip += 1;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
fn fetch_u32(&mut self) -> Result<u32, ExitReason> {
|
||||
let mut bytes = [0u8; 4];
|
||||
for b in &mut bytes {
|
||||
*b = self.fetch_u8()?;
|
||||
}
|
||||
Ok(u32::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
fn fetch_u64(&mut self) -> Result<u64, ExitReason> {
|
||||
let mut bytes = [0u8; 8];
|
||||
for b in &mut bytes {
|
||||
*b = self.fetch_u8()?;
|
||||
}
|
||||
Ok(u64::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
fn fetch_i8(&mut self) -> Result<i8, ExitReason> {
|
||||
Ok(self.fetch_u8()? as i8)
|
||||
}
|
||||
|
||||
fn fetch_i32(&mut self) -> Result<i32, ExitReason> {
|
||||
Ok(self.fetch_u32()? as i32)
|
||||
}
|
||||
|
||||
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL).
|
||||
pub fn step(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mut rex_w = false;
|
||||
let mut rex_r = false;
|
||||
let mut rex_b = false;
|
||||
let mut seg_gs = false;
|
||||
let mut seg_fs = false;
|
||||
|
||||
let mut byte = self.fetch_u8()?;
|
||||
|
||||
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
|
||||
while byte == 0x65 || byte == 0x64 {
|
||||
if byte == 0x65 {
|
||||
seg_gs = true;
|
||||
} else {
|
||||
seg_fs = true;
|
||||
}
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
// Handle REX prefix (0x40 - 0x4F)
|
||||
if (byte & 0xF0) == 0x40 {
|
||||
rex_w = (byte & 0x08) != 0;
|
||||
rex_r = (byte & 0x04) != 0;
|
||||
rex_b = (byte & 0x01) != 0;
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
match byte {
|
||||
// HLT: Halt execution
|
||||
0xF4 => Ok(Some(ExitReason::Halt)),
|
||||
|
||||
// SYSCALL: 0x0F 0x05
|
||||
0x0F => {
|
||||
let second = self.fetch_u8()?;
|
||||
if second == 0x05 {
|
||||
let syscall_num = self.cpu.get(Register::Rax);
|
||||
Ok(Some(ExitReason::Syscall(syscall_num)))
|
||||
} else {
|
||||
Err(ExitReason::IllegalInstruction(second))
|
||||
}
|
||||
}
|
||||
|
||||
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
|
||||
0xB8..=0xBF => {
|
||||
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
if rex_w {
|
||||
let imm = self.fetch_u64()?;
|
||||
self.cpu.set(reg, imm);
|
||||
} else {
|
||||
let imm = self.fetch_u32()? as u64; // Zero-extended in x86-64
|
||||
self.cpu.set(reg, imm);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
|
||||
0x31 | 0x33 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let res = if rex_w {
|
||||
val1 ^ val2
|
||||
} else {
|
||||
(val1 as u32 ^ val2 as u32) as u64
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.update_flags_logic(res, rex_w);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
|
||||
0x01 | 0x03 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
add64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = add32(val1 as u32, val2 as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.cpu.flags = flags;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
|
||||
0x29 | 0x2B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
sub64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = sub32(val1 as u32, val2 as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.cpu.flags = flags;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
|
||||
0x39 | 0x3B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (v1, v2) = if byte == 0x39 {
|
||||
(self.cpu.get(rm), self.cpu.get(reg))
|
||||
} else {
|
||||
(self.cpu.get(reg), self.cpu.get(rm))
|
||||
};
|
||||
let (_, flags) = if rex_w {
|
||||
sub64(v1, v2)
|
||||
} else {
|
||||
let (r, f) = sub32(v1 as u32, v2 as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.flags = flags;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// Immediate group 1: 0x83 /op reg, imm8
|
||||
0x83 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let op = (modrm >> 3) & 7;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let imm8 = self.fetch_i8()? as i64;
|
||||
let imm = imm8 as u64;
|
||||
|
||||
let val = self.cpu.get(rm);
|
||||
match op {
|
||||
0 => {
|
||||
// ADD
|
||||
let (res, flags) = if rex_w {
|
||||
add64(val, imm)
|
||||
} else {
|
||||
let (r, f) = add32(val as u32, imm as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(rm, res);
|
||||
self.cpu.flags = flags;
|
||||
}
|
||||
5 => {
|
||||
// SUB
|
||||
let (res, flags) = if rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(rm, res);
|
||||
self.cpu.flags = flags;
|
||||
}
|
||||
7 => {
|
||||
// CMP
|
||||
let (_, flags) = if rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.flags = flags;
|
||||
}
|
||||
_ => return Err(ExitReason::IllegalInstruction(byte)),
|
||||
}
|
||||
let _ = reg;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
|
||||
0x89 | 0x8B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
|
||||
}
|
||||
|
||||
// JMP rel8 (0xEB)
|
||||
0xEB => {
|
||||
let offset = self.fetch_i8()? as i64;
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// JMP rel32 (0xE9)
|
||||
0xE9 => {
|
||||
let offset = self.fetch_i32()? as i64;
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// JZ/JE rel8 (0x74)
|
||||
0x74 => {
|
||||
let offset = self.fetch_i8()? as i64;
|
||||
if self.cpu.flags.zf {
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// JNZ/JNE rel8 (0x75)
|
||||
0x75 => {
|
||||
let offset = self.fetch_i8()? as i64;
|
||||
if !self.cpu.flags.zf {
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// CALL rel32 (0xE8)
|
||||
0xE8 => {
|
||||
let offset = self.fetch_i32()? as i64;
|
||||
let target = (self.cpu.rip as i64 + offset) as u64;
|
||||
let ret_addr = self.cpu.rip;
|
||||
self.push_u64(ret_addr)?;
|
||||
self.cpu.rip = target;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// RET (0xC3)
|
||||
0xC3 => {
|
||||
let ret_addr = self.pop_u64()?;
|
||||
self.cpu.rip = ret_addr;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// PUSH reg (0x50..=0x57)
|
||||
0x50..=0x57 => {
|
||||
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.cpu.get(reg);
|
||||
self.push_u64(val)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// POP reg (0x58..=0x5F)
|
||||
0x58..=0x5F => {
|
||||
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.pop_u64()?;
|
||||
self.cpu.set(reg, val);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
_ => Err(ExitReason::IllegalInstruction(byte)),
|
||||
}
|
||||
}
|
||||
|
||||
fn push_u64(&mut self, val: u64) -> Result<(), ExitReason> {
|
||||
let sp = self.cpu.get(Register::Rsp);
|
||||
let new_sp = sp.checked_sub(8).ok_or(ExitReason::StackUnderflow)?;
|
||||
self.memory
|
||||
.write_u64(new_sp, val)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(Register::Rsp, new_sp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pop_u64(&mut self) -> Result<u64, ExitReason> {
|
||||
let sp = self.cpu.get(Register::Rsp);
|
||||
let val = self.memory.read_u64(sp).map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(Register::Rsp, sp + 8);
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
fn decode_modrm_reg_reg(
|
||||
&self,
|
||||
modrm: u8,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
) -> Result<(Register, Register), ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(modrm));
|
||||
}
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn execute_mov_rm(
|
||||
&mut self,
|
||||
modrm: u8,
|
||||
rex_w: bool,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
is_load: bool,
|
||||
seg_gs: bool,
|
||||
seg_fs: bool,
|
||||
) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
|
||||
if mode == 3 {
|
||||
// Register-to-register move
|
||||
let rm = Register::from_index(rm_idx);
|
||||
if is_load {
|
||||
let val = self.cpu.get(rm);
|
||||
self.cpu
|
||||
.set(reg, if rex_w { val } else { val as u32 as u64 });
|
||||
} else {
|
||||
let val = self.cpu.get(reg);
|
||||
self.cpu
|
||||
.set(rm, if rex_w { val } else { val as u32 as u64 });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Memory operand [rm + disp] or SIB
|
||||
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
|
||||
// SIB byte follows ModR/M
|
||||
let sib = self.fetch_u8()?;
|
||||
let scale_shift = (sib >> 6) & 3;
|
||||
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
|
||||
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
|
||||
|
||||
let base_v = if mode == 0 && (sib & 7) == 5 {
|
||||
// disp32 with no base register
|
||||
0u64
|
||||
} else {
|
||||
self.cpu.get(Register::from_index(base_raw))
|
||||
};
|
||||
|
||||
let index_v = if (sib >> 3) & 7 == 4 {
|
||||
// index == 4 means no index register (ESP/RSP)
|
||||
0u64
|
||||
} else {
|
||||
self.cpu.get(Register::from_index(index_raw)) << scale_shift
|
||||
};
|
||||
|
||||
let d: i64 = match mode {
|
||||
0 => {
|
||||
if (sib & 7) == 5 {
|
||||
self.fetch_i32()? as i64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
1 => self.fetch_i8()? as i64,
|
||||
2 => self.fetch_i32()? as i64,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
(base_v.wrapping_add(index_v), d)
|
||||
} else {
|
||||
let base_reg = Register::from_index(rm_idx);
|
||||
let base_val = self.cpu.get(base_reg);
|
||||
|
||||
let disp: i64 = match mode {
|
||||
0 => {
|
||||
if (rm_idx & 7) == 5 {
|
||||
// RIP-relative displacement disp32
|
||||
self.fetch_i32()? as i64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
1 => self.fetch_i8()? as i64,
|
||||
2 => self.fetch_i32()? as i64,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
(base_val, disp)
|
||||
};
|
||||
|
||||
let mut effective_addr = if mode == 0 && (rm_idx & 7) == 5 {
|
||||
(self.cpu.rip as i64 + disp) as u64
|
||||
} else {
|
||||
(base_val as i64 + disp) as u64
|
||||
};
|
||||
|
||||
if seg_gs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
|
||||
} else if seg_fs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
|
||||
}
|
||||
|
||||
if is_load {
|
||||
// Load from memory to reg
|
||||
if rex_w {
|
||||
let val = self
|
||||
.memory
|
||||
.read_u64(effective_addr)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(reg, val);
|
||||
} else {
|
||||
let val = self
|
||||
.memory
|
||||
.read_u32(effective_addr)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(reg, val as u64);
|
||||
}
|
||||
} else {
|
||||
// Store from reg to memory
|
||||
let val = self.cpu.get(reg);
|
||||
if rex_w {
|
||||
self.memory
|
||||
.write_u64(effective_addr, val)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
} else {
|
||||
self.memory
|
||||
.write_u32(effective_addr, val as u32)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn update_flags_logic(&mut self, val: u64, is_64: bool) {
|
||||
self.cpu.flags.cf = false;
|
||||
self.cpu.flags.of = false;
|
||||
if is_64 {
|
||||
self.cpu.flags.zf = val == 0;
|
||||
self.cpu.flags.sf = (val as i64) < 0;
|
||||
} else {
|
||||
let val32 = val as u32;
|
||||
self.cpu.flags.zf = val32 == 0;
|
||||
self.cpu.flags.sf = (val32 as i32) < 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add64(a: u64, b: u64) -> (u64, RFlags) {
|
||||
let (res, cf) = a.overflowing_add(b);
|
||||
let of = ((a ^ res) & (b ^ res) & 0x8000_0000_0000_0000) != 0;
|
||||
let sf = (res as i64) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
}
|
||||
|
||||
fn add32(a: u32, b: u32) -> (u32, RFlags) {
|
||||
let (res, cf) = a.overflowing_add(b);
|
||||
let of = ((a ^ res) & (b ^ res) & 0x8000_0000) != 0;
|
||||
let sf = (res as i32) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
}
|
||||
|
||||
fn sub64(a: u64, b: u64) -> (u64, RFlags) {
|
||||
let (res, cf) = a.overflowing_sub(b);
|
||||
let of = ((a ^ b) & (a ^ res) & 0x8000_0000_0000_0000) != 0;
|
||||
let sf = (res as i64) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
}
|
||||
|
||||
fn sub32(a: u32, b: u32) -> (u32, RFlags) {
|
||||
let (res, cf) = a.overflowing_sub(b);
|
||||
let of = ((a ^ b) & (a ^ res) & 0x8000_0000) != 0;
|
||||
let sf = (res as i32) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,819 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest-facing D3D12-style Graphics Runtime Interfaces for Xenora.
|
||||
//!
|
||||
//! Provides typed guest graphics objects, handle management, resource validation,
|
||||
//! command recording, and backend execution dispatch.
|
||||
//!
|
||||
//! Architecturally maps guest concepts:
|
||||
//! - Guest Device (`ID3D12Device` / test device) -> `GraphicsDevice`
|
||||
//! - Guest Command Queue (`ID3D12CommandQueue`) -> `GraphicsCommandQueue`
|
||||
//! - Guest Command Allocator (`ID3D12CommandAllocator`) -> `GraphicsCommandAllocator`
|
||||
//! - Guest Command List (`ID3D12GraphicsCommandList`) -> `GraphicsCommandList`
|
||||
//! - Guest Resource (Buffer/Texture) -> `GraphicsResource`
|
||||
//! - Guest Swap Chain / Present -> Frame presentation & framebuffer readback.
|
||||
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Generation-checked opaque guest graphics handle.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct GraphicsHandle {
|
||||
pub id: u32,
|
||||
pub generation: u32,
|
||||
}
|
||||
|
||||
impl GraphicsHandle {
|
||||
pub const NULL: Self = Self {
|
||||
id: 0,
|
||||
generation: 0,
|
||||
};
|
||||
|
||||
pub fn to_u64(self) -> u64 {
|
||||
((self.generation as u64) << 32) | (self.id as u64)
|
||||
}
|
||||
|
||||
pub fn from_u64(val: u64) -> Self {
|
||||
Self {
|
||||
id: val as u32,
|
||||
generation: (val >> 32) as u32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// D3D12 Command List Type.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CommandListType {
|
||||
Direct = 0,
|
||||
Bundle = 1,
|
||||
Compute = 2,
|
||||
Copy = 3,
|
||||
}
|
||||
|
||||
/// D3D12 Resource Dimension.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ResourceDimension {
|
||||
Unknown = 0,
|
||||
Buffer = 1,
|
||||
Texture1D = 2,
|
||||
Texture2D = 3,
|
||||
Texture3D = 4,
|
||||
}
|
||||
|
||||
/// D3D12 Resource State flags.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceStates(pub u32);
|
||||
|
||||
impl ResourceStates {
|
||||
pub const COMMON: Self = Self(0);
|
||||
pub const VERTEX_AND_CONSTANT_BUFFER: Self = Self(0x1);
|
||||
pub const INDEX_BUFFER: Self = Self(0x2);
|
||||
pub const RENDER_TARGET: Self = Self(0x4);
|
||||
pub const UNORDERED_ACCESS: Self = Self(0x8);
|
||||
pub const DEPTH_WRITE: Self = Self(0x10);
|
||||
pub const DEPTH_READ: Self = Self(0x20);
|
||||
pub const NON_PIXEL_SHADER_RESOURCE: Self = Self(0x40);
|
||||
pub const PIXEL_SHADER_RESOURCE: Self = Self(0x80);
|
||||
pub const COPY_DEST: Self = Self(0x400);
|
||||
pub const COPY_SOURCE: Self = Self(0x800);
|
||||
pub const PRESENT: Self = Self(0);
|
||||
}
|
||||
|
||||
/// Identity of the graphics execution backend.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GraphicsBackendId {
|
||||
/// Deterministic software reference rasterizer (strictly for tests/CI without Metal).
|
||||
SoftwareReference,
|
||||
/// Native Apple Silicon Metal GPU rendering pipeline.
|
||||
MetalNative,
|
||||
}
|
||||
|
||||
/// Explicit result of graphics command execution.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ExecutionOutcome {
|
||||
pub backend: GraphicsBackendId,
|
||||
pub pixels: Vec<u8>,
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub draw_count: usize,
|
||||
}
|
||||
|
||||
/// Typed error for graphics operations.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphicsError {
|
||||
InvalidDeviceHandle,
|
||||
InvalidQueueHandle,
|
||||
InvalidAllocatorHandle,
|
||||
InvalidCommandListHandle,
|
||||
InvalidResourceHandle,
|
||||
ResourceLifetimeViolation,
|
||||
CommandListNotRecording,
|
||||
CommandListAlreadyClosed,
|
||||
EmptyCommandList,
|
||||
InvalidDescriptor,
|
||||
InvalidViewport,
|
||||
Memory(MemoryError),
|
||||
DeviceCreationFailure(String),
|
||||
BackendError(String),
|
||||
NativeMetalRequired,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for GraphicsError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::InvalidDeviceHandle => write!(f, "invalid or stale graphics device handle"),
|
||||
Self::InvalidQueueHandle => write!(f, "invalid or stale command queue handle"),
|
||||
Self::InvalidAllocatorHandle => write!(f, "invalid or stale command allocator handle"),
|
||||
Self::InvalidCommandListHandle => write!(f, "invalid or stale command list handle"),
|
||||
Self::InvalidResourceHandle => write!(f, "invalid or stale graphics resource handle"),
|
||||
Self::ResourceLifetimeViolation => write!(f, "graphics resource lifetime violation"),
|
||||
Self::CommandListNotRecording => write!(f, "command list is not in recording state"),
|
||||
Self::CommandListAlreadyClosed => write!(f, "command list has already been closed"),
|
||||
Self::EmptyCommandList => write!(f, "attempted to submit an empty command list"),
|
||||
Self::InvalidDescriptor => write!(f, "invalid descriptor or descriptor range"),
|
||||
Self::InvalidViewport => write!(f, "invalid viewport extent or bounds"),
|
||||
Self::Memory(e) => write!(f, "guest memory error: {e}"),
|
||||
Self::DeviceCreationFailure(msg) => write!(f, "device creation failure: {msg}"),
|
||||
Self::BackendError(msg) => write!(f, "metal backend error: {msg}"),
|
||||
Self::NativeMetalRequired => write!(
|
||||
f,
|
||||
"native Metal backend required but not provided or failed"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for GraphicsError {}
|
||||
|
||||
impl From<MemoryError> for GraphicsError {
|
||||
fn from(e: MemoryError) -> Self {
|
||||
Self::Memory(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resource description for buffer/texture creation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ResourceDesc {
|
||||
pub dimension: ResourceDimension,
|
||||
pub width: u64,
|
||||
pub height: u32,
|
||||
pub depth_or_array_size: u16,
|
||||
pub mip_levels: u16,
|
||||
pub format_rgba8: bool,
|
||||
}
|
||||
|
||||
/// Guest Graphics Resource.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphicsResource {
|
||||
pub handle: GraphicsHandle,
|
||||
pub desc: ResourceDesc,
|
||||
pub state: ResourceStates,
|
||||
pub guest_backing_addr: Option<u64>,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Primitive Draw Command recorded in a Command List.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphicsCommand {
|
||||
ResourceBarrier {
|
||||
resource: GraphicsHandle,
|
||||
before: ResourceStates,
|
||||
after: ResourceStates,
|
||||
},
|
||||
SetRenderTargets {
|
||||
color_target: Option<GraphicsHandle>,
|
||||
clear_color: [u8; 4],
|
||||
},
|
||||
SetViewport {
|
||||
width: usize,
|
||||
height: usize,
|
||||
},
|
||||
SetVertexBuffer {
|
||||
resource: GraphicsHandle,
|
||||
offset: usize,
|
||||
stride: usize,
|
||||
},
|
||||
DrawInstanced {
|
||||
vertex_count_per_instance: u32,
|
||||
instance_count: u32,
|
||||
start_vertex_location: u32,
|
||||
start_instance_location: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Command List in recording or closed state.
|
||||
pub struct GraphicsCommandList {
|
||||
pub handle: GraphicsHandle,
|
||||
pub list_type: CommandListType,
|
||||
pub is_recording: bool,
|
||||
pub commands: Vec<GraphicsCommand>,
|
||||
}
|
||||
|
||||
/// Command Allocator tracking command recording buffers.
|
||||
pub struct GraphicsCommandAllocator {
|
||||
pub handle: GraphicsHandle,
|
||||
pub list_type: CommandListType,
|
||||
pub is_reset: bool,
|
||||
}
|
||||
|
||||
/// Command Queue for command list submission and execution.
|
||||
pub struct GraphicsCommandQueue {
|
||||
pub handle: GraphicsHandle,
|
||||
pub list_type: CommandListType,
|
||||
pub submitted_lists: Vec<GraphicsHandle>,
|
||||
}
|
||||
|
||||
/// Custom backend renderer signature for testing or Metal dispatch.
|
||||
pub type BackendRenderer<'a> =
|
||||
dyn Fn(&[[f32; 4]; 3], (usize, usize), [u8; 4]) -> Result<Vec<u8>, GraphicsError> + 'a;
|
||||
|
||||
/// Shared thread-safe backend renderer instance.
|
||||
pub type SharedBackendRenderer = Arc<
|
||||
dyn Fn(&[[f32; 4]; 3], (usize, usize), [u8; 4]) -> Result<Vec<u8>, GraphicsError> + Send + Sync,
|
||||
>;
|
||||
|
||||
/// Frame presentation capture holding the last presented frame.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FramePresentation {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub pixels: Vec<u8>,
|
||||
pub frame_index: u64,
|
||||
pub backend: Option<GraphicsBackendId>,
|
||||
}
|
||||
|
||||
/// Central Graphics Context maintaining guest-visible objects and mapping them to Metal.
|
||||
pub struct GraphicsContext {
|
||||
next_id: u32,
|
||||
devices: HashMap<GraphicsHandle, bool>,
|
||||
queues: HashMap<GraphicsHandle, GraphicsCommandQueue>,
|
||||
allocators: HashMap<GraphicsHandle, GraphicsCommandAllocator>,
|
||||
command_lists: HashMap<GraphicsHandle, GraphicsCommandList>,
|
||||
resources: HashMap<GraphicsHandle, GraphicsResource>,
|
||||
pub last_presentation: Arc<Mutex<FramePresentation>>,
|
||||
/// Optional active backend renderer (e.g. Native Metal).
|
||||
backend: Option<SharedBackendRenderer>,
|
||||
backend_id: GraphicsBackendId,
|
||||
}
|
||||
|
||||
impl Default for GraphicsContext {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphicsContext {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
next_id: 1,
|
||||
devices: HashMap::new(),
|
||||
queues: HashMap::new(),
|
||||
allocators: HashMap::new(),
|
||||
command_lists: HashMap::new(),
|
||||
resources: HashMap::new(),
|
||||
last_presentation: Arc::new(Mutex::new(FramePresentation::default())),
|
||||
backend: None,
|
||||
backend_id: GraphicsBackendId::SoftwareReference,
|
||||
}
|
||||
}
|
||||
|
||||
/// Install a native Metal backend adapter.
|
||||
pub fn set_metal_backend<F>(&mut self, renderer: F)
|
||||
where
|
||||
F: Fn(&[[f32; 4]; 3], (usize, usize), [u8; 4]) -> Result<Vec<u8>, GraphicsError>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
self.backend = Some(Arc::new(renderer));
|
||||
self.backend_id = GraphicsBackendId::MetalNative;
|
||||
}
|
||||
|
||||
/// Explicitly configure context to require native Metal without an attached backend.
|
||||
/// Useful for verifying that missing/unsupported Metal devices correctly fail execution.
|
||||
pub fn set_require_metal_without_backend(&mut self) {
|
||||
self.backend = None;
|
||||
self.backend_id = GraphicsBackendId::MetalNative;
|
||||
}
|
||||
|
||||
/// Retrieve the currently configured backend ID.
|
||||
pub fn current_backend_id(&self) -> GraphicsBackendId {
|
||||
self.backend_id
|
||||
}
|
||||
|
||||
fn allocate_handle(&mut self) -> GraphicsHandle {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
GraphicsHandle { id, generation: 1 }
|
||||
}
|
||||
|
||||
/// Create guest graphics device (`D3D12CreateDevice` / test device).
|
||||
pub fn create_device(&mut self) -> Result<GraphicsHandle, GraphicsError> {
|
||||
let handle = self.allocate_handle();
|
||||
self.devices.insert(handle, true);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Create command queue (`ID3D12Device::CreateCommandQueue`).
|
||||
pub fn create_command_queue(
|
||||
&mut self,
|
||||
device: GraphicsHandle,
|
||||
list_type: CommandListType,
|
||||
) -> Result<GraphicsHandle, GraphicsError> {
|
||||
if !self.devices.contains_key(&device) {
|
||||
return Err(GraphicsError::InvalidDeviceHandle);
|
||||
}
|
||||
let handle = self.allocate_handle();
|
||||
self.queues.insert(
|
||||
handle,
|
||||
GraphicsCommandQueue {
|
||||
handle,
|
||||
list_type,
|
||||
submitted_lists: Vec::new(),
|
||||
},
|
||||
);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Create command allocator (`ID3D12Device::CreateCommandAllocator`).
|
||||
pub fn create_command_allocator(
|
||||
&mut self,
|
||||
device: GraphicsHandle,
|
||||
list_type: CommandListType,
|
||||
) -> Result<GraphicsHandle, GraphicsError> {
|
||||
if !self.devices.contains_key(&device) {
|
||||
return Err(GraphicsError::InvalidDeviceHandle);
|
||||
}
|
||||
let handle = self.allocate_handle();
|
||||
self.allocators.insert(
|
||||
handle,
|
||||
GraphicsCommandAllocator {
|
||||
handle,
|
||||
list_type,
|
||||
is_reset: true,
|
||||
},
|
||||
);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Create command list (`ID3D12Device::CreateCommandList`).
|
||||
pub fn create_command_list(
|
||||
&mut self,
|
||||
device: GraphicsHandle,
|
||||
allocator: GraphicsHandle,
|
||||
list_type: CommandListType,
|
||||
) -> Result<GraphicsHandle, GraphicsError> {
|
||||
if !self.devices.contains_key(&device) {
|
||||
return Err(GraphicsError::InvalidDeviceHandle);
|
||||
}
|
||||
let alloc = self
|
||||
.allocators
|
||||
.get(&allocator)
|
||||
.ok_or(GraphicsError::InvalidAllocatorHandle)?;
|
||||
if alloc.list_type != list_type {
|
||||
return Err(GraphicsError::InvalidAllocatorHandle);
|
||||
}
|
||||
|
||||
let handle = self.allocate_handle();
|
||||
self.command_lists.insert(
|
||||
handle,
|
||||
GraphicsCommandList {
|
||||
handle,
|
||||
list_type,
|
||||
is_recording: true,
|
||||
commands: Vec::new(),
|
||||
},
|
||||
);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Create committed resource (Buffer or Texture).
|
||||
pub fn create_committed_resource(
|
||||
&mut self,
|
||||
device: GraphicsHandle,
|
||||
desc: ResourceDesc,
|
||||
initial_state: ResourceStates,
|
||||
guest_addr: Option<u64>,
|
||||
) -> Result<GraphicsHandle, GraphicsError> {
|
||||
if !self.devices.contains_key(&device) {
|
||||
return Err(GraphicsError::InvalidDeviceHandle);
|
||||
}
|
||||
let handle = self.allocate_handle();
|
||||
let size = match desc.dimension {
|
||||
ResourceDimension::Buffer => desc.width as usize,
|
||||
ResourceDimension::Texture2D => (desc.width as usize) * (desc.height as usize) * 4,
|
||||
_ => desc.width as usize,
|
||||
};
|
||||
self.resources.insert(
|
||||
handle,
|
||||
GraphicsResource {
|
||||
handle,
|
||||
desc,
|
||||
state: initial_state,
|
||||
guest_backing_addr: guest_addr,
|
||||
data: vec![0u8; size],
|
||||
},
|
||||
);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Record resource barrier in command list.
|
||||
pub fn cmd_resource_barrier(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
resource: GraphicsHandle,
|
||||
before: ResourceStates,
|
||||
after: ResourceStates,
|
||||
) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
if !self.resources.contains_key(&resource) {
|
||||
return Err(GraphicsError::InvalidResourceHandle);
|
||||
}
|
||||
cmd_list.commands.push(GraphicsCommand::ResourceBarrier {
|
||||
resource,
|
||||
before,
|
||||
after,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record set render targets.
|
||||
pub fn cmd_set_render_targets(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
color_target: Option<GraphicsHandle>,
|
||||
clear_color: [u8; 4],
|
||||
) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
if let Some(target) = color_target
|
||||
&& !self.resources.contains_key(&target)
|
||||
{
|
||||
return Err(GraphicsError::InvalidResourceHandle);
|
||||
}
|
||||
cmd_list.commands.push(GraphicsCommand::SetRenderTargets {
|
||||
color_target,
|
||||
clear_color,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record set viewport.
|
||||
pub fn cmd_set_viewport(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
if width == 0 || height == 0 || width > 4096 || height > 4096 {
|
||||
return Err(GraphicsError::InvalidViewport);
|
||||
}
|
||||
cmd_list
|
||||
.commands
|
||||
.push(GraphicsCommand::SetViewport { width, height });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record set vertex buffer.
|
||||
pub fn cmd_set_vertex_buffer(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
resource: GraphicsHandle,
|
||||
offset: usize,
|
||||
stride: usize,
|
||||
) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
let res = self
|
||||
.resources
|
||||
.get(&resource)
|
||||
.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
if offset + stride > res.data.len() && res.guest_backing_addr.is_none() {
|
||||
return Err(GraphicsError::InvalidDescriptor);
|
||||
}
|
||||
cmd_list.commands.push(GraphicsCommand::SetVertexBuffer {
|
||||
resource,
|
||||
offset,
|
||||
stride,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record draw instanced.
|
||||
pub fn cmd_draw_instanced(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
vertex_count_per_instance: u32,
|
||||
instance_count: u32,
|
||||
start_vertex_location: u32,
|
||||
start_instance_location: u32,
|
||||
) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
cmd_list.commands.push(GraphicsCommand::DrawInstanced {
|
||||
vertex_count_per_instance,
|
||||
instance_count,
|
||||
start_vertex_location,
|
||||
start_instance_location,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close command list.
|
||||
pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> {
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
if !cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListAlreadyClosed);
|
||||
}
|
||||
cmd_list.is_recording = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reset command list with an allocator.
|
||||
pub fn reset_command_list(
|
||||
&mut self,
|
||||
list: GraphicsHandle,
|
||||
allocator: GraphicsHandle,
|
||||
) -> Result<(), GraphicsError> {
|
||||
if !self.allocators.contains_key(&allocator) {
|
||||
return Err(GraphicsError::InvalidAllocatorHandle);
|
||||
}
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get_mut(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
cmd_list.commands.clear();
|
||||
cmd_list.is_recording = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute command list on command queue using the configured backend.
|
||||
pub fn execute_command_list(
|
||||
&mut self,
|
||||
queue: GraphicsHandle,
|
||||
list: GraphicsHandle,
|
||||
memory: &GuestMemory,
|
||||
) -> Result<ExecutionOutcome, GraphicsError> {
|
||||
let backend_closure = self.backend.clone();
|
||||
let backend_id = self.backend_id;
|
||||
let renderer_ref: Option<&BackendRenderer<'_>> = match &backend_closure {
|
||||
Some(arc) => {
|
||||
let r: &BackendRenderer<'_> = arc.as_ref();
|
||||
Some(r)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
self.execute_command_list_internal(queue, list, memory, renderer_ref, backend_id)
|
||||
}
|
||||
|
||||
/// Execute command list strictly using native Metal. Fails with `GraphicsError::NativeMetalRequired`
|
||||
/// if a native Metal backend is not attached.
|
||||
pub fn execute_command_list_native_metal(
|
||||
&mut self,
|
||||
queue: GraphicsHandle,
|
||||
list: GraphicsHandle,
|
||||
memory: &GuestMemory,
|
||||
metal_renderer: &BackendRenderer<'_>,
|
||||
) -> Result<ExecutionOutcome, GraphicsError> {
|
||||
self.execute_command_list_internal(
|
||||
queue,
|
||||
list,
|
||||
memory,
|
||||
Some(metal_renderer),
|
||||
GraphicsBackendId::MetalNative,
|
||||
)
|
||||
}
|
||||
|
||||
/// Internal execution state machine.
|
||||
fn execute_command_list_internal(
|
||||
&mut self,
|
||||
queue: GraphicsHandle,
|
||||
list: GraphicsHandle,
|
||||
memory: &GuestMemory,
|
||||
backend_renderer: Option<&BackendRenderer<'_>>,
|
||||
backend_id: GraphicsBackendId,
|
||||
) -> Result<ExecutionOutcome, GraphicsError> {
|
||||
let cmd_queue = self
|
||||
.queues
|
||||
.get_mut(&queue)
|
||||
.ok_or(GraphicsError::InvalidQueueHandle)?;
|
||||
let cmd_list = self
|
||||
.command_lists
|
||||
.get(&list)
|
||||
.ok_or(GraphicsError::InvalidCommandListHandle)?;
|
||||
|
||||
if cmd_list.is_recording {
|
||||
return Err(GraphicsError::CommandListNotRecording);
|
||||
}
|
||||
if cmd_list.commands.is_empty() {
|
||||
return Err(GraphicsError::EmptyCommandList);
|
||||
}
|
||||
|
||||
cmd_queue.submitted_lists.push(list);
|
||||
|
||||
// State machine parsing recorded commands
|
||||
let mut viewport = (4usize, 3usize);
|
||||
let mut clear_color = [0u8, 0u8, 0u8, 255u8];
|
||||
let mut target_handle: Option<GraphicsHandle> = None;
|
||||
let mut vertex_resource: Option<GraphicsHandle> = None;
|
||||
let mut vertex_offset = 0usize;
|
||||
let mut rendered_output: Option<Vec<u8>> = None;
|
||||
let mut draw_count = 0usize;
|
||||
|
||||
for cmd in &cmd_list.commands {
|
||||
match cmd {
|
||||
GraphicsCommand::ResourceBarrier {
|
||||
resource,
|
||||
before,
|
||||
after,
|
||||
} => {
|
||||
let res = self
|
||||
.resources
|
||||
.get_mut(resource)
|
||||
.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
if res.state != *before && before != &ResourceStates::COMMON {
|
||||
return Err(GraphicsError::ResourceLifetimeViolation);
|
||||
}
|
||||
res.state = *after;
|
||||
}
|
||||
GraphicsCommand::SetRenderTargets {
|
||||
color_target,
|
||||
clear_color: cc,
|
||||
} => {
|
||||
target_handle = *color_target;
|
||||
clear_color = *cc;
|
||||
}
|
||||
GraphicsCommand::SetViewport { width, height } => {
|
||||
viewport = (*width, *height);
|
||||
}
|
||||
GraphicsCommand::SetVertexBuffer {
|
||||
resource, offset, ..
|
||||
} => {
|
||||
vertex_resource = Some(*resource);
|
||||
vertex_offset = *offset;
|
||||
}
|
||||
GraphicsCommand::DrawInstanced {
|
||||
vertex_count_per_instance,
|
||||
..
|
||||
} => {
|
||||
if *vertex_count_per_instance < 3 {
|
||||
continue;
|
||||
}
|
||||
draw_count += 1;
|
||||
let v_res_handle =
|
||||
vertex_resource.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
let v_res = self
|
||||
.resources
|
||||
.get(&v_res_handle)
|
||||
.ok_or(GraphicsError::InvalidResourceHandle)?;
|
||||
|
||||
// Read vertices from guest memory backing or resource data
|
||||
let mut raw_vtx = [0u8; 48]; // 3 * 4 * float32
|
||||
if let Some(guest_addr) = v_res.guest_backing_addr {
|
||||
memory.read_bytes(guest_addr + vertex_offset as u64, &mut raw_vtx)?;
|
||||
} else if v_res.data.len() >= vertex_offset + 48 {
|
||||
raw_vtx.copy_from_slice(&v_res.data[vertex_offset..vertex_offset + 48]);
|
||||
} else {
|
||||
return Err(GraphicsError::InvalidDescriptor);
|
||||
}
|
||||
|
||||
let mut vertices = [[0.0f32; 4]; 3];
|
||||
for (i, row) in vertices.iter_mut().enumerate() {
|
||||
for (j, val) in row.iter_mut().enumerate() {
|
||||
let off = (i * 4 + j) * 4;
|
||||
*val = f32::from_le_bytes(raw_vtx[off..off + 4].try_into().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
let pixels = if let Some(renderer) = backend_renderer {
|
||||
renderer(&vertices, viewport, clear_color)?
|
||||
} else if backend_id == GraphicsBackendId::MetalNative {
|
||||
return Err(GraphicsError::NativeMetalRequired);
|
||||
} else {
|
||||
Self::execute_software_reference_draw(&vertices, viewport, clear_color)?
|
||||
};
|
||||
|
||||
// Update target resource if present
|
||||
if let Some(th) = target_handle
|
||||
&& let Some(target_res) = self.resources.get_mut(&th)
|
||||
&& target_res.data.len() >= pixels.len()
|
||||
{
|
||||
target_res.data[..pixels.len()].copy_from_slice(&pixels);
|
||||
}
|
||||
|
||||
rendered_output = Some(pixels);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let out = rendered_output.unwrap_or_else(|| {
|
||||
let total = viewport.0 * viewport.1;
|
||||
clear_color.repeat(total)
|
||||
});
|
||||
|
||||
// Store into last presentation
|
||||
if let Ok(mut pres) = self.last_presentation.lock() {
|
||||
pres.width = viewport.0;
|
||||
pres.height = viewport.1;
|
||||
pres.pixels = out.clone();
|
||||
pres.frame_index += 1;
|
||||
pres.backend = Some(backend_id);
|
||||
}
|
||||
|
||||
Ok(ExecutionOutcome {
|
||||
backend: backend_id,
|
||||
pixels: out,
|
||||
width: viewport.0,
|
||||
height: viewport.1,
|
||||
draw_count,
|
||||
})
|
||||
}
|
||||
|
||||
/// Software reference rasterizer for deterministic test verification when GPU tests are off.
|
||||
pub fn execute_software_reference_draw(
|
||||
vertices: &[[f32; 4]; 3],
|
||||
viewport: (usize, usize),
|
||||
clear_color: [u8; 4],
|
||||
) -> Result<Vec<u8>, GraphicsError> {
|
||||
let (w, h) = viewport;
|
||||
let mut pixels = clear_color.repeat(w * h);
|
||||
|
||||
// Convert clip-space coordinates to window pixels [0, w-1] x [0, h-1]
|
||||
let p0 = [
|
||||
(vertices[0][0] + 1.0) * 0.5 * w as f32,
|
||||
(1.0 - vertices[0][1]) * 0.5 * h as f32,
|
||||
];
|
||||
let p1 = [
|
||||
(vertices[1][0] + 1.0) * 0.5 * w as f32,
|
||||
(1.0 - vertices[1][1]) * 0.5 * h as f32,
|
||||
];
|
||||
let p2 = [
|
||||
(vertices[2][0] + 1.0) * 0.5 * w as f32,
|
||||
(1.0 - vertices[2][1]) * 0.5 * h as f32,
|
||||
];
|
||||
|
||||
// 2D barycentric edge functions
|
||||
let edge = |a: [f32; 2], b: [f32; 2], c: [f32; 2]| -> f32 {
|
||||
(c[0] - a[0]) * (b[1] - a[1]) - (c[1] - a[1]) * (b[0] - a[0])
|
||||
};
|
||||
|
||||
let area = edge(p0, p1, p2);
|
||||
if area.abs() < 1e-5 {
|
||||
return Ok(pixels);
|
||||
}
|
||||
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let pt = [x as f32 + 0.5, y as f32 + 0.5];
|
||||
let w0 = edge(p1, p2, pt);
|
||||
let w1 = edge(p2, p0, pt);
|
||||
let w2 = edge(p0, p1, pt);
|
||||
|
||||
let inside = if area > 0.0 {
|
||||
w0 >= 0.0 && w1 >= 0.0 && w2 >= 0.0
|
||||
} else {
|
||||
w0 <= 0.0 && w1 <= 0.0 && w2 <= 0.0
|
||||
};
|
||||
|
||||
if inside {
|
||||
let idx = (y * w + x) * 4;
|
||||
pixels[idx..idx + 4].copy_from_slice(&[255, 0, 0, 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(pixels)
|
||||
}
|
||||
}
|
||||
@@ -1,432 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest Import Table Binder and Host Service Dispatch Boundary for Xenora X15.
|
||||
//!
|
||||
//! Maps guest PE IAT (Import Address Table) entries to synthetic dispatch thunks,
|
||||
//! validating the Windows x64 ABI calling convention and dispatching calls to typed
|
||||
//! guest services without exposing raw host function pointers.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// Base virtual address range reserved for synthetic guest import dispatch trampolines.
|
||||
pub const IMPORT_TRAMPOLINE_BASE_VA: u64 = 0x0000_0007_F000_0000;
|
||||
pub const IMPORT_TRAMPOLINE_STRIDE: u64 = 16;
|
||||
|
||||
/// Typed error resulting from import resolution or service dispatch.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ImportError {
|
||||
MalformedDirectory,
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
UnresolvedImport { module: String, symbol: String },
|
||||
Memory(MemoryError),
|
||||
}
|
||||
|
||||
impl fmt::Display for ImportError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MalformedDirectory => write!(f, "malformed PE import directory"),
|
||||
Self::DirectoryOutOfBounds { rva } => {
|
||||
write!(f, "import directory at RVA 0x{rva:08x} is out of bounds")
|
||||
}
|
||||
Self::UnresolvedImport { module, symbol } => {
|
||||
write!(f, "unresolved import dependency: {module}!{symbol}")
|
||||
}
|
||||
Self::Memory(e) => write!(f, "guest memory error binding imports: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ImportError {}
|
||||
|
||||
impl From<MemoryError> for ImportError {
|
||||
fn from(e: MemoryError) -> Self {
|
||||
Self::Memory(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows x64 Calling Convention Argument Extractor.
|
||||
///
|
||||
/// In Microsoft x64 ABI:
|
||||
/// - Arg 0: RCX
|
||||
/// - Arg 1: RDX
|
||||
/// - Arg 2: R8
|
||||
/// - Arg 3: R9
|
||||
/// - Arg 4+: Stack [RSP + 40 + (n-4)*8] (accounting for return address [RSP] and 32-byte shadow space [RSP+8..RSP+40]).
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Win64Args {
|
||||
pub rcx: u64,
|
||||
pub rdx: u64,
|
||||
pub r8: u64,
|
||||
pub r9: u64,
|
||||
pub rsp: u64,
|
||||
}
|
||||
|
||||
impl Win64Args {
|
||||
pub fn new(cpu: &CpuState) -> Self {
|
||||
Self {
|
||||
rcx: cpu.get(Register::Rcx),
|
||||
rdx: cpu.get(Register::Rdx),
|
||||
r8: cpu.get(Register::R8),
|
||||
r9: cpu.get(Register::R9),
|
||||
rsp: cpu.get(Register::Rsp),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get(&self, index: usize, memory: &GuestMemory) -> Result<u64, MemoryError> {
|
||||
match index {
|
||||
0 => Ok(self.rcx),
|
||||
1 => Ok(self.rdx),
|
||||
2 => Ok(self.r8),
|
||||
3 => Ok(self.r9),
|
||||
n => {
|
||||
let stack_offset = 40 + ((n - 4) as u64) * 8;
|
||||
let addr = self
|
||||
.rsp
|
||||
.checked_add(stack_offset)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.read_u64(addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handler for a typed guest service.
|
||||
/// Returns Ok(ret_val) to be placed into RAX, or Err(reason) to halt/fault execution.
|
||||
pub type ServiceHandler = Box<
|
||||
dyn Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason> + Send + Sync,
|
||||
>;
|
||||
|
||||
/// Scope of a registered handler's implementation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ServiceStatus {
|
||||
Implemented,
|
||||
Partial,
|
||||
Stub,
|
||||
}
|
||||
|
||||
impl ServiceStatus {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Implemented => "implemented",
|
||||
Self::Partial => "partial",
|
||||
Self::Stub => "stub",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Registration entry for an imported symbol.
|
||||
pub struct ServiceDescriptor {
|
||||
pub module: String,
|
||||
pub symbol: String,
|
||||
pub handler: ServiceHandler,
|
||||
pub status: ServiceStatus,
|
||||
}
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
services: HashMap<(String, String), usize>, // (module_lowercase, symbol) -> service_index
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
trampoline_to_service: HashMap<u64, usize>, // Trampoline VA -> service_index
|
||||
}
|
||||
|
||||
impl Default for ImportRegistry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ImportRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
services: HashMap::new(),
|
||||
handlers: Vec::new(),
|
||||
trampoline_to_service: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
self.services
|
||||
.get(&(module.to_ascii_lowercase(), symbol.to_owned()))
|
||||
.copied()
|
||||
}
|
||||
|
||||
/// Check whether the exact import key has a binding, including stub handlers.
|
||||
pub fn has_binding(&self, module: &str, symbol: &str) -> bool {
|
||||
self.service_index(module, symbol).is_some()
|
||||
}
|
||||
|
||||
/// Register a host-provided guest service.
|
||||
pub fn register<F>(&mut self, module: &str, symbol: &str, handler: F)
|
||||
where
|
||||
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
let mod_key = module.to_ascii_lowercase();
|
||||
let sym_key = symbol.to_string();
|
||||
let index = self.handlers.len();
|
||||
self.handlers.push(ServiceDescriptor {
|
||||
module: mod_key.clone(),
|
||||
symbol: sym_key.clone(),
|
||||
handler: Box::new(handler),
|
||||
status: ServiceStatus::Implemented,
|
||||
});
|
||||
self.services.insert((mod_key, sym_key), index);
|
||||
}
|
||||
|
||||
/// Describe the canonical binding behind an import without calling it.
|
||||
pub fn binding(&self, module: &str, symbol: &str) -> Option<&ServiceDescriptor> {
|
||||
self.service_index(module, symbol)
|
||||
.map(|index| &self.handlers[index])
|
||||
}
|
||||
|
||||
/// Iterate all canonical registered (module, symbol, status) tuples.
|
||||
///
|
||||
/// Each entry is returned exactly once regardless of how many API-set alias
|
||||
/// keys point at the same underlying handler.
|
||||
pub fn iter_registered(&self) -> impl Iterator<Item = (&str, &str, ServiceStatus)> {
|
||||
self.handlers
|
||||
.iter()
|
||||
.map(|d| (d.module.as_str(), d.symbol.as_str(), d.status))
|
||||
}
|
||||
|
||||
/// Return (alias_module_lowercase, symbol) pairs that resolve to a canonical handler
|
||||
/// in a different module.
|
||||
pub fn iter_aliases(&self) -> impl Iterator<Item = (&str, &str, &str)> {
|
||||
// `services` maps (module_lc, symbol) -> handler_index.
|
||||
// An alias exists when module_lc != handlers[index].module.to_lowercase().
|
||||
self.services.iter().filter_map(|((mod_lc, sym), &idx)| {
|
||||
let canonical_mod = self.handlers[idx].module.to_ascii_lowercase();
|
||||
if *mod_lc != canonical_mod {
|
||||
Some((
|
||||
mod_lc.as_str(),
|
||||
sym.as_str(),
|
||||
self.handlers[idx].module.as_str(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_status(&mut self, module: &str, symbol: &str, status: ServiceStatus) {
|
||||
let index = self
|
||||
.service_index(module, symbol)
|
||||
.expect("registered service");
|
||||
self.handlers[index].status = status;
|
||||
}
|
||||
|
||||
/// Register a service with an explicit implementation status.
|
||||
pub fn register_with_status<F>(
|
||||
&mut self,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
status: ServiceStatus,
|
||||
handler: F,
|
||||
) where
|
||||
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
self.register(module, symbol, handler);
|
||||
self.set_status(module, symbol, status);
|
||||
}
|
||||
|
||||
/// Point an API-set import at an existing handler and its trampoline.
|
||||
pub(crate) fn alias(&mut self, module: &str, target: &str, symbol: &str) {
|
||||
let index = self
|
||||
.service_index(target, symbol)
|
||||
.expect("registered alias target");
|
||||
self.services
|
||||
.insert((module.to_ascii_lowercase(), symbol.to_owned()), index);
|
||||
}
|
||||
|
||||
/// Bind the PE's Import Address Table (IAT) in guest memory to synthetic trampoline VAs.
|
||||
pub fn bind_imports(
|
||||
&mut self,
|
||||
pe: &ParsedPe,
|
||||
bytes: &[u8],
|
||||
loaded_base: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<usize, ImportError> {
|
||||
let import_dir = find_import_directory(bytes)?;
|
||||
let Some((import_rva, import_size)) = import_dir else {
|
||||
return Ok(0);
|
||||
};
|
||||
if import_size == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut desc_file_off = pe
|
||||
.rva_to_file_offset(import_rva)
|
||||
.ok_or(ImportError::DirectoryOutOfBounds { rva: import_rva })?;
|
||||
|
||||
let mut bound_count = 0;
|
||||
|
||||
while desc_file_off + 20 <= bytes.len() {
|
||||
let oft =
|
||||
u32::from_le_bytes(bytes[desc_file_off..desc_file_off + 4].try_into().unwrap());
|
||||
let name_rva = u32::from_le_bytes(
|
||||
bytes[desc_file_off + 12..desc_file_off + 16]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let ft = u32::from_le_bytes(
|
||||
bytes[desc_file_off + 16..desc_file_off + 20]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if oft == 0 && name_rva == 0 && ft == 0 {
|
||||
break;
|
||||
}
|
||||
desc_file_off += 20;
|
||||
|
||||
let mod_name = if let Some(no) = pe.rva_to_file_offset(name_rva) {
|
||||
let mut end = no;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[no..end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN.dll".to_string()
|
||||
};
|
||||
|
||||
let thunk_rva = if oft != 0 { oft } else { ft };
|
||||
let iat_base_rva = ft;
|
||||
|
||||
let Some(mut thunk_off) = pe.rva_to_file_offset(thunk_rva) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let mut idx = 0u32;
|
||||
while thunk_off + 8 <= bytes.len() {
|
||||
let val = u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap());
|
||||
if val == 0 {
|
||||
break;
|
||||
}
|
||||
thunk_off += 8;
|
||||
let iat_rva = iat_base_rva + idx * 8;
|
||||
idx += 1;
|
||||
|
||||
let sym_name = if (val & (1 << 63)) != 0 {
|
||||
format!("Ordinal#{}", val & 0xFFFF)
|
||||
} else {
|
||||
let hint_rva = (val & 0x7FFF_FFFF) as u32;
|
||||
if let Some(ho) = pe.rva_to_file_offset(hint_rva) {
|
||||
let str_start = ho + 2;
|
||||
let mut str_end = str_start;
|
||||
while str_end < bytes.len() && bytes[str_end] != 0 {
|
||||
str_end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN_SYM".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
let Some(service_idx) = self.service_index(&mod_name, &sym_name) else {
|
||||
return Err(ImportError::UnresolvedImport {
|
||||
module: mod_name,
|
||||
symbol: sym_name,
|
||||
});
|
||||
};
|
||||
|
||||
// Assign a deterministic synthetic trampoline VA
|
||||
let trampoline_va =
|
||||
IMPORT_TRAMPOLINE_BASE_VA + (service_idx as u64) * IMPORT_TRAMPOLINE_STRIDE;
|
||||
self.trampoline_to_service
|
||||
.insert(trampoline_va, service_idx);
|
||||
|
||||
// Write trampoline_va into guest IAT entry at (loaded_base + iat_rva)
|
||||
let iat_va = loaded_base + iat_rva as u64;
|
||||
memory.write_u64_bypass(iat_va, trampoline_va)?;
|
||||
bound_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(bound_count)
|
||||
}
|
||||
|
||||
/// Check if target RIP matches a synthetic service trampoline.
|
||||
pub fn is_service_trampoline(&self, rip: u64) -> bool {
|
||||
self.trampoline_to_service.contains_key(&rip)
|
||||
}
|
||||
|
||||
/// Dispatch a service call when guest RIP hits a service trampoline.
|
||||
pub fn dispatch(
|
||||
&self,
|
||||
rip: u64,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<(), ExitReason> {
|
||||
let service_idx = *self
|
||||
.trampoline_to_service
|
||||
.get(&rip)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xFF))?;
|
||||
|
||||
let descriptor = &self.handlers[service_idx];
|
||||
|
||||
// 1. Extract arguments according to Win64 convention
|
||||
let args = Win64Args::new(cpu);
|
||||
|
||||
// 2. Execute service handler
|
||||
let ret_val = (descriptor.handler)(&args, cpu, memory)?;
|
||||
|
||||
// 3. Store return value into RAX
|
||||
cpu.set(Register::Rax, ret_val);
|
||||
|
||||
// 4. Emulate RET instruction: pop return address from guest stack into RIP
|
||||
let rsp = cpu.get(Register::Rsp);
|
||||
let ret_addr = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?;
|
||||
cpu.set(Register::Rsp, rsp + 8);
|
||||
cpu.rip = ret_addr;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn find_import_directory(bytes: &[u8]) -> Result<Option<(u32, u32)>, ImportError> {
|
||||
if bytes.len() < 0x40 {
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
let size_of_opt = u16::from_le_bytes(
|
||||
bytes[coff_offset + 16..coff_offset + 18]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// Import directory is directory index 1 (offset 112 + 1 * 8 = 120 in Optional Header)
|
||||
if size_of_opt < 128 || bytes.len() < opt_offset + 128 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let import_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 120..opt_offset + 124]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let import_size = u32::from_le_bytes(
|
||||
bytes[opt_offset + 124..opt_offset + 128]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if import_rva == 0 || import_size == 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some((import_rva, import_size)))
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! W^X-compliant native executable JIT memory allocator for Apple Silicon.
|
||||
//!
|
||||
//! Uses macOS `MAP_JIT` with `pthread_jit_write_protect_np` and cache invalidation.
|
||||
|
||||
use std::fmt;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn pthread_jit_write_protect_np(enabled: i32);
|
||||
fn sys_dcache_flush(start: *mut libc::c_void, len: usize);
|
||||
fn sys_icache_invalidate(start: *mut libc::c_void, len: usize);
|
||||
}
|
||||
|
||||
/// Errors relating to JIT memory allocation and protection.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum JitError {
|
||||
AllocationFailed(i32),
|
||||
CapacityExceeded,
|
||||
ProtectionFailed,
|
||||
}
|
||||
|
||||
impl fmt::Display for JitError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::AllocationFailed(err) => write!(f, "mmap MAP_JIT failed with errno {err}"),
|
||||
Self::CapacityExceeded => write!(f, "JIT code cache capacity exceeded"),
|
||||
Self::ProtectionFailed => write!(f, "failed to alter JIT memory protection"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for JitError {}
|
||||
|
||||
/// W^X-compliant JIT code buffer on macOS ARM64.
|
||||
pub struct JitMemory {
|
||||
ptr: NonNull<u8>,
|
||||
capacity: usize,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
// JitMemory manages thread-independent JIT code memory (functions can be invoked across threads)
|
||||
unsafe impl Send for JitMemory {}
|
||||
unsafe impl Sync for JitMemory {}
|
||||
|
||||
impl JitMemory {
|
||||
/// Allocate a new JIT memory region using `MAP_JIT`.
|
||||
pub fn new(capacity: usize) -> Result<Self, JitError> {
|
||||
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
|
||||
let aligned_capacity = (capacity + page_size - 1) & !(page_size - 1);
|
||||
|
||||
let ptr = unsafe {
|
||||
libc::mmap(
|
||||
std::ptr::null_mut(),
|
||||
aligned_capacity,
|
||||
libc::PROT_READ | libc::PROT_WRITE | libc::PROT_EXEC,
|
||||
libc::MAP_ANON | libc::MAP_PRIVATE | libc::MAP_JIT,
|
||||
-1,
|
||||
0,
|
||||
)
|
||||
};
|
||||
|
||||
if ptr == libc::MAP_FAILED {
|
||||
let errno = unsafe { *libc::__error() };
|
||||
return Err(JitError::AllocationFailed(errno));
|
||||
}
|
||||
|
||||
// Initialize to executable state by default (write-protected)
|
||||
unsafe {
|
||||
pthread_jit_write_protect_np(1);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
ptr: NonNull::new(ptr as *mut u8).unwrap(),
|
||||
capacity: aligned_capacity,
|
||||
used: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Base pointer of the JIT allocation.
|
||||
pub fn as_ptr(&self) -> *const u8 {
|
||||
self.ptr.as_ptr()
|
||||
}
|
||||
|
||||
/// Total capacity in bytes.
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.capacity
|
||||
}
|
||||
|
||||
/// Currently committed bytes.
|
||||
pub fn used(&self) -> usize {
|
||||
self.used
|
||||
}
|
||||
|
||||
/// Emit an ARM64 machine code block into the JIT memory.
|
||||
///
|
||||
/// Automatically manages `pthread_jit_write_protect_np`, copies bytes,
|
||||
/// flushes data cache and invalidates instruction cache.
|
||||
pub fn emit_block(&mut self, instructions: &[u32]) -> Result<*const u8, JitError> {
|
||||
let bytes_len = instructions.len() * 4;
|
||||
if self.used + bytes_len > self.capacity {
|
||||
return Err(JitError::CapacityExceeded);
|
||||
}
|
||||
|
||||
let emit_offset = self.used;
|
||||
let dst_ptr = unsafe { self.ptr.as_ptr().add(emit_offset) };
|
||||
|
||||
unsafe {
|
||||
// 1. Enable write permission for this thread
|
||||
pthread_jit_write_protect_np(0);
|
||||
|
||||
// 2. Copy machine instructions
|
||||
std::ptr::copy_nonoverlapping(instructions.as_ptr() as *const u8, dst_ptr, bytes_len);
|
||||
|
||||
// 3. Flush D-cache and invalidate I-cache
|
||||
sys_dcache_flush(dst_ptr as *mut libc::c_void, bytes_len);
|
||||
sys_icache_invalidate(dst_ptr as *mut libc::c_void, bytes_len);
|
||||
|
||||
// 4. Restore write-protection (executable only)
|
||||
pthread_jit_write_protect_np(1);
|
||||
}
|
||||
|
||||
self.used += bytes_len;
|
||||
Ok(dst_ptr as *const u8)
|
||||
}
|
||||
|
||||
/// Clear the JIT cache buffer for reuse.
|
||||
pub fn clear(&mut self) {
|
||||
self.used = 0;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for JitMemory {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
libc::munmap(self.ptr.as_ptr() as *mut libc::c_void, self.capacity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Xenora Loader crate.
|
||||
//!
|
||||
//! Provides PE32+ parsing, isolated guest virtual memory, bounded x86-64 CPU
|
||||
//! execution bootstrap, and read-only binary triage.
|
||||
|
||||
pub mod arm64;
|
||||
pub mod cpu;
|
||||
pub mod dbt;
|
||||
pub mod graphics;
|
||||
pub mod imports;
|
||||
pub mod jit;
|
||||
pub mod memory;
|
||||
pub mod pe;
|
||||
pub mod probe;
|
||||
pub mod reloc;
|
||||
pub mod services;
|
||||
pub mod startup;
|
||||
pub mod tls;
|
||||
pub mod triage;
|
||||
|
||||
pub use arm64::Arm64Assembler;
|
||||
pub use cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
pub use dbt::{DbtEngine, DbtMetrics};
|
||||
pub use graphics::{
|
||||
BackendRenderer, CommandListType, ExecutionOutcome, FramePresentation, GraphicsBackendId,
|
||||
GraphicsCommand, GraphicsCommandAllocator, GraphicsCommandList, GraphicsCommandQueue,
|
||||
GraphicsContext, GraphicsError, GraphicsHandle, GraphicsResource, ResourceDesc,
|
||||
ResourceDimension, ResourceStates,
|
||||
};
|
||||
pub use imports::{ImportError, ImportRegistry, ServiceDescriptor, ServiceHandler, Win64Args};
|
||||
pub use jit::{JitError, JitMemory};
|
||||
pub use memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
pub use pe::{LoadedImage, ParsedPe, PeError, PeSection};
|
||||
pub use probe::{
|
||||
ImportedSymbol, InstructionRecord, ProbeConfig, ProbeReport, RelocationCensus, TlsCensus,
|
||||
probe_pe_bytes, run_probe_and_export,
|
||||
};
|
||||
pub use reloc::{
|
||||
IMAGE_REL_BASED_ABSOLUTE, IMAGE_REL_BASED_DIR64, RelocationError, RelocationReport,
|
||||
apply_relocations,
|
||||
};
|
||||
pub use services::{Clock, MockClock, ServicesState, SystemClock, register_standard_services};
|
||||
pub use tls::{TlsDirectory, TlsError, execute_tls_callbacks, parse_tls_directory, setup_tls};
|
||||
pub use triage::{TriageReport, triage_bytes, triage_file};
|
||||
Loaded 100 of 356 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user