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:
authorДмитрий Корлодный <deusex1998@gmail.com>2026-11-28 13:59:12 +0000
committerДмитрий Корлодный <deusex1998@gmail.com>2026-11-28 13:59:12 +0000
commit63b0b680baacdf32defd35bf3ad07e1c0a9f20bf (patch)
tree8ebc44432419b48cbaa56067e96ced5097a6628d /scripts
parent5acf0fa3fcae19eb06674ac0fc6a52712d408d5d (diff)
parent9c49bd5332327e689c5c957786c31b10efb3f32b (diff)
Merge upstream main into PR #2494
Diffstat (limited to 'scripts')
-rw-r--r--scripts/audit_shader4_regs.py57
-rw-r--r--scripts/bench_translate.py309
-rw-r--r--scripts/bench_wave64.py3
-rw-r--r--scripts/build_runtime.ps12
-rw-r--r--scripts/check_apt_key.py41
-rw-r--r--scripts/check_no_game_data.py11
-rw-r--r--scripts/dev.py12
-rw-r--r--scripts/export_old_pr_manifest.py123
-rwxr-xr-xscripts/fetch_vkd3d_proton.py76
-rw-r--r--scripts/launcher_python.sh40
-rw-r--r--scripts/merge_check.py10
-rw-r--r--scripts/play-d3d12.ps193
-rwxr-xr-xscripts/play-linux.sh71
-rw-r--r--scripts/play.ps159
-rw-r--r--scripts/port_ctl.py320
-rw-r--r--scripts/run_address_guard_gpu_test.py10
-rw-r--r--scripts/run_gpu_tests.py85
-rw-r--r--scripts/run_semantic_tests.py176
-rw-r--r--scripts/run_wine_tests.py20
-rw-r--r--scripts/shader_stats.py34
-rw-r--r--scripts/smoke.py332
-rw-r--r--scripts/smooth-motion.ps1104
-rw-r--r--scripts/sync_victory.py94
-rw-r--r--scripts/vs_input_survey.py99
-rw-r--r--scripts/windows-boot/README.md31
-rw-r--r--scripts/windows-boot/boot.ps169
-rw-r--r--scripts/windows-boot/mapped_stack.py313
27 files changed, 2441 insertions, 153 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py
index 1d1980045..9f651fbe5 100644
--- a/scripts/audit_shader4_regs.py
+++ b/scripts/audit_shader4_regs.py
@@ -11,15 +11,19 @@ Directory layout defaults match make_game.py / tools/rdna2spirv.py:
11 <disasm_dir>/../index.json (optional stage map; otherwise stage is inferred from filename prefix) 11 <disasm_dir>/../index.json (optional stage map; otherwise stage is inferred from filename prefix)
12""" 12"""
13import argparse 13import argparse
14import errno
14import json 15import json
15import os 16import os
16import re 17import re
17import struct 18import struct
18import sys 19import sys
20import tempfile
19from collections import Counter 21from collections import Counter
20 22
21ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 23ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22sys.path.insert(0, os.path.join(ROOT, "tools")) 24sys.path.insert(0, os.path.join(ROOT, "tools"))
25from file_mode import published_mode # noqa: E402
26from replace_retry import replace as replace_retry # noqa: E402
23from report_paths import same_report_path # noqa: E402 27from report_paths import same_report_path # noqa: E402
24import shader_ir # noqa: E402 28import shader_ir # noqa: E402
25from shader_meta import SGPR_RMW # noqa: E402 29from shader_meta import SGPR_RMW # noqa: E402
@@ -64,13 +68,21 @@ def load_stage_map(disasm_dir, *, report_path=None):
64 for cand in candidates: 68 for cand in candidates:
65 if os.path.isfile(cand): 69 if os.path.isfile(cand):
66 try: 70 try:
67 with open(cand, encoding="utf-8") as _f: 71 with open(cand, encoding="utf-8-sig") as _f:
68 data = json.load(_f) 72 data = json.load(_f)
69 if isinstance(data, list): 73 if isinstance(data, list):
70 return {os.path.splitext(e["file"])[0]: e.get("stage", "?") for e in data if "file" in e} 74 return {
75 os.path.splitext(e["file"])[0]: e["stage"] if isinstance(e.get("stage"), str) else "?"
76 for e in data
77 if isinstance(e, dict) and isinstance(e.get("file"), str)
78 }
71 if isinstance(data, dict): 79 if isinstance(data, dict):
72 return {k: v.get("stage", "?") for k, v in data.items() if isinstance(v, dict)} 80 return {
73 except (OSError, ValueError, KeyError, TypeError): 81 k: v["stage"] if isinstance(v.get("stage"), str) else "?"
82 for k, v in data.items()
83 if isinstance(v, dict)
84 }
85 except (OSError, ValueError, KeyError, TypeError, RecursionError):
74 pass 86 pass
75 return {} 87 return {}
76 88
@@ -98,10 +110,14 @@ def read_psv0(dxbc_path):
98 off = struct.unpack_from("<I", d, 32 + 4 * k)[0] 110 off = struct.unpack_from("<I", d, 32 + 4 * k)[0]
99 if off + 8 <= len(d) and d[off:off + 4] == b"PSV0": 111 if off + 8 <= len(d) and d[off:off + 4] == b"PSV0":
100 plen = struct.unpack_from("<I", d, off + 4)[0] 112 plen = struct.unpack_from("<I", d, off + 4)[0]
113 if off + 8 + plen > len(d):
114 return None
101 p = d[off + 8:off + 8 + plen] 115 p = d[off + 8:off + 8 + plen]
102 if len(p) < 4: 116 if len(p) < 4:
103 return None 117 return None
104 rsize = struct.unpack_from("<I", p, 0)[0] 118 rsize = struct.unpack_from("<I", p, 0)[0]
119 if 4 + rsize > len(p):
120 return None
105 r = p[4:4 + rsize] 121 r = p[4:4 + rsize]
106 if len(r) < 48: 122 if len(r) < 48:
107 return {"rsize": rsize} 123 return {"rsize": rsize}
@@ -373,6 +389,32 @@ def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), l
373 return out 389 return out
374 390
375 391
392def write_json(path, report):
393 """Atomically write LF-only JSON, preserving file permissions and cleaning up temp files on error."""
394 target = os.path.abspath(path)
395 parent = os.path.dirname(target) or "."
396 os.makedirs(parent, exist_ok=True)
397 if os.path.isdir(target):
398 raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), path)
399 payload = (json.dumps(report, indent=2, allow_nan=False) + "\n").encode("utf-8")
400 fd, tmp_path = tempfile.mkstemp(prefix=".audit_shader4_regs_", suffix=".tmp", dir=parent)
401 try:
402 with os.fdopen(fd, "wb") as f:
403 f.write(payload)
404 os.chmod(tmp_path, published_mode(target))
405 replace_retry(tmp_path, target)
406 except BaseException:
407 try:
408 os.chmod(tmp_path, 0o600)
409 except OSError:
410 pass
411 try:
412 os.unlink(tmp_path)
413 except OSError:
414 pass
415 raise
416
417
376def print_report(rep): 418def print_report(rep):
377 for st, rec in rep.items(): 419 for st, rec in rep.items():
378 print(f"=== {st.upper()} ({rec['count']} shaders; wave64={rec['wave64_heuristic']}, wave32={rec['wave32_heuristic']}) ===") 420 print(f"=== {st.upper()} ({rec['count']} shaders; wave64={rec['wave64_heuristic']}, wave32={rec['wave32_heuristic']}) ===")
@@ -430,7 +472,7 @@ def main(argv=None):
430 print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) 472 print(f"ERROR: {label}{path}: not a folder", file=sys.stderr)
431 return 2 473 return 2
432 474
433 report_path = a.json_out if a.json_out and os.path.isfile(a.json_out) else None 475 report_path = a.json_out or None
434 try: 476 try:
435 rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit, report_path=report_path) 477 rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit, report_path=report_path)
436 except ReportInputCollision as error: 478 except ReportInputCollision as error:
@@ -439,10 +481,7 @@ def main(argv=None):
439 print_report(rep) 481 print_report(rep)
440 if a.json_out: 482 if a.json_out:
441 try: 483 try:
442 os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True) 484 write_json(a.json_out, rep)
443 with open(a.json_out, "w", encoding="utf-8", newline="\n") as f:
444 json.dump(rep, f, indent=2)
445 f.write("\n")
446 except OSError as e: 485 except OSError as e:
447 print(f"ERROR: {a.json_out}: cannot write: {e.strerror or e}", file=sys.stderr) 486 print(f"ERROR: {a.json_out}: cannot write: {e.strerror or e}", file=sys.stderr)
448 return 1 487 return 1
diff --git a/scripts/bench_translate.py b/scripts/bench_translate.py
new file mode 100644
index 000000000..b639098b9
--- /dev/null
+++ b/scripts/bench_translate.py
@@ -0,0 +1,309 @@
1#!/usr/bin/env python3
2"""Throughput of the translator (tools/rdna2spirv.py): microseconds per instruction, so a slowdown is visible.
3
4 python -I scripts/bench_translate.py # fixtures + synthetic programs, best of 3
5 python -I scripts/bench_translate.py --json # the same numbers as JSON
6 python -I scripts/bench_translate.py --runs 5 --max-slowdown 1.5
7
8The repository tests what the translator *emits*; nothing measures how long it takes. A change to the parser or the
9instruction table can cost a large share of the build time and still pass every test, and about 26,503 shaders are
10translated per build. This script is the cheap check for that: it times `rdna2spirv.translate()` on inputs that
11need no game data, no LLVM and no SPIRV-Tools:
12
13- `corpus`: every fixture in tests/semantic/fixtures/disasm, the hand-written listings the semantic tests use.
14 Pixel and vertex listings translate as they are; compute listings need the FSSM header the tests pass separately,
15 so they are counted as skipped.
16- `synthetic`: generated straight-line programs (ALU, s_nop) at fixed instruction counts. The ALU program is the
17 instruction work, the s_nop program is mostly per-instruction overhead, and the two together separate a slower
18 parser from a slower code generator.
19
20Times are best-of-`--runs` seconds of one `translate()` call per program; medians are not used because a single
21unlucky run (another process taking the CPU) is what dominates the tail. The numbers are machine-specific: compare
22them with a run of the same commit, not with the table in the pull request that added this script.
23"""
24import argparse
25import json
26import os
27import statistics
28import struct
29import subprocess
30import sys
31import tempfile
32import time
33import warnings
34
35ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
36TOOLS = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")
37FIXTURES = os.path.join(ROOT, "tests", "semantic", "fixtures", "disasm")
38sys.dont_write_bytecode = True
39sys.path.insert(0, TOOLS)
40import rdna2spirv # noqa: E402
41
42# A DXBC container with zero parts declares no inputs, which is enough for a listing that reads no attribute
43# (tests/semantic/support.py uses the same stub).
44STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
45
46ALU_BODY = ("\tv_add_f32 v1, v1, 1.0\n"
47 "\tv_mul_f32 v2, v1, 2.0\n"
48 "\tv_cndmask_b32 v3, v1, v2, vcc\n"
49 "\tv_and_b32 v4, v3, 0xff\n")
50NOP_BODY = "\ts_nop 0\n"
51
52
53def synthetic(name, body, instructions):
54 """A whole pixel shader: comment, the repeated body, and the export the stage needs to be a shader."""
55 lines = [f"; ps_{name} synthetic benchmark program\n"]
56 lines.extend([body] * ((instructions + body.count("\n") - 1) // body.count("\n")))
57 lines.extend(["\tv_mov_b32 v1, 1\n",
58 "\texp mrt0 v1, v1, v1, v1 done\n",
59 "\ts_waitcnt expcnt(0)\n",
60 "\ts_endpgm\n"])
61 return "".join(lines).encode("utf-8")
62
63
64def translate_bytes(stem, listing, runs):
65 """Best of `runs` wall-clock seconds for one translate() of this listing, and the instruction count."""
66 with tempfile.TemporaryDirectory() as tmp:
67 os.mkdir(os.path.join(tmp, "disasm"))
68 with open(os.path.join(tmp, "disasm", stem + ".s"), "wb") as f:
69 f.write(listing)
70 with open(os.path.join(tmp, stem + ".dxbc"), "wb") as f:
71 f.write(STUB_DXBC)
72 path = os.path.join(tmp, "disasm", stem + ".s")
73 best = None
74 for _ in range(runs):
75 start = time.perf_counter()
76 with warnings.catch_warnings():
77 # The translator leaves its .dxbc handle to the garbage collector; that is its own business here.
78 warnings.simplefilter("ignore")
79 rdna2spirv.translate(path)
80 elapsed = time.perf_counter() - start
81 best = elapsed if best is None else min(best, elapsed)
82 return best
83
84
85def instruction_count(listing):
86 return sum(1 for line in listing.decode("utf-8", "replace").splitlines()
87 if line.startswith("\t") and line.strip())
88
89
90def corpus_rows(runs):
91 """Time every fixture that translates on its own, and count the ones that need an FSSM header."""
92 rows, skipped = [], []
93 for name in sorted(os.listdir(FIXTURES)):
94 if not name.endswith(".s"):
95 continue
96 stem = name[:-2]
97 if stem.startswith("cs_"):
98 # A compute listing reads its group size and RSRC2 out of the FSSM header, which translate() takes from
99 # <dir>/../fssm/<stem>.fssm; the semantic tests pass it per fixture (tests/semantic/support.py).
100 skipped.append(f"{stem}: compute listing, needs a FSSM header")
101 continue
102 with open(os.path.join(FIXTURES, name), "rb") as f:
103 listing = f.read()
104 try:
105 seconds = translate_bytes(stem, listing, runs)
106 except Exception as error: # a listing this run cannot translate: report it, never count it as fast
107 skipped.append(f"{stem}: {type(error).__name__}: {error}")
108 continue
109 instructions = instruction_count(listing)
110 rows.append({"name": stem, "instructions": instructions, "seconds": seconds,
111 "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0})
112 return rows, skipped
113
114
115def synthetic_rows(runs, size):
116 rows = []
117 for name, body, instructions in (("alu", ALU_BODY, size), ("nop", NOP_BODY, size)):
118 listing = synthetic(name, body, instructions)
119 seconds = translate_bytes("ps_" + name, listing, runs)
120 count = instruction_count(listing)
121 rows.append({"name": name, "instructions": count, "seconds": seconds,
122 "us_per_instruction": seconds / count * 1e6})
123 return rows
124
125
126def summarise(rows):
127 if not rows:
128 return {"programs": 0, "instructions": 0, "seconds": 0.0, "us_per_instruction": 0.0}
129 instructions = sum(r["instructions"] for r in rows)
130 seconds = sum(r["seconds"] for r in rows)
131 return {"programs": len(rows), "instructions": instructions, "seconds": seconds,
132 "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0}
133
134
135# Recorded on this machine (AMD Ryzen 9 desktop, Windows 11, Python 3.12.4, commit 1cc6e3c) with --runs 3: the numbers
136# to compare a later run against on the same machine. A different machine moves the absolute value; the shape does not.
137BASELINE = {"corpus_us_per_instruction": 55.4, "alu_us_per_instruction": 32.3, "nop_us_per_instruction": 14.0}
138
139
140def compare(reference, candidate, runs, size, rounds, max_slowdown=None):
141 """Interleaved A/B over two tools/ trees: each round measures both, and the best per side is kept.
142
143 Loading the tree is the subprocess's job (LEONIDA_TOOLS_DIR, as tests/semantic/support.py does it), so the two
144 versions never share a module. Alternating the two in the same round is the point: a machine that slows down or
145 speeds up between measurements moves both sides, not just one.
146 """
147 def measure(path):
148 env = dict(os.environ, LEONIDA_TOOLS_DIR=os.path.abspath(path))
149 result = subprocess.run([sys.executable, "-I", os.path.abspath(__file__), "--json",
150 "--runs", str(runs), "--size", str(size)],
151 capture_output=True, text=True, env=env)
152 if result.returncode != 0:
153 raise SystemExit(f"{path}: the benchmark failed\n{result.stderr.strip()}")
154 return json.loads(result.stdout)["measured"]
155
156 best = {"reference": {}, "candidate": {}}
157 measured_any = False
158 for round_index in range(rounds + 1): # the first round warms the caches and is not counted
159 order = [("reference", reference), ("candidate", candidate)]
160 if round_index % 2:
161 order.reverse() # whoever runs first pays the cold file cache, so the order alternates
162 for side, path in order:
163 measured = measure(path)
164 measured_any = measured_any or bool(measured)
165 if round_index == 0:
166 continue
167 for key, value in measured.items():
168 best[side][key] = min(best[side].get(key, value), value)
169 if not measured_any:
170 raise SystemExit("both trees measured nothing (an empty corpus?); nothing to compare")
171 if sorted(best["reference"]) != sorted(best["candidate"]):
172 only_reference = sorted(set(best["reference"]) - set(best["candidate"]))
173 only_candidate = sorted(set(best["candidate"]) - set(best["reference"]))
174 raise SystemExit("the two trees do not cover the same measurements"
175 + (f"; only in the reference: {', '.join(only_reference)}" if only_reference else "")
176 + (f"; only in the candidate: {', '.join(only_candidate)}" if only_candidate else "")
177 + "; a missing program would read as a ratio that looks like a win")
178 rows = []
179 for key in best["reference"]:
180 ref = best["reference"][key]
181 cand = best["candidate"].get(key, float("nan"))
182 rows.append({"name": key, "reference": ref, "candidate": cand, "ratio": cand / ref if ref else None})
183 print(f"{'measurement':<32} {'reference':>10} {'candidate':>10} {'ratio':>7}")
184 for row in rows:
185 ratio = f"{row['ratio']:>6.2f}x" if row["ratio"] is not None else " n/a"
186 print(f"{row['name']:<32} {row['reference']:>10.1f} {row['candidate']:>10.1f} {ratio}")
187 print(f"\nreference {os.path.abspath(reference)}\ncandidate {os.path.abspath(candidate)}")
188 print("ratio below 1.00 is the candidate being faster; rounds %d, min per side" % rounds)
189 if max_slowdown is not None:
190 # The limit means here what it means against a baseline: a measurement over it is a failure. The ratio is
191 # already candidate/reference, so the limit applies to it directly.
192 slow = [row for row in rows if row["ratio"] is not None and row["ratio"] > max_slowdown]
193 if slow:
194 for row in slow:
195 print(f"slower than the reference by {row['ratio']:.2f}x (limit {max_slowdown:.2f}x): {row['name']}",
196 file=sys.stderr)
197 return 1
198 return 0
199
200
201def main(argv=None):
202 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
203 parser.add_argument("--runs", type=int, default=3, help="translate() calls per program, best one counted")
204 parser.add_argument("--size", type=int, default=2000, help="instructions in each synthetic program")
205 parser.add_argument("--json", action="store_true", help="print one JSON object instead of the tables")
206 parser.add_argument("--max-slowdown", type=float, default=None,
207 help="exit 1 when a per-instruction time exceeds the baseline by this factor, in every output "
208 "format")
209 parser.add_argument("--baseline", metavar="FILE", default=None,
210 help="compare against a baseline written by --write-baseline instead of the committed one; "
211 "the committed numbers are from one machine and mean nothing on another")
212 parser.add_argument("--write-baseline", metavar="FILE", default=None,
213 help="write this run's numbers to FILE as a baseline for --baseline")
214 parser.add_argument("--compare", nargs=2, metavar=("REFERENCE", "CANDIDATE"), default=None,
215 help="time two tools/ trees against each other, interleaved; prints a ratio per measurement")
216 parser.add_argument("--rounds", type=int, default=3, help="rounds of --compare; the best per side is kept")
217 arguments = parser.parse_args(argv)
218 if arguments.rounds < 1:
219 parser.error("--rounds must be at least 1")
220 if arguments.baseline and arguments.write_baseline and \
221 os.path.abspath(arguments.baseline) == os.path.abspath(arguments.write_baseline):
222 # One file for both: a run that fails the limit would still replace the reference it failed against, and the
223 # same workload would pass on the retry.
224 parser.error("--baseline and --write-baseline name the same file; write to a different one")
225 if arguments.compare:
226 for flag, value in (("--json", arguments.json), ("--write-baseline", arguments.write_baseline),
227 ("--baseline", arguments.baseline)):
228 if value:
229 parser.error(f"{flag} does not apply to --compare, which times two trees and prints its own table")
230 return compare(*arguments.compare, arguments.runs, arguments.size, arguments.rounds,
231 arguments.max_slowdown)
232 if arguments.baseline and not os.path.isfile(arguments.baseline):
233 parser.error(f"--baseline {arguments.baseline} does not exist; --write-baseline records one")
234 if arguments.runs < 1:
235 parser.error("--runs must be at least 1")
236 if arguments.size < 1:
237 parser.error("--size must be at least 1")
238
239 corpus, skipped = corpus_rows(arguments.runs)
240 synthetic_programs = synthetic_rows(arguments.runs, arguments.size)
241 corpus_summary = summarise(corpus)
242 synthetic_summary = summarise(synthetic_programs)
243
244 measured = {"corpus_us_per_instruction": corpus_summary["us_per_instruction"]}
245 measured.update({f"{row['name']}_us_per_instruction": row["us_per_instruction"]
246 for row in synthetic_programs})
247
248 baseline, baseline_source = BASELINE, "committed"
249 if arguments.baseline:
250 with open(arguments.baseline, encoding="utf-8") as handle:
251 loaded = json.load(handle)
252 baseline = {key: float(value) for key, value in (loaded.get("measured") or loaded).items()}
253 baseline_source = os.path.abspath(arguments.baseline)
254 if arguments.write_baseline:
255 with open(arguments.write_baseline, "w", encoding="utf-8", newline="\n") as handle:
256 json.dump({"measured": measured, "runs": arguments.runs, "size": arguments.size}, handle,
257 indent=2, sort_keys=True)
258 handle.write("\n")
259 print(f"baseline written to {os.path.abspath(arguments.write_baseline)}", file=sys.stderr)
260
261 # The limit is part of the contract of every output format: a job that collects --json must not read a success
262 # code for a run whose numbers are over the limit. It is evaluated here, once, before either format prints.
263 slow = {}
264 if arguments.max_slowdown is not None:
265 slow = {key: value / baseline[key] for key, value in measured.items()
266 if baseline.get(key) and value > baseline[key] * arguments.max_slowdown}
267
268 if arguments.json:
269 print(json.dumps({
270 "runs": arguments.runs,
271 "corpus": {"summary": corpus_summary, "programs": corpus, "skipped": skipped},
272 "synthetic": {"summary": synthetic_summary, "programs": synthetic_programs, "size": arguments.size},
273 "baseline": baseline,
274 "baseline_source": baseline_source,
275 "measured": measured,
276 "slowdown": {k: (measured[k] / baseline[k] if baseline.get(k) else None) for k in measured},
277 "over_limit": sorted(slow),
278 "max_slowdown": arguments.max_slowdown,
279 }, indent=2, sort_keys=True))
280 return 1 if slow else 0
281
282 print(f"corpus: {corpus_summary['programs']} fixtures, {corpus_summary['instructions']} instructions, "
283 f"{corpus_summary['seconds']:.3f} s, {corpus_summary['us_per_instruction']:.1f} us/instruction "
284 f"({len(skipped)} skipped)")
285 worst = sorted(corpus, key=lambda r: -r["us_per_instruction"])[:5]
286 for row in worst:
287 print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms "
288 f"{row['us_per_instruction']:>6.1f} us/instr")
289 print(f"\nsynthetic ({arguments.size} instructions):")
290 for row in synthetic_programs:
291 reference = baseline.get(row["name"] + "_us_per_instruction")
292 compared = (f"({measured[row['name'] + '_us_per_instruction'] / reference:.2f}x the {baseline_source} baseline)"
293 if reference else "(no baseline for this measurement)")
294 print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms "
295 f"{row['us_per_instruction']:>6.1f} us/instr {compared}")
296 if skipped:
297 print("\nskipped (need the FSSM header, which these runs do not pass):")
298 for line in skipped:
299 print(" " + line)
300
301 if slow:
302 for name, factor in sorted(slow.items()):
303 print(f"slower than baseline ({baseline_source}) by {factor:.2f}x: {name}", file=sys.stderr)
304 return 1
305 return 0
306
307
308if __name__ == "__main__":
309 sys.exit(main())
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index 57253cb57..3a566ebfd 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -97,7 +97,8 @@ def main():
97 ap = argparse.ArgumentParser() 97 ap = argparse.ArgumentParser()
98 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), 98 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"),
99 help="CMake build directory or a configuration directory such as RelWithDebInfo") 99 help="CMake build directory or a configuration directory such as RelWithDebInfo")
100 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) 100 # Empty means unset to build.py: mc_command() then finds llvm-mc on PATH or a versioned llvm-mc-<N>.
101 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", ""))
101 # Vulkan guarantees support for at least 65,535 groups along X in one dispatch. 102 # Vulkan guarantees support for at least 65,535 groups along X in one dispatch.
102 ap.add_argument("--groups", type=positive_int, default=65535) 103 ap.add_argument("--groups", type=positive_int, default=65535)
103 ap.add_argument("--reps", type=positive_int, default=30) 104 ap.add_argument("--reps", type=positive_int, default=30)
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1
index bb25cccd7..d386ba052 100644
--- a/scripts/build_runtime.ps1
+++ b/scripts/build_runtime.ps1
@@ -116,7 +116,7 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO
116rem tools/sandbox.py starts vk_sandbox, and tools/ps_sweep.py --exe / tools/ab_control_flow.py --all-attachments start 116rem tools/sandbox.py starts vk_sandbox, and tools/ps_sweep.py --exe / tools/ab_control_flow.py --all-attachments start
117rem vk_ps_sweep, by name from runtime\build; without them the sandbox says "vk_sandbox is not built" and the sweep has 117rem vk_ps_sweep, by name from runtime\build; without them the sandbox says "vk_sandbox is not built" and the sweep has
118rem no harness to pass. CMake builds both in its Vulkan tools loop (EGEN-FALLBACK-SANDBOX-SWEEP). 118rem no harness to pass. CMake builds both in its Vulkan tools loop (EGEN-FALLBACK-SANDBOX-SWEEP).
119if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sandbox.cpp" /Fe:vk_sandbox.exe || exit /b 1 119if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_sandbox.cpp" /Fe:vk_sandbox.exe /link user32.lib || exit /b 1
120if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_ps_sweep.cpp" /Fe:vk_ps_sweep.exe || exit /b 1 120if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "%VULKAN_SDK%\Include" /I "$src\src" "$src\test\vk_ps_sweep.cpp" /Fe:vk_ps_sweep.exe || exit /b 1
121"@ 121"@
122} 122}
diff --git a/scripts/check_apt_key.py b/scripts/check_apt_key.py
index 160f0203a..f06ce8629 100644
--- a/scripts/check_apt_key.py
+++ b/scripts/check_apt_key.py
@@ -20,6 +20,8 @@ import sys
20 20
21def normalize(fingerprint): 21def normalize(fingerprint):
22 """`fingerprint` as 40 upper-case hex digits, or None if it isn't a v4 fingerprint.""" 22 """`fingerprint` as 40 upper-case hex digits, or None if it isn't a v4 fingerprint."""
23 if not isinstance(fingerprint, str):
24 return None
23 digits = re.sub(r"\s+", "", fingerprint).upper() 25 digits = re.sub(r"\s+", "", fingerprint).upper()
24 return digits if re.fullmatch(r"[0-9A-F]{40}", digits) else None 26 return digits if re.fullmatch(r"[0-9A-F]{40}", digits) else None
25 27
@@ -30,19 +32,26 @@ def primary_fingerprints(colons):
30 expect_primary_fpr = False 32 expect_primary_fpr = False
31 for line in colons.splitlines(): 33 for line in colons.splitlines():
32 fields = line.split(":") 34 fields = line.split(":")
33 if fields[0] == "pub": 35 tag = fields[0]
36 if tag == "pub":
37 if expect_primary_fpr:
38 out.append("")
34 expect_primary_fpr = True 39 expect_primary_fpr = True
35 elif fields[0] == "fpr" and expect_primary_fpr: 40 elif tag == "fpr" and expect_primary_fpr:
36 out.append(fields[9].upper() if len(fields) > 9 else "") 41 out.append(fields[9].strip().upper() if len(fields) > 9 else "")
37 expect_primary_fpr = False 42 expect_primary_fpr = False
38 elif fields[0] in ("sub", "ssb", "sec"): 43 elif tag in ("sub", "ssb", "sec"):
44 if expect_primary_fpr:
45 out.append("")
39 expect_primary_fpr = False 46 expect_primary_fpr = False
47 if expect_primary_fpr:
48 out.append("")
40 return out 49 return out
41 50
42 51
43def show_keys(path, gpg=("gpg",)): 52def show_keys(path, gpg=("gpg",)):
44 """`gpg --show-keys --with-colons` output for the key file at `path` (it lists the file, importing nothing).""" 53 """`gpg --show-keys --with-colons` output for the key file at `path` (it lists the file, importing nothing)."""
45 result = subprocess.run([*gpg, "--batch", "--show-keys", "--with-colons", path], 54 result = subprocess.run([*gpg, "--batch", "--show-keys", "--with-colons", "--", path],
46 capture_output=True, text=True, encoding="utf-8", errors="replace") 55 capture_output=True, text=True, encoding="utf-8", errors="replace")
47 if result.returncode != 0: 56 if result.returncode != 0:
48 raise ValueError(f"gpg could not read {path}: {result.stderr.strip() or 'exit ' + str(result.returncode)}") 57 raise ValueError(f"gpg could not read {path}: {result.stderr.strip() or 'exit ' + str(result.returncode)}")
@@ -52,20 +61,32 @@ def show_keys(path, gpg=("gpg",)):
52def check(path, expected, gpg=("gpg",)): 61def check(path, expected, gpg=("gpg",)):
53 """None if the key file at `path` holds exactly the one primary key `expected`, else why not. `gpg` is the command 62 """None if the key file at `path` holds exactly the one primary key `expected`, else why not. `gpg` is the command
54 that runs GnuPG (a list, so a test can stand another program in).""" 63 that runs GnuPG (a list, so a test can stand another program in)."""
64 norm_expected = normalize(expected)
65 if not norm_expected:
66 return f"not a 40-digit key fingerprint: {expected!r}"
55 try: 67 try:
56 found = primary_fingerprints(show_keys(path, gpg)) 68 colons = show_keys(path, gpg)
57 except (OSError, ValueError) as e: 69 except (OSError, ValueError) as e:
58 return str(e) 70 return str(e)
71 if any(line.split(":", 1)[0] in ("sec", "ssb") for line in colons.splitlines()):
72 return f"{path} holds secret key material; expected a public key only"
73 found = primary_fingerprints(colons)
59 if not found: 74 if not found:
60 return f"{path} holds no public key" 75 return f"{path} holds no public key"
61 if len(found) > 1: 76 if len(found) > 1:
62 return f"{path} holds {len(found)} primary keys ({', '.join(found)}); expected only {expected}" 77 labels = ", ".join(fp or "<missing>" for fp in found)
63 if found[0] != expected: 78 return f"{path} holds {len(found)} primary keys ({labels}); expected only {norm_expected}"
64 return f"{path} is key {found[0]}, expected {expected}" 79 if found[0] != norm_expected:
80 got = found[0] or "<missing>"
81 return f"{path} is key {got}, expected {norm_expected}"
65 return None 82 return None
66 83
67 84
68def main(argv): 85def main(argv=None):
86 argv = sys.argv[1:] if argv is None else list(argv)
87 if argv in (["-h"], ["--help"]):
88 print(__doc__)
89 return 0
69 if len(argv) != 2: 90 if len(argv) != 2:
70 print("usage: check_apt_key.py KEYFILE FINGERPRINT", file=sys.stderr) 91 print("usage: check_apt_key.py KEYFILE FINGERPRINT", file=sys.stderr)
71 return 2 92 return 2
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py
index ae3d06e77..595fc7b1c 100644
--- a/scripts/check_no_game_data.py
+++ b/scripts/check_no_game_data.py
@@ -14,8 +14,8 @@ notes). Text formats (disassembly, .obj, .spvasm)
14have no magic and stay with the extension check. 14have no magic and stay with the extension check.
15 15
16A compressed file hides those magics from both checks, so the script looks inside what the standard library opens: 16A compressed file hides those magics from both checks, so the script looks inside what the standard library opens:
17each member of a zip (found by its central directory too, so with bytes in front of it) or a tar, and the stream of 17each member of a zip (found by its central directory too, so with bytes in front of it) or a tar (including V7), and
18a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory 18the stream of a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory
19under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long. 19under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long.
207-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are 207-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are
21reported as archives that can't be checked. 21reported as archives that can't be checked.
@@ -184,6 +184,13 @@ def archive_kind(f, head):
184 return stream[0] 184 return stream[0]
185 if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]: 185 if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]:
186 return "tar archive" 186 return "tar archive"
187 # V7 tar has no ustar marker. Validate only its first header here; member reads still use the shared budget.
188 try:
189 tarfile.TarInfo.frombuf(head[:tarfile.BLOCKSIZE], tarfile.ENCODING, "surrogateescape")
190 except tarfile.HeaderError:
191 pass
192 else:
193 return "tar archive"
187 # is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting 194 # is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting
188 # archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it. 195 # archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it.
189 if head.startswith(ZIP) or zipfile.is_zipfile(f): 196 if head.startswith(ZIP) or zipfile.is_zipfile(f):
diff --git a/scripts/dev.py b/scripts/dev.py
index fada30da4..4170aac63 100644
--- a/scripts/dev.py
+++ b/scripts/dev.py
@@ -13,6 +13,7 @@ from pathlib import Path
13ROOT = Path(__file__).resolve().parents[1] 13ROOT = Path(__file__).resolve().parents[1]
14BOOT_TRACE = "tools/boot_trace.py" 14BOOT_TRACE = "tools/boot_trace.py"
15GUEST_SCENE = "scripts/run_guest_scene.py" 15GUEST_SCENE = "scripts/run_guest_scene.py"
16SMOKE = "scripts/smoke.py"
16TOOLS = ( 17TOOLS = (
17 ( 18 (
18 "boot-trace", 19 "boot-trace",
@@ -29,6 +30,14 @@ TOOLS = (
29 "Wine when running the Windows loader outside Windows", 30 "Wine when running the Windows loader outside Windows",
30 ), 31 ),
31 ), 32 ),
33 (
34 "smoke",
35 SMOKE,
36 (
37 "Python 3.10+",
38 "Synthetic source-only smoke suite (compilation, clean-room, CLI help, fast tests)",
39 ),
40 ),
32) 41)
33 42
34 43
@@ -94,6 +103,8 @@ def main() -> int:
94 return run_producer(BOOT_TRACE, argv[1:]) 103 return run_producer(BOOT_TRACE, argv[1:])
95 if argv[:1] == ["guest-scene"]: 104 if argv[:1] == ["guest-scene"]:
96 return guest_scene(argv[1:]) 105 return guest_scene(argv[1:])
106 if argv[:1] == ["smoke"]:
107 return run_producer(SMOKE, argv[1:])
97 108
98 parser = argparse.ArgumentParser(description=__doc__) 109 parser = argparse.ArgumentParser(description=__doc__)
99 commands = parser.add_subparsers(dest="command", required=True) 110 commands = parser.add_subparsers(dest="command", required=True)
@@ -101,6 +112,7 @@ def main() -> int:
101 inventory.add_argument("--json", action="store_true", help="write a JSON inventory to stdout") 112 inventory.add_argument("--json", action="store_true", help="write a JSON inventory to stdout")
102 commands.add_parser("boot-trace", help="summarize startup and D3D12 boot traces") 113 commands.add_parser("boot-trace", help="summarize startup and D3D12 boot traces")
103 commands.add_parser("guest-scene", help="run the synthetic guest scene with a required --out") 114 commands.add_parser("guest-scene", help="run the synthetic guest scene with a required --out")
115 commands.add_parser("smoke", help="run the synthetic source-only smoke suite (DX-07)")
104 args = parser.parse_args(argv) 116 args = parser.parse_args(argv)
105 117
106 result = discover() 118 result = discover()
diff --git a/scripts/export_old_pr_manifest.py b/scripts/export_old_pr_manifest.py
new file mode 100644
index 000000000..66d99f1ac
--- /dev/null
+++ b/scripts/export_old_pr_manifest.py
@@ -0,0 +1,123 @@
1"""Write a portable, verifiable manifest of the original repository's surviving history (issue #563).
2
3The original `ItsNotRexed/Leonida` repository went private in November 2026. Its pull requests survive only as the
4`old-pr/<old number>` branches kept here (issue #17) and its issues only as the title/author index in issue #18. Both
5live on GitHub, which is the single point of failure this manifest removes: the branch tips, their authors and dates
6are recorded as a sorted TSV with a SHA-256 beside it, so the record can be checked after the branches themselves are
7gone, and fed to a migration (Radicle, issue #563) without re-reading GitHub.
8
9 python -I scripts/export_old_pr_manifest.py branches --out docs/history --remote origin
10 python -I scripts/export_old_pr_manifest.py issues --index issue-18.md --out docs/history
11
12`branches` reads `refs/remotes/<remote>/old-pr/*` from the local clone; `issues` reads the markdown table posted in
13issue #18. Both write `<kind>.tsv` and `<kind>.sha256` in the output directory, and both are deterministic: the same
14input gives the same bytes, sorting numerically by old number so the order does not depend on ref iteration. Commit
15dates are kept as the commit's own ISO-8601 author date, not as a generation timestamp, for the same reason.
16
17Nothing of the game is read: a branch number, a SHA, a name, a date and a subject line.
18"""
19import argparse
20import hashlib
21import os
22import re
23import subprocess
24import sys
25
26# A subject can contain a tab or a newline; the TSV keeps one record per line with single spaces.
27_WHITESPACE = re.compile(r"\s+")
28
29# | 4 | Would you consider MIT License? | `Ahmet-Dedeler` | |
30_ISSUE_ROW = re.compile(r"^\|\s*(\d+)\s*\|(.+?)\|(.+?)\|(.*?)\|\s*$")
31
32
33def collapse(text: str) -> str:
34 return _WHITESPACE.sub(" ", text).strip()
35
36
37def git(branch_format: str, pattern: str) -> list:
38 r = subprocess.run(
39 ["git", "for-each-ref", "--format=" + branch_format, pattern],
40 capture_output=True, text=True, encoding="utf-8",
41 )
42 if r.returncode:
43 raise SystemExit(f"git for-each-ref failed: {r.stderr.strip()}")
44 return r.stdout.splitlines()
45
46
47def branches(remote: str) -> list:
48 """Rows (number, tip sha, author date, author, subject) for every surviving old pull request branch."""
49 pattern = f"refs/remotes/{remote}/old-pr/*"
50 fmt = "%(refname:lstrip=3)%09%(objectname)%09%(authordate:iso-strict)%09%(authorname)%09%(subject)"
51 rows = []
52 for line in git(fmt, pattern):
53 if not line.strip():
54 continue
55 ref, sha, date, author, subject = (line.split("\t", 4) + [""] * 5)[:5]
56 number = ref.partition("old-pr/")[2]
57 if not number.isdigit() or not re.fullmatch(r"[0-9a-f]{40}", sha):
58 raise SystemExit(f"unexpected ref line: {line!r}")
59 rows.append((int(number), sha, date, collapse(author), collapse(subject)))
60 if not rows:
61 raise SystemExit(f"no refs matched {pattern}; fetch the branches first (git fetch {remote})")
62 numbers = [r[0] for r in rows]
63 if len(set(numbers)) != len(numbers):
64 raise SystemExit("two refs share an old number")
65 return sorted(rows)
66
67
68def issues(text: str) -> list:
69 """Rows (number, title, author, labels) from the markdown table of issue #18."""
70 rows = []
71 for line in text.splitlines():
72 if not line.startswith("|"):
73 continue
74 m = _ISSUE_ROW.match(line)
75 if not m:
76 continue
77 number, title, author, labels = m.groups()
78 if not title.strip() or set(title.strip()) <= set("-: "):
79 continue
80 rows.append((int(number), collapse(title), collapse(author), collapse(labels)))
81 if not rows:
82 raise SystemExit("no issue rows found; is this the table from issue #18?")
83 return sorted(rows)
84
85
86def write_tsv(out_dir: str, kind: str, header: tuple, rows: list) -> str:
87 os.makedirs(out_dir, exist_ok=True)
88 body = "\t".join(header) + "\n"
89 body += "".join("\t".join(str(c) for c in row) + "\n" for row in rows)
90 path = os.path.join(out_dir, kind + ".tsv")
91 with open(path, "w", encoding="utf-8", newline="\n") as f:
92 f.write(body)
93 digest = hashlib.sha256(body.encode("utf-8")).hexdigest()
94 with open(path + ".sha256", "w", encoding="utf-8", newline="\n") as f:
95 f.write(f"{digest} {kind}.tsv\n")
96 return digest
97
98
99def main(argv=None) -> int:
100 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
101 sub = ap.add_subparsers(dest="kind", required=True)
102 b = sub.add_parser("branches", help="manifest the old-pr/* branches")
103 b.add_argument("--remote", default="origin", help="remote that carries the old-pr/* refs (default: origin)")
104 i = sub.add_parser("issues", help="manifest the issue index from issue #18")
105 i.add_argument("--index", required=True, help="file holding the issue table (or - for stdin)")
106 for p in (b, i):
107 p.add_argument("--out", default="docs/history", help="output directory (default: docs/history)")
108 a = ap.parse_args(argv)
109
110 if a.kind == "branches":
111 rows = branches(a.remote)
112 digest = write_tsv(a.out, "old-pr", ("number", "tip", "author_date", "author", "subject"), rows)
113 print(f"{len(rows)} old pull request branches, sha256 {digest}")
114 else:
115 text = sys.stdin.read() if a.index == "-" else open(a.index, encoding="utf-8").read()
116 rows = issues(text)
117 digest = write_tsv(a.out, "issues", ("number", "title", "author", "labels"), rows)
118 print(f"{len(rows)} old issues, sha256 {digest}")
119 return 0
120
121
122if __name__ == "__main__":
123 sys.exit(main())
diff --git a/scripts/fetch_vkd3d_proton.py b/scripts/fetch_vkd3d_proton.py
new file mode 100755
index 000000000..bf4bb9c5d
--- /dev/null
+++ b/scripts/fetch_vkd3d_proton.py
@@ -0,0 +1,76 @@
1#!/usr/bin/env python3
2"""Fetch the pinned VKD3D-Proton release for Leonida's Linux package.
3
4On Linux the D3D12 runtime (victory/, a Windows program) runs under Wine, and Wine needs a Direct3D 12 implementation:
5VKD3D-Proton (LGPL-2.1-or-later, https://github.com/HansKristian-Work/vkd3d-proton) translates it to Vulkan. This
6tool puts the 64-bit d3d12.dll and d3d12core.dll of one pinned release, with its license and a note on where its
7source is, into the package folder, so a Linux player needs nothing else for D3D12 (scripts/play-linux.sh installs
8them into Leonida's own Wine prefix). Every download is checked against the SHA-256 pinned below.
9
10Standard library only (Python 3.14 or newer: compression.zstd reads the release's .tar.zst).
11
12 python -I scripts/fetch_vkd3d_proton.py --out dist/linux/vkd3d-proton
13"""
14import argparse
15import hashlib
16import io
17import os
18import sys
19import tarfile
20import urllib.request
21
22VERSION = "3.1"
23RELEASE = (f"https://github.com/HansKristian-Work/vkd3d-proton/releases/download/v{VERSION}/"
24 f"vkd3d-proton-{VERSION}.tar.zst",
25 "b85ea8219b71093a3924913dd7aae6172333dc0c069983ed510816d67f02120b")
26# The release archive carries no license text: the notice and the LGPL-2.1 from the same tag.
27LICENSE_FILES = {
28 "COPYING": (f"https://raw.githubusercontent.com/HansKristian-Work/vkd3d-proton/v{VERSION}/COPYING",
29 "f51ad4bf5a3bd2b5f383fe28150b23d01e6f5d7b620b194150e7c6a620c43c1f"),
30 "LICENSE": (f"https://raw.githubusercontent.com/HansKristian-Work/vkd3d-proton/v{VERSION}/LICENSE",
31 "dc626520dcd53a22f727af3ee42c770e56c97a64fe3adb063799d8ab032fe551"),
32}
33DLLS = ("d3d12.dll", "d3d12core.dll")
34
35
36def fetch(url, sha256):
37 with urllib.request.urlopen(url, timeout=120) as response:
38 data = response.read()
39 got = hashlib.sha256(data).hexdigest()
40 if got != sha256:
41 raise SystemExit(f"{url}: SHA-256 {got}, expected {sha256}; not used")
42 return data
43
44
45def main():
46 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
47 parser.add_argument("--out", default=os.path.join("dist", "linux", "vkd3d-proton"),
48 help="folder for the DLLs, license and source note (created)")
49 args = parser.parse_args()
50 try:
51 import compression.zstd as zstd
52 except ImportError:
53 raise SystemExit("Python 3.14 or newer is needed (compression.zstd reads the .tar.zst release)")
54
55 os.makedirs(args.out, exist_ok=True)
56 archive = zstd.decompress(fetch(*RELEASE))
57 with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
58 for name in DLLS:
59 member = tar.getmember(f"vkd3d-proton-{VERSION}/x64/{name}")
60 with tar.extractfile(member) as src, open(os.path.join(args.out, name), "wb") as dst:
61 dst.write(src.read())
62 for name, (url, sha256) in LICENSE_FILES.items():
63 with open(os.path.join(args.out, name), "wb") as dst:
64 dst.write(fetch(url, sha256))
65 with open(os.path.join(args.out, "SOURCE.txt"), "w", encoding="utf-8", newline="\n") as note:
66 note.write(f"VKD3D-Proton {VERSION}, unmodified 64-bit d3d12.dll and d3d12core.dll from\n"
67 f"{RELEASE[0]}\n(SHA-256 {RELEASE[1]}).\n"
68 f"Licensed under the GNU Lesser General Public License 2.1 or later (LICENSE, COPYING).\n"
69 f"Source: https://github.com/HansKristian-Work/vkd3d-proton/tree/v{VERSION}\n")
70 print(f"VKD3D-Proton {VERSION}: {', '.join(DLLS)}, LICENSE, COPYING and SOURCE.txt in {args.out}")
71 return 0
72
73
74if __name__ == "__main__":
75 sys.stdout.reconfigure(errors="replace")
76 sys.exit(main())
diff --git a/scripts/launcher_python.sh b/scripts/launcher_python.sh
new file mode 100644
index 000000000..a469f34ec
--- /dev/null
+++ b/scripts/launcher_python.sh
@@ -0,0 +1,40 @@
1# Sourced by the POSIX launchers. Search for versioned Python names on PATH so a new Python minor
2# release works even if the system's unversioned python3 still points to an older interpreter.
3exec_leonida_python() {
4 remaining=${PATH-}
5 best_minor=11
6 best_python=
7 while :; do
8 directory=${remaining%%:*}
9 for candidate in "${directory:-.}"/python3.*; do
10 [ -f "$candidate" ] && [ -x "$candidate" ] || continue
11 name=${candidate##*/}
12 minor=${name#python3.}
13 case $minor in
14 0*|''|*[!0-9]*) continue ;;
15 esac
16 # Invoke by name to keep PATH precedence if that version appears in more than one directory.
17 if [ "$minor" -gt "$best_minor" ] 2>/dev/null && leonida_python_is_supported "$name"; then
18 best_minor=$minor
19 best_python=$name
20 fi
21 done
22 case $remaining in
23 *:*) remaining=${remaining#*:} ;;
24 *) break ;;
25 esac
26 done
27
28 if [ -n "$best_python" ]; then
29 exec "$best_python" -I "$@"
30 fi
31 for name in python3 python; do
32 if leonida_python_is_supported "$name"; then
33 exec "$name" -I "$@"
34 fi
35 done
36}
37
38leonida_python_is_supported() {
39 "$1" -I -c 'import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)' >/dev/null 2>&1
40}
diff --git a/scripts/merge_check.py b/scripts/merge_check.py
index e270cbe00..5499da29c 100644
--- a/scripts/merge_check.py
+++ b/scripts/merge_check.py
@@ -41,13 +41,13 @@ class GitError(Exception):
41 pass 41 pass
42 42
43 43
44def git(repo, *args, check=True): 44def git(repo, *args, check=True, stdout_errors="replace"):
45 try: 45 try:
46 r = subprocess.run(["git", "-C", repo, *args], capture_output=True) 46 r = subprocess.run(["git", "-C", repo, *args], capture_output=True)
47 except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback 47 except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback
48 raise GitError(f"cannot run git: {e.strerror or e}") from None 48 raise GitError(f"cannot run git: {e.strerror or e}") from None
49 # Decode without universal-newline translation: a bare CR inside a Git line is content. 49 # Decode without universal-newline translation: a bare CR inside a Git line is content.
50 r.stdout = r.stdout.decode("utf-8", "replace") 50 r.stdout = r.stdout.decode("utf-8", stdout_errors)
51 r.stderr = r.stderr.decode("utf-8", "replace") 51 r.stderr = r.stderr.decode("utf-8", "replace")
52 if check and r.returncode != 0: 52 if check and r.returncode != 0:
53 raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}") 53 raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}")
@@ -132,7 +132,8 @@ 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 # Keep undecodable bytes distinct while comparing lines from legacy-encoded documents.
136 r = git(repo, "show", f"{rev}:{path}", "--", stdout_errors="surrogateescape")
136 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] 137 lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())]
137 content = [text for _, text in lines] 138 content = [text for _, text in lines]
138 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) 139 return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1))
@@ -153,7 +154,8 @@ def duplicates(repo, main, tree, min_length, block=3):
153 if before[run] and after[run] > before[run]: 154 if before[run] and after[run] > before[run]:
154 marked.update(number for number, _ in window) 155 marked.update(number for number, _ in window)
155 if marked: 156 if marked:
156 found[path] = [text for number, text in after_lines if number in marked] 157 found[path] = [text.encode("utf-8", "surrogateescape").decode("utf-8", "replace")
158 for number, text in after_lines if number in marked]
157 return found 159 return found
158 160
159 161
diff --git a/scripts/play-d3d12.ps1 b/scripts/play-d3d12.ps1
new file mode 100644
index 000000000..6c6396fc2
--- /dev/null
+++ b/scripts/play-d3d12.ps1
@@ -0,0 +1,93 @@
1# Starts the title on Leonida's D3D12 runtime (d3d12/, from trustno1-coder/VIctory-NVIDIA) on Windows.
2# The Vulkan renderer stays scripts\play.ps1; Linux uses scripts\play-linux.sh (docs/linux.md).
3#
4# powershell -ExecutionPolicy Bypass -File scripts\play-d3d12.ps1 -Game <folder with game_scarlett_master.exe>
5#
6# By default the game runs as on an Xbox Series X, rendering 2560x1440 (render scale 2/3 of its 3840x2160 output)
7# with its own temporal upscaler; -SeriesS runs the lighter Series S profile instead, where the game renders its own
8# 720p picture and DLSS takes it to 1080p. -Resolution sets the rendered height (Series X: 1080 or 1440). DLSS and DLSS
9# frame generation need a few of NVIDIA's own files that no repository may carry: d3d12\Get-NVIDIA-DLSS.cmd fetches
10# them from NVIDIA's GitHub once (about 70 MB). Without them the picture is stretched to the screen instead.
11# In the game: F1 = settings (frame generation, frame-rate cap, DLSS preset ...), F3 = the numbers panel.
12#
13# -SmoothMotion starts leonida_sm.exe, the copy NVIDIA's Smooth Motion profile is set for (scripts\smooth-motion.ps1
14# -State on sets it): the driver shows twice the frames the game renders (RTX 40 and 50). Not the
15# default: the one start made that way on 2026-11-27 ended 2.4 s in with the title's own breakpoint
16# (0x80000003 in its main loop), and the next start without it ran. Not looked into yet.
17# -NoDlss the picture is stretched instead of going through DLSS
18# -Dlss DLSS makes the output, on Series X too: quality (rendered at 1440 lines of the 2160), balanced
19# (1296), performance (1080) or ultra (720). Leave -Resolution out with it.
20# -FrameGen DLSS frame generation: 2 shows twice the frames rendered (up to 6 where the card does more). On
21# Series X it needs the DLSS upscale and turns -Dlss quality on unless a mode is given.
22# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9, shown
23# centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch).
24# -Resolution the older path: the game renders at this height and the title's own upscaler does the rest
25# -RayTracing the title's real ray tracing (slower; shaders build for minutes the first time)
26# -Capture F9 in the game saves that frame and the pictures it drew
27# -NoPrecompile start at once: by default every shader is translated and the pipelines earlier runs drew with are
28# made before the title starts (minutes the first time, seconds after)
29# -Log the runtime's log goes to a file under %LOCALAPPDATA%\Leonida\logs
30# -DryRun prints the settings this start would run with and stops: nothing is built or started
31#
32# Builds d3d12/ when it is missing (d3d12\scripts\build-nvidia.ps1: the diag profile, with DLSS when NVIDIA's files
33# are there), keeps the caches and saves under -Data, and hands everything else to d3d12\scripts\play-nvidia.ps1:
34# -SeriesX, -Quality, -Adapter and -More pass through. Nothing goes online.
35param(
36 [Parameter(Mandatory = $true)][string]$Game,
37 [string]$Data = (Join-Path $env:LOCALAPPDATA "Leonida\d3d12"),
38 [switch]$SeriesX,
39 [switch]$SeriesS,
40 [switch]$Quality,
41 [ValidateSet('', '2160', '1440', '1080', '720', '540', '480')][string]$Resolution = '',
42 [ValidateSet('', 'quality', 'balanced', 'performance', 'ultra')][string]$Dlss = '',
43 [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0,
44 [string]$Aspect = '',
45 [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '',
46 [string]$Adapter = '',
47 [hashtable]$More = @{},
48 [switch]$Rebuild,
49 [switch]$SmoothMotion,
50 [switch]$NoSmoothMotion,
51 [switch]$NoDlss,
52 [switch]$RayTracing,
53 [switch]$Capture,
54 [switch]$NoPrecompile,
55 [switch]$Log,
56 [switch]$DryRun
57)
58
59$ErrorActionPreference = "Stop"
60$repo = Split-Path -Parent $PSScriptRoot
61$runtime = Join-Path $repo "d3d12"
62$exe = Join-Path $runtime "target\diag\leonida.exe"
63$title = Join-Path $Game "game_scarlett_master.exe"
64if (-not (Test-Path $title)) { throw "missing: $title" }
65if (-not $DryRun -and ($Rebuild -or -not (Test-Path $exe))) {
66 & (Join-Path $runtime "scripts\build-nvidia.ps1")
67 if ($LASTEXITCODE -ne 0) { throw "cargo build failed ($LASTEXITCODE)" }
68}
69# A shader cache of its own: one filled before the renderer changed (cache\) does not fit its pipelines.
70New-Item -ItemType Directory -Force (Join-Path $Data "cache-2"), (Join-Path $Data "data") | Out-Null
71$env:LEONIDA_GAME_DIR = (Resolve-Path $Game).Path
72$env:LEONIDA_CACHE_DIR = Join-Path $Data "cache-2"
73$env:LEONIDA_DATA_DIR = Join-Path $Data "data"
74
75# Leonida: Smooth Motion only with -SmoothMotion (it was the default for one start, which the title did not
76# survive; -NoSmoothMotion is kept and means the same as leaving -SmoothMotion out).
77$launch = @{ Exe = $title; Build = 'diag'; NoSmoothMotion = (-not $SmoothMotion); More = $More }
78# Leonida: the Series X profile is the default (the user's call: 1080p-1440p as on the bigger consoles).
79if (-not $SeriesS) {
80 $launch.SeriesX = $true
81 # 1440 lines and the title's own upscaler, unless DLSS (which frame generation brings with it) makes the output.
82 if (-not $Resolution -and -not $Dlss -and -not $FrameGen) { $Resolution = '1440' }
83}
84if ($Dlss) { $launch.Dlss = $Dlss }
85if ($FrameGen) { $launch.FrameGen = $FrameGen }
86if ($Aspect) { $launch.Aspect = $Aspect }
87if ($PresentScale) { $launch.PresentScale = $PresentScale }
88foreach ($switch in 'Quality', 'NoDlss', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun') {
89 if ($PSBoundParameters[$switch]) { $launch[$switch] = $true }
90}
91if ($Resolution) { $launch.Resolution = $Resolution }
92if ($Adapter) { $launch.Adapter = $Adapter }
93& (Join-Path $runtime "scripts\play-nvidia.ps1") @launch
diff --git a/scripts/play-linux.sh b/scripts/play-linux.sh
new file mode 100755
index 000000000..e7d48d78e
--- /dev/null
+++ b/scripts/play-linux.sh
@@ -0,0 +1,71 @@
1#!/bin/sh
2# Starts Leonida's D3D12 runtime (d3d12/, a Windows program) on Linux under Wine, with the VKD3D-Proton that comes in
3# the package (scripts/fetch_vkd3d_proton.py puts it in vkd3d-proton/ beside this script), so nothing else needs to be
4# downloaded for Direct3D 12. Wine itself and a Vulkan driver (Mesa or NVIDIA's) are the system's.
5#
6# ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x]
7#
8# Leonida keeps its own Wine prefix (LEONIDA_WINEPREFIX, default ~/.local/share/leonida/prefix): the bundled
9# d3d12.dll and d3d12core.dll are installed there and preferred over Wine's (WINEDLLOVERRIDES), so no other prefix
10# is changed. LEONIDA_* variables already set win over the defaults below.
11set -eu
12
13if [ $# -lt 1 ]; then
14 echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x]" >&2
15 exit 2
16fi
17game_exe=$1
18shift
19console=series-s
20if [ "${1:-}" = "--series-x" ]; then console=series-x; fi
21[ -f "$game_exe" ] || { echo "No $game_exe" >&2; exit 1; }
22
23here=$(cd "$(dirname "$0")" && pwd)
24runtime=${LEONIDA_RUNTIME:-$here/leonida.exe}
25vkd3d=${LEONIDA_VKD3D:-$here/vkd3d-proton}
26[ -f "$runtime" ] || { echo "No $runtime (the Windows build of d3d12/)" >&2; exit 1; }
27for dll in d3d12.dll d3d12core.dll; do
28 [ -f "$vkd3d/$dll" ] || { echo "No $vkd3d/$dll: run scripts/fetch_vkd3d_proton.py when packaging" >&2; exit 1; }
29done
30command -v wine >/dev/null 2>&1 || { echo "Wine is needed (your distribution's wine package, or Proton's)" >&2; exit 1; }
31
32data=${XDG_DATA_HOME:-$HOME/.local/share}/leonida
33export WINEPREFIX=${LEONIDA_WINEPREFIX:-$data/prefix}
34export WINEARCH=win64
35if [ ! -d "$WINEPREFIX/drive_c/windows/system32" ]; then
36 echo "Leonida: making its Wine prefix in $WINEPREFIX"
37 mkdir -p "$WINEPREFIX"
38 WINEDEBUG=-all wineboot -u >/dev/null 2>&1
39fi
40# The bundled VKD3D-Proton, copied in when it is missing or differs (a new package).
41system32=$WINEPREFIX/drive_c/windows/system32
42for dll in d3d12.dll d3d12core.dll; do
43 if ! cmp -s "$vkd3d/$dll" "$system32/$dll"; then cp "$vkd3d/$dll" "$system32/$dll"; fi
44done
45export WINEDLLOVERRIDES="d3d12,d3d12core=n${WINEDLLOVERRIDES:+;$WINEDLLOVERRIDES}"
46
47# Where the title's files are, and where the caches and saves go.
48export LEONIDA_GAME_DIR=${LEONIDA_GAME_DIR:-$(cd "$(dirname "$game_exe")" && pwd)}
49export LEONIDA_CACHE_DIR=${LEONIDA_CACHE_DIR:-$data/cache}
50export LEONIDA_DATA_DIR=${LEONIDA_DATA_DIR:-$data/data}
51mkdir -p "$LEONIDA_CACHE_DIR" "$LEONIDA_DATA_DIR"
52
53# The settings scripts/play-nvidia.ps1 measured (d3d12/README.md), as defaults.
54set_default() { eval "[ -n \"\${$1:-}\" ] || export $1=\"$2\""; }
55set_default LEONIDA_TEXTURE_NO_WAIT 1
56set_default LEONIDA_RELAY 2
57set_default LEONIDA_CARD_STEPS 2
58set_default LEONIDA_DYNAMIC_SLOTS 524288
59set_default LEONIDA_PIPELINE_WAIT_MS 10000
60set_default LEONIDA_RENDER_SCALE 0.5
61set_default LEONIDA_OWN_UPSCALER 1
62set_default LEONIDA_BVH_MISS 1
63set_default LEONIDA_CARD_BUFFERS_MIN_MB 1
64set_default LEONIDA_CARD_BUFFERS_MB 1536
65set_default LEONIDA_COMPOSE 1
66set_default LEONIDA_NAN_SCRUB 1
67set_default LEONIDA_AMBIENT_AIR 1.5
68set_default LEONIDA_AMBIENT_MOST 2
69
70echo "Leonida: $console under Wine with the bundled VKD3D-Proton ($(head -n 1 "$vkd3d/SOURCE.txt" 2>/dev/null || echo bundled))"
71exec wine "$runtime" run "$game_exe" --execute --console "$console"
diff --git a/scripts/play.ps1 b/scripts/play.ps1
new file mode 100644
index 000000000..76b9f5139
--- /dev/null
+++ b/scripts/play.ps1
@@ -0,0 +1,59 @@
1# Starts the title on Leonida's Vulkan renderer with the settings that work today.
2#
3# powershell -ExecutionPolicy Bypass -File scripts\play.ps1 -Game <game folder> -Work <make_game work folder>
4#
5# Every setting is an environment variable the runtime reads (docs/port_status.md); one already set in the shell wins
6# over the default here. Nothing is downloaded and nothing goes online.
7param(
8 [Parameter(Mandatory = $true)][string]$Game, # the folder with game_scarlett_master.exe
9 [Parameter(Mandatory = $true)][string]$Work, # make_game.py's --work folder (its shaders\spirv is used)
10 [string]$Overlay = "", # folder for the title's writable files (default: <Work>\overlay)
11 [string]$Saves = "", # save folder (default: <Work>\saves)
12 [string]$DisplayMode = "2560x1440",
13 [string]$Aspect = "", # LEONIDA_ASPECT: 21:9, 32:9, 43:18, auto (docs/ultrawide.md)
14 [string]$PresentScale = "", # LEONIDA_PRESENT_SCALE: fit or stretch (fit with -Aspect)
15 [string]$Build = "", # the runtime build folder (default: runtime\build-vk\RelWithDebInfo)
16 [switch]$Trace # write a startup trace beside the logs
17)
18
19$ErrorActionPreference = "Stop"
20$repo = Split-Path -Parent $PSScriptRoot
21if (-not $Build) { $Build = Join-Path $repo "runtime\build-vk\RelWithDebInfo" }
22if (-not $Overlay) { $Overlay = Join-Path $Work "overlay" }
23if (-not $Saves) { $Saves = Join-Path $Work "saves" }
24$exe = Join-Path $Build "gta6rt.exe"
25$title = Join-Path $Game "game_scarlett_master.exe"
26foreach ($path in @($exe, $title, (Join-Path $Work "shaders\spirv\index.json"))) {
27 if (-not (Test-Path $path)) { throw "missing: $path (build the runtime and run make_game.py first)" }
28}
29New-Item -ItemType Directory -Force $Overlay, $Saves | Out-Null
30
31function Set-Default([string]$Name, [string]$Value) {
32 if (-not [Environment]::GetEnvironmentVariable($Name)) { [Environment]::SetEnvironmentVariable($Name, $Value) }
33}
34Set-Default "LEONIDA_D3D12" "vulkan"
35Set-Default "LEONIDA_SHADERS" (Join-Path $Work "shaders\spirv")
36Set-Default "LEONIDA_SAVE_DIR" $Saves
37Set-Default "LEONIDA_DISPLAY_MODE" $DisplayMode
38if ($Aspect) { Set-Default "LEONIDA_ASPECT" $Aspect }
39if ($PresentScale) { Set-Default "LEONIDA_PRESENT_SCALE" $PresentScale }
40Set-Default "LEONIDA_KEYBOARD_PAD" "1" # keyboard and mouse as a pad while the window has focus
41# The title's soft asserts (an int3 the console build carries on from) are stepped over and logged; the one known
42# site is game+0x4ffd879 after the start screen (docs/port_status.md, open items).
43Set-Default "LEONIDA_SKIP_INT3" "1"
44$tables = Join-Path $repo "victory\crates\victory-formats\src\bcpack-tables.bin"
45if (Test-Path $tables) { Set-Default "LEONIDA_BCPACK_TABLES" $tables }
46
47$logs = Join-Path $Work "logs"
48New-Item -ItemType Directory -Force $logs | Out-Null
49$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
50$runArgs = @("--run", "`"$title`"", "--game-dir", "`"$Game`"", "--overlay", "`"$Overlay`"")
51# LEONIDA_SKIP_INT3 needs the trace's exception handler, so a trace is always written; -Trace only says so.
52$runArgs += @("--trace", "`"$(Join-Path $logs "trace-$stamp.jsonl")`"")
53if ($Trace) { Write-Host "trace: $(Join-Path $logs "trace-$stamp.jsonl")" }
54Write-Host "Leonida: $title"
55Write-Host "log: $(Join-Path $logs "run-$stamp.log")"
56$process = Start-Process -FilePath $exe -ArgumentList $runArgs -WorkingDirectory $Build -NoNewWindow -PassThru `
57 -RedirectStandardError (Join-Path $logs "run-$stamp.log") -RedirectStandardOutput (Join-Path $logs "out-$stamp.log")
58$process.WaitForExit()
59Write-Host ("exit code 0x{0:X8}" -f $process.ExitCode)
diff --git a/scripts/port_ctl.py b/scripts/port_ctl.py
new file mode 100644
index 000000000..9a7e595d0
--- /dev/null
+++ b/scripts/port_ctl.py
@@ -0,0 +1,320 @@
1#!/usr/bin/env python3
2"""Drive a VIctory run of the title for testing: start, press, shot, fps, stop.
3
4Everything the run writes (logs, frame captures, saves, caches) goes under a
5work folder outside the repository (``--work``, default ``G:\\gta6port`` or
6``LEONIDA_PORT_WORK``). Nothing from the game is read or written here beyond
7what the runtime itself does.
8
9 python -I scripts/port_ctl.py start --name run1 # launch the title
10 python -I scripts/port_ctl.py press Enter # tap A on the stand-in pad
11 python -I scripts/port_ctl.py press W 3000 # hold left stick up for 3 s
12 python -I scripts/port_ctl.py shot # save the next presented frame
13 python -I scripts/port_ctl.py fps # latest frame-rate lines
14 python -I scripts/port_ctl.py status # running?, fps, last warnings
15 python -I scripts/port_ctl.py stop # end the run
16
17Keys (the stand-in pad's table): sticks W A S D / I J K L, triggers Z C,
18buttons X Y Q E F H, Enter (A), Back (B), Esc (Menu), Tab (View),
19Up Down Left Right (D-pad). The runtime reads the pad file only while no real
20controller is connected.
21"""
22
23import argparse
24import json
25import os
26import re
27import subprocess
28import sys
29import time
30
31REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
32VICTORY = os.path.join(REPO, "victory")
33DEFAULT_WORK = os.environ.get("LEONIDA_PORT_WORK", r"G:\gta6port")
34DEFAULT_GAME = os.environ.get("LEONIDA_GAME_DIR", os.path.expanduser(r"~\Documents\GTA6"))
35TITLE_EXE = "game_scarlett_master.exe"
36
37FPS_RE = re.compile(r"(\d+(?:\.\d+)?) fps, (\d+(?:\.\d+)?) ms/frame")
38ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
39
40
41def read_log(log):
42 try:
43 with open(log, encoding="utf-8", errors="replace") as f:
44 return [ANSI_RE.sub("", ln) for ln in f]
45 except OSError:
46 return []
47
48
49def paths(work):
50 ctl = os.path.join(work, "ctl")
51 return {
52 "work": work,
53 "ctl": ctl,
54 "state": os.path.join(ctl, "state.json"),
55 "pad": os.path.join(ctl, "pad.txt"),
56 "shot": os.path.join(ctl, "shot.txt"),
57 "logs": os.path.join(work, "logs"),
58 "captures": os.path.join(work, "captures"),
59 "cache": os.path.join(work, "cache"),
60 "data": os.path.join(work, "data"),
61 }
62
63
64def load_state(p):
65 try:
66 with open(p["state"], encoding="utf-8") as f:
67 return json.load(f)
68 except (OSError, ValueError):
69 return {}
70
71
72def save_state(p, state):
73 os.makedirs(p["ctl"], exist_ok=True)
74 with open(p["state"], "w", encoding="utf-8", newline="\n") as f:
75 json.dump(state, f, indent=1)
76
77
78def alive(pid):
79 if not pid:
80 return False
81 out = subprocess.run(
82 ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"],
83 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
84 ).stdout
85 return f'"{pid}"' in out
86
87
88def write_atomic(path, text):
89 tmp = path + ".tmp"
90 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
91 f.write(text)
92 os.replace(tmp, path)
93
94
95def cmd_start(args, p):
96 state = load_state(p)
97 if alive(state.get("pid")):
98 print(f"a run is already going: pid {state['pid']} ({state.get('name')}); stop it first")
99 return 1
100 exe = args.exe or os.path.join(VICTORY, "target", args.profile, "victory.exe")
101 if not os.path.isfile(exe):
102 print(f"no runtime at {exe}; build it first (cargo build --release -p victory --features diagnostics --bins)")
103 return 1
104 title = os.path.join(args.game, TITLE_EXE)
105 if not os.path.isfile(title):
106 print(f"no title executable at {title}")
107 return 1
108 name = args.name or time.strftime("run-%Y%m%d-%H%M%S")
109 for key in ("ctl", "logs", "captures", "cache", "data"):
110 os.makedirs(p[key], exist_ok=True)
111 captures = os.path.join(p["captures"], name)
112 os.makedirs(captures, exist_ok=True)
113 data = args.data or p["data"]
114 os.makedirs(data, exist_ok=True)
115 # Fresh command files: the runtime only acts on increasing numbers.
116 for f in (p["pad"], p["shot"]):
117 if os.path.exists(f):
118 os.remove(f)
119 env = dict(os.environ)
120 env.update({
121 "VICTORY_GAME_DIR": args.game,
122 "VICTORY_CACHE_DIR": p["cache"],
123 "VICTORY_DATA_DIR": data,
124 "VICTORY_LOG": args.log,
125 "VICTORY_CAPTURE": captures,
126 "VICTORY_CAPTURE_REQUEST": p["shot"],
127 "VICTORY_MOVEMENT_FILE": p["pad"],
128 })
129 if args.world:
130 env["VICTORY_CAPTURE_WORLD"] = "1"
131 for item in args.env or []:
132 k, _, v = item.partition("=")
133 env[k] = v
134 log = os.path.join(p["logs"], f"{name}.log")
135 cmd = [exe, "run", title, "--execute", "--console", args.console]
136 flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
137 # The runtime writes its own bytes here; newline only keeps the repository's line-ending rule.
138 with open(log, "w", encoding="utf-8", newline="\n") as out:
139 proc = subprocess.Popen(cmd, cwd=args.game, env=env, stdout=out, stderr=subprocess.STDOUT,
140 stdin=subprocess.DEVNULL, creationflags=flags)
141 state = {
142 "pid": proc.pid, "name": name, "log": log, "captures": captures, "started": time.time(),
143 "pad_seq": 0, "shot_seq": 0, "cmd": cmd,
144 "env": {k: v for k, v in env.items() if k.startswith("VICTORY_")},
145 }
146 save_state(p, state)
147 print(f"started pid {proc.pid} as {name}\n log {log}\n captures {captures}")
148 return 0
149
150
151def cmd_press(args, p):
152 state = load_state(p)
153 seq = int(time.time() * 1000)
154 seq = max(seq, state.get("pad_seq", 0) + 1)
155 write_atomic(p["pad"], f"{seq} {args.key} {args.ms}")
156 state["pad_seq"] = seq
157 save_state(p, state)
158 print(f"pressed {args.key} for {args.ms} ms (sequence {seq})")
159 if args.wait:
160 time.sleep(args.ms / 1000.0 + 0.4)
161 return 0
162
163
164def newest_png(folder, since):
165 best = None
166 try:
167 for entry in os.scandir(folder):
168 if entry.name.endswith(".png") and entry.stat().st_mtime >= since:
169 if best is None or entry.stat().st_mtime > best.stat().st_mtime:
170 best = entry
171 except OSError:
172 return None
173 return best.path if best else None
174
175
176def shrink(path, width):
177 """A copy of the capture `width` pixels wide beside it (needs Pillow); the capture itself otherwise."""
178 try:
179 from PIL import Image
180 except ImportError:
181 return path
182 with Image.open(path) as im:
183 height = max(1, round(im.height * width / im.width))
184 small = im.resize((width, height), Image.LANCZOS)
185 out = path[:-4] + f"-w{width}.png"
186 small.save(out)
187 return out
188
189
190def cmd_shot(args, p):
191 state = load_state(p)
192 seq = state.get("shot_seq", 0) + 1
193 since = time.time() - 0.5
194 write_atomic(p["shot"], str(seq))
195 state["shot_seq"] = seq
196 save_state(p, state)
197 folder = state.get("captures")
198 deadline = time.time() + args.timeout
199 while time.time() < deadline:
200 found = newest_png(folder, since)
201 if found:
202 time.sleep(0.5) # let the writer finish
203 if args.small:
204 found = shrink(found, args.small)
205 print(found)
206 return 0
207 time.sleep(0.25)
208 print(f"no new frame in {folder} after {args.timeout} s (the title may not be presenting)")
209 return 1
210
211
212def fps_lines(log, count):
213 hits = [ln.rstrip() for ln in read_log(log) if FPS_RE.search(ln)]
214 return hits[-count:]
215
216
217def summarize(line):
218 m = FPS_RE.search(line)
219 if not m:
220 return line
221 tail = line[m.start():]
222 keep = []
223 for pattern in (r"\d+(?:\.\d+)? fps, \d+(?:\.\d+)? ms/frame", r"\(\S+ preparing", r"[\d.]+ on the GPU",
224 r"\d+ draws/frame", r"dropped \d+ without a host pipeline \(\d+ being made\)",
225 r"cpu [\d.]+% gpu \d+% busy ram \d+ MB"):
226 mm = re.search(pattern, tail)
227 if mm:
228 keep.append(mm.group(0))
229 stamp = line[:m.start()].split(" ")[0]
230 return f"{stamp} " + " | ".join(keep)
231
232
233def cmd_fps(args, p):
234 state = load_state(p)
235 log = args.log or state.get("log")
236 if not log:
237 print("no run recorded")
238 return 1
239 for line in fps_lines(log, args.count):
240 print(line if args.full else summarize(line))
241 return 0
242
243
244def cmd_status(args, p):
245 state = load_state(p)
246 if not state:
247 print("no run recorded")
248 return 1
249 up = time.time() - state.get("started", time.time())
250 print(f"{state.get('name')}: pid {state.get('pid')} {'running' if alive(state.get('pid')) else 'NOT running'}, "
251 f"up {int(up // 60)}:{int(up % 60):02d}")
252 for line in fps_lines(state["log"], 3):
253 print(" " + summarize(line))
254 lines = read_log(state["log"])
255 bad = [ln.rstrip() for ln in lines if re.search(r"\b(ERROR|WARN)\b|panicked|crash|DEVICE_HUNG|DEVICE_REMOVED", ln)]
256 for line in bad[-args.warnings:]:
257 print(" ! " + line[:300])
258 return 0
259
260
261def cmd_stop(args, p):
262 state = load_state(p)
263 pid = state.get("pid")
264 if not alive(pid):
265 print("no run is going")
266 return 0
267 subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
268 for _ in range(40):
269 if not alive(pid):
270 break
271 time.sleep(0.25)
272 print(f"stopped pid {pid} ({state.get('name')})")
273 return 0
274
275
276def main():
277 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
278 ap.add_argument("--work", default=DEFAULT_WORK, help="work folder outside the repository")
279 sub = ap.add_subparsers(dest="command", required=True)
280
281 s = sub.add_parser("start", help="launch the title under VIctory")
282 s.add_argument("--name")
283 s.add_argument("--game", default=DEFAULT_GAME)
284 s.add_argument("--exe", help="runtime executable (default: victory/target/<profile>/victory.exe)")
285 s.add_argument("--profile", default="release")
286 s.add_argument("--console", default="series-x", choices=["series-x", "series-s"])
287 s.add_argument("--log", default="info", help="VICTORY_LOG filter")
288 s.add_argument("--data", help="data folder (saves); default <work>/data")
289 s.add_argument("--world", action="store_true", help="also capture world frames (VICTORY_CAPTURE_WORLD)")
290 s.add_argument("--env", action="append", help="extra K=V for the run (repeatable)")
291
292 s = sub.add_parser("press", help="press a stand-in pad key")
293 s.add_argument("key")
294 s.add_argument("ms", nargs="?", type=int, default=200)
295 s.add_argument("--wait", action="store_true", help="return after the hold ends")
296
297 s = sub.add_parser("shot", help="save the next presented frame and print its path")
298 s.add_argument("--timeout", type=float, default=30.0)
299 s.add_argument("--small", type=int, default=0, metavar="WIDTH",
300 help="also write a copy this many pixels wide and print its path (needs Pillow)")
301
302 s = sub.add_parser("fps", help="latest frame-rate lines of the run's log")
303 s.add_argument("--count", type=int, default=5)
304 s.add_argument("--log")
305 s.add_argument("--full", action="store_true")
306
307 s = sub.add_parser("status", help="whether the run is going, its fps and last warnings")
308 s.add_argument("--warnings", type=int, default=5)
309
310 sub.add_parser("stop", help="end the run")
311
312 args = ap.parse_args()
313 p = paths(args.work)
314 return {"start": cmd_start, "press": cmd_press, "shot": cmd_shot, "fps": cmd_fps,
315 "status": cmd_status, "stop": cmd_stop}[args.command](args, p)
316
317
318if __name__ == "__main__":
319 sys.stdout.reconfigure(errors="replace")
320 sys.exit(main())
diff --git a/scripts/run_address_guard_gpu_test.py b/scripts/run_address_guard_gpu_test.py
index f7aa53366..c61b34704 100644
--- a/scripts/run_address_guard_gpu_test.py
+++ b/scripts/run_address_guard_gpu_test.py
@@ -68,15 +68,19 @@ def find_tool(build, name):
68def main(argv=None): 68def main(argv=None):
69 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 69 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
70 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), help="folder with vk_compute_test") 70 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), help="folder with vk_compute_test")
71 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) 71 # No literal default: unset, mc_command() reads LLVM_MC and then finds llvm-mc on PATH or a versioned
72 # Debian/Ubuntu install (llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc), as run_gpu_tests.py does.
73 ap.add_argument("--llvm-mc", default=None)
72 ap.add_argument("--work", default=None, help="keep the intermediate files here") 74 ap.add_argument("--work", default=None, help="keep the intermediate files here")
73 a = ap.parse_args(argv) 75 a = ap.parse_args(argv)
74 vk_compute = find_tool(a.build, "vk_compute_test") 76 vk_compute = find_tool(a.build, "vk_compute_test")
75 if not vk_compute: 77 if not vk_compute:
76 print(f"SKIP: no vk_compute_test under {a.build}") 78 print(f"SKIP: no vk_compute_test under {a.build}")
77 return 77 79 return 77
78 if not shutil.which(a.llvm_mc.split()[0]): 80 import mc_command
79 print(f"SKIP: {a.llvm_mc} not found") 81 mc = mc_command.mc_command(a.llvm_mc)
82 if not shutil.which(mc[0]):
83 print(f"SKIP: {' '.join(mc)} not found")
80 return 77 84 return 77
81 sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) 85 sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders"))
82 sys.path.insert(0, os.path.join(ROOT, "scripts")) 86 sys.path.insert(0, os.path.join(ROOT, "scripts"))
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py
index 60e968783..1b1c9d492 100644
--- a/scripts/run_gpu_tests.py
+++ b/scripts/run_gpu_tests.py
@@ -29,7 +29,7 @@ from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_
29 fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported) 29 fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported)
30from compute_fixture import compute_header 30from compute_fixture import compute_header
31from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) 31from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test)
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, 32from check import (CS_SMEM_VCC, CMPX_CLASS_WORDS, CVT_F32_SAT_CASES, CVT_PK_U8_WORDS, PK_MUL_LO_WORDS, PK_MUL_LO_ENV, GRADIENT_TESTS, TEST_PROGRAMS, TEXTURE_MIP_DEPENDENCIES,
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, 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,
34 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)
35from check import SIGNED_MIP_TEST, UINT_MIP_TEST 35from check import SIGNED_MIP_TEST, UINT_MIP_TEST
@@ -37,6 +37,7 @@ from check import cbv_modulate_test
37from check import IMAGE_STORE_CASES, texture_uav_test 37from check import IMAGE_STORE_CASES, texture_uav_test
38from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS 38from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS
39from 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
40from check import CVT_F16_MODS_WORDS
40from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations 41from 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 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 round_f64_test # the four binary64 roundings on memory-fed inputs
@@ -50,7 +51,7 @@ from check import run_readback
50from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS 51from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS
51from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, 52from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip,
52 unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py 53 unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py
53from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks 54from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem, exp_f32_denorm_problem # pixel producers and checks
54from check import barycentric_problem 55from check import barycentric_problem
55from check import NAN_PAYLOAD_TEST, nan_payload_problem 56from check import NAN_PAYLOAD_TEST, nan_payload_problem
56from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries 57from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries
@@ -102,7 +103,7 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_
102TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here" 103TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here"
103 104
104 105
105def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: 106def assemble_to_s(llvm_mc: str | None, asm_path: str, s_path: str, name: str) -> None:
106 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" 107 """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py."""
107 with open(asm_path, encoding="utf-8") as source: 108 with open(asm_path, encoding="utf-8") as source:
108 raw = source.read() 109 raw = source.read()
@@ -316,13 +317,27 @@ def compute_result(rc: int, msg: str, ok: bool, detail: str) -> tuple[bool | Non
316 return (None, skip) if skip else (ok, detail) 317 return (None, skip) if skip else (ok, detail)
317 318
318 319
320def dump_result(rc: int, msg: str, want: list[int]) -> tuple[bool | None, str]:
321 """(ok, detail) for a vk_compute_test "dump" run whose first len(want) words must be exact. A non-zero exit fails
322 with the program's output even when it printed the words: validation errors come with the right words."""
323 words = dump_words(msg)
324 vals = words[:len(want)] if words else []
325 if rc != 0:
326 detail = f"exit {rc}: {msg or 'no test output'}"
327 else:
328 detail = " ".join(hex(x) for x in vals) if vals else msg
329 return compute_result(rc, msg, rc == 0 and vals == want, detail)
330
331
319def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *, 332def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *,
320 cwd: str | None = None) -> tuple[int, str]: 333 cwd: str | None = None) -> tuple[int, str]:
321 # A hung GPU test program fails its test instead of stalling the suite (check.py, LEONIDA_GPU_TEST_TIMEOUT). 334 # A hung GPU test program fails its test instead of stalling the suite (check.py, LEONIDA_GPU_TEST_TIMEOUT).
322 # gpu=False (the translator over the whole suite) runs without a limit. 335 # gpu=False (the translator over the whole suite) runs without a limit.
323 limit = gpu_test_timeout() if gpu else None 336 limit = gpu_test_timeout() if gpu else None
324 try: 337 try:
325 p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=limit, cwd=cwd) 338 # Keep the exit status and the rest of the log if a tool emits bytes outside the host encoding.
339 p = subprocess.run(cmd, capture_output=True, text=True, errors="backslashreplace",
340 env=env, timeout=limit, cwd=cwd)
326 except subprocess.TimeoutExpired: 341 except subprocess.TimeoutExpired:
327 return 1, timed_out(cmd[0], limit) 342 return 1, timed_out(cmd[0], limit)
328 except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others 343 except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others
@@ -365,7 +380,9 @@ def _device_per_vertex():
365 try: 380 try:
366 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], 381 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")],
367 capture_output=True, text=True, timeout=60) 382 capture_output=True, text=True, timeout=60)
368 answer = json.loads(r.stdout.strip().splitlines()[-1]).get("per_vertex_inputs") 383 report = json.loads(r.stdout.strip().splitlines()[-1])
384 if isinstance(report, dict):
385 answer = report.get("per_vertex_inputs")
369 except (OSError, ValueError, IndexError, subprocess.SubprocessError): 386 except (OSError, ValueError, IndexError, subprocess.SubprocessError):
370 pass 387 pass
371 _PER_VERTEX.append(answer) 388 _PER_VERTEX.append(answer)
@@ -380,7 +397,9 @@ def _device_barycentric_fallback():
380 try: 397 try:
381 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], 398 r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")],
382 capture_output=True, text=True, timeout=60) 399 capture_output=True, text=True, timeout=60)
383 answer = json.loads(r.stdout.strip().splitlines()[-1]).get("barycentric_fallback") 400 report = json.loads(r.stdout.strip().splitlines()[-1])
401 if isinstance(report, dict):
402 answer = report.get("barycentric_fallback")
384 except (OSError, ValueError, IndexError, subprocess.SubprocessError): 403 except (OSError, ValueError, IndexError, subprocess.SubprocessError):
385 pass 404 pass
386 _BARYCENTRIC_FALLBACK.append(answer) 405 _BARYCENTRIC_FALLBACK.append(answer)
@@ -762,8 +781,11 @@ def native_folder(path: str, ansi: str = "mbcs") -> str | None:
762 781
763def main() -> int: 782def main() -> int:
764 ap = argparse.ArgumentParser() 783 ap = argparse.ArgumentParser()
765 ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), 784 # No literal default: unset, mc_command() reads LLVM_MC and then finds llvm-mc on PATH or a versioned
766 help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") 785 # Debian/Ubuntu install (llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc), as the not-found message promises.
786 ap.add_argument("--llvm-mc", default=None,
787 help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' "
788 "(default: LLVM_MC, then llvm-mc on PATH, then the newest llvm-mc-<N>)")
767 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), 789 ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"),
768 help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " 790 help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... "
769 "subfolder that has the test programs is found by itself") 791 "subfolder that has the test programs is found by itself")
@@ -895,6 +917,8 @@ def run_suite(a, work: str) -> int:
895 ]) 917 ])
896 elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): 918 elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"):
897 dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) 919 dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))])
920 elif name in ("ms_w64x_wave_votes", "ms_w64x_wave_loops"): # vertex 64 comes from the second wave: 128 output vertices
921 dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 128, 64, 2))])
898 elif name == "ms_v5_workgroup": 922 elif name == "ms_v5_workgroup":
899 dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) 923 dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))])
900 elif name == "ms_clip": 924 elif name == "ms_clip":
@@ -945,6 +969,8 @@ def run_suite(a, work: str) -> int:
945 cmd.append("--texel-offset-fallback") 969 cmd.append("--texel-offset-fallback")
946 if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py 970 if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py
947 cmd.append("--mesh-compute") 971 cmd.append("--mesh-compute")
972 if os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1": # with --wave64-emulate: one pass per wave
973 cmd.append("--mesh-serial-waves")
948 if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 974 if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1
949 cmd.append("--pc-tail-ubo") 975 cmd.append("--pc-tail-ubo")
950 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) 976 if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md)
@@ -1057,7 +1083,8 @@ def run_suite(a, work: str) -> int:
1057 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. 1083 # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement.
1058 # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either. 1084 # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either.
1059 # The other four pin the SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm). 1085 # The other four pin the SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm).
1060 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) 1086 env = dict(cs_env or os.environ, **PK_MUL_LO_ENV) if name == "cs_pk_mul_lo_const" else cs_env
1087 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env)
1061 want = { 1088 want = {
1062 "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], 1089 "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE],
1063 "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], 1090 "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0],
@@ -1081,10 +1108,7 @@ def run_suite(a, work: str) -> int:
1081 "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], 1108 "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0],
1082 "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], 1109 "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1],
1083 }[name] 1110 }[name]
1084 words = dump_words(msg) 1111 results.append((name,) + dump_result(rc, msg, want))
1085 vals = words[:len(want)] if words else []
1086 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == want,
1087 " ".join(hex(x) for x in vals) if vals else msg))
1088 elif name == "cs_fmt_1010102": 1112 elif name == "cs_fmt_1010102":
1089 problem = fmt_1010102_test(a.build, spirv_dir, cs_env) 1113 problem = fmt_1010102_test(a.build, spirv_dir, cs_env)
1090 results.append((name, not problem, problem or "64/64 dumped words exact")) 1114 results.append((name, not problem, problem or "64/64 dumped words exact"))
@@ -1119,17 +1143,11 @@ def run_suite(a, work: str) -> int:
1119 elif name == "cs_heap_init": 1143 elif name == "cs_heap_init":
1120 # vk_compute_test copies VKC_HEAP_INIT's file into the heap; the shader copies its words at 0x100 to 0. 1144 # vk_compute_test copies VKC_HEAP_INIT's file into the heap; the shader copies its words at 0x100 to 0.
1121 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env())) 1145 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env()))
1122 words = dump_words(msg) 1146 results.append((name,) + dump_result(rc, msg, HEAP_INIT_EXPECTED))
1123 vals = words[:len(HEAP_INIT_EXPECTED)] if words else []
1124 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == HEAP_INIT_EXPECTED,
1125 " ".join(hex(x) for x in vals) if vals else msg))
1126 elif name == "cs_user_sgprs": 1147 elif name == "cs_user_sgprs":
1127 # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. 1148 # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back.
1128 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) 1149 rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV))
1129 words = dump_words(msg) 1150 results.append((name,) + dump_result(rc, msg, USER_SGPRS_WORDS))
1130 vals = words[:len(USER_SGPRS_WORDS)] if words else []
1131 results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS,
1132 " ".join(hex(x) for x in vals) if vals else msg))
1133 elif name == "cs_w32_salu_ext": 1151 elif name == "cs_w32_salu_ext":
1134 detail = salu_ext_test(a.build, spirv_dir, cs_env) 1152 detail = salu_ext_test(a.build, spirv_dir, cs_env)
1135 results.append((name, None if isinstance(detail, Skip) else not detail, 1153 results.append((name, None if isinstance(detail, Skip) else not detail,
@@ -1139,7 +1157,7 @@ def run_suite(a, work: str) -> int:
1139 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names 1157 if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names
1140 results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) 1158 results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)"))
1141 else: 1159 else:
1142 ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, 1160 ok, detail = judge_cs_dump(rc, msg, [0, 0x3FF40000], wave64=False, partial=False, emulated=False,
1143 hexwords=True) 1161 hexwords=True)
1144 results.append((name, ok, detail)) 1162 results.append((name, ok, detail))
1145 elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): 1163 elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"):
@@ -1204,7 +1222,7 @@ def run_suite(a, work: str) -> int:
1204 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. 1222 # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size.
1205 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) 1223 results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated()))
1206 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", 1224 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",
1207 "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", 1225 "cs_w32_cvt_f16_mods", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi",
1208 "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_dpp_w64", 1226 "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_dpp_w64",
1209 "cs_w64_mask_detect", 1227 "cs_w64_mask_detect",
1210 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", 1228 "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute",
@@ -1238,6 +1256,7 @@ def run_suite(a, work: str) -> int:
1238 # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) 1256 # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm)
1239 "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], 1257 "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000],
1240 "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], 1258 "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234],
1259 "cs_w32_cvt_f16_mods": CVT_F16_MODS_WORDS,
1241 "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], 1260 "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D],
1242 "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], 1261 "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE],
1243 # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) 1262 # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header)
@@ -1336,7 +1355,8 @@ def run_suite(a, work: str) -> int:
1336 want = cs_dump_wants[name] 1355 want = cs_dump_wants[name]
1337 # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / 1356 # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute /
1338 # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops / cs_signed_zero_nan, the wave32 1357 # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops / cs_signed_zero_nan, the wave32
1339 # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, 1358 # cs_w32_cvt_f16_mods / cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test:
1359 # ask for a 64-wide subgroup and skip,
1340 # as check.py does, where the device has none 1360 # as check.py does, where the device has none
1341 # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were 1361 # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were
1342 # translated with --wave64-emulate and run on any subgroup size. 1362 # translated with --wave64-emulate and run on any subgroup size.
@@ -1348,7 +1368,7 @@ def run_suite(a, work: str) -> int:
1348 partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") 1368 partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle")
1349 wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", 1369 wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2",
1350 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", 1370 "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop",
1351 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", 1371 "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_cvt_f16_mods",
1352 "cs_w32_lds_subdword", "cs_w32_lds_wide", 1372 "cs_w32_lds_subdword", "cs_w32_lds_wide",
1353 "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", 1373 "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",
1354 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", 1374 "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec",
@@ -1515,6 +1535,7 @@ def run_suite(a, work: str) -> int:
1515 "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), 1535 "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003),
1516 "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), 1536 "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F),
1517 "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), 1537 "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000),
1538 "ps_exp_f32_denorm": (0x01000000, 0x00800000, 0x00000000, 0x00000000),
1518 "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), 1539 "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0),
1519 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) 1540 "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header)
1520 "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) 1541 "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header)
@@ -1523,7 +1544,7 @@ def run_suite(a, work: str) -> int:
1523 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), 1544 "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36),
1524 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), 1545 "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16),
1525 "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), 1546 "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000),
1526 "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 1547 "ps_f64_mods": (0x3FF40000, 0x3FF00000, 0x3FF00000, 0x3FD00000), # needs shaderFloat64
1527 "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 1548 "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64
1528 "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), 1549 "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000),
1529 # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) 1550 # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers)
@@ -1606,6 +1627,9 @@ def run_suite(a, work: str) -> int:
1606 elif name == "ps_ij_computed": 1627 elif name == "ps_ij_computed":
1607 problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) 1628 problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else [])
1608 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" 1629 ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6"
1630 elif name == "ps_exp_f32_denorm_rt":
1631 problem = exp_f32_denorm_problem(read_raw_u32(raw) if os.path.isfile(raw) else [])
1632 ok, detail = not problem, problem or "4096 pixels exact across 64 runtime-dependent inputs"
1609 elif name == "ps_mandelbrot": 1633 elif name == "ps_mandelbrot":
1610 px = read_raw_u32(raw) if os.path.isfile(raw) else [] 1634 px = read_raw_u32(raw) if os.path.isfile(raw) else []
1611 problem = frame_problem(px) or mandelbrot_problem(px) 1635 problem = frame_problem(px) or mandelbrot_problem(px)
@@ -1632,13 +1656,13 @@ def run_suite(a, work: str) -> int:
1632 problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") 1656 problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw")
1633 results.append((name, None if isinstance(problem, Skip) else not problem, 1657 results.append((name, None if isinstance(problem, Skip) else not problem,
1634 problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) 1658 problem or "24/24 workgroup coordinates exact (2 x 3 x 4)"))
1635 elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): 1659 elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_w64x_wave_votes", "ms_w64x_wave_loops"):
1636 raw = os.path.join(raw_dir, f"{name}.raw") 1660 raw = os.path.join(raw_dir, f"{name}.raw")
1637 env = mesh_env(spirv_dir, name, gfx_env) 1661 env = mesh_env(spirv_dir, name, gfx_env)
1638 rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) 1662 rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env)
1639 # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as 1663 # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as
1640 # the wave64 compute dumps are. 1664 # the wave64 compute dumps are.
1641 no64 = (name == "ms_w64x_ballot" and not w64_emulated() and 1665 no64 = (name in ("ms_w64x_ballot", "ms_w64x_wave_votes", "ms_w64x_wave_loops") and not w64_emulated() and
1642 not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) 1666 not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg)))
1643 if rc == UNSUPPORTED: 1667 if rc == UNSUPPORTED:
1644 results.append((name, None, unsupported_skip(msg))) 1668 results.append((name, None, unsupported_skip(msg)))
@@ -1690,14 +1714,15 @@ def run_suite(a, work: str) -> int:
1690 ok, detail = check_flat(raw) 1714 ok, detail = check_flat(raw)
1691 results.append((name, ok, detail)) 1715 results.append((name, ok, detail))
1692 1716
1693 if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed" 1717 if (a.filter or disasm_src is not None) and not results:
1694 names = [os.path.splitext(f)[0] for f in asm_files] 1718 names = [os.path.splitext(f)[0] for f in asm_files]
1695 partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) 1719 partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES)
1696 shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") 1720 shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "")
1697 role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" 1721 role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row"
1698 hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" 1722 hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool"
1699 if all(n.startswith("cs_bench_") for n in names) else "") 1723 if all(n.startswith("cs_bench_") for n in names) else "")
1700 print(f"error: --filter {a.filter!r} selected {shown} but no runnable GPU test cases ({role}){hint}", 1724 selected_by = f"--filter {a.filter!r}" if a.filter else f"--disasm-dir {disasm_src!r}"
1725 print(f"error: {selected_by} selected {shown} but no runnable GPU test cases ({role}){hint}",
1701 file=sys.stderr) 1726 file=sys.stderr)
1702 return 2 1727 return 2
1703 1728
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py
index 514e78133..a25e363bb 100644
--- a/scripts/run_semantic_tests.py
+++ b/scripts/run_semantic_tests.py
@@ -15,10 +15,13 @@ error in serial and parallel runs.
15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in its own process from that folder, so a file sees the same import path as under discover. 15It runs the files `python -m unittest discover -s tests/semantic` finds (`test*.py` by default, and packages below it), each in its own process from that folder, so a file sees the same import path as under discover.
16 16
17The files can run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1, 17The files can run side by side because each one writes only into its own temporary folder; a new test must do the same. With -j 1,
18or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary 18or on a single core, it runs that discover command itself. Prints the output of every failing file, headed by its
19line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. 19exit code (a POSIX signal by name, a known Windows NTSTATUS with its meaning, e.g. 0xC0000005 access violation,
20since a file that crashes prints nothing), and one summary line, and exits 1 if a file fails, none is found, or no
21test ran. Standard library only.
20 22
21The count of tests comes from unittest's own result object, not from its output: a module that writes a line shaped like unittest's summary to stderr - a nested runner, or an atexit handler that runs after unittest's own summary - cannot change it. 23The test count and verdict come from unittest's result, not from printed summaries. A child exiting with status 0
24without a completed result, or after unittest reported failure, fails the run.
22 25
23`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with 26`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with
24`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. 27`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits.
@@ -33,6 +36,7 @@ import locale
33import math 36import math
34import os 37import os
35import re 38import re
39import signal
36import subprocess 40import subprocess
37import sys 41import sys
38import tempfile 42import tempfile
@@ -59,7 +63,7 @@ def _unregister_process(proc):
59def _kill_process_tree(proc): 63def _kill_process_tree(proc):
60 if proc is None: 64 if proc is None:
61 return 65 return
62 if os.name == "nt": 66 if os.name == "nt" and proc.poll() is None:
63 try: 67 try:
64 subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], 68 subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
65 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) 69 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
@@ -74,11 +78,13 @@ def _kill_process_tree(proc):
74def _terminate_active_processes(): 78def _terminate_active_processes():
75 with _processes_lock: 79 with _processes_lock:
76 procs = list(_active_processes) 80 procs = list(_active_processes)
77 for p in procs: 81 if os.name != "nt":
78 try: 82 for p in procs:
79 p.terminate() 83 try:
80 except OSError: 84 p.terminate()
81 pass 85 except OSError:
86 pass
87 # On Windows taskkill /T needs the root process alive to find its descendants.
82 for p in procs: 88 for p in procs:
83 _kill_process_tree(p) 89 _kill_process_tree(p)
84 try: 90 try:
@@ -94,13 +100,44 @@ CHILD_PROGRAM = (
94 "import json, os, sys, unittest\n" 100 "import json, os, sys, unittest\n"
95 "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" 101 "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n"
96 "result = program.result\n" 102 "result = program.result\n"
97 "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" 103 "code = 1 if not result.wasSuccessful() else 5 if not result.testsRun and not result.skipped else 0\n"
98 " json.dump({'testsRun': result.testsRun}, handle)\n" 104 "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8', newline='\\n') as handle:\n"
99 "if not result.wasSuccessful():\n" 105 " json.dump({'testsRun': result.testsRun, 'exitCode': code}, handle)\n"
100 " sys.exit(1)\n" 106 "sys.exit(code)\n")
101 "elif result.testsRun == 0 and len(result.skipped) == 0:\n" 107
102 " sys.exit(5)\n" 108# Windows NTSTATUS codes python.exe exits with when it crashes. A file that dies this way prints nothing, so the code
103 "sys.exit(0)\n") 109# is the only clue there is (an access violation in a pure-Python test points at the machine, not at the test).
110NTSTATUS_CRASHES = {
111 0xC0000005: "access violation",
112 0xC000001D: "illegal instruction",
113 0xC0000017: "out of memory",
114 0xC00000FD: "stack overflow",
115 0xC0000374: "heap corruption",
116 0xC0000409: "fail fast / stack buffer overrun",
117}
118# Known statuses that end a process without it crashing.
119NTSTATUS_OTHER = {
120 0xC000013A: "interrupted with Ctrl+C",
121}
122
123
124def describe_exit(code):
125 """A failed module's exit code in words: `exit code 1`, `killed by SIGSEGV (-11)` for a POSIX signal, or for a
126 known Windows NTSTATUS its hexadecimal value and meaning (3221225477 -> 0xC0000005, access violation). Only the
127 statuses in NTSTATUS_CRASHES are called a crash: a process can also exit with any 32-bit value on purpose, so an
128 unknown one is reported as just its value."""
129 if code < 0:
130 try:
131 return f"killed by {signal.Signals(-code).name} ({code})"
132 except ValueError:
133 return f"killed by signal {-code} ({code})"
134 if code in NTSTATUS_CRASHES:
135 return f"exit code 0x{code:08X}, {NTSTATUS_CRASHES[code]} (the process crashed)"
136 if code in NTSTATUS_OTHER:
137 return f"exit code 0x{code:08X}, {NTSTATUS_OTHER[code]}"
138 if code > 0xFFFF: # an NTSTATUS-sized value reads better in hexadecimal
139 return f"exit code 0x{code:08X}"
140 return f"exit code {code}"
104 141
105 142
106def module_path(directory, module): 143def module_path(directory, module):
@@ -139,14 +176,64 @@ def positive_seconds(value):
139 return seconds 176 return seconds
140 177
141 178
142def read_count(path): 179def read_result(path, process_code):
143 """The number of tests the child ran, as unittest's own result object reported it.""" 180 """Return the effective exit code, completed test count, and any diagnostic."""
144 try: 181 try:
145 with open(path, encoding="utf-8") as handle: 182 with open(path, encoding="utf-8") as handle:
146 return int(json.load(handle)["testsRun"]) 183 result = json.load(handle)
184 count, test_code = result["testsRun"], result["exitCode"]
185 if type(count) is not int or count < 0 or type(test_code) is not int or test_code not in (0, 1, 5):
186 raise ValueError("invalid unittest result")
147 except (OSError, ValueError, KeyError, TypeError): 187 except (OSError, ValueError, KeyError, TypeError):
148 # The child wrote no result: it did not finish, so no test is known to have run. 188 if process_code == 0:
149 return 0 189 return 1, 0, "process exited without a unittest result"
190 return process_code, None, ""
191 if process_code in (0, 5) and process_code != test_code:
192 return 1, count, f"process exited with status {process_code} but unittest reported {test_code}"
193 return process_code, count, ""
194
195
196def result_environment(scratch):
197 result_path = os.path.join(scratch, "count.json")
198 return result_path, dict(os.environ, LEONIDA_TEST_COUNT=result_path)
199
200
201def run_discover(directory, pattern, verbose, timeout):
202 args = ["discover", "-s", directory, "-p", pattern, *(["-v"] if verbose else [])]
203 with tempfile.TemporaryDirectory() as scratch:
204 path, env = result_environment(scratch)
205 proc = subprocess.Popen([sys.executable, "-c", CHILD_PROGRAM, *args], env=env)
206 _register_process(proc)
207 start_time = time.monotonic()
208 try:
209 while True:
210 try:
211 code = proc.wait(timeout=0.2)
212 break
213 except subprocess.TimeoutExpired:
214 if timeout is not None and time.monotonic() - start_time >= timeout:
215 raise
216 except subprocess.TimeoutExpired:
217 _kill_process_tree(proc)
218 print(f"TIMED OUT after {timeout:g} s: unittest discover in {directory}", file=sys.stderr)
219 return 1
220 except KeyboardInterrupt:
221 _kill_process_tree(proc)
222 try:
223 proc.wait(timeout=0.5)
224 except (subprocess.TimeoutExpired, OSError):
225 pass
226 print("interrupted", file=sys.stderr)
227 return 130
228 except BaseException:
229 _kill_process_tree(proc)
230 raise
231 finally:
232 _unregister_process(proc)
233 code, _, diagnostic = read_result(path, code)
234 if diagnostic:
235 print(f"unittest discover in {directory}: {diagnostic}", file=sys.stderr)
236 return code
150 237
151 238
152def run_module(directory, module, verbose, timeout=None): 239def run_module(directory, module, verbose, timeout=None):
@@ -157,8 +244,7 @@ def run_module(directory, module, verbose, timeout=None):
157 target = module[:-len(".__init__")] if module.endswith(".__init__") else module 244 target = module[:-len(".__init__")] if module.endswith(".__init__") else module
158 cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] 245 cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target]
159 with tempfile.TemporaryDirectory() as scratch: 246 with tempfile.TemporaryDirectory() as scratch:
160 count_path = os.path.join(scratch, "count.json") 247 result_path, env = result_environment(scratch)
161 env = dict(os.environ, LEONIDA_TEST_COUNT=count_path)
162 proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 248 proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
163 text=True, errors="replace") 249 text=True, errors="replace")
164 _register_process(proc) 250 _register_process(proc)
@@ -181,13 +267,14 @@ def run_module(directory, module, verbose, timeout=None):
181 raise 267 raise
182 finally: 268 finally:
183 _unregister_process(proc) 269 _unregister_process(proc)
184 count = read_count(count_path) 270 code, count, diagnostic = read_result(result_path, proc.returncode)
185 out = stdout + stderr 271 out = stdout + stderr
186 # Discover imports every package initializer, but an empty one has no tests to run. It is included in the 272 if diagnostic:
187 # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. 273 out += f"\n{diagnostic}\n"
188 if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: 274 # A package initializer that completed with no tests isn't a failed module.
275 if code == 5 and count == 0 and module.endswith(".__init__"):
189 return 0, 0, out 276 return 0, 0, out
190 return proc.returncode, count, out 277 return code, count or 0, out
191 278
192 279
193def main(argv=None): 280def main(argv=None):
@@ -206,35 +293,7 @@ def main(argv=None):
206 print(f"no {a.pattern} files in {directory}") 293 print(f"no {a.pattern} files in {directory}")
207 return 1 294 return 1
208 if a.jobs <= 1: 295 if a.jobs <= 1:
209 cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, 296 return run_discover(directory, a.pattern, a.verbose, a.timeout)
210 "-p", a.pattern, *(["-v"] if a.verbose else [])]
211 proc = subprocess.Popen(cmd)
212 _register_process(proc)
213 start_time = time.monotonic()
214 try:
215 while True:
216 try:
217 return proc.wait(timeout=0.2)
218 except subprocess.TimeoutExpired:
219 if a.timeout is not None and time.monotonic() - start_time >= a.timeout:
220 raise
221 except subprocess.TimeoutExpired:
222 _kill_process_tree(proc)
223 print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr)
224 return 1
225 except KeyboardInterrupt:
226 _kill_process_tree(proc)
227 try:
228 proc.wait(timeout=0.5)
229 except (subprocess.TimeoutExpired, OSError):
230 pass
231 print("interrupted", file=sys.stderr)
232 return 130
233 except BaseException:
234 _kill_process_tree(proc)
235 raise
236 finally:
237 _unregister_process(proc)
238 # Largest files first: they tend to run longest, and one started last would set the wall time alone. 297 # Largest files first: they tend to run longest, and one started last would set the wall time alone.
239 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) 298 modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m)))
240 start, total, failed = time.monotonic(), 0, [] 299 start, total, failed = time.monotonic(), 0, []
@@ -252,7 +311,8 @@ def main(argv=None):
252 total += ran 311 total += ran
253 if code: 312 if code:
254 failed.append(jobs[job]) 313 failed.append(jobs[job])
255 print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) 314 silent = "" if out.strip() else "(no output: the process ended before printing anything)\n"
315 print(f"==== FAILED: {jobs[job]} ({describe_exit(code)})\n{silent}{out}", flush=True)
256 elif a.verbose: 316 elif a.verbose:
257 print(f"==== {jobs[job]}\n{out}", flush=True) 317 print(f"==== {jobs[job]}\n{out}", flush=True)
258 except KeyboardInterrupt: 318 except KeyboardInterrupt:
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py
index d36011430..393b17ce9 100644
--- a/scripts/run_wine_tests.py
+++ b/scripts/run_wine_tests.py
@@ -12,8 +12,8 @@ Some tests open files through absolute paths compiled into them (the GLSL test s
12runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run 12runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run
13($WINEPREFIX, else ~/.wine), unless that drive is already in use there. 13($WINEPREFIX, else ~/.wine), unless that drive is already in use there.
14 14
15Every test is reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the 15Every test is reported. Each name given to --require must be listed and all of its tests must pass, or the
16others show what does and doesn't work under Wine yet without failing the job. 16exit code is 1. The other results 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 19
@@ -515,7 +515,7 @@ def main() -> int:
515 ap.add_argument("--root", type=os.path.abspath, default=ROOT, help="the Linux checkout (default: this repository)") 515 ap.add_argument("--root", type=os.path.abspath, default=ROOT, help="the Linux checkout (default: this repository)")
516 ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"), 516 ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"),
517 help="Wine command (default: $WINE or wine)") 517 help="Wine command (default: $WINE or wine)")
518 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 name whose entries must all pass (repeatable)")
519 ap.add_argument("--timeout", type=positive_seconds, default=120.0, 519 ap.add_argument("--timeout", type=positive_seconds, default=120.0,
520 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, 521 ap.add_argument("--jobs", type=positive_int, default=1,
@@ -546,7 +546,6 @@ def main() -> int:
546 # Each test starts in its own CTest working directory. Keep bare commands on PATH. 546 # Each test starts in its own CTest working directory. Keep bare commands on PATH.
547 if os.path.dirname(wine[0]) and not os.path.isabs(wine[0]): 547 if os.path.dirname(wine[0]) and not os.path.isabs(wine[0]):
548 wine[0] = os.path.join(os.getcwd(), wine[0]) 548 wine[0] = os.path.join(os.getcwd(), wine[0])
549 results = {}
550 results_by_index: dict[int, str] = {} 549 results_by_index: dict[int, str] = {}
551 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") 550 prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine")
552 outcomes: dict[int, tuple[str, str]] = {} 551 outcomes: dict[int, tuple[str, str]] = {}
@@ -557,7 +556,6 @@ def main() -> int:
557 556
558 def report(index: int) -> None: 557 def report(index: int) -> None:
559 status, detail = outcomes[index] 558 status, detail = outcomes[index]
560 results[names[index]] = status
561 print(f"[{status.upper()}] {names[index]}", flush=True) 559 print(f"[{status.upper()}] {names[index]}", flush=True)
562 if status != "pass": 560 if status != "pass":
563 for line in detail.rstrip().splitlines()[-40:]: 561 for line in detail.rstrip().splitlines()[-40:]:
@@ -574,11 +572,12 @@ def main() -> int:
574 else: 572 else:
575 run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) 573 run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report)
576 574
577 missing = list(dict.fromkeys(n for n in args.require if n not in results)) 575 missing = list(dict.fromkeys(n for n in args.require if n not in indices))
578 failed_required = [n for n in args.require if results.get(n) != "pass"] 576 nonpassing_names = {names[index] for index, status in results_by_index.items() if status != "pass"}
579 counts = {s: sum(1 for v in results.values() if v == s) for s in ("pass", "fail", "skip")} 577 failed_required = [n for n in args.require if n not in indices or n in nonpassing_names]
578 counts = {s: sum(1 for v in results_by_index.values() if v == s) for s in ("pass", "fail", "skip")}
580 print(f"\n{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped under Wine " 579 print(f"\n{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped under Wine "
581 f"({len(results)} tests)") 580 f"({len(results_by_index)} tests)")
582 for n in missing: 581 for n in missing:
583 print(f"required test not listed by the Windows build: {n}") 582 print(f"required test not listed by the Windows build: {n}")
584 if failed_required: 583 if failed_required:
@@ -591,7 +590,8 @@ def main() -> int:
591 f.write(f"### Windows tests under {args.label or 'Wine'}\n\n") 590 f.write(f"### Windows tests under {args.label or 'Wine'}\n\n")
592 f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n") 591 f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n")
593 f.write("| Test | Result | Required |\n|---|---|---|\n") 592 f.write("| Test | Result | Required |\n|---|---|---|\n")
594 for name, status in results.items(): 593 for index in order:
594 name, status = names[index], results_by_index[index]
595 f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n") 595 f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n")
596 for name in missing: 596 for name in missing:
597 # The job fails on these, so the table must name them, not only the log. 597 # The job fails on these, so the table must name them, not only the log.
diff --git a/scripts/shader_stats.py b/scripts/shader_stats.py
index 34b61cd8a..85e408099 100644
--- a/scripts/shader_stats.py
+++ b/scripts/shader_stats.py
@@ -50,17 +50,27 @@ def original(path: str) -> tuple[int, int]:
50 if kind == "vgpr": 50 if kind == "vgpr":
51 top = max(top, operand["r"] + operand.get("n", 1)) 51 top = max(top, operand["r"] + operand.get("n", 1))
52 elif kind == "vlist": 52 elif kind == "vlist":
53 top = max(top, max(operand["r"]) + 1) 53 if operand["r"]:
54 top = max(top, max(operand["r"]) + 1)
54 return len(insns), top 55 return len(insns), top
55 56
56 57
57REQUIRED = ("name", "stage", "statistic", "value") 58REQUIRED = ("name", "stage", "statistic", "value")
58 59
59 60
61def _safe_shader_name(name):
62 """True when `name` is a single non-empty filename stem inside the disasm directory."""
63 if not name or name in (".", "..") or "\x00" in name:
64 return False
65 if "/" in name or "\\" in name or os.path.splitdrive(name)[0]:
66 return False
67 return os.path.basename(name) == name
68
69
60def load_stats(path): 70def load_stats(path):
61 """Read counters keyed by (shader, stage) from vk_pipeline_check --stats.""" 71 """Read counters keyed by (shader, stage) from vk_pipeline_check --stats."""
62 out = defaultdict(dict) 72 out = defaultdict(dict)
63 with open(path, newline="", encoding="utf-8") as f: 73 with open(path, newline="", encoding="utf-8-sig") as f:
64 reader = csv.DictReader(f, strict=True) 74 reader = csv.DictReader(f, strict=True)
65 header = reader.fieldnames or [] 75 header = reader.fieldnames or []
66 missing = [c for c in REQUIRED if c not in header] 76 missing = [c for c in REQUIRED if c not in header]
@@ -76,12 +86,16 @@ def load_stats(path):
76 absent = [c for c in REQUIRED if row[c] is None] 86 absent = [c for c in REQUIRED if row[c] is None]
77 if absent: 87 if absent:
78 raise ValueError(f"line {line}: row missing required column(s): {', '.join(absent)}") 88 raise ValueError(f"line {line}: row missing required column(s): {', '.join(absent)}")
89 if not _safe_shader_name(row["name"]):
90 raise ValueError(f"line {line}: invalid shader name {row['name']!r}")
79 out[row["name"], row["stage"]][row["statistic"]] = row["value"] 91 out[row["name"], row["stage"]][row["statistic"]] = row["value"]
80 return out 92 return out
81 93
82 94
83def number(raw): 95def number(raw):
84 """The exact int, or else the finite float, a raw value holds; None if it is missing or not such a number.""" 96 """The exact int, or else the finite float, a raw value holds; None if it is missing or not such a number."""
97 if isinstance(raw, bool):
98 return None
85 try: 99 try:
86 value = float(raw) 100 value = float(raw)
87 except (TypeError, ValueError, OverflowError): 101 except (TypeError, ValueError, OverflowError):
@@ -149,18 +163,18 @@ def median_clause(rs, key, label):
149USAGE = "usage: shader_stats.py <stats.csv> <disasm dir> [--details]" 163USAGE = "usage: shader_stats.py <stats.csv> <disasm dir> [--details]"
150 164
151 165
152def main(): 166def main(argv=None):
153 argv = sys.argv[1:] 167 argv = sys.argv[1:] if argv is None else list(argv)
154 if "-h" in argv or "--help" in argv: 168 if "-h" in argv or "--help" in argv:
155 print(__doc__) 169 print(__doc__)
156 return 0 170 return 0
157 # A misspelt option (--detail) used to be dropped, and the summary printed as if it had been asked for. 171 # A misspelt option (--detail, -d) used to be dropped or misparsed as a positional argument.
158 unknown = [a for a in argv if a.startswith("--") and a != "--details"] 172 unknown = [a for a in argv if a.startswith("-") and a != "--details"]
159 if unknown: 173 if unknown:
160 print(f"unknown option {unknown[0]}\n{USAGE}", file=sys.stderr) 174 print(f"unknown option {unknown[0]}\n{USAGE}", file=sys.stderr)
161 return 2 175 return 2
162 args = [a for a in argv if not a.startswith("--")] 176 args = [a for a in argv if not a.startswith("-")]
163 if len(args) != 2: 177 if len(args) != 2 or not args[0].strip() or not args[1].strip():
164 print(USAGE, file=sys.stderr) 178 print(USAGE, file=sys.stderr)
165 return 2 179 return 2
166 path = args[0] 180 path = args[0]
@@ -169,6 +183,8 @@ def main():
169 except (OSError, ValueError, csv.Error) as e: 183 except (OSError, ValueError, csv.Error) as e:
170 sys.exit(f"{path}: {e}") 184 sys.exit(f"{path}: {e}")
171 disasm = args[1] 185 disasm = args[1]
186 if not os.path.isdir(disasm):
187 sys.exit(f"{disasm}: not a directory")
172 rows = [] 188 rows = []
173 for (name, stage), st in sorted(stats.items()): 189 for (name, stage), st in sorted(stats.items()):
174 src = os.path.join(disasm, name + ".s") 190 src = os.path.join(disasm, name + ".s")
@@ -179,7 +195,7 @@ def main():
179 sys.exit(f"{src}: {e.strerror or e}") 195 sys.exit(f"{src}: {e.strerror or e}")
180 if not rows: 196 if not rows:
181 sys.exit("no shader is in both the statistics and the disasm folder") 197 sys.exit("no shader is in both the statistics and the disasm folder")
182 if "--details" in sys.argv: 198 if "--details" in argv:
183 print(f"{'shader':26} {'stage':5} " + " ".join(f"{head:>{width}}" for _, head, width, _ in COLUMNS)) 199 print(f"{'shader':26} {'stage':5} " + " ".join(f"{head:>{width}}" for _, head, width, _ in COLUMNS))
184 for r in rows: 200 for r in rows:
185 print(f"{r['name']:26} {r['stage']:5} " 201 print(f"{r['name']:26} {r['stage']:5} "
diff --git a/scripts/smoke.py b/scripts/smoke.py
new file mode 100644
index 000000000..131996be9
--- /dev/null
+++ b/scripts/smoke.py
@@ -0,0 +1,332 @@
1#!/usr/bin/env python3
2"""One-command synthetic source-only smoke suite for Leonida (DX-07).
3
4Validates prerequisites, compiles source trees, enforces clean-room boundaries,
5and executes fast synthetic smoke tests on Windows, Linux, and macOS without game files.
6"""
7
8from __future__ import annotations
9
10import argparse
11import compileall
12import contextlib
13import io
14import json
15import os
16from pathlib import Path
17import platform
18import shutil
19import subprocess
20import sys
21import time
22
23ROOT = Path(__file__).resolve().parents[1]
24MIN_PYTHON_VERSION = (3, 10)
25
26
27def check_prerequisites(require_toolchains: list[str] | None = None) -> tuple[dict, bool]:
28 """Check required environment and discover optional toolchains."""
29 py_ver = sys.version_info
30 py_ok = (py_ver.major, py_ver.minor) >= MIN_PYTHON_VERSION
31
32 prereqs = {
33 "python": {
34 "version": f"{py_ver.major}.{py_ver.minor}.{py_ver.micro}",
35 "satisfies": py_ok,
36 "required": f">={MIN_PYTHON_VERSION[0]}.{MIN_PYTHON_VERSION[1]}",
37 }
38 }
39
40 toolchains = {
41 "cmake": _detect_command("cmake", ["--version"]),
42 "ninja": _detect_command("ninja", ["--version"]),
43 "compiler_msvc": _detect_command("cl", []),
44 "compiler_gcc": _detect_command("gcc", ["--version"]),
45 "compiler_clang": _detect_command("clang", ["--version"]),
46 "vulkan_sdk": _detect_vulkan(),
47 "node": _detect_command("node", ["--version"]),
48 "dotnet": _detect_command("dotnet", ["--version"]),
49 }
50
51 all_ok = py_ok
52 if require_toolchains:
53 for req in require_toolchains:
54 found = False
55 if req == "compiler":
56 found = any(
57 toolchains[c]["available"]
58 for c in ("compiler_msvc", "compiler_gcc", "compiler_clang")
59 )
60 elif req in toolchains:
61 found = toolchains[req]["available"]
62 if not found:
63 all_ok = False
64
65 return {"prerequisites": prereqs, "toolchains": toolchains}, all_ok
66
67
68def _detect_command(command: str, version_args: list[str]) -> dict:
69 exe = shutil.which(command)
70 if not exe:
71 return {"available": False, "path": None, "version": None}
72
73 version_str = None
74 if version_args:
75 try:
76 res = subprocess.run(
77 [exe, *version_args],
78 capture_output=True,
79 text=True,
80 timeout=5,
81 )
82 if res.returncode == 0:
83 first_line = (res.stdout or res.stderr).strip().splitlines()
84 if first_line:
85 version_str = first_line[0]
86 except (OSError, subprocess.TimeoutExpired):
87 pass
88
89 return {"available": True, "path": exe, "version": version_str}
90
91
92def _detect_vulkan() -> dict:
93 sdk_dir = os.environ.get("VULKAN_SDK")
94 glslang = shutil.which("glslangValidator") or shutil.which("glslang")
95 available = bool(sdk_dir or glslang)
96 return {
97 "available": available,
98 "path": sdk_dir or (glslang if glslang else None),
99 "version": sdk_dir if sdk_dir else ("glslang found" if glslang else None),
100 }
101
102
103def run_checks(root: Path, quick: bool = False, verbose: bool = False) -> list[dict]:
104 """Execute synthetic source-only sanity checks."""
105 checks = []
106
107 # 1. Bytecode compilation of Python source trees
108 t0 = time.monotonic()
109 compile_ok = True
110 compile_err = None
111 compile_buf = io.StringIO()
112 try:
113 with contextlib.redirect_stdout(compile_buf):
114 if quick:
115 # Quick mode: verify core entry points compile
116 for p in (root / "make_game.py", root / "tools" / "rdna2spirv.py", root / "scripts" / "dev.py", root / "scripts" / "smoke.py"):
117 if p.is_file() and not compileall.compile_file(str(p), quiet=1, force=False):
118 compile_ok = False
119 compile_err = f"{p.name} failed bytecode compilation"
120 break
121 else:
122 # Full mode: verify all tools and scripts
123 res = compileall.compile_dir(str(root / "tools"), quiet=1, force=False)
124 res = compileall.compile_dir(str(root / "scripts"), quiet=1, force=False) and res
125 res = compileall.compile_file(str(root / "make_game.py"), quiet=1, force=False) and res
126 if not res:
127 compile_ok = False
128 compile_err = "One or more files failed bytecode compilation"
129 except Exception as exc: # noqa: BLE001
130 compile_ok = False
131 compile_err = str(exc)
132 if not compile_ok and compile_buf.getvalue().strip():
133 print(compile_buf.getvalue().rstrip(), file=sys.stderr)
134
135 checks.append({
136 "name": "python_compileall",
137 "status": "PASS" if compile_ok else "FAIL",
138 "duration_ms": int((time.monotonic() - t0) * 1000),
139 "details": compile_err or ("Core entry points compile cleanly" if quick else "tools/, scripts/, make_game.py compile cleanly"),
140 })
141
142 # 2. Clean-room validation (no game data)
143 t0 = time.monotonic()
144 check_no_game_script = root / "scripts" / "check_no_game_data.py"
145 if check_no_game_script.is_file():
146 cmd = [sys.executable, "-I", str(check_no_game_script), "make_game.py", "scripts/dev.py"]
147 proc = subprocess.run(cmd, cwd=root, capture_output=True, text=True)
148 no_game_ok = proc.returncode == 0
149 checks.append({
150 "name": "clean_room_no_game_data",
151 "status": "PASS" if no_game_ok else "FAIL",
152 "duration_ms": int((time.monotonic() - t0) * 1000),
153 "details": proc.stderr.strip() if not no_game_ok else "No game data or retail assets detected",
154 })
155 else:
156 checks.append({
157 "name": "clean_room_no_game_data",
158 "status": "SKIP",
159 "duration_ms": 0,
160 "details": "scripts/check_no_game_data.py not present",
161 })
162
163 # 3. Core CLI --help entry points
164 cli_targets = [
165 ("make_game.py", root / "make_game.py"),
166 ("tools/rdna2spirv.py", root / "tools" / "rdna2spirv.py"),
167 ("scripts/dev.py", root / "scripts" / "dev.py"),
168 ]
169 for label, script_path in cli_targets:
170 if not script_path.is_file():
171 checks.append({
172 "name": f"cli_help_{label}",
173 "status": "SKIP",
174 "duration_ms": 0,
175 "details": f"{label} not found",
176 })
177 continue
178
179 t0 = time.monotonic()
180 proc = subprocess.run(
181 [sys.executable, "-I", str(script_path), "--help"],
182 cwd=root,
183 capture_output=True,
184 text=True,
185 timeout=10,
186 )
187 ok = proc.returncode == 0 and bool(proc.stdout)
188 checks.append({
189 "name": f"cli_help_{label}",
190 "status": "PASS" if ok else "FAIL",
191 "duration_ms": int((time.monotonic() - t0) * 1000),
192 "details": f"Exit code {proc.returncode}" if not ok else f"{label} --help exited with 0",
193 })
194
195 # 4. Fast synthetic unit test smoke pass (unless --quick)
196 if not quick:
197 test_targets = [
198 "tests/test_dev_discovery.py",
199 "tests/test_shader_ir_parse.py",
200 ]
201 for rel_test in test_targets:
202 test_path = root / rel_test
203 if not test_path.is_file():
204 continue
205
206 t0 = time.monotonic()
207 proc = subprocess.run(
208 [sys.executable, "-I", str(test_path)],
209 cwd=root,
210 capture_output=True,
211 text=True,
212 timeout=30,
213 )
214 ok = proc.returncode == 0
215 checks.append({
216 "name": f"test_{Path(rel_test).stem}",
217 "status": "PASS" if ok else "FAIL",
218 "duration_ms": int((time.monotonic() - t0) * 1000),
219 "details": proc.stderr.strip() if not ok else "Test suite passed",
220 })
221
222 return checks
223
224
225def main(argv: list[str] | None = None) -> int:
226 parser = argparse.ArgumentParser(
227 prog="smoke.py",
228 description="One-command synthetic source-only smoke suite (DX-07).",
229 )
230 parser.add_argument(
231 "--quick",
232 action="store_true",
233 help="Run fast sanity compilation and CLI help checks only (< 1s)",
234 )
235 parser.add_argument(
236 "--prereqs-only",
237 action="store_true",
238 help="Discover toolchains and report prerequisite status without running checks",
239 )
240 parser.add_argument(
241 "--json",
242 action="store_true",
243 help="Print machine-readable JSON summary",
244 )
245 parser.add_argument(
246 "--require",
247 nargs="+",
248 metavar="TOOL",
249 help="Require specific toolchain(s) to be present (e.g. cmake, ninja, compiler)",
250 )
251 parser.add_argument(
252 "-v", "--verbose",
253 action="store_true",
254 help="Print detailed execution output",
255 )
256
257 args = parser.parse_args(argv)
258
259 diag, prereqs_ok = check_prerequisites(require_toolchains=args.require)
260
261 if not prereqs_ok:
262 if args.json:
263 print(json.dumps({
264 "schema_version": 1,
265 "platform": platform.platform(),
266 "verdict": "ERROR",
267 "error": "Required prerequisites or toolchains missing",
268 **diag,
269 }, indent=2))
270 else:
271 print("error: required environment prerequisites or toolchains missing:", file=sys.stderr)
272 for k, v in diag["prerequisites"].items():
273 if not v["satisfies"]:
274 print(f" - {k}: {v['version']} (requires {v['required']})", file=sys.stderr)
275 if args.require:
276 for req in args.require:
277 print(f" - required toolchain '{req}' was not found", file=sys.stderr)
278 return 2
279
280 if args.prereqs_only:
281 if args.json:
282 print(json.dumps({
283 "schema_version": 1,
284 "platform": platform.platform(),
285 "verdict": "PASS",
286 **diag,
287 }, indent=2))
288 else:
289 print(f"Leonida Smoke Suite — Environment Discovery ({platform.platform()})")
290 print("Prerequisites:")
291 for k, v in diag["prerequisites"].items():
292 status = "OK" if v["satisfies"] else "FAIL"
293 print(f" - {k}: {v['version']} [{status}]")
294 print("Toolchains (optional for synthetic tests):")
295 for k, v in diag["toolchains"].items():
296 status = "PRESENT" if v["available"] else "NOT FOUND"
297 detail = f" ({v['version']})" if v["version"] else ""
298 print(f" - {k}: {status}{detail}")
299 return 0
300
301 if args.json:
302 with contextlib.redirect_stdout(sys.stderr):
303 checks = run_checks(ROOT, quick=args.quick, verbose=args.verbose)
304 else:
305 checks = run_checks(ROOT, quick=args.quick, verbose=args.verbose)
306 all_passed = all(c["status"] in ("PASS", "SKIP") for c in checks)
307
308 if args.json:
309 report = {
310 "schema_version": 1,
311 "platform": platform.platform(),
312 "verdict": "PASS" if all_passed else "FAIL",
313 **diag,
314 "checks": checks,
315 }
316 print(json.dumps(report, indent=2))
317 else:
318 print(f"Leonida Smoke Suite — Source-Only Validation ({platform.platform()})")
319 for c in checks:
320 status_tag = f"[{c['status']}]"
321 print(f" {status_tag:<8} {c['name']:<30} ({c['duration_ms']} ms) — {c['details']}")
322 print("Verdict: " + ("PASS (All source-only checks succeeded)" if all_passed else "FAIL"))
323
324 return 0 if all_passed else 1
325
326
327if __name__ == "__main__":
328 try:
329 sys.stdout.reconfigure(errors="replace")
330 except (AttributeError, ValueError, OSError):
331 pass
332 raise SystemExit(main())
diff --git a/scripts/smooth-motion.ps1 b/scripts/smooth-motion.ps1
new file mode 100644
index 000000000..514b5918d
--- /dev/null
+++ b/scripts/smooth-motion.ps1
@@ -0,0 +1,104 @@
1# Leonida: NVIDIA Smooth Motion (the driver's frame generation, RTX 40 and 50) for leonida_sm.exe.
2# scripts\smooth-motion.ps1 what the profile says now
3# scripts\smooth-motion.ps1 -State on doubles the frames shown (the game renders the same number)
4# scripts\smooth-motion.ps1 -State off
5# It writes one per-application setting in the driver's own profile store through NVAPI (no administrator, no other
6# application touched); the NVIDIA App should be closed while it runs. It takes effect at the next start.
7# The setting's ID (0xB0D384C0, "Smooth Motion - Enable") was found by lepotane/VIctory-leonida (GPL-3.0); the
8# NVAPI entry points are the documented ones of nvapi64.dll's query interface.
9param(
10 [ValidateSet('query', 'on', 'off')][string]$State = 'query',
11 [string]$Exe = 'leonida_sm.exe'
12)
13Add-Type -TypeDefinition @'
14using System;
15using System.Runtime.InteropServices;
16using System.Text;
17
18public static class LeonidaDrs {
19 const uint SmoothMotion = 0xB0D384C0;
20
21 [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Unicode)]
22 struct Setting {
23 public uint version;
24 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] public string name;
25 public uint id; public int type; public int location; public uint isCurrentPredefined; public uint isPredefinedValid;
26 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4100)] public byte[] predefined;
27 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4100)] public byte[] current;
28 }
29 [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Unicode)]
30 struct Profile {
31 public uint version;
32 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] public string name;
33 public uint gpuSupport; public uint isPredefined; public uint numApps; public uint numSettings;
34 }
35 [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Unicode)]
36 struct App {
37 public uint version; public uint isPredefined;
38 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] public string appName;
39 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] public string friendly;
40 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] public string launcher;
41 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 2048)] public string fileInFolder;
42 public uint flags;
43 }
44 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate IntPtr QueryFn(uint id);
45 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int NoArg();
46 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int OutHandle(ref IntPtr h);
47 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int OnHandle(IntPtr h);
48 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int FindAppFn(IntPtr h, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder n, ref IntPtr p, ref App a);
49 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int NewProfileFn(IntPtr h, ref Profile p, ref IntPtr o);
50 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int NewAppFn(IntPtr h, IntPtr p, ref App a);
51 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int GetFn(IntPtr h, IntPtr p, uint id, ref Setting s, ref uint x);
52 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int SetFn(IntPtr h, IntPtr p, ref Setting s, uint x, uint y);
53
54 [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr LoadLibraryW(string n);
55 [DllImport("kernel32.dll")] static extern IntPtr GetProcAddress(IntPtr m, IntPtr ordinal);
56
57 static QueryFn query;
58 static T Fn<T>(uint id) where T : class {
59 IntPtr p = query(id);
60 if (p == IntPtr.Zero) throw new Exception("NVAPI has no entry 0x" + id.ToString("X8"));
61 return (T)(object)Marshal.GetDelegateForFunctionPointer(p, typeof(T));
62 }
63 static uint Ver<T>(int v) { return (uint)(Marshal.SizeOf(typeof(T)) | (v << 16)); }
64 static void Check(int status, string what) { if (status != 0) throw new Exception(what + " failed: NVAPI status " + status); }
65
66 // Returns the value before; writes `value` when it is not null. -1: never set for this application.
67 public static long Run(string exe, int? value) {
68 IntPtr lib = LoadLibraryW("nvapi64.dll");
69 if (lib == IntPtr.Zero) throw new Exception("nvapi64.dll not found: is this an NVIDIA driver?");
70 query = (QueryFn)Marshal.GetDelegateForFunctionPointer(GetProcAddress(lib, (IntPtr)2), typeof(QueryFn));
71 Check(Fn<NoArg>(0x0150E828)(), "NvAPI_Initialize");
72 IntPtr session = IntPtr.Zero;
73 Check(Fn<OutHandle>(0x0694D52E)(ref session), "DRS_CreateSession");
74 try {
75 Check(Fn<OnHandle>(0x375DBD6B)(session), "DRS_LoadSettings");
76 App app = new App { version = Ver<App>(3), appName = exe, friendly = "Leonida", launcher = "", fileInFolder = "" };
77 IntPtr profile = IntPtr.Zero;
78 if (Fn<FindAppFn>(0xEEE566B2)(session, new StringBuilder(exe), ref profile, ref app) != 0 || profile == IntPtr.Zero) {
79 Profile p = new Profile { version = Ver<Profile>(1), name = "Leonida", gpuSupport = 1 };
80 Check(Fn<NewProfileFn>(0xCC176068)(session, ref p, ref profile), "DRS_CreateProfile");
81 app = new App { version = Ver<App>(3), appName = exe, friendly = "Leonida", launcher = "", fileInFolder = "" };
82 Check(Fn<NewAppFn>(0x4347A9DE)(session, profile, ref app), "DRS_CreateApplication");
83 }
84 Setting s = new Setting { version = Ver<Setting>(1), name = "", predefined = new byte[4100], current = new byte[4100] };
85 uint unused = 0;
86 long before = Fn<GetFn>(0xEA99498D)(session, profile, SmoothMotion, ref s, ref unused) == 0 ? (long)BitConverter.ToUInt32(s.current, 0) : -1L;
87 if (value.HasValue) {
88 Setting w = new Setting { version = Ver<Setting>(1), name = "", id = SmoothMotion, predefined = new byte[4100], current = new byte[4100] };
89 Buffer.BlockCopy(BitConverter.GetBytes((uint)value.Value), 0, w.current, 0, 4);
90 Check(Fn<SetFn>(0x8A2CF5F5)(session, profile, ref w, 0, 0), "DRS_SetSetting");
91 Check(Fn<OnHandle>(0xFCBC7E14)(session), "DRS_SaveSettings");
92 }
93 return before;
94 } finally {
95 Fn<OnHandle>(0xDAD9CFF8)(session);
96 }
97 }
98}
99'@ -ErrorAction Stop
100$ErrorActionPreference = 'Stop'
101$value = switch ($State) { 'on' { 1 } 'off' { 0 } default { $null } }
102$before = [LeonidaDrs]::Run($Exe, $value)
103$was = switch ($before) { -1 { 'not set' } 0 { 'off' } default { 'on' } }
104if ($null -eq $value) { "Smooth Motion for ${Exe}: $was" } else { "Smooth Motion for ${Exe}: $was -> $State (from the next start)" }
diff --git a/scripts/sync_victory.py b/scripts/sync_victory.py
new file mode 100644
index 000000000..ccae2c459
--- /dev/null
+++ b/scripts/sync_victory.py
@@ -0,0 +1,94 @@
1#!/usr/bin/env python3
2"""Check DexNom/VIctory for new commits and optionally merge them into victory/.
3
4VIctory lives in this repository as a git subtree under ``victory/`` (added with
5``git subtree add --prefix=victory victory main``). This tool fetches the
6``victory`` remote, reports the commits that are not merged yet and, with
7``--merge``, pulls them in with ``git subtree pull`` so upstream history is kept
8and local changes under ``victory/`` are merged, not overwritten.
9
10Run from anywhere inside the repository:
11
12 python -I scripts/sync_victory.py # report only
13 python -I scripts/sync_victory.py --merge # report, then merge if clean
14
15Exit codes: 0 up to date or merged, 10 updates waiting (report only),
162 git failure, 3 working tree not clean (merge refused), 4 merge conflict.
17"""
18
19import argparse
20import datetime
21import os
22import subprocess
23import sys
24
25REMOTE = "victory"
26BRANCH = "main"
27PREFIX = "victory"
28
29
30def git(*args, check=True):
31 proc = subprocess.run(
32 ["git", *args],
33 stdout=subprocess.PIPE,
34 stderr=subprocess.STDOUT,
35 text=True,
36 encoding="utf-8",
37 errors="replace",
38 )
39 if check and proc.returncode != 0:
40 print(f"git {' '.join(args)} failed ({proc.returncode}):\n{proc.stdout}")
41 sys.exit(2)
42 return proc
43
44
45def main():
46 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
47 ap.add_argument("--merge", action="store_true", help="merge new commits with git subtree pull")
48 args = ap.parse_args()
49
50 top = git("rev-parse", "--show-toplevel").stdout.strip()
51 os.chdir(top)
52 stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
53
54 git("fetch", "--quiet", REMOTE, BRANCH)
55 upstream = git("rev-parse", f"{REMOTE}/{BRANCH}").stdout.strip()
56 merged = git("merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode == 0
57 if merged:
58 print(f"[{stamp}] {REMOTE}/{BRANCH} {upstream[:9]} is already merged; nothing to do.")
59 return 0
60
61 new = git("log", "--oneline", "--no-decorate", f"HEAD..{upstream}").stdout.strip().splitlines()
62 print(f"[{stamp}] {len(new)} new {REMOTE}/{BRANCH} commit(s) up to {upstream[:9]}:")
63 for line in new:
64 print(f" {line}")
65 if not args.merge:
66 return 10
67
68 dirty = git("status", "--porcelain", "--untracked-files=no").stdout.strip()
69 if dirty:
70 print("Working tree has uncommitted changes; commit or stash them, then run --merge again.")
71 print(dirty)
72 return 3
73
74 msg = (
75 f"Merge {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/ ({len(new)} commit(s))\n\n"
76 "Pulled with scripts/sync_victory.py --merge (git subtree pull).\n"
77 )
78 pull = git("subtree", "pull", f"--prefix={PREFIX}", REMOTE, BRANCH, "-m", msg, check=False)
79 print(pull.stdout.strip())
80 if pull.returncode != 0:
81 conflicts = git("diff", "--name-only", "--diff-filter=U", check=False).stdout.strip()
82 if conflicts:
83 print("Merge stopped on conflicts in:")
84 print(conflicts)
85 return 4
86 print("git subtree pull failed.")
87 return 2
88 print(f"Merged {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/.")
89 return 0
90
91
92if __name__ == "__main__":
93 sys.stdout.reconfigure(errors="replace")
94 sys.exit(main())
diff --git a/scripts/vs_input_survey.py b/scripts/vs_input_survey.py
index dcdead783..a4807249c 100644
--- a/scripts/vs_input_survey.py
+++ b/scripts/vs_input_survey.py
@@ -18,13 +18,19 @@ Standard library only. Nothing from the game is printed or written beyond counts
18""" 18"""
19import argparse 19import argparse
20import json 20import json
21import ntpath
21import os 22import os
23import posixpath
22import re 24import re
23import sys 25import sys
26import tempfile
24from collections import Counter 27from collections import Counter
25 28
26ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 29ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27sys.path.insert(0, os.path.join(ROOT, "tools")) 30sys.path.insert(0, os.path.join(ROOT, "tools"))
31from file_mode import published_mode # noqa: E402
32from replace_retry import replace as replace_retry # noqa: E402
33from report_paths import same_report_path # noqa: E402
28import shader_ir # noqa: E402 34import shader_ir # noqa: E402
29from shader_meta import SGPR_RMW # noqa: E402 35from shader_meta import SGPR_RMW # noqa: E402
30 36
@@ -112,21 +118,69 @@ def read_before_write(insns):
112 return read_s, read_v 118 return read_s, read_v
113 119
114 120
115def survey(dxbc_dir): 121def _safe_shader_stem(value):
116 with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: 122 """Validate an index.json 'file' basename against path traversal and return its stem."""
123 if (
124 not isinstance(value, str)
125 or not value
126 or any(ord(c) < 32 or ord(c) == 127 for c in value)
127 or ":" in value
128 or "/" in value
129 or "\\" in value
130 or ntpath.splitdrive(value)[0]
131 or ntpath.basename(value) != value
132 or posixpath.basename(value) != value
133 ):
134 raise ValueError(f"index.json has an invalid shader filename: {value!r}")
135 stem = os.path.splitext(value)[0]
136 if not stem or stem in (".", ".."):
137 raise ValueError(f"index.json has an invalid shader filename: {value!r}")
138 return stem
139
140
141def _write_json_atomic(path, payload):
142 """Write JSON to a sibling staging file and rename atomically, cleaning up read-only staging on error."""
143 dest = os.path.abspath(path)
144 parent = os.path.dirname(dest) or "."
145 staged = None
146 try:
147 with tempfile.NamedTemporaryFile(
148 mode="w", encoding="utf-8", newline="\n", delete=False,
149 dir=parent, prefix=".vs_input_survey-", suffix=".tmp",
150 ) as f:
151 staged = f.name
152 json.dump(payload, f, indent=1)
153 f.write("\n")
154 os.chmod(staged, published_mode(dest))
155 replace_retry(staged, dest)
156 staged = None
157 finally:
158 if staged is not None:
159 try:
160 os.chmod(staged, 0o600)
161 except OSError:
162 pass
163 try:
164 os.unlink(staged)
165 except OSError:
166 pass
167
168
169def _survey_detail(dxbc_dir):
170 with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8-sig") as f:
117 index = json.load(f) 171 index = json.load(f)
118 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): 172 if not isinstance(index, list) or not all(isinstance(e, dict) for e in index):
119 raise ValueError("index.json is not a list of shader entries") 173 raise ValueError("index.json is not a list of shader entries")
120 if not all(isinstance(e.get("file"), str) for e in index if e.get("stage") == "vs"): 174 names = [_safe_shader_stem(e.get("file")) for e in index if e.get("stage") == "vs"]
121 raise ValueError("index.json has a vertex shader entry without a string file")
122 names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"]
123 markers, vgprs, families = Counter(), Counter(), Counter() 175 markers, vgprs, families = Counter(), Counter(), Counter()
124 missing = 0 176 missing = 0
177 disasm_paths = []
125 for n in names: 178 for n in names:
126 path = os.path.join(dxbc_dir, "disasm", n + ".s") 179 path = os.path.join(dxbc_dir, "disasm", n + ".s")
127 if not os.path.isfile(path): 180 if not os.path.isfile(path):
128 missing += 1 181 missing += 1
129 continue 182 continue
183 disasm_paths.append(path)
130 with open(path, encoding="utf-8", errors="replace") as f: 184 with open(path, encoding="utf-8", errors="replace") as f:
131 text = f.read() 185 text = f.read()
132 _, read_v = read_before_write(shader_ir.parse_file(path)["insns"]) 186 _, read_v = read_before_write(shader_ir.parse_file(path)["insns"])
@@ -146,25 +200,39 @@ def survey(dxbc_dir):
146 families["reads v0 (vertex id)" + (" and v3 (instance id)" if 3 in read_v else "")] += 1 200 families["reads v0 (vertex id)" + (" and v3 (instance id)" if 3 in read_v else "")] += 1
147 else: 201 else:
148 families["reads neither v0 nor a fetch call"] += 1 202 families["reads neither v0 nor a fetch call"] += 1
149 return {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers), 203 result = {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers),
150 "input_vgprs_read": dict(sorted(vgprs.items(), key=lambda kv: int(kv[0][1:]))), 204 "input_vgprs_read": dict(sorted(vgprs.items(), key=lambda kv: int(kv[0][1:]))),
151 "families": dict(families)} 205 "families": dict(families)}
206 return result, disasm_paths
207
208
209def survey(dxbc_dir):
210 return _survey_detail(dxbc_dir)[0]
152 211
153 212
154def main(): 213def main(argv=None):
155 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 214 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
156 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py") 215 ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py")
157 ap.add_argument("--json", help="also write the counts as JSON") 216 ap.add_argument("--json", help="also write the counts as JSON")
158 a = ap.parse_args() 217 a = ap.parse_args(argv)
159 index_path = os.path.join(a.dxbc, "index.json") 218 index_path = os.path.join(a.dxbc, "index.json")
160 if a.json and os.path.exists(a.json) and os.path.exists(index_path) and os.path.samefile(a.json, index_path): 219 if a.json:
161 print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr) 220 if os.path.isdir(a.json):
162 return 2 221 print(f"vs_input_survey: error: --json is a directory: {a.json}", file=sys.stderr)
222 return 2
223 if same_report_path(a.json, index_path) or same_report_path(a.json, a.dxbc):
224 print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr)
225 return 2
163 try: 226 try:
164 r = survey(a.dxbc) 227 r, disasm_paths = _survey_detail(a.dxbc)
165 except (OSError, ValueError) as e: # missing or non-folder <dxbc>, unreadable, non-UTF-8 or malformed index.json 228 except (OSError, ValueError) as e: # missing or non-folder <dxbc>, unreadable, non-UTF-8 or malformed index.json
166 print(f"vs_input_survey: error: cannot read {index_path}: {e}", file=sys.stderr) 229 print(f"vs_input_survey: error: cannot read {index_path}: {e}", file=sys.stderr)
167 return 2 230 return 2
231 if a.json:
232 for src_path in disasm_paths:
233 if same_report_path(a.json, src_path):
234 print(f"vs_input_survey: error: --json would overwrite the input {src_path}", file=sys.stderr)
235 return 2
168 m = r["markers"] 236 m = r["markers"]
169 print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)") 237 print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)")
170 print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}") 238 print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}")
@@ -175,8 +243,7 @@ def main():
175 print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout") 243 print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout")
176 if a.json: 244 if a.json:
177 try: 245 try:
178 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 246 _write_json_atomic(a.json, r)
179 json.dump(r, f, indent=1)
180 except OSError as e: 247 except OSError as e:
181 print(f"vs_input_survey: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) 248 print(f"vs_input_survey: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
182 return 2 249 return 2
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md
index 92121a211..1ace54184 100644
--- a/scripts/windows-boot/README.md
+++ b/scripts/windows-boot/README.md
@@ -38,6 +38,7 @@ Only when your shell has not set them already (`-DryRun` prints the final list):
38| `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | 38| `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit |
39| `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup | 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 | 40| `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\pipeline-cache` | one warmed cache shared by every build you boot |
41| `LEONIDA_PIPELINE_JOURNAL_SEED_DIR` | `pipeline_cache.d` beside `gta6rt.exe`, when it exists | the journal `gta6rt --precompile-pipelines` fills there when it runs without `LEONIDA_PIPELINE_CACHE_DIR`, read-only, so its pipelines are not compiled again. Not set when the boot's own journal (`<cache folder>\pipeline_cache.d`, or beside `gta6rt.exe` when the cache folder is empty) is that folder or one holds the other, compared through Windows' final paths (so a junction, symbolic link, substituted or mapped drive, 8.3 name or `\\?\` / `\\.\` prefix counts as the same folder), or when the cache folder is a relative path. `LEONIDA_PIPELINE_JOURNAL_SEED_DIR=` (empty) turns the seed off. If the runtime still logs `[rt] d3d12: invalid or overlapping compute journal directories; journal disabled`, set it so. On NVIDIA, run the pre-compile with the same `LEONIDA_DEVICE_FAULT` as the boot (this script sets `1`): the diagnostics config is part of the journal's file names |
41| `LEONIDA_PEEK` / `_SECONDS` | the game-state and session-state RVAs from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (measured locally, not kept here; unset: no peek) / `5` | game state and session state (low dword), the two numbers every RESULT reports | 42| `LEONIDA_PEEK` / `_SECONDS` | the game-state and session-state RVAs from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (measured locally, not kept here; unset: no peek) / `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_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_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive |
@@ -98,3 +99,33 @@ game processes on one GPU make both runs meaningless and can take the driver dow
98| `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 | 99| `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 |
99 100
100Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). 101Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell).
102
103## Recover a stack from a manually mapped image
104
105When the exception stack stops inside the mapped executable, run `mapped_stack.py` on the existing
106private dump. Supply the exact PE from the crashing build and an x64 CDB from Debugging Tools for
107Windows. If CDB is on your PATH, omit `--cdb`. The optional `--symbols` takes one local directory
108containing the matching runtime images and PDBs.
109
110```powershell
111py -3 -I scripts\windows-boot\mapped_stack.py D:\runs\fault\crash.dmp D:\package\title.exe --symbols D:\build\RelWithDebInfo --cdb "C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe"
112```
113
114The command derives the mapping base, including a relocated base, by locating a unique captured
115instruction window in an executable section of the supplied PE. It checks for a file-backed x64
116unwind entry at the exception RIP and compares captured bytes from the first header page and that
117function's unwind metadata when available.
118A small dump can establish a local code match only. Use the original image even if another build
119has the same function. Exit-only snapshots, faults outside the supplied image, leaf functions
120without unwind entries, and missing, patched or ambiguous instruction windows cannot establish
121this stack.
122
123CDB reads the exception context and uses the disk image's unwind data to recover callers. The
124script makes a temporary copy of the PE beside the dump under the debugger alias `leonida_mapped`.
125It disables network symbols and writes private frame rows to a new `mapped-stack.txt` beside the
126dump. Use `--output` for a different new file. A successful walk recovers at least one caller and
127can stop when later stack memory or module information is missing. Keep dumps and reports outside
128the checkout and share only the outcome and frame count.
129
130Run the synthetic regression tests with `py -3 -I tests\test_mapped_stack.py`. To include the
131native CDB walk, put x64 CDB on PATH or set `LEONIDA_TEST_CDB` to its full path.
diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1
index db11e4e76..9b218d63e 100644
--- a/scripts/windows-boot/boot.ps1
+++ b/scripts/windows-boot/boot.ps1
@@ -281,6 +281,75 @@ foreach ($pair in $EnvPairs) {
281 $bootEnv[$Matches[1]] = $Matches[2] 281 $bootEnv[$Matches[1]] = $Matches[2]
282} 282}
283if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] } 283if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] }
284# The journal `gta6rt --precompile-pipelines` fills beside gta6rt.exe (when it runs without LEONIDA_PIPELINE_CACHE_DIR)
285# is read here as the runtime's read-only seed (LEONIDA_PIPELINE_JOURNAL_SEED_DIR, docs/d3d12_vulkan.md), so the pipelines
286# it holds are not compiled again in the boot's own cache folder. Only when this shell or -SetEnv/KEY= did not decide, and
287# when the two journals are distinct: the runtime turns its journal off for a seed that is, holds or sits in its writable
288# journal (pipeline_cache_journal.h, resolve_roots). A relative cache folder is resolved by the runtime against its own
289# working folder, so it gets no seed here; a name that cannot be resolved gets none either, rather than a stop.
290if (-not $bootEnv.Contains("LEONIDA_PIPELINE_JOURNAL_SEED_DIR")) {
291 # Windows' final path of a folder (GetFinalPathNameByHandle) sees through junctions, symbolic links, substituted
292 # and mapped drives, short 8.3 names and the \\?\ and \\.\ prefixes, as the runtime's std::filesystem checks do.
293 # A folder that does not exist yet is named from its deepest existing parent. Without the helper (a compile error,
294 # a restricted session), the comparison falls back to the spelled paths.
295 function Get-FinalFolderPath([string]$path) {
296 $plain = ($path -replace '^\\\\[?.]\\UNC\\', '\\' -replace '^\\\\[?.]\\', '').TrimEnd('\', '/')
297 try {
298 if (-not ('LeonidaFinalPath' -as [type])) {
299 Add-Type -ErrorAction Stop -TypeDefinition @'
300using System; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles;
301public static class LeonidaFinalPath {
302 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
303 static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr sa, uint disposition, uint flags, IntPtr template);
304 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
305 static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder buffer, uint length, uint flags);
306 public static string Of(string path) {
307 // No access asked, all sharing, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS (needed to open a folder).
308 using (SafeFileHandle h = CreateFileW(path, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) {
309 if (h.IsInvalid) return null;
310 StringBuilder b = new StringBuilder(32768);
311 uint n = GetFinalPathNameByHandleW(h, b, (uint)b.Capacity, 0);
312 return (n == 0 || n >= b.Capacity) ? null : b.ToString();
313 }
314 }
315}
316'@
317 }
318 $existing = $path.TrimEnd('\', '/'); $tail = @()
319 while ($existing -and -not [System.IO.Directory]::Exists($existing)) {
320 $tail = @([System.IO.Path]::GetFileName($existing)) + $tail
321 $existing = [System.IO.Path]::GetDirectoryName($existing)
322 }
323 if (-not $existing) { return $plain }
324 $final = [LeonidaFinalPath]::Of($existing)
325 if (-not $final) { return $plain }
326 $final = $final -replace '^\\\\\?\\UNC\\', '\\' -replace '^\\\\\?\\', ''
327 foreach ($part in $tail) { $final = [System.IO.Path]::Combine($final, $part) }
328 return $final.TrimEnd('\', '/')
329 } catch { return $plain }
330 }
331 $seed = $null
332 try {
333 $runtimeFull = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($RuntimeDir)
334 $precompiled = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($runtimeFull, "pipeline_cache.d")).TrimEnd('\', '/')
335 if (Test-Path -LiteralPath $precompiled -PathType Container) {
336 $cacheDir = $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]
337 $ownJournal = $null
338 if (-not $cacheDir) { $ownJournal = $precompiled } # the runtime then keeps its journal beside gta6rt.exe
339 elseif ($cacheDir -match '^([A-Za-z]:[\\/]|[\\/]{2})') {
340 $ownJournal = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($cacheDir, "pipeline_cache.d")).TrimEnd('\', '/')
341 }
342 if ($ownJournal) {
343 $a = Get-FinalFolderPath $ownJournal
344 $b = Get-FinalFolderPath $precompiled
345 $c = [System.StringComparison]::OrdinalIgnoreCase
346 $overlap = $a.Equals($b, $c) -or $a.StartsWith($b + '\', $c) -or $b.StartsWith($a + '\', $c)
347 if (-not $overlap) { $seed = $precompiled }
348 }
349 }
350 } catch { $seed = $null }
351 if ($seed) { $bootEnv["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = $seed }
352}
284 353
285$launchMode = if ($FirstRunUi) { "--first-run-ui" } else { "--run" } 354$launchMode = if ($FirstRunUi) { "--first-run-ui" } else { "--run" }
286$gameArgs = @($launchMode, $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs 355$gameArgs = @($launchMode, $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs
diff --git a/scripts/windows-boot/mapped_stack.py b/scripts/windows-boot/mapped_stack.py
new file mode 100644
index 000000000..b88a4eb19
--- /dev/null
+++ b/scripts/windows-boot/mapped_stack.py
@@ -0,0 +1,313 @@
1"""Recover a private x64 exception stack with an explicitly supplied, manually mapped PE."""
2import argparse
3from dataclasses import dataclass
4import mmap
5import os
6from pathlib import Path, PureWindowsPath
7import re
8import shutil
9import struct
10import subprocess
11import sys
12import tempfile
13
14ROOT = Path(__file__).resolve().parents[2]
15sys.path.insert(0, str(ROOT / "tools"))
16from pe_inspect import DIR_EXCEPTION, PeFormatError, PeImage
17from report_paths import same_report_path
18
19
20def require(condition, message):
21 if not condition:
22 raise ValueError(message)
23
24
25def bounds(offset, size, end):
26 require(0 <= offset <= end and 0 <= size <= end - offset, "truncated or invalid binary structure")
27
28
29def read(data, fmt, offset):
30 fmt = "<" + fmt
31 bounds(offset, struct.calcsize(fmt), len(data))
32 return struct.unpack_from(fmt, data, offset)
33
34
35def records(start, count, stride, end):
36 bounds(start, count * stride, end)
37 return range(start, start + count * stride, stride)
38
39
40def dump_streams(dump):
41 magic, version, count, directory = read(dump, "4sIII", 0)
42 require(magic == b"MDMP" and version & 0xffff == 0xa793, "expected a Windows minidump")
43 streams = {}
44 for pos in records(directory, count, 12, len(dump)):
45 kind, size, offset = read(dump, "III", pos)
46 if kind in (4, 5, 6, 7, 9):
47 require(kind not in streams, "duplicate minidump stream")
48 bounds(offset, size, len(dump))
49 streams[kind] = (offset, offset + size)
50 return streams
51
52
53def stream(streams, kind, minimum):
54 require(kind in streams, "required minidump stream missing")
55 start, end = streams[kind]
56 bounds(start, minimum, end)
57 return start, end
58
59
60def exception_context(dump, streams):
61 system, _ = stream(streams, 7, 2)
62 require(read(dump, "H", system)[0] == 9, "expected an AMD64 dump")
63 require(6 in streams, "dump has no exception context (exit snapshots are unsupported)")
64 exc, _ = stream(streams, 6, 168)
65 size, offset = read(dump, "II", exc + 160)
66 bounds(offset, size, len(dump))
67 require(size >= 256 and read(dump, "I", offset + 48)[0] & 0x100001 == 0x100001,
68 "missing AMD64 control context")
69 return read(dump, "I", exc)[0], read(dump, "Q", offset + 248)[0], read(dump, "Q", offset + 152)[0]
70
71
72def captured_ranges(dump, streams):
73 if 5 in streams: # MINIDUMP_MEMORY_LIST
74 pos, end = stream(streams, 5, 4)
75 for entry in records(pos + 4, read(dump, "I", pos)[0], 16, end):
76 address, size, offset = read(dump, "QII", entry)
77 bounds(offset, size, len(dump))
78 yield address, size, offset
79 if 9 in streams: # MINIDUMP_MEMORY64_LIST stores all bytes consecutively
80 pos, end = stream(streams, 9, 16)
81 count, offset = read(dump, "QQ", pos)
82 for entry in records(pos + 16, count, 16, end):
83 address, size = read(dump, "QQ", entry)
84 bounds(offset, size, len(dump))
85 yield address, size, offset
86 offset += size
87
88
89def instruction_window(dump, streams, rip):
90 window = None
91 for address, size, offset in captured_ranges(dump, streams):
92 if address <= rip < address + size:
93 start, end = max(rip - 128, address), min(rip + 128, address + size)
94 sample = (start, dump[offset + start - address:offset + end - address])
95 require(window is None or sample == window, "ambiguous instruction capture")
96 window = sample
97 require(window is not None, "exception instructions were not captured")
98 require(len(window[1]) >= 32 and len(set(window[1])) >= 8, "insufficient distinctive instruction bytes")
99 return window
100
101
102@dataclass(frozen=True)
103class Mapping:
104 base: int
105 size: int
106 timestamp: int
107 thread: int
108 rip: int
109 rsp: int
110
111
112def mapping_base(pe, address, sample):
113 # Locate the captured instructions in executable disk bytes. This gives the
114 # actual mapping even after rebasing, without trusting the PE preferred base.
115 base = None
116 previous_end = pe.size_of_headers
117 bounds(0, previous_end, min(pe.size_of_image, len(pe.data)))
118 for section in sorted(pe.sections, key=lambda item: item["rva"]):
119 rva, raw, raw_size = section["rva"], section["rawptr"], section["rawsize"]
120 span = section["vsize"] or raw_size
121 require(rva >= previous_end, "overlapping PE sections")
122 bounds(rva, span, pe.size_of_image)
123 bounds(raw, raw_size, len(pe.data))
124 previous_end = rva + span
125 if not section["exec"]:
126 continue
127 raw_end = raw + min(span, raw_size)
128 pos = pe.data.find(sample, raw, raw_end)
129 if pos >= 0:
130 require(base is None and pe.data.find(sample, pos + 1, raw_end) < 0,
131 "instructions match multiple locations in the image")
132 base = address - (rva + pos - raw)
133 require(base is not None, "exception instructions do not match this PE")
134 require(base > 0 and base % 0x10000 == 0 and base + pe.size_of_image <= 2**64, "invalid inferred mapping base")
135 return base
136
137
138def verify_unwind(dump, streams, pe, base, rip):
139 # A synthetic module label alone does not prove that CDB has unwind data.
140 # Require a file-backed RUNTIME_FUNCTION for the fault, and cross-check its
141 # metadata and the PE headers wherever the dump actually captured them.
142 pdata, pdata_size = pe.directory(DIR_EXCEPTION)
143 pdata_off = pe.offset(pdata, pdata_size)
144 require(pdata >= pe.size_of_headers and pdata_off is not None and pdata_size % 12 == 0,
145 "missing or invalid x64 exception directory")
146 metadata = [(base, min(pe.size_of_headers, 4096), 0)]
147 function_found = False
148 for entry in range(pdata_off, pdata_off + pdata_size, 12):
149 begin, end, unwind = read(pe.data, "III", entry)
150 if begin <= rip - base < end:
151 require(not function_found, "ambiguous x64 function entry")
152 function_found = True
153 unwind_off = pe.offset(unwind, 4)
154 require(unwind >= pe.size_of_headers and unwind_off is not None
155 and pe.data[unwind_off] & 7 in (1, 2), "unsupported x64 unwind information")
156 # The header is followed by an array of 2-byte unwind codes.
157 unwind_size = 4 + pe.data[unwind_off + 2] * 2
158 require(pe.offset(unwind, unwind_size) is not None, "truncated x64 unwind codes")
159 metadata.extend([(base + pdata + entry - pdata_off, 12, entry), (base + unwind, unwind_size, unwind_off)])
160 require(function_found, "no x64 unwind entry covers the exception instructions")
161 for address, length, offset in captured_ranges(dump, streams):
162 for start, count, raw in metadata:
163 lo, hi = max(address, start), min(address + length, start + count)
164 if lo < hi:
165 disk = pe.data[raw + lo - start:raw + hi - start]
166 require(dump[offset + lo - address:offset + hi - address] == disk,
167 "captured image metadata differs from the supplied PE")
168
169
170def check_registered_modules(dump, streams, base, size):
171 modules, end = stream(streams, 4, 4)
172 for entry in records(modules + 4, read(dump, "I", modules)[0], 108, end):
173 loaded, extent = read(dump, "QI", entry)
174 require(base + size <= loaded or base >= loaded + extent, "mapping overlaps a registered module")
175 name_rva = read(dump, "I", entry + 20)[0]
176 length = read(dump, "I", name_rva)[0]
177 require(0 < length <= 65534 and length % 2 == 0, "invalid registered module name")
178 start = name_rva + 4
179 bounds(start, length, len(dump))
180 name = PureWindowsPath(dump[start:start + length].decode("utf-16-le"))
181 require(name.stem.casefold() != "leonida_mapped", "staging name already used by a registered module")
182 require((len(name.parts) == 1 and not name.anchor)
183 or re.fullmatch(r"[A-Za-z]:", name.drive) and name.is_absolute(),
184 "dump contains a nonlocal module path")
185 if os.name == "nt" and name.drive:
186 require(local_drive(name.anchor), "dump references a module on a nonlocal drive")
187
188
189def identify(dump, image):
190 streams = dump_streams(dump)
191 thread, rip, rsp = exception_context(dump, streams)
192 address, sample = instruction_window(dump, streams, rip)
193 pe = PeImage(image)
194 require(pe.machine == 0x8664 and pe.is64, "expected an AMD64 PE32+ image")
195 base = mapping_base(pe, address, sample)
196 check_registered_modules(dump, streams, base, pe.size_of_image)
197 verify_unwind(dump, streams, pe, base, rip)
198 return Mapping(base, pe.size_of_image, pe.timestamp, thread, rip, rsp)
199
200
201ROW = re.compile(r"^\s*([0-9a-f]+)\s+[0-9a-f]{8}\x60[0-9a-f]{8}\s+[0-9a-f]{8}\x60[0-9a-f]{8}\s+(.+)", re.I)
202BEGIN = "LEONIDA_STACK_BEGIN"
203END = "LEONIDA_STACK_END"
204
205
206def stack_rows(output, mapping):
207 lines = output.splitlines()
208 require(lines.count(BEGIN) == 1 and lines.count(END) == 1, "CDB did not finish the stack walk")
209 report = lines[lines.index(BEGIN) + 1:lines.index(END)]
210 require(report and report[0].strip().lower() == f"{mapping.rip:x} {mapping.rsp:x}",
211 "CDB could not select the dump's exception context")
212 rows = []
213 for line in report[1:]:
214 if "following frames may be wrong" in line.lower():
215 break
216 frame = ROW.match(line)
217 if frame:
218 require(int(frame[1], 16) == len(rows), "unexpected CDB frame sequence")
219 if not rows:
220 require(re.match(r"leonida_mapped(?:[+!]|$)", frame[2], re.I), "CDB did not load the mapped image")
221 rows.append(line.strip())
222 require(len(rows) >= 2, "CDB could not recover a caller")
223 return rows
224
225
226def debugger_stack(cdb, dump, symbols, scratch, mapping):
227 # CDB parses its own command language. Only parsed integers enter it. The
228 # PE always has the same safe filename in a new, private working directory.
229 command = (f".reload /f leonida_mapped.exe={mapping.base:x},{mapping.size:x},{mapping.timestamp:x}; "
230 f'~~[{mapping.thread:x}]s; .ecxr; .echo {BEGIN}; '
231 f'.printf "%I64x %I64x\\n", @rip, @rsp; kn 40; .echo {END}; q')
232 require(not any(c in str(scratch) for c in ";*"), "temporary directory cannot form a debugger search path")
233 search = str(scratch) if symbols is None else str(scratch) + ";" + str(symbols)
234 env = {key: value for key, value in os.environ.items() if key.upper() in {"SYSTEMROOT", "WINDIR", "SYSTEMDRIVE"}}
235 env.update(dict.fromkeys(("TEMP", "TMP", "LOCALAPPDATA", "APPDATA", "USERPROFILE"), str(scratch)))
236 run = subprocess.run([str(cdb), "-sins", "-sicv", "-netsyms:no", "-nosqm", "-noshell", "-y", search,
237 "-i", search, "-srcpath", str(scratch), "-z", str(dump), "-c", command],
238 cwd=scratch, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
239 stderr=subprocess.STDOUT, timeout=90)
240 require(run.returncode == 0, "CDB failed to analyze the dump")
241 return stack_rows(run.stdout.decode("utf-8", errors="replace"), mapping)
242
243
244def local_drive(anchor):
245 import ctypes
246 return ctypes.windll.kernel32.GetDriveTypeW(str(anchor)) in (2, 3, 5, 6)
247
248
249def local_path(path):
250 # Reject UNC, device namespace and mapped network drives before opening
251 # inputs or using a directory as a debugger search path.
252 absolute = Path(os.path.abspath(path))
253 require(re.fullmatch(r"[A-Za-z]:", absolute.drive) and local_drive(absolute.anchor),
254 "expected a local filesystem path")
255 resolved = absolute.resolve()
256 require(re.fullmatch(r"[A-Za-z]:", resolved.drive) and local_drive(resolved.anchor),
257 "path resolves outside the local filesystem")
258 return resolved
259
260
261def recover(args):
262 require(os.name == "nt", "the x64 Windows debugger is required")
263 dump, image = local_path(args.dump), local_path(args.image)
264 report = local_path(args.output) if args.output else dump.with_name("mapped-stack.txt")
265 require(not report.is_relative_to(ROOT) and not dump.parent.is_relative_to(ROOT),
266 "keep the dump and the private report outside the checkout")
267 require(not any(same_report_path(report, path) for path in (dump, image)), "report collides with an input")
268 require(not report.exists(), "output already exists; choose a fresh report path")
269 debugger = args.cdb or shutil.which("cdb.exe")
270 require(debugger, "x64 CDB not found; provide --cdb")
271 cdb = local_path(debugger)
272 symbols = local_path(args.symbols) if args.symbols else None
273 require(symbols is None or symbols.is_dir() and not any(c in str(symbols) for c in ";*"),
274 "--symbols requires a single local directory")
275 with tempfile.TemporaryDirectory(dir=dump.parent) as scratch:
276 staged = Path(scratch) / "leonida_mapped.exe"
277 shutil.copyfile(image, staged)
278 with dump.open("rb") as df, staged.open("rb") as ef:
279 with mmap.mmap(df.fileno(), 0, access=mmap.ACCESS_READ) as md, \
280 mmap.mmap(ef.fileno(), 0, access=mmap.ACCESS_READ) as pe:
281 mapping = identify(md, pe)
282 rows = debugger_stack(cdb, dump, symbols, scratch, mapping)
283 # On Windows rename publishes the completed report and refuses an existing
284 # destination, including one created by a concurrent analysis.
285 with tempfile.TemporaryDirectory(dir=report.parent) as pending:
286 finished = Path(pending) / "stack.txt"
287 finished.write_text("\n".join(rows) + "\n", encoding="utf-8", newline="\n")
288 finished.rename(report)
289 print(f"Recovered {len(rows)} frames. Keep the stack report private.")
290
291
292def main():
293 parser = argparse.ArgumentParser(description=__doc__)
294 parser.add_argument("dump", type=Path, help="private Windows exception minidump")
295 parser.add_argument("image", type=Path, help="the exact mapped PE from the crashing build")
296 parser.add_argument("--symbols", type=Path, help="local directory with matching runtime images and PDBs")
297 parser.add_argument("--cdb", type=Path, help="path to the trusted x64 cdb.exe (default: search PATH)")
298 parser.add_argument("--output", type=Path, help="new private output path (default: mapped-stack.txt beside dump)")
299 args = parser.parse_args()
300 try:
301 recover(args)
302 except PeFormatError:
303 parser.exit(1, "invalid PE image\n")
304 except ValueError as error:
305 parser.exit(1, f"{error}\n")
306 except subprocess.TimeoutExpired:
307 parser.exit(1, "CDB timed out\n")
308 except OSError as error:
309 parser.exit(1, f"local file or debugger operation failed ({type(error).__name__})\n")
310
311
312if __name__ == "__main__":
313 main()