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:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 14:37:20 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 14:37:20 -0500
commit721a3b85aedebb52b00b6a34cc269ee72d62b8b6 (patch)
tree39f9295e2b46c4d2abd32181eef242c069b938c2 /scripts
parent5668f16b490a182452521fca3ccfc29e682eca2b (diff)
parente18b59a5b77a8400f66b71b5f12d713bb12c63e0 (diff)
Merge main into wave64-partial-wave-zero
Conflict in scripts/run_gpu_tests.py: the dump-test name list gained cs_w64x_cmp_sdst on main and cs_w64x_partial_swizzle here; both are kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'scripts')
-rw-r--r--scripts/bench_wave64.py8
-rw-r--r--scripts/build_runtime.ps16
-rw-r--r--scripts/check_no_game_data.py21
-rw-r--r--scripts/ci_expected_failures.py18
-rwxr-xr-xscripts/linux-boot/boot-digest.sh75
-rwxr-xr-xscripts/linux-boot/boot-inner.sh45
-rwxr-xr-xscripts/linux-boot/boot.sh42
-rwxr-xr-xscripts/linux-boot/configure-worktree.sh9
-rwxr-xr-xscripts/linux-boot/run-boot.sh56
-rw-r--r--scripts/merge_check.py8
-rwxr-xr-xscripts/run_game_wine.sh293
-rw-r--r--scripts/run_gpu_tests.py86
-rw-r--r--scripts/run_semantic_tests.py209
-rw-r--r--scripts/run_wine_tests.py228
-rw-r--r--scripts/translate_pipeline_compute.py174
-rw-r--r--scripts/windows-boot/README.md93
-rw-r--r--scripts/windows-boot/boot.ps1456
17 files changed, 1742 insertions, 85 deletions
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index e6fd59737..57253cb57 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -44,7 +44,13 @@ def build(work, name, emulate, llvm_mc):
44 r = subprocess.run([sys.executable, "-I", BUILD_PY, out, name], env=env, capture_output=True, text=True) 44 r = subprocess.run([sys.executable, "-I", BUILD_PY, out, name], env=env, capture_output=True, text=True)
45 if r.returncode: 45 if r.returncode:
46 sys.exit(r.stdout + r.stderr) 46 sys.exit(r.stdout + r.stderr)
47 return os.path.join(out, "spirv", name + ".spv") 47 spv = os.path.join(out, "spirv", name + ".spv")
48 if not os.path.isfile(spv):
49 mode = "emulated" if emulate else "native"
50 message = f"{name}: {mode} build did not produce a SPIR-V module"
51 reason = (r.stdout + r.stderr).strip()
52 sys.exit(f"{message}\n{reason}" if reason else message)
53 return spv
48 54
49 55
50def segments(spv: str) -> tuple[int, int] | None: 56def segments(spv: str) -> tuple[int, int] | None:
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index f24cc073f..5dd8bd389 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -86,14 +86,16 @@ $build || exit /b 1
86 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) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." 86 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) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it."
87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" 87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue"
88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } 88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" }
89 $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.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\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } 89 $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.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\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" }
90 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" 90 $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`""
91 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } 91 $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" }
92 $body = @" 92 $body = @"
93cd /d "$out" || exit /b 1 93cd /d "$out" || exit /b 1
94rem 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. 94rem 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.
95rem Keep the host base in step with runtime\CMakeLists.txt GTA6RT_HOST_BASE. 95rem Keep the host base in step with runtime\CMakeLists.txt GTA6RT_HOST_BASE.
96cl /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 /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib || exit /b 1 96python -I "$root\tools\gen_bcpack_runtime_tables.py" "bcpack_tables.inc" || exit /b 1
97cl /nologo /std:c++20 /EHsc /O2 /I "." "$root\tools\bcpack_history_train.cpp" /Fe:bcpack_history_train.exe || exit /b 1
98cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE /I "." $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib user32.lib || exit /b 1
97cl /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 99cl /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
98cl /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 100cl /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
99cl /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 101cl /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
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py
index a5b65e242..ae3d06e77 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -21,7 +21,8 @@ under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb
21reported as archives that can't be checked. 21reported as archives that can't be checked.
22 22
23Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and 23Prints one line per match, `<path>: <format>` (`<format> in <archive> (<member>)` for a match inside an archive), and
24exits 1 if there is any. Standard library only, no game files. 24exits 1 if there is any. It exits 2 when a file cannot be read or git cannot list the tracked files (outside a
25repository, or git not installed). Standard library only, no game files.
25""" 26"""
26import bz2 27import bz2
27import gzip 28import gzip
@@ -41,6 +42,7 @@ MAGICS = (
41 ("RPF9 archive", 0, b"9FPR"), 42 ("RPF9 archive", 0, b"9FPR"),
42 ("RPF9 archive", 0, b"RPF9"), 43 ("RPF9 archive", 0, b"RPF9"),
43 ("TTPF texture pool", 0, b"TTPF"), 44 ("TTPF texture pool", 0, b"TTPF"),
45 ("local BCPack predictor profile", 0, b"BCPHIST1"),
44 ("RAGE resource", 0, b"RSC7"), 46 ("RAGE resource", 0, b"RSC7"),
45 ("RAGE resource", 0, b"RSC8"), 47 ("RAGE resource", 0, b"RSC8"),
46 ("RAGE resource", 0, b"RSCC"), 48 ("RAGE resource", 0, b"RSCC"),
@@ -257,6 +259,14 @@ def tracked_files(root):
257 return [os.path.join(root, p) for p in out.decode("utf-8", "surrogateescape").split("\0") if p] 259 return [os.path.join(root, p) for p in out.decode("utf-8", "surrogateescape").split("\0") if p]
258 260
259 261
262def git_error(e):
263 """One line on why git could not list the files: the first line git printed, or the OS error."""
264 if isinstance(e, subprocess.CalledProcessError):
265 lines = (e.stderr or b"").decode("utf-8", "replace").splitlines()
266 return next((line.strip() for line in lines if line.strip()), f"exit status {e.returncode}")
267 return e.strerror or str(e)
268
269
260def check(paths, unreadable=None): 270def check(paths, unreadable=None):
261 """[(path, format)] for every regular file in `paths` that starts like game data. 271 """[(path, format)] for every regular file in `paths` that starts like game data.
262 272
@@ -285,7 +295,14 @@ def display(path):
285 295
286 296
287def main(argv): 297def main(argv):
288 paths = argv or tracked_files(os.getcwd()) 298 if argv:
299 paths = argv
300 else:
301 try:
302 paths = tracked_files(os.getcwd())
303 except (OSError, subprocess.CalledProcessError) as e:
304 print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr)
305 return 2 # not 1: that is the 'game data found' code
289 unreadable = [] 306 unreadable = []
290 found = check(paths, unreadable) 307 found = check(paths, unreadable)
291 for path, name in found: 308 for path, name in found:
diff --git a/scripts/ci_expected_failures.py b/scripts/ci_expected_failures.py
index 8112dcf4b..f398020f7 100644
--- a/scripts/ci_expected_failures.py
+++ b/scripts/ci_expected_failures.py
@@ -2,11 +2,13 @@
2 2
3 python -I scripts/ci_expected_failures.py FAILED_LIST EXIT_STATUS [EXPECTED ...] 3 python -I scripts/ci_expected_failures.py FAILED_LIST EXIT_STATUS [EXPECTED ...]
4 4
5FAILED_LIST is a file with one failed test name per line, EXIT_STATUS the test runner's exit status, and each 5FAILED_LIST is a UTF-8 file with one failed test name per line and an optional BOM.
6EXPECTED argument one or more whitespace-separated test names (so a workflow can pass one quoted list). Exits 1 when a 6EXIT_STATUS is the test runner's exit status. Each EXPECTED argument is one or more whitespace-separated
7test outside EXPECTED failed, the runner failed without naming a test, or the runner was terminated by a signal 7test names, so a workflow can pass one quoted list.
8(its failure list can be incomplete); 2 on a usage error. `--help` prints this text. An expected failure absent 8
9from a completed run gets a GitHub Actions notice so the list in the workflow can shrink. 9Exits 1 when an unexpected test failed, the runner failed without naming a test, or a signal terminated the runner.
10Exits 2 on a usage error. `--help` prints this text. An expected failure absent from a completed run gets a GitHub
11Actions notice so the list in the workflow can shrink.
10""" 12"""
11 13
12import sys 14import sys
@@ -43,10 +45,10 @@ def main(argv: list[str]) -> int:
43 print(f"ci_expected_failures: EXIT_STATUS {argv[1]!r} is not an integer", file=sys.stderr) 45 print(f"ci_expected_failures: EXIT_STATUS {argv[1]!r} is not an integer", file=sys.stderr)
44 return 2 46 return 2
45 try: 47 try:
46 with open(argv[0], encoding="utf-8") as f: 48 with open(argv[0], encoding="utf-8-sig") as f:
47 failed = [line.strip() for line in f if line.strip()] 49 failed = [line.strip() for line in f if line.strip()]
48 except OSError as e: 50 except (OSError, UnicodeDecodeError) as e:
49 print(f"ci_expected_failures: {argv[0]}: {e.strerror or e}", file=sys.stderr) 51 print(f"ci_expected_failures: {argv[0]}: {getattr(e, 'strerror', None) or e}", file=sys.stderr)
50 return 2 52 return 2
51 expected = [name for arg in argv[2:] for name in arg.split()] 53 expected = [name for arg in argv[2:] for name in arg.split()]
52 code, lines = judge(failed, status, expected) 54 code, lines = judge(failed, status, expected)
diff --git a/scripts/linux-boot/boot-digest.sh b/scripts/linux-boot/boot-digest.sh
new file mode 100755
index 000000000..dd2289e30
--- /dev/null
+++ b/scripts/linux-boot/boot-digest.sh
@@ -0,0 +1,75 @@
1#!/bin/bash
2# ExecStopPost of a leonida-boot-* unit: runs after the boot ends however it ended (exit, crash, oomd kill, timeout).
3# Writes /opt/leonida/work/<agent>/boot-<n>.digest.txt and appends a line to /opt/leonida/work/boots.tsv.
4# Local only: digests quote trace lines, so they never go into commits or PRs.
5set -u
6AGENT=$1; N=$2; WORK=/opt/leonida/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv
7META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=/opt/leonida/work/boots.tsv
8START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null)
9START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s)
10RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?}
11D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2)
12STDOUT=${D3D/d3d12-run-/stdout-run-}
13CAP=/opt/leonida/capture/$AGENT-$N
14
15verdict=OK
16# systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own).
17if journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -q 'systemd-oomd killed'; then RESULT=oom-kill; fi
18case "$RESULT" in
19 oom-kill) verdict="KILLED BY OOM (systemd-oomd or kernel): memory, not a crash" ;;
20 timeout) verdict="TIMEOUT" ;;
21 exit-code) verdict="EXITED WITH ERROR (code $ECODE status $ESTAT)" ;;
22 signal|core-dump) verdict="KILLED BY SIGNAL ($ESTAT)" ;;
23 success) verdict="OK (ran to its time limit or exited cleanly)" ;;
24esac
25grep -q 'time limit reached' "$LOG" 2>/dev/null && [ "$RESULT" = success ] && verdict="OK (ran its full time limit)"
26
27cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0}"; }
28{
29 echo "== leonida boot $AGENT-$N: $verdict"
30 echo "unit result=$RESULT exit_code=$ECODE exit_status=$ESTAT"
31 echo "queued $((BOOT-START)) s, ran $((END-BOOT)) s; trace $D3D"
32 sed -n '/^LEONIDA_\|^WINEDEBUG\|^unit=/p' "$META" 2>/dev/null | tr '\n' ' '; echo
33 echo
34 echo "-- counts"
35 echo "PresentX ok $(cnt 'XboxPresentation::PresentX ok') refused $(cnt 'XboxPresentation::PresentX failed')"
36 echo "CreatePipelineState failed $(cnt 'CreatePipelineState failed') FSPX compute misses $(cnt 'no translated compute shader for FSPX') slot-67 failed $(cnt 'slot 67 call .* failed')"
37 echo "E_NOTIMPL $(cnt 'E_NOTIMPL') wine err: lines $(cnt '^[0-9a-f]{4}:err:|:err:') exceptions $(cnt -i 'exception|unhandled|page fault|access violation')"
38 grep -a -m1 -E 'translated shaders \(' "$D3D" 2>/dev/null
39 grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120
40 echo
41 echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)"
42 [ -f "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index"
43 grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140
44 echo
45 echo "-- resources (2 s samples)"
46 [ -s "$RES" ] && awk -F'\t' 'NR>1{ if(min==""||$2<min)min=$2; if($3>sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm}' "$RES" || echo "no samples"
47 journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200
48 # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of
49 # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well.
50 [ -s "$RES" ] && awk -F'\t' 'NR>1{t=$4+$5; if(t>m)m=t} END{printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024}' "$RES"
51 echo
52 echo "-- system events during the boot (OOM, GPU Xid, segfaults)"
53 { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15
54 echo
55 echo "-- distinct error lines (normalised, with counts; top 60)"
56 for f in "$D3D" "$STDOUT"; do [ -f "$f" ] && cat "$f"; done 2>/dev/null \
57 | grep -a -i -E 'error|fail|E_NOTIMPL|E_INVALIDARG|E_FAIL|0x8[0-9a-f]{7}|exception|assert|abort|unhandled|page fault|refused|not implemented|no translated|no emulation|crash|:err:|fatal|cannot|could not|unsupported|invalid' \
58 | grep -a -v -E ' ok$| called$' \
59 | sed -E 's/#[0-9]+/#N/g; s/0x[0-9a-fA-F]{6,}/0xADDR/g; s/\b[0-9a-f]{64}\b/SHA/g; s/[0-9]{4,}/NUM/g; s/^[0-9a-f]{4}:/TID:/' \
60 | cut -c1-220 | sort | uniq -c | sort -rn | head -60
61 echo
62 echo "-- where the trace ended"
63 [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200
64} > "$OUT" 2>&1
65
66frames=$( [ -f "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-")
67peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{if($4>u)u=$4} END{print u+0}' "$RES" || echo "-")
68exec 7>>"$LEDGER"; flock 7
69# Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot.
70grep -q -P "^[^\t]*\t$AGENT\t$N\t" "$LEDGER" 2>/dev/null && exit 0
71[ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7
72printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \
73 "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \
74 "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META")" >&7
75exit 0
diff --git a/scripts/linux-boot/boot-inner.sh b/scripts/linux-boot/boot-inner.sh
new file mode 100755
index 000000000..e52d3daef
--- /dev/null
+++ b/scripts/linux-boot/boot-inner.sh
@@ -0,0 +1,45 @@
1#!/bin/bash
2# Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots.
3set -u
4WORK=/opt/leonida/work/$BOOT_AGENT; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv
5META=$WORK/boot-$N.meta
6: > "$LOG"
7echo "start_epoch=$(date +%s)" > "$META"
8echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META"
9env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META"
10
11mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1)
12 awk '/^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' /proc/meminfo
13}
14NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500}
15swap_pct() { awk '/^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{printf "%d", t ? (t-f)*100/t : 0}' /proc/meminfo; }
16
17exec 8>/opt/leonida/.gpu.lock; flock 8 # one boot at a time
18echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG"
19for i in $(seq 1 40); do # up to 10 min for memory headroom
20 f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break
21 echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep 15
22done
23echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG"
24exec 9>/opt/leonida/.build.lock; flock 9 # no compiles while the game runs
25echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG"
26echo "boot_epoch=$(date +%s)" >> "$META"
27
28CG=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)
29( printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n'
30 while :; do
31 read -r ma su < <(awk '/^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{print int(a/1024), int((t-f)/1024)}' /proc/meminfo)
32 um=$(( $(cat "$CG/memory.current" 2>/dev/null || echo 0) / 1048576 )); us=$(( $(cat "$CG/memory.swap.current" 2>/dev/null || echo 0) / 1048576 ))
33 g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ' | tr ',' '\t')
34 printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}"
35 sleep 2
36 done ) > "$RES" 2>/dev/null &
37SAMPLER=$!
38
39/opt/leonida/boot.sh run "$BOOT_SECS" >> "$LOG" 2>&1
40rc=$?
41kill $SAMPLER 2>/dev/null
42echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG"
43# boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here.
44[ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; }
45exit $rc
diff --git a/scripts/linux-boot/boot.sh b/scripts/linux-boot/boot.sh
new file mode 100755
index 000000000..55f84f019
--- /dev/null
+++ b/scripts/linux-boot/boot.sh
@@ -0,0 +1,42 @@
1#!/bin/bash
2# Boot the packaged port under Wine with the network off (unshare -rn: user + network namespace, no root).
3# usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped)
4# Traces stay local in /opt/leonida/traces: they can quote game data, never post them.
5set -u
6MODE=${1:?dry-run|init|run}; SECS=${2:-150}
7OUT=/opt/leonida
8REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in
9STAMP=$(date +%H%M%S)
10T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv"
11
12WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx
13export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml="
14export LEONIDA_D3D12=vulkan
15export LEONIDA_SHADERS=$OUT/work/shaders/spirv
16export LEONIDA_ARENA_MB=${LEONIDA_ARENA_MB:-2048}
17export LEONIDA_PIPELINE_CACHE_BYTES=${LEONIDA_PIPELINE_CACHE_BYTES:-4294967296}
18export LEONIDA_STARTUP_CACHE_CHECKPOINTS=1
19export __GL_SHADER_DISK_CACHE=1 __GL_SHADER_DISK_CACHE_PATH=$OUT/cache/nv __GL_SHADER_DISK_CACHE_SIZE=21474836480
20export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1
21[ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1
22
23GAME_WIN='Z:\opt\gta6\GTA6.Xbox.v1.0.2.1'
24EXE=/opt/gta6/GTA6.Xbox.v1.0.2.1/game_scarlett_master.exe
25TRACE_WIN="Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl"
26D3D=$T/d3d12-$MODE-$STAMP.log
27GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=<your build>/gta6rt.exe boots a private build without installing it
28
29args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay 'Z:\opt\leonida\overlay' --trace "$TRACE_WIN")
30[ "$MODE" = run ] && args+=(--trace-d3d12)
31echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D"
32# unshare: new user + network namespace, so the title has no network at all
33if [ "$MODE" = run ]; then
34 timeout --signal=INT --kill-after=20 "$SECS" unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D"
35else
36 unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D"
37fi
38rc=$?; echo "[boot] exit=$rc"
39sleep 0
40python3 -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1
41echo "[boot] summary: $T/summary-$MODE-$STAMP.txt"
42exit $rc
diff --git a/scripts/linux-boot/configure-worktree.sh b/scripts/linux-boot/configure-worktree.sh
new file mode 100755
index 000000000..c983b3357
--- /dev/null
+++ b/scripts/linux-boot/configure-worktree.sh
@@ -0,0 +1,9 @@
1#!/bin/bash
2# usage: configure-worktree.sh <worktree>
3# Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default
4# ~/.local/share/xwin-sdk). SDL3_SRC=<an SDL3 source tree> makes the configure work offline.
5set -eu; W=$(realpath "$1")
6cmake -S "$W/runtime" -B "$W/runtime/build/boot" -G Ninja -DCMAKE_BUILD_TYPE=Release \
7 -DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" \
8 -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON -DLEONIDA_SDL3=ON \
9 ${SDL3_SRC:+-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC"}
diff --git a/scripts/linux-boot/run-boot.sh b/scripts/linux-boot/run-boot.sh
new file mode 100755
index 000000000..523d17795
--- /dev/null
+++ b/scripts/linux-boot/run-boot.sh
@@ -0,0 +1,56 @@
1#!/bin/bash
2# Boot gta6rt as its own systemd --user unit, protected from the swarm and logged in full.
3#
4# usage: run-boot.sh <agent> <n> <gta6rt.exe> [seconds=150] [KEY=VALUE ...]
5# e.g. run-boot.sh fsdraw 3 /path/wt-fsdraw/runtime/build/boot/gta6rt.exe 150 LEONIDA_FOO=1
6#
7# What it does for you:
8# - runs the boot outside your agent's process tree (survives agent/session restarts);
9# - waits for memory headroom before starting, then holds the GPU lock AND the build lock for the whole boot,
10# so no compile competes with the game for RAM;
11# - Series S profile, late-frame capture, source capture and Wine's error channel on by default (override with KEY=VALUE);
12# - samples RAM / swap / the game's memory / VRAM every 2 s;
13# - after the boot, even when systemd-oomd or a crash kills it, writes a digest with the unit result, OOM and GPU
14# kernel events and every distinct error line, and appends one line to the shared ledger /opt/leonida/work/boots.tsv.
15#
16# Outputs (in /opt/leonida/work/<agent>/): boot-<n>.log boot-<n>.resources.tsv boot-<n>.digest.txt
17set -u
18AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# ))
19[ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; }
20# gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once.
21[ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; }
22WORK=/opt/leonida/work/$AGENT; mkdir -p "$WORK"
23UNIT=leonida-boot-$AGENT-$N
24if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi
25
26declare -A ENV=(
27 [WINE]="$HOME/.local/share/Steam/steamapps/common/Proton - Experimental/files/bin/wine"
28 [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx"
29 [WINEDEBUG]="-all,err+all"
30 [GTA6RT]="$EXE"
31 [LEONIDA_CAPTURE]="Z:\\opt\\leonida\\capture\\$AGENT-$N"
32 [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1
33 [LEONIDA_DEVICE_TYPE]=6
34 [LEONIDA_PIPELINE_CACHE_DIR]="Z:\\opt\\leonida\\cache\\pipelines"
35)
36for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done
37args=()
38for k in "${!ENV[@]}"; do args+=(--setenv="$k=${ENV[$k]}"); done
39
40echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)"
41rm -f "$WORK/boot-$N.digest.txt"
42systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory=/opt/leonida \
43 --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \
44 /opt/leonida/boot-inner.sh || { echo "run-boot: could not start $UNIT" >&2; exit 2; }
45# The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the
46# caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest.
47systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \
48 /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done
49 START=$(sed -n "s/^start_epoch=//p" "/opt/leonida/work/$1/boot-$2.meta" 2>/dev/null)
50 RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //")
51 SERVICE_RESULT=${RES:-success} exec /opt/leonida/boot-digest.sh "$1" "$2"' "$UNIT" "$AGENT" "$N"
52# Block until the digest exists (so a caller that waits on this script gets the result), then print it.
53while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done
54echo "run-boot: $UNIT finished. Digest:"
55cat "$WORK/boot-$N.digest.txt"
56head -1 "$WORK/boot-$N.digest.txt" | grep -q ': OK' && exit 0 || exit 1
diff --git a/scripts/merge_check.py b/scripts/merge_check.py
index a5a098964..e270cbe00 100644
--- a/scripts/merge_check.py
+++ b/scripts/merge_check.py
@@ -65,9 +65,9 @@ def _merged_pr_number(subject):
65 65
66 66
67def prior_merges(repo, main, numbers, depth): 67def prior_merges(repo, main, numbers, depth):
68 out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout 68 out = git(repo, "log", "--first-parent", f"-n{depth}", "--format=%H%x09%s", main, "--").stdout
69 hits = {number: [] for number in numbers} 69 hits = {number: [] for number in numbers}
70 for line in out.splitlines(): 70 for line in out.split("\n"):
71 sha, _, subject = line.partition("\t") 71 sha, _, subject = line.partition("\t")
72 number = _merged_pr_number(subject) 72 number = _merged_pr_number(subject)
73 if number in hits: 73 if number in hits:
@@ -113,7 +113,7 @@ def duplicates(repo, main, tree, min_length, block=3):
113 patch = git(repo, "-c", "core.quotePath=true", "diff", "--unified=0", "--no-color", "--no-renames", 113 patch = git(repo, "-c", "core.quotePath=true", "diff", "--unified=0", "--no-color", "--no-renames",
114 "--inter-hunk-context=0", "--src-prefix=a/", "--dst-prefix=b/", "--no-relative", 114 "--inter-hunk-context=0", "--src-prefix=a/", "--dst-prefix=b/", "--no-relative",
115 "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", 115 "--no-ext-diff", "--no-textconv", "--ignore-submodules=all",
116 main, tree).stdout 116 main, tree, "--").stdout
117 for line in patch.split("\n"): 117 for line in patch.split("\n"):
118 if line.startswith("diff --git "): 118 if line.startswith("diff --git "):
119 path, added = None, None 119 path, added = None, None
@@ -132,7 +132,7 @@ def duplicates(repo, main, tree, min_length, block=3):
132 132
133 def windows(rev, path): 133 def windows(rev, path):
134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. 134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file.
135 r = git(repo, "show", f"{rev}:{path}") 135 r = git(repo, "show", f"{rev}:{path}", "--")
136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] 136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())]
137 content = [text for _, text in lines] 137 content = [text for _, text in lines]
138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) 138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1))
diff --git a/scripts/run_game_wine.sh b/scripts/run_game_wine.sh
new file mode 100755
index 000000000..ce01b0a07
--- /dev/null
+++ b/scripts/run_game_wine.sh
@@ -0,0 +1,293 @@
1#!/usr/bin/env bash
2# Run the retail game once under Wine on Linux: `gta6rt.exe --run <exe>` with the startup and D3D12 traces on, sound
3# off, a pinned Vulkan device, a hard time limit and full teardown, then print counts only
4# (tools/game_run_summary.py). Headless on a private kwin_wayland session by default, or on the current display with
5# --visible. `scripts/run_game_wine.sh --help` lists the inputs; docs/linux_proton.md has the requirements.
6#
7# The run folder's logs can quote what the title prints: they stay on this machine. Share the printed summary.
8set -u
9
10ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
11SELF=$ROOT/scripts/run_game_wine.sh
12
13usage() {
14 cat <<'EOF'
15Usage: scripts/run_game_wine.sh --build DIR --exe FILE --game-dir DIR --out DIR [options] [-- gta6rt arguments]
16
17Runs `gta6rt.exe --run <exe>` once under Wine, headless or on this display, with sound off, a pinned Vulkan device,
18a time limit and the startup and D3D12 traces on, then prints counts only. Every path comes from here or from the
19environment; nothing is assumed.
20
21Inputs:
22 --build DIR a build folder holding gta6rt.exe and gta6rt_tls_host.dll, or a checkout: its runtime/ is
23 cross-built with clang-cl and xwin (XWIN_DIR must be set) into --build-dir first
24 --build-dir DIR where a checkout is built (default <checkout>/runtime/build/wine-game-run)
25 --exe FILE the game executable (or LEONIDA_GAME_EXE)
26 --game-dir DIR the package folder; the working folder (or LEONIDA_GAME_DIR)
27 --shaders DIR the translated shader library (or LEONIDA_SHADERS; "none" leaves it unset)
28 --out DIR the run folder; it must not hold a run yet (logs, traces, saves, overlay, summary)
29 --prefix DIR the Wine prefix (or WINEPREFIX; default <out>/prefix)
30
31Options:
32 --seconds N hard time limit of the run (default 600; SIGTERM, then SIGKILL 10 s later)
33 --visible open the window on the current DISPLAY instead of a private headless session
34 --device VID:DID the Vulkan device, as MESA_VK_DEVICE_SELECT=VID:DID! (e.g. 1002:744c); without it Mesa picks
35 --screenshot-every S capture the game window into <out>/shots every S seconds (needs ImageMagick's import and
36 xprop); the shots are game content and stay local
37 --lock FILE the lock that allows one run at a time (default $XDG_RUNTIME_DIR/leonida-run-game-wine.lock,
38 or <out>/run.lock without XDG_RUNTIME_DIR)
39 -h, --help this text
40 -- ARGS further gta6rt arguments, after the fixed ones
41
42Environment:
43 WINE the wine to use (default wine on PATH; for Proton, its files/bin/wine)
44 LEONIDA_* passed to the runtime unchanged (LEONIDA_INPUT_SCRIPT, LEONIDA_ARENA_MB, ...); the launcher
45 sets LEONIDA_AUDIO=silent, and LEONIDA_D3D12=vulkan, LEONIDA_RUMBLE=0 and LEONIDA_SAVE_DIR
46 unless they are set
47
48Headless needs kwin_wayland (with Xwayland) and dbus-run-session: Xvfb has no DRI3, so RADV cannot present there.
49Sound: Wine's audio drivers are disabled, PulseAudio, PipeWire and ALSA point at nothing, and the runtime serves its
50silent output endpoint (LEONIDA_AUDIO=silent).
51EOF
52}
53
54die() { echo "run_game_wine.sh: $*" >&2; exit 2; }
55
56if [ "${1:-}" = --inner ]; then
57 # ---- inside the session: DISPLAY is kwin's Xwayland (headless) or the caller's display (--visible) ----
58 RUN=$2; BUILD=$3; LIMIT=$4; SHOT_EVERY=$5
59 shift 5
60 WINE=${WINE:-wine}
61 WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver
62 [ -x "$WINESERVER" ] || WINESERVER=wineserver
63 unset WAYLAND_DISPLAY # Wine's X11 driver on Xwayland, never its Wayland driver
64 {
65 echo "display: ${DISPLAY:-none}"
66 if command -v xdpyinfo >/dev/null 2>&1; then
67 echo "DRI3 extension: $(xdpyinfo 2>/dev/null | grep -c -w DRI3)"
68 fi
69 } >> "$RUN/session.txt"
70 mkdir -p "$WINEPREFIX"
71 "$WINESERVER" -p
72 # Warm-up: starts the prefix's services; no Mono/Gecko prompts in a new prefix.
73 WINEDLLOVERRIDES="$WINEDLLOVERRIDES;mscoree,mshtml=" "$WINE" wineboot -u </dev/null >/dev/null 2>&1
74 SHOTS=
75 if [ "$SHOT_EVERY" != 0 ]; then
76 mkdir -p "$RUN/shots"
77 (
78 n=0
79 while sleep "$SHOT_EVERY"; do
80 n=$((n + 1))
81 # Wine names the window's class after the executable: gta6rt.exe.
82 for id in $(xprop -root _NET_CLIENT_LIST 2>/dev/null | grep -o '0x[0-9a-f]*'); do
83 if xprop -id "$id" WM_CLASS 2>/dev/null | grep -qi 'gta6rt'; then
84 import -window "$id" "$RUN/shots/$(printf '%04d' "$n").png" 2>/dev/null
85 break
86 fi
87 done
88 done
89 ) &
90 SHOTS=$!
91 fi
92 cd "$GAME_DIR" || { echo 2 > "$RUN/exit_code"; exit 0; }
93 t0=$(date +%s)
94 timeout -k 10 "$LIMIT" "$WINE" "$BUILD/gta6rt.exe" --run "Z:$GAME_EXE" --game-dir "Z:$GAME_DIR" \
95 --overlay "Z:$RUN/overlay" --trace "Z:$RUN/boot.jsonl" --trace-d3d12 "$@" \
96 </dev/null > "$RUN/stdout.log" 2> "$RUN/stderr.log"
97 code=$?
98 echo "$(( $(date +%s) - t0 ))" > "$RUN/seconds"
99 echo "$code" > "$RUN/exit_code"
100 [ -n "$SHOTS" ] && kill "$SHOTS" 2>/dev/null
101 "$WINESERVER" -k 2>/dev/null
102 exit 0
103fi
104
105# ---- arguments ----
106SRC= BUILD_DIR= OUT= PREFIX=${WINEPREFIX:-} LIMIT=600 VISIBLE=0 DEVICE= SHOT_EVERY=0 LOCK=
107EXE=${LEONIDA_GAME_EXE:-} GAME=${LEONIDA_GAME_DIR:-} SHADERS=${LEONIDA_SHADERS:-}
108need() { [ $# -ge 2 ] && [ -n "$2" ] || die "$1 needs a value (see --help)"; }
109while [ $# -gt 0 ]; do
110 case $1 in
111 -h|--help) usage; exit 0 ;;
112 --build) need "$@"; SRC=$2; shift 2 ;;
113 --build-dir) need "$@"; BUILD_DIR=$2; shift 2 ;;
114 --exe) need "$@"; EXE=$2; shift 2 ;;
115 --game-dir) need "$@"; GAME=$2; shift 2 ;;
116 --shaders) need "$@"; SHADERS=$2; shift 2 ;;
117 --out) need "$@"; OUT=$2; shift 2 ;;
118 --prefix) need "$@"; PREFIX=$2; shift 2 ;;
119 --seconds) need "$@"; LIMIT=$2; shift 2 ;;
120 --visible) VISIBLE=1; shift ;;
121 --device) need "$@"; DEVICE=$2; shift 2 ;;
122 --screenshot-every) need "$@"; SHOT_EVERY=$2; shift 2 ;;
123 --lock) need "$@"; LOCK=$2; shift 2 ;;
124 --) shift; break ;;
125 *) die "unknown argument: $1 (see --help)" ;;
126 esac
127done
128
129[ -n "$SRC" ] || die "--build is required: a build folder with gta6rt.exe, or a checkout"
130[ -n "$EXE" ] || die "--exe (or LEONIDA_GAME_EXE) is required: the game executable"
131[ -n "$GAME" ] || die "--game-dir (or LEONIDA_GAME_DIR) is required: the package folder"
132[ -n "$OUT" ] || die "--out is required: the run folder"
133[ -n "$SHADERS" ] || die "--shaders (or LEONIDA_SHADERS) is required: the translated shader library, or none"
134case $LIMIT in ''|*[!0-9]*|0*) die "--seconds must be a whole number of seconds above 0, not '$LIMIT'" ;; esac
135case $SHOT_EVERY in ''|*[!0-9]*) die "--screenshot-every must be a whole number of seconds, not '$SHOT_EVERY'" ;; esac
136if [ -n "$DEVICE" ] && ! [[ $DEVICE =~ ^[0-9a-fA-F]{4}:[0-9a-fA-F]{4}$ ]]; then
137 die "--device takes VID:DID in hex, as lspci -nn prints it (e.g. 1002:744c), not '$DEVICE'"
138fi
139[ -f "$EXE" ] || die "no game executable at $EXE"
140[ -d "$GAME" ] || die "no package folder at $GAME"
141if [ "$SHADERS" != none ]; then
142 SHADERS=${SHADERS#Z:}
143 [ -d "$SHADERS" ] || die "no shader library at $SHADERS"
144fi
145EXE=$(readlink -f "$EXE"); GAME=$(readlink -f "$GAME"); SRC=$(readlink -f "$SRC")
146
147# ---- what the host needs ----
148WINE=${WINE:-wine}
149missing=()
150command -v "$WINE" >/dev/null 2>&1 || missing+=("$WINE (Wine)")
151for t in timeout flock setsid python3; do command -v $t >/dev/null 2>&1 || missing+=("$t"); done
152if [ "$VISIBLE" = 1 ]; then
153 [ -n "${DISPLAY:-}" ] || die "--visible needs DISPLAY: run it from the desktop session (an X11 or Xwayland display)"
154else
155 for t in kwin_wayland dbus-run-session Xwayland; do command -v $t >/dev/null 2>&1 || missing+=("$t"); done
156fi
157if [ "$SHOT_EVERY" != 0 ]; then
158 for t in import xprop; do command -v $t >/dev/null 2>&1 || missing+=("$t (for --screenshot-every)"); done
159fi
160if [ ${#missing[@]} -gt 0 ]; then
161 echo "run_game_wine.sh: missing: ${missing[*]}" >&2
162 [ "$VISIBLE" = 1 ] || echo " headless runs need kwin_wayland with Xwayland: Xvfb has no DRI3, so RADV cannot" \
163 "present there. Install KWin, or run on your display with --visible." >&2
164 exit 2
165fi
166
167# ---- the run folder ----
168mkdir -p "$OUT" || die "cannot create $OUT"
169OUT=$(readlink -f "$OUT")
170RUN=$OUT
171if [ -e "$RUN/boot.jsonl" ] || [ -e "$RUN/stderr.log" ]; then
172 die "$RUN already holds a run; name a new --out"
173fi
174
175# ---- the runtime: a build folder as is, or a checkout built here ----
176if [ -f "$SRC/gta6rt.exe" ]; then
177 BUILD=$SRC
178elif [ -f "$SRC/runtime/CMakeLists.txt" ]; then
179 [ -n "${XWIN_DIR:-}" ] || die "building $SRC needs XWIN_DIR (an xwin splat, docs/linux.md); or pass a build folder"
180 BUILD=$(readlink -f -m "${BUILD_DIR:-$SRC/runtime/build/wine-game-run}")
181 mkdir -p "$BUILD"
182 echo "building the runtime into $BUILD"
183 if [ ! -f "$BUILD/CMakeCache.txt" ]; then
184 cmake -S "$SRC/runtime" -B "$BUILD" --toolchain "$SRC/runtime/cmake/clang-cl-xwin.cmake" \
185 -DCMAKE_BUILD_TYPE=RelWithDebInfo > "$RUN/configure.log" 2>&1 \
186 || die "configure failed (see $RUN/configure.log)"
187 fi
188 cmake --build "$BUILD" --parallel --target gta6rt gta6rt_tls_host > "$RUN/build.log" 2>&1 \
189 || die "build failed (see $RUN/build.log)"
190else
191 die "$SRC is neither a build folder with gta6rt.exe nor a checkout with runtime/CMakeLists.txt"
192fi
193[ -f "$BUILD/gta6rt_tls_host.dll" ] || die "no gta6rt_tls_host.dll next to $BUILD/gta6rt.exe"
194
195# ---- one run at a time: a shared prefix has one wineserver ----
196LOCK=${LOCK:-${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/leonida-run-game-wine.lock}}
197LOCK=${LOCK:-$RUN/run.lock}
198exec 9>"$LOCK" || die "cannot open the lock $LOCK"
199flock -n 9 || die "another run holds $LOCK"
200mkdir -p "$RUN/overlay" "$RUN/saves"
201
202# ---- environment: private session, sound off, pinned device ----
203export GAME_EXE=$EXE GAME_DIR=$GAME
204unset LEONIDA_GAME_EXE LEONIDA_GAME_DIR # launcher inputs; LEONIDA_GAME_DIR also switches the runtime's tests
205export WINE
206export XDG_RUNTIME_DIR=$RUN/xdg
207rm -rf "$XDG_RUNTIME_DIR"; mkdir -p -m 700 "$XDG_RUNTIME_DIR"
208export XDG_CONFIG_HOME=$RUN/session/config XDG_DATA_HOME=$RUN/session/data XDG_CACHE_HOME=$RUN/session/cache \
209 XDG_STATE_HOME=$RUN/session/state
210mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_STATE_HOME"
211unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS
212if [ "$VISIBLE" = 1 ]; then
213 if command -v xdpyinfo >/dev/null 2>&1 && ! xdpyinfo >/dev/null 2>&1; then
214 die "--visible: cannot open display $DISPLAY (XAUTHORITY=${XAUTHORITY:-unset})"
215 fi
216else
217 unset DISPLAY XAUTHORITY
218fi
219export QT_QPA_PLATFORM=offscreen
220if [ -n "$DEVICE" ]; then
221 export MESA_VK_DEVICE_SELECT="$DEVICE!"
222 # kwin and Xwayland's glamor on the card that renders, so the present path stays on one device.
223 for n in /sys/class/drm/renderD*; do
224 [ "$(cat "$n/device/vendor" 2>/dev/null):$(cat "$n/device/device" 2>/dev/null)" = "0x${DEVICE%%:*}:0x${DEVICE#*:}" ] \
225 && export KWIN_DRM_DEVICES=/dev/dri/${n##*/}
226 done
227else
228 unset MESA_VK_DEVICE_SELECT
229 echo "warning: no --device: Mesa picks the Vulkan device (pass --device VID:DID to pin it)" >&2
230fi
231export WINEPREFIX=${PREFIX:-$RUN/prefix} WINEDEBUG=${WINEDEBUG:--all}
232export WINEDLLOVERRIDES="winedbg.exe=d;winemenubuilder.exe=d;winepulse.drv=d;winealsa.drv=d;wineoss.drv=d;winecoreaudio.drv=d"
233export PULSE_SERVER=unix:/nonexistent PIPEWIRE_REMOTE=/nonexistent ALSA_CONFIG_PATH=/dev/null SDL_AUDIODRIVER=dummy
234export LEONIDA_AUDIO=silent
235export LEONIDA_D3D12=${LEONIDA_D3D12:-vulkan}
236export LEONIDA_RUMBLE=${LEONIDA_RUMBLE:-0}
237export LEONIDA_SAVE_DIR=${LEONIDA_SAVE_DIR:-Z:$RUN/saves}
238if [ "$SHADERS" = none ]; then
239 unset LEONIDA_SHADERS
240else
241 export LEONIDA_SHADERS=Z:$SHADERS
242fi
243env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt"
244
245WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver
246[ -x "$WINESERVER" ] || WINESERVER=wineserver
247SESSION_PID=
248teardown() {
249 "$WINESERVER" -k 2>/dev/null
250 if [ -n "$SESSION_PID" ] && kill -0 "$SESSION_PID" 2>/dev/null; then
251 pkill -TERM -s "$SESSION_PID" 2>/dev/null; sleep 2; pkill -KILL -s "$SESSION_PID" 2>/dev/null
252 fi
253 rm -rf "$XDG_RUNTIME_DIR"
254}
255trap teardown EXIT
256trap 'exit 130' INT TERM HUP
257
258# The session command with its arguments baked in (kwin takes one program path).
259{
260 echo '#!/bin/sh'
261 printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY"
262 for a in "$@"; do printf ' %q' "$a"; done
263 echo
264} > "$RUN/inner.sh"
265chmod +x "$RUN/inner.sh"
266
267T0=$(date +%s)
268# setsid: Wine (and kwin, Xwayland and the private D-Bus when headless) form one session that teardown ends as a
269# whole, and never the user's desktop.
270if [ "$VISIBLE" = 1 ]; then
271 setsid "$RUN/inner.sh" > "$RUN/session.log" 2>&1 9>&- &
272else
273 setsid dbus-run-session -- kwin_wayland --virtual --xwayland --socket leonida-run-game-wine --width 1920 \
274 --height 1080 --no-lockscreen --no-global-shortcuts --exit-with-session "$RUN/inner.sh" \
275 > "$RUN/session.log" 2>&1 9>&- &
276fi
277SESSION_PID=$!
278# The session ends when the inner run returns; this outer limit adds a margin for the start-up.
279( sleep $((LIMIT + 180)); kill -TERM "$SESSION_PID" 2>/dev/null ) 9>&- 2>/dev/null &
280WATCH=$!
281wait "$SESSION_PID"
282pkill -P "$WATCH" 2>/dev/null; kill "$WATCH" 2>/dev/null
283teardown; SESSION_PID=
284T1=$(date +%s)
285
286echo "== $(tr '\n' ';' < "$RUN/session.txt" 2>/dev/null | sed 's/;$//')"
287if [ ! -f "$RUN/exit_code" ]; then
288 echo "the run did not start or the session ended early ($((T1 - T0)) s); see $RUN/session.log" >&2
289 exit 3
290fi
291python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt"
292echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine."
293exit 0
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 479c5b64c..897c48317 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -25,18 +25,22 @@ 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_d16_xyz_test, fmt_int_narrow_test, fmt_sint32_test, 28from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test,
29 fmt_xy_xyz_test, tbuffer_store_test) 29 fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported)
30from check import compute_unsupported # vk_compute_test's exit 77 over a feature the module needs
31from compute_fixture import compute_header 30from compute_fixture import compute_header
32from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) 31from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test)
33from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, 32from check import (CS_SMEM_VCC, CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES,
34 TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, 33 TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message,
35 pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test) 34 pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test)
36from check import SIGNED_MIP_TEST, UINT_MIP_TEST 35from check import SIGNED_MIP_TEST, UINT_MIP_TEST
37from check import cbv_modulate_test 36from check import cbv_modulate_test
37from check import IMAGE_STORE_CASES, texture_uav_test
38from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS
38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT 39from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT
39from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations 40from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations
41from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands
42from check import round_f64_test # the four binary64 roundings on memory-fed inputs
43from check import frexp_ldexp_test # binary32 and binary64 frexp, and v_ldexp_f32, on memory-fed records
40from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) 44from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan)
41from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py 45from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py
42from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 46from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8
@@ -94,10 +98,23 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_
94 return struct.pack("<I", len(r)) + bytes(r) 98 return struct.pack("<I", len(r)) + bytes(r)
95 99
96 100
101# A comment line a .asm carries when llvm-mc cannot assemble it (cs_dpp_cmp.asm: a VOPC compare in DPP form).
102TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here"
103
104
97def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: 105def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None:
98 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" 106 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py."""
99 with open(asm_path, encoding="utf-8") as source: 107 with open(asm_path, encoding="utf-8") as source:
100 raw = source.read() 108 raw = source.read()
109 if any(ln.strip() == TEXT_ONLY_MARK for ln in raw.splitlines()):
110 # The source holds an instruction llvm-mc has no gfx1013 encoding for. The translator reads straight-line
111 # code from its text alone (tests/semantic/regen_fixtures.py writes such listings), so the lines go through
112 # as they are.
113 lines = [f"; {name} code 0x0..0x0 (synthetic), gfx1013, 0 invalid words"]
114 lines += ["\t" + ln.strip() for ln in raw.splitlines() if ln.strip() and not ln.lstrip().startswith(";")]
115 with open(s_path, "w", encoding="utf-8", newline="\n") as f:
116 f.write("\n".join(lines) + "\n")
117 return
101 cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 118 cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
102 for ln in raw.splitlines(): 119 for ln in raw.splitlines():
103 s = ln.strip() 120 s = ln.strip()
@@ -264,6 +281,8 @@ def read_raw_u32(path: str) -> list[tuple[int, int, int, int]]:
264 return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)] 281 return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)]
265 282
266 283
284# cs_div_fmas_f64_rt's operands a = 1 + 2^-30, c = -(1 + 2^-29) as s4..s7 (low word first).
285DIV_FMAS_F64_SGPRS = "0x00400000,0x3ff00000,0x00800000,0xbff00000"
267UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders) 286UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders)
268 287
269 288
@@ -429,8 +448,10 @@ def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial:
429 return None, "SKIP (no 64-wide compute subgroup on this device)" 448 return None, "SKIP (no 64-wide compute subgroup on this device)"
430 if rc == 0 and wave64 and "compute subgroup size: 64" not in msg.splitlines(): 449 if rc == 0 and wave64 and "compute subgroup size: 64" not in msg.splitlines():
431 return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)" 450 return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)"
451 if rc != 0:
452 return False, f"exit {rc}: {msg or 'no test output'}"
432 words = dump_words(msg) 453 words = dump_words(msg)
433 if rc != 0 or words is None: 454 if words is None:
434 return False, msg 455 return False, msg
435 vals = words[:len(want)] 456 vals = words[:len(want)]
436 return words_match(vals, want), " ".join((hex if hexwords else str)(x) for x in vals) 457 return words_match(vals, want), " ".join((hex if hexwords else str)(x) for x in vals)
@@ -657,7 +678,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool,
657# Fixtures run by another harness, which needs what these tools do not have (a D3D12 device, the layer's root 678# Fixtures run by another harness, which needs what these tools do not have (a D3D12 device, the layer's root
658# arguments and code base). They are still assembled and translated here, so a translator regression shows, but no 679# arguments and code base). They are still assembled and translated here, so a translator regression shows, but no
659# checker runs them: the test program that owns them judges them. 680# checker runs them: the test program that owns them judges them.
660OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", 681OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "ps_m15_dual": "d3d12_translated_draw_test",
682 "vs_m15": "d3d12_translated_draw_test",
661 "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", 683 "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test",
662 "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test", 684 "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test",
663 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", 685 "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test",
@@ -665,7 +687,8 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_transl
665 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", 687 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test",
666 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test", 688 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test",
667 "ps_live_width": "w64_graphics.py", 689 "ps_live_width": "w64_graphics.py",
668 "ps_heap_index": "d3d12_heap_index_test"} 690 "ps_heap_index": "d3d12_heap_index_test",
691 "ps_quad_flat": "d3d12_quad_index_test", "vs_quad_inst": "d3d12_quad_index_test"}
669 692
670 693
671# Shaders a selected test draws with, built even when the filter leaves them out (#192). 694# Shaders a selected test draws with, built even when the filter leaves them out (#192).
@@ -981,10 +1004,22 @@ def run_suite(a, work: str) -> int:
981 if name in CLIP_CASES: 1004 if name in CLIP_CASES:
982 detail = clip_test(a.build, spirv_dir, name) 1005 detail = clip_test(a.build, spirv_dir, name)
983 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) 1006 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact"))
1007 elif name == "cs_w32_frexp_ldexp":
1008 detail = frexp_ldexp_test(a.build, spirv_dir, cs_env)
1009 results.append((name, None if isinstance(detail, Skip) else not detail,
1010 detail or "768 words exact (64 records, eight results each, and unchanged inputs)"))
984 elif name == "cs_w32_shift64": 1011 elif name == "cs_w32_shift64":
985 detail = shift64_test(a.build, spirv_dir, cs_env) 1012 detail = shift64_test(a.build, spirv_dir, cs_env)
986 results.append((name, None if isinstance(detail, Skip) else not detail, 1013 results.append((name, None if isinstance(detail, Skip) else not detail,
987 detail or "640 words exact (64 shift cases and unchanged inputs)")) 1014 detail or "640 words exact (64 shift cases and unchanged inputs)"))
1015 elif name == "cs_w32_cmp_f64":
1016 detail = cmp_f64_test(a.build, spirv_dir, cs_env)
1017 results.append((name, None if isinstance(detail, Skip) else not detail,
1018 detail or "1536 words exact (256 operand pairs and unchanged inputs)"))
1019 elif name == "cs_w32_round_f64":
1020 detail = round_f64_test(a.build, spirv_dir, cs_env)
1021 results.append((name, None if isinstance(detail, Skip) else not detail,
1022 detail or "1152 words exact (64 inputs, eight roundings each, and unchanged inputs)"))
988 elif name == "cs_workgroup_yz": 1023 elif name == "cs_workgroup_yz":
989 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) 1024 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env)
990 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" 1025 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches"
@@ -1094,6 +1129,10 @@ def run_suite(a, work: str) -> int:
1094 vals = words[:len(USER_SGPRS_WORDS)] if words else [] 1129 vals = words[:len(USER_SGPRS_WORDS)] if words else []
1095 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS, 1130 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS,
1096 " ".join(hex(x) for x in vals) if vals else msg)) 1131 " ".join(hex(x) for x in vals) if vals else msg))
1132 elif name == "cs_w32_salu_ext":
1133 detail = salu_ext_test(a.build, spirv_dir, cs_env)
1134 results.append((name, None if isinstance(detail, Skip) else not detail,
1135 detail or "80 words exact (73 results of 38 scalar ops and the untouched fill)"))
1097 elif name == "cs_f64_add": 1136 elif name == "cs_f64_add":
1098 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1137 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env)
1099 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names 1138 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names
@@ -1102,10 +1141,12 @@ def run_suite(a, work: str) -> int:
1102 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, 1141 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False,
1103 hexwords=True) 1142 hexwords=True)
1104 results.append((name, ok, detail)) 1143 results.append((name, ok, detail))
1105 elif name == "cs_div_fmas_f64": 1144 elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"):
1106 # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64, 1145 # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64,
1107 # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it. 1146 # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it.
1108 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1147 # The _rt fixture reads the same operands from s4..s7, so the driver cannot fold the Fma at compile time.
1148 env = dict(cs_env or os.environ, VKC_SGPRS=DIV_FMAS_F64_SGPRS) if name.endswith("_rt") else cs_env
1149 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env)
1109 if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64 1150 if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64
1110 results.append((name, None, unsupported_skip(msg))) 1151 results.append((name, None, unsupported_skip(msg)))
1111 else: 1152 else:
@@ -1115,7 +1156,8 @@ def run_suite(a, work: str) -> int:
1115 ok = rc == 0 and (words == fused or (not strict and words == split)) 1156 ok = rc == 0 and (words == fused or (not strict and words == split))
1116 detail = " ".join(hex(x) for x in words) if words else msg 1157 detail = " ".join(hex(x) for x in words) if words else msg
1117 if ok and words == split: 1158 if ok and words == split:
1118 detail += " (split: the driver rounds GLSL Fma on doubles twice; --fma khr fixes it)" 1159 detail += (" (split: the driver rounded GLSL Fma on doubles twice%s; --fma khr fixes it)"
1160 % ("" if name.endswith("_rt") else " when folding the constants"))
1119 results.append((name, ok, detail)) 1161 results.append((name, ok, detail))
1120 elif name == "cs_cvt_f32_sat": 1162 elif name == "cs_cvt_f32_sat":
1121 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). 1163 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS).
@@ -1160,20 +1202,21 @@ def run_suite(a, work: str) -> int:
1160 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. 1202 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none.
1161 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. 1203 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size.
1162 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) 1204 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated()))
1163 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", 1205 elif name in ("cs_smem_vcc_base", "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",
1164 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", 1206 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi",
1165 "cs_dpp_bound", "cs_dpp_w64", 1207 "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64",
1166 "cs_w64_mask_detect", 1208 "cs_w64_mask_detect",
1167 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", 1209 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute",
1168 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", 1210 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw",
1169 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", 1211 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load",
1170 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", 1212 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent",
1171 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", 1213 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end",
1172 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", 1214 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec",
1173 "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): 1215 "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"):
1174 cs_dump_wants = { 1216 cs_dump_wants = {
1175 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], 1217 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000],
1176 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone 1218 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone
1219 "cs_smem_vcc_base": CS_SMEM_VCC,
1177 "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, 1220 "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030,
1178 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], 1221 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C],
1179 # SHADER-52: wave32 lane select & 31 (40 → 8) 1222 # SHADER-52: wave32 lane select & 31 (40 → 8)
@@ -1223,6 +1266,7 @@ def run_suite(a, work: str) -> int:
1223 "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16], 1266 "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16],
1224 "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], 1267 "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7],
1225 "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], 1268 "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777],
1269 "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0],
1226 "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], 1270 "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6],
1227 # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] 1271 # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7]
1228 # without it 1272 # without it
@@ -1268,6 +1312,7 @@ def run_suite(a, work: str) -> int:
1268 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], 1312 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32],
1269 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header) 1313 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header)
1270 "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], # .asm header 1314 "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], # .asm header
1315 "cs_w64x_cmp_sdst": [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5], # .asm header
1271 "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes 1316 "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes
1272 # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm) 1317 # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm)
1273 "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120], 1318 "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120],
@@ -1300,7 +1345,7 @@ def run_suite(a, work: str) -> int:
1300 "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", 1345 "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap",
1301 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", 1346 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec",
1302 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", 1347 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8",
1303 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_w32_andn2_exec", 1348 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec",
1304 "cs_w32_exec_computed") and not emulated and not partial 1349 "cs_w32_exec_computed") and not emulated and not partial
1305 if partial: 1350 if partial:
1306 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") 1351 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64")
@@ -1314,7 +1359,7 @@ def run_suite(a, work: str) -> int:
1314 continue 1359 continue
1315 if rc == 0: 1360 if rc == 0:
1316 skip = wave32_lane_skip(msg) 1361 skip = wave32_lane_skip(msg)
1317 if skip is None and name in WAVE32_PIN_DUMPS: 1362 if rc == 0 and skip is None and name in WAVE32_PIN_DUMPS:
1318 # the device may not be able to run the wave size this fixture was written for (a 64-only device 1363 # the device may not be able to run the wave size this fixture was written for (a 64-only device
1319 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too 1364 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too
1320 skip = subgroup_pin_skip(msg, cs_env) 1365 skip = subgroup_pin_skip(msg, cs_env)
@@ -1330,12 +1375,13 @@ def run_suite(a, work: str) -> int:
1330 unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) 1375 unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None)
1331 detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" 1376 detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)"
1332 results.append((name, ok, detail)) 1377 results.append((name, ok, detail))
1333 elif name == "cs_imgstore": 1378 elif name in IMAGE_STORE_CASES:
1334 rc, msg = run_cmd([vk_store, spv]) 1379 rc, msg = run_cmd([vk_store, spv, *IMAGE_STORE_CASES[name]])
1335 results.append((name, *helper_result(rc, msg)))
1336 elif name in ("cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"):
1337 rc, msg = run_cmd([vk_store, spv, "load" if name in ("cs_imgload", "cs_imgload_tfe") else "load-d16"])
1338 results.append((name, *helper_result(rc, msg))) 1380 results.append((name, *helper_result(rc, msg)))
1381 elif name == "cs_texture_uav":
1382 problem = texture_uav_test(a.build, spv)
1383 results.append((name, None if isinstance(problem, Skip) else not problem,
1384 problem or "D3D12/Vulkan storage-image readback matched"))
1339 elif name in MIP_TEST_PASSES: 1385 elif name in MIP_TEST_PASSES:
1340 problem = texture_mip_test(a.build, spirv_dir, name) 1386 problem = texture_mip_test(a.build, spirv_dir, name)
1341 ok = None if isinstance(problem, Skip) else not problem 1387 ok = None if isinstance(problem, Skip) else not problem
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
index c364bb35d..514e78133 100644
--- a/scripts/run_semantic_tests.py
+++ b/scripts/run_semantic_tests.py
@@ -12,12 +12,14 @@ the pattern matches their basenames, not directory paths. Package `__init__.py`
12because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an 12because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an
13error in serial and parallel runs. 13error in serial and parallel runs.
14 14
15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each as 15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in its own process from that folder, so a file sees the same import path as under discover.
16`python -m unittest <module>` from that folder, so a file sees the same import path as under discover. The files can 16
17run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, 17The files can run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1,
18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary 18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary
19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. 19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only.
20 20
21The count of tests comes from unittest's own result object, not from its output: a module that writes a line shaped like unittest's summary to stderr - a nested runner, or an atexit handler that runs after unittest's own summary - cannot change it.
22
21`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with 23`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with
22`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. 24`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits.
23A timeout fails the run and reports any output already produced; other parallel modules keep running. 25A timeout fails the run and reports any output already produced; other parallel modules keep running.
@@ -26,16 +28,80 @@ The default has no time limit. This stops the direct test subprocess, not any de
26import argparse 28import argparse
27import concurrent.futures 29import concurrent.futures
28import fnmatch 30import fnmatch
31import json
29import locale 32import locale
30import math 33import math
31import os 34import os
32import re 35import re
33import subprocess 36import subprocess
34import sys 37import sys
38import tempfile
39import threading
35import time 40import time
36 41
37MAX_TIMEOUT_SECONDS = 24 * 60 * 60 42MAX_TIMEOUT_SECONDS = 24 * 60 * 60
38 43
44# The child processes running right now: on SIGINT / Ctrl+C, the main thread terminates them so no orphans linger.
45_active_processes = set()
46_processes_lock = threading.Lock()
47
48
49def _register_process(proc):
50 with _processes_lock:
51 _active_processes.add(proc)
52
53
54def _unregister_process(proc):
55 with _processes_lock:
56 _active_processes.discard(proc)
57
58
59def _kill_process_tree(proc):
60 if proc is None:
61 return
62 if os.name == "nt":
63 try:
64 subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
65 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
66 except OSError:
67 pass
68 try:
69 proc.kill()
70 except OSError:
71 pass
72
73
74def _terminate_active_processes():
75 with _processes_lock:
76 procs = list(_active_processes)
77 for p in procs:
78 try:
79 p.terminate()
80 except OSError:
81 pass
82 for p in procs:
83 _kill_process_tree(p)
84 try:
85 p.wait(timeout=0.2)
86 except (subprocess.TimeoutExpired, OSError):
87 pass
88
89# The child runs the module through unittest's own program and writes the result to a file, so the count of tests
90# comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1
91# when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so
92# the name is imported and not looked up as an attribute of the program itself.
93CHILD_PROGRAM = (
94 "import json, os, sys, unittest\n"
95 "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n"
96 "result = program.result\n"
97 "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n"
98 " json.dump({'testsRun': result.testsRun}, handle)\n"
99 "if not result.wasSuccessful():\n"
100 " sys.exit(1)\n"
101 "elif result.testsRun == 0 and len(result.skipped) == 0:\n"
102 " sys.exit(5)\n"
103 "sys.exit(0)\n")
104
39 105
40def module_path(directory, module): 106def module_path(directory, module):
41 """Source path of a dotted module name, including a package's `__init__.py`.""" 107 """Source path of a dotted module name, including a package's `__init__.py`."""
@@ -73,28 +139,55 @@ def positive_seconds(value):
73 return seconds 139 return seconds
74 140
75 141
142def read_count(path):
143 """The number of tests the child ran, as unittest's own result object reported it."""
144 try:
145 with open(path, encoding="utf-8") as handle:
146 return int(json.load(handle)["testsRun"])
147 except (OSError, ValueError, KeyError, TypeError):
148 # The child wrote no result: it did not finish, so no test is known to have run.
149 return 0
150
151
76def run_module(directory, module, verbose, timeout=None): 152def run_module(directory, module, verbose, timeout=None):
77 """(return code, tests run, output) of `python -m unittest <target>` run from `directory`.""" 153 """(return code, tests run, output) of `python -m unittest <target>` run from `directory`."""
78 # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a 154 # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a
79 # registration in the initializer happens twice. Running the package itself imports it once; module_path() is 155 # registration in the initializer happens twice. Running the package itself imports it once; module_path() is
80 # still the initializer's path, so the jobs stay sorted by the file they run. 156 # still the initializer's path, so the jobs stay sorted by the file they run.
81 target = module[:-len(".__init__")] if module.endswith(".__init__") else module 157 target = module[:-len(".__init__")] if module.endswith(".__init__") else module
82 cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), target] 158 cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target]
83 try: 159 with tempfile.TemporaryDirectory() as scratch:
84 p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, 160 count_path = os.path.join(scratch, "count.json")
85 errors="replace", timeout=timeout) 161 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path)
86 except subprocess.TimeoutExpired as exc: 162 proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
87 out = exc.stdout or "" 163 text=True, errors="replace")
88 if isinstance(out, bytes): # TimeoutExpired retains bytes even when text=True. 164 _register_process(proc)
89 out = out.decode(locale.getpreferredencoding(False), errors="replace") 165 try:
90 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" 166 stdout, stderr = proc.communicate(timeout=timeout)
91 ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M) 167 except subprocess.TimeoutExpired:
92 count = int(ran.group(1)) if ran else 0 168 _kill_process_tree(proc)
169 stdout, stderr = proc.communicate()
170 # TimeoutExpired retains bytes even when text=True.
171 parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes)
172 else chunk for chunk in (stdout, stderr) if chunk]
173 out = "".join(parts)
174 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n"
175 except BaseException:
176 _kill_process_tree(proc)
177 try:
178 proc.wait(timeout=0.5)
179 except (subprocess.TimeoutExpired, OSError):
180 pass
181 raise
182 finally:
183 _unregister_process(proc)
184 count = read_count(count_path)
185 out = stdout + stderr
93 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the 186 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the
94 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. 187 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure.
95 if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stdout: 188 if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr:
96 return 0, 0, p.stdout 189 return 0, 0, out
97 return p.returncode, count, p.stdout 190 return proc.returncode, count, out
98 191
99 192
100def main(argv=None): 193def main(argv=None):
@@ -113,26 +206,76 @@ def main(argv=None):
113 print(f"no {a.pattern} files in {directory}") 206 print(f"no {a.pattern} files in {directory}")
114 return 1 207 return 1
115 if a.jobs <= 1: 208 if a.jobs <= 1:
209 cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory,
210 "-p", a.pattern, *(["-v"] if a.verbose else [])]
211 proc = subprocess.Popen(cmd)
212 _register_process(proc)
213 start_time = time.monotonic()
116 try: 214 try:
117 return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, 215 while True:
118 "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) 216 try:
217 return proc.wait(timeout=0.2)
218 except subprocess.TimeoutExpired:
219 if a.timeout is not None and time.monotonic() - start_time >= a.timeout:
220 raise
119 except subprocess.TimeoutExpired: 221 except subprocess.TimeoutExpired:
120 # Inherited stdout/stderr have already emitted any partial test output. 222 _kill_process_tree(proc)
121 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) 223 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr)
122 return 1 224 return 1
225 except KeyboardInterrupt:
226 _kill_process_tree(proc)
227 try:
228 proc.wait(timeout=0.5)
229 except (subprocess.TimeoutExpired, OSError):
230 pass
231 print("interrupted", file=sys.stderr)
232 return 130
233 except BaseException:
234 _kill_process_tree(proc)
235 raise
236 finally:
237 _unregister_process(proc)
123 # Largest files first: they tend to run longest, and one started last would set the wall time alone. 238 # Largest files first: they tend to run longest, and one started last would set the wall time alone.
124 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) 239 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m)))
125 start, total, failed = time.monotonic(), 0, [] 240 start, total, failed = time.monotonic(), 0, []
126 with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: 241 pool = concurrent.futures.ThreadPoolExecutor(a.jobs)
127 jobs = {pool.submit(run_module, directory, m, a.verbose, a.timeout): m for m in modules} 242 jobs = {}
128 for job in concurrent.futures.as_completed(jobs): 243 try:
129 code, ran, out = job.result() 244 for m in modules:
130 total += ran 245 jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m
131 if code: 246 pending = set(jobs)
132 failed.append(jobs[job]) 247 while pending:
133 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) 248 done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED)
134 elif a.verbose: 249 for job in done:
135 print(f"==== {jobs[job]}\n{out}", flush=True) 250 pending.remove(job)
251 code, ran, out = job.result()
252 total += ran
253 if code:
254 failed.append(jobs[job])
255 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True)
256 elif a.verbose:
257 print(f"==== {jobs[job]}\n{out}", flush=True)
258 except KeyboardInterrupt:
259 for job in jobs:
260 job.cancel()
261 try:
262 pool.shutdown(wait=False, cancel_futures=True)
263 except TypeError:
264 pool.shutdown(wait=False)
265 _terminate_active_processes()
266 print("interrupted", file=sys.stderr)
267 return 130
268 except BaseException:
269 for job in jobs:
270 job.cancel()
271 try:
272 pool.shutdown(wait=False, cancel_futures=True)
273 except TypeError:
274 pool.shutdown(wait=False)
275 _terminate_active_processes()
276 raise
277 else:
278 pool.shutdown(wait=True)
136 took = time.monotonic() - start 279 took = time.monotonic() - start
137 summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" 280 summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs"
138 print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) 281 print(summary + (": " + ", ".join(sorted(failed)) if failed else ""))
@@ -149,4 +292,8 @@ if __name__ == "__main__":
149 sys.stdout.reconfigure(errors="replace") 292 sys.stdout.reconfigure(errors="replace")
150 except (AttributeError, ValueError, OSError): 293 except (AttributeError, ValueError, OSError):
151 pass 294 pass
152 sys.exit(main()) 295 try:
296 sys.exit(main())
297 except KeyboardInterrupt:
298 print("interrupted", file=sys.stderr)
299 sys.exit(130)
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index 8435f7fb9..d36011430 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -2,7 +2,7 @@
2 2
3Usage: 3Usage:
4 python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida 4 python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida
5 [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--summary FILE] [--label TEXT] 5 [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--jobs N] [--summary FILE] [--label TEXT]
6 6
7--tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was 7--tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was
8made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default: 8made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default:
@@ -16,8 +16,16 @@ Every test is reported. The exit code is 1 if a test named by --require fails or
16others show what does and doesn't work under Wine yet without failing the job. 16others show what does and doesn't work under Wine yet without failing the job.
17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. 17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test.
18Relative executable paths in --wine or WINE are read from the directory where you start this runner. 18Relative executable paths in --wine or WINE are read from the directory where you start this runner.
19
20Each test gets WINEDLLOVERRIDES with winedbg.exe and winemenubuilder.exe disabled, so a crash fails at once instead of
21waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One
22wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command,
23else the one on PATH) and stopped at the end, instead of a new one starting for every test.
24--jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and
25DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default).
19""" 26"""
20import argparse 27import argparse
28from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
21from graphlib import CycleError, TopologicalSorter 29from graphlib import CycleError, TopologicalSorter
22import json 30import json
23import math 31import math
@@ -30,6 +38,7 @@ import signal
30import subprocess 38import subprocess
31import sys 39import sys
32import tempfile 40import tempfile
41import threading
33import time 42import time
34 43
35ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 44ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -120,6 +129,97 @@ class DriveMap:
120 return False 129 return False
121 130
122 131
132# A crashed test would wait in winedbg until the timeout; winemenubuilder writes file associations and menu entries
133# into the user's profile when a fresh prefix is set up.
134DEFAULT_DLL_OVERRIDES = ("winedbg.exe=d", "winemenubuilder.exe=d")
135
136
137def _override_names(entry: str) -> set[str]:
138 """The programs one WINEDLLOVERRIDES entry ("a,b.exe=n") names, lower case and without .dll/.exe."""
139 names = set()
140 for name in entry.partition("=")[0].split(","):
141 name = name.strip().lower()
142 for suffix in (".dll", ".exe"):
143 if name.endswith(suffix):
144 name = name[:-len(suffix)]
145 if name:
146 names.add(name)
147 return names
148
149
150def merge_dll_overrides(given: str | None) -> str:
151 """WINEDLLOVERRIDES with the defaults added, leaving out a default for a program the given value already names."""
152 entries = [e for e in (given or "").split(";") if e.strip()]
153 named = set().union(*(_override_names(e) for e in entries))
154 return ";".join([d for d in DEFAULT_DLL_OVERRIDES if not _override_names(d) & named] + entries)
155
156
157def find_wineserver(wine: list[str]) -> str | None:
158 """The wineserver the --wine command uses: $WINESERVER, else the one next to it, else the one on PATH."""
159 given = os.environ.get("WINESERVER")
160 if given and shutil.which(given):
161 return shutil.which(given)
162 for part in wine:
163 resolved = shutil.which(part)
164 if resolved and os.path.basename(resolved).lower() in ("wine", "wine64"):
165 for folder in (os.path.dirname(resolved), os.path.dirname(os.path.realpath(resolved))):
166 sibling = shutil.which(os.path.join(folder, "wineserver"))
167 if sibling:
168 return sibling
169 return shutil.which("wineserver")
170
171
172class KeptServer:
173 """Keeps one wineserver alive for the run instead of one starting and stopping for every test.
174
175 `wineserver -p` starts a persistent server for $WINEPREFIX; `wineserver -k` stops it and the prefix's Wine
176 processes at the end, also after a failure or Ctrl+C. A server still shutting down (wineboot's lingers a few
177 seconds) is waited for first; one that stays (started by hand with -p) is used and left running.
178 The first Wine program a server runs starts the prefix's services, which inherit its output and live as long as
179 the server: `wine wineboot` starts them with no output, or the first test would wait for the end of its output
180 until the timeout.
181 """
182
183 def __init__(self, command: str | None, wine: list[str]):
184 self.command, self.wine, self.started, self.note = command, wine, False, ""
185
186 def _run(self, *flags, timeout=30.0) -> int | None:
187 try:
188 return subprocess.run([self.command, *flags], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
189 stderr=subprocess.DEVNULL, timeout=timeout).returncode
190 except (OSError, subprocess.TimeoutExpired):
191 return None
192
193 def __enter__(self):
194 if not self.command:
195 self.note = "no wineserver found: each test starts its own"
196 return self
197 code = self._run("-p")
198 if code == 2: # one is already running for this prefix
199 if self._run("-w", timeout=15.0) == 0:
200 code = self._run("-p")
201 else:
202 self.note = "a wineserver already runs for this prefix: used and left running"
203 return self
204 self.started = code == 0
205 if not self.started:
206 self.note = f"could not start {self.command} -p: each test starts its own server"
207 return self
208 self.note = "wineserver kept alive for the run"
209 env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES")))
210 try:
211 subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
212 stderr=subprocess.DEVNULL, env=env, timeout=120)
213 except (OSError, subprocess.TimeoutExpired):
214 pass # the tests start the services then, as without a kept server
215 return self
216
217 def __exit__(self, *exc):
218 if self.started:
219 self._run("-k")
220 return False
221
222
123def wine_path(path: str) -> str: 223def wine_path(path: str) -> str:
124 """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y.""" 224 """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y."""
125 return "Z:" + os.path.abspath(path).replace("/", "\\") 225 return "Z:" + os.path.abspath(path).replace("/", "\\")
@@ -194,6 +294,7 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...
194 if not key or not equals or "\0" in assignment: 294 if not key or not equals or "\0" in assignment:
195 return "fail", "invalid CTest ENVIRONMENT entry: expected NAME=value" 295 return "fail", "invalid CTest ENVIRONMENT entry: expected NAME=value"
196 env[key] = value 296 env[key] = value
297 env["WINEDLLOVERRIDES"] = merge_dll_overrides(env.get("WINEDLLOVERRIDES"))
197 timeout = args.timeout 298 timeout = args.timeout
198 if "TIMEOUT" in props: 299 if "TIMEOUT" in props:
199 try: 300 try:
@@ -257,19 +358,42 @@ def run_test_process(argv: list[str], *, cwd: str, env: dict[str, str],
257 358
258 # Wine's Windows children and launcher wrappers can outlive the immediate child. 359 # Wine's Windows children and launcher wrappers can outlive the immediate child.
259 with subprocess.Popen(argv, **options, start_new_session=True) as proc: 360 with subprocess.Popen(argv, **options, start_new_session=True) as proc:
361 with _running_lock:
362 _running.add(proc.pid)
260 try: 363 try:
261 out, _ = proc.communicate(timeout=timeout) 364 out, _ = proc.communicate(timeout=timeout)
262 except (subprocess.TimeoutExpired, KeyboardInterrupt): 365 except (subprocess.TimeoutExpired, KeyboardInterrupt):
263 # The launcher may have exited while a helper still holds the output pipe. 366 # The launcher may have exited while a helper still holds the output pipe.
264 try: 367 _kill_group(proc.pid)
265 os.killpg(proc.pid, signal.SIGKILL)
266 except ProcessLookupError:
267 pass
268 proc.wait() 368 proc.wait()
269 raise 369 raise
370 finally:
371 with _running_lock:
372 _running.discard(proc.pid)
270 return subprocess.CompletedProcess(argv, proc.returncode, out) 373 return subprocess.CompletedProcess(argv, proc.returncode, out)
271 374
272 375
376# The process groups of the tests running now: with --jobs, Ctrl+C reaches only the main thread, which stops them.
377_running: set[int] = set()
378_running_lock = threading.Lock()
379
380
381def _kill_group(pid: int) -> None:
382 try:
383 os.killpg(pid, signal.SIGKILL)
384 except (ProcessLookupError, PermissionError):
385 pass
386
387
388def stop_running_tests() -> None:
389 if os.name != "posix":
390 return
391 with _running_lock:
392 pids = list(_running)
393 for pid in pids:
394 _kill_group(pid)
395
396
273def positive_seconds(text: str) -> float: 397def positive_seconds(text: str) -> float:
274 """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" 398 """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on."""
275 try: 399 try:
@@ -283,6 +407,17 @@ def positive_seconds(text: str) -> float:
283 return value 407 return value
284 408
285 409
410def positive_int(text: str) -> int:
411 """--jobs: a whole number of at least 1."""
412 try:
413 value = int(text)
414 except ValueError:
415 raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None
416 if value < 1:
417 raise argparse.ArgumentTypeError("must be at least 1")
418 return value
419
420
286def wine_command(text: str) -> list[str]: 421def wine_command(text: str) -> list[str]:
287 """--wine: split into a command the way a shell would, refusing blank or malformed values up front.""" 422 """--wine: split into a command the way a shell would, refusing blank or malformed values up front."""
288 try: 423 try:
@@ -331,6 +466,48 @@ def read_tests(path: str) -> list[dict] | None:
331 return tests 466 return tests
332 467
333 468
469def run_parallel(tests: list[dict], order: list[int], before: dict[int, set[int]], jobs: int, run_one, outcomes: dict,
470 results_by_index: dict, report) -> None:
471 """Run up to `jobs` tests at a time and report them in `order`, as the serial loop does.
472
473 A test starts once the tests it depends on have finished. A RUN_SERIAL test runs alone, and two tests that share
474 a RESOURCE_LOCK never run at the same time.
475 """
476 serial = {index for index, test in enumerate(tests) if truthy(properties(test).get("RUN_SERIAL"))}
477 locks = {index: set(regex_list(properties(test).get("RESOURCE_LOCK", []))) for index, test in enumerate(tests)}
478 waiting, running, held = list(order), {}, set()
479 next_report = 0
480 with ThreadPoolExecutor(max_workers=jobs) as pool:
481 try:
482 while waiting or running:
483 for index in list(waiting):
484 if len(running) >= jobs or any(r in serial for r in running.values()):
485 break
486 if before[index] - results_by_index.keys() or locks[index] & held:
487 continue
488 if index in serial and running:
489 continue
490 waiting.remove(index)
491 held |= locks[index]
492 running[pool.submit(run_one, index)] = index
493 if index in serial:
494 break
495 done, _ = wait(running, return_when=FIRST_COMPLETED)
496 for future in done:
497 index = running.pop(future)
498 outcomes[index] = future.result()
499 results_by_index[index] = outcomes[index][0]
500 held -= locks[index]
501 while next_report < len(order) and order[next_report] in outcomes:
502 report(order[next_report])
503 next_report += 1
504 except BaseException:
505 # Ctrl+C reaches this thread only: stop the tests the workers are waiting on, start no more.
506 pool.shutdown(wait=False, cancel_futures=True)
507 stop_running_tests()
508 raise
509
510
334def main() -> int: 511def main() -> int:
335 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 512 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
336 ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build") 513 ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build")
@@ -341,6 +518,8 @@ def main() -> int:
341 ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") 518 ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)")
342 ap.add_argument("--timeout", type=positive_seconds, default=120.0, 519 ap.add_argument("--timeout", type=positive_seconds, default=120.0,
343 help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") 520 help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)")
521 ap.add_argument("--jobs", type=positive_int, default=1,
522 help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)")
344 ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") 523 ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)")
345 ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version") 524 ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version")
346 args = ap.parse_args() 525 args = ap.parse_args()
@@ -352,9 +531,12 @@ def main() -> int:
352 indices = {name: index for index, name in enumerate(names)} 531 indices = {name: index for index, name in enumerate(names)}
353 setups = fixture_dependencies(tests) 532 setups = fixture_dependencies(tests)
354 sorter = TopologicalSorter(setups) 533 sorter = TopologicalSorter(setups)
534 before = {index: set(setups[index]) for index in range(len(tests))}
355 for index, test in enumerate(tests): 535 for index, test in enumerate(tests):
356 # DEPENDS controls order. Only failed fixture setups block a consumer. 536 # DEPENDS controls order. Only failed fixture setups block a consumer.
357 sorter.add(index, *(indices[name] for name in properties(test).get("DEPENDS", []) if name in indices)) 537 depends = [indices[name] for name in properties(test).get("DEPENDS", []) if name in indices]
538 sorter.add(index, *depends)
539 before[index].update(depends)
358 try: 540 try:
359 order = list(sorter.static_order()) 541 order = list(sorter.static_order())
360 except CycleError: 542 except CycleError:
@@ -367,18 +549,30 @@ def main() -> int:
367 results = {} 549 results = {}
368 results_by_index: dict[int, str] = {} 550 results_by_index: dict[int, str] = {}
369 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") 551 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine")
370 with DriveMap(args.windows_root, args.root, prefix) as drive: 552 outcomes: dict[int, tuple[str, str]] = {}
553
554 def run_one(index: int) -> tuple[str, str]:
555 failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail")
556 return run_test(tests[index], args, wine, failed_setups=failed_setups)
557
558 def report(index: int) -> None:
559 status, detail = outcomes[index]
560 results[names[index]] = status
561 print(f"[{status.upper()}] {names[index]}", flush=True)
562 if status != "pass":
563 for line in detail.rstrip().splitlines()[-40:]:
564 print(f" {line}")
565
566 with DriveMap(args.windows_root, args.root, prefix) as drive, KeptServer(find_wineserver(wine), wine) as server:
371 print(drive.note, flush=True) 567 print(drive.note, flush=True)
372 for index in order: 568 print(server.note, flush=True)
373 name = names[index] 569 if args.jobs == 1:
374 failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail") 570 for index in order:
375 status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups) 571 outcomes[index] = run_one(index)
376 results_by_index[index] = status 572 results_by_index[index] = outcomes[index][0]
377 results[name] = status 573 report(index)
378 print(f"[{status.upper()}] {name}", flush=True) 574 else:
379 if status != "pass": 575 run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report)
380 for line in detail.rstrip().splitlines()[-40:]:
381 print(f" {line}")
382 576
383 missing = list(dict.fromkeys(n for n in args.require if n not in results)) 577 missing = list(dict.fromkeys(n for n in args.require if n not in results))
384 failed_required = [n for n in args.require if results.get(n) != "pass"] 578 failed_required = [n for n in args.require if results.get(n) != "pass"]
diff --git a/scripts/translate_pipeline_compute.py b/scripts/translate_pipeline_compute.py
new file mode 100644
index 000000000..4e691110b
--- /dev/null
+++ b/scripts/translate_pipeline_compute.py
@@ -0,0 +1,174 @@
1"""Build an interrupted or new pipeline compute pack from shader_library.py output (Linux).
2
3Two translation processes, including the parent, each run at most one SPIRV-Tools process.
4Validated modules and their receipts survive interruption. The runtime index is published last.
5"""
6import argparse
7import fcntl
8import hashlib
9import json
10import os
11import resource
12import shutil
13import sys
14import tempfile
15from pathlib import Path
16
17ROOT = Path(__file__).resolve().parents[1]
18sys.path[:0] = [str(ROOT / "tools"), str(ROOT)]
19from make_game import file_sha256 as digest, translation_sources_digest
20import rdna2spirv as translator
21
22
23def build_one(src, out, name, settings, compact=False):
24 listing = src / "disasm" / (name + ".s")
25 side = src / "fspx" / name
26 code, state = (Path(str(side) + suffix) for suffix in (".code", ".state"))
27 code_key, state_key = digest(code), digest(state)
28 container = src / (name + ".dxbc")
29 inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")),
30 digest(container) if container.is_file() else None]
31 key = hashlib.sha256(json.dumps(inputs).encode()).hexdigest()
32 receipt = out / ".compute-cache" / (key + ".json")
33 if receipt.exists():
34 try:
35 row = json.loads(receipt.read_text(encoding="utf-8"))
36 if (row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key):
37 module_hash = row["module"]
38 if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash):
39 if digest(out / (name + "_" + module_hash + ".spv")) == module_hash:
40 return row
41 except (OSError, ValueError, KeyError, TypeError):
42 pass
43
44 asm = translator.translate(str(listing))
45 with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp:
46 sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv"
47 sa.write_text(asm, encoding="utf-8", newline="\n")
48 result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, compact=compact)
49 if result.returncode:
50 raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0])
51 meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing))
52 if (meta.get("stage"), meta.get("fspx_code_sha256"), meta.get("fspx_state_sha256")) != (
53 "cs", code_key, state_key):
54 raise ValueError("compute stage or FSPX identity mismatch")
55 module_hash = digest(sv)
56 sv.replace(out / (name + "_" + module_hash + ".spv"))
57 row = {"meta": meta, "module": module_hash}
58 translator.write_index(str(receipt), row)
59 return row
60
61
62def build_part(src, out, names, settings, report, compact=False):
63 rows, failures = {}, {}
64 for number, name in enumerate(names, 1):
65 try:
66 rows[name] = build_one(src, out, name, settings, compact)
67 except (translator.Unsupported, MemoryError) as e:
68 failures[name] = str(e) or type(e).__name__
69 if number % 100 == 0 or number == len(names):
70 print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True)
71 translator.write_index(str(report), {"rows": rows, "failures": failures})
72
73
74def build(src, out, names, settings, jobs, compact=False):
75 cache = out / ".compute-cache"
76 cache.mkdir(exist_ok=True)
77 with (cache / "lock").open("ab") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp:
78 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
79 reports = [Path(tmp) / str(i) for i in range(jobs)]
80 pid = os.fork() if jobs == 2 else None
81 if pid == 0:
82 try:
83 build_part(src, out, names[1::2], settings, reports[1], compact)
84 except BaseException:
85 import traceback
86 traceback.print_exc()
87 os._exit(1)
88 os._exit(0)
89 try:
90 build_part(src, out, names[::jobs], settings, reports[0], compact)
91 finally:
92 if pid and os.waitpid(pid, 0)[1]:
93 raise RuntimeError("second translation worker failed")
94
95 index, failures, pairs = {}, {}, {}
96 for report in reports:
97 part = json.loads(report.read_text(encoding="utf-8"))
98 failures.update(part["failures"])
99 for name, row in part["rows"].items():
100 module, meta = row["module"], row["meta"]
101 pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"]
102 if pairs.setdefault(pair, module) != module:
103 raise ValueError("conflicting compute modules for one code/state pair")
104 # The same binary can implement different code/state keys. Each needs a runtime entry.
105 entry = name + "_" + module
106 index[entry] = meta
107 by_hash = {}
108 for name, reason in failures.items():
109 code = digest(src / "fspx" / (name + ".code"))
110 state = digest(src / "fspx" / (name + ".state"))
111 by_hash.setdefault(code, {})[state] = reason
112 translator.write_index(str(out / "failures.json"), by_hash)
113 translator.write_index(str(out / "index.json"), index)
114 print(f"{len(index)}/{len(names)} valid, {len(failures)} failed")
115 return int(bool(failures))
116
117
118def main():
119 ap = argparse.ArgumentParser(description=__doc__)
120 ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/")
121 ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory")
122 ap.add_argument("--jobs", type=int, choices=(1, 2), default=2)
123 ap.add_argument("--memory-mib", type=int, default=768, help="virtual memory per process (default 768 MiB)")
124 ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a",
125 help="bindless descriptor table hash shared with the runtime")
126 ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit,
127 default=translator.spirv_loop_guard.DEFAULT_LIMIT, help="maximum loop visits (0 disables)")
128 ap.add_argument("--compact-spirv", action="store_true", help="compact modules with spirv-opt before validation")
129 ap.add_argument("--wave64-emulate", action="store_true")
130 args = ap.parse_args()
131 if args.memory_mib < 1:
132 ap.error("--memory-mib must be positive")
133 src, out = args.inputs.resolve(), args.out.resolve()
134 if out == src or src in out.parents or out in src.parents:
135 ap.error("input and output directories must be separate")
136 os.setpriority(os.PRIO_PROCESS, 0, 19)
137 soft, hard = resource.getrlimit(resource.RLIMIT_AS)
138 bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY)
139 resource.setrlimit(resource.RLIMIT_AS, (bound, hard))
140 versions = []
141 required_tools = ["spirv-as", "spirv-val"]
142 if args.compact_spirv:
143 required_tools.append("spirv-opt")
144 for tool in required_tools:
145 binary = shutil.which(tool)
146 if not binary:
147 ap.error(tool + " is required")
148 versions.append(digest(Path(binary)))
149 settings = [translation_sources_digest(), digest(Path(__file__)), versions, args.wave64_emulate,
150 args.loop_limit, args.descriptor_hash]
151 rows = json.loads((src / "index.json").read_text(encoding="utf-8"))
152 names = []
153 for row in rows:
154 if row["stage"] != "cs":
155 continue
156 filename = row["file"]
157 if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename:
158 ap.error("invalid compute filename in input index")
159 names.append(filename[:-5])
160 if not names or len(set(names)) != len(names):
161 ap.error("expected unique compute filenames in the input index")
162 out.mkdir(parents=True, exist_ok=True)
163 translator.DESCRIPTOR_HASH = args.descriptor_hash
164 translator.LOOP_LIMIT = args.loop_limit
165 translator.WAVE64_EMULATE = args.wave64_emulate
166 return build(src, out, sorted(names), settings, args.jobs, args.compact_spirv)
167
168
169if __name__ == "__main__":
170 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
171 sys.stdout.reconfigure(errors="replace")
172 except AttributeError:
173 pass
174 sys.exit(main())
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md
new file mode 100644
index 000000000..3a875af4b
--- /dev/null
+++ b/scripts/windows-boot/README.md
@@ -0,0 +1,93 @@
1# Native Windows boot harness
2
3`boot.ps1` boots the retail executable under `gta6rt` on native Windows the way the Linux harness
4([`scripts/linux-boot/`](../linux-boot/)) does under Proton: same switches, one game process at a time, a trace of
5every boot and a short digest at the end. Windows PowerShell 5.1 is enough. New here? the repository README
6covers the setup that comes before this.
7
8## Run it
9
10```powershell
11# What would run, with every path checked; launches nothing.
12powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
13
14# A 200 s boot with the default unattended presses (a@45,a@60,a@75,a@90).
15powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
16
17# Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them.
18powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x98f828c,0x78b2818"
19
20# Every parameter.
21Get-Help -Full .\scripts\windows-boot\boot.ps1
22```
23
24Set `LEONIDA_GAME_DIR`, `LEONIDA_SHADERS` (and `GTA6RT`, `LEONIDA_RUNS` if you use other places) once in your
25profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this
26checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`.
27The script refuses an output folder inside the repository.
28
29## What it sets
30
31Only when your shell has not set them already (`-DryRun` prints the final list):
32
33| Variable | Default | Why |
34|---|---|---|
35| `LEONIDA_D3D12` | `vulkan` | the runtime's D3D12-on-Vulkan backend |
36| `LEONIDA_DEVICE_TYPE` | `6` | Series S identity; the runtime answers the title's `ConsoleMode` registry read with it (1920x1080) |
37| `LEONIDA_ARENA_MB` | `2048` | as on Linux |
38| `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit |
39| `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup |
40| `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\pipeline-cache` | one warmed cache shared by every build you boot |
41| `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports |
42| `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps |
43| `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive |
44| `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 |
45| `DISABLE_RTSS_LAYER`, `DISABLE_VULKAN_OBS_CAPTURE` | `1` | keep third-party Vulkan overlay layers out of the process |
46
47Per run, from the parameters: `LEONIDA_SHADERS` (`-Shaders`), `LEONIDA_CAPTURE` (`<out>\cap_<name>`, `-NoCapture`
48turns it off), `LEONIDA_INPUT_SCRIPT` (`-InputScript`, `-NoInput` for none), `LEONIDA_STACKS` (`-Stacks 30,60`: every
49thread's call chain at those seconds, unwound in-process, which works natively where `tools/re/mdmp_unwind.py`
50cannot walk Windows' own DLLs). Other `LEONIDA_*` variables in your shell pass through and are listed.
51
52The command is `gta6rt --run <exe> --game-dir <game> --overlay <out>\overlay --trace <name>.jsonl --trace-d3d12`.
53The overlay takes everything the title writes, so the package folder can stay read-only.
54
55## What you get
56
57In the output folder: `<name>.log` (stderr: `[rt]` lines and the D3D12 trace), `<name>.stdout.log`,
58`<name>.jsonl` (startup trace), `<name>.summary.txt` (`tools/boot_trace.py`), `<name>.digest.txt` and
59`cap_<name>\` (PPM frames plus `index.txt` with the mean RGB of each). The digest:
60
61```
62== boot first: ran its full time limit (200 s), stopped
63shaders: [rt] d3d12: 26586 translated shaders (21 fspx, 0 fspx_compute, 0 fspx_gfx, 52 bvh, 10 exe) from ...
64states: t=0s game=0 session=0 | t=15s game=2 session=0 | t=30s game=3 session=3 | t=60s game=3 session=d
65presents: PresentX ok 1581, failed 0
66input: 13 presses logged
67faults: none
68frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00
69```
70
71`-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The digest holds counts and
72states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game
73and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data").
74
75How to read the states: game state `0x7446510` goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing
76screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively)
77section 2 has the healthy sequence with times and section 3 "which blank do you have".
78
79## One game at a time
80
81The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe`
82runs (another agent's boot, or one started by hand), up to `-LockWaitSeconds` (default an hour, then exit 3). Two
83game processes on one GPU make both runs meaningless and can take the driver down.
84
85## Helper tools (`tools/re/windows/`)
86
87| Tool | What for |
88|---|---|
89| `sym.py IMAGE RVA...` | `gta6rt.exe+0x...` frames to function and line through dbghelp and the build's PDB (the Windows SDK's or Visual Studio's `dbghelp.dll`; `LEONIDA_DBGHELP` names another) |
90| `ripsample.ps1 [-Seconds 20]` | sampling profiler of a running `gta6rt`: per thread, where it spends its time, as module+RVA (`TITLE+0x...` for the title) |
91| `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only |
92
93Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell).
diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1
new file mode 100644
index 000000000..d052a79da
--- /dev/null
+++ b/scripts/windows-boot/boot.ps1
@@ -0,0 +1,456 @@
1<#
2.SYNOPSIS
3 Boot the retail executable under gta6rt on native Windows, one game process at a time, and print a digest.
4
5.DESCRIPTION
6 The native counterpart of scripts/linux-boot/: sets the switches both machines boot with (see
7 docs/re/howto-blank-to-story-load.md, section 1), runs `gta6rt --run` with --trace and --trace-d3d12 for
8 -Seconds, stops it, runs tools/boot_trace.py and prints a short digest: exit, game/session state over time,
9 PresentX count, device-fault lines, capture means. Paste numbers from the digest into a RESULT on the
10 coordination board, never the logs: they can quote the game (AGENTS.md, "No game data").
11
12 Only one game process runs at a time: the script holds a named mutex and also waits while any gta6rt.exe is
13 running (another agent's boot, or one started by hand).
14
15 Every default switch is used only when the variable is not already set in this shell; other LEONIDA_*
16 variables of the shell pass through; -SetEnv overrides all of them. -DryRun lists the result. Outputs go to -OutDir (never inside the repository):
17 <OutDir>\<Name>.log stderr of gta6rt: [rt] diagnostics and [d3d12-trace] lines
18 <OutDir>\<Name>.stdout.log stdout of gta6rt
19 <OutDir>\<Name>.jsonl startup trace (--trace)
20 <OutDir>\<Name>.summary.txt tools/boot_trace.py report
21 <OutDir>\<Name>.digest.txt the digest printed at the end
22 <OutDir>\cap_<Name>\ swapchain captures (PPM) and index.txt with mean RGB per frame
23
24.PARAMETER Name
25 Run name; output files are named after it. Default: boot-<yyyyMMdd-HHmmss>.
26
27.PARAMETER Seconds
28 How long the game runs before it is stopped. Default 180.
29
30.PARAMETER GameDir
31 Your package folder (MicrosoftGame.Config and the .rpf archives as plain files). Default: $env:LEONIDA_GAME_DIR,
32 else game_path.txt beside gta6rt.exe (written by make_game.py's runtime stage).
33
34.PARAMETER Exe
35 game_scarlett_master.exe. Default: $env:LEONIDA_EXE, else <GameDir>\game_scarlett_master.exe.
36
37.PARAMETER Runtime
38 gta6rt.exe (gta6rt_tls_host.dll must sit beside it). Default: $env:GTA6RT, else
39 <repo>\runtime\build\RelWithDebInfo\gta6rt.exe.
40
41.PARAMETER Shaders
42 The translated library, <work>\shaders\spirv. Default: $env:LEONIDA_SHADERS; when neither is given the
43 runtime reads shader_path.txt beside gta6rt.exe.
44
45.PARAMETER OutDir
46 Folder for logs, traces and captures. Default: $env:LEONIDA_RUNS, else $HOME\leonida-runs.
47
48.PARAMETER Overlay
49 Writable folder for everything the title writes (saves, caches). Default <OutDir>\overlay.
50
51.PARAMETER InputScript
52 LEONIDA_INPUT_SCRIPT: timed pad presses, seconds since the pad's first poll (button@seconds, comma-separated;
53 buttons a b x y start back lb rb up down left right). Sets LEONIDA_KEYBOARD_PAD=always. Builds older than
54 main @ 8146ef690 ignore a script longer than 63 characters. Default 'a@45,a@60,a@75,a@90'.
55
56.PARAMETER NoInput
57 No input script (LEONIDA_KEYBOARD_PAD then stays as this shell has it: LEONIDA_KEYBOARD_PAD=1 to play by
58 hand with the window focused).
59
60.PARAMETER Stacks
61 LEONIDA_STACKS: whole seconds at which every thread's call chain is printed to the log, e.g. '30,60'.
62
63.PARAMETER SetEnv
64 Extra or overriding environment variables as a hashtable, when called from a PowerShell prompt:
65 & .\scripts\windows-boot\boot.ps1 -SetEnv @{ LEONIDA_PEEK_SECONDS = '2' }. A value of '' removes the variable.
66
67.PARAMETER EnvPairs
68 Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with
69 powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x75e8eb0".
70 Applied after -SetEnv. KEY= removes the variable for this boot.
71
72.PARAMETER NoCapture
73 Do not set LEONIDA_CAPTURE.
74
75.PARAMETER ExtraArgs
76 More gta6rt arguments, appended after the standard ones.
77
78.PARAMETER Python
79 Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3.
80
81.PARAMETER SummaryLines
82 How many lines of the boot_trace.py report to print. Default 40; 0 prints none.
83
84.PARAMETER LockWaitSeconds
85 How long to wait for another boot to finish. Default 3600.
86
87.PARAMETER DryRun
88 Print the environment and the command line, check the paths, launch nothing.
89
90.PARAMETER DigestOnly
91 Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir).
92
93.EXAMPLE
94 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
95
96.EXAMPLE
97 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
98
99.EXAMPLE
100 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=0x7446510,0x75e8eb0,0x75e8ea0,0x9844898"
101
102.EXAMPLE
103 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first
104#>
105[CmdletBinding(PositionalBinding = $false)]
106param(
107 [string]$Name = "",
108 [int]$Seconds = 180,
109 [string]$GameDir = "",
110 [string]$Exe = "",
111 [string]$Runtime = "",
112 [string]$Shaders = "",
113 [string]$OutDir = "",
114 [string]$Overlay = "",
115 [string]$InputScript = "a@45,a@60,a@75,a@90",
116 [string]$Stacks = "",
117 [hashtable]$SetEnv = @{},
118 [switch]$NoCapture,
119 [switch]$NoInput,
120 [string[]]$ExtraArgs = @(),
121 [string]$Python = "",
122 [int]$SummaryLines = 40,
123 [int]$LockWaitSeconds = 3600,
124 [switch]$DryRun,
125 [switch]$DigestOnly,
126 [Parameter(ValueFromRemainingArguments = $true)]
127 [string[]]$EnvPairs = @()
128)
129
130Set-StrictMode -Version 2.0
131$ErrorActionPreference = "Stop"
132
133$RepoRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\.."))
134$ExeName = "game_scarlett_master.exe"
135
136function Get-FirstValue {
137 param([object[]]$Candidates)
138 foreach ($c in $Candidates) { if ($c -and ([string]$c).Trim()) { return ([string]$c).Trim() } }
139 return ""
140}
141
142function Read-SideFile {
143 # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt).
144 param([string]$Path)
145 if (Test-Path -LiteralPath $Path -PathType Leaf) {
146 $line = Get-Content -LiteralPath $Path -TotalCount 1
147 if ($line) { return ([string]$line).Trim() }
148 }
149 return ""
150}
151
152function ConvertTo-ProcessArgument {
153 # Quote one argument the way the MSVC CRT splits a command line (backslashes before a quote are doubled).
154 param([string]$Value)
155 if ($Value -ne "" -and $Value -notmatch '[\s"]') { return $Value }
156 $sb = New-Object System.Text.StringBuilder
157 [void]$sb.Append('"')
158 $slashes = 0
159 foreach ($ch in $Value.ToCharArray()) {
160 if ($ch -eq '\') { $slashes++; continue }
161 if ($ch -eq '"') { [void]$sb.Append('\', 2 * $slashes + 1) } elseif ($slashes) { [void]$sb.Append('\', $slashes) }
162 $slashes = 0
163 [void]$sb.Append($ch)
164 }
165 if ($slashes) { [void]$sb.Append('\', 2 * $slashes) }
166 [void]$sb.Append('"')
167 return $sb.ToString()
168}
169
170function Test-InsideFolder {
171 param([string]$Path, [string]$Folder)
172 $p = [System.IO.Path]::GetFullPath($Path).TrimEnd('\') + '\'
173 $f = [System.IO.Path]::GetFullPath($Folder).TrimEnd('\') + '\'
174 return $p.StartsWith($f, [System.StringComparison]::OrdinalIgnoreCase)
175}
176
177function Resolve-Python {
178 param([string]$Requested)
179 if ($Requested) { return @($Requested) }
180 if (Get-Command python -ErrorAction SilentlyContinue) { return @("python") }
181 if (Get-Command py -ErrorAction SilentlyContinue) { return @("py", "-3") }
182 return @()
183}
184
185# ------------------------------------------------------------------------------------------------ paths
186
187if (-not $Name) { $Name = "boot-" + (Get-Date -Format "yyyyMMdd-HHmmss") }
188if ($NoInput) { $InputScript = "" }
189if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" }
190
191$Runtime = Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe"))
192$RuntimeDir = Split-Path -Parent $Runtime
193$GameDir = Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt")))
194$Exe = Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" }))
195$Shaders = Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS)
196$OutDir = Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs"))
197$OutDir = [System.IO.Path]::GetFullPath($OutDir)
198$Overlay = Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay"))
199$Capture = Join-Path $OutDir ("cap_" + $Name)
200$LogFile = Join-Path $OutDir ($Name + ".log")
201$StdoutFile = Join-Path $OutDir ($Name + ".stdout.log")
202$TraceFile = Join-Path $OutDir ($Name + ".jsonl")
203$SummaryFile = Join-Path $OutDir ($Name + ".summary.txt")
204$DigestFile = Join-Path $OutDir ($Name + ".digest.txt")
205
206$problems = New-Object System.Collections.Generic.List[string]
207if (Test-InsideFolder $OutDir $RepoRoot) { $problems.Add("-OutDir $OutDir is inside the repository; logs and captures must stay outside it") }
208if (-not (Test-Path -LiteralPath $Runtime -PathType Leaf)) { $problems.Add("no gta6rt.exe at $Runtime (build it, or pass -Runtime / set GTA6RT)") }
209elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) {
210 $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)")
211}
212if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") }
213elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) {
214 $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives")
215}
216if (-not $Exe -or -not (Test-Path -LiteralPath $Exe -PathType Leaf)) { $problems.Add("no $ExeName at '$Exe' (pass -Exe)") }
217if ($Shaders) {
218 if (-not (Test-Path -LiteralPath (Join-Path $Shaders "index.json") -PathType Leaf)) {
219 $problems.Add("$Shaders has no index.json: -Shaders is <work>\shaders\spirv after make_game.py --stages check,shaders")
220 } elseif (-not (Test-Path -LiteralPath (Join-Path $Shaders "exe\index.json") -PathType Leaf)) {
221 Write-Warning "$Shaders has no exe\index.json: the title's 10 embedded shaders are missing and frames cannot draw (JOIN.md, 'The executable trap')"
222 }
223} elseif (-not (Read-SideFile (Join-Path $RuntimeDir "shader_path.txt"))) {
224 $problems.Add("no shader library: pass -Shaders <work>\shaders\spirv or set LEONIDA_SHADERS")
225}
226
227# ------------------------------------------------------------------------------------------ environment
228
229# Defaults: used only when this shell has not set the variable. They match the Linux harness (scripts/linux-boot/).
230$defaults = [ordered]@{
231 LEONIDA_D3D12 = "vulkan"
232 LEONIDA_DEVICE_TYPE = "6" # Series S identity; the runtime answers the ConsoleMode registry read with it
233 LEONIDA_ARENA_MB = "2048"
234 LEONIDA_PIPELINE_CACHE_BYTES = "4294967296"
235 LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1"
236 LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache")
237 LEONIDA_PEEK = "0x7446510,0x98f828c" # game state, session state (low dword)
238 LEONIDA_PEEK_SECONDS = "5"
239 LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints)
240 LEONIDA_CAPTURE_EVERY = "60"
241 LEONIDA_CAPTURE_LIMIT = "40"
242 DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off
243 DISABLE_VULKAN_OBS_CAPTURE = "1"
244}
245if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" }
246# Per-run values: always this script's (from its parameters), whatever the shell has.
247$perRun = [ordered]@{
248 LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture })
249 LEONIDA_INPUT_SCRIPT = $InputScript
250}
251if ($Shaders) { $perRun["LEONIDA_SHADERS"] = $Shaders }
252if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks }
253
254$bootEnv = [ordered]@{}
255foreach ($k in $defaults.Keys) {
256 $cur = [Environment]::GetEnvironmentVariable($k)
257 if ($cur) { $bootEnv[$k] = $cur } else { $bootEnv[$k] = $defaults[$k] }
258}
259foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] }
260# Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below.
261foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) {
262 if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value }
263}
264foreach ($k in $SetEnv.Keys) { $bootEnv[[string]$k] = [string]$SetEnv[$k] }
265foreach ($pair in $EnvPairs) {
266 if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" }
267 $bootEnv[$Matches[1]] = $Matches[2]
268}
269if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] }
270
271$gameArgs = @("--run", $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs
272$argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " "
273
274if (-not $DigestOnly) {
275 Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot"
276 Write-Output "[boot] gta6rt $Runtime"
277 Write-Output "[boot] out $OutDir"
278 foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } }
279 Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine"
280}
281
282if ($DigestOnly) {
283 if (-not (Test-Path -LiteralPath $LogFile)) { Write-Output "[boot] no $LogFile to digest"; exit 2 }
284 $problems.Clear()
285}
286if ($problems.Count) {
287 foreach ($p in $problems) { Write-Output "[boot] problem: $p" }
288 if (-not $DryRun) { exit 2 }
289}
290if ($DryRun) { Write-Output "[boot] dry run: nothing launched"; exit $(if ($problems.Count) { 2 } else { 0 }) }
291
292$verdict = "digest of an earlier run (-DigestOnly)"
293$exitCode = 0
294if (-not $DigestOnly) {
295
296 # --------------------------------------------------------------------------------------------- the lock
297
298 $mutex = New-Object System.Threading.Mutex($false, "Local\LeonidaGameBoot")
299 $owned = $false
300 $saved = @{}
301 $exitCode = 0
302 try {
303 $deadline = (Get-Date).AddSeconds($LockWaitSeconds)
304 $said = $false
305 while (-not $owned) {
306 try { $owned = $mutex.WaitOne(5000) } catch [System.Threading.AbandonedMutexException] { $owned = $true }
307 if ($owned -and (Get-Process -Name gta6rt -ErrorAction SilentlyContinue)) {
308 # A game started by hand or by another script that does not take this lock: wait for it too.
309 $mutex.ReleaseMutex(); $owned = $false; Start-Sleep -Seconds 5
310 }
311 if (-not $owned) {
312 if (-not $said) { Write-Output "[boot] waiting: another game process is running (one at a time)"; $said = $true }
313 if ((Get-Date) -gt $deadline) { Write-Output "[boot] gave up waiting after $LockWaitSeconds s"; exit 3 }
314 }
315 }
316
317 foreach ($d in @($OutDir, $Overlay)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
318 if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) {
319 New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null
320 }
321 if ($bootEnv["LEONIDA_CAPTURE"]) {
322 # A capture folder reused by the same -Name: drop the earlier run's frames and index, nothing else.
323 New-Item -ItemType Directory -Force -Path $Capture | Out-Null
324 Get-ChildItem -LiteralPath $Capture -File | Where-Object { $_.Name -like "frame_*.ppm" -or $_.Name -like "*index.txt" } |
325 Remove-Item -Force -Confirm:$false
326 }
327 foreach ($f in @($LogFile, $StdoutFile, $TraceFile, $SummaryFile, $DigestFile)) {
328 if (Test-Path -LiteralPath $f) { Remove-Item -LiteralPath $f -Force -Confirm:$false }
329 }
330
331 foreach ($k in $bootEnv.Keys) {
332 $saved[$k] = [Environment]::GetEnvironmentVariable($k)
333 $v = $bootEnv[$k]; if ($v -eq "") { $v = $null }
334 [Environment]::SetEnvironmentVariable($k, $v)
335 }
336
337 # ------------------------------------------------------------------------------------------- the boot
338 $started = Get-Date
339 $proc = Start-Process -FilePath $Runtime -ArgumentList $argLine -WorkingDirectory $RepoRoot -NoNewWindow -PassThru `
340 -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile
341 $handle = $proc.Handle # keeps the exit code readable after the process ends
342 $stopped = $false
343 if (-not $proc.WaitForExit($Seconds * 1000)) {
344 $stopped = $true
345 try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { }
346 [void]$proc.WaitForExit(20000)
347 }
348 $ran = [int]((Get-Date) - $started).TotalSeconds
349 $rc = $null
350 try { $rc = $proc.ExitCode } catch { }
351 if ($stopped) { $verdict = "ran its full time limit ($ran s), stopped"; $exitCode = 0 }
352 elseif ($rc -eq $null) { $verdict = "exited by itself after $ran s, exit code unknown"; $exitCode = 1 }
353 else { $verdict = ("exited by itself after {0} s, exit code {1} (0x{2:x8})" -f $ran, $rc, ([int64]$rc -band 0xffffffffL)); $exitCode = [int]$rc }
354 } finally {
355 foreach ($k in $saved.Keys) { [Environment]::SetEnvironmentVariable($k, $saved[$k]) }
356 if ($owned) { $mutex.ReleaseMutex() }
357 $mutex.Dispose()
358 }
359}
360
361# -------------------------------------------------------------------------------------------- the digest
362
363$py = @(Resolve-Python $Python)
364if ($py.Count) {
365 $pyArgs = @()
366 if ($py.Count -gt 1) { $pyArgs += $py[1..($py.Count - 1)] }
367 $pyArgs += @("-I", (Join-Path $RepoRoot "tools\boot_trace.py"), $TraceFile, "--d3d12", $LogFile)
368 # Windows PowerShell 5.1 turns a native program's stderr into error records; with "Stop" that would end the script.
369 $ErrorActionPreference = "Continue"
370 & $py[0] @pyArgs 2>&1 | ForEach-Object { "$_" } | Out-File -FilePath $SummaryFile -Encoding utf8
371 $ErrorActionPreference = "Stop"
372} else {
373 "no python found for tools/boot_trace.py" | Out-File -FilePath $SummaryFile -Encoding utf8
374}
375
376$peekRx = [regex]'\[rt\] peek t=(\d+)s:(.*)$'
377$valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)'
378$states = New-Object System.Collections.Generic.List[string]
379$lastPeek = ""; $prevPair = ""
380$presentOk = 0; $presentFailed = 0; $presses = 0
381$shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string]
382$wrapped = 0
383if (Test-Path -LiteralPath $LogFile) {
384 foreach ($line in [System.IO.File]::ReadLines($LogFile)) {
385 if ($line.Contains("XboxPresentation::PresentX")) {
386 if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ }
387 continue
388 }
389 if ($line.Contains("[rt] peek t=")) {
390 $m = $peekRx.Match($line)
391 if ($m.Success) {
392 $lastPeek = $line.Substring($line.IndexOf("[rt] peek"))
393 $game = "?"; $session = "?"
394 foreach ($v in $valRx.Matches($m.Groups[2].Value)) {
395 $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value
396 if ($rva -eq "7446510") { $game = $val }
397 elseif ($rva -eq "98f828c" -and $val -ne "?") {
398 $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword
399 $session = $(if ($low) { $low } else { "0" })
400 }
401 }
402 $pair = "game=$game session=$session"
403 if ($pair -ne $prevPair) { $states.Add("t=$($m.Groups[1].Value)s $pair"); $prevPair = $pair }
404 }
405 continue
406 }
407 if ($line.Contains("[rt] gameinput: press ")) {
408 # Buttons only: with the keyboard pad, mouse movement is logged as right-stick presses (rsup, rsdown...).
409 if ($line -notmatch 'gameinput: press [lr]s') { $presses++ }
410 continue
411 }
412 if ($line.Contains("[rt] device-fault:") -and -not $line.Contains("device-fault: enabled")) { if ($faults.Count -lt 8) { $faults.Add($line.Trim()) }; continue }
413 if ($line.Contains("VK_ERROR_DEVICE_LOST") -and $faults.Count -lt 8) { $faults.Add($line.Trim()); continue }
414 if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() }
415 if ($line.Contains("wrapped V#")) { $wrapped++ }
416 }
417}
418
419$capText = "no captures"
420$capIndex = Join-Path $Capture "index.txt"
421if (Test-Path -LiteralPath $capIndex) {
422 $frames = 0; $nonBlack = 0; $last = ""; $maxSum = -1.0; $maxText = ""
423 $meanRx = [regex]'mean rgb ([0-9.]+) ([0-9.]+) ([0-9.]+)'
424 foreach ($line in [System.IO.File]::ReadLines($capIndex)) {
425 $m = $meanRx.Match($line)
426 if (-not $m.Success) { continue }
427 $frames++
428 $r = [double]::Parse($m.Groups[1].Value, [Globalization.CultureInfo]::InvariantCulture)
429 $g = [double]::Parse($m.Groups[2].Value, [Globalization.CultureInfo]::InvariantCulture)
430 $b = [double]::Parse($m.Groups[3].Value, [Globalization.CultureInfo]::InvariantCulture)
431 $sum = $r + $g + $b
432 if ($sum -gt 0) { $nonBlack++ }
433 $last = "$($m.Groups[1].Value) $($m.Groups[2].Value) $($m.Groups[3].Value)"
434 if ($sum -gt $maxSum) { $maxSum = $sum; $maxText = $last }
435 }
436 $capText = "$frames captured, $nonBlack non-black; last mean rgb $last; brightest $maxText"
437}
438
439$digest = New-Object System.Collections.Generic.List[string]
440$digest.Add("== boot ${Name}: $verdict")
441$digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated-shaders line (Vulkan device not reached?)' })")
442$digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })")
443$digest.Add("presents: PresentX ok $presentOk, failed $presentFailed")
444$digest.Add("input: $presses presses logged")
445$digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })")
446foreach ($f in $faults) { $digest.Add(" $f") }
447if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") }
448$digest.Add("frames: $capText")
449$digest.Add("files: $LogFile, $TraceFile, $SummaryFile")
450$digest | Out-File -FilePath $DigestFile -Encoding utf8
451$digest
452if ($SummaryLines -gt 0 -and (Test-Path -LiteralPath $SummaryFile)) {
453 Write-Output "-- boot_trace.py (first $SummaryLines lines of $SummaryFile)"
454 Get-Content -LiteralPath $SummaryFile -TotalCount $SummaryLines
455}
456exit $exitCode