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-24 20:26:00 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 20:26:00 -0500
commit154e4ec034902deffa4b89b2cbca9a949f38baec (patch)
tree1b2ef5656de42c172291bc6009efa4c510650815 /scripts
parenteb6a08cd359d98b5777e70d54d0ae8a75879495a (diff)
parent8a242efebf823aeb23c72d17c3d666daf0bbd3e2 (diff)
Merge the #984 result (main + RT-PROTON-STORY-LOAD) into #939
The base is 8a242efeb, the merge of main and #984. 68 files conflicted; they were resolved in seven groups by one rule: the same change in two forms keeps the base's form, everything only #939 has is kept, and where the two solve one problem in two ways the base's is the frame and #939's plugs into it. A, the Xbox proxy (d3d12_xs_device.cpp/.h, d3d12_xs.cpp, d3d12_xs_pso_stream.cpp/.h, d3d12_xs_alloc_size.h, d3d12_xs_desc_clean.h, device_proxy_test.cpp, queue_proxy_test.cpp): the base's files with #939's additions ported in. Device slot 57 asks #939's NativeGraphicsFactory first and falls back to the base's proxy_create_graphics_pipeline_from_native_code on E_NOTIMPL. Kept from #939: the providers (texture lease, raw texture view, resource by address, constant view, descriptor mapping, depth-stencil UAV, texture pages), the title-backed descriptor mirror, slot 13's feature answers, GPU labels on list slots 71/72. Dropped: #939's duplicates of the boot ladder routes, its fallback window, its slot 133 stand-in. A2 (xs_proxy_mock_test.cpp): the base's test with #939's slot 70 raw-buffer case; presentation cases follow #939's rule that a device which ever had a handler has no queue fallback. B1, the Vulkan device (d3d12_vulkan_device.cpp, d3d12_com.cpp/.h, shader_library.h, queue_families.h, pipeline_cache_file.h, startup_trace.h): one lazy-pipeline mechanism, the base's; #939's pending_base_compile and first_use_backend_pipelines dropped, prepare_on_bind and cold_graphics_compile kept. create_texture keeps the base's signature; #939's deferred backing is folded into the base's placed-memory binder. #939's quad lists as triangle indices. B2, the D3D12 tests (d3d12_existing_heap, a8_dimensions, pipeline_cache_seed, title_va, rect_list, shader_library, loader_tls_index0, draw, compute, xmem_placed, shader_library_corpus): the base's tests where both carry the same case, #939's cases added (rebound tables, linear texture map, large vertex batch, executable shaders, default A8 views). C, the backend (vulkan_replay.h, vulkan_backend.h, vulkan_bindless.h, vulkan_scratch.h, vulkan_present.h, rect_list_geometry.h, vk_test_device.h, vk_pipeline_check.cpp, vk_store_test.cpp, bindless_sizing_test.cpp, replay_texture_barrier_test.cpp): the base's prepare_draw and lazy compute, its #1055 release rule and its rectangle generator; #939's rectangle variants, GPU quad index expansion, 1D/3D and depth-stencil UAVs, the label fence on the base's submit. D, memory, services, presentation (xmem.cpp/.h, xg_xs.cpp, xg_xs_test.cpp, title_va_alias.h and its test, main.cpp, frame_pacer.h, xbox_present.cpp/.h; xgameruntime_offline.cpp for one comment): the base's xmem with #939's label hooks, file-backed sections and pin_mapped_data; both texture computers in xg_xs.cpp, the base's answering first; --first-run-ui kept without host speech in its profile. E, build, tools, docs (runtime/CMakeLists.txt, make_game.py, tools/rdna2spirv.py, tools/shader_disasm.py, scripts, tests, docs; docs/README.md and tests/test_exe_shaders_stage.py beyond the conflicts): the base's v_dot4 decode, #281's disassembler form and tests/semantic/test_fspx_dot4_op_sel_disasm.py dropped; the base's executable-shader step with #939's cache fix; 366 registered tests. Co-Authored-By: Claude Fable 5.2 <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
-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.py2
-rw-r--r--scripts/run_gpu_tests.py50
-rw-r--r--scripts/run_semantic_tests.py68
-rw-r--r--scripts/run_wine_tests.py228
-rw-r--r--scripts/translate_pipeline_compute.py170
-rw-r--r--scripts/windows-boot/README.md93
-rw-r--r--scripts/windows-boot/boot.ps1456
15 files changed, 1282 insertions, 47 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 d0690384e..21838be1f 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", "shims\xbox_bvh_builder.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\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\xbox_bvh_builder.cpp", "shims\com_shim.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 || 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/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..81bb3368a 100644
--- a/scripts/merge_check.py
+++ b/scripts/merge_check.py
@@ -67,7 +67,7 @@ def _merged_pr_number(subject):
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", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").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:
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 4e6454b90..141b7e4b9 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -37,6 +37,9 @@ from check import cbv_modulate_test
37from check import IMAGE_STORE_CASES, texture_uav_test 37from check import IMAGE_STORE_CASES, texture_uav_test
38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT 38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT
39from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations 39from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations
40from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands
41from check import round_f64_test # the four binary64 roundings on memory-fed inputs
42from 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) 43from 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 44from 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 45from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8
@@ -94,10 +97,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) 97 return struct.pack("<I", len(r)) + bytes(r)
95 98
96 99
100# A comment line a .asm carries when llvm-mc cannot assemble it (cs_dpp_cmp.asm: a VOPC compare in DPP form).
101TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here"
102
103
97def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: 104def 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.""" 105 """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: 106 with open(asm_path, encoding="utf-8") as source:
100 raw = source.read() 107 raw = source.read()
108 if any(ln.strip() == TEXT_ONLY_MARK for ln in raw.splitlines()):
109 # The source holds an instruction llvm-mc has no gfx1013 encoding for. The translator reads straight-line
110 # code from its text alone (tests/semantic/regen_fixtures.py writes such listings), so the lines go through
111 # as they are.
112 lines = [f"; {name} code 0x0..0x0 (synthetic), gfx1013, 0 invalid words"]
113 lines += ["\t" + ln.strip() for ln in raw.splitlines() if ln.strip() and not ln.lstrip().startswith(";")]
114 with open(s_path, "w", encoding="utf-8", newline="\n") as f:
115 f.write("\n".join(lines) + "\n")
116 return
101 cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 117 cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
102 for ln in raw.splitlines(): 118 for ln in raw.splitlines():
103 s = ln.strip() 119 s = ln.strip()
@@ -264,6 +280,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)] 280 return [struct.unpack_from("<4I", data, 16 * i) for i in range(n)]
265 281
266 282
283# cs_div_fmas_f64_rt's operands a = 1 + 2^-30, c = -(1 + 2^-29) as s4..s7 (low word first).
284DIV_FMAS_F64_SGPRS = "0x00400000,0x3ff00000,0x00800000,0xbff00000"
267UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders) 285UNSUPPORTED = 77 # vk_harness: the device lacks a stage the test draws with (geometry or mesh shaders)
268 286
269 287
@@ -429,8 +447,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)" 447 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(): 448 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)" 449 return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)"
450 if rc != 0:
451 return False, f"exit {rc}: {msg or 'no test output'}"
432 words = dump_words(msg) 452 words = dump_words(msg)
433 if rc != 0 or words is None: 453 if words is None:
434 return False, msg 454 return False, msg
435 vals = words[:len(want)] 455 vals = words[:len(want)]
436 return words_match(vals, want), " ".join((hex if hexwords else str)(x) for x in vals) 456 return words_match(vals, want), " ".join((hex if hexwords else str)(x) for x in vals)
@@ -982,10 +1002,22 @@ def run_suite(a, work: str) -> int:
982 if name in CLIP_CASES: 1002 if name in CLIP_CASES:
983 detail = clip_test(a.build, spirv_dir, name) 1003 detail = clip_test(a.build, spirv_dir, name)
984 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) 1004 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact"))
1005 elif name == "cs_w32_frexp_ldexp":
1006 detail = frexp_ldexp_test(a.build, spirv_dir, cs_env)
1007 results.append((name, None if isinstance(detail, Skip) else not detail,
1008 detail or "768 words exact (64 records, eight results each, and unchanged inputs)"))
985 elif name == "cs_w32_shift64": 1009 elif name == "cs_w32_shift64":
986 detail = shift64_test(a.build, spirv_dir, cs_env) 1010 detail = shift64_test(a.build, spirv_dir, cs_env)
987 results.append((name, None if isinstance(detail, Skip) else not detail, 1011 results.append((name, None if isinstance(detail, Skip) else not detail,
988 detail or "640 words exact (64 shift cases and unchanged inputs)")) 1012 detail or "640 words exact (64 shift cases and unchanged inputs)"))
1013 elif name == "cs_w32_cmp_f64":
1014 detail = cmp_f64_test(a.build, spirv_dir, cs_env)
1015 results.append((name, None if isinstance(detail, Skip) else not detail,
1016 detail or "1536 words exact (256 operand pairs and unchanged inputs)"))
1017 elif name == "cs_w32_round_f64":
1018 detail = round_f64_test(a.build, spirv_dir, cs_env)
1019 results.append((name, None if isinstance(detail, Skip) else not detail,
1020 detail or "1152 words exact (64 inputs, eight roundings each, and unchanged inputs)"))
989 elif name == "cs_workgroup_yz": 1021 elif name == "cs_workgroup_yz":
990 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) 1022 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env)
991 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" 1023 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches"
@@ -1103,10 +1135,12 @@ def run_suite(a, work: str) -> int:
1103 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, 1135 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False,
1104 hexwords=True) 1136 hexwords=True)
1105 results.append((name, ok, detail)) 1137 results.append((name, ok, detail))
1106 elif name == "cs_div_fmas_f64": 1138 elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"):
1107 # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64, 1139 # One-rounding binary64 FMA: strict where the translator emitted OpFmaKHR on doubles (shaderFmaFloat64,
1108 # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it. 1140 # --fma khr); under the default GLSL Fma the split result (0) is allowed, as cs_fma_fused allows it.
1109 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1141 # The _rt fixture reads the same operands from s4..s7, so the driver cannot fold the Fma at compile time.
1142 env = dict(cs_env or os.environ, VKC_SGPRS=DIV_FMAS_F64_SGPRS) if name.endswith("_rt") else cs_env
1143 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env)
1110 if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64 1144 if rc == UNSUPPORTED: # no shaderFloat64, or (--fma khr) no shaderFmaFloat64
1111 results.append((name, None, unsupported_skip(msg))) 1145 results.append((name, None, unsupported_skip(msg)))
1112 else: 1146 else:
@@ -1116,7 +1150,8 @@ def run_suite(a, work: str) -> int:
1116 ok = rc == 0 and (words == fused or (not strict and words == split)) 1150 ok = rc == 0 and (words == fused or (not strict and words == split))
1117 detail = " ".join(hex(x) for x in words) if words else msg 1151 detail = " ".join(hex(x) for x in words) if words else msg
1118 if ok and words == split: 1152 if ok and words == split:
1119 detail += " (split: the driver rounds GLSL Fma on doubles twice; --fma khr fixes it)" 1153 detail += (" (split: the driver rounded GLSL Fma on doubles twice%s; --fma khr fixes it)"
1154 % ("" if name.endswith("_rt") else " when folding the constants"))
1120 results.append((name, ok, detail)) 1155 results.append((name, ok, detail))
1121 elif name == "cs_cvt_f32_sat": 1156 elif name == "cs_cvt_f32_sat":
1122 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS). 1157 # #300's saturating float -> int conversions: one dispatch per input word in s4 (VKC_SGPRS).
@@ -1163,7 +1198,7 @@ def run_suite(a, work: str) -> int:
1163 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) 1198 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated()))
1164 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", 1199 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",
1165 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", 1200 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi",
1166 "cs_dpp_bound", "cs_dpp_w64", 1201 "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64",
1167 "cs_w64_mask_detect", 1202 "cs_w64_mask_detect",
1168 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", 1203 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute",
1169 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", 1204 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw",
@@ -1225,6 +1260,7 @@ def run_suite(a, work: str) -> int:
1225 "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16], 1260 "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16],
1226 "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], 1261 "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7],
1227 "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], 1262 "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777],
1263 "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0],
1228 "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], 1264 "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6],
1229 # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] 1265 # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7]
1230 # without it 1266 # without it
@@ -1299,7 +1335,7 @@ def run_suite(a, work: str) -> int:
1299 "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", 1335 "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",
1300 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", 1336 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec",
1301 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", 1337 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8",
1302 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_w32_andn2_exec", 1338 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec",
1303 "cs_w32_exec_computed") and not emulated and not partial 1339 "cs_w32_exec_computed") and not emulated and not partial
1304 if partial and not emulated: 1340 if partial and not emulated:
1305 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") 1341 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64")
@@ -1313,7 +1349,7 @@ def run_suite(a, work: str) -> int:
1313 continue 1349 continue
1314 if rc == 0: 1350 if rc == 0:
1315 skip = wave32_lane_skip(msg) 1351 skip = wave32_lane_skip(msg)
1316 if skip is None and name in WAVE32_PIN_DUMPS: 1352 if rc == 0 and skip is None and name in WAVE32_PIN_DUMPS:
1317 # the device may not be able to run the wave size this fixture was written for (a 64-only device 1353 # the device may not be able to run the wave size this fixture was written for (a 64-only device
1318 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too 1354 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too
1319 skip = subgroup_pin_skip(msg, cs_env) 1355 skip = subgroup_pin_skip(msg, cs_env)
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
index c364bb35d..03e0ddab4 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,34 @@ 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
35import time 39import time
36 40
37MAX_TIMEOUT_SECONDS = 24 * 60 * 60 41MAX_TIMEOUT_SECONDS = 24 * 60 * 60
38 42
43# The child runs the module through unittest's own program and writes the result to a file, so the count of tests
44# comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1
45# when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so
46# the name is imported and not looked up as an attribute of the program itself.
47CHILD_PROGRAM = (
48 "import json, os, sys, unittest\n"
49 "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n"
50 "result = program.result\n"
51 "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n"
52 " json.dump({'testsRun': result.testsRun}, handle)\n"
53 "if not result.wasSuccessful():\n"
54 " sys.exit(1)\n"
55 "elif result.testsRun == 0 and len(result.skipped) == 0:\n"
56 " sys.exit(5)\n"
57 "sys.exit(0)\n")
58
39 59
40def module_path(directory, module): 60def module_path(directory, module):
41 """Source path of a dotted module name, including a package's `__init__.py`.""" 61 """Source path of a dotted module name, including a package's `__init__.py`."""
@@ -73,28 +93,42 @@ def positive_seconds(value):
73 return seconds 93 return seconds
74 94
75 95
96def read_count(path):
97 """The number of tests the child ran, as unittest's own result object reported it."""
98 try:
99 with open(path, encoding="utf-8") as handle:
100 return int(json.load(handle)["testsRun"])
101 except (OSError, ValueError, KeyError, TypeError):
102 # The child wrote no result: it did not finish, so no test is known to have run.
103 return 0
104
105
76def run_module(directory, module, verbose, timeout=None): 106def run_module(directory, module, verbose, timeout=None):
77 """(return code, tests run, output) of `python -m unittest <target>` run from `directory`.""" 107 """(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 108 # `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 109 # 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. 110 # 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 111 target = module[:-len(".__init__")] if module.endswith(".__init__") else module
82 cmd = [sys.executable, "-m", "unittest", *(["-v"] if verbose else []), target] 112 cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target]
83 try: 113 with tempfile.TemporaryDirectory() as scratch:
84 p = subprocess.run(cmd, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, 114 count_path = os.path.join(scratch, "count.json")
85 errors="replace", timeout=timeout) 115 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path)
86 except subprocess.TimeoutExpired as exc: 116 try:
87 out = exc.stdout or "" 117 p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
88 if isinstance(out, bytes): # TimeoutExpired retains bytes even when text=True. 118 text=True, errors="replace", timeout=timeout)
89 out = out.decode(locale.getpreferredencoding(False), errors="replace") 119 except subprocess.TimeoutExpired as exc:
90 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" 120 # TimeoutExpired retains bytes even when text=True.
91 ran = re.search(r"^Ran (\d+) tests? in", p.stdout, re.M) 121 parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes)
92 count = int(ran.group(1)) if ran else 0 122 else chunk for chunk in (exc.stdout, exc.stderr) if chunk]
123 out = "".join(parts)
124 return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n"
125 count = read_count(count_path)
126 out = p.stdout + p.stderr
93 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the 127 # 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. 128 # 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: 129 if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stderr:
96 return 0, 0, p.stdout 130 return 0, 0, out
97 return p.returncode, count, p.stdout 131 return p.returncode, count, out
98 132
99 133
100def main(argv=None): 134def main(argv=None):
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..a7d70ab54
--- /dev/null
+++ b/scripts/translate_pipeline_compute.py
@@ -0,0 +1,170 @@
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 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