upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorAlmogaver295 <133548141+guimsolutions@users.noreply.github.com>2026-11-23 23:53:36 +0100
committerAlmogaver295 <133548141+guimsolutions@users.noreply.github.com>2026-11-23 23:53:36 +0100
commit33f4a5aedeb48e27b004efe5d6ae306130d55cdd (patch)
tree08361685151a2a6a4ecf9156955fabb35b4b570c /scripts
parent57cb669f52ba6ca4bb58bf2e09492ffbe2b8ee60 (diff)
parent5d74c272363f2703265d44e6aaab1a1df8ddfaf3 (diff)
Merge upstream main and preserve 1D UAV clear compatibilityold-pr/9948
Diffstat (limited to 'scripts')
-rw-r--r--scripts/audit_shader4_regs.py57
-rw-r--r--scripts/bench_wave64.py18
-rw-r--r--scripts/build_llvm_mc.ps130
-rw-r--r--scripts/build_runtime.ps1110
-rw-r--r--scripts/carve_all.ps18
-rw-r--r--scripts/check_apt_key.py93
-rw-r--r--scripts/check_no_game_data.py198
-rw-r--r--scripts/ci_expected_failures.py62
-rw-r--r--scripts/dev.py125
-rw-r--r--scripts/first_look.ps173
-rw-r--r--scripts/merge_check.py213
-rw-r--r--scripts/run_conservative_tier3_reference.ps131
-rw-r--r--scripts/run_gpu_tests.py340
-rw-r--r--scripts/run_guest_scene.py361
-rw-r--r--scripts/run_semantic_tests.py82
-rwxr-xr-xscripts/run_wine_session.sh9
-rw-r--r--scripts/run_wine_tests.py103
-rw-r--r--scripts/shader_stats.py7
-rw-r--r--scripts/vs_input_survey.py2
-rw-r--r--scripts/vs_layout_census.py221
20 files changed, 1994 insertions, 149 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py
index e8d0d0cfd..59aff3bc6 100644
--- a/scripts/audit_shader4_regs.py
+++ b/scripts/audit_shader4_regs.py
@@ -20,6 +20,7 @@ from collections import Counter
20 20
21ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 21ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22sys.path.insert(0, os.path.join(ROOT, "tools")) 22sys.path.insert(0, os.path.join(ROOT, "tools"))
23from report_paths import same_report_path # noqa: E402
23import shader_ir # noqa: E402 24import shader_ir # noqa: E402
24from shader_meta import SGPR_RMW # noqa: E402 25from shader_meta import SGPR_RMW # noqa: E402
25 26
@@ -27,7 +28,15 @@ NO_DEST_OPS = ("s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", "s_branch", "s_c
27 "s_waitcnt", "s_barrier", "s_nop", "s_endpgm", "s_sendmsg", "s_sleep", 28 "s_waitcnt", "s_barrier", "s_nop", "s_endpgm", "s_sendmsg", "s_sleep",
28 "exp", "buffer_store", "tbuffer_store", "global_store", "flat_store", "scratch_store", 29 "exp", "buffer_store", "tbuffer_store", "global_store", "flat_store", "scratch_store",
29 "s_store", "s_buffer_store", "image_store", "ds_write") 30 "s_store", "s_buffer_store", "image_store", "ds_write")
31# DS ops that write args[0]; every other DS op without "_rtn" (atomics, ds_write*, src2 and GWS forms) only reads its
32# operands. Same rule as tools/lane_masks.py.
33DS_HAS_DST = ("ds_read", "ds_swizzle", "ds_permute", "ds_bpermute", "ds_append", "ds_consume", "ds_ordered_count",
34 "ds_nop")
30WAVE64_RE = re.compile(r"exec_hi|v_mbcnt_hi_u32_b32|_saveexec_b64|_wrexec_b64") 35WAVE64_RE = re.compile(r"exec_hi|v_mbcnt_hi_u32_b32|_saveexec_b64|_wrexec_b64")
36# VOP2/VOP3 "c" dot forms accumulate into D (D = D + dot(S0, S1)); the same list the translator's read-before-write
37# tracking uses in tools/rdna2spirv.py.
38VOP_DOT_ACCUM = ("v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16",
39 "v_dot4c_i32_i8", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4")
31 40
32 41
33def base_op(op): 42def base_op(op):
@@ -37,9 +46,22 @@ def base_op(op):
37 return op 46 return op
38 47
39 48
40def load_stage_map(disasm_dir): 49class ReportInputCollision(Exception):
50 pass
51
52
53def protect_input(report_path, input_path, kind):
54 if report_path and os.path.isfile(input_path) and same_report_path(report_path, input_path):
55 raise ReportInputCollision(f"--json {report_path!r} must not overwrite an input {kind} {input_path!r}")
56
57
58def load_stage_map(disasm_dir, *, report_path=None):
41 parent = os.path.dirname(os.path.realpath(disasm_dir)) 59 parent = os.path.dirname(os.path.realpath(disasm_dir))
42 for cand in (os.path.join(parent, "index.json"), os.path.join(disasm_dir, "index.json")): 60 candidates = (os.path.join(parent, "index.json"), os.path.join(disasm_dir, "index.json"))
61 # Protect the fallback index even when the first one supplies the stage map.
62 for cand in candidates:
63 protect_input(report_path, cand, "index")
64 for cand in candidates:
43 if os.path.isfile(cand): 65 if os.path.isfile(cand):
44 try: 66 try:
45 with open(cand, encoding="utf-8") as _f: 67 with open(cand, encoding="utf-8") as _f:
@@ -175,19 +197,28 @@ def rbw_registers(insns):
175 op.startswith(NO_DEST_OPS) 197 op.startswith(NO_DEST_OPS)
176 or (is_gf_atomic and "glc" not in mods) 198 or (is_gf_atomic and "glc" not in mods)
177 or (is_bi_atomic and "glc" not in mods) 199 or (is_bi_atomic and "glc" not in mods)
200 or (op.startswith("ds_") and "_rtn" not in op and not op.startswith(DS_HAS_DST))
201 # A buffer load with lds transfers straight to LDS: args[0] is vaddr, not a written VGPR.
202 or (op.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods)
178 ) 203 )
179 reads_imm_dst = op in SGPR_RMW 204 reads_imm_dst = op in SGPR_RMW
180 # Instructions that read their destination too (buffer/image atomics with glc read and write vdata at args[0]; 205 # Instructions that read their destination too (buffer/image atomics with glc read and write vdata at args[0];
181 # global/flat atomics with glc write vdst at args[0] and read vaddr/vdata/saddr from args[1:]). 206 # global/flat atomics with glc write vdst at args[0] and read vaddr/vdata/saddr from args[1:]).
182 dst_also_read = ( 207 dst_also_read = (
183 reads_imm_dst or "fmac" in op or "mac_" in op or op == "v_writelane_b32" 208 reads_imm_dst or "fmac" in op or "mac_" in op or "dot2c_" in op or "dot4c_" in op or "dot8c_" in op
209 or op == "v_writelane_b32"
184 or op == "v_swap_b32" or (not is_gf_atomic and "_atomic_" in op) 210 or op == "v_swap_b32" or (not is_gf_atomic and "_atomic_" in op)
211 or op in VOP_DOT_ACCUM
185 ) 212 )
213 # A direct-to-LDS MUBUF/MTBUF load writes LDS, not a VGPR: args[0] holds the 4-dword LDS address and is read.
214 is_lds_load = op.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods
186 is_dual_dst = op.startswith("v_") and ( 215 is_dual_dst = op.startswith("v_") and (
187 "_co_" in op or op.startswith(("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) 216 "_co_" in op or op.startswith(("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64"))
188 ) 217 )
189 # Carry-out / scale-out forms write the VGPR and scalar mask first, even when they also take a carry-in source. 218 # Carry-out / scale-out forms write the VGPR and scalar mask first, even when they also take a carry-in source.
190 if not is_no_dest and is_dual_dst and len(args) >= 2: 219 if is_lds_load:
220 dsts, srcs = [], args
221 elif not is_no_dest and is_dual_dst and len(args) >= 2:
191 dsts = args[:2] 222 dsts = args[:2]
192 srcs = args[2:] 223 srcs = args[2:]
193 elif is_no_dest: 224 elif is_no_dest:
@@ -231,16 +262,19 @@ def detect_wave64(insns):
231 ) 262 )
232 263
233 264
234def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None): 265def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None, *, report_path=None):
235 if limit is not None and limit < 0: 266 if limit is not None and limit < 0:
236 raise ValueError("limit must be non-negative") 267 raise ValueError("limit must be non-negative")
237 parent = os.path.dirname(os.path.realpath(disasm_dir)) 268 parent = os.path.dirname(os.path.realpath(disasm_dir))
238 fssm_dir = fssm_dir or os.path.join(parent, "fssm") 269 fssm_dir = fssm_dir or os.path.join(parent, "fssm")
239 dxbc_dir = dxbc_dir or parent 270 dxbc_dir = dxbc_dir or parent
240 stage_map = load_stage_map(disasm_dir)
241 271
242 with os.scandir(disasm_dir) as it: 272 with os.scandir(disasm_dir) as it:
243 files = sorted(e.name for e in it if e.name.endswith(".s") and e.is_file()) 273 files = sorted(e.name for e in it if e.name.endswith(".s") and e.is_file())
274 if report_path:
275 for fname in files:
276 protect_input(report_path, os.path.join(disasm_dir, fname), "listing")
277 stage_map = load_stage_map(disasm_dir, report_path=report_path)
244 if limit is not None: 278 if limit is not None:
245 files = files[:limit] 279 files = files[:limit]
246 280
@@ -285,7 +319,7 @@ def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), l
285 rec["s3_rbw_op_patterns"][pat] += 1 319 rec["s3_rbw_op_patterns"][pat] += 1
286 320
287 fssm_path = os.path.join(fssm_dir, stem + ".fssm") 321 fssm_path = os.path.join(fssm_dir, stem + ".fssm")
288 dxbc_path = os.path.join(dxbc_dir, stem + ".dxbc") 322 protect_input(report_path, fssm_path, "FSSM file")
289 if st == "cs": 323 if st == "cs":
290 dec = decode_cs_rsrc2(fssm_path) 324 dec = decode_cs_rsrc2(fssm_path)
291 if dec: 325 if dec:
@@ -302,6 +336,8 @@ def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), l
302 words = read_fssm_words(fssm_path) 336 words = read_fssm_words(fssm_path)
303 if words: 337 if words:
304 rec["fssm_0x138_words"][" ".join(words)] += 1 338 rec["fssm_0x138_words"][" ".join(words)] += 1
339 dxbc_path = os.path.join(dxbc_dir, stem + ".dxbc")
340 protect_input(report_path, dxbc_path, "DXBC file")
305 psv = read_psv0(dxbc_path) 341 psv = read_psv0(dxbc_path)
306 if psv: 342 if psv:
307 if "threads" in psv: 343 if "threads" in psv:
@@ -382,7 +418,12 @@ def main(argv=None):
382 print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) 418 print(f"ERROR: {label}{path}: not a folder", file=sys.stderr)
383 return 2 419 return 2
384 420
385 rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit) 421 report_path = a.json_out if a.json_out and os.path.isfile(a.json_out) else None
422 try:
423 rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit, report_path=report_path)
424 except ReportInputCollision as error:
425 print(f"ERROR: {error}", file=sys.stderr)
426 return 2
386 print_report(rep) 427 print_report(rep)
387 if a.json_out: 428 if a.json_out:
388 try: 429 try:
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index 433eea00f..72a8bf742 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -19,7 +19,12 @@ import sys
19import tempfile 19import tempfile
20 20
21ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 21ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22BUILD_PY = os.path.join(ROOT, "runtime", "test", "shaders", "build.py") 22SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders")
23BUILD_PY = os.path.join(SHADER_DIR, "build.py")
24sys.path.insert(0, SHADER_DIR)
25from check import EXE, pick_build_dir # noqa: E402
26
27COMPUTE_TEST = "vk_compute_test" + EXE
23CONFIGS = [("AMD native", "*amd*,*radeon*", False), ("AMD --wave64-emulate", "*amd*,*radeon*", True), 28CONFIGS = [("AMD native", "*amd*,*radeon*", False), ("AMD --wave64-emulate", "*amd*,*radeon*", True),
24 ("NVIDIA --wave64-emulate", "*nv*", True)] 29 ("NVIDIA --wave64-emulate", "*nv*", True)]
25 30
@@ -50,7 +55,7 @@ def segments(spv: str) -> tuple[int, int] | None:
50 55
51def run(tools, spv, groups, reps, driver, emulate): 56def run(tools, spv, groups, reps, driver, emulate):
52 env = dict(os.environ, VK_LOADER_DRIVERS_SELECT=driver, VKC_BENCH=str(reps)) 57 env = dict(os.environ, VK_LOADER_DRIVERS_SELECT=driver, VKC_BENCH=str(reps))
53 args = [os.path.join(tools, "vk_compute_test" + (".exe" if os.name == "nt" else "")), spv, str(groups), "dump"] 58 args = [os.path.join(tools, COMPUTE_TEST), spv, str(groups), "dump"]
54 if not emulate: 59 if not emulate:
55 args.append("--require-wave64") 60 args.append("--require-wave64")
56 try: 61 try:
@@ -76,13 +81,16 @@ def positive_int(text):
76 81
77def main(): 82def main():
78 ap = argparse.ArgumentParser() 83 ap = argparse.ArgumentParser()
79 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) 84 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"),
85 help="CMake build directory or a configuration directory such as RelWithDebInfo")
80 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) 86 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"))
81 ap.add_argument("--groups", type=positive_int, default=65536) 87 # Vulkan guarantees support for at least 65,535 groups along X in one dispatch.
88 ap.add_argument("--groups", type=positive_int, default=65535)
82 ap.add_argument("--reps", type=positive_int, default=30) 89 ap.add_argument("--reps", type=positive_int, default=30)
83 ap.add_argument("--procs", type=positive_int, default=5) 90 ap.add_argument("--procs", type=positive_int, default=5)
84 ap.add_argument("--shader", default="cs_bench_mix") 91 ap.add_argument("--shader", default="cs_bench_mix")
85 a = ap.parse_args() 92 a = ap.parse_args()
93 tools = pick_build_dir(a.build, (COMPUTE_TEST,))
86 with tempfile.TemporaryDirectory(prefix="bench-w64-") as work: 94 with tempfile.TemporaryDirectory(prefix="bench-w64-") as work:
87 spv = {False: build(work, a.shader, False, a.llvm_mc), True: build(work, a.shader, True, a.llvm_mc)} 95 spv = {False: build(work, a.shader, False, a.llvm_mc), True: build(work, a.shader, True, a.llvm_mc)}
88 seg = segments(spv[True]) 96 seg = segments(spv[True])
@@ -93,7 +101,7 @@ def main():
93 for name, driver, emulate in CONFIGS: 101 for name, driver, emulate in CONFIGS:
94 med, mins, seen, dev = [], [], set(), None 102 med, mins, seen, dev = [], [], set(), None
95 for _ in range(a.procs): 103 for _ in range(a.procs):
96 t, h, dev = run(a.build, spv[emulate], a.groups, a.reps, driver, emulate) 104 t, h, dev = run(tools, spv[emulate], a.groups, a.reps, driver, emulate)
97 if t is None: 105 if t is None:
98 med = None 106 med = None
99 print(f"{name}: failed or unsupported: {h}") 107 print(f"{name}: failed or unsupported: {h}")
diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1
index e028fd9de..3d4d8044a 100644
--- a/scripts/build_llvm_mc.ps1
+++ b/scripts/build_llvm_mc.ps1
@@ -49,8 +49,29 @@ if (-not ((Test-Path $cmake) -and (Test-Path $ninja))) {
49 49
50$src = Join-Path $Temp "src" 50$src = Join-Path $Temp "src"
51$out = Join-Path $Temp "build" 51$out = Join-Path $Temp "build"
52function Remove-DirectoryRobust([string]$path) {
53 if (-not (Test-Path -LiteralPath $path)) { return }
54 # Strip read-only attributes on nested files and folders so Windows allows deletion
55 Get-ChildItem -LiteralPath $path -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object {
56 try {
57 if ($_.Attributes -band [System.IO.FileAttributes]::ReadOnly) {
58 $_.Attributes = $_.Attributes -bxor [System.IO.FileAttributes]::ReadOnly
59 }
60 } catch {}
61 }
62 for ($attempt = 1; $attempt -le 3; $attempt++) {
63 try {
64 Remove-Item -LiteralPath $path -Recurse -Force -ErrorAction Stop
65 return
66 } catch {
67 Start-Sleep -Milliseconds (100 * $attempt)
68 }
69 }
70 cmd.exe /c "rmdir /s /q `"$path`"" 2>$null
71}
72
52if (-not (Test-Path (Join-Path $src "llvm\CMakeLists.txt"))) { 73if (-not (Test-Path (Join-Path $src "llvm\CMakeLists.txt"))) {
53 if (Test-Path $src) { Remove-Item -Recurse -Force $src } 74 if (Test-Path -LiteralPath $src) { Remove-DirectoryRobust $src }
54 New-Item -ItemType Directory -Force $Temp | Out-Null 75 New-Item -ItemType Directory -Force $Temp | Out-Null
55 # core.longpaths: some llvm/docs paths are about 150 characters, so with a -Temp of about 100 characters the 76 # core.longpaths: some llvm/docs paths are about 150 characters, so with a -Temp of about 100 characters the
56 # sparse checkout fails with "Filename too long" (Windows' 260-character limit). Set in the clone's config only. 77 # sparse checkout fails with "Filename too long" (Windows' 260-character limit). Set in the clone's config only.
@@ -125,10 +146,9 @@ New-Item -ItemType Directory -Force $Dest | Out-Null
125$final = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $Dest "llvm-mc.exe")) 146$final = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $Dest "llvm-mc.exe"))
126Copy-Item -Force $exe $final 147Copy-Item -Force $exe $final
127if (-not $Keep) { 148if (-not $Keep) {
128 try { 149 Remove-DirectoryRobust $Temp
129 Remove-Item -LiteralPath $Temp -Recurse -Force 150 if (Test-Path -LiteralPath $Temp) {
130 } catch { 151 Write-Warning "Installed $final, but cleanup of '$Temp' failed."
131 Write-Warning "Installed $final, but cleanup of '$Temp' failed: $($_.Exception.Message)"
132 } 152 }
133} 153}
134if (-not $NoEnv) { 154if (-not $NoEnv) {
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index 4661d3b7a..2fd5120cc 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -1,5 +1,6 @@
1# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores by default. 1# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores by default.
2# Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly. 2# Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed (or native Windows cmake + ninja on PATH),
3# otherwise calls cl.exe directly.
3# The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or 4# The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or
4# with -FetchSdl3, which lets CMake download the pinned SDL3 release. The cl.exe fallback never builds it. 5# with -FetchSdl3, which lets CMake download the pinned SDL3 release. The cl.exe fallback never builds it.
5param( 6param(
@@ -9,6 +10,30 @@ param(
9) 10)
10$ErrorActionPreference = "Stop" 11$ErrorActionPreference = "Stop"
11 12
13function Invoke-ToolProbe([string]$Exe, [string[]]$ProbeArgs) {
14 $prev = $ErrorActionPreference
15 $ErrorActionPreference = "Continue"
16 try {
17 $global:LASTEXITCODE = 0
18 $text = (& $Exe @ProbeArgs 2>$null) -join "`n"
19 if ($LASTEXITCODE -eq 0) { return $text }
20 } catch {
21 } finally {
22 $ErrorActionPreference = $prev
23 }
24 return $null
25}
26
27function Find-BuildTool([string]$Preferred, [string]$CommandName, [scriptblock]$Validate) {
28 if ($Preferred -and (Test-Path $Preferred)) { return $Preferred }
29 foreach ($cmd in @(Get-Command $CommandName -CommandType Application -All -ErrorAction SilentlyContinue)) {
30 if ($cmd.Source -and ($cmd.Source -match "\.(exe|cmd|bat)$") -and (Test-Path $cmd.Source) -and (& $Validate $cmd.Source)) {
31 return $cmd.Source
32 }
33 }
34 return ""
35}
36
12$root = Split-Path $PSScriptRoot -Parent 37$root = Split-Path $PSScriptRoot -Parent
13$installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer" 38$installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer"
14$vs = & "$installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 39$vs = & "$installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
@@ -20,22 +45,40 @@ $out = Join-Path $src "build"
20New-Item -ItemType Directory -Force $out | Out-Null 45New-Item -ItemType Directory -Force $out | Out-Null
21 46
22$cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake" 47$cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake"
23$cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" 48# Skip MSYS/devkitPro cmake on PATH (docs/design.md): native Windows builds advertise Visual Studio + Ninja generators.
24$ninja = Join-Path $cmakeDir "Ninja\ninja.exe" 49$cmake = Find-BuildTool (Join-Path $cmakeDir "CMake\bin\cmake.exe") "cmake" {
50 param($p)
51 $help = Invoke-ToolProbe $p @("--help")
52 ($null -ne $help) -and ($help -match "Visual Studio") -and ($help -match "\bNinja\b")
53}
54$ninja = Find-BuildTool (Join-Path $cmakeDir "Ninja\ninja.exe") "ninja" {
55 param($p)
56 $null -ne (Invoke-ToolProbe $p @("--version"))
57}
25$cfg = if ($Debug) { "Debug" } else { "RelWithDebInfo" } 58$cfg = if ($Debug) { "Debug" } else { "RelWithDebInfo" }
26$sdl = if ($FetchSdl3) { "-DLEONIDA_SDL3_FETCH=ON" } else { "" } 59$sdl = if ($FetchSdl3) { "-DLEONIDA_SDL3_FETCH=ON" } else { "" }
27# With VULKAN_SDK set, a configure that still finds no Vulkan headers fails instead of dropping the Vulkan D3D12 device. 60# With VULKAN_SDK set, a configure that still finds no Vulkan headers fails instead of dropping the Vulkan D3D12 device.
28$vk = if ($env:VULKAN_SDK) { "-DLEONIDA_REQUIRE_VULKAN=ON" } else { "" } 61$vk = if ($env:VULKAN_SDK) { "-DLEONIDA_REQUIRE_VULKAN=ON" } else { "" }
29 62
30if ((Test-Path $cmake) -and (Test-Path $ninja)) { 63if ($cmake -and $ninja) {
64 $configure = "`"$cmake`" -S `"$src`" -B `"$out`" -G Ninja `"-DCMAKE_MAKE_PROGRAM=$ninja`" -DCMAKE_BUILD_TYPE=$cfg $sdl $vk"
65 $build = "`"$cmake`" --build `"$out`" -j $jobs"
66 # CALL reparses even quoted arguments and doubles a ^ in a checkout path.
67 # A native executable returns directly; a PATH .cmd/.bat wrapper needs its own
68 # cmd.exe so it returns here too, without CALL's second expansion.
69 if ([System.IO.Path]::GetExtension($cmake) -in @(".cmd", ".bat")) {
70 # Escape the outer quotes for the parent batch parser, keeping paths quoted there too.
71 $configure = 'cmd.exe /d /s /c ^"' + $configure + '^"'
72 $build = 'cmd.exe /d /s /c ^"' + $build + '^"'
73 }
31 $body = @" 74 $body = @"
32"$cmake" -S "$src" -B "$out" -G Ninja "-DCMAKE_MAKE_PROGRAM=$ninja" -DCMAKE_BUILD_TYPE=$cfg $sdl $vk || exit /b 1 75$configure || exit /b 1
33"$cmake" --build "$out" -j $jobs || exit /b 1 76$build || exit /b 1
34"@ 77"@
35} else { 78} else {
36 # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here: 79 # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here:
37 # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim. 80 # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim.
38 Write-Warning "VS C++ CMake tools not found: building with cl.exe directly, without the GameInput shim (SDL3). Install the CMake tools component to get it." 81 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it."
39 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" 82 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue"
40 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } 83 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" }
41 $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" } 84 $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp" | ForEach-Object { "`"$src\$_`"" }
@@ -43,13 +86,15 @@ if ((Test-Path $cmake) -and (Test-Path $ninja)) {
43 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } 86 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" }
44 $body = @" 87 $body = @"
45cd /d "$out" || exit /b 1 88cd /d "$out" || exit /b 1
46cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF psapi.lib ole32.lib || exit /b 1 89rem BUILD-1457: a game thread with the default stack size gets this program's reserve, and drivers compile on it. The same number as in CMakeLists.txt.
90cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /STACK:8388608 psapi.lib ole32.lib || exit /b 1
47cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1 91cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1
48cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 92cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1
49cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1 93cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1
50cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\descriptor_table_test.cpp" /Fe:descriptor_table_test.exe /link /OPT:NOREF || exit /b 1 94cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\descriptor_table_test.cpp" /Fe:descriptor_table_test.exe /link /OPT:NOREF || exit /b 1
51cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\command_list_test.cpp" /Fe:command_list_test.exe /link /OPT:NOREF || exit /b 1 95cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\src" "$src\test\command_list_test.cpp" /Fe:command_list_test.exe /link /OPT:NOREF || exit /b 1
52if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe || exit /b 1 96rem BUILD-1457: drivers compile on the checker's threads, and 1 MB of stack is too little for AMD's. The same number as in CMakeLists.txt.
97if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" "$src\test\vk_pipeline_check.cpp" /Fe:vk_pipeline_check.exe /link /STACK:8388608 || exit /b 1
53if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1 98if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_texture_test.cpp" /Fe:vk_texture_test.exe || exit /b 1
54if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sampler_test.cpp" /Fe:vk_sampler_test.exe || exit /b 1 99if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sampler_test.cpp" /Fe:vk_sampler_test.exe || exit /b 1
55if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1 100if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\gfx10_descriptors_test.cpp" /Fe:gfx10_descriptors_test.exe || exit /b 1
@@ -68,13 +113,54 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO
68# (e.g. Spanish "Nota: inclusión del archivo:") match Ninja's msvc_deps_prefix instead of being mojibaked in OEM CP. 113# (e.g. Spanish "Nota: inclusión del archivo:") match Ninja's msvc_deps_prefix instead of being mojibaked in OEM CP.
69$bat = Join-Path $out "_build.cmd" 114$bat = Join-Path $out "_build.cmd"
70# Keep the paths encoded for CP 65001 and start with an ASCII command that cmd.exe can read before switching. 115# Keep the paths encoded for CP 65001 and start with an ASCII command that cmd.exe can read before switching.
116# Here-strings follow the script's checkout line endings; cmd.exe needs CRLF in the generated UTF-8 batch.
117$body = $body -replace "`r?`n", "`r`n"
71$batchText = "@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body`r`n" 118$batchText = "@echo off`r`nchcp 65001 >nul`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body`r`n"
72[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false)) 119[System.IO.File]::WriteAllText($bat, $batchText, [System.Text.UTF8Encoding]::new($false))
73 120
121# -NoNewWindow attaches cmd/cmake to the parent console, so "Configuring done" / ninja status paint
122# over make_game.py's LEONIDA board. Hidden + file redirects keep the console clean; we then emit the
123# logs on our stdout so the board's pipe capture still sees them.
74# /s with a second pair of quotes: cmd.exe strips only the outer pair, so a path holding & or ^ stays quoted. 124# /s with a second pair of quotes: cmd.exe strips only the outer pair, so a path holding & or ^ stays quoted.
75$p = Start-Process cmd.exe -ArgumentList "/s", "/c", "`"`"$bat`"`"" -NoNewWindow -PassThru 125$stdoutLog = Join-Path $out "_build.stdout.log"
126$stderrLog = Join-Path $out "_build.stderr.log"
127foreach ($log in @($stdoutLog, $stderrLog)) {
128 if (Test-Path -LiteralPath $log) { Remove-Item -LiteralPath $log -Force }
129}
130$p = Start-Process -FilePath cmd.exe -ArgumentList "/s", "/c", "`"`"$bat`"`"" -PassThru `
131 -WindowStyle Hidden `
132 -RedirectStandardOutput $stdoutLog `
133 -RedirectStandardError $stderrLog
76$null = $p.Handle # keeps the exit code readable after WaitForExit 134$null = $p.Handle # keeps the exit code readable after WaitForExit
77try { $p.PriorityClass = "BelowNormal" } catch {} 135try { $p.PriorityClass = "BelowNormal" } catch {}
78$p.WaitForExit() 136
137function Emit-NewLogLines {
138 param([ref]$Offset, [string]$Path)
139 if (-not (Test-Path -LiteralPath $Path)) { return }
140 $fs = [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read,
141 [System.IO.FileShare]::ReadWrite)
142 try {
143 if ($fs.Length -lt $Offset.Value) { $Offset.Value = 0 }
144 [void]$fs.Seek($Offset.Value, [System.IO.SeekOrigin]::Begin)
145 $sr = New-Object System.IO.StreamReader($fs)
146 while (($line = $sr.ReadLine()) -ne $null) {
147 Write-Output $line
148 }
149 # Keep a partial trailing line for the next poll (ReadLine consumed only complete lines).
150 $Offset.Value = $fs.Position
151 } finally {
152 $fs.Dispose()
153 }
154}
155
156$outOff = 0
157$errOff = 0
158while (-not $p.HasExited) {
159 Emit-NewLogLines -Offset ([ref]$outOff) -Path $stdoutLog
160 Emit-NewLogLines -Offset ([ref]$errOff) -Path $stderrLog
161 Start-Sleep -Milliseconds 150
162}
163Emit-NewLogLines -Offset ([ref]$outOff) -Path $stdoutLog
164Emit-NewLogLines -Offset ([ref]$errOff) -Path $stderrLog
79if ($p.ExitCode -ne 0) { throw "build failed ($($p.ExitCode))" } 165if ($p.ExitCode -ne 0) { throw "build failed ($($p.ExitCode))" }
80Write-Host "built $out\gta6rt.exe" 166Write-Output "built $out\gta6rt.exe"
diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1
index f66d20945..e7de9e4d9 100644
--- a/scripts/carve_all.ps1
+++ b/scripts/carve_all.ps1
@@ -43,6 +43,14 @@ foreach ($archive in $archives) {
43 if ($s.span -eq 0 -and ($s.compressed_bytes -ne 0 -or $s.unread_bytes -ne 0)) { 43 if ($s.span -eq 0 -and ($s.compressed_bytes -ne 0 -or $s.unread_bytes -ne 0)) {
44 throw 'A zero summary.span requires zero compressed and unread bytes.' 44 throw 'A zero summary.span requires zero compressed and unread bytes.'
45 } 45 }
46 # Stored streams and unread gaps occupy disjoint parts of the span. Subtract instead of
47 # adding the counters so a total just above Int64.MaxValue cannot lose precision.
48 if ($s.compressed_bytes -gt $s.span -or $s.unread_bytes -gt ($s.span - $s.compressed_bytes)) {
49 throw 'summary.compressed_bytes and summary.unread_bytes must fit within summary.span.'
50 }
51 if ($s.bink2_files -gt $s.files) {
52 throw 'summary.bink2_files must not exceed summary.files.'
53 }
46 } catch { 54 } catch {
47 throw "Invalid carve index '$index': $($_.Exception.Message)" 55 throw "Invalid carve index '$index': $($_.Exception.Message)"
48 } 56 }
diff --git a/scripts/check_apt_key.py b/scripts/check_apt_key.py
new file mode 100644
index 000000000..160f0203a
--- /dev/null
+++ b/scripts/check_apt_key.py
@@ -0,0 +1,93 @@
1"""Check that a downloaded apt signing key is the one CI pins, before apt is told to trust it.
2
3 python3 -I scripts/check_apt_key.py KEYFILE FINGERPRINT
4
5The CI workflows fetch the WineHQ and apt.llvm.org signing keys over HTTPS and hand them to apt. Every other download
6in CI is pinned (actions by commit, glslang by SHA-256, the Vulkan headers by commit); this pins the keys by the
7fingerprint each project publishes. The key file must hold exactly one primary key, and its fingerprint must be
8FINGERPRINT (40 hex digits; spaces and case don't matter). A second primary key appended to the file fails the check
9too, since apt would trust it as well. Subkeys are allowed: they are bound to the primary key.
10
11Reads the key with `gpg --show-keys --with-colons` (GnuPG 2.2.8+), which lists a key file without importing it, so no
12keyring changes. Exits 0 when the key matches, 1 when it doesn't or gpg can't read it, 2 on a usage error. Standard
13library only.
14"""
15import os
16import re
17import subprocess
18import sys
19
20
21def normalize(fingerprint):
22 """`fingerprint` as 40 upper-case hex digits, or None if it isn't a v4 fingerprint."""
23 digits = re.sub(r"\s+", "", fingerprint).upper()
24 return digits if re.fullmatch(r"[0-9A-F]{40}", digits) else None
25
26
27def primary_fingerprints(colons):
28 """The fingerprint of each primary key in `gpg --with-colons` output: the `fpr` record right after a `pub` one."""
29 out = []
30 expect_primary_fpr = False
31 for line in colons.splitlines():
32 fields = line.split(":")
33 if fields[0] == "pub":
34 expect_primary_fpr = True
35 elif fields[0] == "fpr" and expect_primary_fpr:
36 out.append(fields[9].upper() if len(fields) > 9 else "")
37 expect_primary_fpr = False
38 elif fields[0] in ("sub", "ssb", "sec"):
39 expect_primary_fpr = False
40 return out
41
42
43def show_keys(path, gpg=("gpg",)):
44 """`gpg --show-keys --with-colons` output for the key file at `path` (it lists the file, importing nothing)."""
45 result = subprocess.run([*gpg, "--batch", "--show-keys", "--with-colons", path],
46 capture_output=True, text=True, encoding="utf-8", errors="replace")
47 if result.returncode != 0:
48 raise ValueError(f"gpg could not read {path}: {result.stderr.strip() or 'exit ' + str(result.returncode)}")
49 return result.stdout
50
51
52def check(path, expected, gpg=("gpg",)):
53 """None if the key file at `path` holds exactly the one primary key `expected`, else why not. `gpg` is the command
54 that runs GnuPG (a list, so a test can stand another program in)."""
55 try:
56 found = primary_fingerprints(show_keys(path, gpg))
57 except (OSError, ValueError) as e:
58 return str(e)
59 if not found:
60 return f"{path} holds no public key"
61 if len(found) > 1:
62 return f"{path} holds {len(found)} primary keys ({', '.join(found)}); expected only {expected}"
63 if found[0] != expected:
64 return f"{path} is key {found[0]}, expected {expected}"
65 return None
66
67
68def main(argv):
69 if len(argv) != 2:
70 print("usage: check_apt_key.py KEYFILE FINGERPRINT", file=sys.stderr)
71 return 2
72 path, fingerprint = argv
73 expected = normalize(fingerprint)
74 if not expected:
75 print(f"not a 40-digit key fingerprint: {fingerprint!r}", file=sys.stderr)
76 return 2
77 if not os.path.isfile(path):
78 print(f"no such key file: {path}", file=sys.stderr)
79 return 1
80 problem = check(path, expected)
81 if problem:
82 print(f"apt key check failed: {problem}", file=sys.stderr)
83 return 1
84 print(f"{path}: key {expected}")
85 return 0
86
87
88if __name__ == "__main__":
89 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
90 sys.stdout.reconfigure(errors="replace")
91 except (AttributeError, ValueError, OSError):
92 pass
93 sys.exit(main(sys.argv[1:]))
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py
index 09bc1d22b..fd6849fd3 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -6,15 +6,32 @@
6The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable 6The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable
7as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the 7as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the
8files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader 8files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader
9containers, SPIR-V, DDS, AWC audio, Ogg, RIFF WAVE, Bink, glTF binaries, PE executables and XVD images. The magics are 9containers, SPIR-V, DDS, AWC audio, PSIN/PAMH/MHIU/SPS1/SGD5/RDS5 containers, YSC/SCRP compiled scripts, the
10animation MoVE container and SKEL_ bone table, Ogg, RIFF WAVE, Bink, glTF binaries, PE executables and XVD
11images. The magics are
10the ones docs/ measures (docs/gamedata.md and the shader and audio notes). Text formats (disassembly, .obj, .spvasm) 12the ones docs/ measures (docs/gamedata.md and the shader and audio notes). Text formats (disassembly, .obj, .spvasm)
11have no magic and stay with the extension check. 13have no magic and stay with the extension check.
12 14
13Prints one line per match, `<path>: <format>`, and exits 1 if there is any. Standard library only, no game files. 15A compressed file hides those magics from both checks, so the script looks inside what the standard library opens:
16each member of a zip (found by its central directory too, so with bytes in front of it) or a tar, and the stream of
17a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory
18under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long.
197-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are
20reported as archives that can't be checked.
21
22Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and
23exits 1 if there is any. Standard library only, no game files.
14""" 24"""
25import bz2
26import gzip
27import io
28import lzma
15import os 29import os
16import subprocess 30import subprocess
17import sys 31import sys
32import tarfile
33import zipfile
34import zlib
18 35
19HEAD = 0x208 # enough for the XVD magic at 0x200 36HEAD = 0x208 # enough for the XVD magic at 0x200
20 37
@@ -36,6 +53,17 @@ MAGICS = (
36 ("DDS texture", 0, b"DDS "), 53 ("DDS texture", 0, b"DDS "),
37 ("AWC audio bank", 0, b"ADAT"), 54 ("AWC audio bank", 0, b"ADAT"),
38 ("AWC audio bank", 0, b"TADA"), 55 ("AWC audio bank", 0, b"TADA"),
56 ("AWC audio bank", 0, b"AWC\x00"),
57 ("PSIN metadata container", 0, b"PSIN"),
58 ("PAMH heightmap", 0, b"PAMH"),
59 ("MHIU heightmap", 0, b"MHIU"),
60 ("SPS1 shader-preset table", 0, b"SPS1"),
61 ("SGD5 effects database", 0, b"SGD5"),
62 ("RDS5 texture container", 0, b"RDS5"),
63 ("YSC compiled script", 0, b"YSC\x00"),
64 ("MoVE animation container", 0, b"MoVE"),
65 ("SKEL_ bone table", 0, b"SKEL_"),
66 ("SCRP compiled script", 0, b"SCRP"),
39 ("Ogg stream", 0, b"OggS"), 67 ("Ogg stream", 0, b"OggS"),
40 ("Bink 2 video", 0, b"KB2"), 68 ("Bink 2 video", 0, b"KB2"),
41 ("Bink video", 0, b"BIK"), 69 ("Bink video", 0, b"BIK"),
@@ -56,18 +84,166 @@ def classify(head, pe_signature=None):
56 return None 84 return None
57 85
58 86
87def read_head_from(f):
88 """(first bytes, the 4 bytes at e_lfanew or None) of the open binary file `f`. The PE signature is read where
89 e_lfanew points, even past the first bytes or straddling their end; a file too short for it gives fewer than 4
90 bytes and no match."""
91 head = f.read(HEAD)
92 if not head.startswith(b"MZ") or len(head) < 0x40:
93 return head, None
94 offset = int.from_bytes(head[0x3C:0x40], "little")
95 if offset + 4 <= len(head):
96 return head, head[offset:offset + 4]
97 f.seek(offset)
98 return head, f.read(4)
99
100
59def read_head(path): 101def read_head(path):
60 """(first bytes, the 4 bytes at e_lfanew or None). The PE signature is read where e_lfanew points, even past 102 """(first bytes, the 4 bytes at e_lfanew or None). The PE signature is read where e_lfanew points, even past
61 the first bytes or straddling their end; a file too short for it gives fewer than 4 bytes and no match.""" 103 the first bytes or straddling their end; a file too short for it gives fewer than 4 bytes and no match."""
62 with open(path, "rb") as f: 104 with open(path, "rb") as f:
63 head = f.read(HEAD) 105 return read_head_from(f)
64 if not head.startswith(b"MZ") or len(head) < 0x40: 106
65 return head, None 107
66 offset = int.from_bytes(head[0x3C:0x40], "little") 108ZIP = b"PK\x03\x04"
67 if offset + 4 <= len(head): 109# Single compressed streams the standard library opens: (name, magic, opener of a binary file object). GzipFile
68 return head, head[offset:offset + 4] 110# gets its mode explicitly: it reads the file object's own `mode`, which for a GzipFile inside it isn't a string.
69 f.seek(offset) 111STREAMS = (
70 return head, f.read(4) 112 ("gzip stream", b"\x1f\x8b", lambda f: gzip.GzipFile(fileobj=f, mode="rb")),
113 ("bzip2 stream", b"BZh", lambda f: bz2.BZ2File(f)),
114 ("xz stream", b"\xfd7zXZ\x00", lambda f: lzma.LZMAFile(f)),
115)
116# Archives the standard library can't open, so what they hold can't be checked.
117OPAQUE = (
118 ("7-Zip archive", b"7z\xbc\xaf\x27\x1c"),
119 ("Zstandard stream", b"\x28\xb5\x2f\xfd"),
120 ("RAR archive", b"Rar!\x1a\x07"),
121)
122MAX_DEPTH = 3 # an archive inside an archive inside an archive; deeper ones are reported as unchecked
123# What looking into one file may cost: the bytes decompressed or copied out of its archives in all, and the archive
124# members listed. Everything inside an archive is read into memory under this budget before it is looked at, so a
125# zip bomb, or a zip inside a gzip (whose central directory sits at the end of the expanded stream), can't make the
126# check run long or grow; past either limit the file is reported as too large to check, not passed.
127MAX_EXPANDED = 64 << 20
128MAX_MEMBERS = 10000
129CHUNK = 1 << 20
130TAR_MAGIC = (257, b"ustar") # POSIX and GNU tar headers
131# What a damaged archive raises while it is opened or read.
132ARCHIVE_ERRORS = (OSError, EOFError, ValueError, zipfile.BadZipFile, tarfile.TarError, lzma.LZMAError, zlib.error,
133 NotImplementedError, RuntimeError)
134
135
136class TooLarge(Exception):
137 """Looking into an archive would take more than its file's budget."""
138
139
140class Budget:
141 """The bytes and members left for one checked file."""
142
143 def __init__(self):
144 self.bytes = MAX_EXPANDED
145 self.members = MAX_MEMBERS
146
147 def spool(self, f):
148 """The rest of `f` read into memory, counted against the byte budget."""
149 out = io.BytesIO()
150 while True:
151 chunk = f.read(min(CHUNK, self.bytes + 1))
152 if not chunk:
153 break
154 self.bytes -= len(chunk)
155 if self.bytes < 0:
156 raise TooLarge
157 out.write(chunk)
158 out.seek(0)
159 return out
160
161 def member(self):
162 self.members -= 1
163 if self.members < 0:
164 raise TooLarge
165
166
167def printable(name):
168 """A member name on one output line: control characters (a newline in a name, say) shown as '?'."""
169 return "".join(c if c.isprintable() else "?" for c in name)
170
171
172def archive_kind(f, head):
173 """The kind of archive the seekable file `f` (first bytes `head`) is, or None."""
174 stream = next((s for s in STREAMS if head.startswith(s[1])), None)
175 if stream:
176 return stream[0]
177 if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]:
178 return "tar archive"
179 # is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting
180 # archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it.
181 if head.startswith(ZIP) or zipfile.is_zipfile(f):
182 return "zip archive"
183 return None
184
185
186def classify_open(f, first, depth=0, budget=None):
187 """The format of the seekable file `f`, whose read_head_from() is `first`: a game-data format, the game-data
188 format of the first match inside it if it's an archive, an archive that can't be checked, or None. Members and
189 streams inside are read into memory under `budget` (one per checked file) before they are looked at."""
190 budget = budget or Budget()
191 head = first[0]
192 name = classify(*first)
193 if name:
194 return name
195 for kind, magic in OPAQUE:
196 if head.startswith(magic):
197 return f"{kind} (contents can't be checked)"
198 kind = archive_kind(f, head)
199 if not kind:
200 return None
201 if depth >= MAX_DEPTH:
202 return f"{kind} nested more than {MAX_DEPTH} deep (contents can't be checked)"
203
204 def look_into(member):
205 inner = budget.spool(member)
206 return classify_open(inner, read_head_from(inner), depth + 1, budget)
207
208 try:
209 f.seek(0)
210 if kind == "zip archive":
211 with zipfile.ZipFile(f) as archive:
212 for info in archive.infolist():
213 budget.member()
214 if info.is_dir():
215 continue
216 with archive.open(info) as member:
217 inner = look_into(member)
218 if inner:
219 return f"{inner} in {kind} ({printable(info.filename)})"
220 return None
221 if kind == "tar archive":
222 with tarfile.open(fileobj=f, mode="r:") as archive:
223 for info in archive:
224 budget.member()
225 if not info.isfile():
226 continue
227 with archive.extractfile(info) as member:
228 inner = look_into(member)
229 if inner:
230 return f"{inner} in {kind} ({printable(info.name)})"
231 return None
232 opener = next(s[2] for s in STREAMS if s[0] == kind)
233 with opener(f) as member:
234 inner = look_into(member)
235 return f"{inner} in {kind}" if inner else None
236 except TooLarge:
237 return (f"{kind} too large to check (over {MAX_EXPANDED >> 20} MiB expanded or {MAX_MEMBERS} members; "
238 "contents can't be checked)")
239 except ARCHIVE_ERRORS:
240 return f"{kind} that can't be opened (contents can't be checked)"
241
242
243def classify_file(path):
244 """The format the file at `path` starts like (looking inside archives), or None."""
245 with open(path, "rb") as f:
246 return classify_open(f, read_head_from(f))
71 247
72 248
73def tracked_files(root): 249def tracked_files(root):
@@ -81,7 +257,7 @@ def check(paths):
81 for path in paths: 257 for path in paths:
82 if os.path.islink(path) or not os.path.isfile(path): 258 if os.path.islink(path) or not os.path.isfile(path):
83 continue # submodules, symlinks, files deleted in the working tree 259 continue # submodules, symlinks, files deleted in the working tree
84 name = classify(*read_head(path)) 260 name = classify_file(path)
85 if name: 261 if name:
86 found.append((path, name)) 262 found.append((path, name))
87 return found 263 return found
diff --git a/scripts/ci_expected_failures.py b/scripts/ci_expected_failures.py
new file mode 100644
index 000000000..8112dcf4b
--- /dev/null
+++ b/scripts/ci_expected_failures.py
@@ -0,0 +1,62 @@
1"""Judge a CI test run that has known failures, each fixed by an open pull request.
2
3 python -I scripts/ci_expected_failures.py FAILED_LIST EXIT_STATUS [EXPECTED ...]
4
5FAILED_LIST is a file with one failed test name per line, EXIT_STATUS the test runner's exit status, and each
6EXPECTED argument one or more whitespace-separated test names (so a workflow can pass one quoted list). Exits 1 when a
7test outside EXPECTED failed, the runner failed without naming a test, or the runner was terminated by a signal
8(its failure list can be incomplete); 2 on a usage error. `--help` prints this text. An expected failure absent
9from a completed run gets a GitHub Actions notice so the list in the workflow can shrink.
10"""
11
12import sys
13
14
15def judge(failed: list[str], status: int, expected: list[str]) -> tuple[int, list[str]]:
16 """(exit status, GitHub Actions workflow commands to print)."""
17 unexpected = [name for name in failed if name not in expected]
18 lines = [f"::error::{name} failed" for name in unexpected]
19 # subprocess reports a signal as -N; the shell pipelines in runtime.yml report it as 128+N.
20 if status < 0 or 128 < status <= 255:
21 lines.append(f"::error::abnormal test runner exit {status}; the failure list may be incomplete")
22 return 1, lines
23 if status != 0 and not failed:
24 lines.append(f"::error::the test runner exited with {status} without naming a failed test")
25 for name in expected:
26 if name in failed:
27 lines.append(f"::warning::{name} failed, as expected until its fix is merged")
28 else:
29 lines.append(f"::notice::{name} passed: drop it from the expected failures")
30 return (1 if unexpected or (status != 0 and not failed) else 0), lines
31
32
33def main(argv: list[str]) -> int:
34 if argv and argv[0] in ("-h", "--help"):
35 print(__doc__.strip())
36 return 0
37 if len(argv) < 2:
38 print(__doc__.strip(), file=sys.stderr)
39 return 2
40 try:
41 status = int(argv[1])
42 except ValueError:
43 print(f"ci_expected_failures: EXIT_STATUS {argv[1]!r} is not an integer", file=sys.stderr)
44 return 2
45 try:
46 with open(argv[0], encoding="utf-8") as f:
47 failed = [line.strip() for line in f if line.strip()]
48 except OSError as e:
49 print(f"ci_expected_failures: {argv[0]}: {e.strerror or e}", file=sys.stderr)
50 return 2
51 expected = [name for arg in argv[2:] for name in arg.split()]
52 code, lines = judge(failed, status, expected)
53 print("\n".join(lines))
54 return code
55
56
57if __name__ == "__main__":
58 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
59 sys.stdout.reconfigure(errors="replace")
60 except (AttributeError, ValueError, OSError):
61 pass
62 sys.exit(main(sys.argv[1:]))
diff --git a/scripts/dev.py b/scripts/dev.py
new file mode 100644
index 000000000..ffe2a0d9f
--- /dev/null
+++ b/scripts/dev.py
@@ -0,0 +1,125 @@
1#!/usr/bin/env python3
2"""Use development tools from this Leonida checkout."""
3
4import argparse
5import json
6import os
7import shlex
8import subprocess
9import sys
10from pathlib import Path
11
12
13ROOT = Path(__file__).resolve().parents[1]
14BOOT_TRACE = "tools/boot_trace.py"
15GUEST_SCENE = "scripts/run_guest_scene.py"
16TOOLS = (
17 (
18 "boot-trace",
19 BOOT_TRACE,
20 ("Python 3", "Startup JSONL from gta6rt --trace or stderr from gta6rt --trace-d3d12"),
21 ),
22 (
23 "guest-scene",
24 GUEST_SCENE,
25 (
26 "Python 3",
27 "gta6rt and tiny_guest_draw built with LEONIDA_GUEST_SCENE (static SDL3)",
28 "Vulkan and the synthetic M1.5 shader fixture with a spirv/ directory",
29 "Wine when running the Windows loader outside Windows",
30 ),
31 ),
32)
33
34
35def discover() -> dict:
36 tools = []
37 for name, path, requirements in TOOLS:
38 present = (ROOT / path).is_file()
39 tools.append({
40 "id": name,
41 "path": path,
42 "present": present,
43 "help_argv": [sys.executable, "-I", path, "--help"] if present else None,
44 "requirements": requirements,
45 })
46 return {
47 "schema_version": 1,
48 "tools": tools,
49 "live_controls": {
50 "available": False,
51 "reason": "This entry point does not expose live attach, pause, step, input or screenshots.",
52 },
53 }
54
55
56def format_help_command(argv: list[str]) -> str:
57 if os.name == "nt":
58 quoted = ("'" + arg.replace("'", "''") + "'" for arg in argv)
59 return "& " + " ".join(quoted)
60 return shlex.join(argv)
61
62
63def run_producer(relative_path: str, args: list[str]) -> int:
64 producer = ROOT / relative_path
65 if not producer.is_file():
66 print(f"error: {relative_path} is missing; use a complete Leonida checkout", file=sys.stderr)
67 return 2
68 try:
69 return subprocess.run(
70 [sys.executable, "-I", str(producer), *args],
71 cwd=Path.cwd(),
72 ).returncode
73 except OSError as exc:
74 print(f"error: could not run {relative_path}: {exc}", file=sys.stderr)
75 return 2
76
77
78def guest_scene(args: list[str]) -> int:
79 # Only enforce the persistent output option here. The runner parses the original argv.
80 parser = argparse.ArgumentParser(prog="dev.py guest-scene", add_help=False, allow_abbrev=False)
81 parser.add_argument("-h", "--help", action="store_true")
82 parser.add_argument("--out", metavar="PATH")
83 options, _ = parser.parse_known_args(args)
84 if not options.help and not options.out:
85 parser.error("--out PATH is required to keep the scene results")
86
87 return run_producer(GUEST_SCENE, args)
88
89
90def main() -> int:
91 # The producer owns its arguments and help. Forward before argparse handles them.
92 argv = sys.argv[1:]
93 if argv[:1] == ["boot-trace"]:
94 return run_producer(BOOT_TRACE, argv[1:])
95 if argv[:1] == ["guest-scene"]:
96 return guest_scene(argv[1:])
97
98 parser = argparse.ArgumentParser(description=__doc__)
99 commands = parser.add_subparsers(dest="command", required=True)
100 inventory = commands.add_parser("discover", help="list producer scripts and their requirements")
101 inventory.add_argument("--json", action="store_true", help="write a JSON inventory to stdout")
102 commands.add_parser("boot-trace", help="summarize startup and D3D12 boot traces")
103 commands.add_parser("guest-scene", help="run the synthetic guest scene with a required --out")
104 args = parser.parse_args(argv)
105
106 result = discover()
107 if args.json:
108 print(json.dumps(result, indent=2))
109 else:
110 sys.stdout.reconfigure(encoding="utf-8")
111 print("Paths and help commands are relative to the Leonida checkout root.")
112 for tool in result["tools"]:
113 status = "present" if tool["present"] else "missing"
114 print(f"{tool['id']}: {tool['path']} ({status})")
115 if tool["help_argv"]:
116 print(f" Help: {format_help_command(tool['help_argv'])}")
117 print(" Requirements (not checked):")
118 for requirement in tool["requirements"]:
119 print(f" - {requirement}")
120 print(f"Live controls: unavailable. {result['live_controls']['reason']}")
121 return 0
122
123
124if __name__ == "__main__":
125 raise SystemExit(main())
diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1
index 9e0e54266..6fb7ca36b 100644
--- a/scripts/first_look.ps1
+++ b/scripts/first_look.ps1
@@ -2,23 +2,26 @@
2# Reads the exe only; no game code runs. 2# Reads the exe only; no game code runs.
3param( 3param(
4 [Parameter(Mandatory)][string]$Exe, 4 [Parameter(Mandatory)][string]$Exe,
5 [string]$GameDir = (Split-Path $Exe -Parent) 5 [string]$GameDir
6) 6)
7$ErrorActionPreference = "Stop" 7$ErrorActionPreference = "Stop"
8$root = Split-Path $PSScriptRoot -Parent 8$root = Split-Path $PSScriptRoot -Parent
9$Exe = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Exe)
10if (-not (Test-Path -LiteralPath $Exe -PathType Leaf)) { throw "$Exe not found" }
11$image = Get-Item -LiteralPath $Exe
12if (-not $GameDir) { $GameDir = $image.DirectoryName }
9$name = [IO.Path]::GetFileNameWithoutExtension($Exe) 13$name = [IO.Path]::GetFileNameWithoutExtension($Exe)
10$out = Join-Path $root "reports\exe\$name" 14$out = Join-Path $root "reports\exe\$name"
11New-Item -ItemType Directory -Force $out | Out-Null 15New-Item -ItemType Directory -Force $out | Out-Null
12 16
13if (-not (Test-Path $Exe)) { throw "$Exe not found" }
14$fs = [IO.File]::OpenRead($Exe); $mz = New-Object byte[] 2; [void]$fs.Read($mz, 0, 2); $fs.Close() 17$fs = [IO.File]::OpenRead($Exe); $mz = New-Object byte[] 2; [void]$fs.Read($mz, 0, 2); $fs.Close()
15if ([Text.Encoding]::ASCII.GetString($mz) -ne "MZ") { 18if ([Text.Encoding]::ASCII.GetString($mz) -ne "MZ") {
16 throw "$Exe doesn't start with an MZ header. It's still packaged or encrypted, so there's nothing to inspect." 19 throw "$Exe doesn't start with an MZ header. It's still packaged or encrypted, so there's nothing to inspect."
17} 20}
18 21
19$size = (Get-Item $Exe).Length 22$size = $image.Length
20$hash = (Get-FileHash $Exe -Algorithm SHA256).Hash.ToLower() 23$hash = (Get-FileHash -LiteralPath $Exe -Algorithm SHA256).Hash.ToLower()
21"sha256 $hash size $size" | Tee-Object (Join-Path $out "hash.txt") 24"sha256 $hash size $size" | Tee-Object -LiteralPath (Join-Path $out "hash.txt")
22 25
23Write-Host "`n== PE inspection" 26Write-Host "`n== PE inspection"
24python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out 27python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out
@@ -35,31 +38,71 @@ if ($LASTEXITCODE -ne 0) { Write-Warning "find_hash_lookup could not scan $Exe"
35Write-Host "`n== What to confirm against this executable (every ASSUMPTION / UNVERIFIED / VERIFY note; called ones first)" 38Write-Host "`n== What to confirm against this executable (every ASSUMPTION / UNVERIFIED / VERIFY note; called ones first)"
36$calls = Join-Path $out ((Split-Path $Exe -Leaf) + ".gdk_calls.json") 39$calls = Join-Path $out ((Split-Path $Exe -Leaf) + ".gdk_calls.json")
37$checklistArgs = @("--out", (Join-Path $out "checklist.md")) 40$checklistArgs = @("--out", (Join-Path $out "checklist.md"))
38if (Test-Path $calls) { $checklistArgs += @("--gdk-calls", $calls) } 41if (Test-Path -LiteralPath $calls) { $checklistArgs += @("--gdk-calls", $calls) }
39python -I (Join-Path $root "tools\exe_checklist.py") @checklistArgs 42python -I (Join-Path $root "tools\exe_checklist.py") @checklistArgs
40if ($LASTEXITCODE -ne 0) { Write-Warning "exe_checklist could not write the checklist" } 43if ($LASTEXITCODE -ne 0) { Write-Warning "exe_checklist could not write the checklist" }
41 44
42$rt = Join-Path $root "runtime\build\gta6rt.exe" 45function Find-RuntimeLoader($build, $folders) {
46 foreach ($folder in $folders) {
47 $candidate = [IO.Path]::Combine($build, $folder, "gta6rt.exe")
48 if (Test-Path -LiteralPath $candidate -PathType Leaf) { return $candidate }
49 }
50}
51
52$build = Join-Path $root "runtime\build"
53$configs = @("RelWithDebInfo", "Release", "MinSizeRel", "Debug")
54$folders = @("") + $configs
55$rt = Find-RuntimeLoader $build $folders
43# A gta6rt.exe older than the runtime sources (a pull since the last build) would report the old shim table, so it 56# A gta6rt.exe older than the runtime sources (a pull since the last build) would report the old shim table, so it
44# is rebuilt then too, not only when missing. 57# is rebuilt then too, not only when missing.
45$sources = @("runtime\src", "runtime\shims", "runtime\CMakeLists.txt") | ForEach-Object { Join-Path $root $_ } | 58$sources = @("runtime\src", "runtime\shims", "runtime\CMakeLists.txt") | ForEach-Object { Join-Path $root $_ } |
46 Where-Object { Test-Path $_ } 59 Where-Object { Test-Path -LiteralPath $_ }
47$newest = $sources | Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue | 60$newest = $sources | ForEach-Object { Get-ChildItem -LiteralPath $_ -Recurse -File -ErrorAction SilentlyContinue } |
48 Sort-Object LastWriteTime -Descending | Select-Object -First 1 61 Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
49$stale = (Test-Path $rt) -and $newest -and ($newest.LastWriteTime -gt (Get-Item $rt).LastWriteTime) 62$stale = $rt -and $newest -and ($newest.LastWriteTimeUtc -gt (Get-Item -LiteralPath $rt).LastWriteTimeUtc)
50if ($stale) { Write-Host "runtime\build\gta6rt.exe is older than $($newest.Name): rebuilding it first" } 63if ($stale) { Write-Host "$rt is older than $($newest.Name): rebuilding it first" }
51if (-not (Test-Path $rt) -or $stale) { & (Join-Path $PSScriptRoot "build_runtime.ps1") } 64$tlsName = "gta6rt_tls_host.dll"
65$hasTls = $rt -and (Test-Path -LiteralPath (Join-Path (Split-Path -LiteralPath $rt) $tlsName) -PathType Leaf)
66if (-not $hasTls -or $stale) {
67 if (-not $hasTls) { Write-Host "Missing runtime files: gta6rt.exe and $tlsName must be in the same folder; rebuilding the runtime" }
68 $cache = Join-Path $build "CMakeCache.txt"
69 if ((Test-Path -LiteralPath $cache -PathType Leaf) -and
70 (Select-String -LiteralPath $cache -Pattern '^CMAKE_GENERATOR:INTERNAL=Visual Studio ' -Quiet)) {
71 # The wrapper configures Ninja and cannot reuse a Visual Studio build tree.
72 $commandEntry = Select-String -LiteralPath $cache -Pattern '^CMAKE_COMMAND:INTERNAL=(.+)$'
73 if (-not $commandEntry) { throw "Missing CMAKE_COMMAND in $cache. Reconfigure the Visual Studio build and retry." }
74 $cmake = $commandEntry.Matches.Groups[1].Value
75 $folders = $configs
76 $types = Select-String -LiteralPath $cache -Pattern '^CMAKE_CONFIGURATION_TYPES:[^=]+=(.+)$'
77 if ($types) {
78 $available = $types.Matches.Groups[1].Value -split ';'
79 $folders = @($configs | Where-Object { $_ -in $available })
80 }
81 $existing = Find-RuntimeLoader $build $folders
82 $configArgs = @()
83 if ($existing) { $configArgs = @("--config", (Split-Path (Split-Path $existing) -Leaf)) }
84 elseif ($types -and $folders.Count) { $configArgs = @("--config", $folders[0]) }
85 & $cmake --build $build --target gta6rt @configArgs
86 if ($LASTEXITCODE -ne 0) { throw "Building gta6rt in $build failed ($LASTEXITCODE)" }
87 } else {
88 & (Join-Path $PSScriptRoot "build_runtime.ps1")
89 }
90 $rt = Find-RuntimeLoader $build $folders
91 if (-not $rt) { throw "runtime build did not produce gta6rt.exe in $build" }
92 $tlsHost = Join-Path (Split-Path -LiteralPath $rt) $tlsName
93 if (-not (Test-Path -LiteralPath $tlsHost -PathType Leaf)) { throw "runtime build did not produce $tlsHost" }
94}
52Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)" 95Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)"
53& { 96& {
54 # Keep native stderr in the report without letting Windows PowerShell stop the dry run on it. 97 # Keep native stderr in the report without letting Windows PowerShell stop the dry run on it.
55 $ErrorActionPreference = "Continue" 98 $ErrorActionPreference = "Continue"
56 $PSNativeCommandUseErrorActionPreference = $false 99 $PSNativeCommandUseErrorActionPreference = $false
57 & $rt --dry-run $Exe --game-dir $GameDir 2>&1 100 & $rt --dry-run $Exe --game-dir $GameDir 2>&1
58} | Tee-Object (Join-Path $out "dryrun.txt") | Select-Object -Last 40 101} | Tee-Object -LiteralPath (Join-Path $out "dryrun.txt") | Select-Object -Last 40
59$dryRunExitCode = $LASTEXITCODE 102$dryRunExitCode = $LASTEXITCODE
60 103
61# Shim to-do list, grouped by DLL, most functions first. 104# Shim to-do list, grouped by DLL, most functions first.
62$report = Get-Content (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json 105$report = Get-Content -LiteralPath (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json
63$todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } 106$todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count }
64$lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } 107$lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count }
65Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines 108Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines
diff --git a/scripts/merge_check.py b/scripts/merge_check.py
new file mode 100644
index 000000000..5deefb36e
--- /dev/null
+++ b/scripts/merge_check.py
@@ -0,0 +1,213 @@
1"""Before a merge round: is a pull request already on main, and would merging it again duplicate text?
2
3 python -I scripts/merge_check.py [--main REF] [--json] [--min-length N] PR=REF [PR=REF ...]
4
5PR is the pull request number and REF its head (a branch, a fetched `refs/pull/PR/head`, a commit). For each one,
6against `--main` (default `origin/main`), using one history scan for the whole batch:
7
8- `merges`: first-parent commits on main whose subject is "Merge pull request #PR" or ends with " (#PR)" (squash
9 merges; "Revert ..." subjects are ignored), newest first. A number that is already there is the case the repeated
10 merges come from: a rebased copy merged again keeps both copies of what it added.
11- `commits`: the PR's commits (merge base..REF) and how many `git cherry` finds on main already (same patch).
12- `duplicates`: runs of three or more consecutive lines the merge would add (each at least `--min-length`
13 characters once stripped) that already stand in the same order in the same file on main. This is what a second
14 merge leaves behind as a doubled paragraph, table or function, whether or not the commits match by patch; a single
15 repeated line is not reported, since code and tables repeat lines legitimately. Only text files (.md, .txt,
16 .rst) make the verdict `duplicates`; a block in code is listed, since equal lines in two functions are ordinary.
17- `conflict`: whether `git merge-tree` reports a conflict (the duplicate check is then on the conflicted tree).
18
19Verdict per PR: `already-merged` (a prior merge exists and either every commit is on main or the conflict-free merged
20tree matches main, as after a multi-commit squash merge), `duplicates`, `conflict` or `clean`.
21Exit 0 when every PR is clean, 1 when any is not, 2 on a usage or git error. Read-only: `merge-tree --write-tree`
22writes only objects, no refs. Standard library only; needs git 2.38 or newer for `merge-tree --write-tree`.
23"""
24import argparse
25import codecs
26import json
27import re
28import subprocess
29import sys
30from collections import Counter
31
32MERGE_SUBJECT = re.compile(r"^Merge pull request #(\d+)\b")
33SQUASH_SUBJECT = re.compile(r"(?:^|\s)\(#(\d+)\)\s*$")
34REVERT_SUBJECT = re.compile(r"^Revert\b", re.IGNORECASE)
35# Where a doubled block is the repeated-merge damage. In code, three equal lines in two functions are ordinary, so a
36# block there is listed but does not change the verdict.
37TEXT_SUFFIXES = (".md", ".txt", ".rst")
38
39
40class GitError(Exception):
41 pass
42
43
44def git(repo, *args, check=True):
45 r = subprocess.run(["git", "-C", repo, *args], capture_output=True)
46 # Decode without universal-newline translation: a bare CR inside a Git line is content.
47 r.stdout = r.stdout.decode("utf-8", "replace")
48 r.stderr = r.stderr.decode("utf-8", "replace")
49 if check and r.returncode != 0:
50 raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}")
51 return r
52
53
54def _merged_pr_number(subject):
55 m = MERGE_SUBJECT.match(subject)
56 if m:
57 return int(m.group(1))
58 if REVERT_SUBJECT.match(subject):
59 return None
60 m = SQUASH_SUBJECT.search(subject)
61 return int(m.group(1)) if m else None
62
63
64def prior_merges(repo, main, numbers, depth):
65 out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout
66 hits = {number: [] for number in numbers}
67 for line in out.splitlines():
68 sha, _, subject = line.partition("\t")
69 number = _merged_pr_number(subject)
70 if number in hits:
71 hits[number].append(sha[:12])
72 return hits
73
74
75def cherry(repo, main, ref):
76 """(commits on the PR side, those whose patch is already on main)."""
77 lines = [l for l in git(repo, "cherry", main, ref).stdout.splitlines() if l.strip()]
78 return len(lines), sum(1 for l in lines if l.startswith("-"))
79
80
81def rev_tree(repo, rev):
82 return git(repo, "rev-parse", f"{rev}^{{tree}}").stdout.strip()
83
84
85def merged_tree(repo, main, ref):
86 r = git(repo, "merge-tree", "--write-tree", main, ref, check=False)
87 if r.returncode not in (0, 1) or not r.stdout.strip():
88 raise GitError(f"git merge-tree {main} {ref}: {r.stderr.strip() or r.returncode}")
89 return r.stdout.split()[0], r.returncode == 1
90
91
92def patch_destination(header):
93 """Decode Git's +++ header. An unquoted path containing spaces can have a trailing tab."""
94 name = header[4:].removesuffix("\t")
95 if name.startswith('"') and name.endswith('"'):
96 # Git's octal escapes describe filesystem bytes, not Unicode code points.
97 name = codecs.escape_decode(name[1:-1].encode("utf-8"))[0].decode("utf-8", "surrogateescape")
98 return name[2:] if name.startswith("b/") else None # Deleted files say /dev/null.
99
100
101def duplicates(repo, main, tree, min_length, block=3):
102 """{path: [line, ...]} for runs of `block` or more consecutive added lines (each at least `min_length` characters
103 once stripped; blank lines skipped) that already stand in the same order in the same file on main: a paragraph,
104 table or function body merged twice. A single repeated line is not reported: code and tables repeat lines
105 legitimately."""
106 found = {}
107 hunks, path, added = {}, None, None
108 patch = git(repo, "-c", "core.quotePath=true", "diff", "--unified=0", "--no-color", "--no-renames",
109 "--src-prefix=a/", "--dst-prefix=b/", "--no-relative", "--no-ext-diff", "--no-textconv",
110 main, tree).stdout
111 for line in patch.split("\n"):
112 if line.startswith("diff --git "):
113 path, added = None, None
114 elif added is None and line.startswith("+++ "):
115 path = patch_destination(line)
116 elif line.startswith("@@ ") and path:
117 added = []
118 hunks.setdefault(path, []).append(added)
119 elif added is not None and line.startswith("+"):
120 text = line[1:].strip()
121 if text:
122 added.append(text)
123 def windows(rev, path):
124 r = git(repo, "show", f"{rev}:{path}", check=False)
125 lines = [l.strip() for l in r.stdout.split("\n") if l.strip()] if r.returncode == 0 else []
126 return r.returncode == 0, Counter(tuple(lines[i:i + block]) for i in range(len(lines) - block + 1))
127
128 for path, groups in hunks.items():
129 exists, before = windows(main, path)
130 if not exists:
131 continue # a new file: nothing to duplicate
132 _, after = windows(tree, path)
133 same = []
134 for added in groups:
135 marked = [False] * len(added)
136 for i in range(len(added) - block + 1):
137 run = tuple(added[i:i + block])
138 # Doubled: on main already, and more copies after the merge. A block the PR moves (deleted where
139 # it was, added elsewhere) keeps its count and is not reported.
140 if all(len(x) >= min_length for x in run) and before[run] and after[run] > before[run]:
141 for j in range(i, i + block):
142 marked[j] = True
143 same += [x for x, m in zip(added, marked) if m]
144 if same:
145 found[path] = same
146 return found
147
148
149def check(repo, main, number, ref, min_length, merges):
150 total, on_main = cherry(repo, main, ref)
151 tree, conflict = merged_tree(repo, main, ref)
152 unchanged = not conflict and tree == rev_tree(repo, main)
153 dups = {} if unchanged else duplicates(repo, main, tree, min_length)
154 text_dups = {p: v for p, v in dups.items() if p.lower().endswith(TEXT_SUFFIXES)}
155 if merges and (total == on_main or unchanged):
156 verdict = "already-merged"
157 elif text_dups:
158 verdict = "duplicates"
159 elif conflict:
160 verdict = "conflict"
161 else:
162 verdict = "clean"
163 return {"pr": number, "ref": ref, "verdict": verdict, "merges": merges,
164 "commits": {"total": total, "on_main": on_main}, "conflict": conflict,
165 "duplicates": {p: len(v) for p, v in dups.items()},
166 "duplicate_samples": {p: v[:3] for p, v in dups.items()}}
167
168
169def parse_pair(text):
170 number, sep, ref = text.partition("=")
171 if not sep or not number.lstrip("#").isdigit() or not ref:
172 raise argparse.ArgumentTypeError(f"expected PR=REF, got {text!r}")
173 return int(number.lstrip("#")), ref
174
175
176def main(argv=None):
177 ap = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0])
178 ap.add_argument("pairs", nargs="+", type=parse_pair, metavar="PR=REF")
179 ap.add_argument("--main", default="origin/main", help="the branch the round merges into (default origin/main)")
180 ap.add_argument("--repo", default=".", help="repository folder (default: the current one)")
181 ap.add_argument("--min-length", type=int, default=40, help="shortest stripped line counted as a duplicate (40)")
182 ap.add_argument("--depth", type=int, default=5000, help="first-parent commits searched for earlier merges (5000)")
183 ap.add_argument("--json", action="store_true", help="one JSON report instead of text")
184 args = ap.parse_args(argv)
185 try:
186 history = prior_merges(args.repo, args.main, (n for n, _ in args.pairs), args.depth)
187 results = [check(args.repo, args.main, n, ref, args.min_length, history[n]) for n, ref in args.pairs]
188 except GitError as e:
189 print(f"merge_check: {e}", file=sys.stderr)
190 return 2
191 if args.json:
192 print(json.dumps(results, indent=2))
193 else:
194 for r in results:
195 c = r["commits"]
196 print(f"#{r['pr']} {r['verdict']}: {c['on_main']}/{c['total']} commit(s) already on main"
197 + (", merged tree matches main"
198 if r["verdict"] == "already-merged" and c["on_main"] != c["total"] else "")
199 + (f", merged before at {', '.join(r['merges'])}" if r["merges"] else "")
200 + (", conflicts" if r["conflict"] else ""))
201 for path, n in sorted(r["duplicates"].items()):
202 note = "" if path.lower().endswith(TEXT_SUFFIXES) else " (code: listed, not counted)"
203 print(f" {path}: {n} added line(s) already there in the same order{note}, "
204 f"e.g. {r['duplicate_samples'][path][0][:90]!r}")
205 return 0 if all(r["verdict"] == "clean" for r in results) else 1
206
207
208if __name__ == "__main__":
209 try:
210 sys.stdout.reconfigure(errors="replace")
211 except (AttributeError, ValueError, OSError):
212 pass
213 sys.exit(main())
diff --git a/scripts/run_conservative_tier3_reference.ps1 b/scripts/run_conservative_tier3_reference.ps1
new file mode 100644
index 000000000..86d043b76
--- /dev/null
+++ b/scripts/run_conservative_tier3_reference.ps1
@@ -0,0 +1,31 @@
1param(
2 [string]$Device = ""
3)
4$ErrorActionPreference = "Stop"
5
6$root = Split-Path $PSScriptRoot -Parent
7$runtime = Join-Path $root "runtime"
8$build = Join-Path $runtime "build\tier3-reference"
9
10& cmake -S $runtime -B $build -G "Visual Studio 17 2022" -A x64 -DLEONIDA_VULKAN_HEADERS_FETCH=ON
11if ($LASTEXITCODE -ne 0) { throw "CMake configure failed ($LASTEXITCODE)." }
12
13& cmake --build $build --config RelWithDebInfo --target d3d12_conservative_tier3_reference_test
14if ($LASTEXITCODE -ne 0) { throw "Building the Tier 3 reference test failed ($LASTEXITCODE)." }
15
16$previousFilter = $env:LEONIDA_VK_DEVICE
17try {
18 if ([string]::IsNullOrWhiteSpace($Device)) {
19 if (Test-Path Env:LEONIDA_VK_DEVICE) { Remove-Item Env:LEONIDA_VK_DEVICE }
20 } else {
21 $env:LEONIDA_VK_DEVICE = $Device
22 }
23 & ctest --test-dir $build -C RelWithDebInfo -R d3d12_conservative_tier3_reference --output-on-failure -V
24 if ($LASTEXITCODE -ne 0) { throw "The Tier 3 reference test failed ($LASTEXITCODE)." }
25} finally {
26 if ($null -eq $previousFilter) {
27 if (Test-Path Env:LEONIDA_VK_DEVICE) { Remove-Item Env:LEONIDA_VK_DEVICE }
28 } else {
29 $env:LEONIDA_VK_DEVICE = $previousFilter
30 }
31}
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 1a0bab1d5..1f9d9fa7f 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -25,29 +25,33 @@ sys.path.insert(0, os.path.join(ROOT, "tools"))
25import mc_command # noqa: E402 25import mc_command # noqa: E402
26sys.path.insert(0, SHADER_DIR) 26sys.path.insert(0, SHADER_DIR)
27from build import CLIP_CASES, clip_container, shader_source 27from build import CLIP_CASES, clip_container, shader_source
28from check import (Skip, clip_test, fmt_1010102_test, fmt_int_narrow_test, fmt_sint32_test, fmt_xy_xyz_test, 28from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test,
29 tbuffer_store_test) 29 fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported)
30from compute_fixture import compute_header 30from compute_fixture import compute_header
31from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) 31from check import SAMPLER_CASES, sampler_test
32from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, GATHER_LOD_TEST, GRADIENT_TESTS, 32from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS,
33 IMAGE_STORE_CASES, MIP_TEST_PASSES, SIGNED_MIP_TEST, TEST_PROGRAMS, TEXTURE_CONSTANTS, 33 GATHER_LOD_TEST, GRADIENT_TESTS, IMAGE_STORE_CASES, MIP_TEST_PASSES, SIGNED_MIP_TEST,
34 TEXTURE_MIP_DEPENDENCIES, TEXTURE_MIP_TEST, USER_SGPRS_ENV, USER_SGPRS_WORDS, mesh_v5_test, 34 UINT_MIP_TEST, TEST_PROGRAMS, TEXTURE_CONSTANTS, TEXTURE_MIP_DEPENDENCIES,
35 not_found_message, pick_build_dir, start_failure, texture_gradient_a16_test, texture_mip_test, 35 TEXTURE_MIP_TEST, USER_SGPRS_ENV, USER_SGPRS_WORDS, mesh_v5_test,
36 texture_uav_test) 36 not_found_message, pick_build_dir, start_failure, table_fetch_test,
37 texture_gradient_a16_test, texture_mip_test, texture_uav_test)
37from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT 38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT
38from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) 39from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan)
39from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py 40from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py
40from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 41from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8
41from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT) 42from check import gpu_test_timeout, timed_out # per-program time limit (LEONIDA_GPU_TEST_TIMEOUT)
43from check import failure # "exit <status>: <last lines>", check.py's detail for a program that exited non-zero
42from check import run_readback 44from check import run_readback
43from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS 45from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS
44from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, 46from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip,
45 unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py 47 unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py
46from check import PIXEL_VERTEX, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks 48from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks
47from check import barycentric_problem 49from check import barycentric_problem
50from check import NAN_PAYLOAD_TEST, nan_payload_problem
48from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries 51from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries
49from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide 52from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide
50from check import FMA_FUSED_ENV, judge_fma_fused # cs_fma_fused: strict under LEONIDA_FMA=khr, fused/split under glsl 53from check import FMA_FUSED_ENV, judge_fma_fused # cs_fma_fused: strict under LEONIDA_FMA=khr, fused/split under glsl
54from check import bary_persp_problem # ps_persp_bary's perspective-correct reference
51 55
52 56
53def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes: 57def make_dxbc(chunks: list[tuple[bytes, bytes]]) -> bytes:
@@ -126,7 +130,25 @@ def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None:
126 f.write("\n".join(lines) + "\n") 130 f.write("\n".join(lines) + "\n")
127 131
128 132
129def spirv_as(asm_text: str, out_spv: str) -> None: 133def resolve_assembler(choice: str) -> str:
134 """Resolve --assembler choice ('auto', 'spirv-as', or 'python') to a concrete assembler name."""
135 if choice in ("spirv-as", "python"):
136 return choice
137 if choice == "auto":
138 return "spirv-as" if shutil.which("spirv-as") else "python"
139 raise ValueError(f"unknown assembler: {choice!r}")
140
141
142def spirv_as(asm_text: str, out_spv: str, assembler: str = "spirv-as") -> None:
143 if assembler == "python":
144 import spirv_asm
145 try:
146 spv_bytes = spirv_asm.assemble(asm_text, target_env="vulkan1.2")
147 except spirv_asm.SpirvAsmError as exc:
148 raise RuntimeError(f"spirv_asm failed for {out_spv}:\n{exc}") from None
149 with open(out_spv, "wb") as f:
150 f.write(spv_bytes)
151 return
130 p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], 152 p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"],
131 input=asm_text, capture_output=True, text=True) 153 input=asm_text, capture_output=True, text=True)
132 if p.returncode != 0: 154 if p.returncode != 0:
@@ -245,6 +267,29 @@ def unsupported_skip(msg: str) -> str:
245 return f"SKIP ({m.group(0) if m else 'unsupported device'})" 267 return f"SKIP ({m.group(0) if m else 'unsupported device'})"
246 268
247 269
270def verdict_line(rc: int, msg: str) -> str:
271 """The detail of a row whose test program judges itself and prints its verdict last: that line. A program that
272 exited non-zero gets its exit status in front, as in check.py, so one that died before its verdict (exit -11 on
273 Linux, 3221225477 = 0xC0000005 on Windows) does not read as a FAIL with only its device or extension line, or
274 with no detail at all."""
275 return failure(rc, msg, 1) if rc else msg.splitlines()[-1] if msg else ""
276
277
278def helper_result(rc: int, msg: str) -> tuple[bool | None, str]:
279 """(ok, detail) for a helper that judges its own output (vk_store_test): 77 is a SKIP that names the missing
280 feature, not a failure (TEST-469); otherwise the exit code decides and verdict_line gives the detail."""
281 if rc == UNSUPPORTED:
282 return None, unsupported_skip(msg)
283 return rc == 0, verdict_line(rc, msg)
284
285
286def compute_result(rc: int, msg: str, ok: bool, detail: str) -> tuple[bool | None, str]:
287 """(ok, detail) for a vk_compute_test run the caller judges itself, unless the module needs a feature the device
288 lacks (check.compute_unsupported: exit 77 with an "unsupported: ..." line), which is a SKIP quoting it."""
289 skip = compute_unsupported(rc, msg)
290 return (None, skip) if skip else (ok, detail)
291
292
248def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *, 293def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *,
249 cwd: str | None = None) -> tuple[int, str]: 294 cwd: str | None = None) -> tuple[int, str]:
250 # A hung GPU test program fails its test instead of stalling the suite (check.py, LEONIDA_GPU_TEST_TIMEOUT). 295 # A hung GPU test program fails its test instead of stalling the suite (check.py, LEONIDA_GPU_TEST_TIMEOUT).
@@ -260,10 +305,15 @@ def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *,
260 305
261 306
262def bary_fallback() -> bool: 307def bary_fallback() -> bool:
263 """LEONIDA_BARY_FALLBACK=1: pixel shaders that read raw barycentrics are translated with --bary-fallback and drawn 308 """LEONIDA_BARY_FALLBACK=1 (or 0): translate raw barycentrics to an ordinary vec3 input and draw it through
264 through their pass-through geometry shader (tools/bary_fallback_gs.py), so they run on a device without 309 tools/bary_fallback_gs.py. Unset, it is on where tools/vk_subgroup_info.py reports a driver with a known
265 VK_KHR_fragment_shader_barycentric (NVIDIA Pascal, for one).""" 310 BaryCoordKHR bug: Mesa ANV (SHADER-925) and AMD's Windows driver on gfx90c iGPUs (#5933)."""
266 return (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() in ("1", "true", "yes", "on") 311 v = (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower()
312 if v in ("1", "true", "yes", "on"):
313 return True
314 if v in ("0", "false", "no", "off"):
315 return False
316 return _device_barycentric_fallback() is True
267 317
268 318
269def f16_interp_fallback() -> bool: 319def f16_interp_fallback() -> bool:
@@ -279,6 +329,7 @@ def f16_interp_fallback() -> bool:
279 329
280 330
281_PER_VERTEX = [] 331_PER_VERTEX = []
332_BARYCENTRIC_FALLBACK = []
282 333
283 334
284def _device_per_vertex(): 335def _device_per_vertex():
@@ -295,6 +346,21 @@ def _device_per_vertex():
295 return _PER_VERTEX[0] 346 return _PER_VERTEX[0]
296 347
297 348
349def _device_barycentric_fallback():
350 """barycentric_fallback from tools/vk_subgroup_info.py (Mesa ANV, SHADER-925; AMD Windows on gfx90c, #5933),
351 cached per suite."""
352 if not _BARYCENTRIC_FALLBACK:
353 answer = None
354 try:
355 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")],
356 capture_output=True, text=True, timeout=60)
357 answer = json.loads(r.stdout.strip().splitlines()[-1]).get("barycentric_fallback")
358 except (OSError, ValueError, IndexError, subprocess.SubprocessError):
359 pass
360 _BARYCENTRIC_FALLBACK.append(answer)
361 return _BARYCENTRIC_FALLBACK[0]
362
363
298def w64_emulated() -> bool: 364def w64_emulated() -> bool:
299 # Wave64 emulation on: the suite runs every wave64 check without asking for a 64-wide 365 # Wave64 emulation on: the suite runs every wave64 check without asking for a 64-wide
300 # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates 366 # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates
@@ -311,11 +377,13 @@ def wavemask_check(vk_compute: str, spv: str, env: dict | None, emulated: bool)
311 --wave64-emulate and runs on any subgroup size, so it asks for none.""" 377 --wave64-emulate and runs on any subgroup size, so it asks for none."""
312 cmd = [vk_compute, spv, "1", "wavemask"] + ([] if emulated else ["--require-wave64"]) 378 cmd = [vk_compute, spv, "1", "wavemask"] + ([] if emulated else ["--require-wave64"])
313 rc, msg = run_cmd(cmd, env=env) 379 rc, msg = run_cmd(cmd, env=env)
380 if skip := compute_unsupported(rc, msg):
381 return None, skip
314 if not emulated and rc == 77: 382 if not emulated and rc == 77:
315 return None, "SKIP (no 64-wide compute subgroup on this device)" 383 return None, "SKIP (no 64-wide compute subgroup on this device)"
316 if not emulated and rc == 0 and "compute subgroup size: 64" not in msg.splitlines(): 384 if not emulated and rc == 0 and "compute subgroup size: 64" not in msg.splitlines():
317 return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)" 385 return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)"
318 return rc == 0, msg.splitlines()[-1] if msg else "" 386 return rc == 0, verdict_line(rc, msg)
319def dump_words(msg: str) -> list[int] | None: 387def dump_words(msg: str) -> list[int] | None:
320 """The eight words of vk_compute_test's "out[0..7] = ..." line, or None unless it is eight decimal words (as in 388 """The eight words of vk_compute_test's "out[0..7] = ..." line, or None unless it is eight decimal words (as in
321 check.py): trailing text, a missing word or a non-number is a malformed dump, not a result.""" 389 check.py): trailing text, a missing word or a non-number is a malformed dump, not a result."""
@@ -345,6 +413,10 @@ def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial:
345 wave64: it was run with --require-wave64, so exit 77 is a skip and the 64-wide confirmation must be printed. 413 wave64: it was run with --require-wave64, so exit 77 is a skip and the 64-wide confirmation must be printed.
346 partial: a group smaller than a wave, run at subgroup size 64 without full subgroups; skipped when the device 414 partial: a group smaller than a wave, run at subgroup size 64 without full subgroups; skipped when the device
347 reports no subgroup size of 64. emulated: translated with --wave64-emulate, runs on any subgroup size.""" 415 reports no subgroup size of 64. emulated: translated with --wave64-emulate, runs on any subgroup size."""
416 if rc == 77: # the program refused the module and said why ("unsupported: <why>"): a skip with that reason, in every mode
417 why = next((ln for ln in msg.splitlines() if ln.startswith("unsupported:")), None)
418 if why:
419 return None, "SKIP (" + why[len("unsupported:"):].strip() + ")"
348 no64 = partial and not emulated and not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg)) 420 no64 = partial and not emulated and not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))
349 if (wave64 and rc == 77) or (no64 and rc == 0): 421 if (wave64 and rc == 77) or (no64 and rc == 0):
350 return None, "SKIP (no 64-wide compute subgroup on this device)" 422 return None, "SKIP (no 64-wide compute subgroup on this device)"
@@ -390,8 +462,6 @@ def check_bitmask_perm(raw_path: str, msg: str = "") -> tuple[bool | None, str]:
390 first = "" 462 first = ""
391 judged = 0 463 judged = 0
392 for i, (lane, v1, v2, v3) in enumerate(px): 464 for i, (lane, v1, v2, v3) in enumerate(px):
393 if lane >= 32: # wave32 test: in a 64-wide subgroup lanes 32-63 hold values it never wrote
394 continue
395 judged += 1 465 judged += 1
396 w1 = lane ^ 9 466 w1 = lane ^ 9
397 w2 = ((lane & 5) | 16) ^ 1 467 w2 = ((lane & 5) | 16) ^ 1
@@ -399,7 +469,7 @@ def check_bitmask_perm(raw_path: str, msg: str = "") -> tuple[bool | None, str]:
399 if not bad: 469 if not bad:
400 first = f"at ({i%64},{i//64}) lane={lane}: got ({v1},{v2},{v3}), want ({w1},{w2},0)" 470 first = f"at ({i%64},{i//64}) lane={lane}: got ({v1},{v2},{v3}), want ({w1},{w2},0)"
401 bad += 1 471 bad += 1
402 return (bad == 0 and judged > 0), (first if bad else f"{judged}/{judged} pixels in lanes 0-31 exact") 472 return (bad == 0 and judged > 0), (first if bad else f"{judged}/{judged} pixels exact")
403 473
404 474
405# Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as 475# Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as
@@ -412,19 +482,33 @@ PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x1
412 "0x1028=0x1,0x102c=0,0x1030=0x7,0x1034=0x80000000,0x1038=0x7,0x103c=0," 482 "0x1028=0x1,0x102c=0,0x1030=0x7,0x1034=0x80000000,0x1038=0x7,0x103c=0,"
413 "0x1040=0x1,0x1044=0x5,0x1048=0x80000000,0x104c=0x5,0x1050=0x7,0x1054=0x5," 483 "0x1040=0x1,0x1044=0x5,0x1048=0x80000000,0x104c=0x5,0x1050=0x7,0x1054=0x5,"
414 "0x1058=0x7,0x105c=0x5"}, 484 "0x1058=0x7,0x105c=0x5"},
485 # 32-bit integer compares: operands from memory (derivations in the .asm header)
486 "ps_vcmp_int32": {"VKH_SGPRS": "0x1000,0,32,0",
487 "VKH_HEAP": "0x1000=0x1,0x1004=0,0x1008=0x80000000,0x100c=0x12345678,0x1010=0x3,"
488 "0x1014=0x5,0x1018=0,0x101c=0"},
415 # float NaN / fract rows measured on RDNA2 hardware (see the .asm headers) 489 # float NaN / fract rows measured on RDNA2 hardware (see the .asm headers)
416 "ps_fnan_med3": {"VKH_SGPRS": "0x1000,0,32,0", 490 "ps_fnan_med3": {"VKH_SGPRS": "0x1000,0,32,0",
417 "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x40e00000,0x1008=0x40a00000," 491 "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x40e00000,0x1008=0x40a00000,"
418 "0x100c=0x7fc10001,0x1010=0x40600000,0x1014=0xc0200000"}, 492 "0x100c=0x7fc10001,0x1010=0x40600000,0x1014=0xc0200000"},
419 "ps_fnan_fract": {"VKH_SGPRS": "0x1000,0,16,0", 493 "ps_fnan_fract": {"VKH_SGPRS": "0x1000,0,16,0",
420 "VKH_HEAP": "0x1000=0xaedbe6ff,0x1004=0x00008800,0x1008=0x7fc10001,0x100c=0xc0200000"}, 494 "VKH_HEAP": "0x1000=0xaedbe6ff,0x1004=0x00008800,0x1008=0x7fc10001,0x100c=0xc0200000"},
495 "ps_fnan_med3_s2": {"VKH_SGPRS": "0x1000,0,16,0",
496 "VKH_HEAP": "0x1000=0x40a00000,0x1004=0x40e00000,0x1008=0x7fc10001,0x100c=0xc0200000"},
497 "ps_f16_fnan_med3": {"VKH_SGPRS": "0x1000,0,16,0",
498 "VKH_HEAP": "0x1000=0x00004500,0x1004=0x00004700,0x1008=0x00007e01,0x100c=0x0000c100"},
421 # f32 VOPC with a NaN, 64-bit integer VOPC: inputs from memory (derivations in the .asm headers) 499 # f32 VOPC with a NaN, 64-bit integer VOPC: inputs from memory (derivations in the .asm headers)
422 "ps_vcmp_f32_nan": {"VKH_SGPRS": "0x1000,0,16,0", 500 "ps_vcmp_f32_nan": {"VKH_SGPRS": "0x1000,0,16,0",
423 "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x3f800000,0x1008=0x40000000"}, 501 "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x3f800000,0x1008=0x40000000"},
424 "ps_vcmp_64": {"VKH_SGPRS": "0x1000,0,64,0", 502 "ps_vcmp_64": {"VKH_SGPRS": "0x1000,0,64,0",
425 "VKH_HEAP": "0x1000=0x80000000,0x1004=0,0x1008=1,0x100c=0,0x1010=0xffffffff," 503 "VKH_HEAP": "0x1000=0x80000000,0x1004=0,0x1008=1,0x100c=0,0x1010=0xffffffff,"
426 "0x1014=0xffffffff,0x1018=1,0x101c=0,0x1020=1,0x1024=0,0x1028=0x80000000," 504 "0x1014=0xffffffff,0x1018=1,0x101c=0,0x1020=1,0x1024=0,0x1028=0x80000000,"
427 "0x102c=0,0x1030=7,0x1034=5,0x1038=7,0x103c=5"}} 505 "0x102c=0,0x1030=7,0x1034=5,0x1038=7,0x103c=5"},
506 # the ps_vint_* integer fixtures share one heap, h0..h7 (see their .asm headers)
507 "ps_vint_logic3": VINT_ENV,
508 "ps_vint_bits": VINT_ENV,
509 "ps_vint_mul24": VINT_ENV,
510 "ps_vint_minmax": VINT_ENV,
511 "ps_vint_minmax3": VINT_ENV}
428 512
429 513
430def check_flat(raw_path: str) -> tuple[bool, str]: 514def check_flat(raw_path: str) -> tuple[bool, str]:
@@ -572,18 +656,19 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_transl
572 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", 656 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test",
573 "ps_m3_post": "d3d12_m3_frame_test", "ps_m3_query": "d3d12_m3_frame_test", 657 "ps_m3_post": "d3d12_m3_frame_test", "ps_m3_query": "d3d12_m3_frame_test",
574 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", 658 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test",
575 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test"} 659 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test",
660 "ps_live_width": "w64_graphics.py"}
576 661
577 662
578# Shaders a selected test draws with, built even when the filter leaves them out (#192). 663# Shaders a selected test draws with, built even when the filter leaves them out (#192).
579DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm", 664DRAWN_WITH = {GATHER_LOD_TEST: "vs_ids.asm", "ps_flat": "vs_ids.asm", "ps_persp_bary": "vs_persp.asm", "ps_texture_sample": "vs_ids.asm", "ps_cube_sample": "vs_ids.asm",
580 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm", 665 "ps_texture_sample_d16": "vs_ids.asm", "ps_sample_c_lz": "vs_ids.asm", "ps_sample_c_lz_a16": "vs_ids.asm",
581 "ps_sample_c": "vs_ids.asm", "ps_sample_c_b": "vs_ids.asm", 666 "ps_table_fetch": "vs_ids.asm", "ps_sample_c": "vs_ids.asm", "ps_sample_c_b": "vs_ids.asm",
582 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm", 667 **{name: "vs_ids.asm" for name in TEXTURE_CONSTANTS}, "ps_ssharp": "vs_ids.asm", "ps_imgatomic": "vs_ids.asm",
583 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm", 668 **{name: "vs_ids.asm" for name in GRADIENT_TESTS}, "vs_clip": "ps_clip_color.asm",
584 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm", 669 "ps_interp_f16_high": "vs_f16_pack.asm", "ms_f16_pack": "ps_interp_f16_high.asm",
585 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm", 670 "ps_interp_f32_mods": "vs_interp_consts.asm", "ps_interp_mov_mods": "vs_interp_consts.asm",
586 SIGNED_MIP_TEST: "vs_ids.asm", 671 SIGNED_MIP_TEST: "vs_ids.asm", UINT_MIP_TEST: "vs_ids.asm",
587 "vs_base_ids": "ps_flat.asm"} 672 "vs_base_ids": "ps_flat.asm"}
588DRAWN_WITH.update({name: "vs_ids.asm" for name in GET_LOD_TESTS}) 673DRAWN_WITH.update({name: "vs_ids.asm" for name in GET_LOD_TESTS})
589 674
@@ -654,12 +739,26 @@ def main() -> int:
654 ap.add_argument("--work", default=None) 739 ap.add_argument("--work", default=None)
655 ap.add_argument("--filter", default="") 740 ap.add_argument("--filter", default="")
656 ap.add_argument("--require-pass", action="store_true", help="exit 1 if no GPU test passes") 741 ap.add_argument("--require-pass", action="store_true", help="exit 1 if no GPU test passes")
742 ap.add_argument("--assembler", choices=("auto", "spirv-as", "python"), default="auto",
743 help="SPIR-V assembler: auto (use spirv-as if on PATH, else tools/spirv_asm.py), "
744 "spirv-as, or python")
745 ap.add_argument("--no-validate", action="store_true",
746 help="skip spirv-val during translation (automatic when --assembler resolves to python "
747 "and spirv-val is not on PATH)")
748 ap.add_argument("--disasm-dir", default=None,
749 help="folder of pre-disassembled <name>.s listings (e.g. tests/semantic/fixtures/disasm); "
750 "skips llvm-mc and runs only fixtures present there")
657 a = ap.parse_args() 751 a = ap.parse_args()
658 # Some test programs run with their working directory in <work>/spirv (vk_texture_test), so a relative path 752 # Some test programs run with their working directory in <work>/spirv (vk_texture_test), so a relative path
659 # given here would point somewhere else for them. 753 # given here would point somewhere else for them.
660 a.build = os.path.abspath(a.build) 754 a.build = os.path.abspath(a.build)
661 if a.work: 755 if a.work:
662 a.work = os.path.abspath(a.work) 756 a.work = os.path.abspath(a.work)
757 if a.disasm_dir is not None:
758 a.disasm_dir = os.path.abspath(a.disasm_dir)
759 if not os.path.isdir(a.disasm_dir):
760 print(f"error: --disasm-dir is not a directory: {a.disasm_dir}", file=sys.stderr)
761 return 2
663 762
664 ext = ".exe" if os.name == "nt" else "" 763 ext = ".exe" if os.name == "nt" else ""
665 required = tuple(t + ext for t in TEST_PROGRAMS) 764 required = tuple(t + ext for t in TEST_PROGRAMS)
@@ -687,7 +786,11 @@ def main() -> int:
687 786
688 work = a.work or tempfile.mkdtemp(prefix="leonida_gpu_tests_") 787 work = a.work or tempfile.mkdtemp(prefix="leonida_gpu_tests_")
689 try: 788 try:
690 os.makedirs(work, exist_ok=True) 789 try:
790 os.makedirs(work, exist_ok=True)
791 except OSError as exc: # the same report run_suite gives for its own folders (#4544)
792 print(f"error: cannot prepare GPU test directory {work}: {exc.strerror or exc}", file=sys.stderr)
793 return 2
691 native = native_folder(work) 794 native = native_folder(work)
692 if native is None: 795 if native is None:
693 print(f"error: the work folder {ascii(work)} has characters outside this PC's ANSI code page and no 8.3 " 796 print(f"error: the work folder {ascii(work)} has characters outside this PC's ANSI code page and no 8.3 "
@@ -712,10 +815,24 @@ W64_GRAPHICS_ONLY = _w64_graphics_only()
712 815
713 816
714def run_suite(a, work: str) -> int: 817def run_suite(a, work: str) -> int:
818 assembler = resolve_assembler(getattr(a, "assembler", "auto"))
819 explicit_no_validate = bool(getattr(a, "no_validate", False))
820 no_validate = explicit_no_validate or (assembler == "python" and shutil.which("spirv-val") is None)
821 disasm_src = getattr(a, "disasm_dir", None)
822
715 asm_files = sorted({f for f in os.listdir(SHADER_DIR) if f.endswith(".asm")} | {n + ".asm" for n in CLIP_CASES}) 823 asm_files = sorted({f for f in os.listdir(SHADER_DIR) if f.endswith(".asm")} | {n + ".asm" for n in CLIP_CASES})
716 # The wave64 pixel fixtures of runtime/test/shaders/w64_graphics.py (tiers A-C, #1541) are checked by that 824 # The wave64 pixel fixtures of runtime/test/shaders/w64_graphics.py (tiers A-C, #1541) are checked by that
717 # runner, not here: they need a 64-wide fragment subgroup or the halves-aware lowering it drives. 825 # runner, not here: they need a 64-wide fragment subgroup or the halves-aware lowering it drives.
718 asm_files = [f for f in asm_files if f[:-4] not in W64_GRAPHICS_ONLY] 826 asm_files = [f for f in asm_files if f[:-4] not in W64_GRAPHICS_ONLY]
827 if disasm_src is not None:
828 available = {os.path.splitext(f)[0] for f in os.listdir(disasm_src) if f.endswith(".s")}
829 asm_files = [
830 f for f in asm_files
831 if all(os.path.splitext(p)[0] in available for p in with_draw_shaders([f]))
832 ]
833 if not asm_files:
834 print(f"error: --disasm-dir {disasm_src!r} matched no GPU test cases", file=sys.stderr)
835 return 2
719 if a.filter: 836 if a.filter:
720 asm_files = [f for f in asm_files if a.filter in f] 837 asm_files = [f for f in asm_files if a.filter in f]
721 if not asm_files: 838 if not asm_files:
@@ -727,8 +844,12 @@ def run_suite(a, work: str) -> int:
727 disasm_dir = os.path.join(work, "disasm") 844 disasm_dir = os.path.join(work, "disasm")
728 spirv_dir = os.path.join(work, "spirv") 845 spirv_dir = os.path.join(work, "spirv")
729 raw_dir = os.path.join(work, "raw") 846 raw_dir = os.path.join(work, "raw")
730 for d in (fssm_dir, disasm_dir, spirv_dir, raw_dir): 847 for directory in (work, fssm_dir, disasm_dir, spirv_dir, raw_dir):
731 os.makedirs(d, exist_ok=True) 848 try:
849 os.makedirs(directory, exist_ok=True)
850 except OSError as exc:
851 print(f"error: cannot prepare GPU test directory {directory}: {exc.strerror or exc}", file=sys.stderr)
852 return 2
732 853
733 # 1. Create synthetic DXBC / FSSM metadata + assemble .asm -> .s 854 # 1. Create synthetic DXBC / FSSM metadata + assemble .asm -> .s
734 disasm_files = [] 855 disasm_files = []
@@ -760,7 +881,14 @@ def run_suite(a, work: str) -> int:
760 f.write(compute_header(os.path.join(SHADER_DIR, fname))) 881 f.write(compute_header(os.path.join(SHADER_DIR, fname)))
761 fname = shader_source(name) + ".asm" 882 fname = shader_source(name) + ".asm"
762 disasm_path = os.path.join(disasm_dir, f"{name}.s") 883 disasm_path = os.path.join(disasm_dir, f"{name}.s")
763 assemble_to_s(a.llvm_mc, os.path.join(SHADER_DIR, fname), disasm_path, name) 884 if disasm_src is not None:
885 try:
886 shutil.copyfile(os.path.join(disasm_src, f"{name}.s"), disasm_path)
887 except shutil.SameFileError:
888 # A replay can use the work folder's existing listings as its source.
889 pass
890 else:
891 assemble_to_s(a.llvm_mc, os.path.join(SHADER_DIR, fname), disasm_path, name)
764 disasm_files.append(disasm_path) 892 disasm_files.append(disasm_path)
765 # A failed translation must not run an old binary left in a reused --work directory. 893 # A failed translation must not run an old binary left in a reused --work directory.
766 Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) 894 Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True)
@@ -770,6 +898,12 @@ def run_suite(a, work: str) -> int:
770 for path in disasm_files: 898 for path in disasm_files:
771 shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path))) 899 shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path)))
772 cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir] 900 cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir]
901 if assembler == "python":
902 cmd += ["--assembler", "python"]
903 if no_validate:
904 if not explicit_no_validate:
905 print("note: spirv-val not found on PATH; translating with --no-validate", flush=True)
906 cmd.append("--no-validate")
773 if w64_emulated(): # wave64 compute/mesh exact on any subgroup size 907 if w64_emulated(): # wave64 compute/mesh exact on any subgroup size
774 cmd.append("--wave64-emulate") 908 cmd.append("--wave64-emulate")
775 if bary_fallback(): # raw barycentrics from an interpolated input, fed by a pass-through GS 909 if bary_fallback(): # raw barycentrics from an interpolated input, fed by a pass-through GS
@@ -803,9 +937,9 @@ def run_suite(a, work: str) -> int:
803 vs_tri = os.path.join(spirv_dir, "vs_tri.spv") 937 vs_tri = os.path.join(spirv_dir, "vs_tri.spv")
804 fs_passthru = os.path.join(spirv_dir, "fs_passthru.spv") 938 fs_passthru = os.path.join(spirv_dir, "fs_passthru.spv")
805 fs_loc1 = os.path.join(spirv_dir, "fs_loc1.spv") 939 fs_loc1 = os.path.join(spirv_dir, "fs_loc1.spv")
806 spirv_as(VS_TRI_SPVASM, vs_tri) 940 spirv_as(VS_TRI_SPVASM, vs_tri, assembler=assembler)
807 spirv_as(make_fs_passthru(0), fs_passthru) 941 spirv_as(make_fs_passthru(0), fs_passthru, assembler=assembler)
808 spirv_as(make_fs_passthru(1), fs_loc1) 942 spirv_as(make_fs_passthru(1), fs_loc1, assembler=assembler)
809 943
810 index = {} 944 index = {}
811 idx_path = os.path.join(spirv_dir, "index.json") 945 idx_path = os.path.join(spirv_dir, "index.json")
@@ -841,16 +975,17 @@ def run_suite(a, work: str) -> int:
841 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) 975 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact"))
842 elif name == "cs_workgroup_yz": 976 elif name == "cs_workgroup_yz":
843 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) 977 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env)
844 results.append((name, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" in msg.splitlines(), msg)) 978 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches"
979 in msg.splitlines(), msg))
845 elif name == "cs_lds": 980 elif name == "cs_lds":
846 rc, msg = run_cmd([vk_compute, spv, "4", "mirror64"], env=cs_env) 981 rc, msg = run_cmd([vk_compute, spv, "4", "mirror64"], env=cs_env)
847 results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) 982 results.append((name,) + compute_result(rc, msg, rc == 0, verdict_line(rc, msg)))
848 elif name == "cs_exec64": 983 elif name == "cs_exec64":
849 rc, msg = run_cmd([vk_compute, spv, "1", "exec64"], env=cs_env) 984 rc, msg = run_cmd([vk_compute, spv, "1", "exec64"], env=cs_env)
850 results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) 985 results.append((name,) + compute_result(rc, msg, rc == 0, verdict_line(rc, msg)))
851 elif name in ("cs_bvh", "cs_bvh32"): # the 64-bit and the 32-bit node pointer: one scene, the same words 986 elif name in ("cs_bvh", "cs_bvh32"): # the 64-bit and the 32-bit node pointer: one scene, the same words
852 rc, msg = run_cmd([vk_compute, spv, "1", "bvh"], env=cs_env) 987 rc, msg = run_cmd([vk_compute, spv, "1", "bvh"], env=cs_env)
853 results.append((name, rc == 0, msg.splitlines()[-1] if msg else "")) 988 results.append((name,) + compute_result(rc, msg, rc == 0, verdict_line(rc, msg)))
854 elif name in STORE_WORDS: 989 elif name in STORE_WORDS:
855 # TEST-184: image atomics (cs_imgatomic, cs_imgatomic3d) and image_get_resinfo (cs_resinfo). vk_store_test 990 # TEST-184: image atomics (cs_imgatomic, cs_imgatomic3d) and image_get_resinfo (cs_resinfo). vk_store_test
856 # binds the images and prints the r32 ones after the dispatch; the expected words are check.py's. 991 # binds the images and prints the r32 ones after the dispatch; the expected words are check.py's.
@@ -870,7 +1005,7 @@ def run_suite(a, work: str) -> int:
870 results.append((name, ok, problem or f"4096 pixels in each of {len(GET_LOD_TESTS[name])} draw(s): the " 1005 results.append((name, ok, problem or f"4096 pixels in each of {len(GET_LOD_TESTS[name])} draw(s): the "
871 "clamped and the calculated LOD within 1/16")) 1006 "clamped and the calculated LOD within 1/16"))
872 elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_smem_sconst_off", "cs_buf_tail", "cs_oob_select", "cs_oob_tail", 1007 elif name in ("cs_bounds", "cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_smem_sconst_off", "cs_buf_tail", "cs_oob_select", "cs_oob_tail",
873 "cs_buf_swizzle", "cs_cmpx_class_f32", "cs_cvt_pk_u8", "cs_buf_load_sub", "cs_buf_fmt8"): 1008 "cs_buf_swizzle", "cs_cmpx_class_f32", "cs_cvt_pk_u8", "cs_pk_mul_lo_const", "cs_buf_load_sub", "cs_buf_fmt8"):
874 # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds 1009 # num_records bounds check (cs_bounds.asm): the out-of-bounds store is dropped and the out-of-bounds
875 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. 1010 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement.
876 # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either. 1011 # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either.
@@ -894,14 +1029,15 @@ def run_suite(a, work: str) -> int:
894 0xBEEF0001], 1029 0xBEEF0001],
895 "cs_cmpx_class_f32": CMPX_CLASS_WORDS, 1030 "cs_cmpx_class_f32": CMPX_CLASS_WORDS,
896 "cs_cvt_pk_u8": CVT_PK_U8_WORDS, 1031 "cs_cvt_pk_u8": CVT_PK_U8_WORDS,
1032 "cs_pk_mul_lo_const": PK_MUL_LO_WORDS,
897 # TEST-510: sub-dword MUBUF loads (RAW end check by element size) and GFX10_FORMAT_8_UINT 1033 # TEST-510: sub-dword MUBUF loads (RAW end check by element size) and GFX10_FORMAT_8_UINT
898 "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], 1034 "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0],
899 "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], 1035 "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1],
900 }[name] 1036 }[name]
901 words = dump_words(msg) 1037 words = dump_words(msg)
902 vals = words[:len(want)] if words else [] 1038 vals = words[:len(want)] if words else []
903 results.append((name, rc == 0 and vals == want, 1039 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == want,
904 " ".join(hex(x) for x in vals) if vals else msg)) 1040 " ".join(hex(x) for x in vals) if vals else msg))
905 elif name == "cs_fmt_1010102": 1041 elif name == "cs_fmt_1010102":
906 problem = fmt_1010102_test(a.build, spirv_dir, cs_env) 1042 problem = fmt_1010102_test(a.build, spirv_dir, cs_env)
907 results.append((name, not problem, problem or "64/64 dumped words exact")) 1043 results.append((name, not problem, problem or "64/64 dumped words exact"))
@@ -923,11 +1059,14 @@ def run_suite(a, work: str) -> int:
923 problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) 1059 problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env)
924 results.append((name, not problem, problem or "80/80 dumped words exact")) 1060 results.append((name, not problem, problem or "80/80 dumped words exact"))
925 results.append((name, not problem, problem or "128/128 dumped words exact")) 1061 results.append((name, not problem, problem or "128/128 dumped words exact"))
926 elif name == "cs_global_neg_offset": 1062 elif name in ("cs_global_neg_offset", "cs_global_mem_ext"):
927 # Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups give a 0x2800-byte 1063 # Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups give a 0x2800-byte
928 # heap holding both the right addresses and the 4096-lower ones. One thread, no wave64 requirement. 1064 # heap holding both the right addresses and the 4096-lower ones. One thread, no wave64 requirement.
1065 # cs_global_mem_ext.asm: global/buffer atomics, 8/16-bit global stores and d16 loads in the same heap.
929 rc, msg = run_cmd([vk_compute, spv, "40", "dump"], env=cs_env) 1066 rc, msg = run_cmd([vk_compute, spv, "40", "dump"], env=cs_env)
930 want = [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 0x9E, 0xFFFF8BAD, 0x57023FFC, 0xEEEEEEEE] 1067 want = {"cs_global_neg_offset": [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, 0x9E, 0xFFFF8BAD,
1068 0x57023FFC, 0xEEEEEEEE],
1069 "cs_global_mem_ext": [0x5, 0xC, 0x977, 0xFFF00000, 0xEDCB5678, 0xEF332211, 0x887766BE, 0xFF801234]}[name]
931 ok, detail = judge_cs_dump(rc, msg, want, wave64=False, partial=False, emulated=False, hexwords=True) 1070 ok, detail = judge_cs_dump(rc, msg, want, wave64=False, partial=False, emulated=False, hexwords=True)
932 results.append((name, ok, detail)) 1071 results.append((name, ok, detail))
933 elif name == "cs_heap_init": 1072 elif name == "cs_heap_init":
@@ -935,36 +1074,56 @@ def run_suite(a, work: str) -> int:
935 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env())) 1074 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env()))
936 words = dump_words(msg) 1075 words = dump_words(msg)
937 vals = words[:len(HEAP_INIT_EXPECTED)] if words else [] 1076 vals = words[:len(HEAP_INIT_EXPECTED)] if words else []
938 results.append((name, rc == 0 and vals == HEAP_INIT_EXPECTED, 1077 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == HEAP_INIT_EXPECTED,
939 " ".join(hex(x) for x in vals) if vals else msg)) 1078 " ".join(hex(x) for x in vals) if vals else msg))
940 elif name == "cs_user_sgprs": 1079 elif name == "cs_user_sgprs":
941 # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. 1080 # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back.
942 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) 1081 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV))
943 words = dump_words(msg) 1082 words = dump_words(msg)
944 vals = words[:len(USER_SGPRS_WORDS)] if words else [] 1083 vals = words[:len(USER_SGPRS_WORDS)] if words else []
945 results.append((name, rc == 0 and vals == USER_SGPRS_WORDS, 1084 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS,
946 " ".join(hex(x) for x in vals) if vals else msg)) 1085 " ".join(hex(x) for x in vals) if vals else msg))
947 elif name == "cs_f64_add": 1086 elif name == "cs_f64_add":
948 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1087 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env)
949 if rc == 77: 1088 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names
950 results.append((name, None, "SKIP (no shaderFloat64 on this device)")) 1089 results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)"))
951 else: 1090 else:
952 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, 1091 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False,
953 hexwords=True) 1092 hexwords=True)
954 results.append((name, ok, detail)) 1093 results.append((name, ok, detail))
1094 elif name == "cs_div_fmas_f64":
1095 # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64,
1096 # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it.
1097 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env)
1098 if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64
1099 results.append((name, None, unsupported_skip(msg)))
1100 else:
1101 words = (dump_words(msg) or [])[:2] if rc == 0 else []
1102 strict = "shaderFmaFloat64" in ((index.get(name) or {}).get("features") or ())
1103 fused, split = [0, 0x3c300000], [0, 0]
1104 ok = rc == 0 and (words == fused or (not strict and words == split))
1105 detail = " ".join(hex(x) for x in words) if words else msg
1106 if ok and words == split:
1107 detail += " (split: the driver rounds GLSL Fma on doubles twice; --fma khr fixes it)"
1108 results.append((name, ok, detail))
955 elif name == "cs_cvt_f32_sat": 1109 elif name == "cs_cvt_f32_sat":
956 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). 1110 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS).
957 wrong = [] 1111 wrong, skip = [], None
958 for bits, unsigned, signed in CVT_F32_SAT_CASES: 1112 for bits, unsigned, signed in CVT_F32_SAT_CASES:
959 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], 1113 rc, msg = run_cmd([vk_compute, spv, "1", "dump"],
960 env=dict(cs_env or os.environ, VKC_SGPRS=f"{bits:#010x}")) 1114 env=dict(cs_env or os.environ, VKC_SGPRS=f"{bits:#010x}"))
1115 if skip := compute_unsupported(rc, msg): # the module, not this input: no other input can run either
1116 break
961 words = dump_words(msg) 1117 words = dump_words(msg)
962 if rc != 0 or not words or words[:2] != [unsigned, signed]: 1118 if rc != 0 or not words or words[:2] != [unsigned, signed]:
963 got = " ".join(hex(x) for x in words[:2]) if words else msg.splitlines()[-1] if msg else "no output" 1119 got = " ".join(hex(x) for x in words[:2]) if words else msg.splitlines()[-1] if msg else "no output"
964 wrong.append(f"{bits:#010x} gave {got}, want {unsigned:#x} {signed:#x}") 1120 wrong.append(f"{bits:#010x} gave {got}, want {unsigned:#x} {signed:#x}")
965 n = len(CVT_F32_SAT_CASES) 1121 n = len(CVT_F32_SAT_CASES)
966 results.append((name, not wrong, f"{n}/{n} inputs exact" if not wrong 1122 if skip:
967 else f"{len(wrong)}/{n} inputs wrong, first {wrong[0]}")) 1123 results.append((name, None, skip))
1124 else:
1125 results.append((name, not wrong, f"{n}/{n} inputs exact" if not wrong
1126 else f"{len(wrong)}/{n} inputs wrong, first {wrong[0]}"))
968 elif name == "cs_fma_fused": 1127 elif name == "cs_fma_fused":
969 # Single-rounded f32 FMA (+ f16 round-to-odd): strict under LEONIDA_FMA=khr (OpFmaKHR, exit 77 if 1128 # Single-rounded f32 FMA (+ f16 round-to-odd): strict under LEONIDA_FMA=khr (OpFmaKHR, exit 77 if
970 # unsupported), fused-or-split f32 allowed under default --fma glsl (e.g. Mesa RADV splits 5/7). 1129 # unsupported), fused-or-split f32 allowed under default --fma glsl (e.g. Mesa RADV splits 5/7).
@@ -974,14 +1133,23 @@ def run_suite(a, work: str) -> int:
974 elif rc != 0: 1133 elif rc != 0:
975 results.append((name, False, msg)) 1134 results.append((name, False, msg))
976 else: 1135 else:
977 khr = os.environ.get("LEONIDA_FMA") == "khr" 1136 # TEST-1147: judge by the mode the translator recorded in index.json, as check.py does.
978 ok, detail = judge_fma_fused(dump_words(msg), khr=khr) 1137 # --fma exact has no KHR capability, so capability/env alone used to accept split words here.
1138 meta = index.get("cs_fma_fused") or {}
1139 mode = meta.get("fma") or ""
1140 if mode:
1141 # The recorded mode wins over a stale LEONIDA_FMA, as in check.py.
1142 strict = mode in ("khr", "exact")
1143 else:
1144 strict = ("shaderFmaFloat32" in (meta.get("features") or ())
1145 or os.environ.get("LEONIDA_FMA") in ("khr", "exact"))
1146 ok, detail = judge_fma_fused(dump_words(msg), khr=strict)
979 results.append((name, ok, detail)) 1147 results.append((name, ok, detail))
980 elif name == "cs_wavemask": 1148 elif name == "cs_wavemask":
981 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. 1149 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none.
982 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. 1150 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size.
983 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) 1151 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated()))
984 elif name in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", 1152 elif name in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half",
985 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", 1153 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi",
986 "cs_dpp_bound", "cs_dpp_w64", 1154 "cs_dpp_bound", "cs_dpp_w64",
987 "cs_w64_mask_detect", 1155 "cs_w64_mask_detect",
@@ -1008,6 +1176,12 @@ def run_suite(a, work: str) -> int:
1008 # 64-bit scalar data ops and v_mad_u64_u32 (cs_w32_salu64.asm) 1176 # 64-bit scalar data ops and v_mad_u64_u32 (cs_w32_salu64.asm)
1009 # more ops with CPU-only checks until now (cs_w32_misc_ext.asm) 1177 # more ops with CPU-only checks until now (cs_w32_misc_ext.asm)
1010 # ops merged on 2026-11-22 with CPU-only checks (cs_w32_new_ops.asm) 1178 # ops merged on 2026-11-22 with CPU-only checks (cs_w32_new_ops.asm)
1179 # plain 8/16-bit MUBUF stores, one crossing a dword (cs_w32_buffer_store_sub.asm)
1180 "cs_w32_buffer_store_sub": [0x1122AB44, 0xCDEF7788, 0x34AABBCC, 0xDDDDDD12, 0x0102035A, 0x05061234, 0xAB, 0xFFFFCDEF],
1181 # 8/16-bit MUBUF d16 loads and stores (cs_w32_buffer_sub16.asm)
1182 "cs_w32_buffer_sub16": [0xBEEF00AA, 0x00AA1234, 0xBEEFFFAA, 0xFFAA1234, 0xBEEF8899, 0x88991234, 0x1122CD44, 0xABCD7788],
1183 # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm)
1184 "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000],
1011 "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], 1185 "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234],
1012 "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], 1186 "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D],
1013 "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], 1187 "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE],
@@ -1064,6 +1238,8 @@ def run_suite(a, work: str) -> int:
1064 "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 1238 "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32
1065 "cs_w32_andn2_exec": [1, 8, 16, 2064, 2068, 3, 20, 1544], # s_andn2_saveexec/wrexec_b32 (.asm header) 1239 "cs_w32_andn2_exec": [1, 8, 16, 2064, 2068, 3, 20, 1544], # s_andn2_saveexec/wrexec_b32 (.asm header)
1066 "cs_w32_sincos": [1, 1, 1, 1, 1, 1], # SHADER-88 (cs_w32_sincos.asm): angles in turns 1240 "cs_w32_sincos": [1, 1, 1, 1, 1, 1], # SHADER-88 (cs_w32_sincos.asm): angles in turns
1241 # SHADER-74: v_permlane16/x16 FI / BOUND_CTRL with the source lane off in EXEC (cs_w32_permlane_fi.asm)
1242 "cs_w32_permlane_fi": [1000, 0, 4, 1, 1000, 0, 52, 49],
1067 "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031], 1243 "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031],
1068 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], 1244 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32],
1069 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header) 1245 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header)
@@ -1095,7 +1271,7 @@ def run_suite(a, work: str) -> int:
1095 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", 1271 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop",
1096 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", 1272 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops",
1097 "cs_w32_lds_subdword", "cs_w32_lds_wide", 1273 "cs_w32_lds_subdword", "cs_w32_lds_wide",
1098 "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_sincos", 1274 "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap",
1099 "cs_lds_b64_cmpst", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", 1275 "cs_lds_b64_cmpst", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec",
1100 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", 1276 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8",
1101 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_w32_andn2_exec") and not emulated and not partial 1277 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_w32_andn2_exec") and not emulated and not partial
@@ -1104,7 +1280,13 @@ def run_suite(a, work: str) -> int:
1104 if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) 1280 if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774)
1105 cs_env = dict(os.environ, **WAVE32_LANE_ENV) 1281 cs_env = dict(os.environ, **WAVE32_LANE_ENV)
1106 rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) 1282 rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env)
1107 skip = wave32_lane_skip(msg) if name in WAVE32_LANE_DUMPS else None 1283 skip = None
1284 if name in WAVE32_LANE_DUMPS:
1285 if rc == UNSUPPORTED:
1286 results.append((name, None, unsupported_skip(msg)))
1287 continue
1288 if rc == 0:
1289 skip = wave32_lane_skip(msg)
1108 if skip is None and name in WAVE32_PIN_DUMPS: 1290 if skip is None and name in WAVE32_PIN_DUMPS:
1109 # the device may not be able to run the wave size this fixture was written for (a 64-only device 1291 # the device may not be able to run the wave size this fixture was written for (a 64-only device
1110 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too 1292 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too
@@ -1123,10 +1305,7 @@ def run_suite(a, work: str) -> int:
1123 results.append((name, ok, detail)) 1305 results.append((name, ok, detail))
1124 elif name in IMAGE_STORE_CASES: 1306 elif name in IMAGE_STORE_CASES:
1125 rc, msg = run_cmd([vk_store, spv, *IMAGE_STORE_CASES[name]]) 1307 rc, msg = run_cmd([vk_store, spv, *IMAGE_STORE_CASES[name]])
1126 if rc == UNSUPPORTED: 1308 results.append((name, *helper_result(rc, msg)))
1127 results.append((name, None, unsupported_skip(msg)))
1128 else:
1129 results.append((name, rc == 0, msg.splitlines()[-1] if msg else ""))
1130 elif name == "cs_texture_uav": 1309 elif name == "cs_texture_uav":
1131 problem = texture_uav_test(a.build, spv) 1310 problem = texture_uav_test(a.build, spv)
1132 results.append((name, None if isinstance(problem, Skip) else not problem, 1311 results.append((name, None if isinstance(problem, Skip) else not problem,
@@ -1135,6 +1314,10 @@ def run_suite(a, work: str) -> int:
1135 problem = texture_mip_test(a.build, spirv_dir, name) 1314 problem = texture_mip_test(a.build, spirv_dir, name)
1136 ok = None if isinstance(problem, Skip) else not problem 1315 ok = None if isinstance(problem, Skip) else not problem
1137 results.append((name, ok, problem or "two passes, 4096 RGBA32F pixels each exact; wrong mip and UV rejected")) 1316 results.append((name, ok, problem or "two passes, 4096 RGBA32F pixels each exact; wrong mip and UV rejected"))
1317 elif name == "ps_table_fetch":
1318 problem = table_fetch_test(a.build, spirv_dir)
1319 results.append((name, None if isinstance(problem, Skip) else not problem,
1320 problem or "4096 exact pixels each for SINT, UINT and descriptor miss"))
1138 elif name in GRADIENT_TESTS: 1321 elif name in GRADIENT_TESTS:
1139 problem = texture_gradient_a16_test(a.build, spirv_dir, name) 1322 problem = texture_gradient_a16_test(a.build, spirv_dir, name)
1140 ok = None if isinstance(problem, Skip) else not problem 1323 ok = None if isinstance(problem, Skip) else not problem
@@ -1158,7 +1341,7 @@ def run_suite(a, work: str) -> int:
1158 ok, detail = check_d16_texture(raw) 1341 ok, detail = check_d16_texture(raw)
1159 results.append((name, ok, detail)) 1342 results.append((name, ok, detail))
1160 else: 1343 else:
1161 results.append((name, rc == 0 and "PASSED" in msg, msg.splitlines()[-1] if msg else "")) 1344 results.append((name, rc == 0 and "PASSED" in msg, verdict_line(rc, msg)))
1162 elif name in TEXTURE_CONSTANTS: 1345 elif name in TEXTURE_CONSTANTS:
1163 expected = TEXTURE_CONSTANTS[name] 1346 expected = TEXTURE_CONSTANTS[name]
1164 tool = os.path.join(a.build, "vk_texture_test" + ext) 1347 tool = os.path.join(a.build, "vk_texture_test" + ext)
@@ -1172,8 +1355,10 @@ def run_suite(a, work: str) -> int:
1172 if rc == UNSUPPORTED: 1355 if rc == UNSUPPORTED:
1173 results.append((name, None, unsupported_skip(msg))) 1356 results.append((name, None, unsupported_skip(msg)))
1174 else: 1357 else:
1175 results.append((name, rc == 0 and bad == 0, "4096/4096 pixels exact" if bad == 0 else 1358 detail = ("4096/4096 pixels exact" if bad == 0 else
1176 f"{bad} pixels differ from {expected}: {msg.splitlines()[-1] if msg else ''}")) 1359 f"{bad} pixels differ from {expected}: {verdict_line(0, msg)}")
1360 # After a non-zero exit no frame was compared: the exit status, not a pixel count.
1361 results.append((name, rc == 0 and bad == 0, verdict_line(rc, msg) if rc else detail))
1177 elif name in ("ps_tex", "ps_imgatomic"): 1362 elif name in ("ps_tex", "ps_imgatomic"):
1178 # A texture through the descriptor hash table and the bindless set (ps_tex), or image atomics in a pixel 1363 # A texture through the descriptor hash table and the bindless set (ps_tex), or image atomics in a pixel
1179 # shader through the set's r32ui storage arrays (ps_imgatomic, drawn with vs_ids). vk_bindless_test 1364 # shader through the set's r32ui storage arrays (ps_imgatomic, drawn with vs_ids). vk_bindless_test
@@ -1185,7 +1370,7 @@ def run_suite(a, work: str) -> int:
1185 reason = next((ln for ln in lines if ln.startswith("unsupported:")), "unsupported device") 1370 reason = next((ln for ln in lines if ln.startswith("unsupported:")), "unsupported device")
1186 results.append((name, None, f"SKIP ({reason})")) 1371 results.append((name, None, f"SKIP ({reason})"))
1187 else: 1372 else:
1188 results.append((name, rc == 0, lines[-1] if lines else "")) 1373 results.append((name, rc == 0, verdict_line(rc, msg)))
1189 elif name == "ps_ssharp": 1374 elif name == "ps_ssharp":
1190 # The S#/T# mip fields through vulkan_sampler() and the view range (check.py's SAMPLER_CASES). 1375 # The S#/T# mip fields through vulkan_sampler() and the view range (check.py's SAMPLER_CASES).
1191 problem = sampler_test(a.build, spirv_dir) 1376 problem = sampler_test(a.build, spirv_dir)
@@ -1230,6 +1415,7 @@ def run_suite(a, work: str) -> int:
1230 continue 1415 continue
1231 const_wants = { 1416 const_wants = {
1232 "ps_clip_color": (0x3E800000, 0x3F000000, 0x3F400000, 0x3F800000), 1417 "ps_clip_color": (0x3E800000, 0x3F000000, 0x3F400000, 0x3F800000),
1418 "ps_exp_color_mask": (0x40000000, 0x40800000, 0x40000000, 0x40800000), # .asm header
1233 "ps_ops": (0x48804300, 5, 7, 0xBFFFFFFC), 1419 "ps_ops": (0x48804300, 5, 7, 0xBFFFFFFC),
1234 "ps_ops2": (0xABCD4400, 0x46001234, 0xBFFFFFFA, 7), 1420 "ps_ops2": (0xABCD4400, 0x46001234, 0xBFFFFFFA, 7),
1235 "ps_ops3": (0xBFFFFFFA, 0x44660066, 0x44AABBCC, 16), 1421 "ps_ops3": (0xBFFFFFFA, 0x44660066, 0x44AABBCC, 16),
@@ -1247,6 +1433,7 @@ def run_suite(a, work: str) -> int:
1247 "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), 1433 "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000),
1248 "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), 1434 "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0),
1249 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) 1435 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header)
1436 "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header)
1250 "ps_med3_mods": (0x3F800000, 0x40400000, 0x40C00000, 0x3F400000), 1437 "ps_med3_mods": (0x3F800000, 0x40400000, 0x40C00000, 0x3F400000),
1251 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), 1438 "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203),
1252 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), 1439 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
@@ -1270,6 +1457,9 @@ def run_suite(a, work: str) -> int:
1270 "ps_sff_imm": (2, 1, 20, 16), # SHADER-46: s_ff0/s_ff1 of an immediate 1457 "ps_sff_imm": (2, 1, 20, 16), # SHADER-46: s_ff0/s_ff1 of an immediate
1271 "ps_fnan_med3": (0x40A00000, 0xC0200000, 0xC0200000, 0x40600000), # measured on RDNA2 hardware 1458 "ps_fnan_med3": (0x40A00000, 0xC0200000, 0xC0200000, 0x40600000), # measured on RDNA2 hardware
1272 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000), 1459 "ps_fnan_fract": (0x3F7FFFFF, 0x00003BFF, 0xC0200000, 0xC0200000),
1460 # v_med3 with a NaN in S2 or in two operands, by the same measured rule (derivations in the .asm headers)
1461 "ps_fnan_med3_s2": (0x40A00000, 0x40A00000, 0xC0200000, 0x40E00000),
1462 "ps_f16_fnan_med3": (0xAAAA4500, 0xAAAA4500, 0xAAAAC100, 0xAAAA4700),
1273 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) 1463 # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers)
1274 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), 1464 "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000),
1275 "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000B), # far branches (.asm header) 1465 "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000B), # far branches (.asm header)
@@ -1278,15 +1468,23 @@ def run_suite(a, work: str) -> int:
1278 "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header) 1468 "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header)
1279 "ps_vcmpx_f16_e64": (0x64C11100, 0x6CF171C1, 0x67C71D18, 0x6FF77DD9), # same, e64 with swapped operands 1469 "ps_vcmpx_f16_e64": (0x64C11100, 0x6CF171C1, 0x67C71D18, 0x6FF77DD9), # same, e64 with swapped operands
1280 "ps_cvt_off": (0xBF000000, 0x3EE00000, 0xBE800000, 0x3F800000), 1470 "ps_cvt_off": (0xBF000000, 0x3EE00000, 0xBE800000, 0x3F800000),
1281 "ps_fmac_f16_mods": (0xAAAA3C00, 0xAAAA3E00, 0xAAAA0000, 0xAAAA4000), 1471 "ps_fmac_f16_mods": (0xAAAA3C00, 0xAAAA3A00, 0xAAAA0000, 0xAAAA4400),
1282 "ps_vop3_const_mods": (0xC0000000, 0xBF800000, 0x3F800000, 0xAAAABC00), 1472 "ps_vop3_const_mods": (0xC0000000, 0xBF800000, 0x3F800000, 0xAAAABC00),
1473 "ps_cndmask_sign_mods": (0xFF800001, 0x7F800001, 0x80000001, 0x7F800001),
1283 "ps_interp_f32_mods": (0x3F800000, 0x00000000, 0x3F400000, 0x3F800000), # drawn with vs_interp_consts 1474 "ps_interp_f32_mods": (0x3F800000, 0x00000000, 0x3F400000, 0x3F800000), # drawn with vs_interp_consts
1284 "ps_interp_mov_mods": (0x3F800000, 0x3FC00000, 0x40000000, 0x3F400000), 1475 "ps_interp_mov_mods": (0x3F800000, 0x3FC00000, 0x40000000, 0x3F400000),
1285 # v_mad_u32_u16 / v_mad_i32_i16 and v_subrev_f16, which had CPU checks only (.asm headers) 1476 # v_mad_u32_u16 / v_mad_i32_i16 and v_subrev_f16, which had CPU checks only (.asm headers)
1286 "ps_valu16_mad": (0x00000002, 0x00030002, 0x00008000, 0x00000004), 1477 "ps_valu16_mad": (0x00000002, 0x00030002, 0x00008000, 0x00000004),
1478 "ps_valu16_mad_sel": (0x00008003, 0xDB880000, 0xFFFFFFFF, 0x80000000), # measured on gfx1036
1287 "ps_valu16_subrev": (0xAAAABC00, 0xAAAAC000, 0xAAAA3C00, 0x42003800), 1479 "ps_valu16_subrev": (0xAAAABC00, 0xAAAAC000, 0xAAAA3C00, 0x42003800),
1288 "ps_vcmp_f32_nan": (0x0000376C, 0x0000FD5B, 0x0000D36C, 0x00000FE7), # from the .asm headers 1480 "ps_vcmp_f32_nan": (0x0000376C, 0x0000FD5B, 0x0000D36C, 0x00000FE7), # from the .asm headers
1289 "ps_vcmp_64": (0x0000B3C4, 0x000091E6, 0x00006787, 0x00007C93), 1481 "ps_vcmp_64": (0x0000B3C4, 0x000091E6, 0x00006787, 0x00007C93),
1482 # 32-bit integer VALU ops on VINT_ENV's heap (derivations in the .asm headers)
1483 "ps_vint_logic3": (0xFFFFFFFE, 0xBBB05070, 0x1D3B5977, 0x123F5F7E),
1484 "ps_vint_bits": (0xFFFFFFFE, 0x40000000, 0x1E6A2C48, 0x000001D5),
1485 "ps_vint_mul24": (0x13345678, 0xFFFFFFFD, 0x00007FFF, 0x0000FFFF),
1486 "ps_vint_minmax": (0x7FFFFFFE, 0x80000001, 0x80000001, 0x7FFFFFFE),
1487 "ps_vint_minmax3": (0xF0F0F0F0, 0xAB800000, 0xF0F0F0F0, 0xAB800000),
1290 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000BE), # same expectation as check.py 1488 "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000BE), # same expectation as check.py
1291 } 1489 }
1292 if skip := wide_pixel_skip(name, msg): # a 64-wide pixel stage the device could not give: nothing to judge 1490 if skip := wide_pixel_skip(name, msg): # a 64-wide pixel stage the device could not give: nothing to judge
@@ -1297,8 +1495,14 @@ def run_suite(a, work: str) -> int:
1297 ok, detail = None, str(skip) 1495 ok, detail = None, str(skip)
1298 else: 1496 else:
1299 ok, detail = check_pixel_const(raw, const_wants[name]) 1497 ok, detail = check_pixel_const(raw, const_wants[name])
1498 elif name == NAN_PAYLOAD_TEST:
1499 problem = nan_payload_problem(read_raw_u32(raw), msg)
1500 ok, detail = not problem, problem or "4096/4096 pixels match the driver-aware NaN payload check"
1300 elif name == "ps_bary": 1501 elif name == "ps_bary":
1301 ok, detail = check_bary(raw) 1502 ok, detail = check_bary(raw)
1503 elif name == "ps_persp_bary":
1504 problem = bary_persp_problem(read_raw_rgba32f(raw))
1505 ok, detail = not problem, problem or "perspective-correct on every covered pixel"
1302 elif name == "ps_bitmask_perm": 1506 elif name == "ps_bitmask_perm":
1303 m = re.search(r"subgroup \d+\.\.(\d+)", msg) 1507 m = re.search(r"subgroup \d+\.\.(\d+)", msg)
1304 if m and int(m.group(1)) < 32: 1508 if m and int(m.group(1)) < 32:
@@ -1312,12 +1516,11 @@ def run_suite(a, work: str) -> int:
1312 elif name == "ps_flat": 1516 elif name == "ps_flat":
1313 ok, detail = check_flat(raw) 1517 ok, detail = check_flat(raw)
1314 elif name == "ps_interp_f16_high": 1518 elif name == "ps_interp_f16_high":
1315 with open(raw, "rb") as source: 1519 # A missing or partial readback is an empty frame for this test, not a crash of the suite (as #3442).
1316 problem = interp_f16_high_problem(list(struct.iter_unpack("<4I", source.read()))) 1520 problem = interp_f16_high_problem(read_raw_u32(raw) if os.path.isfile(raw) else [])
1317 ok, detail = not problem, problem or "f16 low/high halves and f32 control within 2e-3" 1521 ok, detail = not problem, problem or "f16 low/high halves and f32 control within 2e-3"
1318 elif name == "ps_ij_computed": 1522 elif name == "ps_ij_computed":
1319 with open(raw, "rb") as source: 1523 problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else [])
1320 problem = ij_computed_problem(list(struct.iter_unpack("<4I", source.read())))
1321 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" 1524 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6"
1322 elif name == "ps_mandelbrot": 1525 elif name == "ps_mandelbrot":
1323 px = read_raw_u32(raw) if os.path.isfile(raw) else [] 1526 px = read_raw_u32(raw) if os.path.isfile(raw) else []
@@ -1375,8 +1578,8 @@ def run_suite(a, work: str) -> int:
1375 elif rc != 0: 1578 elif rc != 0:
1376 results.append((name, False, msg)) 1579 results.append((name, False, msg))
1377 else: 1580 else:
1378 with open(raw, "rb") as source: 1581 # A missing or partial readback is an empty frame for this test, not a crash of the suite (as #3442).
1379 problem = interp_f16_high_problem(list(struct.iter_unpack("<4I", source.read()))) 1582 problem = interp_f16_high_problem(read_raw_u32(raw) if os.path.isfile(raw) else [])
1380 results.append((name, not problem, problem or "f16 low/high halves and f32 control within 2e-3")) 1583 results.append((name, not problem, problem or "f16 low/high halves and f32 control within 2e-3"))
1381 elif name == "ms_clip": 1584 elif name == "ms_clip":
1382 raw = os.path.join(raw_dir, f"{name}.raw") 1585 raw = os.path.join(raw_dir, f"{name}.raw")
@@ -1417,6 +1620,7 @@ def run_suite(a, work: str) -> int:
1417 print("\n=== GPU TEST RESULTS ===") 1620 print("\n=== GPU TEST RESULTS ===")
1418 passed = skipped = 0 1621 passed = skipped = 0
1419 for name, ok, detail in results: 1622 for name, ok, detail in results:
1623 ok = None if isinstance(detail, Skip) else ok # a check.py helper's "this device can't run it" (cs_fmt_*)
1420 tag = "SKIP" if ok is None else "PASS" if ok else "FAIL" 1624 tag = "SKIP" if ok is None else "PASS" if ok else "FAIL"
1421 passed += ok is True 1625 passed += ok is True
1422 skipped += ok is None 1626 skipped += ok is None
diff --git a/scripts/run_guest_scene.py b/scripts/run_guest_scene.py
new file mode 100644
index 000000000..2933491c6
--- /dev/null
+++ b/scripts/run_guest_scene.py
@@ -0,0 +1,361 @@
1#!/usr/bin/env python3
2"""Run the 600-frame synthetic Win32 guest scene headless in full, save and resume mode and check the results.
3
4 python -I scripts/run_guest_scene.py --loader L --guest G --shaders ROOT [--out DIR] [--wine WINE]
5 [--play-audio] [--negative-controls]
6
7Each run renders offscreen in a fresh process and write overlay. Without --out the runs go to a temporary folder that is removed
8afterwards. The summary is printed first, and on failure the last run's log tails are printed too. Audio stays offline
9unless --play-audio sets LEONIDA_SCENE_AUDIO=winmm. The guest then plays the pulse synchronously with PlaySoundW.
10Run records distinguish a child exit, a deadline expiry and a launch failure.
11--negative-controls also runs a corrupted scene.bin and a corrupted checkpoint.bin, and each one must exit with 1.
12Exit code 0 means every check passed, 1 means a check failed and 2 means bad arguments.
13"""
14from __future__ import annotations
15
16import argparse
17import hashlib
18import json
19import os
20import shutil
21import struct
22import subprocess
23import sys
24import tempfile
25import time
26import wave
27from pathlib import Path
28
29FRAMES, HALF, RECORD_SIZE = 600, 300, 32 # frames.bin: eight little-endian uint32 words per frame
30PAGES, PAGE_SIZE, PAGE_FRAMES = 10, 16, 60
31MODES = {"full": (0, FRAMES), "save": (0, HALF), "resume": (HALF, FRAMES)} # first frame, end frame
32A_FRAMES = (137, 422)
33SHOT_FRAMES = (0, 137, 299, 300, 422, 599)
34DIRECTIONS = ((1, 0), (1, 1), (0, 1), (0, 0), (-1, 0), (-1, -1), (0, -1), (1, 0), (0, 0), (0, 1), (-1, 0), (1, -1))
35VERSION, STATE_WORDS, AUDIO_WORDS = 1, 20, 10
36AUDIO_RATE, AUDIO_SAMPLES, AUDIO_RAMP, AUDIO_HALF_PERIOD = 44100, 11025, 441, 50 # 441 Hz square, 10 ms ramps
37PLAYBACK = {0: "offline", 1: "played", 3: "device error"}
38TIMEOUT = 180
39MARKER = b"GUEST_SCENE_PASS"
40NEGATIVE = {"bad-scene": ("full", b"scene.bin: not the 10 expected pages"),
41 "bad-checkpoint": ("resume", b"checkpoint.bin: bad header or checksum")}
42
43
44class Fail(Exception):
45 pass
46
47
48def check(cond: object, msg: str) -> None:
49 if not cond:
50 raise Fail(msg)
51
52
53def fnv1a(data: bytes, bits: int) -> int:
54 h, prime = (0x811C9DC5, 0x01000193) if bits == 32 else (0xCBF29CE484222325, 0x100000001B3)
55 mask = (1 << bits) - 1
56 for byte in data:
57 h = ((h ^ byte) * prime) & mask
58 return h
59
60
61def sha256(data: bytes) -> str:
62 return hashlib.sha256(data).hexdigest()
63
64
65def tree_files(root: Path) -> dict[str, str]:
66 return {p.relative_to(root).as_posix(): sha256(p.read_bytes()) for p in sorted(root.rglob("*")) if p.is_file()}
67
68
69def tree_hash(files: dict[str, str]) -> str:
70 return sha256(b"".join(rel.encode() + b"\0" + files[rel].encode() + b"\n" for rel in sorted(files)))
71
72
73def write_new(path: Path, data: bytes) -> None:
74 with path.open("xb") as f:
75 f.write(data)
76
77
78def guest_path(path: Path, wine: bool) -> str:
79 """The path as the guest sees it: native on Windows, through the Z: drive under Wine."""
80 full = str(Path(path).resolve())
81 return "Z:" + full.replace("/", "\\") if wine else full
82
83
84def scene_bytes() -> bytes:
85 return bytes((page * 29 + i * 7 + 11) & 255 for page in range(PAGES) for i in range(PAGE_SIZE))
86
87
88def trace() -> list[tuple[int, int, int, int, int]]:
89 """(pad buttons, x, y, scene byte, bias index) after each frame, derived from the input trace alone."""
90 scene, steps, x, y = scene_bytes(), [], 8, 8
91 for f in range(FRAMES):
92 dx, dy = DIRECTIONS[f // 50]
93 x, y = (x + dx) % 64, (y + dy) % 64
94 a = f in A_FRAMES
95 buttons = {-1: 256, 0: 0, 1: 512}[dx] | {-1: 64, 0: 0, 1: 128}[dy] | 4 * a
96 value = scene[(f // PAGE_FRAMES) * PAGE_SIZE + (x + 3 * y) % PAGE_SIZE]
97 steps.append((buttons, x, y, value, ((value >> 5) + bool(dx or dy) + 2 * a) % 4))
98 return steps
99
100
101def predicted_image(offset: int, bias: int) -> tuple[int, bytes]:
102 """FNV-1a 64 of the RGBA32F readback and its P6 screenshot, computed in floats from the draw description."""
103 palette = ((0.5, 0.125, 0.25, 0.5), (0.125, 1.0, 0.75, 1.0), (0.25, 1.125, 0.875, 1.0), (0.75, 0.25, 0.75, 1.0))
104 colors = [tuple(c + (bias / 8 if i and ch < 3 else 0) for ch, c in enumerate(px)) for i, px in enumerate(palette)]
105 binary = [struct.pack("<4f", *color) for color in colors]
106 rgb = [bytes(min(255, int(v * 255 + 0.5)) for v in color[:3]) for color in colors]
107 pixels = [int(offset <= col < offset + 32) if row < 32 else 2 if col >= 32 else 3 if row > col + 32 else 0
108 for row in range(64) for col in range(64)]
109 return fnv1a(b"".join(binary[p] for p in pixels), 64), b"P6\n64 64\n255\n" + b"".join(rgb[p] for p in pixels)
110
111
112def check_reference(frames: bytes, steps: list[tuple[int, ...]], out: Path) -> int:
113 images: dict[tuple[int, int], tuple[int, bytes]] = {}
114 for f, record in enumerate(struct.iter_unpack("<8I", frames)):
115 buttons, x, y, value, bias = steps[f]
116 if (x % 8, bias) not in images:
117 images[x % 8, bias] = predicted_image(x % 8, bias)
118 digest, shot = images[x % 8, bias]
119 check(record == (f, digest & 0xFFFFFFFF, digest >> 32, buttons, x, y, value, bias),
120 f"independent scene/pixel prediction failed at frame {f}: got {record}")
121 if f in SHOT_FRAMES:
122 for mode in ("full", "save" if f < HALF else "resume"):
123 check((out / mode / f"shot_{f:03d}.ppm").read_bytes() == shot,
124 f"{mode}: shot_{f:03d}.ppm differs from the pixel oracle")
125 return len(images)
126
127
128def check_state(path: Path, magic: bytes, frames: bytes, steps: list[tuple[int, ...]]) -> None:
129 """Every word of a state record. The trace decides all but the chain, which is FNV-1a 64 over frames.bin."""
130 data, what = path.read_bytes(), f"{path.parent.name}/{path.name}"
131 check(len(data) == 4 * STATE_WORDS, f"{what}: {len(data)} bytes, want {4 * STATE_WORDS}")
132 n = len(frames) // RECORD_SIZE
133 buttons, x, y, value, bias = steps[n - 1]
134 page, chain = (n - 1) // PAGE_FRAMES, fnv1a(frames, 64)
135 want = (int.from_bytes(magic, "little"), VERSION, STATE_WORDS, n, x, y, buttons, sum(f < n for f in A_FRAMES),
136 1, A_FRAMES[0], page, *struct.unpack_from("<4I", scene_bytes(), page * PAGE_SIZE), value, bias,
137 chain & 0xFFFFFFFF, chain >> 32, fnv1a(data[:-4], 32))
138 for i, (got, exp) in enumerate(zip(struct.unpack(f"<{STATE_WORDS}I", data), want)):
139 check(got == exp, f"{what}: word {i} is {got:#x}, want {exp:#x}")
140
141
142def expected_pcm(peak: int) -> bytes:
143 """The guest's pulse: a 441 Hz square wave with 10 ms linear ramps at both ends, mono 16-bit."""
144 samples = []
145 for i in range(AUDIO_SAMPLES):
146 amp = peak * min(i, AUDIO_SAMPLES - 1 - i, AUDIO_RAMP) // AUDIO_RAMP
147 samples.append(-amp if (i // AUDIO_HALF_PERIOD) & 1 else amp)
148 return struct.pack(f"<{AUDIO_SAMPLES}h", *samples)
149
150
151def check_audio(mode_dir: Path, has_event: bool, play_audio: bool) -> dict:
152 name, wav_path, bin_path = mode_dir.name, mode_dir / "event.wav", mode_dir / "audio.bin"
153 if not has_event:
154 check(not wav_path.exists() and not bin_path.exists(), f"{name}: replayed an earlier sound")
155 return {"event": None}
156 with wave.open(str(wav_path), "rb") as w:
157 fmt = (w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes(), w.getcomptype())
158 pcm = w.readframes(w.getnframes())
159 check(fmt == (1, 2, AUDIO_RATE, AUDIO_SAMPLES, "NONE"), f"{name}: event.wav is {fmt}, want mono 16-bit 44.1 kHz")
160 check(wav_path.stat().st_size == 44 + 2 * AUDIO_SAMPLES, f"{name}: event.wav has extra chunks or bytes")
161 peak = 9000
162 check(pcm == expected_pcm(peak), f"{name}: event.wav samples differ from the generated pulse")
163 raw = bin_path.read_bytes()
164 check(len(raw) == 4 * AUDIO_WORDS, f"{name}: audio.bin is {len(raw)} bytes, want {4 * AUDIO_WORDS}")
165 words = struct.unpack(f"<{AUDIO_WORDS}I", raw)
166 want = (int.from_bytes(b"LSAU", "little"), VERSION, AUDIO_WORDS, A_FRAMES[0], AUDIO_RATE, AUDIO_SAMPLES,
167 fnv1a(pcm, 32))
168 check(words[:7] == want, f"{name}: audio.bin starts {words[:7]}, want {want}")
169 check(words[9] == fnv1a(raw[:-4], 32), f"{name}: audio.bin checksum mismatch")
170 playback, mmresult = words[7], words[8]
171 check(playback in PLAYBACK, f"{name}: invalid playback result {playback}")
172 if play_audio:
173 check(playback in (1, 3), f"{name}: WinMM playback was not attempted")
174 else:
175 check(playback == 0 and mmresult == 0, f"{name}: offline run reports playback {playback}, MMRESULT {mmresult}")
176 return {"event": "event.wav", "frame": words[3], "peak": peak, "pcm_fnv32": f"{words[6]:08x}",
177 "wav_sha256": sha256(wav_path.read_bytes()), "playback": PLAYBACK[playback], "mmresult": mmresult}
178
179
180class Session:
181 """Starts the loader once per run and keeps each run's streams and record under <out>/logs."""
182
183 def __init__(self, args: argparse.Namespace, out: Path) -> None:
184 self.args, self.out, self.logs = args, out, out / "logs"
185 self.runs: dict[str, dict] = {}
186 self.last: list[Path] = []
187
188 def run(self, name: str, mode: str, package: Path, overlay: Path) -> tuple[int, list[bytes], bytes]:
189 a, wine = self.args, bool(self.args.wine)
190 cmd = ([a.wine] if wine else []) + [str(a.loader), "--run", guest_path(a.guest, wine), "--game-dir",
191 guest_path(package, wine), "--overlay", guest_path(overlay, wine),
192 "--", guest_path(a.shaders, wine)]
193 env_set = {"LEONIDA_SCENE_MODE": mode,
194 "LEONIDA_SCENE_AUDIO": "winmm" if a.play_audio else "offline",
195 "LEONIDA_KEYBOARD_PAD": "always", "LEONIDA_GAMEINPUT_THREAD": "0", "LEONIDA_D3D12": "vulkan",
196 "LEONIDA_SHADERS": guest_path(a.shaders / "spirv", wine), "LEONIDA_UNIMPLEMENTED": "stop"}
197 env = dict(os.environ, **env_set)
198 self.last = [self.logs / f"{name}.stdout.log", self.logs / f"{name}.stderr.log"]
199 start = time.monotonic()
200 rc, launch_error = None, None
201 with self.last[0].open("xb") as so, self.last[1].open("xb") as se:
202 try:
203 rc = subprocess.run(cmd, cwd=overlay, env=env, stdin=subprocess.DEVNULL, stdout=so, stderr=se,
204 timeout=TIMEOUT).returncode
205 except subprocess.TimeoutExpired:
206 outcome = "timed_out"
207 except OSError as e:
208 outcome = "launch_failed"
209 launch_error = str(e)
210 else:
211 outcome = "exited"
212 stdout, stderr = (p.read_bytes() for p in self.last)
213 rec = {"cmd": cmd, "cwd": str(overlay), "env": env_set, "outcome": outcome, "returncode": rc, "timeout_s": TIMEOUT,
214 "seconds": round(time.monotonic() - start, 3), "stdout_sha256": sha256(stdout),
215 "stderr_sha256": sha256(stderr)}
216 if launch_error is not None:
217 rec["launch_error"] = launch_error
218 write_new(self.logs / f"{name}.json", json.dumps(rec, indent=2).encode())
219 self.runs[name] = rec
220 if launch_error is not None:
221 raise Fail(f"{name}: could not launch {cmd[0]}: {launch_error}")
222 check(rc is not None, f"{name}: timed out after {TIMEOUT}s")
223 return rc, [line.rstrip(b"\r") for line in stdout.splitlines()], stdout + stderr
224
225 def expect_pass(self, mode: str, package: Path) -> None:
226 first, end = MODES[mode]
227 rc, lines, _ = self.run(mode, mode, package, self.out / mode)
228 check(rc == 0, f"{mode}: exit code {rc}")
229 want, got = MARKER + b" frames=%d" % (end - first), [line for line in lines if line.startswith(MARKER)]
230 check(got == [want], f"{mode}: want one {want.decode()!r} line, got {[g.decode('ascii', 'replace') for g in got]}")
231
232 def expect_fail(self, name: str, package: Path, overlay: Path) -> dict:
233 mode, diagnostic = NEGATIVE[name]
234 rc, lines, text = self.run(name, mode, package, overlay)
235 check(rc == 1, f"{name}: exit code {rc}, want exactly 1")
236 check(not any(line.startswith(MARKER) for line in lines), f"{name}: printed {MARKER.decode()}")
237 check(diagnostic in text, f"{name}: no diagnostic naming {diagnostic.decode()}")
238 for output in ("frames.bin", "state.bin"):
239 check(not (overlay / output).exists(), f"{name}: published {output} after failing")
240 return {"returncode": rc, "diagnostic": diagnostic.decode()}
241
242
243def negative_controls(session: Session, out: Path) -> dict:
244 bad_package, scene = out / "neg-scene-package", bytearray(scene_bytes())
245 bad_package.mkdir()
246 scene[0] ^= 0xFF
247 write_new(bad_package / "scene.bin", bytes(scene))
248 (out / "neg-bad-scene").mkdir()
249 results = {"bad-scene": session.expect_fail("bad-scene", bad_package, out / "neg-bad-scene")}
250 overlay, ckpt = out / "neg-bad-checkpoint", bytearray((out / "save" / "checkpoint.bin").read_bytes())
251 overlay.mkdir()
252 ckpt[20] ^= 0xFF
253 write_new(overlay / "checkpoint.bin", bytes(ckpt))
254 results["bad-checkpoint"] = session.expect_fail("bad-checkpoint", out / "package", overlay)
255 return results
256
257
258def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int:
259 out.mkdir(parents=True, exist_ok=True) # parse_args has checked that it is new or empty
260 session = Session(args, out)
261 report: dict = {"status": "fail", "frames": FRAMES, "headless": True, "wine": args.wine, "temporary": temporary,
262 "audio_mode": "winmm" if args.play_audio else "offline", "report": str(out / "report.json")}
263 try:
264 shader_files = tree_files(args.shaders)
265 report["inputs"] = {
266 "loader": {"path": str(args.loader), "sha256": sha256(args.loader.read_bytes())},
267 "guest": {"path": str(args.guest), "sha256": sha256(args.guest.read_bytes())},
268 "shaders": {"path": str(args.shaders), "files": len(shader_files), "tree_sha256": tree_hash(shader_files)},
269 "scene.bin": sha256(scene_bytes())}
270 for sub in ("logs", "package", *MODES):
271 (out / sub).mkdir()
272 package = out / "package"
273 write_new(package / "scene.bin", scene_bytes())
274 report["runs"] = session.runs
275 for mode in MODES:
276 if mode == "resume":
277 write_new(out / mode / "checkpoint.bin", (out / "save" / "checkpoint.bin").read_bytes())
278 session.expect_pass(mode, package)
279 frames = {m: (out / m / "frames.bin").read_bytes() for m in MODES}
280 for m, (first, end) in MODES.items():
281 check(len(frames[m]) == (end - first) * RECORD_SIZE, f"{m}: frames.bin is {len(frames[m])} bytes")
282 check(not list((out / m).glob("*.tmp")), f"{m}: an unpublished .tmp file was left behind")
283 check(frames["save"] + frames["resume"] == frames["full"], "save+resume frames.bin differ from full")
284 steps = trace()
285 report["predicted_images"] = check_reference(frames["full"], steps, out)
286 report["frame_chain"] = f"{fnv1a(frames['full'], 64):016x}"
287 check_state(out / "save" / "state.bin", b"LSST", frames["save"], steps)
288 for m in ("full", "resume"):
289 check_state(out / m / "state.bin", b"LSST", frames["full"], steps)
290 check_state(out / "save" / "checkpoint.bin", b"LSCK", frames["save"], steps)
291 for m in ("full", "resume"):
292 check((out / m / "checkpoint.bin").read_bytes() == (out / "save" / "checkpoint.bin").read_bytes(),
293 f"{m}: checkpoint.bin differs from the save run's")
294 report["audio"] = {m: check_audio(out / m, m != "resume", args.play_audio) for m in MODES}
295 check((out / "full" / "event.wav").read_bytes() == (out / "save" / "event.wav").read_bytes(),
296 "event.wav differs between full and save")
297 if args.negative_controls:
298 report["negative_controls"] = negative_controls(session, out)
299 check(tree_files(package) == {"scene.bin": sha256(scene_bytes())}, "a guest modified the synthetic package")
300 report["status"] = "pass"
301 except (Fail, OSError, ValueError, struct.error, wave.Error, EOFError) as e:
302 report["error"] = str(e) if isinstance(e, Fail) else f"{type(e).__name__}: {e}"
303 for log in session.last:
304 if log.is_file():
305 tail = log.read_bytes().decode("utf-8", "replace").splitlines()[-40:]
306 print(f"--- last {len(tail)} lines of {log} ---", *tail, sep="\n", file=sys.stderr)
307 finally:
308 report["outputs"] = {d.name: {"tree_sha256": tree_hash(files), "files": files} for d in sorted(out.iterdir())
309 if d.is_dir() and d.name != "logs" for files in [tree_files(d)]}
310 write_new(out / "report.json", json.dumps(report, indent=2, sort_keys=True).encode())
311 print(f"{report['status'].upper()}: {report.get('error', 'all guest scene checks passed')}")
312 if not temporary:
313 print(out / "report.json")
314 return 0 if report["status"] == "pass" else 1
315
316
317def parse_args() -> argparse.Namespace:
318 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
319 ap.add_argument("--loader", type=Path, required=True)
320 ap.add_argument("--guest", type=Path, required=True)
321 ap.add_argument("--shaders", type=Path, required=True, help="shader root containing spirv/")
322 ap.add_argument("--out", type=Path, help="new or empty folder (default: a temporary folder, removed afterwards)")
323 ap.add_argument("--wine", help="run the loader through this Wine binary")
324 ap.add_argument("--play-audio", action="store_true", help="LEONIDA_SCENE_AUDIO=winmm instead of offline")
325 ap.add_argument("--negative-controls", action="store_true", help="also run a bad scene.bin and checkpoint")
326 args = ap.parse_args()
327 for name in ("loader", "guest"):
328 if not getattr(args, name).is_file():
329 ap.error(f"--{name}: no such file")
330 if not (args.shaders / "spirv").is_dir():
331 ap.error("--shaders: no spirv/ folder under it")
332 if args.wine:
333 found = args.wine if Path(args.wine).is_file() else shutil.which(args.wine)
334 if not found:
335 ap.error("--wine: not found")
336 args.wine = str(Path(found).resolve())
337 elif os.name != "nt":
338 ap.error("--wine is required outside Windows")
339 if args.out and args.out.exists() and (not args.out.is_dir() or any(args.out.iterdir())):
340 ap.error("--out must be new or an empty folder")
341 args.loader, args.guest, args.shaders = args.loader.resolve(), args.guest.resolve(), args.shaders.resolve()
342 return args
343
344
345def main() -> int:
346 args = parse_args()
347 if args.out:
348 return execute(args, args.out.resolve(), temporary=False)
349 with tempfile.TemporaryDirectory(prefix="guest-scene-", ignore_cleanup_errors=True) as tmp:
350 return execute(args, Path(tmp) / "run", temporary=True)
351
352
353if __name__ == "__main__":
354 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
355 sys.stdout.reconfigure(errors="replace")
356 except (AttributeError, ValueError, OSError):
357 pass
358 # Redirected Windows streams may use a code page that cannot encode a path in the report.
359 sys.stdout.reconfigure(errors="backslashreplace")
360 sys.stderr.reconfigure(errors="backslashreplace")
361 sys.exit(main())
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
new file mode 100644
index 000000000..78cfde01a
--- /dev/null
+++ b/scripts/run_semantic_tests.py
@@ -0,0 +1,82 @@
1r"""Run the translator regression suite (tests/semantic) one process per test file, several files at a time.
2
3 python -I scripts/run_semantic_tests.py tests/semantic # one file per core
4 python -I scripts/run_semantic_tests.py tests/semantic -j 4 # four at a time
5 python -I scripts/run_semantic_tests.py tests/semantic -v # also print the output of the files that pass
6
7It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py`, and packages below it), each as
8`python -m unittest <module>` from that folder, so a file sees the same import path as under discover. The files can
9run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1,
10or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary
11line, and exits 1 if a file fails or none is found. Standard library only.
12"""
13import argparse
14import concurrent.futures
15import fnmatch
16import os
17import re
18import subprocess
19import sys
20import time
21
22
23def test_modules(directory):
24 """Dotted names of the test modules unittest discover finds under `directory` (it enters packages only)."""
25 names = []
26 for base, dirs, files in os.walk(directory):
27 dirs[:] = sorted(d for d in dirs if os.path.isfile(os.path.join(base, d, "__init__.py")))
28 prefix = os.path.relpath(base, directory).replace(os.sep, ".")
29 for name in sorted(files):
30 if fnmatch.fnmatchcase(name, "test*.py"):
31 names.append(name[:-3] if prefix == "." else f"{prefix}.{name[:-3]}")
32 return names
33
34
35def run_module(directory, module, verbose):
36 """(return code, tests run, output) of `python -m unittest <module>` run from `directory`."""
37 cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), module]
38 p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
39 errors="replace")
40 ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M)
41 return p.returncode, int(ran.group(1)) if ran else 0, p.stdout
42
43
44def main(argv=None):
45 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
46 ap.add_argument("directory", help="the suite's folder, tests/semantic")
47 ap.add_argument("-j", "--jobs", type=int, default=os.cpu_count() or 1, help="files at a time (default: cores)")
48 ap.add_argument("-v", "--verbose", action="store_true", help="unittest -v, and print passing files' output")
49 a = ap.parse_args(argv)
50 directory = os.path.abspath(a.directory)
51 if a.jobs <= 1:
52 return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory,
53 *(["-v"] if a.verbose else [])])
54 modules = test_modules(directory)
55 if not modules:
56 print(f"no test*.py files in {directory}")
57 return 1
58 # Largest files first: they tend to run longest, and one started last would set the wall time alone.
59 modules.sort(key=lambda m: -os.path.getsize(os.path.join(directory, *m.split(".")) + ".py"))
60 start, total, failed = time.monotonic(), 0, []
61 with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool:
62 jobs = {pool.submit(run_module, directory, m, a.verbose): m for m in modules}
63 for job in concurrent.futures.as_completed(jobs):
64 code, ran, out = job.result()
65 total += ran
66 if code:
67 failed.append(jobs[job])
68 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True)
69 elif a.verbose:
70 print(f"==== {jobs[job]}\n{out}", flush=True)
71 took = time.monotonic() - start
72 summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs"
73 print(summary + (": " + ", ".join(sorted(failed)) if failed else ""))
74 return 1 if failed else 0
75
76
77if __name__ == "__main__":
78 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
79 sys.stdout.reconfigure(errors="replace")
80 except (AttributeError, ValueError, OSError):
81 pass
82 sys.exit(main())
diff --git a/scripts/run_wine_session.sh b/scripts/run_wine_session.sh
new file mode 100755
index 000000000..72ace4407
--- /dev/null
+++ b/scripts/run_wine_session.sh
@@ -0,0 +1,9 @@
1#!/usr/bin/env bash
2# Run CI tests on the display that initialized their dedicated Wine prefix.
3set -e
4: "${WINEPREFIX:?Set WINEPREFIX to a dedicated test prefix}"
5
6# Stop this prefix's Wine processes before Xvfb tears down the display.
7trap 'wineserver -k || true' EXIT
8timeout 5m wineboot --init </dev/null
9"$@" </dev/null
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index c9d2e5edf..4a6adb8c5 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -25,6 +25,7 @@ import os
25import re 25import re
26import shlex 26import shlex
27import shutil 27import shutil
28import signal
28import subprocess 29import subprocess
29import sys 30import sys
30import tempfile 31import tempfile
@@ -80,15 +81,26 @@ class DriveMap:
80 if not os.path.isdir(dosdevices): 81 if not os.path.isdir(dosdevices):
81 self.note = f"no Wine prefix at {self.prefix}: drive {drive}: not mapped" 82 self.note = f"no Wine prefix at {self.prefix}: drive {drive}: not mapped"
82 return self 83 return self
84 already_set = f"drive {drive}: is already set in {dosdevices}: left as it is"
83 if os.path.lexists(link): 85 if os.path.lexists(link):
84 self.note = f"drive {drive}: is already set in {dosdevices}: left as it is" 86 self.note = already_set
85 return self 87 return self
86 self.scratch = tempfile.mkdtemp(prefix="wine-drive-") 88 self.scratch = tempfile.mkdtemp(prefix="wine-drive-")
87 parent = os.path.join(self.scratch, *rest[:-1]) 89 try:
88 os.makedirs(parent, exist_ok=True) 90 parent = os.path.join(self.scratch, *rest[:-1])
89 os.symlink(self.root, os.path.join(parent, rest[-1])) 91 os.makedirs(parent, exist_ok=True)
90 os.symlink(self.scratch, link) 92 os.symlink(self.root, os.path.join(parent, rest[-1]))
91 self.link = link 93 try:
94 os.symlink(self.scratch, link)
95 except FileExistsError:
96 self.note = already_set
97 return self
98 self.link = link
99 finally:
100 # __exit__ only runs after a successful __enter__.
101 if self.link is None:
102 shutil.rmtree(self.scratch, ignore_errors=True)
103 self.scratch = None
92 self.note = f"drive {drive}: maps {self.windows_root} to {self.root} for this run" 104 self.note = f"drive {drive}: maps {self.windows_root} to {self.root} for this run"
93 return self 105 return self
94 106
@@ -157,9 +169,11 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...
157 for a in command[1:]: 169 for a in command[1:]:
158 mapped = map_path(a, args.windows_root, args.root) 170 mapped = map_path(a, args.windows_root, args.root)
159 argv.append(wine_path(mapped) if mapped is not None else a) 171 argv.append(wine_path(mapped) if mapped is not None else a)
160 cwd = props.get("WORKING_DIRECTORY") 172 listed_cwd = props.get("WORKING_DIRECTORY")
161 cwd = map_path(cwd, args.windows_root, args.root) if cwd else os.path.dirname(exe) 173 cwd = map_path(listed_cwd, args.windows_root, args.root) if listed_cwd else None
162 if not cwd or not os.path.isdir(cwd): 174 if cwd is not None and not os.path.isdir(cwd):
175 return "fail", f"CTest working directory is not a directory: {listed_cwd} (mapped to {cwd})"
176 if cwd is None:
163 cwd = os.path.dirname(exe) 177 cwd = os.path.dirname(exe)
164 assignments = props.get("ENVIRONMENT", []) 178 assignments = props.get("ENVIRONMENT", [])
165 if not isinstance(assignments, list): 179 if not isinstance(assignments, list):
@@ -182,10 +196,18 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...
182 return "fail", "invalid CTest TIMEOUT" 196 return "fail", "invalid CTest TIMEOUT"
183 if ctest_timeout > 0: 197 if ctest_timeout > 0:
184 timeout = min(timeout, ctest_timeout) 198 timeout = min(timeout, ctest_timeout)
199 skip_code = props.get("SKIP_RETURN_CODE")
200 if skip_code is not None:
201 error = "invalid CTest SKIP_RETURN_CODE: expected an integer from 0 to 255"
202 try:
203 skip_code = int(str(skip_code))
204 except ValueError:
205 return "fail", error
206 if not 0 <= skip_code <= 255:
207 return "fail", error
185 start = time.monotonic() 208 start = time.monotonic()
186 try: 209 try:
187 proc = subprocess.run(argv, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 210 proc = run_test_process(argv, cwd=cwd, env=env, timeout=timeout)
188 timeout=timeout)
189 except subprocess.TimeoutExpired as e: 211 except subprocess.TimeoutExpired as e:
190 out = (e.stdout or b"").decode("utf-8", "replace") 212 out = (e.stdout or b"").decode("utf-8", "replace")
191 return "fail", f"timed out after {timeout} s\n{out}" 213 return "fail", f"timed out after {timeout} s\n{out}"
@@ -198,8 +220,7 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...
198 # A negative return code is a host-signal termination (e.g. SIGSEGV), not a process exit code: 220 # A negative return code is a host-signal termination (e.g. SIGSEGV), not a process exit code:
199 # report it as a failure before SKIP_RETURN_CODE or WILL_FAIL can reinterpret it. 221 # report it as a failure before SKIP_RETURN_CODE or WILL_FAIL can reinterpret it.
200 return "fail", f"killed by signal {-code} in {elapsed:.1f} s\n{out}" 222 return "fail", f"killed by signal {-code} in {elapsed:.1f} s\n{out}"
201 skip_code = props.get("SKIP_RETURN_CODE") 223 if code == skip_code:
202 if skip_code is not None and code == int(skip_code):
203 return "skip", f"exit {code} (skip) in {elapsed:.1f} s\n{out}" 224 return "skip", f"exit {code} (skip) in {elapsed:.1f} s\n{out}"
204 detail = f"exit {code} in {elapsed:.1f} s\n{out}" 225 detail = f"exit {code} in {elapsed:.1f} s\n{out}"
205 skip_patterns = regex_list(props.get("SKIP_REGULAR_EXPRESSION", [])) 226 skip_patterns = regex_list(props.get("SKIP_REGULAR_EXPRESSION", []))
@@ -219,6 +240,27 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...
219 return ("pass" if passed else "fail"), detail 240 return ("pass" if passed else "fail"), detail
220 241
221 242
243def run_test_process(argv: list[str], *, cwd: str, env: dict[str, str],
244 timeout: float) -> subprocess.CompletedProcess:
245 options = dict(cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
246 if os.name != "posix":
247 return subprocess.run(argv, **options, timeout=timeout)
248
249 # Wine's Windows children and launcher wrappers can outlive the immediate child.
250 with subprocess.Popen(argv, **options, start_new_session=True) as proc:
251 try:
252 out, _ = proc.communicate(timeout=timeout)
253 except (subprocess.TimeoutExpired, KeyboardInterrupt):
254 # The launcher may have exited while a helper still holds the output pipe.
255 try:
256 os.killpg(proc.pid, signal.SIGKILL)
257 except ProcessLookupError:
258 pass
259 proc.wait()
260 raise
261 return subprocess.CompletedProcess(argv, proc.returncode, out)
262
263
222def positive_seconds(text: str) -> float: 264def positive_seconds(text: str) -> float:
223 """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" 265 """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on."""
224 try: 266 try:
@@ -243,6 +285,17 @@ def wine_command(text: str) -> list[str]:
243 return parts 285 return parts
244 286
245 287
288def valid_test_property(entry) -> bool:
289 if not isinstance(entry, dict) or not isinstance(entry.get("name"), str) or "value" not in entry:
290 return False
291 name, value = entry["name"], entry["value"]
292 if name == "WORKING_DIRECTORY":
293 return isinstance(value, str) and "\0" not in value
294 if name in ("PASS_REGULAR_EXPRESSION", "FAIL_REGULAR_EXPRESSION", "SKIP_REGULAR_EXPRESSION"):
295 return isinstance(value, str) or (isinstance(value, list) and all(isinstance(p, str) for p in value))
296 return True
297
298
246def valid_test_row(test) -> bool: 299def valid_test_row(test) -> bool:
247 if not isinstance(test, dict) or not isinstance(test.get("name"), str): 300 if not isinstance(test, dict) or not isinstance(test.get("name"), str):
248 return False 301 return False
@@ -251,10 +304,7 @@ def valid_test_row(test) -> bool:
251 if not isinstance(command, list) or not all(isinstance(arg, str) and "\0" not in arg for arg in command): 304 if not isinstance(command, list) or not all(isinstance(arg, str) and "\0" not in arg for arg in command):
252 return False 305 return False
253 entries = test.get("properties", []) 306 entries = test.get("properties", [])
254 return isinstance(entries, list) and all( 307 return isinstance(entries, list) and all(valid_test_property(entry) for entry in entries)
255 isinstance(entry, dict) and isinstance(entry.get("name"), str) and "value" in entry
256 for entry in entries
257 )
258 308
259 309
260def read_tests(path: str) -> list[dict] | None: 310def read_tests(path: str) -> list[dict] | None:
@@ -276,7 +326,7 @@ def main() -> int:
276 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 326 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
277 ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build") 327 ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build")
278 ap.add_argument("--windows-root", required=True, help="the Windows checkout the tests were listed in") 328 ap.add_argument("--windows-root", required=True, help="the Windows checkout the tests were listed in")
279 ap.add_argument("--root", default=ROOT, help="the Linux checkout (default: this repository)") 329 ap.add_argument("--root", type=os.path.abspath, default=ROOT, help="the Linux checkout (default: this repository)")
280 ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"), 330 ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"),
281 help="Wine command (default: $WINE or wine)") 331 help="Wine command (default: $WINE or wine)")
282 ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") 332 ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)")
@@ -289,22 +339,29 @@ def main() -> int:
289 tests = read_tests(args.tests) 339 tests = read_tests(args.tests)
290 if tests is None: 340 if tests is None:
291 return 2 341 return 2
292 dependencies = fixture_dependencies(tests) 342 names = [test.get("name", "?") for test in tests]
343 indices = {name: index for index, name in enumerate(names)}
344 setups = fixture_dependencies(tests)
345 sorter = TopologicalSorter(setups)
346 for index, test in enumerate(tests):
347 # DEPENDS controls order. Only failed fixture setups block a consumer.
348 sorter.add(index, *(indices[name] for name in properties(test).get("DEPENDS", []) if name in indices))
293 try: 349 try:
294 order = list(TopologicalSorter(dependencies).static_order()) 350 order = list(sorter.static_order())
295 except CycleError: 351 except CycleError:
296 print("ERROR: CTest fixture setup dependencies form a cycle", file=sys.stderr) 352 print("ERROR: CTest test dependencies form a cycle", file=sys.stderr)
297 return 2 353 return 2
298 wine = args.wine 354 wine = args.wine
299 results = {} 355 results = {}
356 results_by_index: dict[int, str] = {}
300 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") 357 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine")
301 names = [test.get("name", "?") for test in tests]
302 with DriveMap(args.windows_root, args.root, prefix) as drive: 358 with DriveMap(args.windows_root, args.root, prefix) as drive:
303 print(drive.note, flush=True) 359 print(drive.note, flush=True)
304 for index in order: 360 for index in order:
305 name = names[index] 361 name = names[index]
306 failed_setups = tuple(names[setup] for setup in dependencies[index] if results[names[setup]] == "fail") 362 failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail")
307 status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups) 363 status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups)
364 results_by_index[index] = status
308 results[name] = status 365 results[name] = status
309 print(f"[{status.upper()}] {name}", flush=True) 366 print(f"[{status.upper()}] {name}", flush=True)
310 if status != "pass": 367 if status != "pass":
diff --git a/scripts/shader_stats.py b/scripts/shader_stats.py
index d3a18c3ff..fb95a1843 100644
--- a/scripts/shader_stats.py
+++ b/scripts/shader_stats.py
@@ -8,6 +8,7 @@ the driver's instruction count with the original one (code growth) and its VGPRs
8code uses, and it flags scratch memory and spills: a register file that didn't fit in registers and went to memory, 8code uses, and it flags scratch memory and spills: a register file that didn't fit in registers and went to memory,
9which is the expensive case (relative VGPR indexing, v_movrels/v_movreld, forces it). It prints a summary per stage and, 9which is the expensive case (relative VGPR indexing, v_movrels/v_movreld, forces it). It prints a summary per stage and,
10with --details, one line per shader. 10with --details, one line per shader.
11Growth is unavailable when the original listing has no parsed instructions; its driver counters are still shown.
11 12
12Metrics are read only where the driver emits these exact RADV/ACO statistic names with a numeric value: Instructions, 13Metrics are read only where the driver emits these exact RADV/ACO statistic names with a numeric value: Instructions,
13VGPRs, SGPRs, Scratch size, Spilled VGPRs, Spilled SGPRs, Subgroups per SIMD. No equivalence is claimed for other 14VGPRs, SGPRs, Scratch size, Spilled VGPRs, Spilled SGPRs, Subgroups per SIMD. No equivalence is claimed for other
@@ -59,7 +60,7 @@ def load_stats(path):
59 """Read counters keyed by (shader, stage) from vk_pipeline_check --stats.""" 60 """Read counters keyed by (shader, stage) from vk_pipeline_check --stats."""
60 out = defaultdict(dict) 61 out = defaultdict(dict)
61 with open(path, newline="", encoding="utf-8") as f: 62 with open(path, newline="", encoding="utf-8") as f:
62 reader = csv.DictReader(f) 63 reader = csv.DictReader(f, strict=True)
63 header = reader.fieldnames or [] 64 header = reader.fieldnames or []
64 missing = [c for c in REQUIRED if c not in header] 65 missing = [c for c in REQUIRED if c not in header]
65 if missing: 66 if missing:
@@ -69,6 +70,8 @@ def load_stats(path):
69 raise ValueError(f"line 1: duplicated required header column(s): {', '.join(duplicates)}") 70 raise ValueError(f"line 1: duplicated required header column(s): {', '.join(duplicates)}")
70 for row in reader: 71 for row in reader:
71 line = reader.line_num 72 line = reader.line_num
73 if None in row:
74 raise ValueError(f"line {line}: row has more fields than the header")
72 absent = [c for c in REQUIRED if row[c] is None] 75 absent = [c for c in REQUIRED if row[c] is None]
73 if absent: 76 if absent:
74 raise ValueError(f"line {line}: row missing required column(s): {', '.join(absent)}") 77 raise ValueError(f"line {line}: row missing required column(s): {', '.join(absent)}")
@@ -96,7 +99,7 @@ def shader_row(name, stage, st, src):
96 r = {"name": name, "stage": stage, "orig": n_orig, "v_orig": v_orig} 99 r = {"name": name, "stage": stage, "orig": n_orig, "v_orig": v_orig}
97 for key, stat in METRICS: 100 for key, stat in METRICS:
98 r[key] = number(st.get(stat)) 101 r[key] = number(st.get(stat))
99 r["growth"] = None if r["aco"] is None else r["aco"] / max(n_orig, 1) 102 r["growth"] = r["aco"] / n_orig if n_orig and r["aco"] is not None else None
100 103
101 spill_counts = [number(st.get(stat)) for stat in SPILLS] 104 spill_counts = [number(st.get(stat)) for stat in SPILLS]
102 known_spills = [v for v in spill_counts if v is not None] 105 known_spills = [v for v in spill_counts if v is not None]
diff --git a/scripts/vs_input_survey.py b/scripts/vs_input_survey.py
index fa6701c15..0c2326309 100644
--- a/scripts/vs_input_survey.py
+++ b/scripts/vs_input_survey.py
@@ -114,6 +114,8 @@ def survey(dxbc_dir):
114 index = json.load(f) 114 index = json.load(f)
115 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): 115 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index):
116 raise ValueError("index.json is not a list of shader entries") 116 raise ValueError("index.json is not a list of shader entries")
117 if not all(isinstance(e.get("file"), str) for e in index if e.get("stage") == "vs"):
118 raise ValueError("index.json has a vertex shader entry without a string file")
117 names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"] 119 names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"]
118 markers, vgprs, families = Counter(), Counter(), Counter() 120 markers, vgprs, families = Counter(), Counter(), Counter()
119 missing = 0 121 missing = 0
diff --git a/scripts/vs_layout_census.py b/scripts/vs_layout_census.py
new file mode 100644
index 000000000..249a9c74e
--- /dev/null
+++ b/scripts/vs_layout_census.py
@@ -0,0 +1,221 @@
1"""SHADER-33 follow-up: which PAL hardware stage every FSSM payload runs on, and whether the VS input layout holds.
2
3 python -I scripts/vs_layout_census.py <work>/shaders/dxbc [--json OUT] [--limit N]
4
5Reads <dxbc>/index.json, every tag-0x0D payload of each container (tools/fssm_unpack.unpack_all) and its PAL
6stage descriptors (tools/pal_stages.stage_descriptors), then the code: the .s listing for the container's last
7payload (fssm_unpack's default) and, for any earlier payload, a fresh llvm-mc disassembly. Prints counts only:
8
9- payloads by (API id, PAL hardware id) and the carve index's stage for the same stem
10- NGG markers per hardware id: `exp prim`, any `s_sendmsg`, `s_sendmsg MSG_GS_ALLOC_REQ` (the NGG
11 allocation), `s_sendmsg` with `GS_OP_*` (legacy geometry-stream output) and `v_mbcnt`
12- for API-VS payloads (hardware id 4 = the hardware VS; id 2 = the ES variant of a two-payload container):
13 the fetch call, the entry VGPRs read before written (scripts/vs_input_survey.read_before_write) and the
14 v0/v3 families of scripts/vs_input_survey.survey
15
16The hardware-stage names come from tools/pal_stages.py (an outside project's id order); this census is what
17checks them against the code: every hardware-id-7 payload carries the NGG markers and no other stage does.
18Standard library only; llvm-mc only for payloads without a listing. Nothing from the game is printed or
19written beyond counts.
20"""
21import argparse
22import json
23import os
24import re
25import sys
26from collections import Counter, defaultdict
27
28ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29sys.path.insert(0, os.path.join(ROOT, "tools"))
30sys.path.insert(0, os.path.join(ROOT, "scripts"))
31import fssm_unpack # noqa: E402
32import pal_stages # noqa: E402
33import shader_disasm # noqa: E402
34import shader_ir # noqa: E402
35from vs_input_survey import (FETCH_CALL, MBCNT, PARAM_EXPORT, POS0_EXPORT, PRIM_EXPORT, SENDMSG, # noqa: E402
36 read_before_write)
37
38ALLOC_REQ = re.compile(r"s_sendmsg\s+sendmsg\(MSG_GS_ALLOC_REQ\)")
39GS_OP = re.compile(r"s_sendmsg\s+sendmsg\(MSG_GS,")
40
41
42def markers(text):
43 """The code markers that separate the NGG path, legacy GS stream output and the plain VS."""
44 return {
45 "exp prim": bool(PRIM_EXPORT.search(text)),
46 "s_sendmsg": bool(SENDMSG.search(text)),
47 "s_sendmsg GS_ALLOC_REQ": bool(ALLOC_REQ.search(text)),
48 "s_sendmsg GS_OP": bool(GS_OP.search(text)),
49 "v_mbcnt": bool(MBCNT.search(text)),
50 "exp pos0": bool(POS0_EXPORT.search(text)),
51 "exp param": bool(PARAM_EXPORT.search(text)),
52 "fetch call": bool(FETCH_CALL.search(text)),
53 }
54
55
56def insns_from_text(text):
57 """shader_ir instructions from listing text (no file, no pc tracking: read_before_write needs neither)."""
58 insns = []
59 for line in text.splitlines():
60 if not line.startswith("\t"):
61 continue
62 ins = shader_ir.parse_line(line)
63 if ins:
64 insns.append(ins)
65 return insns
66
67
68def default_disasm(blob):
69 """llvm-mc disassembly of one FSSM payload's code range (the same mcpu make_game uses)."""
70 start, end, _how = shader_disasm.code_range(blob)
71 if end is None:
72 return ""
73 asm, _bad, _err = shader_disasm.disasm(blob[start:end], "gfx1013")
74 return asm
75
76
77def payloads_of(dxbc_path):
78 """(stem, payload index, blob, listed) for every tag-0x0D payload of every container, in index order."""
79 with open(dxbc_path, "rb") as f:
80 data = f.read()
81 try:
82 blobs = fssm_unpack.unpack_all(data)
83 except (ValueError, OSError):
84 return []
85 listed = len(blobs) - 1
86 return [(os.path.splitext(os.path.basename(dxbc_path))[0], i, blob, i == listed)
87 for i, blob in enumerate(blobs)]
88
89
90def survey(dxbc_dir, disasm_fn=None, limit=None):
91 """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs."""
92 index_path = os.path.join(dxbc_dir, "index.json")
93 with open(index_path, encoding="utf-8") as f:
94 index = json.load(f)
95 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index):
96 raise ValueError("index.json is not a list of shader entries")
97 stages = {}
98 names = []
99 for e in index:
100 if isinstance(e.get("file"), str):
101 stem = os.path.splitext(e["file"])[0]
102 if stem not in stages:
103 names.append(stem)
104 stages[stem] = e.get("stage")
105 if limit is not None:
106 names = names[:limit]
107
108 by_stage_hw = Counter()
109 markers_by_hw = defaultdict(Counter)
110 descriptors_per_blob = Counter()
111 api_mismatch = 0
112 no_record = 0
113 vs_rows = []
114 disassembled = 0
115 for name in names:
116 dxbc_path = os.path.join(dxbc_dir, name + ".dxbc")
117 if not os.path.isfile(dxbc_path):
118 continue
119 rows = payloads_of(dxbc_path)
120 for _stem, payload_index, blob, listed in rows:
121 records = pal_stages.stage_descriptors(blob)
122 if not records:
123 no_record += 1
124 continue
125 first = records[0]
126 hw, api = first["hardware_id"], first["api_id"]
127 by_stage_hw[(stages.get(name), api, hw)] += 1
128 descriptors_per_blob[len(records)] += 1
129 if stages.get(name) and api is not None and stages[name] != {0: "vs", 1: "ps", 2: "gs", 3: "cs",
130 6: "ms"}.get(api):
131 api_mismatch += 1
132 listing = os.path.join(dxbc_dir, "disasm", name + ".s")
133 if listed and os.path.isfile(listing):
134 with open(listing, encoding="utf-8", errors="replace") as f:
135 text = f.read()
136 elif disasm_fn is not None:
137 text = disasm_fn(blob)
138 disassembled += 1
139 else:
140 text = None
141 if text is not None:
142 for key, value in markers(text).items():
143 if value:
144 markers_by_hw[hw][key] += 1
145 if api == 0:
146 entry = {"hw": hw, "payload": payload_index, "listed": listed}
147 if text is not None:
148 _, read_v = read_before_write(insns_from_text(text))
149 low = sorted(r for r in read_v if r < 16)
150 entry.update({
151 "fetch": bool(FETCH_CALL.search(text)),
152 "reads_v0": 0 in read_v,
153 "reads_v3": 3 in read_v,
154 "reads_v1_v2": any(r in (1, 2) for r in read_v),
155 "low_vgprs": low,
156 })
157 vs_rows.append(entry)
158
159 return {
160 "containers": len(names),
161 "payloads": sum(by_stage_hw.values()),
162 "payloads_without_record": no_record,
163 "descriptors_per_blob": dict(sorted(descriptors_per_blob.items())),
164 "api_stage_mismatches": api_mismatch,
165 "disassembled_unlisted": disassembled,
166 "by_stage_hw": {"|".join(str(x) for x in k): v for k, v in sorted(by_stage_hw.items(),
167 key=lambda kv: (str(kv[0][0]), kv[0][1] or -1, kv[0][2] or -1))},
168 "markers_by_hw": {str(hw): dict(sorted(c.items())) for hw, c in sorted(markers_by_hw.items())},
169 "vs_payloads": len(vs_rows),
170 "vs_by_hw": dict(sorted(Counter(r["hw"] for r in vs_rows).items())),
171 "vs_fetch": sum(1 for r in vs_rows if r.get("fetch")),
172 "vs_reads_v0": sum(1 for r in vs_rows if r.get("reads_v0")),
173 "vs_reads_v3": sum(1 for r in vs_rows if r.get("reads_v3")),
174 "vs_reads_v1_v2": sum(1 for r in vs_rows if r.get("reads_v1_v2")),
175 "vs_low_vgprs": {str(hw): dict(sorted(Counter(",".join(map(str, r.get("low_vgprs", ())))
176 for r in vs_rows if r["hw"] == hw).items(),
177 key=lambda kv: -kv[1])[:12])
178 for hw in sorted({r["hw"] for r in vs_rows})},
179 }
180
181
182def main(argv=None):
183 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
184 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py")
185 ap.add_argument("--json", help="also write the counts as JSON")
186 ap.add_argument("--limit", type=int, help="stop after this many containers (index order)")
187 a = ap.parse_args(argv)
188 index_path = os.path.join(a.dxbc, "index.json")
189 if a.json and os.path.exists(a.json) and os.path.exists(index_path) and os.path.samefile(a.json, index_path):
190 print(f"vs_layout_census: error: --json would overwrite the input {index_path}", file=sys.stderr)
191 return 2
192 try:
193 r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit)
194 except (OSError, ValueError) as e:
195 print(f"vs_layout_census: error: cannot read {index_path}: {e}", file=sys.stderr)
196 return 2
197 print(f"{r['containers']} containers, {r['payloads']} payloads "
198 f"({r['payloads_without_record']} without a PAL record), descriptors per blob {r['descriptors_per_blob']}")
199 print("stage/hw (carve stage|API|PAL hw):", r["by_stage_hw"])
200 print("markers by PAL hw:", r["markers_by_hw"])
201 print(f"API-vs payloads {r['vs_payloads']} by PAL hw {r['vs_by_hw']}: fetch {r['vs_fetch']}, "
202 f"reads v0 {r['vs_reads_v0']}, reads v3 {r['vs_reads_v3']}, reads v1/v2 {r['vs_reads_v1_v2']}")
203 print("VS/ES entry VGPRs (low 16, top 12):", r["vs_low_vgprs"])
204 print(f"API stage mismatches {r['api_stage_mismatches']}, "
205 f"unlisted payloads disassembled {r['disassembled_unlisted']}")
206 if a.json:
207 try:
208 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
209 json.dump(r, f, indent=1)
210 except OSError as e:
211 print(f"vs_layout_census: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
212 return 2
213 return 0
214
215
216if __name__ == "__main__":
217 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
218 sys.stdout.reconfigure(errors="replace")
219 except (AttributeError, ValueError, OSError):
220 pass
221 sys.exit(main())