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:
authorBloh09 <104168236+Bloh09@users.noreply.github.com>2026-11-28 19:40:09 -0800
committerBloh09 <104168236+Bloh09@users.noreply.github.com>2026-11-28 19:40:09 -0800
commit3fbfcc6f8d824f3900b3b473e856ad4373f39bd8 (patch)
tree8ebf2f30d6311c4e72e948c5da50fc7139ff67ad /scripts
parentf6cbdb93854dc9b9b04252ba48925c846b5489ad (diff)
parentb6bf3aa0be76d3b90eef9a12e1698f5c1b3b7816 (diff)
Merge upstream/main into fix/ci-main-red-tests
Resolved conflicts in bench_translate.py, export_old_pr_manifest.py, pc_prompt_glyphs.py and xbox_prompt_glyphs.py by taking main's errors=replace guards (#2590). Dropped CI-STDOUT-GUARD-NEW-TOOLS.
Diffstat (limited to 'scripts')
-rw-r--r--scripts/bench_translate.py5
-rw-r--r--scripts/build_runtime.ps12
-rw-r--r--scripts/check_compute_journal_overlay.py47
-rw-r--r--scripts/corpus_watch.py55
-rw-r--r--scripts/export_old_pr_manifest.py5
-rw-r--r--scripts/run_gpu_tests.py10
-rw-r--r--scripts/run_guest_scene.py11
-rw-r--r--scripts/run_wine_tests.py7
-rw-r--r--scripts/vs_layout_census.py50
-rw-r--r--scripts/windows-boot/README.md12
-rw-r--r--scripts/windows-boot/boot.ps133
-rw-r--r--scripts/windows-boot/crash_monitor.cpp204
-rw-r--r--scripts/windows-boot/test_crash_monitor.py133
13 files changed, 520 insertions, 54 deletions
diff --git a/scripts/bench_translate.py b/scripts/bench_translate.py
index f6000a82c..6c60b3493 100644
--- a/scripts/bench_translate.py
+++ b/scripts/bench_translate.py
@@ -306,8 +306,5 @@ def main(argv=None):
306 306
307 307
308if __name__ == "__main__": 308if __name__ == "__main__":
309 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode 309 sys.stdout.reconfigure(errors="replace")
310 sys.stdout.reconfigure(errors="replace")
311 except (AttributeError, ValueError, OSError):
312 pass
313 sys.exit(main()) 310 sys.exit(main())
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index d386ba052..a1d7151b5 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -86,7 +86,7 @@ $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\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_queue.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } 89 $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_queue.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp", "shims\appnotify.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 = @"
diff --git a/scripts/check_compute_journal_overlay.py b/scripts/check_compute_journal_overlay.py
index 4ea23f84c..1ef6eb501 100644
--- a/scripts/check_compute_journal_overlay.py
+++ b/scripts/check_compute_journal_overlay.py
@@ -25,6 +25,7 @@ def entries(cache):
25 d = cache / "pipeline_cache.d" 25 d = cache / "pipeline_cache.d"
26 if not d.exists(): 26 if not d.exists():
27 return {} 27 return {}
28 require(d.is_dir(), "pipeline_cache.d is not a directory")
28 out = {} 29 out = {}
29 for p in d.iterdir(): 30 for p in d.iterdir():
30 require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and 31 require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and
@@ -45,7 +46,10 @@ def run(exe, root, device, strict):
45 if label == "local-B": 46 if label == "local-B":
46 # Bring only B into a fresh process; no session or shared cache crosses this boundary. 47 # Bring only B into a fresh process; no session or shared cache crosses this boundary.
47 (cache / "pipeline_cache.d").mkdir() 48 (cache / "pipeline_cache.d").mkdir()
48 src, = (root / "new-B" / "pipeline_cache.d").iterdir() 49 b_dir = root / "new-B" / "pipeline_cache.d"
50 srcs = list(b_dir.iterdir()) if b_dir.is_dir() else []
51 require(len(srcs) == 1 and srcs[0].is_file(), "new-B did not leave one journal file to copy")
52 src = srcs[0]
49 shutil.copy2(src, cache / "pipeline_cache.d" / src.name) 53 shutil.copy2(src, cache / "pipeline_cache.d" / src.name)
50 local_before = entries(cache) 54 local_before = entries(cache)
51 env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} 55 env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")}
@@ -57,7 +61,8 @@ def run(exe, root, device, strict):
57 if label != "cold": 61 if label != "cold":
58 env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d") 62 env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d")
59 p = subprocess.run([str(exe)] + (["--second-shader"] if second else []), 63 p = subprocess.run([str(exe)] + (["--second-shader"] if second else []),
60 stdin=subprocess.DEVNULL, capture_output=True, text=True, errors="replace", 64 stdin=subprocess.DEVNULL, capture_output=True, text=True,
65 encoding="utf-8", errors="replace",
61 cwd=cache, env=env, timeout=60) 66 cwd=cache, env=env, timeout=60)
62 if p.returncode == 77: 67 if p.returncode == 77:
63 print("SKIP: the authored compute fixture is unsupported on this device") 68 print("SKIP: the authored compute fixture is unsupported on this device")
@@ -77,7 +82,11 @@ def run(exe, root, device, strict):
77 local = entries(cache) 82 local = entries(cache)
78 if label == "cold": 83 if label == "cold":
79 require(len(local) == 1, "cold A was not journaled") 84 require(len(local) == 1, "cold A was not journaled")
80 source, = (seed / "pipeline_cache.d").iterdir() 85 seed_dir = seed / "pipeline_cache.d"
86 seed_entries = list(seed_dir.iterdir()) if seed_dir.is_dir() else []
87 require(len(seed_entries) == 1 and seed_entries[0].is_file(),
88 "cold A did not leave one seed journal file")
89 source = seed_entries[0]
81 # Make an erroneous hourly LRU touch observable without making the probe depend on system time. 90 # Make an erroneous hourly LRU touch observable without making the probe depend on system time.
82 old = time.time_ns() - 48 * 3600 * 10**9 91 old = time.time_ns() - 48 * 3600 * 10**9
83 os.utime(source, ns=(old, old)) 92 os.utime(source, ns=(old, old))
@@ -95,17 +104,31 @@ def run(exe, root, device, strict):
95 return 0 104 return 0
96 105
97 106
107def main(argv=None) -> int:
108 parser = argparse.ArgumentParser(description=__doc__)
109 parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe")
110 parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector")
111 parser.add_argument("--require-hit", action="store_true")
112 args = parser.parse_args(argv)
113 try:
114 exe = args.executable.resolve(strict=True)
115 except OSError as exc:
116 print(f"ERROR: {exc}", file=sys.stderr)
117 return 2
118 if not exe.is_file() or exe.name.lower() not in ("d3d12_compute_journal_test.exe", "d3d12_compute_journal_test"):
119 print(f"ERROR: expected the compute test executable, not {exe.name}", file=sys.stderr)
120 return 2
121 try:
122 with tempfile.TemporaryDirectory(prefix="leonida-authored-journal-") as tmp:
123 return run(exe, Path(tmp), args.device, args.require_hit)
124 except (RuntimeError, subprocess.TimeoutExpired, OSError) as exc:
125 print(f"ERROR: {exc}", file=sys.stderr)
126 return 1
127
128
98if __name__ == "__main__": 129if __name__ == "__main__":
99 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode 130 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
100 sys.stdout.reconfigure(errors="replace") 131 sys.stdout.reconfigure(errors="replace")
101 except (AttributeError, ValueError, OSError): 132 except (AttributeError, ValueError, OSError):
102 pass 133 pass
103 parser = argparse.ArgumentParser(description=__doc__) 134 raise SystemExit(main())
104 parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe")
105 parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector")
106 parser.add_argument("--require-hit", action="store_true")
107 args = parser.parse_args()
108 exe = args.executable.resolve(strict=True)
109 require(exe.name.lower() == "d3d12_compute_journal_test.exe", "expected the compute test, not the game")
110 with tempfile.TemporaryDirectory(prefix="leonida-authored-journal-") as tmp:
111 raise SystemExit(run(exe, Path(tmp), args.device, args.require_hit))
diff --git a/scripts/corpus_watch.py b/scripts/corpus_watch.py
index a09bf8ab9..fdc48b7aa 100644
--- a/scripts/corpus_watch.py
+++ b/scripts/corpus_watch.py
@@ -18,6 +18,7 @@ Standard library only; all text writes name their line ending.
18""" 18"""
19import argparse 19import argparse
20import json 20import json
21import math
21import os 22import os
22import shutil 23import shutil
23import subprocess 24import subprocess
@@ -47,16 +48,20 @@ def corpus_counts(work):
47 dxbc = old_dxbc 48 dxbc = old_dxbc
48 spirv_path = os.path.join(work, "spirv", "index.json") 49 spirv_path = os.path.join(work, "spirv", "index.json")
49 50
50 with open(dxbc, encoding="utf-8") as f: 51 with open(dxbc, encoding="utf-8-sig") as f:
51 carved = json.load(f) 52 carved = json.load(f)
53 if not isinstance(carved, (list, dict)):
54 raise ValueError(f"{dxbc}: expected a JSON list or object")
52 entries = carved if isinstance(carved, list) else list(carved.values()) 55 entries = carved if isinstance(carved, list) else list(carved.values())
53 56
54 per_stage = {} 57 per_stage = {}
55 validated = 0 58 validated = 0
56 spirv_entries = 0 59 spirv_entries = 0
57 if os.path.isfile(spirv_path): 60 if os.path.isfile(spirv_path):
58 with open(spirv_path, encoding="utf-8") as f: 61 with open(spirv_path, encoding="utf-8-sig") as f:
59 spirv = json.load(f) 62 spirv = json.load(f)
63 if not isinstance(spirv, dict):
64 raise ValueError(f"{spirv_path}: expected a JSON object")
60 spirv_entries = len(spirv) 65 spirv_entries = len(spirv)
61 for meta in spirv.values(): 66 for meta in spirv.values():
62 if isinstance(meta, dict) and "error" not in meta: 67 if isinstance(meta, dict) and "error" not in meta:
@@ -71,20 +76,29 @@ def corpus_counts(work):
71 "validated": validated, "per_stage": per_stage} 76 "validated": validated, "per_stage": per_stage}
72 77
73 78
74def outputs_collide(work, report, results, log): 79def outputs_collide(work, report, results, log, game=None, out=None):
75 """Refuse an output that names an input or another output.""" 80 """Refuse an output that names an input or another output."""
76 outputs = [p for p in (report, results, log) if p] 81 outputs = [p for p in (report, results, log, out) if p]
77 for i, first in enumerate(outputs): 82 for i, first in enumerate(outputs):
78 for second in outputs[i + 1:]: 83 for second in outputs[i + 1:]:
79 if same_report_path(first, second): 84 if same_report_path(first, second):
80 return True 85 return True
81 for out in outputs: 86 inputs = [p for p in (work, game) if p]
82 if same_report_path(out, work): 87 if work:
83 return True 88 inputs.extend([
89 os.path.join(work, "shaders", "dxbc", "index.json"),
90 os.path.join(work, "shaders", "spirv", "index.json"),
91 os.path.join(work, "dxbc", "index.json"),
92 os.path.join(work, "spirv", "index.json"),
93 ])
94 for target_out in outputs:
95 for inp in inputs:
96 if same_report_path(target_out, inp):
97 return True
84 return False 98 return False
85 99
86 100
87def main(): 101def main(argv=None):
88 ap = argparse.ArgumentParser(description=__doc__) 102 ap = argparse.ArgumentParser(description=__doc__)
89 ap.add_argument("--game", required=True, help="your package folder") 103 ap.add_argument("--game", required=True, help="your package folder")
90 ap.add_argument("--work", required=True, help="work folder (outside the repo)") 104 ap.add_argument("--work", required=True, help="work folder (outside the repo)")
@@ -98,9 +112,16 @@ def main():
98 ap.add_argument("--pull", action="store_true", help="git pull --ff-only before each run") 112 ap.add_argument("--pull", action="store_true", help="git pull --ff-only before each run")
99 ap.add_argument("--github", action="store_true", help="also refresh dashboard PR/CI panels") 113 ap.add_argument("--github", action="store_true", help="also refresh dashboard PR/CI panels")
100 ap.add_argument("--jobs", type=int) 114 ap.add_argument("--jobs", type=int)
101 a = ap.parse_args() 115 a = ap.parse_args(argv)
116 if not math.isfinite(a.interval) or a.interval < 0:
117 ap.error("--interval must be a finite nonnegative number")
102 if not a.once and a.interval <= 0: 118 if not a.once and a.interval <= 0:
103 ap.error("use --once or --interval HOURS") 119 ap.error("use --once or --interval HOURS")
120 if a.jobs is not None and a.jobs < 1:
121 ap.error("--jobs must be at least 1")
122 for flag, val in (("--results", a.results), ("--log", a.log)):
123 if val and (os.path.isdir(val) or val.endswith(("/", "\\"))):
124 ap.error(f"{flag} must name a file, not a directory: {val}")
104 125
105 repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 126 repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
106 log_path = a.log 127 log_path = a.log
@@ -112,7 +133,7 @@ def main():
112 with open(log_path, "a", encoding="utf-8", newline="\n") as f: 133 with open(log_path, "a", encoding="utf-8", newline="\n") as f:
113 f.write(line + "\n") 134 f.write(line + "\n")
114 135
115 if outputs_collide(a.work, a.report, a.results, log_path): 136 if outputs_collide(a.work, a.report, a.results, log_path, game=a.game, out=a.out):
116 ap.error("an output names the work folder or another output") 137 ap.error("an output names the work folder or another output")
117 138
118 for tool in ("llvm-mc", "spirv-val", "git"): 139 for tool in ("llvm-mc", "spirv-val", "git"):
@@ -123,13 +144,19 @@ def main():
123 probe = subprocess.run( 144 probe = subprocess.run(
124 ["llvm-mc", "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1013", 145 ["llvm-mc", "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1013",
125 "-filetype=obj", "-o", os.devnull], 146 "-filetype=obj", "-o", os.devnull],
126 input="s_nop 0\n", text=True, capture_output=True) 147 input="s_nop 0\n", text=True, encoding="utf-8", errors="replace", capture_output=True)
127 if probe.returncode != 0: 148 if probe.returncode != 0:
128 ap.error("llvm-mc cannot assemble gfx1013 (AMDGPU target missing)") 149 ap.error("llvm-mc cannot assemble gfx1013 (AMDGPU target missing)")
129 150
151 for file_out in (a.results, log_path):
152 if file_out:
153 parent = os.path.dirname(os.path.abspath(file_out))
154 if parent:
155 os.makedirs(parent, exist_ok=True)
156
130 def run(cmd, timeout): 157 def run(cmd, timeout):
131 return subprocess.run(cmd, cwd=repo, text=True, stdout=subprocess.PIPE, 158 return subprocess.run(cmd, cwd=repo, text=True, encoding="utf-8", errors="replace",
132 stderr=subprocess.STDOUT, timeout=timeout) 159 stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
133 160
134 def run_once(): 161 def run_once():
135 if a.pull: 162 if a.pull:
@@ -170,7 +197,7 @@ def main():
170 f"validated={counts['validated']}") 197 f"validated={counts['validated']}")
171 for stage, (nc, nv) in sorted(counts["per_stage"].items()): 198 for stage, (nc, nv) in sorted(counts["per_stage"].items()):
172 log(f" {stage}: {nv}/{nc} validated") 199 log(f" {stage}: {nv}/{nc} validated")
173 with open(a.results, encoding="utf-8") as f: 200 with open(a.results, encoding="utf-8-sig") as f:
174 previous = [json.loads(x) for x in f if x.strip()] 201 previous = [json.loads(x) for x in f if x.strip()]
175 if len(previous) >= 2: 202 if len(previous) >= 2:
176 before = previous[-2].get("counts") or {} 203 before = previous[-2].get("counts") or {}
diff --git a/scripts/export_old_pr_manifest.py b/scripts/export_old_pr_manifest.py
index a83b12822..7198e6b3d 100644
--- a/scripts/export_old_pr_manifest.py
+++ b/scripts/export_old_pr_manifest.py
@@ -120,8 +120,5 @@ def main(argv=None) -> int:
120 120
121 121
122if __name__ == "__main__": 122if __name__ == "__main__":
123 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode 123 sys.stdout.reconfigure(errors="replace")
124 sys.stdout.reconfigure(errors="replace")
125 except (AttributeError, ValueError, OSError):
126 pass
127 sys.exit(main()) 124 sys.exit(main())
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 3112df46d..97fba6ee3 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -1023,11 +1023,11 @@ def run_suite(a, work: str) -> int:
1023 for fname in asm_files: 1023 for fname in asm_files:
1024 name = os.path.splitext(fname)[0] 1024 name = os.path.splitext(fname)[0]
1025 spv = os.path.join(spirv_dir, f"{name}.spv") 1025 spv = os.path.join(spirv_dir, f"{name}.spv")
1026 if name == "ps_ij_computed" and (bary_fallback() or f16_interp_fallback()): 1026 if name == "ps_ij_computed" and bary_fallback():
1027 # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair, so there 1027 # Before the .spv check: under --bary-fallback the translator refuses a computed I/J pair, so there
1028 # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). 1028 # is no .spv (--f16-interp-fallback alone lowers it via DerivativeControl + BaryCoordKHR).
1029 results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs: " 1029 results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; "
1030 "no --bary-fallback / --f16-interp-fallback)")) 1030 "unsupported under --bary-fallback)"))
1031 continue 1031 continue
1032 if not os.path.isfile(spv): 1032 if not os.path.isfile(spv):
1033 results.append((name, False, "missing .spv (translation failed)")) 1033 results.append((name, False, "missing .spv (translation failed)"))
diff --git a/scripts/run_guest_scene.py b/scripts/run_guest_scene.py
index 55f770c8b..0753f2aa7 100644
--- a/scripts/run_guest_scene.py
+++ b/scripts/run_guest_scene.py
@@ -4,6 +4,8 @@
4 python -I scripts/run_guest_scene.py --loader L --guest G --shaders ROOT [--out DIR] [--wine WINE] 4 python -I scripts/run_guest_scene.py --loader L --guest G --shaders ROOT [--out DIR] [--wine WINE]
5 [--play-audio] [--negative-controls] 5 [--play-audio] [--negative-controls]
6 6
7Outside Windows, --wine defaults to $WINE (e.g. UMU-Proton's files/bin/wine) and one of the two is required.
8
7Each run renders offscreen in a fresh process and write overlay. Without --out the runs go to a temporary folder that is removed 9Each run renders offscreen in a fresh process and write overlay. Without --out the runs go to a temporary folder that is removed
8afterwards. The summary is printed first, and on failure the last run's log tails are printed too. Audio stays offline 10afterwards. The summary is printed first, and on failure the last run's log tails are printed too. Audio stays offline
9unless --play-audio sets LEONIDA_SCENE_AUDIO=winmm. The guest then plays the pulse synchronously with PlaySoundW. 11unless --play-audio sets LEONIDA_SCENE_AUDIO=winmm. The guest then plays the pulse synchronously with PlaySoundW.
@@ -325,13 +327,14 @@ def parse_args() -> argparse.Namespace:
325 ap.add_argument("--guest", type=Path, required=True) 327 ap.add_argument("--guest", type=Path, required=True)
326 ap.add_argument("--shaders", type=Path, required=True, help="shader root containing spirv/") 328 ap.add_argument("--shaders", type=Path, required=True, help="shader root containing spirv/")
327 ap.add_argument("--out", type=Path, help="new or empty folder (default: a temporary folder, removed afterwards)") 329 ap.add_argument("--out", type=Path, help="new or empty folder (default: a temporary folder, removed afterwards)")
328 ap.add_argument("--wine", help="run the loader through this Wine binary") 330 ap.add_argument("--wine", default=(os.environ.get("WINE") or None) if os.name != "nt" else None,
331 help="run the loader through this Wine binary (default: $WINE outside Windows)")
329 ap.add_argument("--wine-arg", action="append", default=[], help="argument to the Wine launcher (repeatable)") 332 ap.add_argument("--wine-arg", action="append", default=[], help="argument to the Wine launcher (repeatable)")
330 ap.add_argument("--play-audio", action="store_true", help="LEONIDA_SCENE_AUDIO=winmm instead of offline") 333 ap.add_argument("--play-audio", action="store_true", help="LEONIDA_SCENE_AUDIO=winmm instead of offline")
331 ap.add_argument("--negative-controls", action="store_true", help="also run a bad scene.bin and checkpoint") 334 ap.add_argument("--negative-controls", action="store_true", help="also run a bad scene.bin and checkpoint")
332 args = ap.parse_args() 335 args = ap.parse_args()
333 if args.wine_arg and not args.wine: 336 if args.wine_arg and not args.wine:
334 ap.error("--wine-arg requires --wine") 337 ap.error("--wine-arg requires --wine" if os.name == "nt" else "--wine-arg requires --wine or WINE")
335 for name in ("loader", "guest"): 338 for name in ("loader", "guest"):
336 if not getattr(args, name).is_file(): 339 if not getattr(args, name).is_file():
337 ap.error(f"--{name}: no such file") 340 ap.error(f"--{name}: no such file")
@@ -340,10 +343,10 @@ def parse_args() -> argparse.Namespace:
340 if args.wine: 343 if args.wine:
341 found = args.wine if Path(args.wine).is_file() else shutil.which(args.wine) 344 found = args.wine if Path(args.wine).is_file() else shutil.which(args.wine)
342 if not found: 345 if not found:
343 ap.error("--wine: not found") 346 ap.error(f"--wine: not found: {args.wine}")
344 args.wine = str(Path(found).resolve()) 347 args.wine = str(Path(found).resolve())
345 elif os.name != "nt": 348 elif os.name != "nt":
346 ap.error("--wine is required outside Windows") 349 ap.error("--wine (or WINE) is required outside Windows")
347 if args.out and args.out.exists() and (not args.out.is_dir() or any(args.out.iterdir())): 350 if args.out and args.out.exists() and (not args.out.is_dir() or any(args.out.iterdir())):
348 ap.error("--out must be new or an empty folder") 351 ap.error("--out must be new or an empty folder")
349 args.loader, args.guest, args.shaders = args.loader.resolve(), args.guest.resolve(), args.shaders.resolve() 352 args.loader, args.guest, args.shaders = args.loader.resolve(), args.guest.resolve(), args.shaders.resolve()
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index e43f62016..fa98fad31 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -104,7 +104,8 @@ class DriveMap:
104 <root>/runtime/build/generated/x.spv. The drive is a dosdevices link to a scratch folder holding a/Leonida/Leonida 104 <root>/runtime/build/generated/x.spv. The drive is a dosdevices link to a scratch folder holding a/Leonida/Leonida
105 as a link to the root. If the Windows checkout is the drive root itself, the drive links directly to the 105 as a link to the root. If the Windows checkout is the drive root itself, the drive links directly to the
106 Linux checkout. Temporary links and scratch folders are removed afterwards. A drive the prefix already has 106 Linux checkout. Temporary links and scratch folders are removed afterwards. A drive the prefix already has
107 (c:, z:, or one set up by hand) is left alone, and so is a root without an absolute drive path. 107 (c:, z:, or one set up by hand) is left alone, and so is a root without an absolute drive path. A prefix that
108 cannot take the link (read-only, permission denied) also leaves the drive unmapped; the note says why.
108 """ 109 """
109 110
110 def __init__(self, windows_root: str, root: str, prefix: str): 111 def __init__(self, windows_root: str, root: str, prefix: str):
@@ -141,6 +142,10 @@ class DriveMap:
141 self.note = already_set 142 self.note = already_set
142 return self 143 return self
143 self.link = link 144 self.link = link
145 except OSError as e:
146 # A read-only or otherwise unwritable prefix: run the tests without the drive, and say so.
147 self.note = f"cannot map drive {drive}: {e.strerror or e}: the run goes on without it"
148 return self
144 finally: 149 finally:
145 # __exit__ only runs after a successful __enter__. 150 # __exit__ only runs after a successful __enter__.
146 if self.link is None and self.scratch is not None: 151 if self.link is None and self.scratch is not None:
diff --git a/scripts/vs_layout_census.py b/scripts/vs_layout_census.py
index 1d7174e77..8ba9b8a14 100644
--- a/scripts/vs_layout_census.py
+++ b/scripts/vs_layout_census.py
@@ -23,13 +23,16 @@ import json
23import os 23import os
24import re 24import re
25import sys 25import sys
26import tempfile
26from collections import Counter, defaultdict 27from collections import Counter, defaultdict
27 28
28ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 29ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29sys.path.insert(0, os.path.join(ROOT, "tools")) 30sys.path.insert(0, os.path.join(ROOT, "tools"))
30sys.path.insert(0, os.path.join(ROOT, "scripts")) 31sys.path.insert(0, os.path.join(ROOT, "scripts"))
32from file_mode import published_mode # noqa: E402
31import fssm_unpack # noqa: E402 33import fssm_unpack # noqa: E402
32import pal_stages # noqa: E402 34import pal_stages # noqa: E402
35import replace_retry # noqa: E402
33import shader_disasm # noqa: E402 36import shader_disasm # noqa: E402
34from report_paths import same_report_path # noqa: E402 37from report_paths import same_report_path # noqa: E402
35import shader_ir # noqa: E402 38import shader_ir # noqa: E402
@@ -90,8 +93,11 @@ def payloads_of(dxbc_path):
90 93
91def load_index(dxbc_dir): 94def load_index(dxbc_dir):
92 """(stage by stem, stems in index order) from <dxbc>/index.json.""" 95 """(stage by stem, stems in index order) from <dxbc>/index.json."""
93 with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: 96 try:
94 index = json.load(f) 97 with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8-sig") as f:
98 index = json.load(f)
99 except RecursionError:
100 raise ValueError("invalid JSON: recursion limit exceeded") from None
95 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): 101 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index):
96 raise ValueError("index.json is not a list of shader entries") 102 raise ValueError("index.json is not a list of shader entries")
97 stages = {} 103 stages = {}
@@ -111,7 +117,7 @@ def input_paths(dxbc_dir):
111 paths = [os.path.join(dxbc_dir, "index.json")] 117 paths = [os.path.join(dxbc_dir, "index.json")]
112 try: 118 try:
113 _stages, names = load_index(dxbc_dir) 119 _stages, names = load_index(dxbc_dir)
114 except (OSError, ValueError): 120 except (OSError, ValueError, RecursionError):
115 return paths 121 return paths
116 for name in names: 122 for name in names:
117 paths.append(os.path.join(dxbc_dir, name + ".dxbc")) 123 paths.append(os.path.join(dxbc_dir, name + ".dxbc"))
@@ -121,6 +127,8 @@ def input_paths(dxbc_dir):
121 127
122def survey(dxbc_dir, disasm_fn=None, limit=None): 128def survey(dxbc_dir, disasm_fn=None, limit=None):
123 """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" 129 """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs."""
130 if limit is not None and limit < 1:
131 raise ValueError("limit must be at least 1")
124 stages, names = load_index(dxbc_dir) 132 stages, names = load_index(dxbc_dir)
125 if limit is not None: 133 if limit is not None:
126 names = names[:limit] 134 names = names[:limit]
@@ -199,16 +207,45 @@ def survey(dxbc_dir, disasm_fn=None, limit=None):
199 } 207 }
200 208
201 209
210def _write_json_atomic(out_path, payload):
211 dest = os.path.realpath(out_path)
212 dest_dir = os.path.dirname(dest) or "."
213 os.makedirs(dest_dir, exist_ok=True)
214 fd, temp = tempfile.mkstemp(dir=dest_dir, prefix=".vs-layout-", suffix=".tmp")
215 try:
216 try:
217 f = os.fdopen(fd, "w", encoding="utf-8", newline="\n")
218 except BaseException:
219 os.close(fd)
220 raise
221 with f:
222 json.dump(payload, f, indent=1)
223 f.write("\n")
224 f.flush()
225 os.fsync(f.fileno())
226 os.chmod(temp, published_mode(dest))
227 replace_retry.replace(temp, dest)
228 except BaseException:
229 try:
230 os.chmod(temp, 0o600)
231 os.unlink(temp)
232 except OSError:
233 pass
234 raise
235
236
202def main(argv=None): 237def main(argv=None):
203 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 238 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
204 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py") 239 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py")
205 ap.add_argument("--json", help="also write the counts as JSON") 240 ap.add_argument("--json", help="also write the counts as JSON")
206 ap.add_argument("--limit", type=int, help="stop after this many containers (index order)") 241 ap.add_argument("--limit", type=int, help="stop after this many containers (index order)")
207 a = ap.parse_args(argv) 242 a = ap.parse_args(argv)
243 if a.limit is not None and a.limit < 1:
244 ap.error("--limit must be at least 1")
208 index_path = os.path.join(a.dxbc, "index.json") 245 index_path = os.path.join(a.dxbc, "index.json")
209 if a.json: 246 if a.json:
210 # Refuse before survey(): it reads the whole corpus and runs llvm-mc for every unlisted payload. 247 # Refuse before survey(): it reads the whole corpus and runs llvm-mc for every unlisted payload.
211 if os.path.isdir(a.json): 248 if os.path.isdir(a.json) or a.json.endswith(("/", "\\")):
212 print(f"vs_layout_census: error: --json {a.json} is a directory, not a JSON file", file=sys.stderr) 249 print(f"vs_layout_census: error: --json {a.json} is a directory, not a JSON file", file=sys.stderr)
213 return 2 250 return 2
214 for path in input_paths(a.dxbc): 251 for path in input_paths(a.dxbc):
@@ -217,7 +254,7 @@ def main(argv=None):
217 return 2 254 return 2
218 try: 255 try:
219 r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) 256 r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit)
220 except (OSError, ValueError) as e: 257 except (OSError, ValueError, RecursionError) as e:
221 print(f"vs_layout_census: error: cannot read {index_path}: {e}", file=sys.stderr) 258 print(f"vs_layout_census: error: cannot read {index_path}: {e}", file=sys.stderr)
222 return 2 259 return 2
223 print(f"{r['containers']} containers, {r['payloads']} payloads " 260 print(f"{r['containers']} containers, {r['payloads']} payloads "
@@ -231,8 +268,7 @@ def main(argv=None):
231 f"unlisted payloads disassembled {r['disassembled_unlisted']}") 268 f"unlisted payloads disassembled {r['disassembled_unlisted']}")
232 if a.json: 269 if a.json:
233 try: 270 try:
234 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 271 _write_json_atomic(a.json, r)
235 json.dump(r, f, indent=1)
236 except OSError as e: 272 except OSError as e:
237 print(f"vs_layout_census: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) 273 print(f"vs_layout_census: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
238 return 2 274 return 2
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md
index 8fbba6182..3f2284673 100644
--- a/scripts/windows-boot/README.md
+++ b/scripts/windows-boot/README.md
@@ -26,6 +26,18 @@ profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\bui
26checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`. 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. 27The script refuses an output folder inside the repository.
28 28
29### Private crash diagnostics
30
31Build the `gta6rt_crash_monitor` target in the same x64 Windows build as the runtime, then add
32`-CrashDump` to your usual boot command. Each invocation reserves a fresh directory under `-OutDir`.
33An unhandled exception writes `crash.dmp` and `stack.txt` for the faulting thread. An explicit nonzero
34exit captures the last thread at process exit, which may already be in shutdown. Handled exceptions,
35successful exits and the boot time limit produce no crash report.
36
37Keep matching PDBs beside the runtime for local symbol names. Frames without symbols can appear as
38addresses, and unwinding can stop at manually mapped code. Dumps can contain process memory and stacks
39can identify private inputs. Keep both on your machine. Share only the outcome, error class and counts.
40
29## What it sets 41## What it sets
30 42
31Only when your shell has not set them already (`-DryRun` prints the final list): 43Only when your shell has not set them already (`-DryRun` prints the final list):
diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1
index 801867f11..a0e713c17 100644
--- a/scripts/windows-boot/boot.ps1
+++ b/scripts/windows-boot/boot.ps1
@@ -91,6 +91,9 @@
91.PARAMETER DryRun 91.PARAMETER DryRun
92 Print the environment and the command line, check the paths, launch nothing. 92 Print the environment and the command line, check the paths, launch nothing.
93 93
94.PARAMETER CrashDump
95 Run under the native Windows crash monitor. A crash dump and stack go into a fresh private folder under -OutDir.
96
94.PARAMETER DigestOnly 97.PARAMETER DigestOnly
95 Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir). 98 Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir).
96 99
@@ -120,6 +123,7 @@ param(
120 [string]$Stacks = "", 123 [string]$Stacks = "",
121 [hashtable]$SetEnv = @{}, 124 [hashtable]$SetEnv = @{},
122 [switch]$NoCapture, 125 [switch]$NoCapture,
126 [switch]$CrashDump,
123 [switch]$NoInput, 127 [switch]$NoInput,
124 [string[]]$ExtraArgs = @(), 128 [string[]]$ExtraArgs = @(),
125 [switch]$FirstRunUi, 129 [switch]$FirstRunUi,
@@ -214,6 +218,12 @@ if (-not (Test-Path -LiteralPath $Runtime -PathType Leaf)) { $problems.Add("no g
214elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) { 218elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) {
215 $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)") 219 $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)")
216} 220}
221if ($CrashDump) {
222 $monitor = Join-Path $RuntimeDir "gta6rt_crash_monitor.exe"
223 if (-not (Test-Path -LiteralPath $monitor -PathType Leaf)) {
224 $problems.Add("-CrashDump needs the gta6rt_crash_monitor build target beside the runtime")
225 }
226}
217if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") } 227if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") }
218elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) { 228elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) {
219 $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives") 229 $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives")
@@ -420,11 +430,30 @@ if (-not $DigestOnly) {
420 430
421 # ------------------------------------------------------------------------------------------- the boot 431 # ------------------------------------------------------------------------------------------- the boot
422 $started = Get-Date 432 $started = Get-Date
423 $proc = Start-Process -FilePath $Runtime -ArgumentList $argLine -WorkingDirectory $RepoRoot -NoNewWindow -PassThru ` 433 $launchFile = $Runtime
434 $launchArgs = $argLine
435 if ($CrashDump) {
436 $crashDir = Join-Path $OutDir ("{0}-crash-{1}" -f $Name, [guid]::NewGuid().ToString("N"))
437 $runtimePath = (Get-Item -LiteralPath $Runtime).FullName
438 $childCommand = "$(ConvertTo-ProcessArgument $runtimePath) $argLine"
439 $launchFile = $monitor
440 $launchArgs = (@($RepoRoot, $crashDir, $Seconds, $runtimePath, $childCommand) |
441 ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " "
442 }
443 $proc = Start-Process -FilePath $launchFile -ArgumentList $launchArgs -WorkingDirectory $RepoRoot -NoNewWindow -PassThru `
424 -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile 444 -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile
425 $handle = $proc.Handle # keeps the exit code readable after the process ends 445 $handle = $proc.Handle # keeps the exit code readable after the process ends
426 $stopped = $false 446 $stopped = $false
427 if (-not $proc.WaitForExit($Seconds * 1000)) { 447 if ($CrashDump) {
448 # The monitor owns the deadline so a dump already in progress can finish.
449 $proc.WaitForExit()
450 $stopped = Test-Path -LiteralPath (Join-Path $crashDir "timed-out")
451 if (Test-Path -LiteralPath (Join-Path $crashDir "crash.dmp")) {
452 Write-Output "[boot] private crash diagnostics: $crashDir"
453 } elseif ($proc.ExitCode -ne 0) {
454 Write-Warning "No crash dump was saved. See the monitor diagnostics in $LogFile"
455 }
456 } elseif (-not $proc.WaitForExit($Seconds * 1000)) {
428 $stopped = $true 457 $stopped = $true
429 try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } 458 try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { }
430 [void]$proc.WaitForExit(20000) 459 [void]$proc.WaitForExit(20000)
diff --git a/scripts/windows-boot/crash_monitor.cpp b/scripts/windows-boot/crash_monitor.cpp
new file mode 100644
index 000000000..7cabf38ee
--- /dev/null
+++ b/scripts/windows-boot/crash_monitor.cpp
@@ -0,0 +1,204 @@
1// Optional out-of-process observer used by boot.ps1 on x64 Windows.
2#define WIN32_LEAN_AND_MEAN
3#define NOMINMAX
4#include <windows.h>
5#include <dbghelp.h>
6#include <cerrno>
7#include <cstdio>
8#include <cstdlib>
9#include <cwchar>
10#include <filesystem>
11#include <fstream>
12#include <iomanip>
13#include <string>
14
15namespace fs = std::filesystem;
16
17namespace {
18struct Handle {
19 HANDLE value;
20 ~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
21 Handle(const Handle&) = delete;
22 Handle& operator=(const Handle&) = delete;
23 explicit Handle(HANDLE handle) : value(handle) {}
24};
25
26void report_error(const char* operation, DWORD error = GetLastError()) {
27 std::fprintf(stderr, "[crash-monitor] %s failed (%lu)\n", operation, error);
28}
29
30bool write_dump(const fs::path& dir, HANDLE process, DWORD pid, MINIDUMP_EXCEPTION_INFORMATION* info) {
31 const auto partial = dir / L"crash.dmp.partial";
32 {
33 Handle file(CreateFileW(partial.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr));
34 if (file.value == INVALID_HANDLE_VALUE) { report_error("create dump"); return false; }
35 if (!MiniDumpWriteDump(process, pid, file.value, MiniDumpWithThreadInfo, info, nullptr, nullptr)) {
36 report_error("MiniDumpWriteDump");
37 return false;
38 }
39 }
40 if (!MoveFileExW(partial.c_str(), (dir / L"crash.dmp").c_str(), MOVEFILE_WRITE_THROUGH)) {
41 report_error("publish dump");
42 return false;
43 }
44 return true;
45}
46
47void write_stack(std::ostream& out, HANDLE process, HANDLE thread, CONTEXT ctx, const fs::path& symbols) {
48 // Only look beside the runtime. Ignore debugger environment paths and embedded build-machine paths.
49 SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_NO_PROMPTS |
50 SYMOPT_IGNORE_NT_SYMPATH | SYMOPT_IGNORE_CVREC | SYMOPT_DISABLE_SYMSRV_AUTODETECT);
51 const bool loaded = SymInitializeW(process, symbols.c_str(), TRUE) != FALSE;
52 STACKFRAME64 frame{};
53 frame.AddrPC = {ctx.Rip, 0, AddrModeFlat};
54 frame.AddrStack = {ctx.Rsp, 0, AddrModeFlat};
55 frame.AddrFrame = {ctx.Rbp, 0, AddrModeFlat};
56 for (unsigned n = 0; n < 64 && frame.AddrPC.Offset; ++n) {
57 const auto pc = frame.AddrPC.Offset;
58 const auto sp = frame.AddrStack.Offset;
59 out << '#' << std::dec << n << " 0x" << std::hex << pc;
60 IMAGEHLP_MODULE64 module{};
61 module.SizeOfStruct = sizeof(module);
62 if (loaded && SymGetModuleInfo64(process, pc, &module))
63 out << ' ' << module.ModuleName << "+0x" << pc - module.BaseOfImage;
64 alignas(SYMBOL_INFO) char storage[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]{};
65 auto* symbol = reinterpret_cast<SYMBOL_INFO*>(storage);
66 symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
67 symbol->MaxNameLen = MAX_SYM_NAME;
68 DWORD64 displacement = 0;
69 if (loaded && SymFromAddr(process, pc, &displacement, symbol))
70 out << " (" << symbol->Name << "+0x" << displacement << ')';
71 out << '\n';
72 if (!loaded || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr,
73 SymFunctionTableAccess64, SymGetModuleBase64, nullptr))
74 break;
75 if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) {
76 // The first StackWalk64 call can describe the initial frame again.
77 if (n != 0 || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr,
78 SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) break;
79 if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) break;
80 }
81 }
82 if (loaded) SymCleanup(process);
83}
84
85void capture(const fs::path& dir, const fs::path& symbols, HANDLE process, const DEBUG_EVENT& event) {
86 const bool exception = event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT;
87 const DWORD code = exception ? event.u.Exception.ExceptionRecord.ExceptionCode : event.u.ExitProcess.dwExitCode;
88 Handle thread(OpenThread(THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT, FALSE, event.dwThreadId));
89 CONTEXT ctx{};
90 ctx.ContextFlags = CONTEXT_ALL;
91 const bool got_context = thread.value && GetThreadContext(thread.value, &ctx);
92 EXCEPTION_RECORD record{};
93 if (exception) {
94 record = event.u.Exception.ExceptionRecord;
95 record.ExceptionRecord = nullptr; // Nested records belong to the child address space.
96 }
97 EXCEPTION_POINTERS pointers{&record, &ctx};
98 MINIDUMP_EXCEPTION_INFORMATION info{event.dwThreadId, &pointers, FALSE};
99 if (!write_dump(dir, process, event.dwProcessId, exception && got_context ? &info : nullptr))
100 DeleteFileW((dir / L"crash.dmp.partial").c_str());
101
102 std::ofstream stack(dir / L"stack.txt");
103 stack << "kind=" << (exception ? "unhandled_exception" : "abnormal_exit")
104 << "\ncode=0x" << std::hex << std::setw(8) << std::setfill('0') << code
105 << "\nthread=" << std::dec << event.dwThreadId << '\n';
106 if (got_context) write_stack(stack, process, thread.value, ctx, symbols);
107 else stack << "thread context unavailable at this debug event\n";
108 stack.close();
109 if (!stack) report_error("write stack.txt", ERROR_WRITE_FAULT);
110}
111
112DWORD monitor(HANDLE process, const fs::path& dir, const fs::path& symbols, ULONGLONG deadline) {
113 bool initial_break = true;
114 bool captured = false;
115 bool stopped = false;
116 for (;;) {
117 DEBUG_EVENT event{};
118 if (!WaitForDebugEventEx(&event, 100)) {
119 if (GetLastError() != ERROR_SEM_TIMEOUT) { report_error("WaitForDebugEventEx"); return 1; }
120 } else {
121 DWORD disposition = DBG_CONTINUE;
122 const bool exiting = event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT;
123 if (event.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT && event.u.CreateProcessInfo.hFile)
124 CloseHandle(event.u.CreateProcessInfo.hFile);
125 if (event.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT && event.u.LoadDll.hFile)
126 CloseHandle(event.u.LoadDll.hFile);
127 if (event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) {
128 const auto& ex = event.u.Exception;
129 if (initial_break && ex.dwFirstChance && ex.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
130 initial_break = false; // The loader breakpoint belongs to the debugger.
131 else {
132 disposition = DBG_EXCEPTION_NOT_HANDLED;
133 if (!ex.dwFirstChance && !stopped && !captured) {
134 capture(dir, symbols, process, event);
135 captured = true;
136 }
137 }
138 } else if (exiting && event.u.ExitProcess.dwExitCode && !stopped && !captured) {
139 capture(dir, symbols, process, event);
140 }
141 if (!ContinueDebugEvent(event.dwProcessId, event.dwThreadId, disposition)) {
142 report_error("ContinueDebugEvent");
143 return 1;
144 }
145 if (exiting) {
146 if (!stopped) return event.u.ExitProcess.dwExitCode;
147 std::ofstream marker(dir / L"timed-out");
148 marker.close();
149 return marker ? 0 : 1;
150 }
151 }
152 if (!captured && !stopped && GetTickCount64() >= deadline) {
153 if (TerminateProcess(process, ERROR_TIMEOUT)) stopped = true;
154 else if (GetLastError() != ERROR_ACCESS_DENIED) { report_error("TerminateProcess"); return 1; }
155 }
156 }
157}
158} // namespace
159
160int wmain(int argc, wchar_t** argv) {
161 if (argc != 6) {
162 std::fputs("usage: gta6rt_crash_monitor REPO NEW_REPORT_DIR SECONDS RUNTIME CHILD_COMMAND_LINE\n", stderr);
163 return 2;
164 }
165 wchar_t* end = nullptr;
166 const long seconds = std::wcstol(argv[3], &end, 10);
167 if (end == argv[3] || *end || errno == ERANGE || seconds < 0) return 2;
168 try {
169 const fs::path repo = fs::canonical(argv[1]);
170 const fs::path dir = fs::weakly_canonical(fs::absolute(argv[2]));
171 const fs::path runtime = fs::canonical(argv[4]);
172 // Resolve junctions and compare file identity (Windows path case can differ).
173 for (auto p = dir.parent_path();; p = p.parent_path()) {
174 if (fs::equivalent(p, repo)) {
175 std::fputs("[crash-monitor] private output must be outside the checkout\n", stderr);
176 return 2;
177 }
178 if (p == p.root_path()) break;
179 }
180 if (!fs::create_directory(dir)) {
181 std::fputs("[crash-monitor] report directory already exists\n", stderr);
182 return 2;
183 }
184 STARTUPINFOW startup{};
185 startup.cb = sizeof(startup);
186 startup.dwFlags = STARTF_USESTDHANDLES;
187 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
188 startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
189 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
190 PROCESS_INFORMATION pi{};
191 std::wstring command(argv[5]);
192 if (!CreateProcessW(runtime.c_str(), command.data(), nullptr, nullptr, TRUE, DEBUG_ONLY_THIS_PROCESS,
193 nullptr, nullptr, &startup, &pi)) {
194 report_error("CreateProcessW");
195 return 2;
196 }
197 Handle process(pi.hProcess);
198 Handle thread(pi.hThread);
199 return static_cast<int>(monitor(process.value, dir, runtime.parent_path(), GetTickCount64() + seconds * 1000ULL));
200 } catch (const fs::filesystem_error& e) {
201 report_error("resolve private output or runtime", e.code().value());
202 return 2;
203 }
204}
diff --git a/scripts/windows-boot/test_crash_monitor.py b/scripts/windows-boot/test_crash_monitor.py
new file mode 100644
index 000000000..140a870ab
--- /dev/null
+++ b/scripts/windows-boot/test_crash_monitor.py
@@ -0,0 +1,133 @@
1"""Exercise the native Windows crash monitor with an entirely synthetic child."""
2import os
3from pathlib import Path
4import shutil
5import struct
6import subprocess
7import sys
8import tempfile
9import unittest
10
11REPO = Path(__file__).resolve().parents[2]
12
13
14@unittest.skipUnless(__name__ == "__main__", "run through the windows_crash_monitor CTest target")
15class CrashMonitorTest(unittest.TestCase):
16 def setUp(self):
17 tmp = tempfile.TemporaryDirectory(prefix="leonida crash test ")
18 self.addCleanup(tmp.cleanup)
19 self.report = Path(tmp.name) / "private run"
20
21 def run_fixture(self, mode, *args, seconds=10):
22 env = dict(os.environ, LEONIDA_TEST_CRASH_MODE=mode)
23 result = subprocess.run(
24 [MONITOR, REPO, self.report, str(seconds), FIXTURE,
25 subprocess.list2cmdline([str(FIXTURE), *args])],
26 env=env, capture_output=True, timeout=30,
27 )
28 return result.returncode & 0xffffffff
29
30 def check_artifacts(self, code, exception):
31 data = (self.report / "crash.dmp").read_bytes()
32 self.assertEqual(data[:4], b"MDMP")
33 count, offset = struct.unpack_from("<II", data, 8)
34 streams = dict((kind, pos) for kind, size, pos in
35 (struct.unpack_from("<III", data, offset + 12*i) for i in range(count)))
36 self.assertIn(3, streams) # ThreadListStream
37 trace = (self.report / "stack.txt").read_text()
38 self.assertIn(f"code=0x{code:08x}", trace)
39 if exception:
40 pos = streams[6] # ExceptionStream: thread ID, padding, exception record
41 thread_id, _, actual_code = struct.unpack_from("<III", data, pos)
42 self.assertEqual(actual_code, code)
43 self.assertIn(f"thread={thread_id}\n", trace)
44 self.assertIn("kind=unhandled_exception", trace)
45 self.assertIn("#0 ", trace)
46 else:
47 self.assertNotIn(6, streams)
48 self.assertIn("kind=abnormal_exit", trace)
49 self.assertFalse((self.report / "crash.dmp.partial").exists())
50 return trace
51
52 def test_worker(self):
53 code = 0xe0421234
54 self.assertEqual(self.run_fixture("worker"), code)
55 trace = self.check_artifacts(code, True)
56 if FIXTURE.with_suffix(".pdb").exists():
57 self.assertIn("crash_worker", trace)
58
59 def test_breakpoint(self):
60 self.assertEqual(self.run_fixture("break"), 0x80000003)
61 self.check_artifacts(0x80000003, True)
62
63 def test_explicit_exit(self):
64 self.assertEqual(self.run_fixture("exit"), 23)
65 trace = self.check_artifacts(23, False)
66 self.assertIn("#0 ", trace)
67
68 def test_exit_with_exception_number(self):
69 self.assertEqual(self.run_fixture("numeric"), 0xc0000005)
70 self.check_artifacts(0xc0000005, False)
71
72 def test_handled(self):
73 self.assertEqual(self.run_fixture("handled"), 0)
74 self.assertFalse(any(self.report.iterdir()))
75
76 def test_arguments_and_clean_exit(self):
77 self.assertEqual(self.run_fixture("argv", "a b\\", 'a"b'), 0)
78 self.assertFalse(any(self.report.iterdir()))
79
80 def test_timeout(self):
81 self.assertEqual(self.run_fixture("timer", seconds=1), 0)
82 self.assertEqual([p.name for p in self.report.iterdir()], ["timed-out"])
83
84 def test_existing_directory(self):
85 self.report.mkdir()
86 sentinel = self.report / "keep"
87 sentinel.write_bytes(b"original")
88 self.assertNotEqual(self.run_fixture("worker"), 0)
89 self.assertEqual(list(self.report.iterdir()), [sentinel])
90 self.assertEqual(sentinel.read_text(), "original")
91
92 def test_repo_rejected(self):
93 self.report = REPO / (self.report.parent.name + "-forbidden")
94 self.assertNotEqual(self.run_fixture("worker"), 0)
95 self.assertFalse(self.report.exists())
96
97 def test_boot_entry_point(self):
98 root = self.report.parent
99 (root / "MicrosoftGame.Config").touch()
100 (root / "index.json").write_bytes(b"{}")
101 (root / "exe").mkdir()
102 (root / "exe" / "index.json").write_bytes(b"{}")
103 (root / "gta6rt_tls_host.dll").touch()
104 fixture = shutil.copy2(FIXTURE, root)
105 shutil.copy2(MONITOR, root)
106 out = root / "output"
107 script = REPO / "scripts" / "windows-boot" / "boot.ps1"
108 # Isolate the fixture from a developer's normal boot settings and paths.
109 env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")}
110 for mode, expected in (("exit", 23), ("timer", 0)):
111 with self.subTest(mode=mode):
112 result = subprocess.run(
113 ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script,
114 "-CrashDump", "-Name", mode, "-Runtime", fixture, "-Exe", fixture, "-GameDir", root,
115 "-Shaders", root, "-OutDir", out, "-Python", sys.executable, "-Seconds",
116 "1" if mode == "timer" else "10", "-LockWaitSeconds", "1", "-NoInput", "-NoCapture"],
117 env=dict(env, LEONIDA_TEST_CRASH_MODE=mode), capture_output=True, timeout=30,
118 )
119 self.assertEqual(result.returncode, expected, (result.stdout, result.stderr))
120 self.assertTrue((out / f"{mode}.digest.txt").is_file())
121 self.assertIn(b"fixture stdout", (out / f"{mode}.stdout.log").read_bytes())
122 self.assertIn(b"fixture stderr", (out / f"{mode}.log").read_bytes())
123 report, = out.glob(f"{mode}-crash-*")
124 if mode == "exit":
125 self.assertTrue((report / "crash.dmp").is_file())
126 else:
127 self.assertTrue((report / "timed-out").is_file())
128 self.assertFalse((report / "crash.dmp").exists())
129
130
131if __name__ == "__main__":
132 MONITOR, FIXTURE = map(Path, sys.argv[1:3])
133 unittest.main(argv=sys.argv[:1], verbosity=2)