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 22:09:38 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-24 22:09:38 -0500
commit5115f0887940595aa0f46fed7fc9db28b64151ff (patch)
tree98b4df97d3b97af290331ea9893587e250c0fac0 /scripts
parentc8f7515e2e6fb2a2a61eb1e986ee8c6fd4431399 (diff)
parentb07b9ecb09b47fa6496f01ad9d8fe87d205bd5d8 (diff)
Merge main into RT-DIRECT-HEAP-COMPUTE (#1064)
main already supplies the directly indexed heaps to compute dispatches (integration #984, the tree this pull request was split from): with_direct_heaps()/compute_user_data() on Dispatch and the ExecuteIndirect dispatch path, RootArgumentLayout::compute_arguments_end (kNoSgpr for a spilled signature), LEONIDA_COMPUTE_DIRECT_HEAPS=0, and the first form of this test (direct dispatch, indirect after a resource-only rebind, the GPU read through the heap). That form stays. What this pull request adds beyond it is carried onto it: the review-round reports, the extra recorded-argument checks, the census tool and its evidence. Conflicts: - runtime/shims/d3d12_com.cpp: main's with_direct_heaps()/compute_user_data() and its one-argument note_direct_heap_indexing(). Carried: compute_user_data() makes the note itself, so an ExecuteIndirect dispatch with no heap bound is reported too (record_dispatch's own call removed), and a heap with no inline dword left is reported once per heap kind ("compute root arguments leave no inline SGPR for the resource/sampler heap"); a spilled signature (main: kNoSgpr) gets one note of its own. Dropped: the PR's GetEnvironmentVariableA switch (main's direct_heaps_enabled) and its "graphics heap-base SGPR is not supplied" notes (main supplies the graphics heaps). - runtime/shims/d3d12_com.h, runtime/shims/d3d12_vulkan_device.cpp: main's (compute_arguments_end and graphics_arguments_end with their comment; compute_arguments_end only when the compute arguments do not spill). - runtime/test/glsl/cs_user_data.comp: main's; its direct-indexing mode (s5 = 0xFFFFFFFC, heap at s9) is this pull request's, byte for byte. - runtime/test/d3d12_compute_test.cpp: the PR's block replaces main's earlier form of it (a superset: adds the bundle dispatch that inherits the parent's heaps, an indirect dispatch with only the sampler heap, signatures ending at s30 and s31, and the LEONIDA_COMPUTE_DIRECT_HEAPS=0 expectations). - docs/d3d12_vulkan.md: main's section 3.4 (the BatchCull s7 and PreSkin s9 evidence), with the PR's census paragraph (tools/compute_heap_layout_census.py, the seven paired layouts, the heap order as a hypothesis) and the no-room and spill reports. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'scripts')
-rw-r--r--scripts/bench_wave64.py8
-rw-r--r--scripts/build_runtime.ps16
-rw-r--r--scripts/check_no_game_data.py1
-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.py6
-rw-r--r--scripts/run_gpu_tests.py75
-rw-r--r--scripts/run_wine_tests.py228
-rw-r--r--scripts/translate_pipeline_compute.py174
-rw-r--r--scripts/windows-boot/README.md93
-rw-r--r--scripts/windows-boot/boot.ps1456
14 files changed, 1232 insertions, 42 deletions
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index e6fd59737..57253cb57 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -44,7 +44,13 @@ def build(work, name, emulate, llvm_mc):
44 r = subprocess.run([sys.executable, "-I", BUILD_PY, out, name], env=env, capture_output=True, text=True) 44 r = subprocess.run([sys.executable, "-I", BUILD_PY, out, name], env=env, capture_output=True, text=True)
45 if r.returncode: 45 if r.returncode:
46 sys.exit(r.stdout + r.stderr) 46 sys.exit(r.stdout + r.stderr)
47 return os.path.join(out, "spirv", name + ".spv") 47 spv = os.path.join(out, "spirv", name + ".spv")
48 if not os.path.isfile(spv):
49 mode = "emulated" if emulate else "native"
50 message = f"{name}: {mode} build did not produce a SPIR-V module"
51 reason = (r.stdout + r.stderr).strip()
52 sys.exit(f"{message}\n{reason}" if reason else message)
53 return spv
48 54
49 55
50def segments(spv: str) -> tuple[int, int] | None: 56def segments(spv: str) -> tuple[int, int] | None:
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index f24cc073f..733d2c041 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -86,14 +86,16 @@ $build || exit /b 1
86 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." 86 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it."
87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" 87 $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue"
88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } 88 $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" }
89 $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } 89 $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\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 bccee5e68..ae3d06e77 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -42,6 +42,7 @@ MAGICS = (
42 ("RPF9 archive", 0, b"9FPR"), 42 ("RPF9 archive", 0, b"9FPR"),
43 ("RPF9 archive", 0, b"RPF9"), 43 ("RPF9 archive", 0, b"RPF9"),
44 ("TTPF texture pool", 0, b"TTPF"), 44 ("TTPF texture pool", 0, b"TTPF"),
45 ("local BCPack predictor profile", 0, b"BCPHIST1"),
45 ("RAGE resource", 0, b"RSC7"), 46 ("RAGE resource", 0, b"RSC7"),
46 ("RAGE resource", 0, b"RSC8"), 47 ("RAGE resource", 0, b"RSC8"),
47 ("RAGE resource", 0, b"RSCC"), 48 ("RAGE resource", 0, b"RSCC"),
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 81bb3368a..e270cbe00 100644
--- a/scripts/merge_check.py
+++ b/scripts/merge_check.py
@@ -65,7 +65,7 @@ def _merged_pr_number(subject):
65 65
66 66
67def prior_merges(repo, main, numbers, depth): 67def prior_merges(repo, main, numbers, depth):
68 out = git(repo, "log", main, "--first-parent", f"-n{depth}", "--format=%H%x09%s").stdout 68 out = git(repo, "log", "--first-parent", f"-n{depth}", "--format=%H%x09%s", main, "--").stdout
69 hits = {number: [] for number in numbers} 69 hits = {number: [] for number in numbers}
70 for line in out.split("\n"): 70 for line in out.split("\n"):
71 sha, _, subject = line.partition("\t") 71 sha, _, subject = line.partition("\t")
@@ -113,7 +113,7 @@ def duplicates(repo, main, tree, min_length, block=3):
113 patch = git(repo, "-c", "core.quotePath=true", "diff", "--unified=0", "--no-color", "--no-renames", 113 patch = git(repo, "-c", "core.quotePath=true", "diff", "--unified=0", "--no-color", "--no-renames",
114 "--inter-hunk-context=0", "--src-prefix=a/", "--dst-prefix=b/", "--no-relative", 114 "--inter-hunk-context=0", "--src-prefix=a/", "--dst-prefix=b/", "--no-relative",
115 "--no-ext-diff", "--no-textconv", "--ignore-submodules=all", 115 "--no-ext-diff", "--no-textconv", "--ignore-submodules=all",
116 main, tree).stdout 116 main, tree, "--").stdout
117 for line in patch.split("\n"): 117 for line in patch.split("\n"):
118 if line.startswith("diff --git "): 118 if line.startswith("diff --git "):
119 path, added = None, None 119 path, added = None, None
@@ -132,7 +132,7 @@ def duplicates(repo, main, tree, min_length, block=3):
132 132
133 def windows(rev, path): 133 def windows(rev, path):
134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. 134 # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file.
135 r = git(repo, "show", f"{rev}:{path}") 135 r = git(repo, "show", f"{rev}:{path}", "--")
136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] 136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())]
137 content = [text for _, text in lines] 137 content = [text for _, text in lines]
138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) 138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1))
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index e8fce4277..8ba62104d 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -25,18 +25,22 @@ sys.path.insert(0, os.path.join(ROOT, "tools"))
25import mc_command # noqa: E402 25import mc_command # noqa: E402
26sys.path.insert(0, SHADER_DIR) 26sys.path.insert(0, SHADER_DIR)
27from build import CLIP_CASES, clip_container, shader_source 27from build import CLIP_CASES, clip_container, shader_source
28from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test, fmt_sint32_test, 28from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_narrow_test,
29 fmt_xy_xyz_test, tbuffer_store_test) 29 fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported)
30from check import compute_unsupported # vk_compute_test's exit 77 over a feature the module needs
31from compute_fixture import compute_header 30from compute_fixture import compute_header
32from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) 31from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test)
33from check import (CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES, 32from check import (CS_SMEM_VCC, CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES,
34 TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message, 33 TEXTURE_MIP_TEST, GATHER_LOD_TEST, MIP_TEST_PASSES, TEXTURE_CONSTANTS, USER_SGPRS_ENV, USER_SGPRS_WORDS, Skip, mesh_v5_test, not_found_message,
35 pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test) 34 pick_build_dir, start_failure, table_fetch_test, texture_gradient_a16_test, texture_mip_test)
36from check import SIGNED_MIP_TEST, UINT_MIP_TEST 35from check import SIGNED_MIP_TEST, UINT_MIP_TEST
37from check import cbv_modulate_test 36from check import cbv_modulate_test
37from check import IMAGE_STORE_CASES, texture_uav_test
38from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS
38from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT 39from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT
39from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations 40from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations
41from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands
42from check import round_f64_test # the four binary64 roundings on memory-fed inputs
43from check import frexp_ldexp_test # binary32 and binary64 frexp, and v_ldexp_f32, on memory-fed records
40from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan) 44from check import judged_words, words_match # dump words not judged on some devices (cs_signed_zero_nan)
41from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py 45from check import TEXOFF_ARGS, texoff_problem # ps_texoff's expected words and arguments live in check.py
42from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8 46from check import TEXOFF_FALLBACK, texoff_env # LEONIDA_TEXOFF_FALLBACK=1: texel offsets without maintenance8
@@ -94,10 +98,23 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_
94 return struct.pack("<I", len(r)) + bytes(r) 98 return struct.pack("<I", len(r)) + bytes(r)
95 99
96 100
101# A comment line a .asm carries when llvm-mc cannot assemble it (cs_dpp_cmp.asm: a VOPC compare in DPP form).
102TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here"
103
104
97def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: 105def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None:
98 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" 106 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py."""
99 with open(asm_path, encoding="utf-8") as source: 107 with open(asm_path, encoding="utf-8") as source:
100 raw = source.read() 108 raw = source.read()
109 if any(ln.strip() == TEXT_ONLY_MARK for ln in raw.splitlines()):
110 # The source holds an instruction llvm-mc has no gfx1013 encoding for. The translator reads straight-line
111 # code from its text alone (tests/semantic/regen_fixtures.py writes such listings), so the lines go through
112 # as they are.
113 lines = [f"; {name} code 0x0..0x0 (synthetic), gfx1013, 0 invalid words"]
114 lines += ["\t" + ln.strip() for ln in raw.splitlines() if ln.strip() and not ln.lstrip().startswith(";")]
115 with open(s_path, "w", encoding="utf-8", newline="\n") as f:
116 f.write("\n".join(lines) + "\n")
117 return
101 cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 118 cmd = mc_command.mc_command(llvm_mc) + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
102 for ln in raw.splitlines(): 119 for ln in raw.splitlines():
103 s = ln.strip() 120 s = ln.strip()
@@ -431,8 +448,10 @@ def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial:
431 return None, "SKIP (no 64-wide compute subgroup on this device)" 448 return None, "SKIP (no 64-wide compute subgroup on this device)"
432 if rc == 0 and wave64 and "compute subgroup size: 64" not in msg.splitlines(): 449 if rc == 0 and wave64 and "compute subgroup size: 64" not in msg.splitlines():
433 return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)" 450 return False, "64-wide subgroup was not confirmed (rebuild vk_compute_test)"
451 if rc != 0:
452 return False, f"exit {rc}: {msg or 'no test output'}"
434 words = dump_words(msg) 453 words = dump_words(msg)
435 if rc != 0 or words is None: 454 if words is None:
436 return False, msg 455 return False, msg
437 vals = words[:len(want)] 456 vals = words[:len(want)]
438 return words_match(vals, want), " ".join((hex if hexwords else str)(x) for x in vals) 457 return words_match(vals, want), " ".join((hex if hexwords else str)(x) for x in vals)
@@ -667,7 +686,8 @@ OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_transl
667 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test", 686 "cs_m4_fill": "d3d12_m4_compute_test", "cs_m4_indirect": "d3d12_m4_compute_test",
668 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test", 687 "cs_buf_typed": "d3d12_buffer_uav_test", "cs_buf_counter": "d3d12_buffer_uav_test",
669 "ps_live_width": "w64_graphics.py", 688 "ps_live_width": "w64_graphics.py",
670 "ps_heap_index": "d3d12_heap_index_test"} 689 "ps_heap_index": "d3d12_heap_index_test",
690 "ps_quad_flat": "d3d12_quad_index_test", "vs_quad_inst": "d3d12_quad_index_test"}
671 691
672 692
673# Shaders a selected test draws with, built even when the filter leaves them out (#192). 693# Shaders a selected test draws with, built even when the filter leaves them out (#192).
@@ -983,10 +1003,22 @@ def run_suite(a, work: str) -> int:
983 if name in CLIP_CASES: 1003 if name in CLIP_CASES:
984 detail = clip_test(a.build, spirv_dir, name) 1004 detail = clip_test(a.build, spirv_dir, name)
985 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact")) 1005 results.append((name, None if isinstance(detail, Skip) else not detail, detail or "four pixel masks exact"))
1006 elif name == "cs_w32_frexp_ldexp":
1007 detail = frexp_ldexp_test(a.build, spirv_dir, cs_env)
1008 results.append((name, None if isinstance(detail, Skip) else not detail,
1009 detail or "768 words exact (64 records, eight results each, and unchanged inputs)"))
986 elif name == "cs_w32_shift64": 1010 elif name == "cs_w32_shift64":
987 detail = shift64_test(a.build, spirv_dir, cs_env) 1011 detail = shift64_test(a.build, spirv_dir, cs_env)
988 results.append((name, None if isinstance(detail, Skip) else not detail, 1012 results.append((name, None if isinstance(detail, Skip) else not detail,
989 detail or "640 words exact (64 shift cases and unchanged inputs)")) 1013 detail or "640 words exact (64 shift cases and unchanged inputs)"))
1014 elif name == "cs_w32_cmp_f64":
1015 detail = cmp_f64_test(a.build, spirv_dir, cs_env)
1016 results.append((name, None if isinstance(detail, Skip) else not detail,
1017 detail or "1536 words exact (256 operand pairs and unchanged inputs)"))
1018 elif name == "cs_w32_round_f64":
1019 detail = round_f64_test(a.build, spirv_dir, cs_env)
1020 results.append((name, None if isinstance(detail, Skip) else not detail,
1021 detail or "1152 words exact (64 inputs, eight roundings each, and unchanged inputs)"))
990 elif name == "cs_workgroup_yz": 1022 elif name == "cs_workgroup_yz":
991 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env) 1023 rc, msg = run_cmd([vk_compute, spv, "2x3x4", "workgroup_yz"], env=cs_env)
992 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches" 1024 results.append((name,) + compute_result(rc, msg, rc == 0 and "2x3x4 workgroup Y/Z: 0 mismatches"
@@ -1096,6 +1128,10 @@ def run_suite(a, work: str) -> int:
1096 vals = words[:len(USER_SGPRS_WORDS)] if words else [] 1128 vals = words[:len(USER_SGPRS_WORDS)] if words else []
1097 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS, 1129 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS,
1098 " ".join(hex(x) for x in vals) if vals else msg)) 1130 " ".join(hex(x) for x in vals) if vals else msg))
1131 elif name == "cs_w32_salu_ext":
1132 detail = salu_ext_test(a.build, spirv_dir, cs_env)
1133 results.append((name, None if isinstance(detail, Skip) else not detail,
1134 detail or "80 words exact (73 results of 38 scalar ops and the untouched fill)"))
1099 elif name == "cs_f64_add": 1135 elif name == "cs_f64_add":
1100 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1136 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env)
1101 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names 1137 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names
@@ -1165,20 +1201,21 @@ def run_suite(a, work: str) -> int:
1165 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. 1201 # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none.
1166 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. 1202 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size.
1167 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) 1203 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated()))
1168 elif name in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", 1204 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",
1169 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", 1205 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi",
1170 "cs_dpp_bound", "cs_dpp_w64", 1206 "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64",
1171 "cs_w64_mask_detect", 1207 "cs_w64_mask_detect",
1172 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", 1208 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute",
1173 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", 1209 "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw",
1174 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", 1210 "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load",
1175 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", 1211 "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent",
1176 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", 1212 "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end",
1177 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", 1213 "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec",
1178 "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): 1214 "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"):
1179 cs_dump_wants = { 1215 cs_dump_wants = {
1180 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], 1216 "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000],
1181 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone 1217 # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone
1218 "cs_smem_vcc_base": CS_SMEM_VCC,
1182 "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, 1219 "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030,
1183 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], 1220 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C],
1184 # SHADER-52: wave32 lane select & 31 (40 → 8) 1221 # SHADER-52: wave32 lane select & 31 (40 → 8)
@@ -1228,6 +1265,7 @@ def run_suite(a, work: str) -> int:
1228 "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16], 1265 "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16],
1229 "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], 1266 "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7],
1230 "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], 1267 "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777],
1268 "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0],
1231 "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], 1269 "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6],
1232 # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] 1270 # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7]
1233 # without it 1271 # without it
@@ -1272,6 +1310,7 @@ def run_suite(a, work: str) -> int:
1272 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], 1310 "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32],
1273 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header) 1311 "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header)
1274 "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], # .asm header 1312 "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], # .asm header
1313 "cs_w64x_cmp_sdst": [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5], # .asm header
1275 "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes 1314 "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes
1276 # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm) 1315 # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm)
1277 "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120], 1316 "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120],
@@ -1302,7 +1341,7 @@ def run_suite(a, work: str) -> int:
1302 "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", 1341 "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",
1303 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", 1342 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec",
1304 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", 1343 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8",
1305 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_w32_andn2_exec", 1344 "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec",
1306 "cs_w32_exec_computed") and not emulated and not partial 1345 "cs_w32_exec_computed") and not emulated and not partial
1307 if partial and not emulated: 1346 if partial and not emulated:
1308 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") 1347 cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64")
@@ -1316,7 +1355,7 @@ def run_suite(a, work: str) -> int:
1316 continue 1355 continue
1317 if rc == 0: 1356 if rc == 0:
1318 skip = wave32_lane_skip(msg) 1357 skip = wave32_lane_skip(msg)
1319 if skip is None and name in WAVE32_PIN_DUMPS: 1358 if rc == 0 and skip is None and name in WAVE32_PIN_DUMPS:
1320 # the device may not be able to run the wave size this fixture was written for (a 64-only device 1359 # the device may not be able to run the wave size this fixture was written for (a 64-only device
1321 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too 1360 # can't pin 32, so cs_barrier_loop's words mean nothing); check.py skips it too
1322 skip = subgroup_pin_skip(msg, cs_env) 1361 skip = subgroup_pin_skip(msg, cs_env)
@@ -1332,15 +1371,13 @@ def run_suite(a, work: str) -> int:
1332 unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) 1371 unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None)
1333 detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" 1372 detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)"
1334 results.append((name, ok, detail)) 1373 results.append((name, ok, detail))
1335 elif name == "cs_imgstore": 1374 elif name in IMAGE_STORE_CASES:
1336 rc, msg = run_cmd([vk_store, spv]) 1375 rc, msg = run_cmd([vk_store, spv, *IMAGE_STORE_CASES[name]])
1337 results.append((name, *helper_result(rc, msg)))
1338 elif name == "cs_imgstore_cube": # GPU-CUBE-STORE: six-layer 2D-array views at bindings 11/12/13
1339 rc, msg = run_cmd([vk_store, spv, "cube"])
1340 results.append((name, *helper_result(rc, msg)))
1341 elif name in ("cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", "cs_sample_lz_int_d16"):
1342 rc, msg = run_cmd([vk_store, spv, "load" if name in ("cs_imgload", "cs_imgload_tfe") else "load-d16"])
1343 results.append((name, *helper_result(rc, msg))) 1376 results.append((name, *helper_result(rc, msg)))
1377 elif name == "cs_texture_uav":
1378 problem = texture_uav_test(a.build, spv)
1379 results.append((name, None if isinstance(problem, Skip) else not problem,
1380 problem or "D3D12/Vulkan storage-image readback matched"))
1344 elif name in MIP_TEST_PASSES: 1381 elif name in MIP_TEST_PASSES:
1345 problem = texture_mip_test(a.build, spirv_dir, name) 1382 problem = texture_mip_test(a.build, spirv_dir, name)
1346 ok = None if isinstance(problem, Skip) else not problem 1383 ok = None if isinstance(problem, Skip) else not problem
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index 8435f7fb9..d36011430 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -2,7 +2,7 @@
2 2
3Usage: 3Usage:
4 python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida 4 python -I scripts/run_wine_tests.py --tests ctest.json --windows-root D:/a/Leonida/Leonida
5 [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--summary FILE] [--label TEXT] 5 [--root DIR] [--wine CMD] [--require NAME ...] [--timeout SECONDS] [--jobs N] [--summary FILE] [--label TEXT]
6 6
7--tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was 7--tests is the output of `ctest --show-only=json-v1` from the Windows build, and --windows-root the checkout it was
8made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default: 8made in (forward slashes, as `cygpath -m` prints it). Paths under it are mapped to --root, the Linux checkout (default:
@@ -16,8 +16,16 @@ Every test is reported. The exit code is 1 if a test named by --require fails or
16others show what does and doesn't work under Wine yet without failing the job. 16others show what does and doesn't work under Wine yet without failing the job.
17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test. 17--timeout caps each process; a shorter positive CTest TIMEOUT takes precedence for that test.
18Relative executable paths in --wine or WINE are read from the directory where you start this runner. 18Relative executable paths in --wine or WINE are read from the directory where you start this runner.
19
20Each test gets WINEDLLOVERRIDES with winedbg.exe and winemenubuilder.exe disabled, so a crash fails at once instead of
21waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One
22wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command,
23else the one on PATH) and stopped at the end, instead of a new one starting for every test.
24--jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and
25DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default).
19""" 26"""
20import argparse 27import argparse
28from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
21from graphlib import CycleError, TopologicalSorter 29from graphlib import CycleError, TopologicalSorter
22import json 30import json
23import math 31import math
@@ -30,6 +38,7 @@ import signal
30import subprocess 38import subprocess
31import sys 39import sys
32import tempfile 40import tempfile
41import threading
33import time 42import time
34 43
35ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 44ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -120,6 +129,97 @@ class DriveMap:
120 return False 129 return False
121 130
122 131
132# A crashed test would wait in winedbg until the timeout; winemenubuilder writes file associations and menu entries
133# into the user's profile when a fresh prefix is set up.
134DEFAULT_DLL_OVERRIDES = ("winedbg.exe=d", "winemenubuilder.exe=d")
135
136
137def _override_names(entry: str) -> set[str]:
138 """The programs one WINEDLLOVERRIDES entry ("a,b.exe=n") names, lower case and without .dll/.exe."""
139 names = set()
140 for name in entry.partition("=")[0].split(","):
141 name = name.strip().lower()
142 for suffix in (".dll", ".exe"):
143 if name.endswith(suffix):
144 name = name[:-len(suffix)]
145 if name:
146 names.add(name)
147 return names
148
149
150def merge_dll_overrides(given: str | None) -> str:
151 """WINEDLLOVERRIDES with the defaults added, leaving out a default for a program the given value already names."""
152 entries = [e for e in (given or "").split(";") if e.strip()]
153 named = set().union(*(_override_names(e) for e in entries))
154 return ";".join([d for d in DEFAULT_DLL_OVERRIDES if not _override_names(d) & named] + entries)
155
156
157def find_wineserver(wine: list[str]) -> str | None:
158 """The wineserver the --wine command uses: $WINESERVER, else the one next to it, else the one on PATH."""
159 given = os.environ.get("WINESERVER")
160 if given and shutil.which(given):
161 return shutil.which(given)
162 for part in wine:
163 resolved = shutil.which(part)
164 if resolved and os.path.basename(resolved).lower() in ("wine", "wine64"):
165 for folder in (os.path.dirname(resolved), os.path.dirname(os.path.realpath(resolved))):
166 sibling = shutil.which(os.path.join(folder, "wineserver"))
167 if sibling:
168 return sibling
169 return shutil.which("wineserver")
170
171
172class KeptServer:
173 """Keeps one wineserver alive for the run instead of one starting and stopping for every test.
174
175 `wineserver -p` starts a persistent server for $WINEPREFIX; `wineserver -k` stops it and the prefix's Wine
176 processes at the end, also after a failure or Ctrl+C. A server still shutting down (wineboot's lingers a few
177 seconds) is waited for first; one that stays (started by hand with -p) is used and left running.
178 The first Wine program a server runs starts the prefix's services, which inherit its output and live as long as
179 the server: `wine wineboot` starts them with no output, or the first test would wait for the end of its output
180 until the timeout.
181 """
182
183 def __init__(self, command: str | None, wine: list[str]):
184 self.command, self.wine, self.started, self.note = command, wine, False, ""
185
186 def _run(self, *flags, timeout=30.0) -> int | None:
187 try:
188 return subprocess.run([self.command, *flags], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
189 stderr=subprocess.DEVNULL, timeout=timeout).returncode
190 except (OSError, subprocess.TimeoutExpired):
191 return None
192
193 def __enter__(self):
194 if not self.command:
195 self.note = "no wineserver found: each test starts its own"
196 return self
197 code = self._run("-p")
198 if code == 2: # one is already running for this prefix
199 if self._run("-w", timeout=15.0) == 0:
200 code = self._run("-p")
201 else:
202 self.note = "a wineserver already runs for this prefix: used and left running"
203 return self
204 self.started = code == 0
205 if not self.started:
206 self.note = f"could not start {self.command} -p: each test starts its own server"
207 return self
208 self.note = "wineserver kept alive for the run"
209 env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES")))
210 try:
211 subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
212 stderr=subprocess.DEVNULL, env=env, timeout=120)
213 except (OSError, subprocess.TimeoutExpired):
214 pass # the tests start the services then, as without a kept server
215 return self
216
217 def __exit__(self, *exc):
218 if self.started:
219 self._run("-k")
220 return False
221
222
123def wine_path(path: str) -> str: 223def wine_path(path: str) -> str:
124 """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y.""" 224 """Wine's Z: drive is the Unix root, so a Windows program reads /x/y as Z:\\x\\y."""
125 return "Z:" + os.path.abspath(path).replace("/", "\\") 225 return "Z:" + os.path.abspath(path).replace("/", "\\")
@@ -194,6 +294,7 @@ def run_test(test: dict, args, wine: list[str], *, failed_setups: tuple[str, ...
194 if not key or not equals or "\0" in assignment: 294 if not key or not equals or "\0" in assignment:
195 return "fail", "invalid CTest ENVIRONMENT entry: expected NAME=value" 295 return "fail", "invalid CTest ENVIRONMENT entry: expected NAME=value"
196 env[key] = value 296 env[key] = value
297 env["WINEDLLOVERRIDES"] = merge_dll_overrides(env.get("WINEDLLOVERRIDES"))
197 timeout = args.timeout 298 timeout = args.timeout
198 if "TIMEOUT" in props: 299 if "TIMEOUT" in props:
199 try: 300 try:
@@ -257,19 +358,42 @@ def run_test_process(argv: list[str], *, cwd: str, env: dict[str, str],
257 358
258 # Wine's Windows children and launcher wrappers can outlive the immediate child. 359 # Wine's Windows children and launcher wrappers can outlive the immediate child.
259 with subprocess.Popen(argv, **options, start_new_session=True) as proc: 360 with subprocess.Popen(argv, **options, start_new_session=True) as proc:
361 with _running_lock:
362 _running.add(proc.pid)
260 try: 363 try:
261 out, _ = proc.communicate(timeout=timeout) 364 out, _ = proc.communicate(timeout=timeout)
262 except (subprocess.TimeoutExpired, KeyboardInterrupt): 365 except (subprocess.TimeoutExpired, KeyboardInterrupt):
263 # The launcher may have exited while a helper still holds the output pipe. 366 # The launcher may have exited while a helper still holds the output pipe.
264 try: 367 _kill_group(proc.pid)
265 os.killpg(proc.pid, signal.SIGKILL)
266 except ProcessLookupError:
267 pass
268 proc.wait() 368 proc.wait()
269 raise 369 raise
370 finally:
371 with _running_lock:
372 _running.discard(proc.pid)
270 return subprocess.CompletedProcess(argv, proc.returncode, out) 373 return subprocess.CompletedProcess(argv, proc.returncode, out)
271 374
272 375
376# The process groups of the tests running now: with --jobs, Ctrl+C reaches only the main thread, which stops them.
377_running: set[int] = set()
378_running_lock = threading.Lock()
379
380
381def _kill_group(pid: int) -> None:
382 try:
383 os.killpg(pid, signal.SIGKILL)
384 except (ProcessLookupError, PermissionError):
385 pass
386
387
388def stop_running_tests() -> None:
389 if os.name != "posix":
390 return
391 with _running_lock:
392 pids = list(_running)
393 for pid in pids:
394 _kill_group(pid)
395
396
273def positive_seconds(text: str) -> float: 397def positive_seconds(text: str) -> float:
274 """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" 398 """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on."""
275 try: 399 try:
@@ -283,6 +407,17 @@ def positive_seconds(text: str) -> float:
283 return value 407 return value
284 408
285 409
410def positive_int(text: str) -> int:
411 """--jobs: a whole number of at least 1."""
412 try:
413 value = int(text)
414 except ValueError:
415 raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None
416 if value < 1:
417 raise argparse.ArgumentTypeError("must be at least 1")
418 return value
419
420
286def wine_command(text: str) -> list[str]: 421def wine_command(text: str) -> list[str]:
287 """--wine: split into a command the way a shell would, refusing blank or malformed values up front.""" 422 """--wine: split into a command the way a shell would, refusing blank or malformed values up front."""
288 try: 423 try:
@@ -331,6 +466,48 @@ def read_tests(path: str) -> list[dict] | None:
331 return tests 466 return tests
332 467
333 468
469def run_parallel(tests: list[dict], order: list[int], before: dict[int, set[int]], jobs: int, run_one, outcomes: dict,
470 results_by_index: dict, report) -> None:
471 """Run up to `jobs` tests at a time and report them in `order`, as the serial loop does.
472
473 A test starts once the tests it depends on have finished. A RUN_SERIAL test runs alone, and two tests that share
474 a RESOURCE_LOCK never run at the same time.
475 """
476 serial = {index for index, test in enumerate(tests) if truthy(properties(test).get("RUN_SERIAL"))}
477 locks = {index: set(regex_list(properties(test).get("RESOURCE_LOCK", []))) for index, test in enumerate(tests)}
478 waiting, running, held = list(order), {}, set()
479 next_report = 0
480 with ThreadPoolExecutor(max_workers=jobs) as pool:
481 try:
482 while waiting or running:
483 for index in list(waiting):
484 if len(running) >= jobs or any(r in serial for r in running.values()):
485 break
486 if before[index] - results_by_index.keys() or locks[index] & held:
487 continue
488 if index in serial and running:
489 continue
490 waiting.remove(index)
491 held |= locks[index]
492 running[pool.submit(run_one, index)] = index
493 if index in serial:
494 break
495 done, _ = wait(running, return_when=FIRST_COMPLETED)
496 for future in done:
497 index = running.pop(future)
498 outcomes[index] = future.result()
499 results_by_index[index] = outcomes[index][0]
500 held -= locks[index]
501 while next_report < len(order) and order[next_report] in outcomes:
502 report(order[next_report])
503 next_report += 1
504 except BaseException:
505 # Ctrl+C reaches this thread only: stop the tests the workers are waiting on, start no more.
506 pool.shutdown(wait=False, cancel_futures=True)
507 stop_running_tests()
508 raise
509
510
334def main() -> int: 511def main() -> int:
335 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 512 ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
336 ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build") 513 ap.add_argument("--tests", required=True, help="ctest --show-only=json-v1 output from the Windows build")
@@ -341,6 +518,8 @@ def main() -> int:
341 ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") 518 ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)")
342 ap.add_argument("--timeout", type=positive_seconds, default=120.0, 519 ap.add_argument("--timeout", type=positive_seconds, default=120.0,
343 help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") 520 help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)")
521 ap.add_argument("--jobs", type=positive_int, default=1,
522 help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)")
344 ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") 523 ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)")
345 ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version") 524 ap.add_argument("--label", help="named in the summary's heading, e.g. the Wine version")
346 args = ap.parse_args() 525 args = ap.parse_args()
@@ -352,9 +531,12 @@ def main() -> int:
352 indices = {name: index for index, name in enumerate(names)} 531 indices = {name: index for index, name in enumerate(names)}
353 setups = fixture_dependencies(tests) 532 setups = fixture_dependencies(tests)
354 sorter = TopologicalSorter(setups) 533 sorter = TopologicalSorter(setups)
534 before = {index: set(setups[index]) for index in range(len(tests))}
355 for index, test in enumerate(tests): 535 for index, test in enumerate(tests):
356 # DEPENDS controls order. Only failed fixture setups block a consumer. 536 # DEPENDS controls order. Only failed fixture setups block a consumer.
357 sorter.add(index, *(indices[name] for name in properties(test).get("DEPENDS", []) if name in indices)) 537 depends = [indices[name] for name in properties(test).get("DEPENDS", []) if name in indices]
538 sorter.add(index, *depends)
539 before[index].update(depends)
358 try: 540 try:
359 order = list(sorter.static_order()) 541 order = list(sorter.static_order())
360 except CycleError: 542 except CycleError:
@@ -367,18 +549,30 @@ def main() -> int:
367 results = {} 549 results = {}
368 results_by_index: dict[int, str] = {} 550 results_by_index: dict[int, str] = {}
369 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") 551 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine")
370 with DriveMap(args.windows_root, args.root, prefix) as drive: 552 outcomes: dict[int, tuple[str, str]] = {}
553
554 def run_one(index: int) -> tuple[str, str]:
555 failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail")
556 return run_test(tests[index], args, wine, failed_setups=failed_setups)
557
558 def report(index: int) -> None:
559 status, detail = outcomes[index]
560 results[names[index]] = status
561 print(f"[{status.upper()}] {names[index]}", flush=True)
562 if status != "pass":
563 for line in detail.rstrip().splitlines()[-40:]:
564 print(f" {line}")
565
566 with DriveMap(args.windows_root, args.root, prefix) as drive, KeptServer(find_wineserver(wine), wine) as server:
371 print(drive.note, flush=True) 567 print(drive.note, flush=True)
372 for index in order: 568 print(server.note, flush=True)
373 name = names[index] 569 if args.jobs == 1:
374 failed_setups = tuple(names[setup] for setup in setups[index] if results_by_index[setup] == "fail") 570 for index in order:
375 status, detail = run_test(tests[index], args, wine, failed_setups=failed_setups) 571 outcomes[index] = run_one(index)
376 results_by_index[index] = status 572 results_by_index[index] = outcomes[index][0]
377 results[name] = status 573 report(index)
378 print(f"[{status.upper()}] {name}", flush=True) 574 else:
379 if status != "pass": 575 run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report)
380 for line in detail.rstrip().splitlines()[-40:]:
381 print(f" {line}")
382 576
383 missing = list(dict.fromkeys(n for n in args.require if n not in results)) 577 missing = list(dict.fromkeys(n for n in args.require if n not in results))
384 failed_required = [n for n in args.require if results.get(n) != "pass"] 578 failed_required = [n for n in args.require if results.get(n) != "pass"]
diff --git a/scripts/translate_pipeline_compute.py b/scripts/translate_pipeline_compute.py
new file mode 100644
index 000000000..4e691110b
--- /dev/null
+++ b/scripts/translate_pipeline_compute.py
@@ -0,0 +1,174 @@
1"""Build an interrupted or new pipeline compute pack from shader_library.py output (Linux).
2
3Two translation processes, including the parent, each run at most one SPIRV-Tools process.
4Validated modules and their receipts survive interruption. The runtime index is published last.
5"""
6import argparse
7import fcntl
8import hashlib
9import json
10import os
11import resource
12import shutil
13import sys
14import tempfile
15from pathlib import Path
16
17ROOT = Path(__file__).resolve().parents[1]
18sys.path[:0] = [str(ROOT / "tools"), str(ROOT)]
19from make_game import file_sha256 as digest, translation_sources_digest
20import rdna2spirv as translator
21
22
23def build_one(src, out, name, settings, compact=False):
24 listing = src / "disasm" / (name + ".s")
25 side = src / "fspx" / name
26 code, state = (Path(str(side) + suffix) for suffix in (".code", ".state"))
27 code_key, state_key = digest(code), digest(state)
28 container = src / (name + ".dxbc")
29 inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")),
30 digest(container) if container.is_file() else None]
31 key = hashlib.sha256(json.dumps(inputs).encode()).hexdigest()
32 receipt = out / ".compute-cache" / (key + ".json")
33 if receipt.exists():
34 try:
35 row = json.loads(receipt.read_text(encoding="utf-8"))
36 if (row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key):
37 module_hash = row["module"]
38 if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash):
39 if digest(out / (name + "_" + module_hash + ".spv")) == module_hash:
40 return row
41 except (OSError, ValueError, KeyError, TypeError):
42 pass
43
44 asm = translator.translate(str(listing))
45 with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp:
46 sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv"
47 sa.write_text(asm, encoding="utf-8", newline="\n")
48 result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, compact=compact)
49 if result.returncode:
50 raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0])
51 meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing))
52 if (meta.get("stage"), meta.get("fspx_code_sha256"), meta.get("fspx_state_sha256")) != (
53 "cs", code_key, state_key):
54 raise ValueError("compute stage or FSPX identity mismatch")
55 module_hash = digest(sv)
56 sv.replace(out / (name + "_" + module_hash + ".spv"))
57 row = {"meta": meta, "module": module_hash}
58 translator.write_index(str(receipt), row)
59 return row
60
61
62def build_part(src, out, names, settings, report, compact=False):
63 rows, failures = {}, {}
64 for number, name in enumerate(names, 1):
65 try:
66 rows[name] = build_one(src, out, name, settings, compact)
67 except (translator.Unsupported, MemoryError) as e:
68 failures[name] = str(e) or type(e).__name__
69 if number % 100 == 0 or number == len(names):
70 print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True)
71 translator.write_index(str(report), {"rows": rows, "failures": failures})
72
73
74def build(src, out, names, settings, jobs, compact=False):
75 cache = out / ".compute-cache"
76 cache.mkdir(exist_ok=True)
77 with (cache / "lock").open("ab") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp:
78 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
79 reports = [Path(tmp) / str(i) for i in range(jobs)]
80 pid = os.fork() if jobs == 2 else None
81 if pid == 0:
82 try:
83 build_part(src, out, names[1::2], settings, reports[1], compact)
84 except BaseException:
85 import traceback
86 traceback.print_exc()
87 os._exit(1)
88 os._exit(0)
89 try:
90 build_part(src, out, names[::jobs], settings, reports[0], compact)
91 finally:
92 if pid and os.waitpid(pid, 0)[1]:
93 raise RuntimeError("second translation worker failed")
94
95 index, failures, pairs = {}, {}, {}
96 for report in reports:
97 part = json.loads(report.read_text(encoding="utf-8"))
98 failures.update(part["failures"])
99 for name, row in part["rows"].items():
100 module, meta = row["module"], row["meta"]
101 pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"]
102 if pairs.setdefault(pair, module) != module:
103 raise ValueError("conflicting compute modules for one code/state pair")
104 # The same binary can implement different code/state keys. Each needs a runtime entry.
105 entry = name + "_" + module
106 index[entry] = meta
107 by_hash = {}
108 for name, reason in failures.items():
109 code = digest(src / "fspx" / (name + ".code"))
110 state = digest(src / "fspx" / (name + ".state"))
111 by_hash.setdefault(code, {})[state] = reason
112 translator.write_index(str(out / "failures.json"), by_hash)
113 translator.write_index(str(out / "index.json"), index)
114 print(f"{len(index)}/{len(names)} valid, {len(failures)} failed")
115 return int(bool(failures))
116
117
118def main():
119 ap = argparse.ArgumentParser(description=__doc__)
120 ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/")
121 ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory")
122 ap.add_argument("--jobs", type=int, choices=(1, 2), default=2)
123 ap.add_argument("--memory-mib", type=int, default=768, help="virtual memory per process (default 768 MiB)")
124 ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a",
125 help="bindless descriptor table hash shared with the runtime")
126 ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit,
127 default=translator.spirv_loop_guard.DEFAULT_LIMIT, help="maximum loop visits (0 disables)")
128 ap.add_argument("--compact-spirv", action="store_true", help="compact modules with spirv-opt before validation")
129 ap.add_argument("--wave64-emulate", action="store_true")
130 args = ap.parse_args()
131 if args.memory_mib < 1:
132 ap.error("--memory-mib must be positive")
133 src, out = args.inputs.resolve(), args.out.resolve()
134 if out == src or src in out.parents or out in src.parents:
135 ap.error("input and output directories must be separate")
136 os.setpriority(os.PRIO_PROCESS, 0, 19)
137 soft, hard = resource.getrlimit(resource.RLIMIT_AS)
138 bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY)
139 resource.setrlimit(resource.RLIMIT_AS, (bound, hard))
140 versions = []
141 required_tools = ["spirv-as", "spirv-val"]
142 if args.compact_spirv:
143 required_tools.append("spirv-opt")
144 for tool in required_tools:
145 binary = shutil.which(tool)
146 if not binary:
147 ap.error(tool + " is required")
148 versions.append(digest(Path(binary)))
149 settings = [translation_sources_digest(), digest(Path(__file__)), versions, args.wave64_emulate,
150 args.loop_limit, args.descriptor_hash]
151 rows = json.loads((src / "index.json").read_text(encoding="utf-8"))
152 names = []
153 for row in rows:
154 if row["stage"] != "cs":
155 continue
156 filename = row["file"]
157 if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename:
158 ap.error("invalid compute filename in input index")
159 names.append(filename[:-5])
160 if not names or len(set(names)) != len(names):
161 ap.error("expected unique compute filenames in the input index")
162 out.mkdir(parents=True, exist_ok=True)
163 translator.DESCRIPTOR_HASH = args.descriptor_hash
164 translator.LOOP_LIMIT = args.loop_limit
165 translator.WAVE64_EMULATE = args.wave64_emulate
166 return build(src, out, sorted(names), settings, args.jobs, args.compact_spirv)
167
168
169if __name__ == "__main__":
170 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
171 sys.stdout.reconfigure(errors="replace")
172 except AttributeError:
173 pass
174 sys.exit(main())
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md
new file mode 100644
index 000000000..3a875af4b
--- /dev/null
+++ b/scripts/windows-boot/README.md
@@ -0,0 +1,93 @@
1# Native Windows boot harness
2
3`boot.ps1` boots the retail executable under `gta6rt` on native Windows the way the Linux harness
4([`scripts/linux-boot/`](../linux-boot/)) does under Proton: same switches, one game process at a time, a trace of
5every boot and a short digest at the end. Windows PowerShell 5.1 is enough. New here? the repository README
6covers the setup that comes before this.
7
8## Run it
9
10```powershell
11# What would run, with every path checked; launches nothing.
12powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
13
14# A 200 s boot with the default unattended presses (a@45,a@60,a@75,a@90).
15powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
16
17# Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them.
18powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x98f828c,0x78b2818"
19
20# Every parameter.
21Get-Help -Full .\scripts\windows-boot\boot.ps1
22```
23
24Set `LEONIDA_GAME_DIR`, `LEONIDA_SHADERS` (and `GTA6RT`, `LEONIDA_RUNS` if you use other places) once in your
25profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this
26checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`.
27The script refuses an output folder inside the repository.
28
29## What it sets
30
31Only when your shell has not set them already (`-DryRun` prints the final list):
32
33| Variable | Default | Why |
34|---|---|---|
35| `LEONIDA_D3D12` | `vulkan` | the runtime's D3D12-on-Vulkan backend |
36| `LEONIDA_DEVICE_TYPE` | `6` | Series S identity; the runtime answers the title's `ConsoleMode` registry read with it (1920x1080) |
37| `LEONIDA_ARENA_MB` | `2048` | as on Linux |
38| `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit |
39| `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup |
40| `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\pipeline-cache` | one warmed cache shared by every build you boot |
41| `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports |
42| `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps |
43| `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive |
44| `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 |
45| `DISABLE_RTSS_LAYER`, `DISABLE_VULKAN_OBS_CAPTURE` | `1` | keep third-party Vulkan overlay layers out of the process |
46
47Per run, from the parameters: `LEONIDA_SHADERS` (`-Shaders`), `LEONIDA_CAPTURE` (`<out>\cap_<name>`, `-NoCapture`
48turns it off), `LEONIDA_INPUT_SCRIPT` (`-InputScript`, `-NoInput` for none), `LEONIDA_STACKS` (`-Stacks 30,60`: every
49thread's call chain at those seconds, unwound in-process, which works natively where `tools/re/mdmp_unwind.py`
50cannot walk Windows' own DLLs). Other `LEONIDA_*` variables in your shell pass through and are listed.
51
52The command is `gta6rt --run <exe> --game-dir <game> --overlay <out>\overlay --trace <name>.jsonl --trace-d3d12`.
53The overlay takes everything the title writes, so the package folder can stay read-only.
54
55## What you get
56
57In the output folder: `<name>.log` (stderr: `[rt]` lines and the D3D12 trace), `<name>.stdout.log`,
58`<name>.jsonl` (startup trace), `<name>.summary.txt` (`tools/boot_trace.py`), `<name>.digest.txt` and
59`cap_<name>\` (PPM frames plus `index.txt` with the mean RGB of each). The digest:
60
61```
62== boot first: ran its full time limit (200 s), stopped
63shaders: [rt] d3d12: 26586 translated shaders (21 fspx, 0 fspx_compute, 0 fspx_gfx, 52 bvh, 10 exe) from ...
64states: t=0s game=0 session=0 | t=15s game=2 session=0 | t=30s game=3 session=3 | t=60s game=3 session=d
65presents: PresentX ok 1581, failed 0
66input: 13 presses logged
67faults: none
68frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00
69```
70
71`-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The digest holds counts and
72states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game
73and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data").
74
75How to read the states: game state `0x7446510` goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing
76screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively)
77section 2 has the healthy sequence with times and section 3 "which blank do you have".
78
79## One game at a time
80
81The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe`
82runs (another agent's boot, or one started by hand), up to `-LockWaitSeconds` (default an hour, then exit 3). Two
83game processes on one GPU make both runs meaningless and can take the driver down.
84
85## Helper tools (`tools/re/windows/`)
86
87| Tool | What for |
88|---|---|
89| `sym.py IMAGE RVA...` | `gta6rt.exe+0x...` frames to function and line through dbghelp and the build's PDB (the Windows SDK's or Visual Studio's `dbghelp.dll`; `LEONIDA_DBGHELP` names another) |
90| `ripsample.ps1 [-Seconds 20]` | sampling profiler of a running `gta6rt`: per thread, where it spends its time, as module+RVA (`TITLE+0x...` for the title) |
91| `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only |
92
93Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell).
diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1
new file mode 100644
index 000000000..d052a79da
--- /dev/null
+++ b/scripts/windows-boot/boot.ps1
@@ -0,0 +1,456 @@
1<#
2.SYNOPSIS
3 Boot the retail executable under gta6rt on native Windows, one game process at a time, and print a digest.
4
5.DESCRIPTION
6 The native counterpart of scripts/linux-boot/: sets the switches both machines boot with (see
7 docs/re/howto-blank-to-story-load.md, section 1), runs `gta6rt --run` with --trace and --trace-d3d12 for
8 -Seconds, stops it, runs tools/boot_trace.py and prints a short digest: exit, game/session state over time,
9 PresentX count, device-fault lines, capture means. Paste numbers from the digest into a RESULT on the
10 coordination board, never the logs: they can quote the game (AGENTS.md, "No game data").
11
12 Only one game process runs at a time: the script holds a named mutex and also waits while any gta6rt.exe is
13 running (another agent's boot, or one started by hand).
14
15 Every default switch is used only when the variable is not already set in this shell; other LEONIDA_*
16 variables of the shell pass through; -SetEnv overrides all of them. -DryRun lists the result. Outputs go to -OutDir (never inside the repository):
17 <OutDir>\<Name>.log stderr of gta6rt: [rt] diagnostics and [d3d12-trace] lines
18 <OutDir>\<Name>.stdout.log stdout of gta6rt
19 <OutDir>\<Name>.jsonl startup trace (--trace)
20 <OutDir>\<Name>.summary.txt tools/boot_trace.py report
21 <OutDir>\<Name>.digest.txt the digest printed at the end
22 <OutDir>\cap_<Name>\ swapchain captures (PPM) and index.txt with mean RGB per frame
23
24.PARAMETER Name
25 Run name; output files are named after it. Default: boot-<yyyyMMdd-HHmmss>.
26
27.PARAMETER Seconds
28 How long the game runs before it is stopped. Default 180.
29
30.PARAMETER GameDir
31 Your package folder (MicrosoftGame.Config and the .rpf archives as plain files). Default: $env:LEONIDA_GAME_DIR,
32 else game_path.txt beside gta6rt.exe (written by make_game.py's runtime stage).
33
34.PARAMETER Exe
35 game_scarlett_master.exe. Default: $env:LEONIDA_EXE, else <GameDir>\game_scarlett_master.exe.
36
37.PARAMETER Runtime
38 gta6rt.exe (gta6rt_tls_host.dll must sit beside it). Default: $env:GTA6RT, else
39 <repo>\runtime\build\RelWithDebInfo\gta6rt.exe.
40
41.PARAMETER Shaders
42 The translated library, <work>\shaders\spirv. Default: $env:LEONIDA_SHADERS; when neither is given the
43 runtime reads shader_path.txt beside gta6rt.exe.
44
45.PARAMETER OutDir
46 Folder for logs, traces and captures. Default: $env:LEONIDA_RUNS, else $HOME\leonida-runs.
47
48.PARAMETER Overlay
49 Writable folder for everything the title writes (saves, caches). Default <OutDir>\overlay.
50
51.PARAMETER InputScript
52 LEONIDA_INPUT_SCRIPT: timed pad presses, seconds since the pad's first poll (button@seconds, comma-separated;
53 buttons a b x y start back lb rb up down left right). Sets LEONIDA_KEYBOARD_PAD=always. Builds older than
54 main @ 8146ef690 ignore a script longer than 63 characters. Default 'a@45,a@60,a@75,a@90'.
55
56.PARAMETER NoInput
57 No input script (LEONIDA_KEYBOARD_PAD then stays as this shell has it: LEONIDA_KEYBOARD_PAD=1 to play by
58 hand with the window focused).
59
60.PARAMETER Stacks
61 LEONIDA_STACKS: whole seconds at which every thread's call chain is printed to the log, e.g. '30,60'.
62
63.PARAMETER SetEnv
64 Extra or overriding environment variables as a hashtable, when called from a PowerShell prompt:
65 & .\scripts\windows-boot\boot.ps1 -SetEnv @{ LEONIDA_PEEK_SECONDS = '2' }. A value of '' removes the variable.
66
67.PARAMETER EnvPairs
68 Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with
69 powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x75e8eb0".
70 Applied after -SetEnv. KEY= removes the variable for this boot.
71
72.PARAMETER NoCapture
73 Do not set LEONIDA_CAPTURE.
74
75.PARAMETER ExtraArgs
76 More gta6rt arguments, appended after the standard ones.
77
78.PARAMETER Python
79 Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3.
80
81.PARAMETER SummaryLines
82 How many lines of the boot_trace.py report to print. Default 40; 0 prints none.
83
84.PARAMETER LockWaitSeconds
85 How long to wait for another boot to finish. Default 3600.
86
87.PARAMETER DryRun
88 Print the environment and the command line, check the paths, launch nothing.
89
90.PARAMETER DigestOnly
91 Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir).
92
93.EXAMPLE
94 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
95
96.EXAMPLE
97 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv
98
99.EXAMPLE
100 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=0x7446510,0x75e8eb0,0x75e8ea0,0x9844898"
101
102.EXAMPLE
103 powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first
104#>
105[CmdletBinding(PositionalBinding = $false)]
106param(
107 [string]$Name = "",
108 [int]$Seconds = 180,
109 [string]$GameDir = "",
110 [string]$Exe = "",
111 [string]$Runtime = "",
112 [string]$Shaders = "",
113 [string]$OutDir = "",
114 [string]$Overlay = "",
115 [string]$InputScript = "a@45,a@60,a@75,a@90",
116 [string]$Stacks = "",
117 [hashtable]$SetEnv = @{},
118 [switch]$NoCapture,
119 [switch]$NoInput,
120 [string[]]$ExtraArgs = @(),
121 [string]$Python = "",
122 [int]$SummaryLines = 40,
123 [int]$LockWaitSeconds = 3600,
124 [switch]$DryRun,
125 [switch]$DigestOnly,
126 [Parameter(ValueFromRemainingArguments = $true)]
127 [string[]]$EnvPairs = @()
128)
129
130Set-StrictMode -Version 2.0
131$ErrorActionPreference = "Stop"
132
133$RepoRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\.."))
134$ExeName = "game_scarlett_master.exe"
135
136function Get-FirstValue {
137 param([object[]]$Candidates)
138 foreach ($c in $Candidates) { if ($c -and ([string]$c).Trim()) { return ([string]$c).Trim() } }
139 return ""
140}
141
142function Read-SideFile {
143 # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt).
144 param([string]$Path)
145 if (Test-Path -LiteralPath $Path -PathType Leaf) {
146 $line = Get-Content -LiteralPath $Path -TotalCount 1
147 if ($line) { return ([string]$line).Trim() }
148 }
149 return ""
150}
151
152function ConvertTo-ProcessArgument {
153 # Quote one argument the way the MSVC CRT splits a command line (backslashes before a quote are doubled).
154 param([string]$Value)
155 if ($Value -ne "" -and $Value -notmatch '[\s"]') { return $Value }
156 $sb = New-Object System.Text.StringBuilder
157 [void]$sb.Append('"')
158 $slashes = 0
159 foreach ($ch in $Value.ToCharArray()) {
160 if ($ch -eq '\') { $slashes++; continue }
161 if ($ch -eq '"') { [void]$sb.Append('\', 2 * $slashes + 1) } elseif ($slashes) { [void]$sb.Append('\', $slashes) }
162 $slashes = 0
163 [void]$sb.Append($ch)
164 }
165 if ($slashes) { [void]$sb.Append('\', 2 * $slashes) }
166 [void]$sb.Append('"')
167 return $sb.ToString()
168}
169
170function Test-InsideFolder {
171 param([string]$Path, [string]$Folder)
172 $p = [System.IO.Path]::GetFullPath($Path).TrimEnd('\') + '\'
173 $f = [System.IO.Path]::GetFullPath($Folder).TrimEnd('\') + '\'
174 return $p.StartsWith($f, [System.StringComparison]::OrdinalIgnoreCase)
175}
176
177function Resolve-Python {
178 param([string]$Requested)
179 if ($Requested) { return @($Requested) }
180 if (Get-Command python -ErrorAction SilentlyContinue) { return @("python") }
181 if (Get-Command py -ErrorAction SilentlyContinue) { return @("py", "-3") }
182 return @()
183}
184
185# ------------------------------------------------------------------------------------------------ paths
186
187if (-not $Name) { $Name = "boot-" + (Get-Date -Format "yyyyMMdd-HHmmss") }
188if ($NoInput) { $InputScript = "" }
189if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" }
190
191$Runtime = Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe"))
192$RuntimeDir = Split-Path -Parent $Runtime
193$GameDir = Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt")))
194$Exe = Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" }))
195$Shaders = Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS)
196$OutDir = Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs"))
197$OutDir = [System.IO.Path]::GetFullPath($OutDir)
198$Overlay = Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay"))
199$Capture = Join-Path $OutDir ("cap_" + $Name)
200$LogFile = Join-Path $OutDir ($Name + ".log")
201$StdoutFile = Join-Path $OutDir ($Name + ".stdout.log")
202$TraceFile = Join-Path $OutDir ($Name + ".jsonl")
203$SummaryFile = Join-Path $OutDir ($Name + ".summary.txt")
204$DigestFile = Join-Path $OutDir ($Name + ".digest.txt")
205
206$problems = New-Object System.Collections.Generic.List[string]
207if (Test-InsideFolder $OutDir $RepoRoot) { $problems.Add("-OutDir $OutDir is inside the repository; logs and captures must stay outside it") }
208if (-not (Test-Path -LiteralPath $Runtime -PathType Leaf)) { $problems.Add("no gta6rt.exe at $Runtime (build it, or pass -Runtime / set GTA6RT)") }
209elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) {
210 $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)")
211}
212if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") }
213elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) {
214 $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives")
215}
216if (-not $Exe -or -not (Test-Path -LiteralPath $Exe -PathType Leaf)) { $problems.Add("no $ExeName at '$Exe' (pass -Exe)") }
217if ($Shaders) {
218 if (-not (Test-Path -LiteralPath (Join-Path $Shaders "index.json") -PathType Leaf)) {
219 $problems.Add("$Shaders has no index.json: -Shaders is <work>\shaders\spirv after make_game.py --stages check,shaders")
220 } elseif (-not (Test-Path -LiteralPath (Join-Path $Shaders "exe\index.json") -PathType Leaf)) {
221 Write-Warning "$Shaders has no exe\index.json: the title's 10 embedded shaders are missing and frames cannot draw (JOIN.md, 'The executable trap')"
222 }
223} elseif (-not (Read-SideFile (Join-Path $RuntimeDir "shader_path.txt"))) {
224 $problems.Add("no shader library: pass -Shaders <work>\shaders\spirv or set LEONIDA_SHADERS")
225}
226
227# ------------------------------------------------------------------------------------------ environment
228
229# Defaults: used only when this shell has not set the variable. They match the Linux harness (scripts/linux-boot/).
230$defaults = [ordered]@{
231 LEONIDA_D3D12 = "vulkan"
232 LEONIDA_DEVICE_TYPE = "6" # Series S identity; the runtime answers the ConsoleMode registry read with it
233 LEONIDA_ARENA_MB = "2048"
234 LEONIDA_PIPELINE_CACHE_BYTES = "4294967296"
235 LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1"
236 LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache")
237 LEONIDA_PEEK = "0x7446510,0x98f828c" # game state, session state (low dword)
238 LEONIDA_PEEK_SECONDS = "5"
239 LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints)
240 LEONIDA_CAPTURE_EVERY = "60"
241 LEONIDA_CAPTURE_LIMIT = "40"
242 DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off
243 DISABLE_VULKAN_OBS_CAPTURE = "1"
244}
245if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" }
246# Per-run values: always this script's (from its parameters), whatever the shell has.
247$perRun = [ordered]@{
248 LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture })
249 LEONIDA_INPUT_SCRIPT = $InputScript
250}
251if ($Shaders) { $perRun["LEONIDA_SHADERS"] = $Shaders }
252if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks }
253
254$bootEnv = [ordered]@{}
255foreach ($k in $defaults.Keys) {
256 $cur = [Environment]::GetEnvironmentVariable($k)
257 if ($cur) { $bootEnv[$k] = $cur } else { $bootEnv[$k] = $defaults[$k] }
258}
259foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] }
260# Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below.
261foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) {
262 if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value }
263}
264foreach ($k in $SetEnv.Keys) { $bootEnv[[string]$k] = [string]$SetEnv[$k] }
265foreach ($pair in $EnvPairs) {
266 if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" }
267 $bootEnv[$Matches[1]] = $Matches[2]
268}
269if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] }
270
271$gameArgs = @("--run", $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs
272$argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " "
273
274if (-not $DigestOnly) {
275 Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot"
276 Write-Output "[boot] gta6rt $Runtime"
277 Write-Output "[boot] out $OutDir"
278 foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } }
279 Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine"
280}
281
282if ($DigestOnly) {
283 if (-not (Test-Path -LiteralPath $LogFile)) { Write-Output "[boot] no $LogFile to digest"; exit 2 }
284 $problems.Clear()
285}
286if ($problems.Count) {
287 foreach ($p in $problems) { Write-Output "[boot] problem: $p" }
288 if (-not $DryRun) { exit 2 }
289}
290if ($DryRun) { Write-Output "[boot] dry run: nothing launched"; exit $(if ($problems.Count) { 2 } else { 0 }) }
291
292$verdict = "digest of an earlier run (-DigestOnly)"
293$exitCode = 0
294if (-not $DigestOnly) {
295
296 # --------------------------------------------------------------------------------------------- the lock
297
298 $mutex = New-Object System.Threading.Mutex($false, "Local\LeonidaGameBoot")
299 $owned = $false
300 $saved = @{}
301 $exitCode = 0
302 try {
303 $deadline = (Get-Date).AddSeconds($LockWaitSeconds)
304 $said = $false
305 while (-not $owned) {
306 try { $owned = $mutex.WaitOne(5000) } catch [System.Threading.AbandonedMutexException] { $owned = $true }
307 if ($owned -and (Get-Process -Name gta6rt -ErrorAction SilentlyContinue)) {
308 # A game started by hand or by another script that does not take this lock: wait for it too.
309 $mutex.ReleaseMutex(); $owned = $false; Start-Sleep -Seconds 5
310 }
311 if (-not $owned) {
312 if (-not $said) { Write-Output "[boot] waiting: another game process is running (one at a time)"; $said = $true }
313 if ((Get-Date) -gt $deadline) { Write-Output "[boot] gave up waiting after $LockWaitSeconds s"; exit 3 }
314 }
315 }
316
317 foreach ($d in @($OutDir, $Overlay)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
318 if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) {
319 New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null
320 }
321 if ($bootEnv["LEONIDA_CAPTURE"]) {
322 # A capture folder reused by the same -Name: drop the earlier run's frames and index, nothing else.
323 New-Item -ItemType Directory -Force -Path $Capture | Out-Null
324 Get-ChildItem -LiteralPath $Capture -File | Where-Object { $_.Name -like "frame_*.ppm" -or $_.Name -like "*index.txt" } |
325 Remove-Item -Force -Confirm:$false
326 }
327 foreach ($f in @($LogFile, $StdoutFile, $TraceFile, $SummaryFile, $DigestFile)) {
328 if (Test-Path -LiteralPath $f) { Remove-Item -LiteralPath $f -Force -Confirm:$false }
329 }
330
331 foreach ($k in $bootEnv.Keys) {
332 $saved[$k] = [Environment]::GetEnvironmentVariable($k)
333 $v = $bootEnv[$k]; if ($v -eq "") { $v = $null }
334 [Environment]::SetEnvironmentVariable($k, $v)
335 }
336
337 # ------------------------------------------------------------------------------------------- the boot
338 $started = Get-Date
339 $proc = Start-Process -FilePath $Runtime -ArgumentList $argLine -WorkingDirectory $RepoRoot -NoNewWindow -PassThru `
340 -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile
341 $handle = $proc.Handle # keeps the exit code readable after the process ends
342 $stopped = $false
343 if (-not $proc.WaitForExit($Seconds * 1000)) {
344 $stopped = $true
345 try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { }
346 [void]$proc.WaitForExit(20000)
347 }
348 $ran = [int]((Get-Date) - $started).TotalSeconds
349 $rc = $null
350 try { $rc = $proc.ExitCode } catch { }
351 if ($stopped) { $verdict = "ran its full time limit ($ran s), stopped"; $exitCode = 0 }
352 elseif ($rc -eq $null) { $verdict = "exited by itself after $ran s, exit code unknown"; $exitCode = 1 }
353 else { $verdict = ("exited by itself after {0} s, exit code {1} (0x{2:x8})" -f $ran, $rc, ([int64]$rc -band 0xffffffffL)); $exitCode = [int]$rc }
354 } finally {
355 foreach ($k in $saved.Keys) { [Environment]::SetEnvironmentVariable($k, $saved[$k]) }
356 if ($owned) { $mutex.ReleaseMutex() }
357 $mutex.Dispose()
358 }
359}
360
361# -------------------------------------------------------------------------------------------- the digest
362
363$py = @(Resolve-Python $Python)
364if ($py.Count) {
365 $pyArgs = @()
366 if ($py.Count -gt 1) { $pyArgs += $py[1..($py.Count - 1)] }
367 $pyArgs += @("-I", (Join-Path $RepoRoot "tools\boot_trace.py"), $TraceFile, "--d3d12", $LogFile)
368 # Windows PowerShell 5.1 turns a native program's stderr into error records; with "Stop" that would end the script.
369 $ErrorActionPreference = "Continue"
370 & $py[0] @pyArgs 2>&1 | ForEach-Object { "$_" } | Out-File -FilePath $SummaryFile -Encoding utf8
371 $ErrorActionPreference = "Stop"
372} else {
373 "no python found for tools/boot_trace.py" | Out-File -FilePath $SummaryFile -Encoding utf8
374}
375
376$peekRx = [regex]'\[rt\] peek t=(\d+)s:(.*)$'
377$valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)'
378$states = New-Object System.Collections.Generic.List[string]
379$lastPeek = ""; $prevPair = ""
380$presentOk = 0; $presentFailed = 0; $presses = 0
381$shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string]
382$wrapped = 0
383if (Test-Path -LiteralPath $LogFile) {
384 foreach ($line in [System.IO.File]::ReadLines($LogFile)) {
385 if ($line.Contains("XboxPresentation::PresentX")) {
386 if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ }
387 continue
388 }
389 if ($line.Contains("[rt] peek t=")) {
390 $m = $peekRx.Match($line)
391 if ($m.Success) {
392 $lastPeek = $line.Substring($line.IndexOf("[rt] peek"))
393 $game = "?"; $session = "?"
394 foreach ($v in $valRx.Matches($m.Groups[2].Value)) {
395 $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value
396 if ($rva -eq "7446510") { $game = $val }
397 elseif ($rva -eq "98f828c" -and $val -ne "?") {
398 $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword
399 $session = $(if ($low) { $low } else { "0" })
400 }
401 }
402 $pair = "game=$game session=$session"
403 if ($pair -ne $prevPair) { $states.Add("t=$($m.Groups[1].Value)s $pair"); $prevPair = $pair }
404 }
405 continue
406 }
407 if ($line.Contains("[rt] gameinput: press ")) {
408 # Buttons only: with the keyboard pad, mouse movement is logged as right-stick presses (rsup, rsdown...).
409 if ($line -notmatch 'gameinput: press [lr]s') { $presses++ }
410 continue
411 }
412 if ($line.Contains("[rt] device-fault:") -and -not $line.Contains("device-fault: enabled")) { if ($faults.Count -lt 8) { $faults.Add($line.Trim()) }; continue }
413 if ($line.Contains("VK_ERROR_DEVICE_LOST") -and $faults.Count -lt 8) { $faults.Add($line.Trim()); continue }
414 if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() }
415 if ($line.Contains("wrapped V#")) { $wrapped++ }
416 }
417}
418
419$capText = "no captures"
420$capIndex = Join-Path $Capture "index.txt"
421if (Test-Path -LiteralPath $capIndex) {
422 $frames = 0; $nonBlack = 0; $last = ""; $maxSum = -1.0; $maxText = ""
423 $meanRx = [regex]'mean rgb ([0-9.]+) ([0-9.]+) ([0-9.]+)'
424 foreach ($line in [System.IO.File]::ReadLines($capIndex)) {
425 $m = $meanRx.Match($line)
426 if (-not $m.Success) { continue }
427 $frames++
428 $r = [double]::Parse($m.Groups[1].Value, [Globalization.CultureInfo]::InvariantCulture)
429 $g = [double]::Parse($m.Groups[2].Value, [Globalization.CultureInfo]::InvariantCulture)
430 $b = [double]::Parse($m.Groups[3].Value, [Globalization.CultureInfo]::InvariantCulture)
431 $sum = $r + $g + $b
432 if ($sum -gt 0) { $nonBlack++ }
433 $last = "$($m.Groups[1].Value) $($m.Groups[2].Value) $($m.Groups[3].Value)"
434 if ($sum -gt $maxSum) { $maxSum = $sum; $maxText = $last }
435 }
436 $capText = "$frames captured, $nonBlack non-black; last mean rgb $last; brightest $maxText"
437}
438
439$digest = New-Object System.Collections.Generic.List[string]
440$digest.Add("== boot ${Name}: $verdict")
441$digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated-shaders line (Vulkan device not reached?)' })")
442$digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })")
443$digest.Add("presents: PresentX ok $presentOk, failed $presentFailed")
444$digest.Add("input: $presses presses logged")
445$digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })")
446foreach ($f in $faults) { $digest.Add(" $f") }
447if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") }
448$digest.Add("frames: $capText")
449$digest.Add("files: $LogFile, $TraceFile, $SummaryFile")
450$digest | Out-File -FilePath $DigestFile -Encoding utf8
451$digest
452if ($SummaryLines -gt 0 -and (Test-Path -LiteralPath $SummaryFile)) {
453 Write-Output "-- boot_trace.py (first $SummaryLines lines of $SummaryFile)"
454 Get-Content -LiteralPath $SummaryFile -TotalCount $SummaryLines
455}
456exit $exitCode