diff options
| author | kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> | 2026-12-01 19:13:49 +0800 |
|---|---|---|
| committer | kirigayakazima <46666711+kirigayakazima@users.noreply.github.com> | 2026-12-01 19:13:49 +0800 |
| commit | f613e6d8ea682e3c4e4c6d90d47f3c57692713b4 (patch) | |
| tree | bc9c50715ee96ea57aacf85feb1b68270395e553 /scripts | |
| parent | bf41c1699f26e22f9edad2e3faebca8a3782fdfe (diff) | |
| parent | 3ee508b469012606cf90f6efe7bec5ef65c446e7 (diff) | |
Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
# scripts/merge_check.py
Diffstat (limited to 'scripts')
47 files changed, 4435 insertions, 629 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py index 50fc5500e..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 | """ |
| 13 | import argparse | 13 | import argparse |
| 14 | import errno | ||
| 14 | import json | 15 | import json |
| 15 | import os | 16 | import os |
| 16 | import re | 17 | import re |
| 17 | import struct | 18 | import struct |
| 18 | import sys | 19 | import sys |
| 20 | import tempfile | ||
| 19 | from collections import Counter | 21 | from collections import Counter |
| 20 | 22 | ||
| 21 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 23 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 22 | sys.path.insert(0, os.path.join(ROOT, "tools")) | 24 | sys.path.insert(0, os.path.join(ROOT, "tools")) |
| 25 | from file_mode import published_mode # noqa: E402 | ||
| 26 | from replace_retry import replace as replace_retry # noqa: E402 | ||
| 23 | from report_paths import same_report_path # noqa: E402 | 27 | from report_paths import same_report_path # noqa: E402 |
| 24 | import shader_ir # noqa: E402 | 28 | import shader_ir # noqa: E402 |
| 25 | from shader_meta import SGPR_RMW # noqa: E402 | 29 | from 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} |
| @@ -215,10 +231,13 @@ def rbw_registers(insns): | |||
| 215 | is_dual_dst = op.startswith("v_") and ( | 231 | is_dual_dst = op.startswith("v_") and ( |
| 216 | "_co_" in op or op.startswith(("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) | 232 | "_co_" in op or op.startswith(("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) |
| 217 | ) | 233 | ) |
| 234 | # The assembler's short form v_add_co_ci_u32 vD, src0, src1 (also sub/subrev) has VCC as its carry-out and | ||
| 235 | # carry-in and names neither: args[1] is src0, read, not a carry-out destination. | ||
| 236 | is_short_co_ci = op.endswith("_co_ci_u32") and len(args) == 3 | ||
| 218 | # Carry-out / scale-out forms write the VGPR and scalar mask first, even when they also take a carry-in source. | 237 | # Carry-out / scale-out forms write the VGPR and scalar mask first, even when they also take a carry-in source. |
| 219 | if is_lds_load: | 238 | if is_lds_load: |
| 220 | dsts, srcs = [], args | 239 | dsts, srcs = [], args |
| 221 | elif not is_no_dest and is_dual_dst and len(args) >= 2: | 240 | elif not is_no_dest and is_dual_dst and len(args) >= 2 and not is_short_co_ci: |
| 222 | dsts = args[:2] | 241 | dsts = args[:2] |
| 223 | srcs = args[2:] | 242 | srcs = args[2:] |
| 224 | elif is_no_dest: | 243 | elif is_no_dest: |
| @@ -370,6 +389,32 @@ def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), l | |||
| 370 | return out | 389 | return out |
| 371 | 390 | ||
| 372 | 391 | ||
| 392 | def 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 | |||
| 373 | def print_report(rep): | 418 | def print_report(rep): |
| 374 | for st, rec in rep.items(): | 419 | for st, rec in rep.items(): |
| 375 | 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']}) ===") |
| @@ -427,7 +472,7 @@ def main(argv=None): | |||
| 427 | print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) | 472 | print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) |
| 428 | return 2 | 473 | return 2 |
| 429 | 474 | ||
| 430 | 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 |
| 431 | try: | 476 | try: |
| 432 | 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) |
| 433 | except ReportInputCollision as error: | 478 | except ReportInputCollision as error: |
| @@ -436,10 +481,7 @@ def main(argv=None): | |||
| 436 | print_report(rep) | 481 | print_report(rep) |
| 437 | if a.json_out: | 482 | if a.json_out: |
| 438 | try: | 483 | try: |
| 439 | os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True) | 484 | write_json(a.json_out, rep) |
| 440 | with open(a.json_out, "w", encoding="utf-8", newline="\n") as f: | ||
| 441 | json.dump(rep, f, indent=2) | ||
| 442 | f.write("\n") | ||
| 443 | except OSError as e: | 485 | except OSError as e: |
| 444 | 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) |
| 445 | return 1 | 487 | return 1 |
diff --git a/scripts/bench_translate.py b/scripts/bench_translate.py new file mode 100644 index 000000000..5e9ce4f94 --- /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 | |||
| 8 | The repository tests what the translator *emits*; nothing measures how long it takes. A change to the parser or the | ||
| 9 | instruction table can cost a large share of the build time and still pass every test, and about 26,503 shaders are | ||
| 10 | translated per build. This script is the cheap check for that: it times `rdna2spirv.translate()` on inputs that | ||
| 11 | need 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 | |||
| 20 | Times are best-of-`--runs` seconds of one `translate()` call per program; medians are not used because a single | ||
| 21 | unlucky run (another process taking the CPU) is what dominates the tail. The numbers are machine-specific: compare | ||
| 22 | them with a run of the same commit, not with the table in the pull request that added this script. | ||
| 23 | """ | ||
| 24 | import argparse | ||
| 25 | import json | ||
| 26 | import os | ||
| 27 | import struct | ||
| 28 | import subprocess | ||
| 29 | import sys | ||
| 30 | import tempfile | ||
| 31 | import time | ||
| 32 | import warnings | ||
| 33 | |||
| 34 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 35 | TOOLS = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 36 | FIXTURES = os.path.join(ROOT, "tests", "semantic", "fixtures", "disasm") | ||
| 37 | sys.dont_write_bytecode = True | ||
| 38 | sys.path.insert(0, TOOLS) | ||
| 39 | import rdna2spirv # noqa: E402 | ||
| 40 | |||
| 41 | # A DXBC container with zero parts declares no inputs, which is enough for a listing that reads no attribute | ||
| 42 | # (tests/semantic/support.py uses the same stub). | ||
| 43 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 44 | |||
| 45 | ALU_BODY = ("\tv_add_f32 v1, v1, 1.0\n" | ||
| 46 | "\tv_mul_f32 v2, v1, 2.0\n" | ||
| 47 | "\tv_cndmask_b32 v3, v1, v2, vcc\n" | ||
| 48 | "\tv_and_b32 v4, v3, 0xff\n") | ||
| 49 | NOP_BODY = "\ts_nop 0\n" | ||
| 50 | |||
| 51 | |||
| 52 | def synthetic(name, body, instructions): | ||
| 53 | """A whole pixel shader: comment, the repeated body, and the export the stage needs to be a shader.""" | ||
| 54 | lines = [f"; ps_{name} synthetic benchmark program\n"] | ||
| 55 | lines.extend([body] * ((instructions + body.count("\n") - 1) // body.count("\n"))) | ||
| 56 | lines.extend(["\tv_mov_b32 v1, 1\n", | ||
| 57 | "\texp mrt0 v1, v1, v1, v1 done\n", | ||
| 58 | "\ts_waitcnt expcnt(0)\n", | ||
| 59 | "\ts_endpgm\n"]) | ||
| 60 | return "".join(lines).encode("utf-8") | ||
| 61 | |||
| 62 | |||
| 63 | def translate_bytes(stem, listing, runs): | ||
| 64 | """Best of `runs` wall-clock seconds for one translate() of this listing, and the instruction count.""" | ||
| 65 | with tempfile.TemporaryDirectory() as tmp: | ||
| 66 | os.mkdir(os.path.join(tmp, "disasm")) | ||
| 67 | with open(os.path.join(tmp, "disasm", stem + ".s"), "wb") as f: | ||
| 68 | f.write(listing) | ||
| 69 | with open(os.path.join(tmp, stem + ".dxbc"), "wb") as f: | ||
| 70 | f.write(STUB_DXBC) | ||
| 71 | path = os.path.join(tmp, "disasm", stem + ".s") | ||
| 72 | best = None | ||
| 73 | for _ in range(runs): | ||
| 74 | start = time.perf_counter() | ||
| 75 | with warnings.catch_warnings(): | ||
| 76 | # The translator leaves its .dxbc handle to the garbage collector; that is its own business here. | ||
| 77 | warnings.simplefilter("ignore") | ||
| 78 | rdna2spirv.translate(path) | ||
| 79 | elapsed = time.perf_counter() - start | ||
| 80 | best = elapsed if best is None else min(best, elapsed) | ||
| 81 | return best | ||
| 82 | |||
| 83 | |||
| 84 | def instruction_count(listing): | ||
| 85 | return sum(1 for line in listing.decode("utf-8", "replace").splitlines() | ||
| 86 | if line.startswith("\t") and line.strip()) | ||
| 87 | |||
| 88 | |||
| 89 | def corpus_rows(runs): | ||
| 90 | """Time every fixture that translates on its own, and count the ones that need an FSSM header.""" | ||
| 91 | rows, skipped = [], [] | ||
| 92 | for name in sorted(os.listdir(FIXTURES)): | ||
| 93 | if not name.endswith(".s"): | ||
| 94 | continue | ||
| 95 | stem = name[:-2] | ||
| 96 | if stem.startswith("cs_"): | ||
| 97 | # A compute listing reads its group size and RSRC2 out of the FSSM header, which translate() takes from | ||
| 98 | # <dir>/../fssm/<stem>.fssm; the semantic tests pass it per fixture (tests/semantic/support.py). | ||
| 99 | skipped.append(f"{stem}: compute listing, needs a FSSM header") | ||
| 100 | continue | ||
| 101 | with open(os.path.join(FIXTURES, name), "rb") as f: | ||
| 102 | listing = f.read() | ||
| 103 | try: | ||
| 104 | seconds = translate_bytes(stem, listing, runs) | ||
| 105 | except Exception as error: # a listing this run cannot translate: report it, never count it as fast | ||
| 106 | skipped.append(f"{stem}: {type(error).__name__}: {error}") | ||
| 107 | continue | ||
| 108 | instructions = instruction_count(listing) | ||
| 109 | rows.append({"name": stem, "instructions": instructions, "seconds": seconds, | ||
| 110 | "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0}) | ||
| 111 | return rows, skipped | ||
| 112 | |||
| 113 | |||
| 114 | def synthetic_rows(runs, size): | ||
| 115 | rows = [] | ||
| 116 | for name, body, instructions in (("alu", ALU_BODY, size), ("nop", NOP_BODY, size)): | ||
| 117 | listing = synthetic(name, body, instructions) | ||
| 118 | seconds = translate_bytes("ps_" + name, listing, runs) | ||
| 119 | count = instruction_count(listing) | ||
| 120 | rows.append({"name": name, "instructions": count, "seconds": seconds, | ||
| 121 | "us_per_instruction": seconds / count * 1e6}) | ||
| 122 | return rows | ||
| 123 | |||
| 124 | |||
| 125 | def summarise(rows): | ||
| 126 | if not rows: | ||
| 127 | return {"programs": 0, "instructions": 0, "seconds": 0.0, "us_per_instruction": 0.0} | ||
| 128 | instructions = sum(r["instructions"] for r in rows) | ||
| 129 | seconds = sum(r["seconds"] for r in rows) | ||
| 130 | return {"programs": len(rows), "instructions": instructions, "seconds": seconds, | ||
| 131 | "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0} | ||
| 132 | |||
| 133 | |||
| 134 | # Recorded on this machine (AMD Ryzen 9 desktop, Windows 11, Python 3.12.4, commit 1cc6e3c) with --runs 3: the numbers | ||
| 135 | # to compare a later run against on the same machine. A different machine moves the absolute value; the shape does not. | ||
| 136 | BASELINE = {"corpus_us_per_instruction": 55.4, "alu_us_per_instruction": 32.3, "nop_us_per_instruction": 14.0} | ||
| 137 | |||
| 138 | |||
| 139 | def compare(reference, candidate, runs, size, rounds, max_slowdown=None): | ||
| 140 | """Interleaved A/B over two tools/ trees: each round measures both, and the best per side is kept. | ||
| 141 | |||
| 142 | Loading the tree is the subprocess's job (LEONIDA_TOOLS_DIR, as tests/semantic/support.py does it), so the two | ||
| 143 | versions never share a module. Alternating the two in the same round is the point: a machine that slows down or | ||
| 144 | speeds up between measurements moves both sides, not just one. | ||
| 145 | """ | ||
| 146 | def measure(path): | ||
| 147 | env = dict(os.environ, LEONIDA_TOOLS_DIR=os.path.abspath(path)) | ||
| 148 | result = subprocess.run([sys.executable, "-I", os.path.abspath(__file__), "--json", | ||
| 149 | "--runs", str(runs), "--size", str(size)], | ||
| 150 | capture_output=True, text=True, env=env) | ||
| 151 | if result.returncode != 0: | ||
| 152 | raise SystemExit(f"{path}: the benchmark failed\n{result.stderr.strip()}") | ||
| 153 | return json.loads(result.stdout)["measured"] | ||
| 154 | |||
| 155 | best = {"reference": {}, "candidate": {}} | ||
| 156 | measured_any = False | ||
| 157 | for round_index in range(rounds + 1): # the first round warms the caches and is not counted | ||
| 158 | order = [("reference", reference), ("candidate", candidate)] | ||
| 159 | if round_index % 2: | ||
| 160 | order.reverse() # whoever runs first pays the cold file cache, so the order alternates | ||
| 161 | for side, path in order: | ||
| 162 | measured = measure(path) | ||
| 163 | measured_any = measured_any or bool(measured) | ||
| 164 | if round_index == 0: | ||
| 165 | continue | ||
| 166 | for key, value in measured.items(): | ||
| 167 | best[side][key] = min(best[side].get(key, value), value) | ||
| 168 | if not measured_any: | ||
| 169 | raise SystemExit("both trees measured nothing (an empty corpus?); nothing to compare") | ||
| 170 | if sorted(best["reference"]) != sorted(best["candidate"]): | ||
| 171 | only_reference = sorted(set(best["reference"]) - set(best["candidate"])) | ||
| 172 | only_candidate = sorted(set(best["candidate"]) - set(best["reference"])) | ||
| 173 | raise SystemExit("the two trees do not cover the same measurements" | ||
| 174 | + (f"; only in the reference: {', '.join(only_reference)}" if only_reference else "") | ||
| 175 | + (f"; only in the candidate: {', '.join(only_candidate)}" if only_candidate else "") | ||
| 176 | + "; a missing program would read as a ratio that looks like a win") | ||
| 177 | rows = [] | ||
| 178 | for key in best["reference"]: | ||
| 179 | ref = best["reference"][key] | ||
| 180 | cand = best["candidate"].get(key, float("nan")) | ||
| 181 | rows.append({"name": key, "reference": ref, "candidate": cand, "ratio": cand / ref if ref else None}) | ||
| 182 | print(f"{'measurement':<32} {'reference':>10} {'candidate':>10} {'ratio':>7}") | ||
| 183 | for row in rows: | ||
| 184 | ratio = f"{row['ratio']:>6.2f}x" if row["ratio"] is not None else " n/a" | ||
| 185 | print(f"{row['name']:<32} {row['reference']:>10.1f} {row['candidate']:>10.1f} {ratio}") | ||
| 186 | print(f"\nreference {os.path.abspath(reference)}\ncandidate {os.path.abspath(candidate)}") | ||
| 187 | print("ratio below 1.00 is the candidate being faster; rounds %d, min per side" % rounds) | ||
| 188 | if max_slowdown is not None: | ||
| 189 | # The limit means here what it means against a baseline: a measurement over it is a failure. The ratio is | ||
| 190 | # already candidate/reference, so the limit applies to it directly. | ||
| 191 | slow = [row for row in rows if row["ratio"] is not None and row["ratio"] > max_slowdown] | ||
| 192 | if slow: | ||
| 193 | for row in slow: | ||
| 194 | print(f"slower than the reference by {row['ratio']:.2f}x (limit {max_slowdown:.2f}x): {row['name']}", | ||
| 195 | file=sys.stderr) | ||
| 196 | return 1 | ||
| 197 | return 0 | ||
| 198 | |||
| 199 | |||
| 200 | def main(argv=None): | ||
| 201 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 202 | parser.add_argument("--runs", type=int, default=3, help="translate() calls per program, best one counted") | ||
| 203 | parser.add_argument("--size", type=int, default=2000, help="instructions in each synthetic program") | ||
| 204 | parser.add_argument("--json", action="store_true", help="print one JSON object instead of the tables") | ||
| 205 | parser.add_argument("--max-slowdown", type=float, default=None, | ||
| 206 | help="exit 1 when a per-instruction time exceeds the baseline by this factor, in every output " | ||
| 207 | "format") | ||
| 208 | parser.add_argument("--baseline", metavar="FILE", default=None, | ||
| 209 | help="compare against a baseline written by --write-baseline instead of the committed one; " | ||
| 210 | "the committed numbers are from one machine and mean nothing on another") | ||
| 211 | parser.add_argument("--write-baseline", metavar="FILE", default=None, | ||
| 212 | help="write this run's numbers to FILE as a baseline for --baseline") | ||
| 213 | parser.add_argument("--compare", nargs=2, metavar=("REFERENCE", "CANDIDATE"), default=None, | ||
| 214 | help="time two tools/ trees against each other, interleaved; prints a ratio per measurement") | ||
| 215 | parser.add_argument("--rounds", type=int, default=3, help="rounds of --compare; the best per side is kept") | ||
| 216 | arguments = parser.parse_args(argv) | ||
| 217 | if arguments.rounds < 1: | ||
| 218 | parser.error("--rounds must be at least 1") | ||
| 219 | if arguments.baseline and arguments.write_baseline and \ | ||
| 220 | os.path.abspath(arguments.baseline) == os.path.abspath(arguments.write_baseline): | ||
| 221 | # One file for both: a run that fails the limit would still replace the reference it failed against, and the | ||
| 222 | # same workload would pass on the retry. | ||
| 223 | parser.error("--baseline and --write-baseline name the same file; write to a different one") | ||
| 224 | if arguments.compare: | ||
| 225 | for flag, value in (("--json", arguments.json), ("--write-baseline", arguments.write_baseline), | ||
| 226 | ("--baseline", arguments.baseline)): | ||
| 227 | if value: | ||
| 228 | parser.error(f"{flag} does not apply to --compare, which times two trees and prints its own table") | ||
| 229 | return compare(*arguments.compare, arguments.runs, arguments.size, arguments.rounds, | ||
| 230 | arguments.max_slowdown) | ||
| 231 | if arguments.baseline and not os.path.isfile(arguments.baseline): | ||
| 232 | parser.error(f"--baseline {arguments.baseline} does not exist; --write-baseline records one") | ||
| 233 | if arguments.runs < 1: | ||
| 234 | parser.error("--runs must be at least 1") | ||
| 235 | if arguments.size < 1: | ||
| 236 | parser.error("--size must be at least 1") | ||
| 237 | |||
| 238 | corpus, skipped = corpus_rows(arguments.runs) | ||
| 239 | synthetic_programs = synthetic_rows(arguments.runs, arguments.size) | ||
| 240 | corpus_summary = summarise(corpus) | ||
| 241 | synthetic_summary = summarise(synthetic_programs) | ||
| 242 | |||
| 243 | measured = {"corpus_us_per_instruction": corpus_summary["us_per_instruction"]} | ||
| 244 | measured.update({f"{row['name']}_us_per_instruction": row["us_per_instruction"] | ||
| 245 | for row in synthetic_programs}) | ||
| 246 | |||
| 247 | baseline, baseline_source = BASELINE, "committed" | ||
| 248 | if arguments.baseline: | ||
| 249 | with open(arguments.baseline, encoding="utf-8") as handle: | ||
| 250 | loaded = json.load(handle) | ||
| 251 | baseline = {key: float(value) for key, value in (loaded.get("measured") or loaded).items()} | ||
| 252 | baseline_source = os.path.abspath(arguments.baseline) | ||
| 253 | if arguments.write_baseline: | ||
| 254 | with open(arguments.write_baseline, "w", encoding="utf-8", newline="\n") as handle: | ||
| 255 | json.dump({"measured": measured, "runs": arguments.runs, "size": arguments.size}, handle, | ||
| 256 | indent=2, sort_keys=True) | ||
| 257 | handle.write("\n") | ||
| 258 | print(f"baseline written to {os.path.abspath(arguments.write_baseline)}", file=sys.stderr) | ||
| 259 | |||
| 260 | # The limit is part of the contract of every output format: a job that collects --json must not read a success | ||
| 261 | # code for a run whose numbers are over the limit. It is evaluated here, once, before either format prints. | ||
| 262 | slow = {} | ||
| 263 | if arguments.max_slowdown is not None: | ||
| 264 | slow = {key: value / baseline[key] for key, value in measured.items() | ||
| 265 | if baseline.get(key) and value > baseline[key] * arguments.max_slowdown} | ||
| 266 | |||
| 267 | if arguments.json: | ||
| 268 | print(json.dumps({ | ||
| 269 | "runs": arguments.runs, | ||
| 270 | "corpus": {"summary": corpus_summary, "programs": corpus, "skipped": skipped}, | ||
| 271 | "synthetic": {"summary": synthetic_summary, "programs": synthetic_programs, "size": arguments.size}, | ||
| 272 | "baseline": baseline, | ||
| 273 | "baseline_source": baseline_source, | ||
| 274 | "measured": measured, | ||
| 275 | "slowdown": {k: (measured[k] / baseline[k] if baseline.get(k) else None) for k in measured}, | ||
| 276 | "over_limit": sorted(slow), | ||
| 277 | "max_slowdown": arguments.max_slowdown, | ||
| 278 | }, indent=2, sort_keys=True)) | ||
| 279 | return 1 if slow else 0 | ||
| 280 | |||
| 281 | print(f"corpus: {corpus_summary['programs']} fixtures, {corpus_summary['instructions']} instructions, " | ||
| 282 | f"{corpus_summary['seconds']:.3f} s, {corpus_summary['us_per_instruction']:.1f} us/instruction " | ||
| 283 | f"({len(skipped)} skipped)") | ||
| 284 | worst = sorted(corpus, key=lambda r: -r["us_per_instruction"])[:5] | ||
| 285 | for row in worst: | ||
| 286 | print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms " | ||
| 287 | f"{row['us_per_instruction']:>6.1f} us/instr") | ||
| 288 | print(f"\nsynthetic ({arguments.size} instructions):") | ||
| 289 | for row in synthetic_programs: | ||
| 290 | reference = baseline.get(row["name"] + "_us_per_instruction") | ||
| 291 | compared = (f"({measured[row['name'] + '_us_per_instruction'] / reference:.2f}x the {baseline_source} baseline)" | ||
| 292 | if reference else "(no baseline for this measurement)") | ||
| 293 | print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms " | ||
| 294 | f"{row['us_per_instruction']:>6.1f} us/instr {compared}") | ||
| 295 | if skipped: | ||
| 296 | print("\nskipped (need the FSSM header, which these runs do not pass):") | ||
| 297 | for line in skipped: | ||
| 298 | print(" " + line) | ||
| 299 | |||
| 300 | if slow: | ||
| 301 | for name, factor in sorted(slow.items()): | ||
| 302 | print(f"slower than baseline ({baseline_source}) by {factor:.2f}x: {name}", file=sys.stderr) | ||
| 303 | return 1 | ||
| 304 | return 0 | ||
| 305 | |||
| 306 | |||
| 307 | if __name__ == "__main__": | ||
| 308 | sys.stdout.reconfigure(errors="replace") | ||
| 309 | sys.exit(main()) | ||
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py index 57253cb57..3872c7b37 100644 --- a/scripts/bench_wave64.py +++ b/scripts/bench_wave64.py | |||
| @@ -15,7 +15,6 @@ native 64-wide subgroup, such as Apple Silicon. Every process must complete the | |||
| 15 | output hash; there is deliberately no claim that the hash was compared with a native Wave64 device. | 15 | output hash; there is deliberately no claim that the hash was compared with a native Wave64 device. |
| 16 | """ | 16 | """ |
| 17 | import argparse | 17 | import argparse |
| 18 | import json | ||
| 19 | import os | 18 | import os |
| 20 | import re | 19 | import re |
| 21 | import statistics | 20 | import statistics |
| @@ -97,7 +96,8 @@ def main(): | |||
| 97 | ap = argparse.ArgumentParser() | 96 | ap = argparse.ArgumentParser() |
| 98 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), | 97 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), |
| 99 | help="CMake build directory or a configuration directory such as RelWithDebInfo") | 98 | 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")) | 99 | # Empty means unset to build.py: mc_command() then finds llvm-mc on PATH or a versioned llvm-mc-<N>. |
| 100 | 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. | 101 | # Vulkan guarantees support for at least 65,535 groups along X in one dispatch. |
| 102 | ap.add_argument("--groups", type=positive_int, default=65535) | 102 | ap.add_argument("--groups", type=positive_int, default=65535) |
| 103 | ap.add_argument("--reps", type=positive_int, default=30) | 103 | ap.add_argument("--reps", type=positive_int, default=30) |
diff --git a/scripts/build_llvm_mc.ps1 b/scripts/build_llvm_mc.ps1 index acaa4718e..97015a9db 100644 --- a/scripts/build_llvm_mc.ps1 +++ b/scripts/build_llvm_mc.ps1 | |||
| @@ -7,11 +7,17 @@ | |||
| 7 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 | 7 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 |
| 8 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -Dest D:\tools\llvm-mc -NoEnv | 8 | # powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -Dest D:\tools\llvm-mc -NoEnv |
| 9 | # | 9 | # |
| 10 | # -Version defaults to 23.1.5, the release the shader corpus was measured with. LLVM 21.1.8's gfx1013 decoder | ||
| 11 | # cannot decode 840 of the 2,684 pipeline-library compute programs: their listings carry 79,490 undecodable words and | ||
| 12 | # the translator refuses them ("fall-through into undecodable words"), which leaves the shaders stage at 1,844 of | ||
| 13 | # 2,684. llvm-mc 23.1.5 disassembles those 840 with no rejected word, and the stage then translates 2,683 of 2,684 | ||
| 14 | # (the last wants s_sethalt, which the translator does not implement). docs/design.md, "Disassembling shaders". | ||
| 15 | # | ||
| 10 | # The default -Dest is outside AppData on purpose: `python` from the Python install manager (the app execution alias | 16 | # The default -Dest is outside AppData on purpose: `python` from the Python install manager (the app execution alias |
| 11 | # in WindowsApps) doesn't see folders that other programs create under %LOCALAPPDATA% or %APPDATA%, so an llvm-mc.exe | 17 | # in WindowsApps) doesn't see folders that other programs create under %LOCALAPPDATA% or %APPDATA%, so an llvm-mc.exe |
| 12 | # there looks missing to make_game.py and the tools, although LLVM_MC names it. | 18 | # there looks missing to make_game.py and the tools, although LLVM_MC names it. |
| 13 | param( | 19 | param( |
| 14 | [string]$Version = "21.1.8", | 20 | [string]$Version = "23.1.5", |
| 15 | [string]$Dest = (Join-Path $env:USERPROFILE ".leonida\llvm-mc"), | 21 | [string]$Dest = (Join-Path $env:USERPROFILE ".leonida\llvm-mc"), |
| 16 | [string]$Temp = (Join-Path $env:TEMP "leonida-llvm-mc"), | 22 | [string]$Temp = (Join-Path $env:TEMP "leonida-llvm-mc"), |
| 17 | [switch]$NoEnv, # don't set LLVM_MC for the current user | 23 | [switch]$NoEnv, # don't set LLVM_MC for the current user |
| @@ -19,12 +25,17 @@ param( | |||
| 19 | ) | 25 | ) |
| 20 | $ErrorActionPreference = "Stop" | 26 | $ErrorActionPreference = "Stop" |
| 21 | 27 | ||
| 28 | if ([string]::IsNullOrWhiteSpace($Version) -or $Version -match '[\s\x00-\x1f%]') { | ||
| 29 | throw "-Version '$Version' is not a valid LLVM release version." | ||
| 30 | } | ||
| 31 | |||
| 22 | # cmd.exe expands %...% on every line of _build.cmd (twice on a CALL line), so a -Temp with % in it breaks the build. | 32 | # cmd.exe expands %...% on every line of _build.cmd (twice on a CALL line), so a -Temp with % in it breaks the build. |
| 23 | # A relative -Temp is checked as the full path it resolves to (the working directory can hold the %). | 33 | # A relative -Temp is checked as the full path it resolves to (the working directory can hold the %). |
| 24 | $fullTemp = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Temp)) | 34 | $fullTemp = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Temp)) |
| 25 | if ($fullTemp.Contains('%')) { | 35 | if ($fullTemp.Contains('%')) { |
| 26 | throw "-Temp '$fullTemp' contains '%', which cmd.exe expands in the generated _build.cmd. Choose a -Temp folder without % in its path." | 36 | throw "-Temp '$fullTemp' contains '%', which cmd.exe expands in the generated _build.cmd. Choose a -Temp folder without % in its path." |
| 27 | } | 37 | } |
| 38 | $Temp = $fullTemp | ||
| 28 | 39 | ||
| 29 | if (-not $Keep) { | 40 | if (-not $Keep) { |
| 30 | # Compare directory boundaries, including when the paths do not exist yet. | 41 | # Compare directory boundaries, including when the paths do not exist yet. |
| @@ -40,19 +51,26 @@ foreach ($t in "git", "python") { | |||
| 40 | if (-not (Get-Command $t -ErrorAction SilentlyContinue)) { throw "$t wasn't found on PATH." } | 51 | if (-not (Get-Command $t -ErrorAction SilentlyContinue)) { throw "$t wasn't found on PATH." } |
| 41 | } | 52 | } |
| 42 | $installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer" | 53 | $installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer" |
| 43 | $vs = & "$installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath | 54 | $vswhere = Join-Path $installer "vswhere.exe" |
| 55 | if (-not (Test-Path -LiteralPath $vswhere -PathType Leaf)) { throw "Visual Studio with the C++ x64 tools wasn't found." } | ||
| 56 | $vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath | ||
| 44 | if (-not $vs) { throw "Visual Studio with the C++ x64 tools wasn't found." } | 57 | if (-not $vs) { throw "Visual Studio with the C++ x64 tools wasn't found." } |
| 45 | $vcvars = Join-Path $vs "VC\Auxiliary\Build\vcvars64.bat" | 58 | $vcvars = Join-Path $vs "VC\Auxiliary\Build\vcvars64.bat" |
| 59 | if (-not (Test-Path -LiteralPath $vcvars -PathType Leaf)) { throw "Visual Studio vcvars64.bat wasn't found at '$vcvars'." } | ||
| 46 | $jobs = [Math]::Max(1, [int]([Environment]::ProcessorCount / 2)) | 60 | $jobs = [Math]::Max(1, [int]([Environment]::ProcessorCount / 2)) |
| 47 | 61 | ||
| 48 | $cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake" | 62 | $cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake" |
| 49 | $cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" | 63 | $cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" |
| 64 | if (-not (Test-Path -LiteralPath $cmake -PathType Leaf)) { | ||
| 65 | $cmakeCmd = Get-Command cmake -ErrorAction SilentlyContinue | ||
| 66 | $cmake = if ($cmakeCmd) { $cmakeCmd.Source } else { $null } | ||
| 67 | } | ||
| 50 | $ninja = Join-Path $cmakeDir "Ninja\ninja.exe" | 68 | $ninja = Join-Path $cmakeDir "Ninja\ninja.exe" |
| 51 | if (-not ((Test-Path $cmake) -and (Test-Path $ninja))) { | 69 | if (-not (Test-Path -LiteralPath $ninja -PathType Leaf)) { |
| 52 | $cmake = (Get-Command cmake -ErrorAction SilentlyContinue).Source | 70 | $ninjaCmd = Get-Command ninja -ErrorAction SilentlyContinue |
| 53 | $ninja = (Get-Command ninja -ErrorAction SilentlyContinue).Source | 71 | $ninja = if ($ninjaCmd) { $ninjaCmd.Source } else { $null } |
| 54 | if (-not ($cmake -and $ninja)) { throw "CMake and Ninja weren't found (install VS's 'C++ CMake tools' or put them on PATH)." } | ||
| 55 | } | 72 | } |
| 73 | if (-not ($cmake -and $ninja)) { throw "CMake and Ninja weren't found (install VS's 'C++ CMake tools' or put them on PATH)." } | ||
| 56 | 74 | ||
| 57 | $src = Join-Path $Temp "src" | 75 | $src = Join-Path $Temp "src" |
| 58 | $out = Join-Path $Temp "build" | 76 | $out = Join-Path $Temp "build" |
| @@ -144,14 +162,14 @@ if ($p.ExitCode -ne 0) { throw "build failed ($($p.ExitCode)); the build folder | |||
| 144 | $exe = Join-Path $out "bin\llvm-mc.exe" | 162 | $exe = Join-Path $out "bin\llvm-mc.exe" |
| 145 | # Through a file: a PowerShell pipe can prepend a BOM, which llvm-mc rejects as an invalid token. | 163 | # Through a file: a PowerShell pipe can prepend a BOM, which llvm-mc rejects as an invalid token. |
| 146 | $probeFile = Join-Path $Temp "probe.txt" | 164 | $probeFile = Join-Path $Temp "probe.txt" |
| 147 | [IO.File]::WriteAllText($probeFile, "0x00 0x00 0x81 0xbf`n") | 165 | [IO.File]::WriteAllText($probeFile, "0x00 0x00 0x81 0xbf`n", [System.Text.UTF8Encoding]::new($false)) |
| 148 | $probe = & $exe --disassemble -triple=amdgcn -mcpu=gfx1013 $probeFile | 166 | $probe = & $exe --disassemble -triple=amdgcn -mcpu=gfx1013 $probeFile |
| 149 | if ($LASTEXITCODE -ne 0 -or -not ($probe -match "s_endpgm")) { throw "the built llvm-mc didn't disassemble an s_endpgm" } | 167 | if ($LASTEXITCODE -ne 0 -or -not ($probe -match "s_endpgm")) { throw "the built llvm-mc didn't disassemble an s_endpgm" } |
| 150 | 168 | ||
| 151 | New-Item -ItemType Directory -Force $Dest | Out-Null | 169 | New-Item -ItemType Directory -Force $Dest | Out-Null |
| 152 | # LLVM_MC is saved for future terminals, whose working directory can differ from this one. | 170 | # LLVM_MC is saved for future terminals, whose working directory can differ from this one. |
| 153 | $final = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $Dest "llvm-mc.exe")) | 171 | $final = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $Dest "llvm-mc.exe")) |
| 154 | Copy-Item -Force $exe $final | 172 | Copy-Item -LiteralPath $exe -Destination $final -Force |
| 155 | if (-not $Keep) { | 173 | if (-not $Keep) { |
| 156 | Remove-DirectoryRobust $Temp | 174 | Remove-DirectoryRobust $Temp |
| 157 | if (Test-Path -LiteralPath $Temp) { | 175 | if (Test-Path -LiteralPath $Temp) { |
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 5dd8bd389..a1d7151b5 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 | |||
| @@ -86,7 +86,7 @@ $build || exit /b 1 | |||
| 86 | Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." | 86 | Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." |
| 87 | $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" | 87 | $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" |
| 88 | $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } | 88 | $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } |
| 89 | $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } | 89 | $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_pso_stream.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_queue.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp", "shims\appnotify.cpp" | ForEach-Object { "`"$src\$_`"" } |
| 90 | $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" | 90 | $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" |
| 91 | $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } | 91 | $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } |
| 92 | $body = @" | 92 | $body = @" |
| @@ -116,7 +116,7 @@ if defined VULKAN_SDK cl /nologo /std:c++20 /EHsc /O2 /DWIN32_LEAN_AND_MEAN /DNO | |||
| 116 | rem tools/sandbox.py starts vk_sandbox, and tools/ps_sweep.py --exe / tools/ab_control_flow.py --all-attachments start | 116 | rem tools/sandbox.py starts vk_sandbox, and tools/ps_sweep.py --exe / tools/ab_control_flow.py --all-attachments start |
| 117 | rem vk_ps_sweep, by name from runtime\build; without them the sandbox says "vk_sandbox is not built" and the sweep has | 117 | rem vk_ps_sweep, by name from runtime\build; without them the sandbox says "vk_sandbox is not built" and the sweep has |
| 118 | rem no harness to pass. CMake builds both in its Vulkan tools loop (EGEN-FALLBACK-SANDBOX-SWEEP). | 118 | rem no harness to pass. CMake builds both in its Vulkan tools loop (EGEN-FALLBACK-SANDBOX-SWEEP). |
| 119 | if 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 | 119 | if 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 |
| 120 | if 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 | 120 | if 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/carve_all.ps1 b/scripts/carve_all.ps1 deleted file mode 100644 index e7de9e4d9..000000000 --- a/scripts/carve_all.ps1 +++ /dev/null | |||
| @@ -1,63 +0,0 @@ | |||
| 1 | # Carves every .rpf in the game folder into <Out>\<archive path with _>, smallest first (research tool; the | ||
| 2 | # build itself doesn't need it). Skips archives that already have an index.json. Summary: <Out>\coverage.json | ||
| 3 | param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) | ||
| 4 | $root = Split-Path $PSScriptRoot -Parent | ||
| 5 | $tool = Join-Path $root "tools\rpf9_carve.py" | ||
| 6 | # -Game may be relative or end in a separator; archive names are cut from a separator-ended prefix. | ||
| 7 | $Game = (Resolve-Path -LiteralPath $Game).ProviderPath | ||
| 8 | # Resolve-Path preserves 8.3 short components (e.g. RUNNER~1), while Get-ChildItem emits canonical | ||
| 9 | # FullName paths. Deriving the prefix from Resolve-Path then cuts the wrong number of characters and | ||
| 10 | # re-carves already-caved archives; use the canonical form for both sides of the Substring. | ||
| 11 | $prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\' | ||
| 12 | $destinations = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::OrdinalIgnoreCase) | ||
| 13 | # Validate every destination before accepting any cached index or starting a carve. | ||
| 14 | $archives = foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -Filter *.rpf | Sort-Object Length) { | ||
| 15 | $rel = $f.FullName.Substring($prefix.Length) | ||
| 16 | $name = [IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_")) | ||
| 17 | if ($destinations.ContainsKey($name)) { | ||
| 18 | throw ("Archives '{0}' and '{1}' both map to '{2}'." -f $destinations[$name], $rel, $name) | ||
| 19 | } | ||
| 20 | $destinations.Add($name, $rel) | ||
| 21 | [pscustomobject]@{ file = $f; relative = $rel; destination = Join-Path $Out $name } | ||
| 22 | } | ||
| 23 | |||
| 24 | $rows = @() | ||
| 25 | foreach ($archive in $archives) { | ||
| 26 | $f = $archive.file | ||
| 27 | $rel = $archive.relative | ||
| 28 | $dest = $archive.destination | ||
| 29 | $index = Join-Path $dest "index.json" | ||
| 30 | if (-not (Test-Path -LiteralPath $index)) { | ||
| 31 | Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB)) | ||
| 32 | python -I $tool $f.FullName $dest | Select-Object -Last 1 | ||
| 33 | if ($LASTEXITCODE -ne 0) { throw "Carving $rel failed (exit $LASTEXITCODE)" } | ||
| 34 | } | ||
| 35 | try { | ||
| 36 | $s = (Get-Content -LiteralPath $index -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop).summary | ||
| 37 | foreach ($field in 'files', 'bink2_files', 'span', 'compressed_bytes', 'unread_bytes', 'inflated_bytes') { | ||
| 38 | $value = $s.$field | ||
| 39 | if ((($value -isnot [int]) -and ($value -isnot [long])) -or $value -lt 0) { | ||
| 40 | throw "summary.$field must be a non-negative integer." | ||
| 41 | } | ||
| 42 | } | ||
| 43 | if ($s.span -eq 0 -and ($s.compressed_bytes -ne 0 -or $s.unread_bytes -ne 0)) { | ||
| 44 | throw 'A zero summary.span requires zero compressed and unread bytes.' | ||
| 45 | } | ||
| 46 | # Stored streams and unread gaps occupy disjoint parts of the span. Subtract instead of | ||
| 47 | # adding the counters so a total just above Int64.MaxValue cannot lose precision. | ||
| 48 | if ($s.compressed_bytes -gt $s.span -or $s.unread_bytes -gt ($s.span - $s.compressed_bytes)) { | ||
| 49 | throw 'summary.compressed_bytes and summary.unread_bytes must fit within summary.span.' | ||
| 50 | } | ||
| 51 | if ($s.bink2_files -gt $s.files) { | ||
| 52 | throw 'summary.bink2_files must not exceed summary.files.' | ||
| 53 | } | ||
| 54 | } catch { | ||
| 55 | throw "Invalid carve index '$index': $($_.Exception.Message)" | ||
| 56 | } | ||
| 57 | $denominator = [math]::Max(1L, $s.span) | ||
| 58 | $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span | ||
| 59 | readable = [math]::Round($s.compressed_bytes / $denominator, 4) | ||
| 60 | unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes } | ||
| 61 | } | ||
| 62 | $rows | ConvertTo-Json | Set-Content -Encoding utf8 -LiteralPath (Join-Path $Out "coverage.json") | ||
| 63 | $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 | ||
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 | ||
| 21 | def normalize(fingerprint): | 21 | def 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 | ||
| 43 | def show_keys(path, gpg=("gpg",)): | 52 | def 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",)): | |||
| 52 | def check(path, expected, gpg=("gpg",)): | 61 | def 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 | ||
| 68 | def main(argv): | 85 | def 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_compute_journal_overlay.py b/scripts/check_compute_journal_overlay.py index 4ea23f84c..1ef6eb501 100644 --- a/scripts/check_compute_journal_overlay.py +++ b/scripts/check_compute_journal_overlay.py | |||
| @@ -25,6 +25,7 @@ def entries(cache): | |||
| 25 | d = cache / "pipeline_cache.d" | 25 | d = cache / "pipeline_cache.d" |
| 26 | if not d.exists(): | 26 | if not d.exists(): |
| 27 | return {} | 27 | return {} |
| 28 | require(d.is_dir(), "pipeline_cache.d is not a directory") | ||
| 28 | out = {} | 29 | out = {} |
| 29 | for p in d.iterdir(): | 30 | for p in d.iterdir(): |
| 30 | require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and | 31 | require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and |
| @@ -45,7 +46,10 @@ def run(exe, root, device, strict): | |||
| 45 | if label == "local-B": | 46 | if label == "local-B": |
| 46 | # Bring only B into a fresh process; no session or shared cache crosses this boundary. | 47 | # Bring only B into a fresh process; no session or shared cache crosses this boundary. |
| 47 | (cache / "pipeline_cache.d").mkdir() | 48 | (cache / "pipeline_cache.d").mkdir() |
| 48 | src, = (root / "new-B" / "pipeline_cache.d").iterdir() | 49 | b_dir = root / "new-B" / "pipeline_cache.d" |
| 50 | srcs = list(b_dir.iterdir()) if b_dir.is_dir() else [] | ||
| 51 | require(len(srcs) == 1 and srcs[0].is_file(), "new-B did not leave one journal file to copy") | ||
| 52 | src = srcs[0] | ||
| 49 | shutil.copy2(src, cache / "pipeline_cache.d" / src.name) | 53 | shutil.copy2(src, cache / "pipeline_cache.d" / src.name) |
| 50 | local_before = entries(cache) | 54 | local_before = entries(cache) |
| 51 | env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} | 55 | env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} |
| @@ -57,7 +61,8 @@ def run(exe, root, device, strict): | |||
| 57 | if label != "cold": | 61 | if label != "cold": |
| 58 | env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d") | 62 | env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d") |
| 59 | p = subprocess.run([str(exe)] + (["--second-shader"] if second else []), | 63 | p = subprocess.run([str(exe)] + (["--second-shader"] if second else []), |
| 60 | stdin=subprocess.DEVNULL, capture_output=True, text=True, errors="replace", | 64 | stdin=subprocess.DEVNULL, capture_output=True, text=True, |
| 65 | encoding="utf-8", errors="replace", | ||
| 61 | cwd=cache, env=env, timeout=60) | 66 | cwd=cache, env=env, timeout=60) |
| 62 | if p.returncode == 77: | 67 | if p.returncode == 77: |
| 63 | print("SKIP: the authored compute fixture is unsupported on this device") | 68 | print("SKIP: the authored compute fixture is unsupported on this device") |
| @@ -77,7 +82,11 @@ def run(exe, root, device, strict): | |||
| 77 | local = entries(cache) | 82 | local = entries(cache) |
| 78 | if label == "cold": | 83 | if label == "cold": |
| 79 | require(len(local) == 1, "cold A was not journaled") | 84 | require(len(local) == 1, "cold A was not journaled") |
| 80 | source, = (seed / "pipeline_cache.d").iterdir() | 85 | seed_dir = seed / "pipeline_cache.d" |
| 86 | seed_entries = list(seed_dir.iterdir()) if seed_dir.is_dir() else [] | ||
| 87 | require(len(seed_entries) == 1 and seed_entries[0].is_file(), | ||
| 88 | "cold A did not leave one seed journal file") | ||
| 89 | source = seed_entries[0] | ||
| 81 | # Make an erroneous hourly LRU touch observable without making the probe depend on system time. | 90 | # Make an erroneous hourly LRU touch observable without making the probe depend on system time. |
| 82 | old = time.time_ns() - 48 * 3600 * 10**9 | 91 | old = time.time_ns() - 48 * 3600 * 10**9 |
| 83 | os.utime(source, ns=(old, old)) | 92 | os.utime(source, ns=(old, old)) |
| @@ -95,17 +104,31 @@ def run(exe, root, device, strict): | |||
| 95 | return 0 | 104 | return 0 |
| 96 | 105 | ||
| 97 | 106 | ||
| 107 | def main(argv=None) -> int: | ||
| 108 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 109 | parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe") | ||
| 110 | parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector") | ||
| 111 | parser.add_argument("--require-hit", action="store_true") | ||
| 112 | args = parser.parse_args(argv) | ||
| 113 | try: | ||
| 114 | exe = args.executable.resolve(strict=True) | ||
| 115 | except OSError as exc: | ||
| 116 | print(f"ERROR: {exc}", file=sys.stderr) | ||
| 117 | return 2 | ||
| 118 | if not exe.is_file() or exe.name.lower() not in ("d3d12_compute_journal_test.exe", "d3d12_compute_journal_test"): | ||
| 119 | print(f"ERROR: expected the compute test executable, not {exe.name}", file=sys.stderr) | ||
| 120 | return 2 | ||
| 121 | try: | ||
| 122 | with tempfile.TemporaryDirectory(prefix="leonida-authored-journal-") as tmp: | ||
| 123 | return run(exe, Path(tmp), args.device, args.require_hit) | ||
| 124 | except (RuntimeError, subprocess.TimeoutExpired, OSError) as exc: | ||
| 125 | print(f"ERROR: {exc}", file=sys.stderr) | ||
| 126 | return 1 | ||
| 127 | |||
| 128 | |||
| 98 | if __name__ == "__main__": | 129 | if __name__ == "__main__": |
| 99 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | 130 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode |
| 100 | sys.stdout.reconfigure(errors="replace") | 131 | sys.stdout.reconfigure(errors="replace") |
| 101 | except (AttributeError, ValueError, OSError): | 132 | except (AttributeError, ValueError, OSError): |
| 102 | pass | 133 | pass |
| 103 | parser = argparse.ArgumentParser(description=__doc__) | 134 | raise SystemExit(main()) |
| 104 | parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe") | ||
| 105 | parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector") | ||
| 106 | parser.add_argument("--require-hit", action="store_true") | ||
| 107 | args = parser.parse_args() | ||
| 108 | exe = args.executable.resolve(strict=True) | ||
| 109 | require(exe.name.lower() == "d3d12_compute_journal_test.exe", "expected the compute test, not the game") | ||
| 110 | with tempfile.TemporaryDirectory(prefix="leonida-authored-journal-") as tmp: | ||
| 111 | raise SystemExit(run(exe, Path(tmp), args.device, args.require_hit)) | ||
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py index ae3d06e77..92097253c 100644 --- a/scripts/check_no_game_data.py +++ b/scripts/check_no_game_data.py | |||
| @@ -3,6 +3,10 @@ | |||
| 3 | python3 -I scripts/check_no_game_data.py # every file `git ls-files` lists | 3 | python3 -I scripts/check_no_game_data.py # every file `git ls-files` lists |
| 4 | python3 -I scripts/check_no_game_data.py PATH... # only these files | 4 | python3 -I scripts/check_no_game_data.py PATH... # only these files |
| 5 | 5 | ||
| 6 | Explicit PATH inputs must be regular files, not directories or symlinks. A missing, unreadable or non-regular | ||
| 7 | explicit input is reported on stderr and causes exit 2 unless another input matches game data (exit 1). | ||
| 8 | Default git enumeration still skips symlinks, submodules and files deleted from the working tree. | ||
| 9 | |||
| 6 | The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable | 10 | The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable |
| 7 | as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the | 11 | as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the |
| 8 | files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader | 12 | files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader |
| @@ -14,8 +18,8 @@ notes). Text formats (disassembly, .obj, .spvasm) | |||
| 14 | have no magic and stay with the extension check. | 18 | have no magic and stay with the extension check. |
| 15 | 19 | ||
| 16 | A compressed file hides those magics from both checks, so the script looks inside what the standard library opens: | 20 | A compressed file hides those magics from both checks, so the script looks inside what the standard library opens: |
| 17 | each member of a zip (found by its central directory too, so with bytes in front of it) or a tar, and the stream of | 21 | each member of a zip (found by its central directory too, so with bytes in front of it) or a tar (including V7), and |
| 18 | a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory | 22 | the 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 |
| 19 | under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long. | 23 | under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long. |
| 20 | 7-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are | 24 | 7-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are |
| 21 | reported as archives that can't be checked. | 25 | reported as archives that can't be checked. |
| @@ -25,10 +29,12 @@ exits 1 if there is any. It exits 2 when a file cannot be read or git cannot lis | |||
| 25 | repository, or git not installed). Standard library only, no game files. | 29 | repository, or git not installed). Standard library only, no game files. |
| 26 | """ | 30 | """ |
| 27 | import bz2 | 31 | import bz2 |
| 32 | import errno | ||
| 28 | import gzip | 33 | import gzip |
| 29 | import io | 34 | import io |
| 30 | import lzma | 35 | import lzma |
| 31 | import os | 36 | import os |
| 37 | import stat | ||
| 32 | import subprocess | 38 | import subprocess |
| 33 | import sys | 39 | import sys |
| 34 | import tarfile | 40 | import tarfile |
| @@ -184,6 +190,13 @@ def archive_kind(f, head): | |||
| 184 | return stream[0] | 190 | return stream[0] |
| 185 | if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]: | 191 | if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]: |
| 186 | return "tar archive" | 192 | return "tar archive" |
| 193 | # V7 tar has no ustar marker. Validate only its first header here; member reads still use the shared budget. | ||
| 194 | try: | ||
| 195 | tarfile.TarInfo.frombuf(head[:tarfile.BLOCKSIZE], tarfile.ENCODING, "surrogateescape") | ||
| 196 | except tarfile.HeaderError: | ||
| 197 | pass | ||
| 198 | else: | ||
| 199 | 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 | 200 | # 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. | 201 | # 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): | 202 | if head.startswith(ZIP) or zipfile.is_zipfile(f): |
| @@ -267,15 +280,19 @@ def git_error(e): | |||
| 267 | return e.strerror or str(e) | 280 | return e.strerror or str(e) |
| 268 | 281 | ||
| 269 | 282 | ||
| 270 | def check(paths, unreadable=None): | 283 | def check(paths, unreadable=None, *, explicit=False): |
| 271 | """[(path, format)] for every regular file in `paths` that starts like game data. | 284 | """[(path, format)] for every regular file in `paths` that starts like game data. |
| 272 | 285 | ||
| 273 | A file that exists but cannot be opened or read is appended to `unreadable` (when given) as (path, error).""" | 286 | Files that cannot be opened or read are appended to `unreadable` (when given) as (path, error). |
| 287 | Explicit inputs also report missing paths and non-regular entries instead of silently skipping them.""" | ||
| 274 | found = [] | 288 | found = [] |
| 275 | for path in paths: | 289 | for path in paths: |
| 276 | if os.path.islink(path) or not os.path.isfile(path): | ||
| 277 | continue # submodules, symlinks, files deleted in the working tree | ||
| 278 | try: | 290 | try: |
| 291 | if explicit: | ||
| 292 | if not stat.S_ISREG(os.lstat(path).st_mode): | ||
| 293 | raise OSError(errno.EINVAL, "not a regular file", path) | ||
| 294 | elif os.path.islink(path) or not os.path.isfile(path): | ||
| 295 | continue # submodules, symlinks, files deleted in the working tree | ||
| 279 | name = classify_file(path) | 296 | name = classify_file(path) |
| 280 | except OSError as e: | 297 | except OSError as e: |
| 281 | if unreadable is not None: | 298 | if unreadable is not None: |
| @@ -304,7 +321,7 @@ def main(argv): | |||
| 304 | print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr) | 321 | print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr) |
| 305 | return 2 # not 1: that is the 'game data found' code | 322 | return 2 # not 1: that is the 'game data found' code |
| 306 | unreadable = [] | 323 | unreadable = [] |
| 307 | found = check(paths, unreadable) | 324 | found = check(paths, unreadable, explicit=bool(argv)) |
| 308 | for path, name in found: | 325 | for path, name in found: |
| 309 | print(f"{display(path)}: {name}") | 326 | print(f"{display(path)}: {name}") |
| 310 | for path, e in unreadable: | 327 | for path, e in unreadable: |
diff --git a/scripts/ci_expected_failures.py b/scripts/ci_expected_failures.py index f398020f7..866706ddd 100644 --- a/scripts/ci_expected_failures.py +++ b/scripts/ci_expected_failures.py | |||
| @@ -24,12 +24,13 @@ def judge(failed: list[str], status: int, expected: list[str]) -> tuple[int, lis | |||
| 24 | return 1, lines | 24 | return 1, lines |
| 25 | if status != 0 and not failed: | 25 | if status != 0 and not failed: |
| 26 | lines.append(f"::error::the test runner exited with {status} without naming a failed test") | 26 | lines.append(f"::error::the test runner exited with {status} without naming a failed test") |
| 27 | return 1, lines | ||
| 27 | for name in expected: | 28 | for name in expected: |
| 28 | if name in failed: | 29 | if name in failed: |
| 29 | lines.append(f"::warning::{name} failed, as expected until its fix is merged") | 30 | lines.append(f"::warning::{name} failed, as expected until its fix is merged") |
| 30 | else: | 31 | else: |
| 31 | lines.append(f"::notice::{name} passed: drop it from the expected failures") | 32 | lines.append(f"::notice::{name} passed: drop it from the expected failures") |
| 32 | return (1 if unexpected or (status != 0 and not failed) else 0), lines | 33 | return (1 if unexpected else 0), lines |
| 33 | 34 | ||
| 34 | 35 | ||
| 35 | def main(argv: list[str]) -> int: | 36 | def main(argv: list[str]) -> int: |
diff --git a/scripts/compute_workers_win.py b/scripts/compute_workers_win.py index 1ab6915ca..860d91bf3 100644 --- a/scripts/compute_workers_win.py +++ b/scripts/compute_workers_win.py | |||
| @@ -73,7 +73,7 @@ def verify(job, process, mib, worker): | |||
| 73 | 73 | ||
| 74 | @contextlib.contextmanager | 74 | @contextlib.contextmanager |
| 75 | def job(mib, worker): | 75 | def job(mib, worker): |
| 76 | if not 0 < mib <= ((1 << (c.sizeof(Z)*8))-1) >> 20: | 76 | if type(mib) is not int or not 0 < mib <= ((1 << (c.sizeof(Z)*8))-1) >> 20: |
| 77 | raise ValueError("invalid --memory-mib for Windows job") | 77 | raise ValueError("invalid --memory-mib for Windows job") |
| 78 | h = check(create_job(None, None)) # unnamed, never inherited; no breakaway | 78 | h = check(create_job(None, None)) # unnamed, never inherited; no breakaway |
| 79 | try: | 79 | try: |
| @@ -98,7 +98,7 @@ def output_lock(path): | |||
| 98 | # One nonblocking, no-share open; duplicated into workers so an interrupted parent cannot | 98 | # One nonblocking, no-share open; duplicated into workers so an interrupted parent cannot |
| 99 | # release exclusivity before the last worker has actually left. Never delete/recreate the lock. | 99 | # release exclusivity before the last worker has actually left. Never delete/recreate the lock. |
| 100 | h = create_file(str(path), 0xc0000000, 0, None, 4, 0x80, None) | 100 | h = create_file(str(path), 0xc0000000, 0, None, 4, 0x80, None) |
| 101 | if h == H(-1).value: | 101 | if not h or h == H(-1).value: |
| 102 | raise c.WinError(c.get_last_error()) | 102 | raise c.WinError(c.get_last_error()) |
| 103 | try: | 103 | try: |
| 104 | yield h | 104 | yield h |
| @@ -119,13 +119,30 @@ def drain(h): | |||
| 119 | time.sleep(.02) | 119 | time.sleep(.02) |
| 120 | 120 | ||
| 121 | 121 | ||
| 122 | def _worker_executable(): | ||
| 123 | # Inside a Windows venv, sys.executable is a launcher stub that spawns the base interpreter as a second process, | ||
| 124 | # filling the two-process Job Object limit before a tool starts. Run the base interpreter directly when available. | ||
| 125 | base = getattr(sys, "_base_executable", None) | ||
| 126 | if base and os.path.isfile(base): | ||
| 127 | return base | ||
| 128 | return sys.executable | ||
| 129 | |||
| 130 | |||
| 122 | @contextlib.contextmanager | 131 | @contextlib.contextmanager |
| 123 | def start(request, mib, lock): | 132 | def start(request, mib, lock): |
| 133 | if type(lock) is not int or lock <= 0: | ||
| 134 | raise ValueError("invalid Windows lock handle") | ||
| 135 | if type(mib) is not int or not 0 < mib <= ((1 << (c.sizeof(Z)*8))-1) >> 20: | ||
| 136 | raise ValueError("invalid --memory-mib for Windows job") | ||
| 137 | # A single framed gate validated before creating a job object or spawning a child. | ||
| 138 | gate = (json.dumps([str(request), mib, lock]) + "\n").encode("ascii") | ||
| 139 | if len(gate) > 65536: | ||
| 140 | raise ValueError("compute worker gate too large") | ||
| 124 | with job(mib, True) as h: | 141 | with job(mib, True) as h: |
| 125 | si = subprocess.STARTUPINFO(lpAttributeList={"handle_list": [lock]}) | 142 | si = subprocess.STARTUPINFO(lpAttributeList={"handle_list": [lock]}) |
| 126 | os.set_handle_inheritable(lock, True) | 143 | os.set_handle_inheritable(lock, True) |
| 127 | try: | 144 | try: |
| 128 | p = subprocess.Popen([sys.executable, "-I", "-B", str(Path(__file__).resolve()), "--shard"], | 145 | p = subprocess.Popen([_worker_executable(), "-I", "-B", str(Path(__file__).resolve()), "--shard"], |
| 129 | stdin=subprocess.PIPE, startupinfo=si, close_fds=True, creationflags=LOW) | 146 | stdin=subprocess.PIPE, startupinfo=si, close_fds=True, creationflags=LOW) |
| 130 | finally: | 147 | finally: |
| 131 | os.set_handle_inheritable(lock, False) | 148 | os.set_handle_inheritable(lock, False) |
| @@ -134,10 +151,7 @@ def start(request, mib, lock): | |||
| 134 | check(assign(h, int(p._handle))) | 151 | check(assign(h, int(p._handle))) |
| 135 | attached = True | 152 | attached = True |
| 136 | verify(h, int(p._handle), mib, True) | 153 | verify(h, int(p._handle), mib, True) |
| 137 | # A single framed gate. EOF, even after a short write, is not permission to start. | 154 | # EOF, even after a short write, is not permission to start. |
| 138 | gate = (json.dumps([str(request), mib, lock])+"\n").encode("ascii") | ||
| 139 | if len(gate)>65536: | ||
| 140 | raise ValueError("compute worker gate too large") | ||
| 141 | p.stdin.write(gate) | 155 | p.stdin.write(gate) |
| 142 | p.stdin.close() | 156 | p.stdin.close() |
| 143 | yield p | 157 | yield p |
| @@ -169,14 +183,29 @@ def run(requests, mib, lock): | |||
| 169 | 183 | ||
| 170 | def child(): | 184 | def child(): |
| 171 | line = sys.stdin.buffer.readline(65537) | 185 | line = sys.stdin.buffer.readline(65537) |
| 172 | if not line.endswith(b"\n") or len(line)>65536: | 186 | if not line.endswith(b"\n") or len(line) > 65536: |
| 173 | raise ValueError("no complete Windows compute gate") | 187 | raise ValueError("no complete Windows compute gate") |
| 174 | request, mib, lock = json.loads(line) | ||
| 175 | # NULL queries this worker's immediate job. No job handle in a worker can keep it alive after | ||
| 176 | # coordinator death. No library/source inputs touched before membership and effective limits. | ||
| 177 | verify(None, current(), mib, True) | ||
| 178 | os.set_handle_inheritable(lock, False) | ||
| 179 | try: | 188 | try: |
| 189 | payload = json.loads(line.decode("ascii")) | ||
| 190 | except (UnicodeDecodeError, ValueError, RecursionError): | ||
| 191 | raise ValueError("invalid Windows compute gate") from None | ||
| 192 | if not isinstance(payload, list) or len(payload) != 3: | ||
| 193 | raise ValueError("invalid Windows compute gate") | ||
| 194 | request, mib, lock = payload | ||
| 195 | if ( | ||
| 196 | not isinstance(request, str) | ||
| 197 | or not request | ||
| 198 | or type(mib) is not int | ||
| 199 | or mib <= 0 | ||
| 200 | or type(lock) is not int | ||
| 201 | or lock <= 0 | ||
| 202 | ): | ||
| 203 | raise ValueError("invalid Windows compute gate") | ||
| 204 | try: | ||
| 205 | # NULL queries this worker's immediate job. No job handle in a worker can keep it alive after | ||
| 206 | # coordinator death. No library/source inputs touched before membership and effective limits. | ||
| 207 | verify(None, current(), mib, True) | ||
| 208 | os.set_handle_inheritable(lock, False) | ||
| 180 | sys.path.insert(0, str(Path(__file__).resolve().parent)) | 209 | sys.path.insert(0, str(Path(__file__).resolve().parent)) |
| 181 | from translate_pipeline_compute import run_request | 210 | from translate_pipeline_compute import run_request |
| 182 | run_request(Path(request)) | 211 | run_request(Path(request)) |
diff --git a/scripts/corpus_watch.py b/scripts/corpus_watch.py index a09bf8ab9..fdc48b7aa 100644 --- a/scripts/corpus_watch.py +++ b/scripts/corpus_watch.py | |||
| @@ -18,6 +18,7 @@ Standard library only; all text writes name their line ending. | |||
| 18 | """ | 18 | """ |
| 19 | import argparse | 19 | import argparse |
| 20 | import json | 20 | import json |
| 21 | import math | ||
| 21 | import os | 22 | import os |
| 22 | import shutil | 23 | import shutil |
| 23 | import subprocess | 24 | import subprocess |
| @@ -47,16 +48,20 @@ def corpus_counts(work): | |||
| 47 | dxbc = old_dxbc | 48 | dxbc = old_dxbc |
| 48 | spirv_path = os.path.join(work, "spirv", "index.json") | 49 | spirv_path = os.path.join(work, "spirv", "index.json") |
| 49 | 50 | ||
| 50 | with open(dxbc, encoding="utf-8") as f: | 51 | with open(dxbc, encoding="utf-8-sig") as f: |
| 51 | carved = json.load(f) | 52 | carved = json.load(f) |
| 53 | if not isinstance(carved, (list, dict)): | ||
| 54 | raise ValueError(f"{dxbc}: expected a JSON list or object") | ||
| 52 | entries = carved if isinstance(carved, list) else list(carved.values()) | 55 | entries = carved if isinstance(carved, list) else list(carved.values()) |
| 53 | 56 | ||
| 54 | per_stage = {} | 57 | per_stage = {} |
| 55 | validated = 0 | 58 | validated = 0 |
| 56 | spirv_entries = 0 | 59 | spirv_entries = 0 |
| 57 | if os.path.isfile(spirv_path): | 60 | if os.path.isfile(spirv_path): |
| 58 | with open(spirv_path, encoding="utf-8") as f: | 61 | with open(spirv_path, encoding="utf-8-sig") as f: |
| 59 | spirv = json.load(f) | 62 | spirv = json.load(f) |
| 63 | if not isinstance(spirv, dict): | ||
| 64 | raise ValueError(f"{spirv_path}: expected a JSON object") | ||
| 60 | spirv_entries = len(spirv) | 65 | spirv_entries = len(spirv) |
| 61 | for meta in spirv.values(): | 66 | for meta in spirv.values(): |
| 62 | if isinstance(meta, dict) and "error" not in meta: | 67 | if isinstance(meta, dict) and "error" not in meta: |
| @@ -71,20 +76,29 @@ def corpus_counts(work): | |||
| 71 | "validated": validated, "per_stage": per_stage} | 76 | "validated": validated, "per_stage": per_stage} |
| 72 | 77 | ||
| 73 | 78 | ||
| 74 | def outputs_collide(work, report, results, log): | 79 | def outputs_collide(work, report, results, log, game=None, out=None): |
| 75 | """Refuse an output that names an input or another output.""" | 80 | """Refuse an output that names an input or another output.""" |
| 76 | outputs = [p for p in (report, results, log) if p] | 81 | outputs = [p for p in (report, results, log, out) if p] |
| 77 | for i, first in enumerate(outputs): | 82 | for i, first in enumerate(outputs): |
| 78 | for second in outputs[i + 1:]: | 83 | for second in outputs[i + 1:]: |
| 79 | if same_report_path(first, second): | 84 | if same_report_path(first, second): |
| 80 | return True | 85 | return True |
| 81 | for out in outputs: | 86 | inputs = [p for p in (work, game) if p] |
| 82 | if same_report_path(out, work): | 87 | if work: |
| 83 | return True | 88 | inputs.extend([ |
| 89 | os.path.join(work, "shaders", "dxbc", "index.json"), | ||
| 90 | os.path.join(work, "shaders", "spirv", "index.json"), | ||
| 91 | os.path.join(work, "dxbc", "index.json"), | ||
| 92 | os.path.join(work, "spirv", "index.json"), | ||
| 93 | ]) | ||
| 94 | for target_out in outputs: | ||
| 95 | for inp in inputs: | ||
| 96 | if same_report_path(target_out, inp): | ||
| 97 | return True | ||
| 84 | return False | 98 | return False |
| 85 | 99 | ||
| 86 | 100 | ||
| 87 | def main(): | 101 | def main(argv=None): |
| 88 | ap = argparse.ArgumentParser(description=__doc__) | 102 | ap = argparse.ArgumentParser(description=__doc__) |
| 89 | ap.add_argument("--game", required=True, help="your package folder") | 103 | ap.add_argument("--game", required=True, help="your package folder") |
| 90 | ap.add_argument("--work", required=True, help="work folder (outside the repo)") | 104 | ap.add_argument("--work", required=True, help="work folder (outside the repo)") |
| @@ -98,9 +112,16 @@ def main(): | |||
| 98 | ap.add_argument("--pull", action="store_true", help="git pull --ff-only before each run") | 112 | ap.add_argument("--pull", action="store_true", help="git pull --ff-only before each run") |
| 99 | ap.add_argument("--github", action="store_true", help="also refresh dashboard PR/CI panels") | 113 | ap.add_argument("--github", action="store_true", help="also refresh dashboard PR/CI panels") |
| 100 | ap.add_argument("--jobs", type=int) | 114 | ap.add_argument("--jobs", type=int) |
| 101 | a = ap.parse_args() | 115 | a = ap.parse_args(argv) |
| 116 | if not math.isfinite(a.interval) or a.interval < 0: | ||
| 117 | ap.error("--interval must be a finite nonnegative number") | ||
| 102 | if not a.once and a.interval <= 0: | 118 | if not a.once and a.interval <= 0: |
| 103 | ap.error("use --once or --interval HOURS") | 119 | ap.error("use --once or --interval HOURS") |
| 120 | if a.jobs is not None and a.jobs < 1: | ||
| 121 | ap.error("--jobs must be at least 1") | ||
| 122 | for flag, val in (("--results", a.results), ("--log", a.log)): | ||
| 123 | if val and (os.path.isdir(val) or val.endswith(("/", "\\"))): | ||
| 124 | ap.error(f"{flag} must name a file, not a directory: {val}") | ||
| 104 | 125 | ||
| 105 | repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 126 | repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 106 | log_path = a.log | 127 | log_path = a.log |
| @@ -112,7 +133,7 @@ def main(): | |||
| 112 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: | 133 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: |
| 113 | f.write(line + "\n") | 134 | f.write(line + "\n") |
| 114 | 135 | ||
| 115 | if outputs_collide(a.work, a.report, a.results, log_path): | 136 | if outputs_collide(a.work, a.report, a.results, log_path, game=a.game, out=a.out): |
| 116 | ap.error("an output names the work folder or another output") | 137 | ap.error("an output names the work folder or another output") |
| 117 | 138 | ||
| 118 | for tool in ("llvm-mc", "spirv-val", "git"): | 139 | for tool in ("llvm-mc", "spirv-val", "git"): |
| @@ -123,13 +144,19 @@ def main(): | |||
| 123 | probe = subprocess.run( | 144 | probe = subprocess.run( |
| 124 | ["llvm-mc", "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1013", | 145 | ["llvm-mc", "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1013", |
| 125 | "-filetype=obj", "-o", os.devnull], | 146 | "-filetype=obj", "-o", os.devnull], |
| 126 | input="s_nop 0\n", text=True, capture_output=True) | 147 | input="s_nop 0\n", text=True, encoding="utf-8", errors="replace", capture_output=True) |
| 127 | if probe.returncode != 0: | 148 | if probe.returncode != 0: |
| 128 | ap.error("llvm-mc cannot assemble gfx1013 (AMDGPU target missing)") | 149 | ap.error("llvm-mc cannot assemble gfx1013 (AMDGPU target missing)") |
| 129 | 150 | ||
| 151 | for file_out in (a.results, log_path): | ||
| 152 | if file_out: | ||
| 153 | parent = os.path.dirname(os.path.abspath(file_out)) | ||
| 154 | if parent: | ||
| 155 | os.makedirs(parent, exist_ok=True) | ||
| 156 | |||
| 130 | def run(cmd, timeout): | 157 | def run(cmd, timeout): |
| 131 | return subprocess.run(cmd, cwd=repo, text=True, stdout=subprocess.PIPE, | 158 | return subprocess.run(cmd, cwd=repo, text=True, encoding="utf-8", errors="replace", |
| 132 | stderr=subprocess.STDOUT, timeout=timeout) | 159 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout) |
| 133 | 160 | ||
| 134 | def run_once(): | 161 | def run_once(): |
| 135 | if a.pull: | 162 | if a.pull: |
| @@ -170,7 +197,7 @@ def main(): | |||
| 170 | f"validated={counts['validated']}") | 197 | f"validated={counts['validated']}") |
| 171 | for stage, (nc, nv) in sorted(counts["per_stage"].items()): | 198 | for stage, (nc, nv) in sorted(counts["per_stage"].items()): |
| 172 | log(f" {stage}: {nv}/{nc} validated") | 199 | log(f" {stage}: {nv}/{nc} validated") |
| 173 | with open(a.results, encoding="utf-8") as f: | 200 | with open(a.results, encoding="utf-8-sig") as f: |
| 174 | previous = [json.loads(x) for x in f if x.strip()] | 201 | previous = [json.loads(x) for x in f if x.strip()] |
| 175 | if len(previous) >= 2: | 202 | if len(previous) >= 2: |
| 176 | before = previous[-2].get("counts") or {} | 203 | before = previous[-2].get("counts") or {} |
diff --git a/scripts/dev.py b/scripts/dev.py index fada30da4..00bf1bb21 100644 --- a/scripts/dev.py +++ b/scripts/dev.py | |||
| @@ -13,6 +13,7 @@ from pathlib import Path | |||
| 13 | ROOT = Path(__file__).resolve().parents[1] | 13 | ROOT = Path(__file__).resolve().parents[1] |
| 14 | BOOT_TRACE = "tools/boot_trace.py" | 14 | BOOT_TRACE = "tools/boot_trace.py" |
| 15 | GUEST_SCENE = "scripts/run_guest_scene.py" | 15 | GUEST_SCENE = "scripts/run_guest_scene.py" |
| 16 | SMOKE = "scripts/smoke.py" | ||
| 16 | TOOLS = ( | 17 | TOOLS = ( |
| 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 | ||
| @@ -81,19 +90,21 @@ def guest_scene(args: list[str]) -> int: | |||
| 81 | parser.add_argument("-h", "--help", action="store_true") | 90 | parser.add_argument("-h", "--help", action="store_true") |
| 82 | parser.add_argument("--out", metavar="PATH") | 91 | parser.add_argument("--out", metavar="PATH") |
| 83 | options, _ = parser.parse_known_args(args) | 92 | options, _ = parser.parse_known_args(args) |
| 84 | if not options.help and not options.out: | 93 | if not options.help and not (options.out and options.out.strip()): |
| 85 | parser.error("--out PATH is required to keep the scene results") | 94 | parser.error("--out PATH is required to keep the scene results") |
| 86 | 95 | ||
| 87 | return run_producer(GUEST_SCENE, args) | 96 | return run_producer(GUEST_SCENE, args) |
| 88 | 97 | ||
| 89 | 98 | ||
| 90 | def main() -> int: | 99 | def main(argv: list[str] | None = None) -> int: |
| 91 | # The producer owns its arguments and help. Forward before argparse handles them. | 100 | # The producer owns its arguments and help. Forward before argparse handles them. |
| 92 | argv = sys.argv[1:] | 101 | argv = sys.argv[1:] if argv is None else list(argv) |
| 93 | if argv[:1] == ["boot-trace"]: | 102 | if argv[:1] == ["boot-trace"]: |
| 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,13 +112,17 @@ 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() |
| 107 | if args.json: | 119 | if args.json: |
| 108 | print(json.dumps(result, indent=2)) | 120 | print(json.dumps(result, indent=2)) |
| 109 | else: | 121 | else: |
| 110 | sys.stdout.reconfigure(encoding="utf-8") | 122 | try: |
| 123 | sys.stdout.reconfigure(encoding="utf-8") | ||
| 124 | except (AttributeError, ValueError, OSError): | ||
| 125 | pass | ||
| 111 | print("Paths and help commands are relative to the Leonida checkout root.") | 126 | print("Paths and help commands are relative to the Leonida checkout root.") |
| 112 | for tool in result["tools"]: | 127 | for tool in result["tools"]: |
| 113 | status = "present" if tool["present"] else "missing" | 128 | status = "present" if tool["present"] else "missing" |
diff --git a/scripts/export_old_pr_manifest.py b/scripts/export_old_pr_manifest.py new file mode 100644 index 000000000..7198e6b3d --- /dev/null +++ b/scripts/export_old_pr_manifest.py | |||
| @@ -0,0 +1,124 @@ | |||
| 1 | """Write a portable, verifiable manifest of the original repository's surviving history (issue #563). | ||
| 2 | |||
| 3 | The 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 | ||
| 5 | live on GitHub, which is the single point of failure this manifest removes: the branch tips, their authors and dates | ||
| 6 | are recorded as a sorted TSV with a SHA-256 beside it, so the record can be checked after the branches themselves are | ||
| 7 | gone, 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 | ||
| 13 | issue #18. Both write `<kind>.tsv` and `<kind>.sha256` in the output directory, and both are deterministic: the same | ||
| 14 | input gives the same bytes, sorting numerically by old number so the order does not depend on ref iteration. Commit | ||
| 15 | dates are kept as the commit's own ISO-8601 author date, not as a generation timestamp, for the same reason. | ||
| 16 | |||
| 17 | Nothing of the game is read: a branch number, a SHA, a name, a date and a subject line. | ||
| 18 | """ | ||
| 19 | import argparse | ||
| 20 | import hashlib | ||
| 21 | import os | ||
| 22 | import re | ||
| 23 | import subprocess | ||
| 24 | import 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 | |||
| 33 | def collapse(text: str) -> str: | ||
| 34 | return _WHITESPACE.sub(" ", text).strip() | ||
| 35 | |||
| 36 | |||
| 37 | def 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 | |||
| 47 | def 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 | |||
| 68 | def 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 | |||
| 86 | def 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 | |||
| 99 | def 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 | |||
| 122 | if __name__ == "__main__": | ||
| 123 | sys.stdout.reconfigure(errors="replace") | ||
| 124 | 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 | |||
| 4 | On Linux the D3D12 runtime (victory/, a Windows program) runs under Wine, and Wine needs a Direct3D 12 implementation: | ||
| 5 | VKD3D-Proton (LGPL-2.1-or-later, https://github.com/HansKristian-Work/vkd3d-proton) translates it to Vulkan. This | ||
| 6 | tool puts the 64-bit d3d12.dll and d3d12core.dll of one pinned release, with its license and a note on where its | ||
| 7 | source is, into the package folder, so a Linux player needs nothing else for D3D12 (scripts/play-linux.sh installs | ||
| 8 | them into Leonida's own Wine prefix). Every download is checked against the SHA-256 pinned below. | ||
| 9 | |||
| 10 | Standard 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 | """ | ||
| 14 | import argparse | ||
| 15 | import hashlib | ||
| 16 | import io | ||
| 17 | import os | ||
| 18 | import sys | ||
| 19 | import tarfile | ||
| 20 | import urllib.request | ||
| 21 | |||
| 22 | VERSION = "3.1" | ||
| 23 | RELEASE = (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. | ||
| 27 | LICENSE_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 | } | ||
| 33 | DLLS = ("d3d12.dll", "d3d12core.dll") | ||
| 34 | |||
| 35 | |||
| 36 | def 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 | |||
| 45 | def 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 | |||
| 74 | if __name__ == "__main__": | ||
| 75 | sys.stdout.reconfigure(errors="replace") | ||
| 76 | sys.exit(main()) | ||
diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1 index f302d5701..78ebc758b 100644 --- a/scripts/first_look.ps1 +++ b/scripts/first_look.ps1 | |||
| @@ -9,13 +9,25 @@ $root = Split-Path $PSScriptRoot -Parent | |||
| 9 | $Exe = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Exe) | 9 | $Exe = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Exe) |
| 10 | if (-not (Test-Path -LiteralPath $Exe -PathType Leaf)) { throw "$Exe not found" } | 10 | if (-not (Test-Path -LiteralPath $Exe -PathType Leaf)) { throw "$Exe not found" } |
| 11 | $image = Get-Item -LiteralPath $Exe | 11 | $image = Get-Item -LiteralPath $Exe |
| 12 | if (-not $GameDir) { $GameDir = $image.DirectoryName } | 12 | if ($GameDir) { |
| 13 | $GameDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($GameDir) | ||
| 14 | if (-not (Test-Path -LiteralPath $GameDir -PathType Container)) { throw "$GameDir not found or not a directory" } | ||
| 15 | } else { | ||
| 16 | $GameDir = $image.DirectoryName | ||
| 17 | } | ||
| 13 | $name = [IO.Path]::GetFileNameWithoutExtension($Exe) | 18 | $name = [IO.Path]::GetFileNameWithoutExtension($Exe) |
| 14 | $out = Join-Path $root "reports\exe\$name" | 19 | $out = Join-Path $root "reports\exe\$name" |
| 15 | New-Item -ItemType Directory -Force $out | Out-Null | 20 | if (Test-Path -LiteralPath $out -PathType Leaf) { throw "$out is a file, not a directory" } |
| 21 | [void][IO.Directory]::CreateDirectory($out) | ||
| 16 | 22 | ||
| 17 | $fs = [IO.File]::OpenRead($Exe); $mz = New-Object byte[] 2; [void]$fs.Read($mz, 0, 2); $fs.Close() | 23 | $fs = [IO.File]::OpenRead($Exe) |
| 18 | if ([Text.Encoding]::ASCII.GetString($mz) -ne "MZ") { | 24 | try { |
| 25 | $mz = New-Object byte[] 2 | ||
| 26 | $read = $fs.Read($mz, 0, 2) | ||
| 27 | } finally { | ||
| 28 | $fs.Dispose() | ||
| 29 | } | ||
| 30 | if ($read -ne 2 -or [Text.Encoding]::ASCII.GetString($mz) -ne "MZ") { | ||
| 19 | throw "$Exe doesn't start with an MZ header. It's still packaged or encrypted, so there's nothing to inspect." | 31 | throw "$Exe doesn't start with an MZ header. It's still packaged or encrypted, so there's nothing to inspect." |
| 20 | } | 32 | } |
| 21 | 33 | ||
| @@ -24,6 +36,8 @@ $hash = (Get-FileHash -LiteralPath $Exe -Algorithm SHA256).Hash.ToLower() | |||
| 24 | "sha256 $hash size $size" | Tee-Object -LiteralPath (Join-Path $out "hash.txt") | 36 | "sha256 $hash size $size" | Tee-Object -LiteralPath (Join-Path $out "hash.txt") |
| 25 | 37 | ||
| 26 | Write-Host "`n== PE inspection" | 38 | Write-Host "`n== PE inspection" |
| 39 | $reportPath = Join-Path $out "$([IO.Path]::GetFileName($Exe)).json" | ||
| 40 | if (Test-Path -LiteralPath $reportPath -PathType Leaf) { Remove-Item -LiteralPath $reportPath -Force } | ||
| 27 | python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out | 41 | python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out |
| 28 | if ($LASTEXITCODE -ne 0) { throw "pe_inspect failed" } | 42 | if ($LASTEXITCODE -ne 0) { throw "pe_inspect failed" } |
| 29 | 43 | ||
| @@ -85,7 +99,9 @@ if (-not $hasTls -or $stale) { | |||
| 85 | & $cmake --build $build --target gta6rt @configArgs | 99 | & $cmake --build $build --target gta6rt @configArgs |
| 86 | if ($LASTEXITCODE -ne 0) { throw "Building gta6rt in $build failed ($LASTEXITCODE)" } | 100 | if ($LASTEXITCODE -ne 0) { throw "Building gta6rt in $build failed ($LASTEXITCODE)" } |
| 87 | } else { | 101 | } else { |
| 102 | $global:LASTEXITCODE = 0 | ||
| 88 | & (Join-Path $PSScriptRoot "build_runtime.ps1") | 103 | & (Join-Path $PSScriptRoot "build_runtime.ps1") |
| 104 | if ($LASTEXITCODE -ne 0) { throw "build_runtime.ps1 failed ($LASTEXITCODE)" } | ||
| 89 | } | 105 | } |
| 90 | $rt = Find-RuntimeLoader $build $folders | 106 | $rt = Find-RuntimeLoader $build $folders |
| 91 | if (-not $rt) { throw "runtime build did not produce gta6rt.exe in $build" } | 107 | if (-not $rt) { throw "runtime build did not produce gta6rt.exe in $build" } |
| @@ -102,7 +118,8 @@ Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)" | |||
| 102 | $dryRunExitCode = $LASTEXITCODE | 118 | $dryRunExitCode = $LASTEXITCODE |
| 103 | 119 | ||
| 104 | # Shim to-do list, grouped by DLL, most functions first. | 120 | # Shim to-do list, grouped by DLL, most functions first. |
| 105 | $report = Get-Content -LiteralPath (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json | 121 | if (-not (Test-Path -LiteralPath $reportPath -PathType Leaf)) { throw "pe_inspect did not write $reportPath" } |
| 122 | $report = Get-Content -LiteralPath $reportPath -Raw | ConvertFrom-Json | ||
| 106 | $todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } | 123 | $todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } |
| 107 | $lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } | 124 | $lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } |
| 108 | # "unverified" only comes from a host that isn't Windows and has no Wine prefix (pe_inspect.py, classify_dll): most | 125 | # "unverified" only comes from a host that isn't Windows and has no Wine prefix (pe_inspect.py, classify_dll): most |
diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1 new file mode 100644 index 000000000..7d38505ce --- /dev/null +++ b/scripts/game-gate.ps1 | |||
| @@ -0,0 +1,216 @@ | |||
| 1 | #Requires -Version 7.0 | ||
| 2 | # The in-game gate for the D3D12 runtime (leonida.exe): one run, measured the same way on every machine. | ||
| 3 | # | ||
| 4 | # pwsh -NoProfile -File scripts\game-gate.ps1 run -Game <dir> -Data <dir> -DataTemplate <dir> -Name <label> [options] | ||
| 5 | # pwsh -NoProfile -File scripts\game-gate.ps1 start <same options> # the same, detached: returns at once, prints the run folder | ||
| 6 | # pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder> # asks a run to stop (a STOP file) | ||
| 7 | # | ||
| 8 | # It starts the game through this checkout's scripts\play-d3d12.ps1, so a run is what players run, and writes one | ||
| 9 | # folder per run under -RunRoot (default: <Data>\gate-runs): run.json, launch.ps1, settings.txt (the play script's | ||
| 10 | # -DryRun), leonida-settings.txt (the F1 menu file, when there is one), launcher.txt (the precompile lines), | ||
| 11 | # leonida.log (the runtime's log), events.jsonl (what this script did and saw), data\ (a copy of -DataTemplate, so | ||
| 12 | # the tester's own saves are never touched) and summary.json (tools\game_gate.py, schema in docs\game_gate.md). | ||
| 13 | # | ||
| 14 | # It stops the game with WM_SYSCOMMAND/SC_CLOSE (the runtime's own end: the title suspended, the pipeline cache | ||
| 15 | # saved) when -WorldSeconds were spent in the world, when a STOP file appears in the run folder, or after | ||
| 16 | # -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR. | ||
| 17 | # Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'. | ||
| 18 | param( | ||
| 19 | [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, | ||
| 20 | [string]$Game = '', | ||
| 21 | [string]$Data = '', | ||
| 22 | [string]$DataTemplate = '', | ||
| 23 | [string]$Name = '', | ||
| 24 | [string]$RunRoot = '', | ||
| 25 | [string]$RunDir = '', | ||
| 26 | [int]$WorldSeconds = 300, | ||
| 27 | [int]$MaxMinutes = 45, | ||
| 28 | [string]$More = '', | ||
| 29 | [string]$PlayArgs = '', | ||
| 30 | [string]$Python = '' | ||
| 31 | ) | ||
| 32 | $ErrorActionPreference = 'Stop' | ||
| 33 | $repo = Split-Path -Parent $PSScriptRoot | ||
| 34 | $tool = Join-Path $repo 'tools\game_gate.py' | ||
| 35 | $play = Join-Path $repo 'scripts\play-d3d12.ps1' | ||
| 36 | $exe = Join-Path $repo 'd3d12\target\diag\leonida.exe' | ||
| 37 | $menuFile = Join-Path $repo 'd3d12\leonida-settings.txt' | ||
| 38 | if (-not $Python) { $Python = (Get-Command python -ErrorAction Stop).Source } | ||
| 39 | |||
| 40 | if ($Verb -eq 'stop') { | ||
| 41 | if (-not $RunDir -or -not (Test-Path (Join-Path $RunDir 'run.json'))) { throw "not a run folder: '$RunDir'" } | ||
| 42 | Set-Content (Join-Path $RunDir 'STOP') 'stop' -NoNewline | ||
| 43 | "asked $RunDir to stop" | ||
| 44 | exit 0 | ||
| 45 | } | ||
| 46 | |||
| 47 | foreach ($p in 'Game', 'Data', 'DataTemplate', 'Name') { | ||
| 48 | if (-not (Get-Variable $p -ValueOnly)) { throw "-$p is needed" } | ||
| 49 | } | ||
| 50 | $Game = (Resolve-Path $Game).Path | ||
| 51 | $Data = (Resolve-Path $Data).Path | ||
| 52 | $DataTemplate = (Resolve-Path $DataTemplate).Path | ||
| 53 | if (-not $RunRoot) { $RunRoot = Join-Path $Data 'gate-runs' } | ||
| 54 | New-Item -ItemType Directory -Force $RunRoot | Out-Null | ||
| 55 | $RunRoot = (Resolve-Path $RunRoot).Path | ||
| 56 | # A run writes gigabytes of logs and a copy of the saves: never into a checkout. | ||
| 57 | if (($RunRoot + '\').StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "-RunRoot is inside the checkout: $RunRoot" } | ||
| 58 | if (-not (Test-Path $exe)) { throw "no ${exe}: build it first (d3d12\scripts\build-nvidia.ps1), the play script would build it inside the run" } | ||
| 59 | if (-not $RunDir) { $RunDir = Join-Path $RunRoot ('{0}-{1}' -f (Get-Date -Format 'yyyyMMdd-HHmmss'), ($Name -replace '[^\w.-]', '_')) } | ||
| 60 | |||
| 61 | function Get-RunningGame { | ||
| 62 | Get-CimInstance Win32_Process -Filter "Name='leonida.exe' OR Name='leonida_sm.exe'" | | ||
| 63 | Where-Object { $_.CommandLine -match '\srun\s' } | Select-Object -First 1 | ||
| 64 | } | ||
| 65 | |||
| 66 | if ($Verb -eq 'start') { | ||
| 67 | if (Get-RunningGame) { throw 'a leonida run is already running' } | ||
| 68 | $pwsh = (Get-Process -Id $PID).Path | ||
| 69 | $quote = { param($s) '"' + ($s -replace '"', '\"') + '"' } | ||
| 70 | $line = @(& $quote $pwsh; '-NoProfile'; '-ExecutionPolicy'; 'Bypass'; '-File'; & $quote $PSCommandPath; 'run' | ||
| 71 | '-Game'; & $quote $Game; '-Data'; & $quote $Data; '-DataTemplate'; & $quote $DataTemplate; '-Name'; & $quote $Name | ||
| 72 | '-RunRoot'; & $quote $RunRoot; '-RunDir'; & $quote $RunDir; '-WorldSeconds'; $WorldSeconds; '-MaxMinutes'; $MaxMinutes | ||
| 73 | '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python) -join ' ' | ||
| 74 | # Created by Windows, not as a child of this shell: an agent's or a console's end does not end the run. | ||
| 75 | $startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 } | ||
| 76 | $made = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ | ||
| 77 | CommandLine = $line; CurrentDirectory = $repo; ProcessStartupInformation = $startup } | ||
| 78 | if ($made.ReturnValue -ne 0) { throw "starting the run failed ($($made.ReturnValue))" } | ||
| 79 | $RunDir | ||
| 80 | exit 0 | ||
| 81 | } | ||
| 82 | |||
| 83 | # ---- run: the supervisor, in the foreground. | ||
| 84 | if (Get-RunningGame) { throw 'a leonida run is already running' } | ||
| 85 | New-Item -ItemType Directory -Force $RunDir | Out-Null | ||
| 86 | # A detached run has no console: what this script says, and any error, goes to supervisor.log. | ||
| 87 | Start-Transcript -Path (Join-Path $RunDir 'supervisor.log') -Append | Out-Null | ||
| 88 | $events = Join-Path $RunDir 'events.jsonl' | ||
| 89 | function Add-Event([string]$event, [hashtable]$fields = @{}) { | ||
| 90 | $e = [ordered]@{ t = (Get-Date).ToUniversalTime().ToString('o'); event = $event } | ||
| 91 | foreach ($k in $fields.Keys) { $e[$k] = $fields[$k] } | ||
| 92 | Add-Content $events ($e | ConvertTo-Json -Compress) | ||
| 93 | } | ||
| 94 | |||
| 95 | # The tester's saves, copied: the run plays from its own data folder (-More wins over the play script's own). | ||
| 96 | Copy-Item -Path (Join-Path $DataTemplate '*') -Destination (New-Item -ItemType Directory -Force (Join-Path $RunDir 'data')).FullName -Recurse | ||
| 97 | $hadMenuFile = Test-Path $menuFile | ||
| 98 | if ($hadMenuFile) { Copy-Item $menuFile (Join-Path $RunDir 'leonida-settings.txt') } | ||
| 99 | |||
| 100 | $settings = [ordered]@{ | ||
| 101 | LEONIDA_DATA_DIR = (Join-Path $RunDir 'data') | ||
| 102 | LEONIDA_LOG = 'info,leonida_gpu::frame=debug' | ||
| 103 | } | ||
| 104 | foreach ($s in ($More -split ';' | Where-Object { $_ -match '=' })) { $k, $v = $s -split '=', 2; $settings[$k.Trim()] = $v.Trim() } | ||
| 105 | $moreText = ($settings.GetEnumerator() | ForEach-Object { " {0} = '{1}'" -f $_.Key, ($_.Value -replace "'", "''") }) -join "`n" | ||
| 106 | $launch = Join-Path $RunDir 'launch.ps1' | ||
| 107 | Set-Content $launch @" | ||
| 108 | # Written by scripts\game-gate.ps1: how this run started the game. | ||
| 109 | `$env:NO_COLOR = '1' | ||
| 110 | Set-Location '$repo' | ||
| 111 | `$settings = @{ | ||
| 112 | $moreText | ||
| 113 | } | ||
| 114 | & '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args | ||
| 115 | "@ | ||
| 116 | |||
| 117 | $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1 | ||
| 118 | $builtWith = Join-Path $repo 'd3d12\target\diag\built-with.txt' | ||
| 119 | [ordered]@{ | ||
| 120 | name = $Name | ||
| 121 | started_utc = (Get-Date).ToUniversalTime().ToString('o') | ||
| 122 | commit = (git -C $repo rev-parse --short HEAD) | ||
| 123 | dirty = [bool](git -C $repo status --porcelain --untracked-files=no) | ||
| 124 | untracked = @(git -C $repo status --porcelain --untracked-files=normal | Where-Object { $_.StartsWith('??') }).Count | ||
| 125 | exe_sha16 = (Get-FileHash $exe -Algorithm SHA256).Hash.Substring(0, 16).ToLower() | ||
| 126 | built_with = if (Test-Path $builtWith) { (Get-Content $builtWith -Raw).Trim() } else { $null } | ||
| 127 | gpu = $gpu.Name | ||
| 128 | driver = $gpu.DriverVersion | ||
| 129 | play_args = $PlayArgs | ||
| 130 | world_seconds = $WorldSeconds | ||
| 131 | max_minutes = $MaxMinutes | ||
| 132 | f1_settings_file = $hadMenuFile | ||
| 133 | } | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json') | ||
| 134 | |||
| 135 | & pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt') | ||
| 136 | $launcher = Start-Process pwsh -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $launch) -WindowStyle Hidden -PassThru ` | ||
| 137 | -RedirectStandardOutput (Join-Path $RunDir 'launcher.txt') -RedirectStandardError (Join-Path $RunDir 'leonida.log') | ||
| 138 | Add-Event 'started' @{ launcher = $launcher.Id } | ||
| 139 | |||
| 140 | if (-not ('GateWindow' -as [type])) { | ||
| 141 | Add-Type -TypeDefinition @' | ||
| 142 | using System; | ||
| 143 | using System.Runtime.InteropServices; | ||
| 144 | public static class GateWindow { | ||
| 145 | delegate bool EnumProc(IntPtr h, IntPtr l); | ||
| 146 | [StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; } | ||
| 147 | [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l); | ||
| 148 | [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); | ||
| 149 | [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); | ||
| 150 | [DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out RECT r); | ||
| 151 | [DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint msg, IntPtr w, IntPtr l); | ||
| 152 | // WM_SYSCOMMAND/SC_CLOSE to the process's largest visible window: the runtime's end_title path. (A plain | ||
| 153 | // WM_CLOSE goes to the title's own window procedure, which does not end the run.) | ||
| 154 | public static bool Close(int pid) { | ||
| 155 | IntPtr best = IntPtr.Zero; long area = 0; | ||
| 156 | EnumWindows((h, l) => { | ||
| 157 | uint p; GetWindowThreadProcessId(h, out p); | ||
| 158 | RECT r; | ||
| 159 | if (p == (uint)pid && IsWindowVisible(h) && GetClientRect(h, out r)) { | ||
| 160 | long a = (long)(r.R - r.L) * (r.B - r.T); | ||
| 161 | if (a > area) { area = a; best = h; } | ||
| 162 | } | ||
| 163 | return true; | ||
| 164 | }, IntPtr.Zero); | ||
| 165 | return best != IntPtr.Zero && PostMessage(best, 0x0112, new IntPtr(0xF060), IntPtr.Zero); | ||
| 166 | } | ||
| 167 | } | ||
| 168 | '@ | ||
| 169 | } | ||
| 170 | |||
| 171 | $began = Get-Date | ||
| 172 | $title = $null # the game process ($Game, the same name in any case, is its folder) | ||
| 173 | $stopReason = $null | ||
| 174 | try { | ||
| 175 | while ($true) { | ||
| 176 | Start-Sleep -Seconds 5 | ||
| 177 | if (-not $title) { | ||
| 178 | $found = Get-RunningGame | ||
| 179 | if ($found) { | ||
| 180 | $title = Get-Process -Id $found.ProcessId | ||
| 181 | $null = $title.Handle # held now, so that the exit code can be read after the process ends | ||
| 182 | Add-Event 'game' @{ pid = $found.ProcessId; image = $found.Name } | ||
| 183 | } | ||
| 184 | } | ||
| 185 | if ($title -and $title.HasExited) { break } | ||
| 186 | if (-not $title -and $launcher.HasExited) { break } | ||
| 187 | $state = & $Python -I $tool state $RunDir | ConvertFrom-Json | ||
| 188 | if ($state.relaunched) { $stopReason = 'relaunched' } | ||
| 189 | elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' } | ||
| 190 | elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' } | ||
| 191 | elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' } | ||
| 192 | if ($stopReason) { break } | ||
| 193 | } | ||
| 194 | |||
| 195 | if ($stopReason -and $title -and -not $title.HasExited) { | ||
| 196 | Add-Event 'stop_requested' @{ reason = $stopReason } | ||
| 197 | if ([GateWindow]::Close($title.Id)) { Add-Event 'close_sent' } | ||
| 198 | if (-not $title.WaitForExit(60000)) { | ||
| 199 | Stop-Process -Id $title.Id -Force | ||
| 200 | Add-Event 'killed' | ||
| 201 | $title.WaitForExit() | ||
| 202 | } | ||
| 203 | } elseif ($stopReason) { | ||
| 204 | Add-Event 'stop_requested' @{ reason = $stopReason } | ||
| 205 | } | ||
| 206 | if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } } | ||
| 207 | if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force } | ||
| 208 | } catch { | ||
| 209 | Add-Event 'error' @{ message = $_.Exception.Message; line = $_.InvocationInfo.ScriptLineNumber } | ||
| 210 | Write-Host "gate error: $($_.Exception.Message) (line $($_.InvocationInfo.ScriptLineNumber))" | ||
| 211 | } finally { | ||
| 212 | & $Python -I $tool summary $RunDir | ||
| 213 | $code = $LASTEXITCODE | ||
| 214 | Stop-Transcript | Out-Null | ||
| 215 | } | ||
| 216 | exit $code | ||
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. | ||
| 3 | exec_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 | |||
| 38 | leonida_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/linux-boot/boot-digest.sh b/scripts/linux-boot/boot-digest.sh index dd2289e30..9a7c06d68 100755 --- a/scripts/linux-boot/boot-digest.sh +++ b/scripts/linux-boot/boot-digest.sh | |||
| @@ -3,14 +3,23 @@ | |||
| 3 | # Writes /opt/leonida/work/<agent>/boot-<n>.digest.txt and appends a line to /opt/leonida/work/boots.tsv. | 3 | # Writes /opt/leonida/work/<agent>/boot-<n>.digest.txt and appends a line to /opt/leonida/work/boots.tsv. |
| 4 | # Local only: digests quote trace lines, so they never go into commits or PRs. | 4 | # Local only: digests quote trace lines, so they never go into commits or PRs. |
| 5 | set -u | 5 | set -u |
| 6 | AGENT=$1; N=$2; WORK=/opt/leonida/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | 6 | AGENT=${1:?agent}; N=${2:?n} |
| 7 | META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=/opt/leonida/work/boots.tsv | 7 | if [ "$AGENT" = "." ] || [ "$AGENT" = ".." ] || ! [[ "$AGENT" =~ ^[A-Za-z0-9._-]+$ ]]; then |
| 8 | echo "boot-digest: invalid agent: $AGENT" >&2; exit 2 | ||
| 9 | fi | ||
| 10 | if ! [[ "$N" =~ ^[0-9]+$ ]]; then | ||
| 11 | echo "boot-digest: invalid boot number: $N" >&2; exit 2 | ||
| 12 | fi | ||
| 13 | ROOT=${LEONIDA_BOOT_ROOT:-/opt/leonida} | ||
| 14 | WORK=$ROOT/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | ||
| 15 | META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=$ROOT/work/boots.tsv | ||
| 16 | mkdir -p "$WORK" "$(dirname "$LEDGER")" | ||
| 8 | START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null) | 17 | START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null) |
| 9 | START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s) | 18 | START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s) |
| 10 | RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?} | 19 | RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?} |
| 11 | D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2) | 20 | D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2) |
| 12 | STDOUT=${D3D/d3d12-run-/stdout-run-} | 21 | STDOUT=${D3D/d3d12-run-/stdout-run-} |
| 13 | CAP=/opt/leonida/capture/$AGENT-$N | 22 | CAP=$ROOT/capture/$AGENT-$N |
| 14 | 23 | ||
| 15 | verdict=OK | 24 | verdict=OK |
| 16 | # systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own). | 25 | # systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own). |
| @@ -39,15 +48,15 @@ cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0 | |||
| 39 | grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120 | 48 | grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120 |
| 40 | echo | 49 | echo |
| 41 | echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)" | 50 | echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)" |
| 42 | [ -f "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index" | 51 | [ -s "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index" |
| 43 | grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140 | 52 | grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140 |
| 44 | echo | 53 | echo |
| 45 | echo "-- resources (2 s samples)" | 54 | echo "-- resources (2 s samples)" |
| 46 | [ -s "$RES" ] && awk -F'\t' 'NR>1{ if(min==""||$2<min)min=$2; if($3>sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm}' "$RES" || echo "no samples" | 55 | [ -s "$RES" ] && awk -F'\t' 'NR>1{ c++; if(min==""||$2<min)min=$2; if($3>sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{ if(c>0) printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm; else print "no samples" }' "$RES" || echo "no samples" |
| 47 | journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200 | 56 | journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200 |
| 48 | # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of | 57 | # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of |
| 49 | # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well. | 58 | # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well. |
| 50 | [ -s "$RES" ] && awk -F'\t' 'NR>1{t=$4+$5; if(t>m)m=t} END{printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024}' "$RES" | 59 | [ -s "$RES" ] && awk -F'\t' 'NR>1{ c++; t=$4+$5; if(t>m)m=t } END{ if(c>0) printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024 }' "$RES" |
| 51 | echo | 60 | echo |
| 52 | echo "-- system events during the boot (OOM, GPU Xid, segfaults)" | 61 | echo "-- system events during the boot (OOM, GPU Xid, segfaults)" |
| 53 | { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15 | 62 | { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15 |
| @@ -63,13 +72,13 @@ cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0 | |||
| 63 | [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200 | 72 | [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200 |
| 64 | } > "$OUT" 2>&1 | 73 | } > "$OUT" 2>&1 |
| 65 | 74 | ||
| 66 | frames=$( [ -f "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-") | 75 | frames=$( [ -s "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-") |
| 67 | peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{if($4>u)u=$4} END{print u+0}' "$RES" || echo "-") | 76 | peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{c++; if($4>u)u=$4} END{if(c>0) print u+0; else print "-"}' "$RES" || echo "-") |
| 68 | exec 7>>"$LEDGER"; flock 7 | 77 | exec 7>>"$LEDGER"; if command -v flock >/dev/null 2>&1; then flock 7; fi |
| 69 | # Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot. | 78 | # Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot. |
| 70 | grep -q -P "^[^\t]*\t$AGENT\t$N\t" "$LEDGER" 2>/dev/null && exit 0 | 79 | awk -F'\t' -v a="$AGENT" -v n="$N" 'NR>1 && $2==a && $3==n {found=1; exit} END{exit !found}' "$LEDGER" 2>/dev/null && exit 0 |
| 71 | [ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7 | 80 | [ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7 |
| 72 | printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \ | 81 | printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \ |
| 73 | "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \ | 82 | "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \ |
| 74 | "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META")" >&7 | 83 | "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META" 2>/dev/null)" >&7 |
| 75 | exit 0 | 84 | exit 0 |
diff --git a/scripts/linux-boot/boot-inner.sh b/scripts/linux-boot/boot-inner.sh index e52d3daef..aa5f1147f 100755 --- a/scripts/linux-boot/boot-inner.sh +++ b/scripts/linux-boot/boot-inner.sh | |||
| @@ -1,44 +1,125 @@ | |||
| 1 | #!/bin/bash | 1 | #!/bin/bash |
| 2 | # Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots. | 2 | # Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots. |
| 3 | set -u | 3 | set -u |
| 4 | WORK=/opt/leonida/work/$BOOT_AGENT; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | 4 | |
| 5 | die() { | ||
| 6 | echo "ERROR: $*" >&2 | ||
| 7 | exit 2 | ||
| 8 | } | ||
| 9 | |||
| 10 | OUT=${LEONIDA_BOOT_ROOT:-${LEONIDA_OUT:-/opt/leonida}} | ||
| 11 | BOOT_AGENT=${BOOT_AGENT:-} | ||
| 12 | BOOT_N=${BOOT_N:-} | ||
| 13 | BOOT_SECS=${BOOT_SECS:-} | ||
| 14 | GTA6RT=${GTA6RT:-} | ||
| 15 | BOOT_SH=${BOOT_SH:-$OUT/boot.sh} | ||
| 16 | NVIDIA_SMI=${NVIDIA_SMI:-nvidia-smi} | ||
| 17 | PROC_MEMINFO=${LEONIDA_MEMINFO_PATH:-/proc/meminfo} | ||
| 18 | CGROUP_SELF=${LEONIDA_SELF_CGROUP_PATH:-/proc/self/cgroup} | ||
| 19 | CGROUP_ROOT=${LEONIDA_CGROUP_ROOT:-/sys/fs/cgroup} | ||
| 20 | WAIT_SLEEP=${LEONIDA_WAIT_SLEEP_SECS:-15} | ||
| 21 | SAMPLE_SLEEP=${LEONIDA_SAMPLE_SLEEP_SECS:-2} | ||
| 22 | WAIT_ITERS=${LEONIDA_WAIT_ITERS:-40} | ||
| 23 | |||
| 24 | [ -n "$BOOT_AGENT" ] || die "BOOT_AGENT must be set" | ||
| 25 | [ -n "$BOOT_N" ] || die "BOOT_N must be set" | ||
| 26 | [ -n "$BOOT_SECS" ] || die "BOOT_SECS must be set" | ||
| 27 | [ -n "$GTA6RT" ] || die "GTA6RT must be set" | ||
| 28 | case "$BOOT_AGENT" in | ||
| 29 | .|..|*/*|*\\*|*..*) die "BOOT_AGENT must be a single path segment: $BOOT_AGENT" ;; | ||
| 30 | esac | ||
| 31 | case "$BOOT_N" in | ||
| 32 | .|..|*/*|*\\*|*..*) die "BOOT_N must be a single path segment: $BOOT_N" ;; | ||
| 33 | esac | ||
| 34 | [[ "$BOOT_SECS" =~ ^[0-9]+$ ]] || die "BOOT_SECS must be a non-negative integer: $BOOT_SECS" | ||
| 35 | [[ "$WAIT_ITERS" =~ ^[0-9]+$ ]] || die "WAIT_ITERS must be a non-negative integer: $WAIT_ITERS" | ||
| 36 | |||
| 37 | NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500} | ||
| 38 | [[ "$NEED" =~ ^[0-9]+$ ]] || die "LEONIDA_BOOT_MIN_FREE_MB must be a non-negative integer: $NEED" | ||
| 39 | |||
| 40 | WORK=${LEONIDA_BOOT_WORK:-$OUT/work/$BOOT_AGENT}; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | ||
| 5 | META=$WORK/boot-$N.meta | 41 | META=$WORK/boot-$N.meta |
| 42 | mkdir -p "$OUT" "$WORK" || die "cannot create work directory: $WORK" | ||
| 6 | : > "$LOG" | 43 | : > "$LOG" |
| 7 | echo "start_epoch=$(date +%s)" > "$META" | 44 | echo "start_epoch=$(date +%s)" > "$META" |
| 8 | echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META" | 45 | echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META" |
| 9 | env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META" | 46 | env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META" || true |
| 10 | 47 | ||
| 11 | mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1) | 48 | mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1) |
| 12 | awk '/^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' /proc/meminfo | 49 | [ -r "$PROC_MEMINFO" ] || { echo 0; return; } |
| 50 | awk 'BEGIN{a=0; s=0} /^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' "$PROC_MEMINFO" | ||
| 13 | } | 51 | } |
| 14 | NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500} | 52 | swap_pct() { |
| 15 | swap_pct() { awk '/^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{printf "%d", t ? (t-f)*100/t : 0}' /proc/meminfo; } | 53 | [ -r "$PROC_MEMINFO" ] || { echo 0; return; } |
| 54 | awk 'BEGIN{t=0; f=0} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{pct=(t>0 ? (t-f)*100/t : 0); printf "%d", pct}' "$PROC_MEMINFO" | ||
| 55 | } | ||
| 56 | read_uint() { | ||
| 57 | local v="" | ||
| 58 | if [ -r "$1" ]; then | ||
| 59 | v=$(cat "$1" 2>/dev/null || true) | ||
| 60 | v=${v//$'\r'/} | ||
| 61 | fi | ||
| 62 | [[ "$v" =~ ^[0-9]+$ ]] || v=0 | ||
| 63 | printf '%s' "$v" | ||
| 64 | } | ||
| 65 | |||
| 66 | SAMPLER="" | ||
| 67 | cleanup() { | ||
| 68 | if [ -n "${SAMPLER:-}" ]; then | ||
| 69 | kill "$SAMPLER" 2>/dev/null || true | ||
| 70 | wait "$SAMPLER" 2>/dev/null || true | ||
| 71 | SAMPLER="" | ||
| 72 | fi | ||
| 73 | } | ||
| 74 | trap cleanup EXIT INT TERM | ||
| 16 | 75 | ||
| 17 | exec 8>/opt/leonida/.gpu.lock; flock 8 # one boot at a time | 76 | exec 8>"$OUT/.gpu.lock" |
| 77 | if command -v flock >/dev/null 2>&1; then flock 8; fi # one boot at a time | ||
| 18 | echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG" | 78 | echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG" |
| 19 | for i in $(seq 1 40); do # up to 10 min for memory headroom | 79 | for ((i = 1; i <= WAIT_ITERS; i++)); do # up to 10 min for memory headroom |
| 20 | f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break | 80 | f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break |
| 21 | echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep 15 | 81 | echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep "$WAIT_SLEEP" |
| 22 | done | 82 | done |
| 23 | echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG" | 83 | echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG" |
| 24 | exec 9>/opt/leonida/.build.lock; flock 9 # no compiles while the game runs | 84 | exec 9>"$OUT/.build.lock" |
| 85 | if command -v flock >/dev/null 2>&1; then flock 9; fi # no compiles while the game runs | ||
| 25 | echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG" | 86 | echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG" |
| 26 | echo "boot_epoch=$(date +%s)" >> "$META" | 87 | echo "boot_epoch=$(date +%s)" >> "$META" |
| 27 | 88 | ||
| 28 | CG=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup) | 89 | cg_rel="" |
| 29 | ( printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n' | 90 | if [ -r "$CGROUP_SELF" ]; then |
| 91 | cg_rel=$(awk -F: '$1=="0"{print $3; exit}' "$CGROUP_SELF" 2>/dev/null || true) | ||
| 92 | [ -n "$cg_rel" ] || cg_rel=$(awk -F: 'NF>=3{p=$3} END{print p}' "$CGROUP_SELF" 2>/dev/null || true) | ||
| 93 | cg_rel=${cg_rel//$'\r'/} | ||
| 94 | fi | ||
| 95 | CG=$CGROUP_ROOT$cg_rel | ||
| 96 | ( trap 'kill "${sleep_pid:-}" 2>/dev/null || true; exit 0' TERM INT | ||
| 97 | sleep_pid="" | ||
| 98 | printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n' | ||
| 30 | while :; do | 99 | while :; do |
| 31 | read -r ma su < <(awk '/^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{print int(a/1024), int((t-f)/1024)}' /proc/meminfo) | 100 | ma=0; su=0 |
| 32 | um=$(( $(cat "$CG/memory.current" 2>/dev/null || echo 0) / 1048576 )); us=$(( $(cat "$CG/memory.swap.current" 2>/dev/null || echo 0) / 1048576 )) | 101 | if [ -r "$PROC_MEMINFO" ]; then |
| 33 | g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ' | tr ',' '\t') | 102 | read -r ma su < <(awk 'BEGIN{a=0; t=0; f=0} /^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{u=(t>f ? t-f : 0); print int(a/1024), int(u/1024)}' "$PROC_MEMINFO") |
| 103 | fi | ||
| 104 | um=$(( $(read_uint "$CG/memory.current") / 1048576 )) | ||
| 105 | us=$(( $(read_uint "$CG/memory.swap.current") / 1048576 )) | ||
| 106 | g=$("$NVIDIA_SMI" --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1 | tr -d ' \r' | tr ',' '\t') | ||
| 34 | printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}" | 107 | printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}" |
| 35 | sleep 2 | 108 | sleep "$SAMPLE_SLEEP" & |
| 109 | sleep_pid=$! | ||
| 110 | wait "$sleep_pid" 2>/dev/null || break | ||
| 111 | sleep_pid="" | ||
| 36 | done ) > "$RES" 2>/dev/null & | 112 | done ) > "$RES" 2>/dev/null & |
| 37 | SAMPLER=$! | 113 | SAMPLER=$! |
| 38 | 114 | ||
| 39 | /opt/leonida/boot.sh run "$BOOT_SECS" >> "$LOG" 2>&1 | 115 | if [ -f "$BOOT_SH" ]; then |
| 40 | rc=$? | 116 | "$BOOT_SH" run "$BOOT_SECS" >> "$LOG" 2>&1 |
| 41 | kill $SAMPLER 2>/dev/null | 117 | rc=$? |
| 118 | else | ||
| 119 | echo "[run-boot] missing boot script: $BOOT_SH" >> "$LOG" | ||
| 120 | rc=127 | ||
| 121 | fi | ||
| 122 | cleanup | ||
| 42 | echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG" | 123 | echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG" |
| 43 | # boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here. | 124 | # boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here. |
| 44 | [ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; } | 125 | [ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; } |
diff --git a/scripts/linux-boot/boot.sh b/scripts/linux-boot/boot.sh index 55f84f019..6a2268f27 100755 --- a/scripts/linux-boot/boot.sh +++ b/scripts/linux-boot/boot.sh | |||
| @@ -3,13 +3,65 @@ | |||
| 3 | # usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped) | 3 | # usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped) |
| 4 | # Traces stay local in /opt/leonida/traces: they can quote game data, never post them. | 4 | # Traces stay local in /opt/leonida/traces: they can quote game data, never post them. |
| 5 | set -u | 5 | set -u |
| 6 | MODE=${1:?dry-run|init|run}; SECS=${2:-150} | 6 | usage() { |
| 7 | OUT=/opt/leonida | 7 | echo "usage: boot.sh dry-run|init|run [seconds]" |
| 8 | } | ||
| 9 | |||
| 10 | if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then | ||
| 11 | usage | ||
| 12 | exit 0 | ||
| 13 | fi | ||
| 14 | if [ $# -lt 1 ] || [ $# -gt 2 ]; then | ||
| 15 | usage >&2 | ||
| 16 | exit 2 | ||
| 17 | fi | ||
| 18 | |||
| 19 | MODE=$1 | ||
| 20 | SECS=${2:-150} | ||
| 21 | case "$MODE" in | ||
| 22 | dry-run|init|run) ;; | ||
| 23 | *) | ||
| 24 | echo "boot.sh: invalid mode: $MODE (expected dry-run, init, or run)" >&2 | ||
| 25 | exit 2 | ||
| 26 | ;; | ||
| 27 | esac | ||
| 28 | if ! [[ "$SECS" =~ ^[1-9][0-9]*$ ]]; then | ||
| 29 | echo "boot.sh: invalid seconds: $SECS (expected positive integer)" >&2 | ||
| 30 | exit 2 | ||
| 31 | fi | ||
| 32 | |||
| 33 | OUT=${LEONIDA_OUT:-/opt/leonida} | ||
| 8 | REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in | 34 | REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in |
| 35 | WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx | ||
| 36 | PYTHON3=${PYTHON3:-python3} | ||
| 37 | UNSHARE=${UNSHARE:-unshare} | ||
| 38 | TIMEOUT=${TIMEOUT:-timeout} | ||
| 39 | GAME_DIR=${LEONIDA_GAME_DIR:-/opt/gta6/GTA6.Xbox.v1.0.2.1} | ||
| 40 | GAME_WIN=${LEONIDA_GAME_WIN:-'Z:\opt\gta6\GTA6.Xbox.v1.0.2.1'} | ||
| 41 | EXE=${LEONIDA_EXE:-$GAME_DIR/game_scarlett_master.exe} | ||
| 42 | OVERLAY_WIN=${LEONIDA_OVERLAY_WIN:-'Z:\opt\leonida\overlay'} | ||
| 43 | GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=<your build>/gta6rt.exe boots a private build without installing it | ||
| 44 | |||
| 45 | if [ ! -f "$GTA6RT" ]; then | ||
| 46 | echo "boot.sh: missing gta6rt executable: $GTA6RT" >&2 | ||
| 47 | exit 2 | ||
| 48 | fi | ||
| 49 | if ! command -v "$UNSHARE" >/dev/null 2>&1; then | ||
| 50 | echo "boot.sh: missing required command: $UNSHARE" >&2 | ||
| 51 | exit 2 | ||
| 52 | fi | ||
| 53 | if [ "$MODE" = run ] && ! command -v "$TIMEOUT" >/dev/null 2>&1; then | ||
| 54 | echo "boot.sh: missing required command: $TIMEOUT" >&2 | ||
| 55 | exit 2 | ||
| 56 | fi | ||
| 57 | if ! command -v "$WINE" >/dev/null 2>&1; then | ||
| 58 | echo "boot.sh: missing required Wine binary: $WINE" >&2 | ||
| 59 | exit 2 | ||
| 60 | fi | ||
| 61 | |||
| 9 | STAMP=$(date +%H%M%S) | 62 | STAMP=$(date +%H%M%S) |
| 10 | T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv" | 63 | T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv" |
| 11 | 64 | ||
| 12 | WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx | ||
| 13 | export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml=" | 65 | export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml=" |
| 14 | export LEONIDA_D3D12=vulkan | 66 | export LEONIDA_D3D12=vulkan |
| 15 | export LEONIDA_SHADERS=$OUT/work/shaders/spirv | 67 | export LEONIDA_SHADERS=$OUT/work/shaders/spirv |
| @@ -20,23 +72,22 @@ export __GL_SHADER_DISK_CACHE=1 __GL_SHADER_DISK_CACHE_PATH=$OUT/cache/nv __GL_S | |||
| 20 | export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 | 72 | export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 |
| 21 | [ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1 | 73 | [ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1 |
| 22 | 74 | ||
| 23 | GAME_WIN='Z:\opt\gta6\GTA6.Xbox.v1.0.2.1' | 75 | TRACE_WIN=${LEONIDA_TRACE_WIN:-"Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl"} |
| 24 | EXE=/opt/gta6/GTA6.Xbox.v1.0.2.1/game_scarlett_master.exe | ||
| 25 | TRACE_WIN="Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl" | ||
| 26 | D3D=$T/d3d12-$MODE-$STAMP.log | 76 | D3D=$T/d3d12-$MODE-$STAMP.log |
| 27 | GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=<your build>/gta6rt.exe boots a private build without installing it | ||
| 28 | 77 | ||
| 29 | args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay 'Z:\opt\leonida\overlay' --trace "$TRACE_WIN") | 78 | args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay "$OVERLAY_WIN" --trace "$TRACE_WIN") |
| 30 | [ "$MODE" = run ] && args+=(--trace-d3d12) | 79 | [ "$MODE" = run ] && args+=(--trace-d3d12) |
| 31 | echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D" | 80 | echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D" |
| 32 | # unshare: new user + network namespace, so the title has no network at all | 81 | # unshare: new user + network namespace, so the title has no network at all |
| 33 | if [ "$MODE" = run ]; then | 82 | if [ "$MODE" = run ]; then |
| 34 | timeout --signal=INT --kill-after=20 "$SECS" unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" | 83 | "$TIMEOUT" --signal=INT --kill-after=20 "$SECS" "$UNSHARE" -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" |
| 35 | else | 84 | else |
| 36 | unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" | 85 | "$UNSHARE" -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" |
| 37 | fi | 86 | fi |
| 38 | rc=$?; echo "[boot] exit=$rc" | 87 | rc=$?; echo "[boot] exit=$rc" |
| 39 | sleep 0 | 88 | sleep 0 |
| 40 | python3 -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1 | 89 | if [ -f "$REPO/tools/boot_trace.py" ]; then |
| 41 | echo "[boot] summary: $T/summary-$MODE-$STAMP.txt" | 90 | "$PYTHON3" -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1 || true |
| 42 | exit $rc | 91 | echo "[boot] summary: $T/summary-$MODE-$STAMP.txt" |
| 92 | fi | ||
| 93 | exit "$rc" | ||
diff --git a/scripts/linux-boot/configure-worktree.sh b/scripts/linux-boot/configure-worktree.sh index c983b3357..ef94973a9 100755 --- a/scripts/linux-boot/configure-worktree.sh +++ b/scripts/linux-boot/configure-worktree.sh | |||
| @@ -2,8 +2,49 @@ | |||
| 2 | # usage: configure-worktree.sh <worktree> | 2 | # usage: configure-worktree.sh <worktree> |
| 3 | # Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default | 3 | # Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default |
| 4 | # ~/.local/share/xwin-sdk). SDL3_SRC=<an SDL3 source tree> makes the configure work offline. | 4 | # ~/.local/share/xwin-sdk). SDL3_SRC=<an SDL3 source tree> makes the configure work offline. |
| 5 | set -eu; W=$(realpath "$1") | 5 | set -eu |
| 6 | cmake -S "$W/runtime" -B "$W/runtime/build/boot" -G Ninja -DCMAKE_BUILD_TYPE=Release \ | 6 | |
| 7 | -DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" \ | 7 | usage() { |
| 8 | -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON -DLEONIDA_SDL3=ON \ | 8 | echo "usage: configure-worktree.sh <worktree>" |
| 9 | ${SDL3_SRC:+-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC"} | 9 | } |
| 10 | |||
| 11 | die() { | ||
| 12 | echo "ERROR: $*" >&2 | ||
| 13 | exit 2 | ||
| 14 | } | ||
| 15 | |||
| 16 | if [ "$#" -ge 1 ] && { [ "$1" = "-h" ] || [ "$1" = "--help" ]; }; then | ||
| 17 | usage | ||
| 18 | exit 0 | ||
| 19 | fi | ||
| 20 | |||
| 21 | [ "$#" -eq 1 ] || { usage >&2; exit 2; } | ||
| 22 | [ -n "$1" ] || die "worktree path must not be empty" | ||
| 23 | [ -d "$1" ] || die "worktree directory does not exist: $1" | ||
| 24 | |||
| 25 | W=$(realpath "$1") | ||
| 26 | [ -f "$W/runtime/CMakeLists.txt" ] || die "not a runtime worktree (missing runtime/CMakeLists.txt): $W" | ||
| 27 | [ -f "$W/runtime/cmake/clang-cl-xwin.cmake" ] || die "missing toolchain file: $W/runtime/cmake/clang-cl-xwin.cmake" | ||
| 28 | |||
| 29 | CMAKE=${CMAKE:-cmake} | ||
| 30 | command -v "$CMAKE" >/dev/null 2>&1 || die "cmake executable not found: $CMAKE" | ||
| 31 | |||
| 32 | if [ -n "${SDL3_SRC:-}" ] && [ ! -d "$SDL3_SRC" ]; then | ||
| 33 | die "SDL3_SRC directory does not exist: $SDL3_SRC" | ||
| 34 | fi | ||
| 35 | |||
| 36 | cmake_args=( | ||
| 37 | -S "$W/runtime" | ||
| 38 | -B "$W/runtime/build/boot" | ||
| 39 | -G Ninja | ||
| 40 | -DCMAKE_BUILD_TYPE=Release | ||
| 41 | -DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" | ||
| 42 | -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" | ||
| 43 | -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON | ||
| 44 | -DLEONIDA_SDL3=ON | ||
| 45 | ) | ||
| 46 | if [ -n "${SDL3_SRC:-}" ]; then | ||
| 47 | cmake_args+=(-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC") | ||
| 48 | fi | ||
| 49 | |||
| 50 | "$CMAKE" "${cmake_args[@]}" | ||
diff --git a/scripts/linux-boot/run-boot.sh b/scripts/linux-boot/run-boot.sh index 523d17795..b23036ccb 100755 --- a/scripts/linux-boot/run-boot.sh +++ b/scripts/linux-boot/run-boot.sh | |||
| @@ -16,10 +16,26 @@ | |||
| 16 | # Outputs (in /opt/leonida/work/<agent>/): boot-<n>.log boot-<n>.resources.tsv boot-<n>.digest.txt | 16 | # Outputs (in /opt/leonida/work/<agent>/): boot-<n>.log boot-<n>.resources.tsv boot-<n>.digest.txt |
| 17 | set -u | 17 | set -u |
| 18 | AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# )) | 18 | AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# )) |
| 19 | if [ "$AGENT" = "." ] || [ "$AGENT" = ".." ] || ! [[ "$AGENT" =~ ^[A-Za-z0-9._-]+$ ]]; then | ||
| 20 | echo "run-boot: invalid agent: $AGENT" >&2; exit 2 | ||
| 21 | fi | ||
| 22 | if ! [[ "$N" =~ ^[0-9]+$ ]]; then | ||
| 23 | echo "run-boot: invalid boot number: $N" >&2; exit 2 | ||
| 24 | fi | ||
| 25 | if ! [[ "$SECS" =~ ^[1-9][0-9]*$ ]]; then | ||
| 26 | echo "run-boot: invalid seconds (expected positive integer): $SECS" >&2; exit 2 | ||
| 27 | fi | ||
| 28 | for kv in "$@"; do | ||
| 29 | if ! [[ "$kv" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then | ||
| 30 | echo "run-boot: invalid environment override (expected KEY=VALUE): $kv" >&2; exit 2 | ||
| 31 | fi | ||
| 32 | done | ||
| 19 | [ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; } | 33 | [ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; } |
| 20 | # gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once. | 34 | # gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once. |
| 21 | [ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; } | 35 | [ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; } |
| 22 | WORK=/opt/leonida/work/$AGENT; mkdir -p "$WORK" | 36 | ROOT=${LEONIDA_BOOT_ROOT:-/opt/leonida} |
| 37 | WIN_ROOT=${ROOT#/}; WIN_ROOT="Z:\\${WIN_ROOT//\//\\}" | ||
| 38 | WORK=$ROOT/work/$AGENT; mkdir -p "$WORK" | ||
| 23 | UNIT=leonida-boot-$AGENT-$N | 39 | UNIT=leonida-boot-$AGENT-$N |
| 24 | if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi | 40 | if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi |
| 25 | 41 | ||
| @@ -28,10 +44,10 @@ declare -A ENV=( | |||
| 28 | [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx" | 44 | [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx" |
| 29 | [WINEDEBUG]="-all,err+all" | 45 | [WINEDEBUG]="-all,err+all" |
| 30 | [GTA6RT]="$EXE" | 46 | [GTA6RT]="$EXE" |
| 31 | [LEONIDA_CAPTURE]="Z:\\opt\\leonida\\capture\\$AGENT-$N" | 47 | [LEONIDA_CAPTURE]="$WIN_ROOT\\capture\\$AGENT-$N" |
| 32 | [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1 | 48 | [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1 |
| 33 | [LEONIDA_DEVICE_TYPE]=6 | 49 | [LEONIDA_DEVICE_TYPE]=6 |
| 34 | [LEONIDA_PIPELINE_CACHE_DIR]="Z:\\opt\\leonida\\cache\\pipelines" | 50 | [LEONIDA_PIPELINE_CACHE_DIR]="$WIN_ROOT\\cache\\pipelines" |
| 35 | ) | 51 | ) |
| 36 | for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done | 52 | for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done |
| 37 | args=() | 53 | args=() |
| @@ -39,16 +55,16 @@ for k in "${!ENV[@]}"; do args+=(--setenv="$k=${ENV[$k]}"); done | |||
| 39 | 55 | ||
| 40 | echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)" | 56 | echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)" |
| 41 | rm -f "$WORK/boot-$N.digest.txt" | 57 | rm -f "$WORK/boot-$N.digest.txt" |
| 42 | systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory=/opt/leonida \ | 58 | systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory="$ROOT" \ |
| 43 | --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \ | 59 | --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \ |
| 44 | /opt/leonida/boot-inner.sh || { echo "run-boot: could not start $UNIT" >&2; exit 2; } | 60 | "$ROOT/boot-inner.sh" || { echo "run-boot: could not start $UNIT" >&2; exit 2; } |
| 45 | # The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the | 61 | # The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the |
| 46 | # caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest. | 62 | # caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest. |
| 47 | systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \ | 63 | systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \ |
| 48 | /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done | 64 | /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done |
| 49 | START=$(sed -n "s/^start_epoch=//p" "/opt/leonida/work/$1/boot-$2.meta" 2>/dev/null) | 65 | START=$(sed -n "s/^start_epoch=//p" "$3/work/$1/boot-$2.meta" 2>/dev/null) |
| 50 | RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //") | 66 | RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //") |
| 51 | SERVICE_RESULT=${RES:-success} exec /opt/leonida/boot-digest.sh "$1" "$2"' "$UNIT" "$AGENT" "$N" | 67 | SERVICE_RESULT=${RES:-success} exec "$3/boot-digest.sh" "$1" "$2"' "$UNIT" "$AGENT" "$N" "$ROOT" |
| 52 | # Block until the digest exists (so a caller that waits on this script gets the result), then print it. | 68 | # Block until the digest exists (so a caller that waits on this script gets the result), then print it. |
| 53 | while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done | 69 | while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done |
| 54 | echo "run-boot: $UNIT finished. Digest:" | 70 | echo "run-boot: $UNIT finished. Digest:" |
diff --git a/scripts/merge_check.py b/scripts/merge_check.py index f2a4ffd02..be2b69176 100644 --- a/scripts/merge_check.py +++ b/scripts/merge_check.py | |||
| @@ -42,7 +42,7 @@ class GitError(Exception): | |||
| 42 | pass | 42 | pass |
| 43 | 43 | ||
| 44 | 44 | ||
| 45 | def git(repo, *args, check=True, timeout=GIT_TIMEOUT): | 45 | def git(repo, *args, check=True, stdout_errors="replace", timeout=GIT_TIMEOUT): |
| 46 | try: | 46 | try: |
| 47 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True, timeout=timeout) | 47 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True, timeout=timeout) |
| 48 | except subprocess.TimeoutExpired: | 48 | except subprocess.TimeoutExpired: |
| @@ -50,7 +50,7 @@ def git(repo, *args, check=True, timeout=GIT_TIMEOUT): | |||
| 50 | except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback | 50 | except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback |
| 51 | raise GitError(f"cannot run git: {e.strerror or e}") from None | 51 | raise GitError(f"cannot run git: {e.strerror or e}") from None |
| 52 | # Decode without universal-newline translation: a bare CR inside a Git line is content. | 52 | # Decode without universal-newline translation: a bare CR inside a Git line is content. |
| 53 | r.stdout = r.stdout.decode("utf-8", "replace") | 53 | r.stdout = r.stdout.decode("utf-8", stdout_errors) |
| 54 | r.stderr = r.stderr.decode("utf-8", "replace") | 54 | r.stderr = r.stderr.decode("utf-8", "replace") |
| 55 | if check and r.returncode != 0: | 55 | if check and r.returncode != 0: |
| 56 | raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}") | 56 | raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}") |
| @@ -135,7 +135,8 @@ def duplicates(repo, main, tree, min_length, block=3): | |||
| 135 | 135 | ||
| 136 | def windows(rev, path): | 136 | def windows(rev, path): |
| 137 | # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. | 137 | # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. |
| 138 | r = git(repo, "show", f"{rev}:{path}", "--") | 138 | # Keep undecodable bytes distinct while comparing lines from legacy-encoded documents. |
| 139 | r = git(repo, "show", f"{rev}:{path}", "--", stdout_errors="surrogateescape") | ||
| 139 | lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] | 140 | lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] |
| 140 | content = [text for _, text in lines] | 141 | content = [text for _, text in lines] |
| 141 | return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) | 142 | return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) |
| @@ -156,7 +157,8 @@ def duplicates(repo, main, tree, min_length, block=3): | |||
| 156 | if before[run] and after[run] > before[run]: | 157 | if before[run] and after[run] > before[run]: |
| 157 | marked.update(number for number, _ in window) | 158 | marked.update(number for number, _ in window) |
| 158 | if marked: | 159 | if marked: |
| 159 | found[path] = [text for number, text in after_lines if number in marked] | 160 | found[path] = [text.encode("utf-8", "surrogateescape").decode("utf-8", "replace") |
| 161 | for number, text in after_lines if number in marked] | ||
| 160 | return found | 162 | return found |
| 161 | 163 | ||
| 162 | 164 | ||
diff --git a/scripts/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1 deleted file mode 100644 index 28c6575f6..000000000 --- a/scripts/meta_to_xml.ps1 +++ /dev/null | |||
| @@ -1,52 +0,0 @@ | |||
| 1 | # Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers. | ||
| 2 | # Run in Windows PowerShell 5.1. | ||
| 3 | # .\meta_to_xml.ps1 -Carve <work>\carve -Out <work>\meta [-Limit N] | ||
| 4 | # Each blob becomes <Out>\<archive>\<offset>.xml. Failures go to <Out>\failures.txt (UTF-8 with BOM) with the error message. | ||
| 5 | param( | ||
| 6 | [string]$Carve = "<work>\carve", | ||
| 7 | [string]$Out = "<work>\meta", | ||
| 8 | [string]$CodeWalker = "<ref>\codewalker-gen9", | ||
| 9 | [int]$Limit = 0 | ||
| 10 | ) | ||
| 11 | $ErrorActionPreference = "Stop" | ||
| 12 | try { (Get-Process -Id $PID).PriorityClass = "BelowNormal" } catch {} | ||
| 13 | Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Mathematics.dll" | ||
| 14 | [void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") | ||
| 15 | New-Item -ItemType Directory -Force $Out | Out-Null | ||
| 16 | $fail = Join-Path $Out "failures.txt" | ||
| 17 | "" | Set-Content -LiteralPath $fail -Encoding utf8 | ||
| 18 | $ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0 | ||
| 19 | |||
| 20 | foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { | ||
| 21 | $idx = Join-Path $dir.FullName "index.json" | ||
| 22 | if (-not (Test-Path -LiteralPath $idx)) { continue } | ||
| 23 | $files = (Get-Content -LiteralPath $idx -Raw | ConvertFrom-Json).files | | ||
| 24 | Where-Object { $_.head.StartsWith("5053494e") -or $_.head.StartsWith("52424630") } | ||
| 25 | if (-not $files) { continue } | ||
| 26 | $dest = Join-Path $Out $dir.Name | ||
| 27 | New-Item -ItemType Directory -Force $dest | Out-Null | ||
| 28 | foreach ($r in $files) { | ||
| 29 | if ($Limit -and $n -ge $Limit) { break } | ||
| 30 | $n++ | ||
| 31 | $name = "{0:x12}" -f [int64]$r.off | ||
| 32 | $kind = if ($r.head.StartsWith("5053494e")) { "pso" } else { "rbf" } | ||
| 33 | try { | ||
| 34 | $bytes = [IO.File]::ReadAllBytes((Join-Path $dir.FullName "$name.bin")) | ||
| 35 | if ($kind -eq "pso") { | ||
| 36 | $f = New-Object CodeWalker.GameFiles.PsoFile; $f.Load($bytes) | ||
| 37 | $xml = [CodeWalker.GameFiles.PsoXml]::GetXml($f) | ||
| 38 | } else { | ||
| 39 | $f = New-Object CodeWalker.GameFiles.RbfFile; $f.Load($bytes) | ||
| 40 | $xml = [CodeWalker.GameFiles.RbfXml]::GetXml($f) | ||
| 41 | } | ||
| 42 | [IO.File]::WriteAllText((Join-Path $dest "$name.$kind.xml"), $xml) | ||
| 43 | $ok[$kind]++ | ||
| 44 | } catch { | ||
| 45 | $bad[$kind]++ | ||
| 46 | $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception } | ||
| 47 | "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content -LiteralPath $fail -Encoding utf8 | ||
| 48 | } | ||
| 49 | } | ||
| 50 | if ($Limit -and $n -ge $Limit) { break } | ||
| 51 | } | ||
| 52 | "pso ok $($ok.pso) failed $($bad.pso); rbf ok $($ok.rbf) failed $($bad.rbf) -> $Out" | ||
diff --git a/scripts/play-d3d12.ps1 b/scripts/play-d3d12.ps1 new file mode 100644 index 000000000..70cb328ec --- /dev/null +++ b/scripts/play-d3d12.ps1 | |||
| @@ -0,0 +1,115 @@ | |||
| 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 with a 2560x1440 output and its own dynamic resolution and temporal | ||
| 7 | # upscaler: it renders between 1080 and 1440 lines by how long its frames take (-Lowest 1080); -SeriesS runs the | ||
| 8 | # lighter Series S profile instead, where the game renders its own 720p picture and DLSS takes it to 1080p. | ||
| 9 | # -Resolution holds one rendered height instead (Series X: 1080 or 1440), -Lowest sets the lowest one. DLSS and DLSS | ||
| 10 | # frame generation need a few of NVIDIA's own files that no repository may carry: d3d12\Get-NVIDIA-DLSS.cmd fetches | ||
| 11 | # them from NVIDIA's GitHub once (about 70 MB). Without them the picture is stretched to the screen instead. | ||
| 12 | # In the game: F1 = settings (frame generation, frame-rate cap, DLSS preset ...), F3 = the numbers panel. | ||
| 13 | # | ||
| 14 | # -SmoothMotion starts leonida_sm.exe, the copy NVIDIA's Smooth Motion profile is set for (scripts\smooth-motion.ps1 | ||
| 15 | # -State on sets it): the driver shows twice the frames the game renders (RTX 40 and 50). Not the | ||
| 16 | # default: the one start made that way on 2026-11-27 ended 2.4 s in with the title's own breakpoint | ||
| 17 | # (0x80000003 in its main loop), and the next start without it ran. Not looked into yet. | ||
| 18 | # -NoDlss the picture is stretched instead of going through DLSS | ||
| 19 | # -Dlss DLSS makes the output, on Series X too: quality (rendered at 1440 lines of the 2160), balanced | ||
| 20 | # (1296), performance (1080) or ultra (720). Leave -Resolution out with it. | ||
| 21 | # -FrameGen DLSS frame generation: 2 shows twice the frames rendered (up to 6 where the card does more). On | ||
| 22 | # Series X it needs the DLSS upscale and turns -Dlss quality on unless a mode is given. Without it, on | ||
| 23 | # RTX 40 and 50 cards with NVIDIA's files there, d3d12\scripts\play-nvidia.ps1 turns 2x on by itself | ||
| 24 | # on the title's own upscaler, held to 28 shown frames a second. | ||
| 25 | # -NoFrameGen no DLSS frame generation at all, the frames the game renders only | ||
| 26 | # -MotionBlur the game's own motion blur (left out by default: at this frame rate it smears in blocks on turns) | ||
| 27 | # -FsrFrameGen AMD's FSR 3 frame generation instead (2x), for cards without DLSS frame generation (RTX 20 and 30): | ||
| 28 | # needs AMD's two signed FidelityFX DLLs in d3d12\amd-sdk\FidelityFX\bin | ||
| 29 | # -Fullscreen the game's window borderless over its whole monitor (Alt+Enter switches while it runs) | ||
| 30 | # -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 | ||
| 31 | # centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch). | ||
| 32 | # -Resolution the older path: the game renders at this height and the title's own upscaler does the rest | ||
| 33 | # -Lowest the lowest height of the title's own dynamic resolution (1080 by default on Series X): it renders | ||
| 34 | # between this and 1440 lines. Same save, RTX 4060 Ti (2026-11-29): 57.0 and 59.6 ms a frame (median, | ||
| 35 | # two series) against 66.0 and 67.9 at -Resolution 1440; the frames sat at 1080 there. | ||
| 36 | # -RayTracing the title's real ray tracing (slower; shaders build for minutes the first time) | ||
| 37 | # -Capture F9 in the game saves that frame and the pictures it drew | ||
| 38 | # -NoPrecompile start at once: by default every shader is translated and the pipelines earlier runs drew with are | ||
| 39 | # made before the title starts (minutes the first time, seconds after) | ||
| 40 | # -Log the runtime's log goes to a file under %LOCALAPPDATA%\Leonida\logs | ||
| 41 | # -DryRun prints the settings this start would run with and stops: nothing is built or started | ||
| 42 | # -PcGlyphs a folder of your own pictures for the keyboard-and-mouse button prompts instead of the built-in key | ||
| 43 | # caps (docs/prompt_glyphs.md; both prompt movies are built before the start when missing) | ||
| 44 | # | ||
| 45 | # Builds d3d12/ when it is missing (d3d12\scripts\build-nvidia.ps1: the diag profile, with DLSS when NVIDIA's files | ||
| 46 | # are there), keeps the caches and saves under -Data, and hands everything else to d3d12\scripts\play-nvidia.ps1: | ||
| 47 | # -SeriesX, -Quality, -Adapter and -More pass through. Nothing goes online. | ||
| 48 | param( | ||
| 49 | [Parameter(Mandatory = $true)][string]$Game, | ||
| 50 | [string]$Data = (Join-Path $env:LOCALAPPDATA "Leonida\d3d12"), | ||
| 51 | [switch]$SeriesX, | ||
| 52 | [switch]$SeriesS, | ||
| 53 | [switch]$Quality, | ||
| 54 | [ValidateSet('', '2160', '1440', '1080', '720', '540', '480')][string]$Resolution = '', | ||
| 55 | [ValidateSet('', '1440', '1080', '720', '540', '480')][string]$Lowest = '', | ||
| 56 | [ValidateSet('', 'quality', 'balanced', 'performance', 'ultra')][string]$Dlss = '', | ||
| 57 | [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0, | ||
| 58 | [switch]$NoFrameGen, | ||
| 59 | [switch]$MotionBlur, | ||
| 60 | [switch]$FsrFrameGen, | ||
| 61 | [switch]$Fullscreen, | ||
| 62 | [string]$Aspect = '', | ||
| 63 | [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '', | ||
| 64 | [string]$Adapter = '', | ||
| 65 | [hashtable]$More = @{}, | ||
| 66 | [switch]$Rebuild, | ||
| 67 | [switch]$SmoothMotion, | ||
| 68 | [switch]$NoSmoothMotion, | ||
| 69 | [switch]$NoDlss, | ||
| 70 | [switch]$RayTracing, | ||
| 71 | [switch]$Capture, | ||
| 72 | [switch]$NoPrecompile, | ||
| 73 | [switch]$Log, | ||
| 74 | [switch]$DryRun, | ||
| 75 | [string]$PcGlyphs = '' | ||
| 76 | ) | ||
| 77 | |||
| 78 | $ErrorActionPreference = "Stop" | ||
| 79 | $repo = Split-Path -Parent $PSScriptRoot | ||
| 80 | $runtime = Join-Path $repo "d3d12" | ||
| 81 | $exe = Join-Path $runtime "target\diag\leonida.exe" | ||
| 82 | $title = Join-Path $Game "game_scarlett_master.exe" | ||
| 83 | if (-not (Test-Path $title)) { throw "missing: $title" } | ||
| 84 | if (-not $DryRun -and ($Rebuild -or -not (Test-Path $exe))) { | ||
| 85 | & (Join-Path $runtime "scripts\build-nvidia.ps1") | ||
| 86 | if ($LASTEXITCODE -ne 0) { throw "cargo build failed ($LASTEXITCODE)" } | ||
| 87 | } | ||
| 88 | # A shader cache of its own: one filled before the renderer changed (cache\) does not fit its pipelines. | ||
| 89 | New-Item -ItemType Directory -Force (Join-Path $Data "cache-2"), (Join-Path $Data "data") | Out-Null | ||
| 90 | $env:LEONIDA_GAME_DIR = (Resolve-Path $Game).Path | ||
| 91 | $env:LEONIDA_CACHE_DIR = Join-Path $Data "cache-2" | ||
| 92 | $env:LEONIDA_DATA_DIR = Join-Path $Data "data" | ||
| 93 | |||
| 94 | # Leonida: Smooth Motion only with -SmoothMotion (it was the default for one start, which the title did not | ||
| 95 | # survive; -NoSmoothMotion is kept and means the same as leaving -SmoothMotion out). | ||
| 96 | $launch = @{ Exe = $title; Build = 'diag'; NoSmoothMotion = (-not $SmoothMotion); More = $More } | ||
| 97 | # Leonida: the Series X profile is the default (the user's call: 1080p-1440p as on the bigger consoles). | ||
| 98 | if (-not $SeriesS) { | ||
| 99 | $launch.SeriesX = $true | ||
| 100 | # 1080 to 1440 lines by the title's own dynamic resolution and its own upscaler, unless a height is held | ||
| 101 | # (-Resolution) or DLSS (which -FrameGen brings with it) makes the output. | ||
| 102 | if (-not $Resolution -and -not $Lowest -and -not $Dlss -and -not $FrameGen) { $Lowest = '1080' } | ||
| 103 | } | ||
| 104 | if ($Dlss) { $launch.Dlss = $Dlss } | ||
| 105 | if ($FrameGen) { $launch.FrameGen = $FrameGen } | ||
| 106 | if ($Aspect) { $launch.Aspect = $Aspect } | ||
| 107 | if ($PresentScale) { $launch.PresentScale = $PresentScale } | ||
| 108 | foreach ($switch in 'Quality', 'NoDlss', 'NoFrameGen', 'MotionBlur', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun', 'FsrFrameGen', 'Fullscreen') { | ||
| 109 | if ($PSBoundParameters[$switch]) { $launch[$switch] = $true } | ||
| 110 | } | ||
| 111 | if ($Resolution) { $launch.Resolution = $Resolution } | ||
| 112 | if ($Lowest) { $launch.Lowest = $Lowest } | ||
| 113 | if ($Adapter) { $launch.Adapter = $Adapter } | ||
| 114 | if ($PcGlyphs) { $launch.PcGlyphs = (Resolve-Path $PcGlyphs).Path } | ||
| 115 | & (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..35a44256f --- /dev/null +++ b/scripts/play-linux.sh | |||
| @@ -0,0 +1,74 @@ | |||
| 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. | ||
| 11 | set -eu | ||
| 12 | |||
| 13 | if [ $# -lt 1 ]; then | ||
| 14 | echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x]" >&2 | ||
| 15 | exit 2 | ||
| 16 | fi | ||
| 17 | game_exe=$1 | ||
| 18 | shift | ||
| 19 | console=series-s | ||
| 20 | if [ "${1:-}" = "--series-x" ]; then console=series-x; fi | ||
| 21 | [ -f "$game_exe" ] || { echo "No $game_exe" >&2; exit 1; } | ||
| 22 | |||
| 23 | here=$(cd "$(dirname "$0")" && pwd) | ||
| 24 | runtime=${LEONIDA_RUNTIME:-$here/leonida.exe} | ||
| 25 | vkd3d=${LEONIDA_VKD3D:-$here/vkd3d-proton} | ||
| 26 | [ -f "$runtime" ] || { echo "No $runtime (the Windows build of d3d12/)" >&2; exit 1; } | ||
| 27 | for 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; } | ||
| 29 | done | ||
| 30 | command -v wine >/dev/null 2>&1 || { echo "Wine is needed (your distribution's wine package, or Proton's)" >&2; exit 1; } | ||
| 31 | |||
| 32 | data=${XDG_DATA_HOME:-$HOME/.local/share}/leonida | ||
| 33 | export WINEPREFIX=${LEONIDA_WINEPREFIX:-$data/prefix} | ||
| 34 | export WINEARCH=win64 | ||
| 35 | if [ ! -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 | ||
| 39 | fi | ||
| 40 | # The bundled VKD3D-Proton, copied in when it is missing or differs (a new package). | ||
| 41 | system32=$WINEPREFIX/drive_c/windows/system32 | ||
| 42 | for dll in d3d12.dll d3d12core.dll; do | ||
| 43 | if ! cmp -s "$vkd3d/$dll" "$system32/$dll"; then cp "$vkd3d/$dll" "$system32/$dll"; fi | ||
| 44 | done | ||
| 45 | export WINEDLLOVERRIDES="d3d12,d3d12core=n${WINEDLLOVERRIDES:+;$WINEDLLOVERRIDES}" | ||
| 46 | |||
| 47 | # Where the title's files are, and where the caches and saves go. | ||
| 48 | export LEONIDA_GAME_DIR=${LEONIDA_GAME_DIR:-$(cd "$(dirname "$game_exe")" && pwd)} | ||
| 49 | export LEONIDA_CACHE_DIR=${LEONIDA_CACHE_DIR:-$data/cache} | ||
| 50 | export LEONIDA_DATA_DIR=${LEONIDA_DATA_DIR:-$data/data} | ||
| 51 | mkdir -p "$LEONIDA_CACHE_DIR" "$LEONIDA_DATA_DIR" | ||
| 52 | |||
| 53 | # The settings scripts/play-nvidia.ps1 measured (d3d12/README.md), as defaults. | ||
| 54 | set_default() { eval "[ -n \"\${$1:-}\" ] || export $1=\"$2\""; } | ||
| 55 | set_default LEONIDA_TEXTURE_NO_WAIT 1 | ||
| 56 | set_default LEONIDA_RELAY 2 | ||
| 57 | set_default LEONIDA_CARD_STEPS 2 | ||
| 58 | set_default LEONIDA_DYNAMIC_SLOTS 524288 | ||
| 59 | set_default LEONIDA_PIPELINE_WAIT_MS 10000 | ||
| 60 | set_default LEONIDA_RENDER_SCALE 0.5 | ||
| 61 | set_default LEONIDA_OWN_UPSCALER 1 | ||
| 62 | set_default LEONIDA_BVH_MISS 1 | ||
| 63 | set_default LEONIDA_CARD_BUFFERS_MIN_MB 1 | ||
| 64 | set_default LEONIDA_CARD_BUFFERS_MB 1536 | ||
| 65 | set_default LEONIDA_COMPOSE 1 | ||
| 66 | set_default LEONIDA_NAN_SCRUB 1 | ||
| 67 | set_default LEONIDA_AMBIENT_AIR 1.5 | ||
| 68 | set_default LEONIDA_AMBIENT_MOST 2 | ||
| 69 | # Match the Windows launcher defaults; explicit 0 keeps either path off for comparisons. | ||
| 70 | set_default LEONIDA_COPY_SCOPED 1 | ||
| 71 | set_default LEONIDA_PORT_DESCRIPTORS 1 | ||
| 72 | |||
| 73 | echo "Leonida: $console under Wine with the bundled VKD3D-Proton ($(head -n 1 "$vkd3d/SOURCE.txt" 2>/dev/null || echo bundled))" | ||
| 74 | exec wine "$runtime" run "$game_exe" --execute --console "$console" | ||
diff --git a/scripts/play.ps1 b/scripts/play.ps1 new file mode 100644 index 000000000..70a990685 --- /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. | ||
| 7 | param( | ||
| 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 | ||
| 21 | if (-not $Build) { $Build = Join-Path $repo "runtime\build-vk\RelWithDebInfo" } | ||
| 22 | if (-not $Overlay) { $Overlay = Join-Path $Work "overlay" } | ||
| 23 | if (-not $Saves) { $Saves = Join-Path $Work "saves" } | ||
| 24 | $exe = Join-Path $Build "gta6rt.exe" | ||
| 25 | $title = Join-Path $Game "game_scarlett_master.exe" | ||
| 26 | foreach ($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 | } | ||
| 29 | New-Item -ItemType Directory -Force $Overlay, $Saves | Out-Null | ||
| 30 | |||
| 31 | function Set-Default([string]$Name, [string]$Value) { | ||
| 32 | if (-not [Environment]::GetEnvironmentVariable($Name)) { [Environment]::SetEnvironmentVariable($Name, $Value) } | ||
| 33 | } | ||
| 34 | Set-Default "LEONIDA_D3D12" "vulkan" | ||
| 35 | Set-Default "LEONIDA_SHADERS" (Join-Path $Work "shaders\spirv") | ||
| 36 | Set-Default "LEONIDA_SAVE_DIR" $Saves | ||
| 37 | Set-Default "LEONIDA_DISPLAY_MODE" $DisplayMode | ||
| 38 | if ($Aspect) { Set-Default "LEONIDA_ASPECT" $Aspect } | ||
| 39 | if ($PresentScale) { Set-Default "LEONIDA_PRESENT_SCALE" $PresentScale } | ||
| 40 | Set-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). | ||
| 43 | Set-Default "LEONIDA_SKIP_INT3" "1" | ||
| 44 | $tables = Join-Path $repo "d3d12\crates\leonida-formats\src\bcpack-tables.bin" | ||
| 45 | if (Test-Path $tables) { Set-Default "LEONIDA_BCPACK_TABLES" $tables } | ||
| 46 | |||
| 47 | $logs = Join-Path $Work "logs" | ||
| 48 | New-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")`"") | ||
| 53 | if ($Trace) { Write-Host "trace: $(Join-Path $logs "trace-$stamp.jsonl")" } | ||
| 54 | Write-Host "Leonida: $title" | ||
| 55 | Write-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() | ||
| 59 | Write-Host ("exit code 0x{0:X8}" -f $process.ExitCode) | ||
diff --git a/scripts/red_green.py b/scripts/red_green.py new file mode 100644 index 000000000..1af2fd167 --- /dev/null +++ b/scripts/red_green.py | |||
| @@ -0,0 +1,487 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Checks a pull request red and green on this machine (docs/testing.md, "Red and green on your machine"). | ||
| 3 | |||
| 4 | python -I scripts/red_green.py <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch] | ||
| 5 | [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] | ||
| 6 | |||
| 7 | Green is the base (`<remote>/main` after a fetch, by default) with the pull request merged. Red is the base with | ||
| 8 | only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it | ||
| 9 | pass; a test that passes on both proves nothing about the change. | ||
| 10 | |||
| 11 | The red side comes from the pull request's diff against its merge base with the base: | ||
| 12 | - test files, whole: a file under a `tests` folder (`tests/**`, a crate's `tests/`, `src/tests/`), `*_tests.rs`, | ||
| 13 | `tests.rs`; | ||
| 14 | - in other Rust files, the hunks that change only `#[cfg(test)]` items (a `#[cfg(test)] mod x { ... }` block, a | ||
| 15 | `#[cfg(test)] mod x_tests;` line, a `#[cfg(test)]` function), blank lines and comments around them allowed. | ||
| 16 | That change is committed on the merge base, then cherry-picked onto the base. A conflict, or a pull request with no | ||
| 17 | test, is "red not constructible". | ||
| 18 | |||
| 19 | It runs `cargo test --no-fail-fast` for the D3D12 crates the pull request touches (from `d3d12/`, so the pinned | ||
| 20 | toolchain applies) and the changed `tests/**/test*.py` files with unittest, on both sides, in one worktree and one | ||
| 21 | cargo target dir under --work-dir (default `<git common dir>/red-green`), red first. It keeps both between runs: the | ||
| 22 | second run on the same crates builds only what changed. C++ `runtime/` tests are not run here (docs/testing.md has | ||
| 23 | the fork-CI way). | ||
| 24 | |||
| 25 | Exit 0: at least one test went from red to green and no test that passes on red fails on green. 1: any other | ||
| 26 | verdict. 2: a usage or git error. | ||
| 27 | """ | ||
| 28 | from __future__ import annotations | ||
| 29 | |||
| 30 | import argparse | ||
| 31 | import json | ||
| 32 | import os | ||
| 33 | import re | ||
| 34 | import subprocess | ||
| 35 | import sys | ||
| 36 | import tempfile | ||
| 37 | from pathlib import Path | ||
| 38 | |||
| 39 | IDENTITY = { | ||
| 40 | "GIT_AUTHOR_NAME": "red_green", "GIT_AUTHOR_EMAIL": "red_green@localhost", | ||
| 41 | "GIT_COMMITTER_NAME": "red_green", "GIT_COMMITTER_EMAIL": "red_green@localhost", | ||
| 42 | } | ||
| 43 | |||
| 44 | |||
| 45 | class Failure(Exception): | ||
| 46 | """A usage or git error: the command exits 2 with its message.""" | ||
| 47 | |||
| 48 | |||
| 49 | def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None = None) -> subprocess.CompletedProcess: | ||
| 50 | return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) | ||
| 51 | |||
| 52 | |||
| 53 | def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: | ||
| 54 | r = run(["git", *args], cwd, env, data) | ||
| 55 | if check and r.returncode != 0: | ||
| 56 | why = (r.stderr or r.stdout).decode("utf-8", "replace").strip().splitlines() | ||
| 57 | raise Failure(f"git {' '.join(args)}: {why[-1] if why else 'exit ' + str(r.returncode)}") | ||
| 58 | return r.stdout.decode("utf-8", "replace").strip() | ||
| 59 | |||
| 60 | |||
| 61 | def blob(cwd: Path, rev: str, path: str) -> bytes | None: | ||
| 62 | r = run(["git", "cat-file", "blob", f"{rev}:{path}"], cwd) | ||
| 63 | return r.stdout if r.returncode == 0 else None | ||
| 64 | |||
| 65 | |||
| 66 | def lines_of(data: bytes) -> list[bytes]: | ||
| 67 | """Lines as git counts them (on \\n only), each with its end.""" | ||
| 68 | parts = data.split(b"\n") | ||
| 69 | out = [p + b"\n" for p in parts[:-1]] | ||
| 70 | if parts[-1]: | ||
| 71 | out.append(parts[-1]) | ||
| 72 | return out | ||
| 73 | |||
| 74 | |||
| 75 | # --- which files and hunks are tests --------------------------------------------------------------------------- | ||
| 76 | |||
| 77 | def is_test_file(path: str) -> bool: | ||
| 78 | parts = path.split("/") | ||
| 79 | return "tests" in parts[:-1] or parts[-1].endswith("_tests.rs") or parts[-1] == "tests.rs" | ||
| 80 | |||
| 81 | |||
| 82 | CFG = re.compile(r"^\s*#\[cfg\((.*)\)\]\s*$") | ||
| 83 | RAW_OPEN = re.compile(r'b?r(#*)"') | ||
| 84 | CHAR = re.compile(r"b?'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F]+\}|.)|[^\\'])'") | ||
| 85 | |||
| 86 | |||
| 87 | def is_test_cfg(expr: str) -> bool: | ||
| 88 | expr = expr.replace(" ", "") | ||
| 89 | if "not(test" in expr: | ||
| 90 | return False | ||
| 91 | return expr == "test" or (expr.startswith("all(") and re.search(r"[(,]test[,)]", expr) is not None) | ||
| 92 | |||
| 93 | |||
| 94 | def item_end(lines: list[str], start: int) -> int | None: | ||
| 95 | """The last line of the Rust item that starts at `start`: its `;` before any brace, or its closing brace.""" | ||
| 96 | depth, opened, state = 0, False, None | ||
| 97 | for i in range(start, len(lines)): | ||
| 98 | s, k = lines[i], 0 | ||
| 99 | while k < len(s): | ||
| 100 | c = s[k] | ||
| 101 | if state == "str": | ||
| 102 | if c == "\\": | ||
| 103 | k += 2 | ||
| 104 | continue | ||
| 105 | if c == '"': | ||
| 106 | state = None | ||
| 107 | elif isinstance(state, int): # a raw string with `state` hashes | ||
| 108 | close = '"' + "#" * state | ||
| 109 | if s.startswith(close, k): | ||
| 110 | state, k = None, k + len(close) | ||
| 111 | continue | ||
| 112 | elif state == "comment": | ||
| 113 | if s.startswith("*/", k): | ||
| 114 | state, k = None, k + 2 | ||
| 115 | continue | ||
| 116 | else: | ||
| 117 | if s.startswith("//", k): | ||
| 118 | break | ||
| 119 | if s.startswith("/*", k): | ||
| 120 | state, k = "comment", k + 2 | ||
| 121 | continue | ||
| 122 | m = RAW_OPEN.match(s, k) | ||
| 123 | if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): | ||
| 124 | state, k = len(m.group(1)), m.end() | ||
| 125 | continue | ||
| 126 | m = CHAR.match(s, k) | ||
| 127 | if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): | ||
| 128 | k = m.end() | ||
| 129 | continue | ||
| 130 | if c == '"': | ||
| 131 | state = "str" | ||
| 132 | elif c == "{": | ||
| 133 | depth, opened = depth + 1, True | ||
| 134 | elif c == "}": | ||
| 135 | depth -= 1 | ||
| 136 | if opened and depth == 0: | ||
| 137 | return i | ||
| 138 | elif c == ";" and not opened and depth == 0: | ||
| 139 | return i | ||
| 140 | k += 1 | ||
| 141 | return None | ||
| 142 | |||
| 143 | |||
| 144 | def test_lines(data: bytes) -> set[int]: | ||
| 145 | """0-based indexes of the lines that belong to `#[cfg(test)]` items.""" | ||
| 146 | lines = [line.decode("utf-8", "replace") for line in lines_of(data)] | ||
| 147 | out: set[int] = set() | ||
| 148 | i = 0 | ||
| 149 | while i < len(lines): | ||
| 150 | m = CFG.match(lines[i]) | ||
| 151 | if m and is_test_cfg(m.group(1)): | ||
| 152 | j = i + 1 | ||
| 153 | while j < len(lines) and (not lines[j].strip() or lines[j].lstrip().startswith(("#[", "//"))): | ||
| 154 | j += 1 | ||
| 155 | end = item_end(lines, j) if j < len(lines) else None | ||
| 156 | if end is not None: | ||
| 157 | out.update(range(i, end + 1)) | ||
| 158 | i = end + 1 | ||
| 159 | continue | ||
| 160 | i += 1 | ||
| 161 | return out | ||
| 162 | |||
| 163 | |||
| 164 | def neutral(line: bytes) -> bool: | ||
| 165 | text = line.decode("utf-8", "replace").strip() | ||
| 166 | return not text or text.startswith("//") | ||
| 167 | |||
| 168 | |||
| 169 | HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") | ||
| 170 | |||
| 171 | |||
| 172 | def hunks(diff: str) -> list[tuple[int, int, int, int]]: | ||
| 173 | out = [] | ||
| 174 | for line in diff.splitlines(): | ||
| 175 | m = HUNK.match(line) | ||
| 176 | if m: | ||
| 177 | a, b, c, d = m.group(1), m.group(2), m.group(3), m.group(4) | ||
| 178 | out.append((int(a), 1 if b is None else int(b), int(c), 1 if d is None else int(d))) | ||
| 179 | return out | ||
| 180 | |||
| 181 | |||
| 182 | def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: | ||
| 183 | """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" | ||
| 184 | old_lines, new_lines = lines_of(old), lines_of(new) | ||
| 185 | old_tests, new_tests = test_lines(old), test_lines(new) | ||
| 186 | keep = [] | ||
| 187 | for a, b, c, d in hunks(diff): | ||
| 188 | removed = range(a - 1, a - 1 + b) | ||
| 189 | added = range(c - 1, c - 1 + d) | ||
| 190 | lines = [(i in old_tests, old_lines[i]) for i in removed] + [(i in new_tests, new_lines[i]) for i in added] | ||
| 191 | if lines and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines): | ||
| 192 | keep.append((a, b, c, d)) | ||
| 193 | if not keep: | ||
| 194 | return None | ||
| 195 | out = list(old_lines) | ||
| 196 | for a, b, c, d in sorted(keep, reverse=True): | ||
| 197 | at = a if b == 0 else a - 1 | ||
| 198 | out[at:at + b] = new_lines[c - 1:c - 1 + d] | ||
| 199 | return b"".join(out) | ||
| 200 | |||
| 201 | |||
| 202 | # --- the two sides ------------------------------------------------------------------------------------------------ | ||
| 203 | |||
| 204 | def red_commit(repo: Path, merge_base: str, head: str) -> tuple[str | None, list[str]]: | ||
| 205 | """A commit on the merge base with only the pull request's tests, and the files it takes them from.""" | ||
| 206 | changed = git(repo, "diff", "--name-status", "--no-renames", "-z", merge_base, head).split("\0") | ||
| 207 | pairs = [(changed[i], changed[i + 1]) for i in range(0, len(changed) - 1, 2)] | ||
| 208 | plan: list[tuple[str, tuple[str, bytes] | None]] = [] | ||
| 209 | for status, path in pairs: | ||
| 210 | if is_test_file(path): | ||
| 211 | if status == "D": | ||
| 212 | plan.append((path, None)) | ||
| 213 | continue | ||
| 214 | mode = git(repo, "ls-tree", head, "--", path).split(" ", 1)[0] | ||
| 215 | plan.append((path, (mode, blob(repo, head, path) or b""))) | ||
| 216 | elif path.endswith(".rs") and status == "M": | ||
| 217 | diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path) | ||
| 218 | merged = test_hunks(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff) | ||
| 219 | if merged is not None: | ||
| 220 | mode = git(repo, "ls-tree", merge_base, "--", path).split(" ", 1)[0] | ||
| 221 | plan.append((path, (mode, merged))) | ||
| 222 | if not plan: | ||
| 223 | return None, [] | ||
| 224 | with tempfile.TemporaryDirectory(prefix="red-green-index-") as tmp: | ||
| 225 | env = dict(os.environ, GIT_INDEX_FILE=str(Path(tmp) / "index"), **IDENTITY) | ||
| 226 | git(repo, "read-tree", merge_base, env=env) | ||
| 227 | for path, change in plan: | ||
| 228 | if change is None: | ||
| 229 | git(repo, "update-index", "--force-remove", "--", path, env=env) | ||
| 230 | else: | ||
| 231 | mode, data = change | ||
| 232 | sha = git(repo, "hash-object", "-w", "--stdin", data=data) | ||
| 233 | git(repo, "update-index", "--add", "--cacheinfo", f"{mode},{sha},{path}", env=env) | ||
| 234 | tree = git(repo, "write-tree", env=env) | ||
| 235 | commit = git(repo, "commit-tree", tree, "-p", merge_base, "-m", f"red_green: the tests of {head[:12]} only", | ||
| 236 | env=env) | ||
| 237 | return commit, [path for path, _ in plan] | ||
| 238 | |||
| 239 | |||
| 240 | def checkout(repo: Path, tree: Path, base: str) -> None: | ||
| 241 | if not (tree / ".git").exists(): | ||
| 242 | git(repo, "worktree", "add", "--detach", "--force", str(tree), base) | ||
| 243 | return | ||
| 244 | git(tree, "cherry-pick", "--quit", check=False) | ||
| 245 | git(tree, "merge", "--quit", check=False) | ||
| 246 | git(tree, "reset", "--hard", "-q") | ||
| 247 | git(tree, "clean", "-fdq") | ||
| 248 | git(tree, "checkout", "--detach", "--force", "-q", base) | ||
| 249 | |||
| 250 | |||
| 251 | def conflicts(tree: Path) -> list[str]: | ||
| 252 | return [p for p in git(tree, "diff", "--name-only", "--diff-filter=U").splitlines() if p] | ||
| 253 | |||
| 254 | |||
| 255 | # --- running the tests -------------------------------------------------------------------------------------------- | ||
| 256 | |||
| 257 | UNIT = re.compile(r"^\s*(?:Running\s.*?([\w-]+?)-[0-9a-f]{16}(?:\.exe)?\)|Doc-tests\s+(\S+))\s*$") | ||
| 258 | CARGO_TEST = re.compile(r"^test (.+?) \.\.\. (ok|FAILED|ignored)\b") | ||
| 259 | CARGO_ERROR = re.compile(r"^error(?:\[E\d+\])?: ") | ||
| 260 | |||
| 261 | |||
| 262 | def crates_of(tree: Path, paths: list[str]) -> list[str]: | ||
| 263 | names = [] | ||
| 264 | for path in paths: | ||
| 265 | parts = path.split("/") | ||
| 266 | if len(parts) > 3 and parts[0] == "d3d12" and parts[1] in ("crates", "apps"): | ||
| 267 | manifest = tree / "d3d12" / parts[1] / parts[2] / "Cargo.toml" | ||
| 268 | if manifest.is_file(): | ||
| 269 | m = re.search(r'^\s*name\s*=\s*"([^"]+)"', manifest.read_text(encoding="utf-8"), re.M) | ||
| 270 | if m and m.group(1) not in names: | ||
| 271 | names.append(m.group(1)) | ||
| 272 | return names | ||
| 273 | |||
| 274 | |||
| 275 | def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: | ||
| 276 | cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] | ||
| 277 | cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] | ||
| 278 | env = dict(os.environ, CARGO_TARGET_DIR=str(target)) | ||
| 279 | r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | ||
| 280 | out = r.stdout.decode("utf-8", "replace") | ||
| 281 | tests, unit, error = {}, "?", None | ||
| 282 | for line in out.splitlines(): | ||
| 283 | m = UNIT.match(line) | ||
| 284 | if m: | ||
| 285 | unit = m.group(1) or "doc:" + m.group(2) | ||
| 286 | continue | ||
| 287 | m = CARGO_TEST.match(line) | ||
| 288 | if m: | ||
| 289 | tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] | ||
| 290 | elif error is None and CARGO_ERROR.match(line): | ||
| 291 | error = line.strip() | ||
| 292 | no_build = r.returncode != 0 and not tests | ||
| 293 | return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build else None} | ||
| 294 | |||
| 295 | |||
| 296 | PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|skipped|expected failure|unexpected success)", | ||
| 297 | re.M) | ||
| 298 | |||
| 299 | |||
| 300 | def python_tests(tree: Path, files: list[str]) -> dict: | ||
| 301 | tests, no_build = {}, [] | ||
| 302 | for f in files: | ||
| 303 | start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) | ||
| 304 | r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], | ||
| 305 | cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | ||
| 306 | out = r.stdout.decode("utf-8", "replace") | ||
| 307 | found = 0 | ||
| 308 | for name, where, status in PY_TEST.findall(out): | ||
| 309 | if "_FailedTest" in where: | ||
| 310 | no_build.append(f"{f}: does not import") | ||
| 311 | continue | ||
| 312 | key = where if where.endswith("." + name) else f"{where}.{name}" | ||
| 313 | tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") | ||
| 314 | found += 1 | ||
| 315 | if not found and r.returncode != 0 and f"{f}: does not import" not in no_build: | ||
| 316 | no_build.append(f"{f}: exit {r.returncode}") | ||
| 317 | return {"tests": tests, "no_build": "; ".join(no_build) or None} | ||
| 318 | |||
| 319 | |||
| 320 | def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: | ||
| 321 | result = {"tests": {}, "no_build": []} | ||
| 322 | for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ | ||
| 323 | ([python_tests(tree, py_files)] if py_files else []): | ||
| 324 | result["tests"].update(part["tests"]) | ||
| 325 | if part["no_build"]: | ||
| 326 | result["no_build"].append(part["no_build"]) | ||
| 327 | return result | ||
| 328 | |||
| 329 | |||
| 330 | # --- reading the two sides ---------------------------------------------------------------------------------------- | ||
| 331 | |||
| 332 | def compare(red: dict | None, green: dict | None) -> dict: | ||
| 333 | r = red["tests"] if red else {} | ||
| 334 | g = green["tests"] if green else {} | ||
| 335 | rows = {"red_to_green": [], "regressions": [], "fail_on_both": [], "only_on_green": [], "only_on_red": []} | ||
| 336 | both_ok = 0 | ||
| 337 | for key in sorted(set(r) | set(g)): | ||
| 338 | a, b = r.get(key), g.get(key) | ||
| 339 | if a == "failed" and b == "ok": | ||
| 340 | rows["red_to_green"].append(key) | ||
| 341 | elif a == "ok" and b == "failed": | ||
| 342 | rows["regressions"].append(key) | ||
| 343 | elif a == "failed" and b == "failed": | ||
| 344 | rows["fail_on_both"].append(key) | ||
| 345 | elif a is None and b is not None: | ||
| 346 | rows["only_on_green"].append(f"{key} ({b})") | ||
| 347 | elif b is None and a is not None: | ||
| 348 | rows["only_on_red"].append(f"{key} ({a})") | ||
| 349 | elif a == "ok" and b == "ok": | ||
| 350 | both_ok += 1 | ||
| 351 | rows["pass_on_both"] = both_ok | ||
| 352 | return rows | ||
| 353 | |||
| 354 | |||
| 355 | def verdict(red_why: str | None, green_why: str | None, red: dict | None, green: dict | None, rows: dict) -> str: | ||
| 356 | if green_why: | ||
| 357 | return "green not constructible" | ||
| 358 | green_failed = rows["regressions"] or any(r.endswith("(failed)") for r in rows["only_on_green"]) | ||
| 359 | if green and green["no_build"] or green_failed: | ||
| 360 | return "green fails" | ||
| 361 | if red_why: | ||
| 362 | return "red not constructible" | ||
| 363 | if not (red and red["tests"]) and not (green and green["tests"]): | ||
| 364 | return "no tests ran" | ||
| 365 | if rows["red_to_green"]: | ||
| 366 | return "red then green" | ||
| 367 | if red and red["no_build"] and rows["only_on_green"]: | ||
| 368 | return "red does not build" | ||
| 369 | return "no red" | ||
| 370 | |||
| 371 | |||
| 372 | def report(r: dict) -> str: | ||
| 373 | out = [f"base {r['base']} {r['base_commit'][:9]}, head {r['head']} {r['head_commit'][:9]}, " | ||
| 374 | f"merge base {r['merge_base'][:9]}"] | ||
| 375 | out.append("red: " + (r["red_why"] or "the base plus the tests of " + ", ".join(r["red_files"]))) | ||
| 376 | out.append("green: " + (r["green_why"] or "the base with the pull request merged")) | ||
| 377 | out.append("ran: " + ", ".join([f"cargo -p {c}" for c in r["crates"]] + r["python_files"] or ["nothing"])) | ||
| 378 | for name in ("red", "green"): | ||
| 379 | s = r[name] | ||
| 380 | if s and s["no_build"]: | ||
| 381 | out.append(f"{name} does not build: " + "; ".join(s["no_build"])) | ||
| 382 | rows = r["rows"] | ||
| 383 | labels = {"red_to_green": "red then green", "regressions": "pass on red, FAIL on green", | ||
| 384 | "fail_on_both": "fail on both (failing on the base too?)", "only_on_green": "only on green", | ||
| 385 | "only_on_red": "only on red"} | ||
| 386 | for key, label in labels.items(): | ||
| 387 | if rows[key]: | ||
| 388 | out.append(f"{label} ({len(rows[key])}):") | ||
| 389 | out += [f" {t}" for t in rows[key][:40]] | ||
| 390 | if len(rows[key]) > 40: | ||
| 391 | out.append(f" ... {len(rows[key]) - 40} more") | ||
| 392 | out.append(f"pass on both: {rows['pass_on_both']}") | ||
| 393 | out.append(f"verdict: {r['verdict']}") | ||
| 394 | return "\n".join(out) | ||
| 395 | |||
| 396 | |||
| 397 | def main(argv: list[str] | None = None) -> int: | ||
| 398 | p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | ||
| 399 | p.add_argument("pr", help="a pull request number (fetched from --remote) or a git ref") | ||
| 400 | p.add_argument("--base", help="the base to test on (default <remote>/main, fetched)") | ||
| 401 | p.add_argument("--remote", default="origin", help="where main and pull requests are fetched from (origin)") | ||
| 402 | p.add_argument("--no-fetch", action="store_true", help="use the refs as they are") | ||
| 403 | p.add_argument("--work-dir", type=Path, help="the worktree and cargo target dir (<git common dir>/red-green)") | ||
| 404 | p.add_argument("--crate", action="append", default=[], help="a cargo package to test as well (repeatable)") | ||
| 405 | p.add_argument("--no-cargo", action="store_true", help="skip the cargo tests") | ||
| 406 | p.add_argument("--no-python", action="store_true", help="skip the Python tests") | ||
| 407 | p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") | ||
| 408 | p.add_argument("--json", action="store_true", help="print the result as JSON") | ||
| 409 | a = p.parse_args(argv) | ||
| 410 | try: | ||
| 411 | repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) | ||
| 412 | common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) | ||
| 413 | base = a.base or f"{a.remote}/main" | ||
| 414 | if not a.no_fetch: | ||
| 415 | if not a.base: | ||
| 416 | git(repo, "fetch", "-q", a.remote, "main") | ||
| 417 | if a.pr.isdigit(): | ||
| 418 | git(repo, "fetch", "-q", a.remote, f"pull/{a.pr}/head") | ||
| 419 | head = git(repo, "rev-parse", "FETCH_HEAD" if a.pr.isdigit() and not a.no_fetch else a.pr + "^{commit}") | ||
| 420 | base_commit = git(repo, "rev-parse", base + "^{commit}") | ||
| 421 | merge_base = git(repo, "merge-base", base_commit, head) | ||
| 422 | work = (a.work_dir or common / "red-green").resolve() | ||
| 423 | work.mkdir(parents=True, exist_ok=True) | ||
| 424 | lock = work / "lock" | ||
| 425 | try: | ||
| 426 | fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY) | ||
| 427 | except FileExistsError: | ||
| 428 | raise Failure(f"{lock} exists: another run is going, or delete it if none is") from None | ||
| 429 | os.write(fd, str(os.getpid()).encode()) | ||
| 430 | os.close(fd) | ||
| 431 | try: | ||
| 432 | result = check(repo, work, a, base, base_commit, head, merge_base) | ||
| 433 | finally: | ||
| 434 | lock.unlink(missing_ok=True) | ||
| 435 | except Failure as e: | ||
| 436 | print(f"red_green: {e}", file=sys.stderr) | ||
| 437 | return 2 | ||
| 438 | print(json.dumps(result, indent=1) if a.json else report(result)) | ||
| 439 | return 0 if result["verdict"] == "red then green" else 1 | ||
| 440 | |||
| 441 | |||
| 442 | def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, merge_base: str) -> dict: | ||
| 443 | tree, target = work / "tree", work / "target" | ||
| 444 | changed = [p for p in git(repo, "diff", "--name-only", "--no-renames", merge_base, head).splitlines() if p] | ||
| 445 | checkout(repo, tree, base_commit) | ||
| 446 | crates = [] if a.no_cargo else crates_of(tree, changed) + [c for c in a.crate if c not in crates_of(tree, changed)] | ||
| 447 | py_files = [] if a.no_python else [ | ||
| 448 | f for f in changed if f.startswith("tests/") and re.fullmatch(r"test\w*\.py", f.rsplit("/", 1)[-1])] | ||
| 449 | env = dict(os.environ, **IDENTITY) | ||
| 450 | |||
| 451 | red, red_why = None, None | ||
| 452 | commit, red_files = red_commit(repo, merge_base, head) | ||
| 453 | if commit is None: | ||
| 454 | red_why = "not constructible: the pull request changes no test" | ||
| 455 | else: | ||
| 456 | git(tree, "cherry-pick", "--no-commit", commit, env=env, check=False) | ||
| 457 | stuck = conflicts(tree) | ||
| 458 | if stuck: | ||
| 459 | red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) | ||
| 460 | else: | ||
| 461 | print("red_green: red side...", file=sys.stderr) | ||
| 462 | red = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) | ||
| 463 | |||
| 464 | green, green_why = None, None | ||
| 465 | checkout(repo, tree, base_commit) | ||
| 466 | git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) | ||
| 467 | stuck = conflicts(tree) | ||
| 468 | if stuck: | ||
| 469 | green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) | ||
| 470 | else: | ||
| 471 | print("red_green: green side...", file=sys.stderr) | ||
| 472 | green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) | ||
| 473 | checkout(repo, tree, base_commit) | ||
| 474 | |||
| 475 | rows = compare(red, green) | ||
| 476 | return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, | ||
| 477 | "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, | ||
| 478 | "python_files": py_files, "red": red, "green": green, "rows": rows, | ||
| 479 | "verdict": verdict(red_why, green_why, red, green, rows)} | ||
| 480 | |||
| 481 | |||
| 482 | if __name__ == "__main__": | ||
| 483 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 484 | sys.stdout.reconfigure(errors="replace") | ||
| 485 | except (AttributeError, ValueError, OSError): | ||
| 486 | pass | ||
| 487 | sys.exit(main()) | ||
diff --git a/scripts/run_address_guard_gpu_test.py b/scripts/run_address_guard_gpu_test.py new file mode 100644 index 000000000..c61b34704 --- /dev/null +++ b/scripts/run_address_guard_gpu_test.py | |||
| @@ -0,0 +1,137 @@ | |||
| 1 | """GPU test of the address guard (rdna2spirv.py --address-guard; docs/d3d12_vulkan.md, "Address guard"). | ||
| 2 | |||
| 3 | Assembles runtime/test/shaders/cs_address_guard.asm, translates it with --address-guard and runs it with | ||
| 4 | vk_compute_test twice on a 2 MiB heap: once with the guard's header (the page table backs the arena and the page at | ||
| 5 | 0x90000), once without its magic (the guard off). Every address the program uses is inside the heap's buffer, so | ||
| 6 | neither run can fault, whatever the guard does: the guard-on run shows that the refused accesses read 0 and left | ||
| 7 | memory alone although memory was there, and the guard-off run that the same module then reads it. | ||
| 8 | |||
| 9 | python -I scripts/run_address_guard_gpu_test.py --build runtime/build [--llvm-mc CMD] [--work DIR] | ||
| 10 | |||
| 11 | Pin the GPU (MESA_VK_DEVICE_SELECT, VK_DRIVER_FILES) as for scripts/run_gpu_tests.py. Exit 0 when both runs give | ||
| 12 | the expected words, 1 otherwise, 77 when vk_compute_test or llvm-mc is missing. | ||
| 13 | """ | ||
| 14 | import argparse | ||
| 15 | import os | ||
| 16 | import shutil | ||
| 17 | import struct | ||
| 18 | import subprocess | ||
| 19 | import sys | ||
| 20 | import tempfile | ||
| 21 | |||
| 22 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 23 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 24 | import address_guard as ag # noqa: E402 | ||
| 25 | |||
| 26 | NAME = "cs_address_guard" | ||
| 27 | HEAP_BYTES = 2 << 20 | ||
| 28 | LIMIT = ag.RESERVED_END # the "arena": offsets below it pass without a lookup | ||
| 29 | TABLE = 0x100000 # the page table, inside the buffer but past the arena | ||
| 30 | BACKED = [(0x90000, 0x91000)] # the one page outside the arena the table backs | ||
| 31 | SEEDS = {0x90000: 0xA11CE000, 0x90004: 0xA11CE004, 0x90FFC: 0xF00DF00D, 0x91000: 0xF00DF00E, | ||
| 32 | 0xA0000: 0xBADBAD00, 0xA0004: 0xBADBAD04, 0xA0008: 0xBADBAD08} | ||
| 33 | # out[0..7] (cs_address_guard.asm's header) and other words after the run. | ||
| 34 | EXPECTED_ON = [0xA11CE000, 0, 0, 0, 0, 0, 0xA11CE004, 0] | ||
| 35 | EXPECTED_OFF = [0xA11CE000, 0xBADBAD00, 0xBADBAD08, 0xF00DF00D, 0xF00DF00E, 0xBADBAD00, 0xA11CE004, 0xBADBAD00] | ||
| 36 | MEMORY_ON = {0xA0004: 0xBADBAD04, 0xA0008: 0xBADBAD08, # untouched | ||
| 37 | ag.DUMP + 4: 0x5707, ag.DUMP + 8: 1, # where the refused store and atomic went | ||
| 38 | ag.HEADER + 24: 6, # six refused accesses | ||
| 39 | ag.HEADER + 32: 0xA0000, ag.HEADER + 36: 0} # the last one, the s_load at 0xa0000 | ||
| 40 | MEMORY_OFF = {0xA0004: 0x5707, 0xA0008: 0xBADBAD09, ag.DUMP + 4: 0, ag.HEADER + 24: 0} | ||
| 41 | |||
| 42 | |||
| 43 | def heap(guard_on): | ||
| 44 | """The heap's bytes: header (without the magic when not `guard_on`), seeds and page table; zero elsewhere.""" | ||
| 45 | words = ag.table_words(BACKED) | ||
| 46 | end = TABLE + 4 * len(words) | ||
| 47 | assert end <= HEAP_BYTES | ||
| 48 | buf = bytearray(end) | ||
| 49 | hdr = bytearray(ag.header(LIMIT, TABLE)) | ||
| 50 | if not guard_on: | ||
| 51 | hdr[0:8] = bytes(8) | ||
| 52 | buf[ag.HEADER:ag.HEADER + len(hdr)] = hdr | ||
| 53 | for at, value in SEEDS.items(): | ||
| 54 | struct.pack_into("<I", buf, at, value) | ||
| 55 | struct.pack_into(f"<{len(words)}I", buf, TABLE, *words) | ||
| 56 | return bytes(buf) | ||
| 57 | |||
| 58 | |||
| 59 | def find_tool(build, name): | ||
| 60 | for sub in ("", "RelWithDebInfo", "Release", "Debug"): | ||
| 61 | for ext in ("", ".exe"): | ||
| 62 | path = os.path.join(build, sub, name + ext) | ||
| 63 | if os.path.isfile(path): | ||
| 64 | return path | ||
| 65 | return None | ||
| 66 | |||
| 67 | |||
| 68 | def main(argv=None): | ||
| 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") | ||
| 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) | ||
| 74 | ap.add_argument("--work", default=None, help="keep the intermediate files here") | ||
| 75 | a = ap.parse_args(argv) | ||
| 76 | vk_compute = find_tool(a.build, "vk_compute_test") | ||
| 77 | if not vk_compute: | ||
| 78 | print(f"SKIP: no vk_compute_test under {a.build}") | ||
| 79 | return 77 | ||
| 80 | import mc_command | ||
| 81 | mc = mc_command.mc_command(a.llvm_mc) | ||
| 82 | if not shutil.which(mc[0]): | ||
| 83 | print(f"SKIP: {' '.join(mc)} not found") | ||
| 84 | return 77 | ||
| 85 | sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) | ||
| 86 | sys.path.insert(0, os.path.join(ROOT, "scripts")) | ||
| 87 | from compute_fixture import compute_header | ||
| 88 | import run_gpu_tests | ||
| 89 | work = a.work or tempfile.mkdtemp(prefix="leonida-guard-") | ||
| 90 | asm = os.path.join(ROOT, "runtime", "test", "shaders", NAME + ".asm") | ||
| 91 | for sub in ("disasm", "fssm", "spirv"): | ||
| 92 | os.makedirs(os.path.join(work, sub), exist_ok=True) | ||
| 93 | run_gpu_tests.assemble_to_s(a.llvm_mc, asm, os.path.join(work, "disasm", NAME + ".s"), NAME) | ||
| 94 | with open(os.path.join(work, NAME + ".dxbc"), "wb") as f: | ||
| 95 | f.write(run_gpu_tests.make_dxbc([])) | ||
| 96 | with open(os.path.join(work, "fssm", NAME + ".fssm"), "wb") as f: | ||
| 97 | f.write(compute_header(asm)) | ||
| 98 | spirv = os.path.join(work, "spirv") | ||
| 99 | p = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "rdna2spirv.py"), | ||
| 100 | os.path.join(work, "disasm"), "--out", spirv, "--address-guard"], | ||
| 101 | capture_output=True, text=True) | ||
| 102 | spv = os.path.join(spirv, NAME + ".spv") | ||
| 103 | if p.returncode != 0 or not os.path.isfile(spv): | ||
| 104 | print(p.stdout + p.stderr) | ||
| 105 | print("FAIL: translation") | ||
| 106 | return 1 | ||
| 107 | failures = 0 | ||
| 108 | for guard_on, expected, memory in ((True, EXPECTED_ON, MEMORY_ON), (False, EXPECTED_OFF, MEMORY_OFF)): | ||
| 109 | label = "guard on" if guard_on else "guard off" | ||
| 110 | init, dump = os.path.join(work, f"heap_{label[6:]}.bin"), os.path.join(work, f"dump_{label[6:]}.bin") | ||
| 111 | with open(init, "wb") as f: | ||
| 112 | f.write(heap(guard_on)) | ||
| 113 | env = dict(os.environ, VKC_HEAP_INIT=init, VKC_OUT_WORDS=str(HEAP_BYTES // 4), VKC_DUMP=dump) | ||
| 114 | r = subprocess.run([vk_compute, spv, "1", "dump"], capture_output=True, text=True, env=env, timeout=120) | ||
| 115 | if r.returncode != 0 or not os.path.isfile(dump): | ||
| 116 | print(f"FAIL ({label}): vk_compute_test exit {r.returncode}\n{r.stdout}{r.stderr}") | ||
| 117 | failures += 1 | ||
| 118 | continue | ||
| 119 | with open(dump, "rb") as f: | ||
| 120 | data = f.read() | ||
| 121 | word = lambda at: struct.unpack_from("<I", data, at)[0] # noqa: E731 | ||
| 122 | got = [word(4 * k) for k in range(8)] | ||
| 123 | bad = [f"out[{k}] = {g:#x}, want {w:#x}" for k, (g, w) in enumerate(zip(got, expected)) if g != w] | ||
| 124 | bad += [f"[{at:#x}] = {word(at):#x}, want {w:#x}" for at, w in memory.items() if word(at) != w] | ||
| 125 | print(f"{'PASS' if not bad else 'FAIL'} ({label}): out = {' '.join(f'{g:#x}' for g in got)}") | ||
| 126 | for line in bad: | ||
| 127 | print(" " + line) | ||
| 128 | failures += bool(bad) | ||
| 129 | return 1 if failures else 0 | ||
| 130 | |||
| 131 | |||
| 132 | if __name__ == "__main__": | ||
| 133 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 134 | sys.stdout.reconfigure(errors="replace") | ||
| 135 | except (AttributeError, ValueError, OSError): | ||
| 136 | pass | ||
| 137 | sys.exit(main()) | ||
diff --git a/scripts/run_game_wine.sh b/scripts/run_game_wine.sh index ce01b0a07..cc60d6767 100755 --- a/scripts/run_game_wine.sh +++ b/scripts/run_game_wine.sh | |||
| @@ -55,11 +55,13 @@ die() { echo "run_game_wine.sh: $*" >&2; exit 2; } | |||
| 55 | 55 | ||
| 56 | if [ "${1:-}" = --inner ]; then | 56 | if [ "${1:-}" = --inner ]; then |
| 57 | # ---- inside the session: DISPLAY is kwin's Xwayland (headless) or the caller's display (--visible) ---- | 57 | # ---- inside the session: DISPLAY is kwin's Xwayland (headless) or the caller's display (--visible) ---- |
| 58 | [ "$#" -ge 5 ] || die "--inner requires RUN BUILD LIMIT SHOT_EVERY" | ||
| 58 | RUN=$2; BUILD=$3; LIMIT=$4; SHOT_EVERY=$5 | 59 | RUN=$2; BUILD=$3; LIMIT=$4; SHOT_EVERY=$5 |
| 59 | shift 5 | 60 | shift 5 |
| 60 | WINE=${WINE:-wine} | 61 | WINE=${WINE:-wine} |
| 61 | WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver | 62 | wine_bin=$(command -v "$WINE" 2>/dev/null || true) |
| 62 | [ -x "$WINESERVER" ] || WINESERVER=wineserver | 63 | WINESERVER=${wine_bin:+$(dirname "$wine_bin")/wineserver} |
| 64 | [ -n "$WINESERVER" ] && [ -x "$WINESERVER" ] || WINESERVER=wineserver | ||
| 63 | unset WAYLAND_DISPLAY # Wine's X11 driver on Xwayland, never its Wayland driver | 65 | unset WAYLAND_DISPLAY # Wine's X11 driver on Xwayland, never its Wayland driver |
| 64 | { | 66 | { |
| 65 | echo "display: ${DISPLAY:-none}" | 67 | echo "display: ${DISPLAY:-none}" |
| @@ -70,7 +72,7 @@ if [ "${1:-}" = --inner ]; then | |||
| 70 | mkdir -p "$WINEPREFIX" | 72 | mkdir -p "$WINEPREFIX" |
| 71 | "$WINESERVER" -p | 73 | "$WINESERVER" -p |
| 72 | # Warm-up: starts the prefix's services; no Mono/Gecko prompts in a new prefix. | 74 | # Warm-up: starts the prefix's services; no Mono/Gecko prompts in a new prefix. |
| 73 | WINEDLLOVERRIDES="$WINEDLLOVERRIDES;mscoree,mshtml=" "$WINE" wineboot -u </dev/null >/dev/null 2>&1 | 75 | WINEDLLOVERRIDES="${WINEDLLOVERRIDES:+$WINEDLLOVERRIDES;}mscoree,mshtml=" "$WINE" wineboot -u </dev/null >/dev/null 2>&1 |
| 74 | SHOTS= | 76 | SHOTS= |
| 75 | if [ "$SHOT_EVERY" != 0 ]; then | 77 | if [ "$SHOT_EVERY" != 0 ]; then |
| 76 | mkdir -p "$RUN/shots" | 78 | mkdir -p "$RUN/shots" |
| @@ -97,7 +99,10 @@ if [ "${1:-}" = --inner ]; then | |||
| 97 | code=$? | 99 | code=$? |
| 98 | echo "$(( $(date +%s) - t0 ))" > "$RUN/seconds" | 100 | echo "$(( $(date +%s) - t0 ))" > "$RUN/seconds" |
| 99 | echo "$code" > "$RUN/exit_code" | 101 | echo "$code" > "$RUN/exit_code" |
| 100 | [ -n "$SHOTS" ] && kill "$SHOTS" 2>/dev/null | 102 | if [ -n "$SHOTS" ]; then |
| 103 | kill "$SHOTS" 2>/dev/null || true | ||
| 104 | wait "$SHOTS" 2>/dev/null || true | ||
| 105 | fi | ||
| 101 | "$WINESERVER" -k 2>/dev/null | 106 | "$WINESERVER" -k 2>/dev/null |
| 102 | exit 0 | 107 | exit 0 |
| 103 | fi | 108 | fi |
| @@ -132,10 +137,11 @@ done | |||
| 132 | [ -n "$OUT" ] || die "--out is required: the run folder" | 137 | [ -n "$OUT" ] || die "--out is required: the run folder" |
| 133 | [ -n "$SHADERS" ] || die "--shaders (or LEONIDA_SHADERS) is required: the translated shader library, or none" | 138 | [ -n "$SHADERS" ] || die "--shaders (or LEONIDA_SHADERS) is required: the translated shader library, or none" |
| 134 | case $LIMIT in ''|*[!0-9]*|0*) die "--seconds must be a whole number of seconds above 0, not '$LIMIT'" ;; esac | 139 | case $LIMIT in ''|*[!0-9]*|0*) die "--seconds must be a whole number of seconds above 0, not '$LIMIT'" ;; esac |
| 135 | case $SHOT_EVERY in ''|*[!0-9]*) die "--screenshot-every must be a whole number of seconds, not '$SHOT_EVERY'" ;; esac | 140 | case $SHOT_EVERY in ''|*[!0-9]*|0?*) die "--screenshot-every must be a whole number of seconds, not '$SHOT_EVERY'" ;; esac |
| 136 | if [ -n "$DEVICE" ] && ! [[ $DEVICE =~ ^[0-9a-fA-F]{4}:[0-9a-fA-F]{4}$ ]]; then | 141 | if [ -n "$DEVICE" ] && ! [[ $DEVICE =~ ^[0-9a-fA-F]{4}:[0-9a-fA-F]{4}$ ]]; then |
| 137 | die "--device takes VID:DID in hex, as lspci -nn prints it (e.g. 1002:744c), not '$DEVICE'" | 142 | die "--device takes VID:DID in hex, as lspci -nn prints it (e.g. 1002:744c), not '$DEVICE'" |
| 138 | fi | 143 | fi |
| 144 | [ -e "$SRC" ] || die "no build path at $SRC" | ||
| 139 | [ -f "$EXE" ] || die "no game executable at $EXE" | 145 | [ -f "$EXE" ] || die "no game executable at $EXE" |
| 140 | [ -d "$GAME" ] || die "no package folder at $GAME" | 146 | [ -d "$GAME" ] || die "no package folder at $GAME" |
| 141 | if [ "$SHADERS" != none ]; then | 147 | if [ "$SHADERS" != none ]; then |
| @@ -195,6 +201,7 @@ fi | |||
| 195 | # ---- one run at a time: a shared prefix has one wineserver ---- | 201 | # ---- one run at a time: a shared prefix has one wineserver ---- |
| 196 | LOCK=${LOCK:-${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/leonida-run-game-wine.lock}} | 202 | LOCK=${LOCK:-${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/leonida-run-game-wine.lock}} |
| 197 | LOCK=${LOCK:-$RUN/run.lock} | 203 | LOCK=${LOCK:-$RUN/run.lock} |
| 204 | mkdir -p "$(dirname "$LOCK")" || die "cannot create lock parent for $LOCK" | ||
| 198 | exec 9>"$LOCK" || die "cannot open the lock $LOCK" | 205 | exec 9>"$LOCK" || die "cannot open the lock $LOCK" |
| 199 | flock -n 9 || die "another run holds $LOCK" | 206 | flock -n 9 || die "another run holds $LOCK" |
| 200 | mkdir -p "$RUN/overlay" "$RUN/saves" | 207 | mkdir -p "$RUN/overlay" "$RUN/saves" |
| @@ -217,11 +224,18 @@ else | |||
| 217 | unset DISPLAY XAUTHORITY | 224 | unset DISPLAY XAUTHORITY |
| 218 | fi | 225 | fi |
| 219 | export QT_QPA_PLATFORM=offscreen | 226 | export QT_QPA_PLATFORM=offscreen |
| 227 | DRM_SYSFS=${LEONIDA_DRM_SYSFS_DIR:-/sys/class/drm} | ||
| 220 | if [ -n "$DEVICE" ]; then | 228 | if [ -n "$DEVICE" ]; then |
| 221 | export MESA_VK_DEVICE_SELECT="$DEVICE!" | 229 | export MESA_VK_DEVICE_SELECT="$DEVICE!" |
| 222 | # kwin and Xwayland's glamor on the card that renders, so the present path stays on one device. | 230 | # kwin and Xwayland's glamor on the card that renders, so the present path stays on one device. |
| 223 | for n in /sys/class/drm/renderD*; do | 231 | lc() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; } # not ${x,,}: macOS's bash 3.2 lacks it |
| 224 | [ "$(cat "$n/device/vendor" 2>/dev/null):$(cat "$n/device/device" 2>/dev/null)" = "0x${DEVICE%%:*}:0x${DEVICE#*:}" ] \ | 232 | dev_lc=$(lc "$DEVICE") |
| 233 | for n in "$DRM_SYSFS"/renderD*; do | ||
| 234 | [ -e "$n" ] || continue | ||
| 235 | ven=$(cat "$n/device/vendor" 2>/dev/null || true) | ||
| 236 | did=$(cat "$n/device/device" 2>/dev/null || true) | ||
| 237 | ven=${ven//$'\r'/}; did=${did//$'\r'/} | ||
| 238 | [ "$(lc "$ven"):$(lc "$did")" = "0x${dev_lc%%:*}:0x${dev_lc#*:}" ] \ | ||
| 225 | && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} | 239 | && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} |
| 226 | done | 240 | done |
| 227 | else | 241 | else |
| @@ -242,8 +256,9 @@ else | |||
| 242 | fi | 256 | fi |
| 243 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" | 257 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" |
| 244 | 258 | ||
| 245 | WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver | 259 | wine_bin=$(command -v "$WINE" 2>/dev/null || true) |
| 246 | [ -x "$WINESERVER" ] || WINESERVER=wineserver | 260 | WINESERVER=${wine_bin:+$(dirname "$wine_bin")/wineserver} |
| 261 | [ -n "$WINESERVER" ] && [ -x "$WINESERVER" ] || WINESERVER=wineserver | ||
| 247 | SESSION_PID= | 262 | SESSION_PID= |
| 248 | teardown() { | 263 | teardown() { |
| 249 | "$WINESERVER" -k 2>/dev/null | 264 | "$WINESERVER" -k 2>/dev/null |
| @@ -257,7 +272,7 @@ trap 'exit 130' INT TERM HUP | |||
| 257 | 272 | ||
| 258 | # The session command with its arguments baked in (kwin takes one program path). | 273 | # The session command with its arguments baked in (kwin takes one program path). |
| 259 | { | 274 | { |
| 260 | echo '#!/bin/sh' | 275 | echo '#!/usr/bin/env bash' |
| 261 | printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" | 276 | printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" |
| 262 | for a in "$@"; do printf ' %q' "$a"; done | 277 | for a in "$@"; do printf ' %q' "$a"; done |
| 263 | echo | 278 | echo |
| @@ -276,10 +291,17 @@ else | |||
| 276 | fi | 291 | fi |
| 277 | SESSION_PID=$! | 292 | SESSION_PID=$! |
| 278 | # The session ends when the inner run returns; this outer limit adds a margin for the start-up. | 293 | # The session ends when the inner run returns; this outer limit adds a margin for the start-up. |
| 279 | ( sleep $((LIMIT + 180)); kill -TERM "$SESSION_PID" 2>/dev/null ) 9>&- 2>/dev/null & | 294 | ( trap 'kill "${watch_sleep_pid:-}" 2>/dev/null || true; exit 0' TERM INT |
| 295 | watch_sleep_pid="" | ||
| 296 | sleep $((LIMIT + 180)) & | ||
| 297 | watch_sleep_pid=$! | ||
| 298 | wait "$watch_sleep_pid" 2>/dev/null || exit 0 | ||
| 299 | kill -TERM "$SESSION_PID" 2>/dev/null ) 9>&- </dev/null >/dev/null 2>&1 & | ||
| 280 | WATCH=$! | 300 | WATCH=$! |
| 281 | wait "$SESSION_PID" | 301 | wait "$SESSION_PID" |
| 282 | pkill -P "$WATCH" 2>/dev/null; kill "$WATCH" 2>/dev/null | 302 | pkill -P "$WATCH" 2>/dev/null || true |
| 303 | kill "$WATCH" 2>/dev/null || true | ||
| 304 | wait "$WATCH" 2>/dev/null || true | ||
| 283 | teardown; SESSION_PID= | 305 | teardown; SESSION_PID= |
| 284 | T1=$(date +%s) | 306 | T1=$(date +%s) |
| 285 | 307 | ||
| @@ -289,5 +311,6 @@ if [ ! -f "$RUN/exit_code" ]; then | |||
| 289 | exit 3 | 311 | exit 3 |
| 290 | fi | 312 | fi |
| 291 | python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" | 313 | python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" |
| 314 | summary_rc=${PIPESTATUS[0]} | ||
| 292 | echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." | 315 | echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." |
| 293 | exit 0 | 316 | exit "$summary_rc" |
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index f87290ec6..7f299b0be 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) |
| 30 | from compute_fixture import compute_header | 30 | from compute_fixture import compute_header |
| 31 | from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) | 31 | from check import SAMPLER_CASES, sampler_test # ps_ssharp: the S#/T# mip fields (vk_sampler_test) |
| 32 | from 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, | 32 | from 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) |
| 35 | from check import SIGNED_MIP_TEST, UINT_MIP_TEST | 35 | from check import SIGNED_MIP_TEST, UINT_MIP_TEST |
| @@ -37,6 +37,7 @@ from check import cbv_modulate_test | |||
| 37 | from check import IMAGE_STORE_CASES, texture_uav_test | 37 | from check import IMAGE_STORE_CASES, texture_uav_test |
| 38 | from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS | 38 | from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS |
| 39 | from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT | 39 | from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT |
| 40 | from check import CVT_F16_MODS_WORDS | ||
| 40 | from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations | 41 | from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations |
| 41 | from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands | 42 | from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands |
| 42 | from check import round_f64_test # the four binary64 roundings on memory-fed inputs | 43 | from check import round_f64_test # the four binary64 roundings on memory-fed inputs |
| @@ -50,11 +51,12 @@ from check import run_readback | |||
| 50 | from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS | 51 | from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS |
| 51 | from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, | 52 | from 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 |
| 53 | from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks | 54 | from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem, exp_f32_denorm_problem # pixel producers and checks |
| 54 | from check import barycentric_problem | 55 | from check import barycentric_problem |
| 55 | from check import NAN_PAYLOAD_TEST, nan_payload_problem | 56 | from check import NAN_PAYLOAD_TEST, nan_payload_problem |
| 56 | from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries | 57 | from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries |
| 57 | from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide | 58 | from check import wide_pixel_skip # ps_w64x_readlane: judged only where the fragment stage was required 64-wide |
| 59 | from check import paravirtual_exp2_skip # ps_exp_f32_denorm_rt: judged only where OpExp2 is exact on 2^-125 | ||
| 58 | from check import FMA_FUSED_ENV, judge_fma_fused # cs_fma_fused: strict under LEONIDA_FMA=khr, fused/split under glsl | 60 | from check import FMA_FUSED_ENV, judge_fma_fused # cs_fma_fused: strict under LEONIDA_FMA=khr, fused/split under glsl |
| 59 | from check import bary_persp_problem # ps_persp_bary's perspective-correct reference | 61 | from check import bary_persp_problem # ps_persp_bary's perspective-correct reference |
| 60 | 62 | ||
| @@ -102,7 +104,7 @@ def make_ms_psv0(threads_x: int, maxv: int, maxp: int, topology: int = 2, group_ | |||
| 102 | TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here" | 104 | TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here" |
| 103 | 105 | ||
| 104 | 106 | ||
| 105 | def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: | 107 | def 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.""" | 108 | """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: | 109 | with open(asm_path, encoding="utf-8") as source: |
| 108 | raw = source.read() | 110 | raw = source.read() |
| @@ -169,7 +171,7 @@ def spirv_as(asm_text: str, out_spv: str, assembler: str = "spirv-as") -> None: | |||
| 169 | return | 171 | return |
| 170 | try: | 172 | try: |
| 171 | p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], | 173 | p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], |
| 172 | input=asm_text, capture_output=True, text=True) | 174 | input=asm_text, capture_output=True, encoding="utf-8", errors="backslashreplace") |
| 173 | except FileNotFoundError: | 175 | except FileNotFoundError: |
| 174 | raise RuntimeError("spirv-as not found on PATH (use --assembler python to assemble with tools/spirv_asm.py)") from None | 176 | raise RuntimeError("spirv-as not found on PATH (use --assembler python to assemble with tools/spirv_asm.py)") from None |
| 175 | except OSError as exc: | 177 | except OSError as exc: |
| @@ -316,13 +318,27 @@ def compute_result(rc: int, msg: str, ok: bool, detail: str) -> tuple[bool | Non | |||
| 316 | return (None, skip) if skip else (ok, detail) | 318 | return (None, skip) if skip else (ok, detail) |
| 317 | 319 | ||
| 318 | 320 | ||
| 321 | def dump_result(rc: int, msg: str, want: list[int]) -> tuple[bool | None, str]: | ||
| 322 | """(ok, detail) for a vk_compute_test "dump" run whose first len(want) words must be exact. A non-zero exit fails | ||
| 323 | with the program's output even when it printed the words: validation errors come with the right words.""" | ||
| 324 | words = dump_words(msg) | ||
| 325 | vals = words[:len(want)] if words else [] | ||
| 326 | if rc != 0: | ||
| 327 | detail = f"exit {rc}: {msg or 'no test output'}" | ||
| 328 | else: | ||
| 329 | detail = " ".join(hex(x) for x in vals) if vals else msg | ||
| 330 | return compute_result(rc, msg, rc == 0 and vals == want, detail) | ||
| 331 | |||
| 332 | |||
| 319 | def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *, | 333 | def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *, |
| 320 | cwd: str | None = None) -> tuple[int, str]: | 334 | 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). | 335 | # 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. | 336 | # gpu=False (the translator over the whole suite) runs without a limit. |
| 323 | limit = gpu_test_timeout() if gpu else None | 337 | limit = gpu_test_timeout() if gpu else None |
| 324 | try: | 338 | try: |
| 325 | p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=limit, cwd=cwd) | 339 | # Keep the exit status and the rest of the log if a tool emits bytes outside the host encoding. |
| 340 | p = subprocess.run(cmd, capture_output=True, text=True, errors="backslashreplace", | ||
| 341 | env=env, timeout=limit, cwd=cwd) | ||
| 326 | except subprocess.TimeoutExpired: | 342 | except subprocess.TimeoutExpired: |
| 327 | return 1, timed_out(cmd[0], limit) | 343 | 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 | 344 | except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others |
| @@ -354,8 +370,15 @@ def f16_interp_fallback() -> bool: | |||
| 354 | return _device_per_vertex() is False | 370 | return _device_per_vertex() is False |
| 355 | 371 | ||
| 356 | 372 | ||
| 373 | def no_ftz32() -> bool: | ||
| 374 | """Translate with --no-ftz32 when tools/vk_subgroup_info.py reports denorm_flush_to_zero_f32: false | ||
| 375 | (drivers such as NVIDIA Vulkan that do not advertise DenormFlushToZero 32).""" | ||
| 376 | return _device_denorm_ftz_f32() is False | ||
| 377 | |||
| 378 | |||
| 357 | _PER_VERTEX = [] | 379 | _PER_VERTEX = [] |
| 358 | _BARYCENTRIC_FALLBACK = [] | 380 | _BARYCENTRIC_FALLBACK = [] |
| 381 | _DENORM_FTZ_F32 = [] | ||
| 359 | 382 | ||
| 360 | 383 | ||
| 361 | def _device_per_vertex(): | 384 | def _device_per_vertex(): |
| @@ -365,7 +388,9 @@ def _device_per_vertex(): | |||
| 365 | try: | 388 | try: |
| 366 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | 389 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], |
| 367 | capture_output=True, text=True, timeout=60) | 390 | capture_output=True, text=True, timeout=60) |
| 368 | answer = json.loads(r.stdout.strip().splitlines()[-1]).get("per_vertex_inputs") | 391 | report = json.loads(r.stdout.strip().splitlines()[-1]) |
| 392 | if isinstance(report, dict): | ||
| 393 | answer = report.get("per_vertex_inputs") | ||
| 369 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | 394 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): |
| 370 | pass | 395 | pass |
| 371 | _PER_VERTEX.append(answer) | 396 | _PER_VERTEX.append(answer) |
| @@ -380,13 +405,31 @@ def _device_barycentric_fallback(): | |||
| 380 | try: | 405 | try: |
| 381 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | 406 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], |
| 382 | capture_output=True, text=True, timeout=60) | 407 | capture_output=True, text=True, timeout=60) |
| 383 | answer = json.loads(r.stdout.strip().splitlines()[-1]).get("barycentric_fallback") | 408 | report = json.loads(r.stdout.strip().splitlines()[-1]) |
| 409 | if isinstance(report, dict): | ||
| 410 | answer = report.get("barycentric_fallback") | ||
| 384 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | 411 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): |
| 385 | pass | 412 | pass |
| 386 | _BARYCENTRIC_FALLBACK.append(answer) | 413 | _BARYCENTRIC_FALLBACK.append(answer) |
| 387 | return _BARYCENTRIC_FALLBACK[0] | 414 | return _BARYCENTRIC_FALLBACK[0] |
| 388 | 415 | ||
| 389 | 416 | ||
| 417 | def _device_denorm_ftz_f32(): | ||
| 418 | """denorm_flush_to_zero_f32 from tools/vk_subgroup_info.py for the device the tests run on (cached), or None.""" | ||
| 419 | if not _DENORM_FTZ_F32: | ||
| 420 | answer = None | ||
| 421 | try: | ||
| 422 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | ||
| 423 | capture_output=True, text=True, timeout=60) | ||
| 424 | report = json.loads(r.stdout.strip().splitlines()[-1]) | ||
| 425 | if isinstance(report, dict) and isinstance(report.get("denorm_flush_to_zero_f32"), bool): | ||
| 426 | answer = report["denorm_flush_to_zero_f32"] | ||
| 427 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | ||
| 428 | pass | ||
| 429 | _DENORM_FTZ_F32.append(answer) | ||
| 430 | return _DENORM_FTZ_F32[0] | ||
| 431 | |||
| 432 | |||
| 390 | def w64_emulated() -> bool: | 433 | def w64_emulated() -> bool: |
| 391 | # Wave64 emulation on: the suite runs every wave64 check without asking for a 64-wide | 434 | # Wave64 emulation on: the suite runs every wave64 check without asking for a 64-wide |
| 392 | # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates | 435 | # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates |
| @@ -432,6 +475,155 @@ def subgroup_pin_skip(msg: str, cs_env: dict | None) -> Skip | None: | |||
| 432 | # report a failure that is really an unpinnable wave size (GCN3/GCN4 expose 64..64 only). | 475 | # report a failure that is really an unpinnable wave size (GCN3/GCN4 expose 64..64 only). |
| 433 | WAVE32_PIN_DUMPS = ("cs_barrier_loop",) | 476 | WAVE32_PIN_DUMPS = ("cs_barrier_loop",) |
| 434 | 477 | ||
| 478 | # Compute dump fixtures (sorted one entry per line to avoid horizontal-tuple merge conflicts). | ||
| 479 | # Adding a fixture edits only CS_DUMP_WANTS (and CS_DUMP_NON_WAVE64 / CS_DUMP_HEXWORDS if applicable). | ||
| 480 | CS_DUMP_WANTS: dict[str, list[int]] = { | ||
| 481 | "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120], | ||
| 482 | "cs_barrier_early_end": [127, 126, 125, 124, 123, 122, 121, 120], | ||
| 483 | "cs_barrier_loop": [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE], | ||
| 484 | "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], | ||
| 485 | "cs_dpp": [1, 0, 3, 2, 5, 4, 7, 6], | ||
| 486 | "cs_dpp8": [7, 6, 5, 4, 3, 2, 1, 0], | ||
| 487 | "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], | ||
| 488 | "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16], | ||
| 489 | "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0], | ||
| 490 | "cs_dpp_cmpx": [1, 1, 0, 0, 3, 3, 2, 2], | ||
| 491 | "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], | ||
| 492 | "cs_dpp_mask": [1, 0, 3, 2, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE], | ||
| 493 | "cs_dpp_ops": [100, 10, 11, 12, 13, 14, 15, 16], | ||
| 494 | "cs_dpp_row": [0, 0, 1, 2, 3, 4, 5, 6], | ||
| 495 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], | ||
| 496 | "cs_exec_const": [16, 8, 2, 16, 0, 16], | ||
| 497 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], | ||
| 498 | "cs_lds_b64_cmpst": [0x11110001, 0x22220002, 0x33330003, 0x44440004, 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC], | ||
| 499 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], | ||
| 500 | "cs_mask_vgpr_exec": [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF], | ||
| 501 | "cs_movrelsd_2": [11, 33, 33, 55, 1717, 77, 1515, 1717], | ||
| 502 | "cs_signed_zero_nan": [0x80000000, 0x80000000, 0x80008000, 0x00008000, 1, 1, 1, 0x00007C00], | ||
| 503 | "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], | ||
| 504 | "cs_smem_vcc_base": CS_SMEM_VCC, | ||
| 505 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], | ||
| 506 | "cs_w32_andn2_exec": [1, 8, 16, 2064, 2068, 3, 20, 1544], | ||
| 507 | "cs_w32_buffer_store_sub": [0x1122AB44, 0xCDEF7788, 0x34AABBCC, 0xDDDDDD12, 0x0102035A, 0x05061234, 0xAB, 0xFFFFCDEF], | ||
| 508 | "cs_w32_buffer_sub16": [0xBEEF00AA, 0x00AA1234, 0xBEEFFFAA, 0xFFAA1234, 0xBEEF8899, 0x88991234, 0x1122CD44, 0xABCD7788], | ||
| 509 | "cs_w32_cvt_f16_mods": CVT_F16_MODS_WORDS, | ||
| 510 | "cs_w32_exec_computed": [259, 1028, 3088, 7682, 512, 4100, 0, 3], | ||
| 511 | "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], | ||
| 512 | "cs_w32_int_ext": [1, 27, 1, 0x33332222, 0xC0000000, 0x4000, 18, 0x20304050], | ||
| 513 | "cs_w32_lane_wrap": [25, 16, 777, 777], | ||
| 514 | "cs_w32_lds_subdword": [0x11B2D444, 0xA1B2C3D4, 0xFFFFFFB2, 0x000000B2, 0x00000011, 0xFFFFA1B2, 0x0000A1B2, 0xFFFFC3D4], | ||
| 515 | "cs_w32_lds_u8_d16": [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234], | ||
| 516 | "cs_w32_lds_wide": [0xCAFEF00D, 0xFEEDFACE, 0x600DD00D, 0x00000000, 0x8BADF00D, 0xDEADC0DE, 0x12345678, 0x9ABCDEF0], | ||
| 517 | "cs_w32_mask_imm": [2056, 20, 2, 6152, 2050, 4112, 258, 32], | ||
| 518 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], | ||
| 519 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], | ||
| 520 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], | ||
| 521 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], | ||
| 522 | "cs_w32_permlane_fi": [1000, 0, 4, 1, 1000, 0, 52, 49], | ||
| 523 | "cs_w32_permute": [218, 29, 8, 211, 0, 15, 99, 15], | ||
| 524 | "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], | ||
| 525 | "cs_w32_sincos": [1, 1, 1, 1, 1, 1], | ||
| 526 | "cs_w32_wrxchg2_ext": [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF, 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678], | ||
| 527 | "cs_w32_wrxchg2st64": [0x33333333, 0x44444444, 0x55550005, 0x66660006, 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0], | ||
| 528 | "cs_w64_exec_computed": [291, 1028, 11264, 771, 8192, 4132, 0, 3], | ||
| 529 | "cs_w64_mask_detect": [48], | ||
| 530 | "cs_w64_mask_imm": [2056, 1084, 828, 2052, 319, 2104, 516, 2064], | ||
| 531 | "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], | ||
| 532 | "cs_w64x_ballot": [2053, 2061, 2069, 2077, 2085, 2093, 2101, 2109], | ||
| 533 | "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], | ||
| 534 | "cs_w64x_branch": [0, 0, 0, 0, 5, 5, 9, 9], | ||
| 535 | "cs_w64x_chain_barrier": [564, 563, 500, 627], | ||
| 536 | "cs_w64x_cmp_sdst": [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5], | ||
| 537 | "cs_w64x_lds_raw": [132, 137, 100, 108, 131, 101, 149, 118], | ||
| 538 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], | ||
| 539 | "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], | ||
| 540 | "cs_w64x_mask_reuse": [8, 40, 8, 40, 2, 20, 10, 64], | ||
| 541 | "cs_w64x_mask_reuse2": [10, 20, 8, 8, 5, 2, 132, 131], | ||
| 542 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], | ||
| 543 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], | ||
| 544 | "cs_w64x_partial_swizzle": [508, 523, 0, 0, 528, 0, 531, 0], | ||
| 545 | "cs_w64x_permute": [218, 442, 435, 239, 0, 99, 239, 232], | ||
| 546 | "cs_w64x_readfirstlane": [140, 140, 163, 132, 100, 105, 133, 48], | ||
| 547 | "cs_w64x_readlane": [121, 121, 16, 97, 16, 100, 100, 121], | ||
| 548 | "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], | ||
| 549 | "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031], | ||
| 550 | "cs_w64x_wg128_branches": [121, 121, 343, 343, 14, 31, 19812, 22728], | ||
| 551 | "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 4660, 99], | ||
| 552 | "cs_wave64_ballot": [32, 16, 24, 40, 8, 48], | ||
| 553 | "cs_wm_bfm64": [16, 8, 8, 40], | ||
| 554 | "cs_wm_half_cmp": [1, 0, 1, 1], | ||
| 555 | "cs_wm_half_ops": [32, 16, 16, 0, 16], | ||
| 556 | "cs_wm_scc_rfl": [55, 48], | ||
| 557 | "cs_wqm_w32": [12, 1, 4, 0, 8, 15728880, 4, 32], | ||
| 558 | "cs_wqm_w64": [20, 4, 12, 8, 1, 0, 15728895, 20], | ||
| 559 | "cs_wqm_w64_half": [11, 14, 0, 1, 6, 8, 12, 2], | ||
| 560 | } | ||
| 561 | |||
| 562 | # Fixtures in CS_DUMP_WANTS that run without --require-wave64 (wave32, scalar, barrier, and DPP tests). | ||
| 563 | CS_DUMP_NON_WAVE64: frozenset[str] = frozenset({ | ||
| 564 | "cs_barrier_divergent", | ||
| 565 | "cs_barrier_early_end", | ||
| 566 | "cs_barrier_loop", | ||
| 567 | "cs_bpermute32", | ||
| 568 | "cs_dpp", | ||
| 569 | "cs_dpp8", | ||
| 570 | "cs_dpp_bank", | ||
| 571 | "cs_dpp_bound", | ||
| 572 | "cs_dpp_cmp", | ||
| 573 | "cs_dpp_cmpx", | ||
| 574 | "cs_dpp_fi", | ||
| 575 | "cs_dpp_mask", | ||
| 576 | "cs_dpp_ops", | ||
| 577 | "cs_dpp_row", | ||
| 578 | "cs_exec_const", | ||
| 579 | "cs_lds_atomics_ext", | ||
| 580 | "cs_lds_b64_cmpst", | ||
| 581 | "cs_lds_xchg64_ext", | ||
| 582 | "cs_mask_vgpr_exec", | ||
| 583 | "cs_movrelsd_2", | ||
| 584 | "cs_signed_zero_nan", | ||
| 585 | "cs_smem_soffset_imm", | ||
| 586 | "cs_store", | ||
| 587 | "cs_w32_andn2_exec", | ||
| 588 | "cs_w32_buffer_store_sub", | ||
| 589 | "cs_w32_buffer_sub16", | ||
| 590 | "cs_w32_cvt_f16_mods", | ||
| 591 | "cs_w32_exec_computed", | ||
| 592 | "cs_w32_fcmpswap", | ||
| 593 | "cs_w32_int_ext", | ||
| 594 | "cs_w32_lane_wrap", | ||
| 595 | "cs_w32_lds_subdword", | ||
| 596 | "cs_w32_lds_u8_d16", | ||
| 597 | "cs_w32_lds_wide", | ||
| 598 | "cs_w32_mask_imm", | ||
| 599 | "cs_w32_misc_ext", | ||
| 600 | "cs_w32_new_ops", | ||
| 601 | "cs_w32_partial_permute", | ||
| 602 | "cs_w32_partial_scmp", | ||
| 603 | "cs_w32_permlane_fi", | ||
| 604 | "cs_w32_permute", | ||
| 605 | "cs_w32_salu64", | ||
| 606 | "cs_w32_sincos", | ||
| 607 | "cs_w32_wrxchg2_ext", | ||
| 608 | "cs_w32_wrxchg2st64", | ||
| 609 | "cs_wqm_w32", | ||
| 610 | }) | ||
| 611 | |||
| 612 | # Fixtures in CS_DUMP_WANTS whose mismatch diagnostics format output words in hex. | ||
| 613 | CS_DUMP_HEXWORDS: frozenset[str] = frozenset({ | ||
| 614 | "cs_lds_atomics_ext", | ||
| 615 | "cs_lds_b64_cmpst", | ||
| 616 | "cs_lds_xchg64_ext", | ||
| 617 | "cs_signed_zero_nan", | ||
| 618 | "cs_smem_soffset_imm", | ||
| 619 | "cs_store", | ||
| 620 | "cs_w32_lds_subdword", | ||
| 621 | "cs_w32_lds_u8_d16", | ||
| 622 | "cs_w32_lds_wide", | ||
| 623 | "cs_w32_wrxchg2_ext", | ||
| 624 | "cs_w32_wrxchg2st64", | ||
| 625 | }) | ||
| 626 | |||
| 435 | 627 | ||
| 436 | def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial: bool, emulated: bool, | 628 | def judge_cs_dump(rc: int, msg: str, want: list[int], *, wave64: bool, partial: bool, emulated: bool, |
| 437 | hexwords: bool = False) -> tuple[bool | None, str]: | 629 | hexwords: bool = False) -> tuple[bool | None, str]: |
| @@ -762,8 +954,11 @@ def native_folder(path: str, ansi: str = "mbcs") -> str | None: | |||
| 762 | 954 | ||
| 763 | def main() -> int: | 955 | def main() -> int: |
| 764 | ap = argparse.ArgumentParser() | 956 | ap = argparse.ArgumentParser() |
| 765 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), | 957 | # 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'") | 958 | # Debian/Ubuntu install (llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc), as the not-found message promises. |
| 959 | ap.add_argument("--llvm-mc", default=None, | ||
| 960 | help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' " | ||
| 961 | "(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"), | 962 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), |
| 768 | help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " | 963 | help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " |
| 769 | "subfolder that has the test programs is found by itself") | 964 | "subfolder that has the test programs is found by itself") |
| @@ -776,6 +971,9 @@ def main() -> int: | |||
| 776 | ap.add_argument("--no-validate", action="store_true", | 971 | ap.add_argument("--no-validate", action="store_true", |
| 777 | help="skip spirv-val during translation (automatic when --assembler resolves to python " | 972 | help="skip spirv-val during translation (automatic when --assembler resolves to python " |
| 778 | "and spirv-val is not on PATH)") | 973 | "and spirv-val is not on PATH)") |
| 974 | ap.add_argument("--no-ftz32", action="store_true", | ||
| 975 | help="translate shaders with --no-ftz32 (automatic when tools/vk_subgroup_info.py reports " | ||
| 976 | "denorm_flush_to_zero_f32: false)") | ||
| 779 | ap.add_argument("--disasm-dir", default=None, | 977 | ap.add_argument("--disasm-dir", default=None, |
| 780 | help="folder of pre-disassembled <name>.s listings (e.g. tests/semantic/fixtures/disasm); " | 978 | help="folder of pre-disassembled <name>.s listings (e.g. tests/semantic/fixtures/disasm); " |
| 781 | "skips llvm-mc and runs only fixtures present there") | 979 | "skips llvm-mc and runs only fixtures present there") |
| @@ -895,6 +1093,8 @@ def run_suite(a, work: str) -> int: | |||
| 895 | ]) | 1093 | ]) |
| 896 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): | 1094 | 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))]) | 1095 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) |
| 1096 | elif name in ("ms_w64x_wave_votes", "ms_w64x_wave_loops"): # vertex 64 comes from the second wave: 128 output vertices | ||
| 1097 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 128, 64, 2))]) | ||
| 898 | elif name == "ms_v5_workgroup": | 1098 | elif name == "ms_v5_workgroup": |
| 899 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) | 1099 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) |
| 900 | elif name == "ms_clip": | 1100 | elif name == "ms_clip": |
| @@ -925,9 +1125,18 @@ def run_suite(a, work: str) -> int: | |||
| 925 | Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) | 1125 | Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) |
| 926 | 1126 | ||
| 927 | # 2. Translate this run's inputs only. The translator looks for metadata one level above the input directory. | 1127 | # 2. Translate this run's inputs only. The translator looks for metadata one level above the input directory. |
| 928 | with tempfile.TemporaryDirectory(prefix="disasm-", dir=work) as selected_disasm: | 1128 | try: |
| 929 | for path in disasm_files: | 1129 | staging = tempfile.TemporaryDirectory(prefix="disasm-", dir=work) |
| 930 | shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path))) | 1130 | except OSError as exc: |
| 1131 | print(f"error: cannot create a disassembly staging directory in {work}: {exc}", file=sys.stderr) | ||
| 1132 | return 2 | ||
| 1133 | with staging as selected_disasm: | ||
| 1134 | try: | ||
| 1135 | for path in disasm_files: | ||
| 1136 | shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path))) | ||
| 1137 | except OSError as exc: | ||
| 1138 | print(f"error: cannot stage disassembly for translation: {exc}", file=sys.stderr) | ||
| 1139 | return 2 | ||
| 931 | cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir] | 1140 | cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir] |
| 932 | if assembler == "python": | 1141 | if assembler == "python": |
| 933 | cmd += ["--assembler", "python"] | 1142 | cmd += ["--assembler", "python"] |
| @@ -941,10 +1150,14 @@ def run_suite(a, work: str) -> int: | |||
| 941 | cmd.append("--bary-fallback") | 1150 | cmd.append("--bary-fallback") |
| 942 | if f16_interp_fallback(): # *_f16 interps from decoded-half inputs, no PerVertexKHR (MoltenVK) | 1151 | if f16_interp_fallback(): # *_f16 interps from decoded-half inputs, no PerVertexKHR (MoltenVK) |
| 943 | cmd.append("--f16-interp-fallback") | 1152 | cmd.append("--f16-interp-fallback") |
| 1153 | if getattr(a, "no_ftz32", False) or no_ftz32(): # no DenormFlushToZero 32 (e.g. NVIDIA Vulkan) | ||
| 1154 | cmd.append("--no-ftz32") | ||
| 944 | if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 | 1155 | if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 |
| 945 | cmd.append("--texel-offset-fallback") | 1156 | cmd.append("--texel-offset-fallback") |
| 946 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py | 1157 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py |
| 947 | cmd.append("--mesh-compute") | 1158 | cmd.append("--mesh-compute") |
| 1159 | if os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1": # with --wave64-emulate: one pass per wave | ||
| 1160 | 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 | 1161 | 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") | 1162 | cmd.append("--pc-tail-ubo") |
| 950 | if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) | 1163 | if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) |
| @@ -988,11 +1201,11 @@ def run_suite(a, work: str) -> int: | |||
| 988 | for fname in asm_files: | 1201 | for fname in asm_files: |
| 989 | name = os.path.splitext(fname)[0] | 1202 | name = os.path.splitext(fname)[0] |
| 990 | spv = os.path.join(spirv_dir, f"{name}.spv") | 1203 | spv = os.path.join(spirv_dir, f"{name}.spv") |
| 991 | if name == "ps_ij_computed" and (bary_fallback() or f16_interp_fallback()): | 1204 | if name == "ps_ij_computed" and bary_fallback(): |
| 992 | # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair, so there | 1205 | # Before the .spv check: under --bary-fallback the translator refuses a computed I/J pair, so there |
| 993 | # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). | 1206 | # is no .spv (--f16-interp-fallback alone lowers it via DerivativeControl + BaryCoordKHR). |
| 994 | results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs: " | 1207 | results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; " |
| 995 | "no --bary-fallback / --f16-interp-fallback)")) | 1208 | "unsupported under --bary-fallback)")) |
| 996 | continue | 1209 | continue |
| 997 | if not os.path.isfile(spv): | 1210 | if not os.path.isfile(spv): |
| 998 | results.append((name, False, "missing .spv (translation failed)")) | 1211 | results.append((name, False, "missing .spv (translation failed)")) |
| @@ -1057,7 +1270,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. | 1270 | # 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. | 1271 | # 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). | 1272 | # 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) | 1273 | env = dict(cs_env or os.environ, **PK_MUL_LO_ENV) if name == "cs_pk_mul_lo_const" else cs_env |
| 1274 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env) | ||
| 1061 | want = { | 1275 | want = { |
| 1062 | "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], | 1276 | "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], |
| 1063 | "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], | 1277 | "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], |
| @@ -1081,10 +1295,25 @@ def run_suite(a, work: str) -> int: | |||
| 1081 | "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], | 1295 | "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], |
| 1082 | "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], | 1296 | "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], |
| 1083 | }[name] | 1297 | }[name] |
| 1084 | words = dump_words(msg) | 1298 | results.append((name,) + dump_result(rc, msg, want)) |
| 1085 | vals = words[:len(want)] if words else [] | 1299 | elif name == "cs_w64x_dynamic_r32_uint": |
| 1086 | results.append((name,) + compute_result(rc, msg, rc == 0 and vals == want, | 1300 | word = 0x8A600250 |
| 1087 | " ".join(hex(x) for x in vals) if vals else msg)) | 1301 | descriptor_at, value_at = 0x100, 0x180 |
| 1302 | with tempfile.TemporaryDirectory(prefix="dynamic-r32-", dir=work) as scratch: | ||
| 1303 | heap = os.path.join(scratch, "heap.bin") | ||
| 1304 | with open(heap, "wb") as stream: | ||
| 1305 | descriptor = struct.pack("<4I", value_at, 4 << 16, 1, (2 << 28) | (20 << 12) | 4) | ||
| 1306 | stream.write(descriptor) | ||
| 1307 | stream.write(bytes(value_at - descriptor_at - len(descriptor))) | ||
| 1308 | stream.write(struct.pack("<I", word)) | ||
| 1309 | env = dict(cs_env or os.environ, VKC_SGPRS=f"0,{descriptor_at}", | ||
| 1310 | VKC_HEAP_FILE=f"{heap}@{descriptor_at}") | ||
| 1311 | command = [vk_compute, spv, "1", "dump"] | ||
| 1312 | if not w64_emulated(): | ||
| 1313 | command.append("--require-wave64") | ||
| 1314 | rc, msg = run_cmd(command, env=env) | ||
| 1315 | results.append((name,) + judge_cs_dump(rc, msg, [word] * 8, wave64=not w64_emulated(), | ||
| 1316 | partial=False, emulated=w64_emulated())) | ||
| 1088 | elif name == "cs_fmt_1010102": | 1317 | elif name == "cs_fmt_1010102": |
| 1089 | problem = fmt_1010102_test(a.build, spirv_dir, cs_env) | 1318 | problem = fmt_1010102_test(a.build, spirv_dir, cs_env) |
| 1090 | results.append((name, not problem, problem or "64/64 dumped words exact")) | 1319 | results.append((name, not problem, problem or "64/64 dumped words exact")) |
| @@ -1119,17 +1348,11 @@ def run_suite(a, work: str) -> int: | |||
| 1119 | elif name == "cs_heap_init": | 1348 | 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. | 1349 | # 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())) | 1350 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env())) |
| 1122 | words = dump_words(msg) | 1351 | 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": | 1352 | elif name == "cs_user_sgprs": |
| 1127 | # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. | 1353 | # 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)) | 1354 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) |
| 1129 | words = dump_words(msg) | 1355 | 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": | 1356 | elif name == "cs_w32_salu_ext": |
| 1134 | detail = salu_ext_test(a.build, spirv_dir, cs_env) | 1357 | detail = salu_ext_test(a.build, spirv_dir, cs_env) |
| 1135 | results.append((name, None if isinstance(detail, Skip) else not detail, | 1358 | results.append((name, None if isinstance(detail, Skip) else not detail, |
| @@ -1139,7 +1362,7 @@ def run_suite(a, work: str) -> int: | |||
| 1139 | if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names | 1362 | 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)")) | 1363 | results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) |
| 1141 | else: | 1364 | else: |
| 1142 | ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, | 1365 | ok, detail = judge_cs_dump(rc, msg, [0, 0x3FF40000], wave64=False, partial=False, emulated=False, |
| 1143 | hexwords=True) | 1366 | hexwords=True) |
| 1144 | results.append((name, ok, detail)) | 1367 | results.append((name, ok, detail)) |
| 1145 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): | 1368 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): |
| @@ -1203,157 +1426,18 @@ def run_suite(a, work: str) -> int: | |||
| 1203 | # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. | 1426 | # Whole-wave mask test, as in check.py: needs a 64-wide subgroup, skipped where the device has none. |
| 1204 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. | 1427 | # 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())) | 1428 | 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", | 1429 | elif name in CS_DUMP_WANTS: |
| 1207 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", | 1430 | want = CS_DUMP_WANTS[name] |
| 1208 | "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64", | 1431 | # Every dump outside CS_DUMP_NON_WAVE64 is a whole-wave (wave64) test: ask for a 64-wide subgroup and |
| 1209 | "cs_w64_mask_detect", | 1432 | # skip, as check.py does, where the device has none (vk_compute_test exits 77). With |
| 1210 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", | 1433 | # LEONIDA_W64_EMULATE=1 they were translated with --wave64-emulate and run on any subgroup size. |
| 1211 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", | ||
| 1212 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", | ||
| 1213 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", | ||
| 1214 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", | ||
| 1215 | "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", | ||
| 1216 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): | ||
| 1217 | cs_dump_wants = { | ||
| 1218 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], | ||
| 1219 | # base + soffset + imm (cs_smem_soffset_imm.asm); out[4..7] are seeds the shader leaves alone | ||
| 1220 | "cs_smem_vcc_base": CS_SMEM_VCC, | ||
| 1221 | "cs_smem_soffset_imm": [0x5EED0024, 0x5EED0028, 0x5EED002C, 0x5EED0030, | ||
| 1222 | 0x5EED0010, 0x5EED0014, 0x5EED0018, 0x5EED001C], | ||
| 1223 | # SHADER-52: wave32 lane select & 31 (40 → 8) | ||
| 1224 | "cs_w32_lane_wrap": [25, 16, 777, 777], | ||
| 1225 | # v_movrelsd_2_b32: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]] (cs_movrelsd_2.asm) | ||
| 1226 | "cs_movrelsd_2": [11, 33, 33, 55, 1717, 77, 1515, 1717], | ||
| 1227 | # SHADER-90: ds_permute_b32 (cs_w32_permute.asm): scatter, unwritten lane = 0, EXEC gates the write | ||
| 1228 | "cs_w32_permute": [218, 29, 8, 211, 0, 15, 99, 15], | ||
| 1229 | # integer ops with CPU-only checks until now (cs_w32_int_ext.asm) | ||
| 1230 | "cs_w32_int_ext": [1, 27, 1, 0x33332222, 0xC0000000, 0x4000, 18, 0x20304050], | ||
| 1231 | # 64-bit scalar data ops and v_mad_u64_u32 (cs_w32_salu64.asm) | ||
| 1232 | # more ops with CPU-only checks until now (cs_w32_misc_ext.asm) | ||
| 1233 | # ops merged on 2026-11-22 with CPU-only checks (cs_w32_new_ops.asm) | ||
| 1234 | # plain 8/16-bit MUBUF stores, one crossing a dword (cs_w32_buffer_store_sub.asm) | ||
| 1235 | "cs_w32_buffer_store_sub": [0x1122AB44, 0xCDEF7788, 0x34AABBCC, 0xDDDDDD12, 0x0102035A, 0x05061234, 0xAB, 0xFFFFCDEF], | ||
| 1236 | # 8/16-bit MUBUF d16 loads and stores (cs_w32_buffer_sub16.asm) | ||
| 1237 | "cs_w32_buffer_sub16": [0xBEEF00AA, 0x00AA1234, 0xBEEFFFAA, 0xFFAA1234, 0xBEEF8899, 0x88991234, 0x1122CD44, 0xABCD7788], | ||
| 1238 | # 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], | ||
| 1240 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], | ||
| 1241 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], | ||
| 1242 | "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) | ||
| 1244 | "cs_w32_lds_u8_d16": [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234], | ||
| 1245 | # 8/16-bit and 64/96/128-bit LDS accesses (cs_w32_lds_subdword.asm / cs_w32_lds_wide.asm headers) | ||
| 1246 | "cs_w32_lds_subdword": [0x11B2D444, 0xA1B2C3D4, 0xFFFFFFB2, 0x000000B2, 0x00000011, 0xFFFFA1B2, 0x0000A1B2, 0xFFFFC3D4], | ||
| 1247 | "cs_w32_lds_wide": [0xCAFEF00D, 0xFEEDFACE, 0x600DD00D, 0x00000000, 0x8BADF00D, 0xDEADC0DE, 0x12345678, 0x9ABCDEF0], | ||
| 1248 | # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header) | ||
| 1249 | "cs_lds_b64_cmpst": [0x11110001, 0x22220002, 0x33330003, 0x44440004, | ||
| 1250 | 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC], | ||
| 1251 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) | ||
| 1252 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, | ||
| 1253 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], | ||
| 1254 | # ds_wrxchg2_rtn_b32's pair cases and ds_wrxchg2st64_rtn_b32 | ||
| 1255 | # (cs_w32_wrxchg2_ext.asm / cs_w32_wrxchg2st64.asm headers) | ||
| 1256 | "cs_w32_wrxchg2_ext": [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF, | ||
| 1257 | 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678], | ||
| 1258 | "cs_w32_wrxchg2st64": [0x33333333, 0x44444444, 0x55550005, 0x66660006, | ||
| 1259 | 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0], | ||
| 1260 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) | ||
| 1261 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, | ||
| 1262 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], | ||
| 1263 | # constant EXEC masks (cs_exec_const.asm): each lane takes its own bit of the constant | ||
| 1264 | "cs_exec_const": [16, 8, 2, 16, 0, 16], | ||
| 1265 | # constant lane masks: lane L takes bit L (cs_w32_mask_imm.asm / cs_w64_mask_imm.asm headers) | ||
| 1266 | "cs_w32_mask_imm": [2056, 20, 2, 6152, 2050, 4112, 258, 32], | ||
| 1267 | "cs_w64_mask_imm": [2056, 1084, 828, 2052, 319, 2104, 516, 2064], | ||
| 1268 | "cs_dpp": [1, 0, 3, 2, 5, 4, 7, 6], | ||
| 1269 | "cs_dpp_row": [0, 0, 1, 2, 3, 4, 5, 6], | ||
| 1270 | "cs_dpp_mask": [1, 0, 3, 2, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE], | ||
| 1271 | "cs_dpp8": [7, 6, 5, 4, 3, 2, 1, 0], | ||
| 1272 | "cs_dpp_ops": [100, 10, 11, 12, 13, 14, 15, 16], | ||
| 1273 | "cs_dpp_bound": [10, 10, 11, 12, 13, 14, 15, 16], | ||
| 1274 | "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], | ||
| 1275 | "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], | ||
| 1276 | "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0], | ||
| 1277 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], | ||
| 1278 | # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] | ||
| 1279 | # without it | ||
| 1280 | "cs_signed_zero_nan": [0x80000000, 0x80000000, 0x80008000, 0x00008000, 1, 1, 1, 0x00007C00], | ||
| 1281 | "cs_wave64_ballot": [32, 16, 24, 40, 8, 48], | ||
| 1282 | "cs_wm_half_ops": [32, 16, 16, 0, 16], | ||
| 1283 | "cs_wm_half_cmp": [1, 0, 1, 1], | ||
| 1284 | "cs_wm_bfm64": [16, 8, 8, 40], | ||
| 1285 | "cs_wm_scc_rfl": [55, 48], | ||
| 1286 | "cs_w64_mask_detect": [48], | ||
| 1287 | "cs_wqm_w64": [20, 4, 12, 8, 1, 0, 15728895, 20], # cs_wqm_w64.asm / cs_wqm_w32.asm headers | ||
| 1288 | "cs_wqm_w32": [12, 1, 4, 0, 8, 15728880, 4, 32], | ||
| 1289 | "cs_wqm_w64_half": [11, 14, 0, 1, 6, 8, 12, 2], | ||
| 1290 | # cross-half tests (derivations in each .asm); need exact wave64 or its emulation | ||
| 1291 | "cs_w64x_readlane": [121, 121, 16, 97, 16, 100, 100, 121], | ||
| 1292 | "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 4660, 99], | ||
| 1293 | "cs_w64x_readfirstlane": [140, 140, 163, 132, 100, 105, 133, 48], | ||
| 1294 | "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], | ||
| 1295 | "cs_w64x_permute": [218, 442, 435, 239, 0, 99, 239, 232], # SHADER-90, cs_w64x_permute.asm | ||
| 1296 | "cs_w64x_branch": [0, 0, 0, 0, 5, 5, 9, 9], | ||
| 1297 | "cs_w64x_mask_reuse": [8, 40, 8, 40, 2, 20, 10, 64], | ||
| 1298 | "cs_w64x_mask_reuse2": [10, 20, 8, 8, 5, 2, 132, 131], | ||
| 1299 | "cs_w64x_chain_barrier": [564, 563, 500, 627], | ||
| 1300 | "cs_w64x_ballot": [2053, 2061, 2069, 2077, 2085, 2093, 2101, 2109], | ||
| 1301 | "cs_w64x_wg128_branches": [121, 121, 343, 343, 14, 31, 19812, 22728], | ||
| 1302 | "cs_w64x_lds_raw": [132, 137, 100, 108, 131, 101, 149, 118], | ||
| 1303 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], | ||
| 1304 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], | ||
| 1305 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave | ||
| 1306 | "cs_w64x_partial_swizzle": [508, 523, 0, 0, 528, 0, 531, 0], # swizzle from a missing lane: 0 | ||
| 1307 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 | ||
| 1308 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) | ||
| 1309 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], | ||
| 1310 | "cs_w32_andn2_exec": [1, 8, 16, 2064, 2068, 3, 20, 1544], # s_andn2_saveexec/wrexec_b32 (.asm header) | ||
| 1311 | # SHADER-1264: a computed value written to exec_lo / exec_hi gives each lane its own bit | ||
| 1312 | # (cs_w32_exec_computed.asm / cs_w64_exec_computed.asm headers) | ||
| 1313 | "cs_w32_exec_computed": [259, 1028, 3088, 7682, 512, 4100, 0, 3], | ||
| 1314 | "cs_w64_exec_computed": [291, 1028, 11264, 771, 8192, 4132, 0, 3], | ||
| 1315 | "cs_w32_sincos": [1, 1, 1, 1, 1, 1], # SHADER-88 (cs_w32_sincos.asm): angles in turns | ||
| 1316 | # SHADER-74: v_permlane16/x16 FI / BOUND_CTRL with the source lane off in EXEC (cs_w32_permlane_fi.asm) | ||
| 1317 | "cs_w32_permlane_fi": [1000, 0, 4, 1, 1000, 0, 52, 49], | ||
| 1318 | "cs_w64x_sbarrier": [605, 605, 686, 686, 3032, 3013, 3032, 3031], | ||
| 1319 | "cs_w64x_load_ballot_load": [43, 74, 75, 42, 42, 18, 41, 32], | ||
| 1320 | "cs_w64x_andn2_exec": [1, 16, 32, 4144, 2052, 3, 8, 1544], # s_andn2_saveexec/wrexec_b64 (.asm header) | ||
| 1321 | "cs_w64x_saveexec_b64": [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171], # .asm header | ||
| 1322 | "cs_w64x_cmp_sdst": [10240, 6144, 2053, 8224, 7714, 6184, 4144, 5], # .asm header | ||
| 1323 | "cs_bpermute32": [0, 50, 162, 99, 36, 218, 183, 15], # wave32: needs 32 lanes | ||
| 1324 | # SHADER-91: s_barrier sites in different wave-uniform branches meet (cs_barrier_divergent.asm) | ||
| 1325 | "cs_barrier_divergent": [127, 126, 125, 124, 123, 122, 121, 120], | ||
| 1326 | # SHADER-91: other waves end without s_barrier (cs_barrier_early_end.asm); a loop whose trip count | ||
| 1327 | # differs per wave (cs_barrier_loop.asm) | ||
| 1328 | "cs_barrier_early_end": [127, 126, 125, 124, 123, 122, 121, 120], | ||
| 1329 | "cs_barrier_loop": [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE], | ||
| 1330 | # SHADER-21 part 2: a mask copied to a VGPR with v_mov_b32 respects EXEC — | ||
| 1331 | # inactive lanes keep the old VGPR (cs_mask_vgpr_exec.asm) | ||
| 1332 | "cs_mask_vgpr_exec": [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, | ||
| 1333 | 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF], | ||
| 1334 | } | ||
| 1335 | want = cs_dump_wants[name] | ||
| 1336 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / | ||
| 1337 | # 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 | ||
| 1338 | # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, | ||
| 1339 | # as check.py does, where the device has none | ||
| 1340 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were | ||
| 1341 | # translated with --wave64-emulate and run on any subgroup size. | ||
| 1342 | # cs_w64x_partial, cs_w64x_partial_scmp and cs_w64x_partial_swizzle (40-thread groups) can't have full | 1434 | # cs_w64x_partial, cs_w64x_partial_scmp and cs_w64x_partial_swizzle (40-thread groups) can't have full |
| 1343 | # subgroups: they ask for size 64 without them. With LEONIDA_W64_EMULATE=1 they ask for 32, the width the | 1435 | # subgroups: they ask for size 64 without them. With LEONIDA_W64_EMULATE=1 they ask for 32, the width the |
| 1344 | # emulation is for, as check.py's partial_wave_test does. RADV defaults compute to 64, and there | 1436 | # emulation is for, as check.py's partial_wave_test does. RADV defaults compute to 64, and there |
| 1345 | # cs_w64x_partial_swizzle came out right even before its missing-lane reads were fixed; at 32 it did not. | 1437 | # cs_w64x_partial_swizzle came out right even before its missing-lane reads were fixed; at 32 it did not. |
| 1346 | emulated = w64_emulated() | 1438 | emulated = w64_emulated() |
| 1347 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") | 1439 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") |
| 1348 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", | 1440 | wave64 = name not in CS_DUMP_NON_WAVE64 and not emulated and not partial |
| 1349 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", | ||
| 1350 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", | ||
| 1351 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | ||
| 1352 | "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", | ||
| 1353 | "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", | ||
| 1354 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", | ||
| 1355 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", | ||
| 1356 | "cs_w32_exec_computed") and not emulated and not partial | ||
| 1357 | if partial: | 1441 | if partial: |
| 1358 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") | 1442 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") |
| 1359 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) | 1443 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) |
| @@ -1375,9 +1459,7 @@ def run_suite(a, work: str) -> int: | |||
| 1375 | else: | 1459 | else: |
| 1376 | want = judged_words(name, msg, want) # cs_signed_zero_nan on Apple and llvmpipe (check.py) | 1460 | want = judged_words(name, msg, want) # cs_signed_zero_nan on Apple and llvmpipe (check.py) |
| 1377 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, | 1461 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, |
| 1378 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", | 1462 | hexwords=name in CS_DUMP_HEXWORDS) |
| 1379 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | ||
| 1380 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_signed_zero_nan")) | ||
| 1381 | if ok and None in want: | 1463 | if ok and None in want: |
| 1382 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) | 1464 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) |
| 1383 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" | 1465 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" |
| @@ -1514,6 +1596,7 @@ def run_suite(a, work: str) -> int: | |||
| 1514 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), | 1596 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), |
| 1515 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), | 1597 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), |
| 1516 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), | 1598 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), |
| 1599 | "ps_exp_f32_denorm": (0x01000000, 0x00800000, 0x00000000, 0x00000000), | ||
| 1517 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), | 1600 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), |
| 1518 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) | 1601 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) |
| 1519 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) | 1602 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) |
| @@ -1522,7 +1605,7 @@ def run_suite(a, work: str) -> int: | |||
| 1522 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), | 1605 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), |
| 1523 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), | 1606 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), |
| 1524 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), | 1607 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), |
| 1525 | "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 | 1608 | "ps_f64_mods": (0x3FF40000, 0x3FF00000, 0x3FF00000, 0x3FD00000), # needs shaderFloat64 |
| 1526 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 | 1609 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 |
| 1527 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), | 1610 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), |
| 1528 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) | 1611 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) |
| @@ -1546,6 +1629,7 @@ def run_suite(a, work: str) -> int: | |||
| 1546 | # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) | 1629 | # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) |
| 1547 | "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), | 1630 | "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3F800000), |
| 1548 | "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000B), # far branches (.asm header) | 1631 | "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000B), # far branches (.asm header) |
| 1632 | "ps_pops_wait_loop": (0x00000001, 0x00000000, 0x3F800000, 0x3F800000), # POPS wait loop (.asm header) | ||
| 1549 | "ps_vcmp_f16": (0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA), # 16-bit float v_cmp e32 (.asm header) | 1633 | "ps_vcmp_f16": (0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA), # 16-bit float v_cmp e32 (.asm header) |
| 1550 | "ps_vcmp_f16_e64": (0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9), # same, e64 with swapped operands | 1634 | "ps_vcmp_f16_e64": (0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9), # same, e64 with swapped operands |
| 1551 | "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header) | 1635 | "ps_vcmpx_f16": (0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA), # 16-bit float v_cmpx e32 (.asm header) |
| @@ -1573,6 +1657,9 @@ def run_suite(a, work: str) -> int: | |||
| 1573 | if skip := wide_pixel_skip(name, msg): # a 64-wide pixel stage the device could not give: nothing to judge | 1657 | if skip := wide_pixel_skip(name, msg): # a 64-wide pixel stage the device could not give: nothing to judge |
| 1574 | results.append((name, None, str(skip))) | 1658 | results.append((name, None, str(skip))) |
| 1575 | continue | 1659 | continue |
| 1660 | if skip := paravirtual_exp2_skip(name, msg): # Apple Paravirtual: OpExp2 is two ulps low on 2^-125 | ||
| 1661 | results.append((name, None, str(skip))) | ||
| 1662 | continue | ||
| 1576 | if name in const_wants: | 1663 | if name in const_wants: |
| 1577 | if name == "ps_vcmpx_forms" and (skip := vcmpx_forms_narrow_skip(msg)): | 1664 | if name == "ps_vcmpx_forms" and (skip := vcmpx_forms_narrow_skip(msg)): |
| 1578 | ok, detail = None, str(skip) | 1665 | ok, detail = None, str(skip) |
| @@ -1605,6 +1692,9 @@ def run_suite(a, work: str) -> int: | |||
| 1605 | elif name == "ps_ij_computed": | 1692 | elif name == "ps_ij_computed": |
| 1606 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | 1693 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) |
| 1607 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" | 1694 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" |
| 1695 | elif name == "ps_exp_f32_denorm_rt": | ||
| 1696 | problem = exp_f32_denorm_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | ||
| 1697 | ok, detail = not problem, problem or "4096 pixels exact across 64 runtime-dependent inputs" | ||
| 1608 | elif name == "ps_mandelbrot": | 1698 | elif name == "ps_mandelbrot": |
| 1609 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] | 1699 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] |
| 1610 | problem = frame_problem(px) or mandelbrot_problem(px) | 1700 | problem = frame_problem(px) or mandelbrot_problem(px) |
| @@ -1631,13 +1721,13 @@ def run_suite(a, work: str) -> int: | |||
| 1631 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") | 1721 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") |
| 1632 | results.append((name, None if isinstance(problem, Skip) else not problem, | 1722 | results.append((name, None if isinstance(problem, Skip) else not problem, |
| 1633 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) | 1723 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) |
| 1634 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): | 1724 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_w64x_wave_votes", "ms_w64x_wave_loops"): |
| 1635 | raw = os.path.join(raw_dir, f"{name}.raw") | 1725 | raw = os.path.join(raw_dir, f"{name}.raw") |
| 1636 | env = mesh_env(spirv_dir, name, gfx_env) | 1726 | env = mesh_env(spirv_dir, name, gfx_env) |
| 1637 | rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) | 1727 | rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) |
| 1638 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as | 1728 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as |
| 1639 | # the wave64 compute dumps are. | 1729 | # the wave64 compute dumps are. |
| 1640 | no64 = (name == "ms_w64x_ballot" and not w64_emulated() and | 1730 | no64 = (name in ("ms_w64x_ballot", "ms_w64x_wave_votes", "ms_w64x_wave_loops") and not w64_emulated() and |
| 1641 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) | 1731 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) |
| 1642 | if rc == UNSUPPORTED: | 1732 | if rc == UNSUPPORTED: |
| 1643 | results.append((name, None, unsupported_skip(msg))) | 1733 | results.append((name, None, unsupported_skip(msg))) |
| @@ -1689,14 +1779,15 @@ def run_suite(a, work: str) -> int: | |||
| 1689 | ok, detail = check_flat(raw) | 1779 | ok, detail = check_flat(raw) |
| 1690 | results.append((name, ok, detail)) | 1780 | results.append((name, ok, detail)) |
| 1691 | 1781 | ||
| 1692 | if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed" | 1782 | if (a.filter or disasm_src is not None) and not results: |
| 1693 | names = [os.path.splitext(f)[0] for f in asm_files] | 1783 | names = [os.path.splitext(f)[0] for f in asm_files] |
| 1694 | partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) | 1784 | partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) |
| 1695 | shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") | 1785 | shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") |
| 1696 | role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" | 1786 | role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" |
| 1697 | hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" | 1787 | hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" |
| 1698 | if all(n.startswith("cs_bench_") for n in names) else "") | 1788 | if all(n.startswith("cs_bench_") for n in names) else "") |
| 1699 | print(f"error: --filter {a.filter!r} selected {shown} but no runnable GPU test cases ({role}){hint}", | 1789 | selected_by = f"--filter {a.filter!r}" if a.filter else f"--disasm-dir {disasm_src!r}" |
| 1790 | print(f"error: {selected_by} selected {shown} but no runnable GPU test cases ({role}){hint}", | ||
| 1700 | file=sys.stderr) | 1791 | file=sys.stderr) |
| 1701 | return 2 | 1792 | return 2 |
| 1702 | 1793 | ||
diff --git a/scripts/run_guest_scene.py b/scripts/run_guest_scene.py index 60d5ded90..0753f2aa7 100644 --- a/scripts/run_guest_scene.py +++ b/scripts/run_guest_scene.py | |||
| @@ -4,6 +4,8 @@ | |||
| 4 | python -I scripts/run_guest_scene.py --loader L --guest G --shaders ROOT [--out DIR] [--wine WINE] | 4 | python -I scripts/run_guest_scene.py --loader L --guest G --shaders ROOT [--out DIR] [--wine WINE] |
| 5 | [--play-audio] [--negative-controls] | 5 | [--play-audio] [--negative-controls] |
| 6 | 6 | ||
| 7 | Outside Windows, --wine defaults to $WINE (e.g. UMU-Proton's files/bin/wine) and one of the two is required. | ||
| 8 | |||
| 7 | Each run renders offscreen in a fresh process and write overlay. Without --out the runs go to a temporary folder that is removed | 9 | Each run renders offscreen in a fresh process and write overlay. Without --out the runs go to a temporary folder that is removed |
| 8 | afterwards. The summary is printed first, and on failure the last run's log tails are printed too. Audio stays offline | 10 | afterwards. The summary is printed first, and on failure the last run's log tails are printed too. Audio stays offline |
| 9 | unless --play-audio sets LEONIDA_SCENE_AUDIO=winmm. The guest then plays the pulse synchronously with PlaySoundW. | 11 | unless --play-audio sets LEONIDA_SCENE_AUDIO=winmm. The guest then plays the pulse synchronously with PlaySoundW. |
| @@ -256,12 +258,13 @@ def negative_controls(session: Session, out: Path) -> dict: | |||
| 256 | 258 | ||
| 257 | 259 | ||
| 258 | def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: | 260 | def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: |
| 261 | session = Session(args, out) | ||
| 259 | try: | 262 | try: |
| 260 | out.mkdir(parents=True, exist_ok=True) # parse_args has checked that it is new or empty | 263 | out.mkdir(parents=True, exist_ok=True) # parse_args has checked that it is new or empty |
| 264 | session.logs.mkdir() # Reserve the output even if another run passed the same check. | ||
| 261 | except OSError as exc: | 265 | except OSError as exc: |
| 262 | print(f"error: could not create output directory {out}: {exc}", file=sys.stderr) | 266 | print(f"error: could not create output directory {out}: {exc}", file=sys.stderr) |
| 263 | return 1 | 267 | return 1 |
| 264 | session = Session(args, out) | ||
| 265 | report: dict = {"status": "fail", "frames": FRAMES, "headless": True, "wine": args.wine, "temporary": temporary, | 268 | report: dict = {"status": "fail", "frames": FRAMES, "headless": True, "wine": args.wine, "temporary": temporary, |
| 266 | "audio_mode": "winmm" if args.play_audio else "offline", "report": str(out / "report.json")} | 269 | "audio_mode": "winmm" if args.play_audio else "offline", "report": str(out / "report.json")} |
| 267 | try: | 270 | try: |
| @@ -271,7 +274,7 @@ def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: | |||
| 271 | "guest": {"path": str(args.guest), "sha256": sha256(args.guest.read_bytes())}, | 274 | "guest": {"path": str(args.guest), "sha256": sha256(args.guest.read_bytes())}, |
| 272 | "shaders": {"path": str(args.shaders), "files": len(shader_files), "tree_sha256": tree_hash(shader_files)}, | 275 | "shaders": {"path": str(args.shaders), "files": len(shader_files), "tree_sha256": tree_hash(shader_files)}, |
| 273 | "scene.bin": sha256(scene_bytes())} | 276 | "scene.bin": sha256(scene_bytes())} |
| 274 | for sub in ("logs", "package", *MODES): | 277 | for sub in ("package", *MODES): |
| 275 | (out / sub).mkdir() | 278 | (out / sub).mkdir() |
| 276 | package = out / "package" | 279 | package = out / "package" |
| 277 | write_new(package / "scene.bin", scene_bytes()) | 280 | write_new(package / "scene.bin", scene_bytes()) |
| @@ -324,13 +327,14 @@ def parse_args() -> argparse.Namespace: | |||
| 324 | ap.add_argument("--guest", type=Path, required=True) | 327 | ap.add_argument("--guest", type=Path, required=True) |
| 325 | ap.add_argument("--shaders", type=Path, required=True, help="shader root containing spirv/") | 328 | ap.add_argument("--shaders", type=Path, required=True, help="shader root containing spirv/") |
| 326 | ap.add_argument("--out", type=Path, help="new or empty folder (default: a temporary folder, removed afterwards)") | 329 | ap.add_argument("--out", type=Path, help="new or empty folder (default: a temporary folder, removed afterwards)") |
| 327 | ap.add_argument("--wine", help="run the loader through this Wine binary") | 330 | ap.add_argument("--wine", default=(os.environ.get("WINE") or None) if os.name != "nt" else None, |
| 331 | help="run the loader through this Wine binary (default: $WINE outside Windows)") | ||
| 328 | ap.add_argument("--wine-arg", action="append", default=[], help="argument to the Wine launcher (repeatable)") | 332 | ap.add_argument("--wine-arg", action="append", default=[], help="argument to the Wine launcher (repeatable)") |
| 329 | ap.add_argument("--play-audio", action="store_true", help="LEONIDA_SCENE_AUDIO=winmm instead of offline") | 333 | ap.add_argument("--play-audio", action="store_true", help="LEONIDA_SCENE_AUDIO=winmm instead of offline") |
| 330 | ap.add_argument("--negative-controls", action="store_true", help="also run a bad scene.bin and checkpoint") | 334 | ap.add_argument("--negative-controls", action="store_true", help="also run a bad scene.bin and checkpoint") |
| 331 | args = ap.parse_args() | 335 | args = ap.parse_args() |
| 332 | if args.wine_arg and not args.wine: | 336 | if args.wine_arg and not args.wine: |
| 333 | ap.error("--wine-arg requires --wine") | 337 | ap.error("--wine-arg requires --wine" if os.name == "nt" else "--wine-arg requires --wine or WINE") |
| 334 | for name in ("loader", "guest"): | 338 | for name in ("loader", "guest"): |
| 335 | if not getattr(args, name).is_file(): | 339 | if not getattr(args, name).is_file(): |
| 336 | ap.error(f"--{name}: no such file") | 340 | ap.error(f"--{name}: no such file") |
| @@ -339,10 +343,10 @@ def parse_args() -> argparse.Namespace: | |||
| 339 | if args.wine: | 343 | if args.wine: |
| 340 | found = args.wine if Path(args.wine).is_file() else shutil.which(args.wine) | 344 | found = args.wine if Path(args.wine).is_file() else shutil.which(args.wine) |
| 341 | if not found: | 345 | if not found: |
| 342 | ap.error("--wine: not found") | 346 | ap.error(f"--wine: not found: {args.wine}") |
| 343 | args.wine = str(Path(found).resolve()) | 347 | args.wine = str(Path(found).resolve()) |
| 344 | elif os.name != "nt": | 348 | elif os.name != "nt": |
| 345 | ap.error("--wine is required outside Windows") | 349 | ap.error("--wine (or WINE) is required outside Windows") |
| 346 | if args.out and args.out.exists() and (not args.out.is_dir() or any(args.out.iterdir())): | 350 | if args.out and args.out.exists() and (not args.out.is_dir() or any(args.out.iterdir())): |
| 347 | ap.error("--out must be new or an empty folder") | 351 | ap.error("--out must be new or an empty folder") |
| 348 | args.loader, args.guest, args.shaders = args.loader.resolve(), args.guest.resolve(), args.shaders.resolve() | 352 | args.loader, args.guest, args.shaders = args.loader.resolve(), args.guest.resolve(), args.shaders.resolve() |
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e78133..7b6b1bec8 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py | |||
| @@ -12,13 +12,17 @@ the pattern matches their basenames, not directory paths. Package `__init__.py` | |||
| 12 | because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an | 12 | because discover imports them and runs any TestCase they define regardless of the pattern. No matching files is an |
| 13 | error in serial and parallel runs. | 13 | error in serial and parallel runs. |
| 14 | 14 | ||
| 15 | It 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. | 15 | It 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. A package's |
| 16 | `load_tests` hook receives the discovery pattern and controls which tests run in that package's worker. | ||
| 16 | 17 | ||
| 17 | The 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, | 18 | The 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, |
| 18 | or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary | 19 | or on a single core, it runs that discover command itself. Prints the output of every failing file, headed by its |
| 19 | line, and exits 1 if a file fails, none is found, or no test ran. Standard library only. | 20 | exit code (a POSIX signal by name, a known Windows NTSTATUS with its meaning, e.g. 0xC0000005 access violation, |
| 21 | since a file that crashes prints nothing), and one summary line, and exits 1 if a file fails, none is found, or no | ||
| 22 | test ran. Standard library only. | ||
| 20 | 23 | ||
| 21 | The 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. | 24 | The test count and verdict come from unittest's result, not from printed summaries. A child exiting with status 0 |
| 25 | without a completed result, or after unittest reported failure, fails the run. | ||
| 22 | 26 | ||
| 23 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with | 27 | `--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. | 28 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. |
| @@ -33,11 +37,13 @@ import locale | |||
| 33 | import math | 37 | import math |
| 34 | import os | 38 | import os |
| 35 | import re | 39 | import re |
| 40 | import signal | ||
| 36 | import subprocess | 41 | import subprocess |
| 37 | import sys | 42 | import sys |
| 38 | import tempfile | 43 | import tempfile |
| 39 | import threading | 44 | import threading |
| 40 | import time | 45 | import time |
| 46 | import unittest | ||
| 41 | 47 | ||
| 42 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 | 48 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 |
| 43 | 49 | ||
| @@ -59,7 +65,7 @@ def _unregister_process(proc): | |||
| 59 | def _kill_process_tree(proc): | 65 | def _kill_process_tree(proc): |
| 60 | if proc is None: | 66 | if proc is None: |
| 61 | return | 67 | return |
| 62 | if os.name == "nt": | 68 | if os.name == "nt" and proc.poll() is None: |
| 63 | try: | 69 | try: |
| 64 | subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], | 70 | subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], |
| 65 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | 71 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| @@ -74,11 +80,13 @@ def _kill_process_tree(proc): | |||
| 74 | def _terminate_active_processes(): | 80 | def _terminate_active_processes(): |
| 75 | with _processes_lock: | 81 | with _processes_lock: |
| 76 | procs = list(_active_processes) | 82 | procs = list(_active_processes) |
| 77 | for p in procs: | 83 | if os.name != "nt": |
| 78 | try: | 84 | for p in procs: |
| 79 | p.terminate() | 85 | try: |
| 80 | except OSError: | 86 | p.terminate() |
| 81 | pass | 87 | except OSError: |
| 88 | pass | ||
| 89 | # On Windows taskkill /T needs the root process alive to find its descendants. | ||
| 82 | for p in procs: | 90 | for p in procs: |
| 83 | _kill_process_tree(p) | 91 | _kill_process_tree(p) |
| 84 | try: | 92 | try: |
| @@ -94,13 +102,84 @@ CHILD_PROGRAM = ( | |||
| 94 | "import json, os, sys, unittest\n" | 102 | "import json, os, sys, unittest\n" |
| 95 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" | 103 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" |
| 96 | "result = program.result\n" | 104 | "result = program.result\n" |
| 97 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" | 105 | "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" | 106 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8', newline='\\n') as handle:\n" |
| 99 | "if not result.wasSuccessful():\n" | 107 | " json.dump({'testsRun': result.testsRun, 'exitCode': code}, handle)\n" |
| 100 | " sys.exit(1)\n" | 108 | "sys.exit(code)\n") |
| 101 | "elif result.testsRun == 0 and len(result.skipped) == 0:\n" | 109 | |
| 102 | " sys.exit(5)\n" | 110 | # A parallel worker runs run_worker() below from this file: one module, or a package initializer whose `load_tests` |
| 103 | "sys.exit(0)\n") | 111 | # hook (if it has one) decides what runs in that package. It writes the same result file as CHILD_PROGRAM, plus |
| 112 | # whether the package's own modules still have to run as jobs of their own. | ||
| 113 | WORKER_PROGRAM = "import runpy, sys; sys.exit(runpy.run_path(sys.argv[1])['run_worker'](*sys.argv[2:]))" | ||
| 114 | |||
| 115 | |||
| 116 | def write_worker_result(count, include_children, code=None): | ||
| 117 | with open(os.environ["LEONIDA_TEST_COUNT"], "w", encoding="utf-8", newline="\n") as handle: | ||
| 118 | json.dump({"testsRun": count, "exitCode": code, "includeChildren": include_children}, handle) | ||
| 119 | |||
| 120 | |||
| 121 | class PackageLoader(unittest.TestLoader): | ||
| 122 | def __init__(self, pattern): | ||
| 123 | super().__init__() | ||
| 124 | self.pattern = pattern | ||
| 125 | self.include_children = False | ||
| 126 | |||
| 127 | def loadTestsFromModule(self, module, *, pattern=None): | ||
| 128 | self.include_children = getattr(module, "load_tests", None) is None | ||
| 129 | if self.include_children: | ||
| 130 | # Children can still run if a test in the initializer times out or crashes later. | ||
| 131 | write_worker_result(None, True) | ||
| 132 | return super().loadTestsFromModule(module, pattern=pattern) | ||
| 133 | # Enter through discover so a hook can call loader.discover() itself without being called recursively. | ||
| 134 | return unittest.TestLoader().discover(os.path.dirname(module.__file__), pattern=self.pattern, | ||
| 135 | top_level_dir=os.getcwd()) | ||
| 136 | |||
| 137 | |||
| 138 | def run_worker(module, pattern, verbosity): | ||
| 139 | """Run one worker's suite and report unittest's result independently of its printed output.""" | ||
| 140 | # Import the package by its name so its initializer is not also executed as pkg.__init__. | ||
| 141 | target = module.removesuffix(".__init__") | ||
| 142 | loader = PackageLoader(pattern) if target != module else unittest.TestLoader() | ||
| 143 | program = unittest.TestProgram(module=None, argv=["unittest", target], testLoader=loader, | ||
| 144 | verbosity=int(verbosity), exit=False) | ||
| 145 | result = program.result | ||
| 146 | code = 1 if not result.wasSuccessful() else 5 if not result.testsRun and not result.skipped else 0 | ||
| 147 | write_worker_result(result.testsRun, getattr(loader, "include_children", False), code) | ||
| 148 | return code | ||
| 149 | |||
| 150 | # Windows NTSTATUS codes python.exe exits with when it crashes. A file that dies this way prints nothing, so the code | ||
| 151 | # is the only clue there is (an access violation in a pure-Python test points at the machine, not at the test). | ||
| 152 | NTSTATUS_CRASHES = { | ||
| 153 | 0xC0000005: "access violation", | ||
| 154 | 0xC000001D: "illegal instruction", | ||
| 155 | 0xC0000017: "out of memory", | ||
| 156 | 0xC00000FD: "stack overflow", | ||
| 157 | 0xC0000374: "heap corruption", | ||
| 158 | 0xC0000409: "fail fast / stack buffer overrun", | ||
| 159 | } | ||
| 160 | # Known statuses that end a process without it crashing. | ||
| 161 | NTSTATUS_OTHER = { | ||
| 162 | 0xC000013A: "interrupted with Ctrl+C", | ||
| 163 | } | ||
| 164 | |||
| 165 | |||
| 166 | def describe_exit(code): | ||
| 167 | """A failed module's exit code in words: `exit code 1`, `killed by SIGSEGV (-11)` for a POSIX signal, or for a | ||
| 168 | known Windows NTSTATUS its hexadecimal value and meaning (3221225477 -> 0xC0000005, access violation). Only the | ||
| 169 | statuses in NTSTATUS_CRASHES are called a crash: a process can also exit with any 32-bit value on purpose, so an | ||
| 170 | unknown one is reported as just its value.""" | ||
| 171 | if code < 0: | ||
| 172 | try: | ||
| 173 | return f"killed by {signal.Signals(-code).name} ({code})" | ||
| 174 | except ValueError: | ||
| 175 | return f"killed by signal {-code} ({code})" | ||
| 176 | if code in NTSTATUS_CRASHES: | ||
| 177 | return f"exit code 0x{code:08X}, {NTSTATUS_CRASHES[code]} (the process crashed)" | ||
| 178 | if code in NTSTATUS_OTHER: | ||
| 179 | return f"exit code 0x{code:08X}, {NTSTATUS_OTHER[code]}" | ||
| 180 | if code > 0xFFFF: # an NTSTATUS-sized value reads better in hexadecimal | ||
| 181 | return f"exit code 0x{code:08X}" | ||
| 182 | return f"exit code {code}" | ||
| 104 | 183 | ||
| 105 | 184 | ||
| 106 | def module_path(directory, module): | 185 | def module_path(directory, module): |
| @@ -139,26 +218,82 @@ def positive_seconds(value): | |||
| 139 | return seconds | 218 | return seconds |
| 140 | 219 | ||
| 141 | 220 | ||
| 142 | def read_count(path): | 221 | def read_result(path, process_code): |
| 143 | """The number of tests the child ran, as unittest's own result object reported it.""" | 222 | """Return the effective exit code, completed test count, any diagnostic, and whether a package worker left its |
| 223 | children to run as jobs of their own (it says so before its tests run, so a crash or timeout keeps it).""" | ||
| 224 | include_children = False | ||
| 144 | try: | 225 | try: |
| 145 | with open(path, encoding="utf-8") as handle: | 226 | with open(path, encoding="utf-8") as handle: |
| 146 | return int(json.load(handle)["testsRun"]) | 227 | result = json.load(handle) |
| 228 | include_children = isinstance(result, dict) and result.get("includeChildren") is True | ||
| 229 | count, test_code = result["testsRun"], result["exitCode"] | ||
| 230 | if type(count) is not int or count < 0 or type(test_code) is not int or test_code not in (0, 1, 5): | ||
| 231 | raise ValueError("invalid unittest result") | ||
| 147 | except (OSError, ValueError, KeyError, TypeError): | 232 | except (OSError, ValueError, KeyError, TypeError): |
| 148 | # The child wrote no result: it did not finish, so no test is known to have run. | 233 | if process_code == 0: |
| 149 | return 0 | 234 | return 1, 0, "process exited without a unittest result", include_children |
| 235 | return process_code, None, "", include_children | ||
| 236 | if process_code in (0, 5) and process_code != test_code: | ||
| 237 | return (1, count, f"process exited with status {process_code} but unittest reported {test_code}", | ||
| 238 | include_children) | ||
| 239 | return process_code, count, "", include_children | ||
| 240 | |||
| 241 | |||
| 242 | def result_environment(scratch): | ||
| 243 | result_path = os.path.join(scratch, "count.json") | ||
| 244 | return result_path, dict(os.environ, LEONIDA_TEST_COUNT=result_path) | ||
| 245 | |||
| 246 | |||
| 247 | def run_discover(directory, pattern, verbose, timeout): | ||
| 248 | args = ["discover", "-s", directory, "-p", pattern, *(["-v"] if verbose else [])] | ||
| 249 | with tempfile.TemporaryDirectory() as scratch: | ||
| 250 | path, env = result_environment(scratch) | ||
| 251 | proc = subprocess.Popen([sys.executable, "-c", CHILD_PROGRAM, *args], env=env) | ||
| 252 | _register_process(proc) | ||
| 253 | try: | ||
| 254 | deadline = None if timeout is None else time.monotonic() + timeout | ||
| 255 | while True: | ||
| 256 | wait_seconds = 0.2 | ||
| 257 | if deadline is not None: | ||
| 258 | remaining = deadline - time.monotonic() | ||
| 259 | if remaining <= 0: | ||
| 260 | raise subprocess.TimeoutExpired(proc.args, timeout) | ||
| 261 | wait_seconds = min(wait_seconds, remaining) | ||
| 262 | try: | ||
| 263 | code = proc.wait(timeout=wait_seconds) | ||
| 264 | break | ||
| 265 | except subprocess.TimeoutExpired: | ||
| 266 | continue | ||
| 267 | except subprocess.TimeoutExpired: | ||
| 268 | _kill_process_tree(proc) | ||
| 269 | print(f"TIMED OUT after {timeout:g} s: unittest discover in {directory}", file=sys.stderr) | ||
| 270 | return 1 | ||
| 271 | except KeyboardInterrupt: | ||
| 272 | _kill_process_tree(proc) | ||
| 273 | try: | ||
| 274 | proc.wait(timeout=0.5) | ||
| 275 | except (subprocess.TimeoutExpired, OSError): | ||
| 276 | pass | ||
| 277 | print("interrupted", file=sys.stderr) | ||
| 278 | return 130 | ||
| 279 | except BaseException: | ||
| 280 | _kill_process_tree(proc) | ||
| 281 | raise | ||
| 282 | finally: | ||
| 283 | _unregister_process(proc) | ||
| 284 | code, _, diagnostic, _ = read_result(path, code) | ||
| 285 | if diagnostic: | ||
| 286 | print(f"unittest discover in {directory}: {diagnostic}", file=sys.stderr) | ||
| 287 | return code | ||
| 150 | 288 | ||
| 151 | 289 | ||
| 152 | def run_module(directory, module, verbose, timeout=None): | 290 | def run_module(directory, module, pattern, verbose, timeout=None): |
| 153 | """(return code, tests run, output) of `python -m unittest <target>` run from `directory`.""" | 291 | """(return code, tests run, output, whether to run the package's children) of one worker run from `directory`.""" |
| 154 | # `python -m unittest pkg.__init__` imports pkg and then runs the same file again as pkg.__init__, so a | 292 | # run_worker() runs a package by its name, not as pkg.__init__: `python -m unittest pkg.__init__` imports pkg |
| 155 | # registration in the initializer happens twice. Running the package itself imports it once; module_path() is | 293 | # and then runs the same file again, so a registration in the initializer would happen twice. |
| 156 | # still the initializer's path, so the jobs stay sorted by the file they run. | 294 | cmd = [sys.executable, "-c", WORKER_PROGRAM, os.path.abspath(__file__), module, pattern, "2" if verbose else "1"] |
| 157 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module | ||
| 158 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] | ||
| 159 | with tempfile.TemporaryDirectory() as scratch: | 295 | with tempfile.TemporaryDirectory() as scratch: |
| 160 | count_path = os.path.join(scratch, "count.json") | 296 | 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, | 297 | proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 163 | text=True, errors="replace") | 298 | text=True, errors="replace") |
| 164 | _register_process(proc) | 299 | _register_process(proc) |
| @@ -171,7 +306,8 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 171 | parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) | 306 | parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) |
| 172 | else chunk for chunk in (stdout, stderr) if chunk] | 307 | else chunk for chunk in (stdout, stderr) if chunk] |
| 173 | out = "".join(parts) | 308 | out = "".join(parts) |
| 174 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" | 309 | include_children = read_result(result_path, 1)[3] |
| 310 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n", include_children | ||
| 175 | except BaseException: | 311 | except BaseException: |
| 176 | _kill_process_tree(proc) | 312 | _kill_process_tree(proc) |
| 177 | try: | 313 | try: |
| @@ -181,13 +317,14 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 181 | raise | 317 | raise |
| 182 | finally: | 318 | finally: |
| 183 | _unregister_process(proc) | 319 | _unregister_process(proc) |
| 184 | count = read_count(count_path) | 320 | code, count, diagnostic, include_children = read_result(result_path, proc.returncode) |
| 185 | out = stdout + stderr | 321 | out = stdout + stderr |
| 186 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the | 322 | if diagnostic: |
| 187 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. | 323 | out += f"\n{diagnostic}\n" |
| 188 | if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: | 324 | # A package initializer that completed with no tests isn't a failed module. |
| 189 | return 0, 0, out | 325 | if code == 5 and count == 0 and module.endswith(".__init__"): |
| 190 | return proc.returncode, count, out | 326 | return 0, 0, out, include_children |
| 327 | return code, count or 0, out, include_children | ||
| 191 | 328 | ||
| 192 | 329 | ||
| 193 | def main(argv=None): | 330 | def main(argv=None): |
| @@ -206,53 +343,40 @@ def main(argv=None): | |||
| 206 | print(f"no {a.pattern} files in {directory}") | 343 | print(f"no {a.pattern} files in {directory}") |
| 207 | return 1 | 344 | return 1 |
| 208 | if a.jobs <= 1: | 345 | if a.jobs <= 1: |
| 209 | cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, | 346 | 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. | 347 | # 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))) | 348 | modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) |
| 240 | start, total, failed = time.monotonic(), 0, [] | 349 | # A package's modules start once its initializer has run and reported no `load_tests` hook of its own. |
| 350 | children = {} | ||
| 351 | for module in modules: | ||
| 352 | package, _, _ = module.removesuffix(".__init__").rpartition(".") | ||
| 353 | children.setdefault(package, []).append(module) | ||
| 354 | |||
| 355 | start, total, files_run, failed = time.monotonic(), 0, 0, [] | ||
| 241 | pool = concurrent.futures.ThreadPoolExecutor(a.jobs) | 356 | pool = concurrent.futures.ThreadPoolExecutor(a.jobs) |
| 242 | jobs = {} | 357 | jobs, pending = {}, set() |
| 358 | |||
| 359 | def submit(package): | ||
| 360 | for m in children.get(package, ()): | ||
| 361 | job = pool.submit(run_module, directory, m, a.pattern, a.verbose, a.timeout) | ||
| 362 | jobs[job] = m | ||
| 363 | pending.add(job) | ||
| 364 | |||
| 243 | try: | 365 | try: |
| 244 | for m in modules: | 366 | submit("") |
| 245 | jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m | ||
| 246 | pending = set(jobs) | ||
| 247 | while pending: | 367 | while pending: |
| 248 | done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED) | 368 | done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED) |
| 249 | for job in done: | 369 | for job in done: |
| 250 | pending.remove(job) | 370 | pending.remove(job) |
| 251 | code, ran, out = job.result() | 371 | code, ran, out, include_children = job.result() |
| 372 | files_run += 1 | ||
| 252 | total += ran | 373 | total += ran |
| 374 | if include_children: | ||
| 375 | submit(jobs[job].removesuffix(".__init__")) | ||
| 253 | if code: | 376 | if code: |
| 254 | failed.append(jobs[job]) | 377 | failed.append(jobs[job]) |
| 255 | print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) | 378 | silent = "" if out.strip() else "(no output: the process ended before printing anything)\n" |
| 379 | print(f"==== FAILED: {jobs[job]} ({describe_exit(code)})\n{silent}{out}", flush=True) | ||
| 256 | elif a.verbose: | 380 | elif a.verbose: |
| 257 | print(f"==== {jobs[job]}\n{out}", flush=True) | 381 | print(f"==== {jobs[job]}\n{out}", flush=True) |
| 258 | except KeyboardInterrupt: | 382 | except KeyboardInterrupt: |
| @@ -277,7 +401,7 @@ def main(argv=None): | |||
| 277 | else: | 401 | else: |
| 278 | pool.shutdown(wait=True) | 402 | pool.shutdown(wait=True) |
| 279 | took = time.monotonic() - start | 403 | took = time.monotonic() - start |
| 280 | summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" | 404 | summary = f"{files_run} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" |
| 281 | print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) | 405 | print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) |
| 282 | if total == 0: | 406 | if total == 0: |
| 283 | # An empty package initializer is a job that legitimately runs no tests; a run where every job did is not a | 407 | # An empty package initializer is a job that legitimately runs no tests; a run where every job did is not a |
diff --git a/scripts/run_standalone_tests.py b/scripts/run_standalone_tests.py new file mode 100644 index 000000000..5c6695ceb --- /dev/null +++ b/scripts/run_standalone_tests.py | |||
| @@ -0,0 +1,70 @@ | |||
| 1 | """Run selected standalone Python test files, one subprocess per file. | ||
| 2 | |||
| 3 | Read a newline-delimited list of paths from stdin and run each with python -I | ||
| 4 | from the caller's working directory. Selection stays with the CI workflow, so | ||
| 5 | pytest and standalone tests use the same predicate. Bounded parallelism keeps | ||
| 6 | each file's output together and still reports every failure at the end. | ||
| 7 | """ | ||
| 8 | import argparse | ||
| 9 | from concurrent.futures import ThreadPoolExecutor, as_completed | ||
| 10 | import subprocess | ||
| 11 | import sys | ||
| 12 | |||
| 13 | |||
| 14 | def positive_int(value): | ||
| 15 | jobs = int(value) | ||
| 16 | if jobs < 1: | ||
| 17 | raise argparse.ArgumentTypeError("jobs must be positive") | ||
| 18 | return jobs | ||
| 19 | |||
| 20 | |||
| 21 | def run_file(path): | ||
| 22 | try: | ||
| 23 | # A test (or one of its children) must not read the stream of selected paths. | ||
| 24 | result = subprocess.run([sys.executable, "-I", path], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, | ||
| 25 | stderr=subprocess.STDOUT, text=True, errors="replace") | ||
| 26 | except OSError as exc: | ||
| 27 | return 1, f"Could not start test: {exc}\n" | ||
| 28 | return result.returncode, result.stdout | ||
| 29 | |||
| 30 | |||
| 31 | def run_tests(paths, jobs): | ||
| 32 | if not paths: | ||
| 33 | print("No standalone test files selected", file=sys.stderr) | ||
| 34 | return 1 | ||
| 35 | |||
| 36 | failed = [] | ||
| 37 | with ThreadPoolExecutor(max_workers=jobs) as pool: | ||
| 38 | pending = {pool.submit(run_file, path): path for path in paths} | ||
| 39 | for future in as_completed(pending): | ||
| 40 | path = pending.pop(future) | ||
| 41 | code, output = future.result() | ||
| 42 | print(f"== {path}", flush=True) | ||
| 43 | if output: | ||
| 44 | print(output, end="" if output.endswith("\n") else "\n", flush=True) | ||
| 45 | if code: | ||
| 46 | failed.append(path) | ||
| 47 | |||
| 48 | # Match the Windows check job's file annotations, regardless of completion order. | ||
| 49 | for path in sorted(failed): | ||
| 50 | print(f"::error file={path}::{path} failed") | ||
| 51 | print(f"{len(paths)} files, {len(failed)} files failed", flush=True) | ||
| 52 | return int(bool(failed)) | ||
| 53 | |||
| 54 | |||
| 55 | def main(argv=None): | ||
| 56 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 57 | parser.add_argument("-j", "--jobs", type=positive_int, default=1, help="files at a time (default: 1)") | ||
| 58 | args = parser.parse_args(argv) | ||
| 59 | return run_tests([path for path in sys.stdin.read().splitlines() if path], args.jobs) | ||
| 60 | |||
| 61 | |||
| 62 | if __name__ == "__main__": | ||
| 63 | if sys.stdout.isatty(): | ||
| 64 | sys.stdout.reconfigure(errors="replace") | ||
| 65 | else: | ||
| 66 | # GitHub Actions reads annotations as UTF-8, including on Windows. | ||
| 67 | sys.stdout.reconfigure(encoding="utf-8", errors="replace") | ||
| 68 | # Git Bash writes its find/printf paths as UTF-8, even on Windows. | ||
| 69 | sys.stdin.reconfigure(encoding="utf-8") | ||
| 70 | sys.exit(main()) | ||
diff --git a/scripts/run_wine_session.sh b/scripts/run_wine_session.sh index 72ace4407..437e18c3c 100755 --- a/scripts/run_wine_session.sh +++ b/scripts/run_wine_session.sh | |||
| @@ -1,9 +1,23 @@ | |||
| 1 | #!/usr/bin/env bash | 1 | #!/usr/bin/env bash |
| 2 | # Run CI tests on the display that initialized their dedicated Wine prefix. | 2 | # Run CI tests on the display that initialized their dedicated Wine prefix. |
| 3 | # | ||
| 4 | # The prefix is initialized and stopped with the Wine the tests use: $WINE (default: wine), as | ||
| 5 | # run_wine_tests.py does, so Proton's or UMU-Proton's files/bin/wine also works on a host without a | ||
| 6 | # system Wine. The wineserver is $WINESERVER, else the one next to $WINE, else wineserver on PATH. | ||
| 3 | set -e | 7 | set -e |
| 4 | : "${WINEPREFIX:?Set WINEPREFIX to a dedicated test prefix}" | 8 | : "${WINEPREFIX:?Set WINEPREFIX to a dedicated test prefix}" |
| 5 | 9 | ||
| 10 | wine=${WINE:-wine} | ||
| 11 | if ! wine_path=$(command -v -- "$wine"); then | ||
| 12 | echo "run_wine_session.sh: Wine not found: $wine (set WINE to the wine executable)" >&2 | ||
| 13 | exit 127 | ||
| 14 | fi | ||
| 15 | if [[ -z ${WINESERVER:-} ]]; then | ||
| 16 | WINESERVER=$(dirname -- "$wine_path")/wineserver | ||
| 17 | [[ -x $WINESERVER ]] || WINESERVER=wineserver | ||
| 18 | fi | ||
| 19 | |||
| 6 | # Stop this prefix's Wine processes before Xvfb tears down the display. | 20 | # Stop this prefix's Wine processes before Xvfb tears down the display. |
| 7 | trap 'wineserver -k || true' EXIT | 21 | trap '"$WINESERVER" -k || true' EXIT |
| 8 | timeout 5m wineboot --init </dev/null | 22 | timeout 5m "$wine_path" wineboot --init </dev/null |
| 9 | "$@" </dev/null | 23 | "$@" </dev/null |
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py index d36011430..fa98fad31 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 | |||
| 12 | runtime/build/generated). For those, the drive of --windows-root is pointed at --root in the Wine prefix for the run | 12 | runtime/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 | ||
| 15 | Every test is reported. The exit code is 1 if a test named by --require fails or is missing, else 0: the | 15 | Every test is reported. Each name given to --require must be listed and all of its tests must pass, or the |
| 16 | others show what does and doesn't work under Wine yet without failing the job. | 16 | exit 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. |
| 18 | Relative executable paths in --wine or WINE are read from the directory where you start this runner. | 18 | Relative executable paths in --wine or WINE are read from the directory where you start this runner. |
| 19 | 19 | ||
| @@ -21,11 +21,13 @@ Each test gets WINEDLLOVERRIDES with winedbg.exe and winemenubuilder.exe disable | |||
| 21 | waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One | 21 | waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One |
| 22 | wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command, | 22 | wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command, |
| 23 | else the one on PATH) and stopped at the end, instead of a new one starting for every test. | 23 | else the one on PATH) and stopped at the end, instead of a new one starting for every test. |
| 24 | Separate runs under Wine must use different prefixes or run one after the other. | ||
| 24 | --jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and | 25 | --jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and |
| 25 | DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default). | 26 | DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default). |
| 26 | """ | 27 | """ |
| 27 | import argparse | 28 | import argparse |
| 28 | from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait | 29 | from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait |
| 30 | from contextlib import ExitStack, contextmanager | ||
| 29 | from graphlib import CycleError, TopologicalSorter | 31 | from graphlib import CycleError, TopologicalSorter |
| 30 | import json | 32 | import json |
| 31 | import math | 33 | import math |
| @@ -42,6 +44,8 @@ import threading | |||
| 42 | import time | 44 | import time |
| 43 | 45 | ||
| 44 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 46 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 47 | # subprocess uses poll on Linux, whose timeout is a signed int in milliseconds. | ||
| 48 | MAX_TIMEOUT_SECONDS = (2**31 - 1) // 1_000 | ||
| 45 | 49 | ||
| 46 | 50 | ||
| 47 | def _make_parent(path: str) -> None: | 51 | def _make_parent(path: str) -> None: |
| @@ -69,6 +73,30 @@ def map_path(arg: str, windows_root: str, root: str) -> str | None: | |||
| 69 | return None | 73 | return None |
| 70 | 74 | ||
| 71 | 75 | ||
| 76 | @contextmanager | ||
| 77 | def prefix_ownership(prefix: str): | ||
| 78 | """Keep another runner from sharing this run's temporary drive or kept server.""" | ||
| 79 | if os.name != "posix": | ||
| 80 | yield None # Native Windows only runs the synthetic harness tests. | ||
| 81 | return | ||
| 82 | |||
| 83 | import fcntl | ||
| 84 | |||
| 85 | with ExitStack() as cleanup: | ||
| 86 | try: | ||
| 87 | os.makedirs(prefix, mode=0o700, exist_ok=True) | ||
| 88 | # Lock the directory itself so aliases share one lock, with no stale lock file after an interruption. | ||
| 89 | fd = os.open(prefix, os.O_RDONLY | os.O_DIRECTORY) | ||
| 90 | cleanup.callback(os.close, fd) | ||
| 91 | fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 92 | except BlockingIOError: | ||
| 93 | yield f"a Wine test runner is already running in {prefix}; use another WINEPREFIX or retry after it ends" | ||
| 94 | except OSError as exc: | ||
| 95 | yield f"cannot lock Wine prefix {prefix}: {exc.strerror or exc}" | ||
| 96 | else: | ||
| 97 | yield None | ||
| 98 | |||
| 99 | |||
| 72 | class DriveMap: | 100 | class DriveMap: |
| 73 | """Points the drive of the Windows checkout at the Linux one inside the Wine prefix, for the run. | 101 | """Points the drive of the Windows checkout at the Linux one inside the Wine prefix, for the run. |
| 74 | 102 | ||
| @@ -76,7 +104,8 @@ class DriveMap: | |||
| 76 | <root>/runtime/build/generated/x.spv. The drive is a dosdevices link to a scratch folder holding a/Leonida/Leonida | 104 | <root>/runtime/build/generated/x.spv. The drive is a dosdevices link to a scratch folder holding a/Leonida/Leonida |
| 77 | as a link to the root. If the Windows checkout is the drive root itself, the drive links directly to the | 105 | as a link to the root. If the Windows checkout is the drive root itself, the drive links directly to the |
| 78 | Linux checkout. Temporary links and scratch folders are removed afterwards. A drive the prefix already has | 106 | Linux checkout. Temporary links and scratch folders are removed afterwards. A drive the prefix already has |
| 79 | (c:, z:, or one set up by hand) is left alone, and so is a root without an absolute drive path. | 107 | (c:, z:, or one set up by hand) is left alone, and so is a root without an absolute drive path. A prefix that |
| 108 | cannot take the link (read-only, permission denied) also leaves the drive unmapped; the note says why. | ||
| 80 | """ | 109 | """ |
| 81 | 110 | ||
| 82 | def __init__(self, windows_root: str, root: str, prefix: str): | 111 | def __init__(self, windows_root: str, root: str, prefix: str): |
| @@ -113,6 +142,10 @@ class DriveMap: | |||
| 113 | self.note = already_set | 142 | self.note = already_set |
| 114 | return self | 143 | return self |
| 115 | self.link = link | 144 | self.link = link |
| 145 | except OSError as e: | ||
| 146 | # A read-only or otherwise unwritable prefix: run the tests without the drive, and say so. | ||
| 147 | self.note = f"cannot map drive {drive}: {e.strerror or e}: the run goes on without it" | ||
| 148 | return self | ||
| 116 | finally: | 149 | finally: |
| 117 | # __exit__ only runs after a successful __enter__. | 150 | # __exit__ only runs after a successful __enter__. |
| 118 | if self.link is None and self.scratch is not None: | 151 | if self.link is None and self.scratch is not None: |
| @@ -190,6 +223,14 @@ class KeptServer: | |||
| 190 | except (OSError, subprocess.TimeoutExpired): | 223 | except (OSError, subprocess.TimeoutExpired): |
| 191 | return None | 224 | return None |
| 192 | 225 | ||
| 226 | def _warmup(self) -> None: | ||
| 227 | env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) | ||
| 228 | try: | ||
| 229 | subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, | ||
| 230 | stderr=subprocess.DEVNULL, env=env, timeout=120) | ||
| 231 | except (OSError, subprocess.TimeoutExpired): | ||
| 232 | pass # the tests start the services then, as without a kept server | ||
| 233 | |||
| 193 | def __enter__(self): | 234 | def __enter__(self): |
| 194 | if not self.command: | 235 | if not self.command: |
| 195 | self.note = "no wineserver found: each test starts its own" | 236 | self.note = "no wineserver found: each test starts its own" |
| @@ -200,18 +241,14 @@ class KeptServer: | |||
| 200 | code = self._run("-p") | 241 | code = self._run("-p") |
| 201 | else: | 242 | else: |
| 202 | self.note = "a wineserver already runs for this prefix: used and left running" | 243 | self.note = "a wineserver already runs for this prefix: used and left running" |
| 244 | self._warmup() | ||
| 203 | return self | 245 | return self |
| 204 | self.started = code == 0 | 246 | self.started = code == 0 |
| 205 | if not self.started: | 247 | if not self.started: |
| 206 | self.note = f"could not start {self.command} -p: each test starts its own server" | 248 | self.note = f"could not start {self.command} -p: each test starts its own server" |
| 207 | return self | 249 | return self |
| 208 | self.note = "wineserver kept alive for the run" | 250 | self.note = "wineserver kept alive for the run" |
| 209 | env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) | 251 | self._warmup() |
| 210 | try: | ||
| 211 | subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, | ||
| 212 | stderr=subprocess.DEVNULL, env=env, timeout=120) | ||
| 213 | except (OSError, subprocess.TimeoutExpired): | ||
| 214 | pass # the tests start the services then, as without a kept server | ||
| 215 | return self | 252 | return self |
| 216 | 253 | ||
| 217 | def __exit__(self, *exc): | 254 | def __exit__(self, *exc): |
| @@ -229,14 +266,17 @@ def properties(test: dict) -> dict: | |||
| 229 | return {p["name"]: p["value"] for p in test.get("properties", [])} | 266 | return {p["name"]: p["value"] for p in test.get("properties", [])} |
| 230 | 267 | ||
| 231 | 268 | ||
| 232 | def fixture_dependencies(tests: list[dict]) -> dict[int, tuple[int, ...]]: | 269 | def fixture_dependencies(tests: list[dict]) -> tuple[dict[int, tuple[int, ...]], dict[int, tuple[int, ...]]]: |
| 233 | """Find the listed setup tests that must finish before each fixture consumer.""" | 270 | """Return setup-success dependencies and teardown ordering dependencies.""" |
| 234 | metadata = [properties(test) for test in tests] | 271 | metadata = [properties(test) for test in tests] |
| 235 | setups: dict[str, list[int]] = {} | 272 | setups: dict[str, list[int]] = {} |
| 273 | consumers: dict[str, list[int]] = {} | ||
| 236 | for index, props in enumerate(metadata): | 274 | for index, props in enumerate(metadata): |
| 237 | for fixture in props.get("FIXTURES_SETUP", []): | 275 | for fixture in props.get("FIXTURES_SETUP", []): |
| 238 | setups.setdefault(fixture, []).append(index) | 276 | setups.setdefault(fixture, []).append(index) |
| 239 | return { | 277 | for fixture in props.get("FIXTURES_REQUIRED", []): |
| 278 | consumers.setdefault(fixture, []).append(index) | ||
| 279 | required_setups = { | ||
| 240 | index: tuple(dict.fromkeys( | 280 | index: tuple(dict.fromkeys( |
| 241 | setup | 281 | setup |
| 242 | for fixture in props.get("FIXTURES_REQUIRED", []) | 282 | for fixture in props.get("FIXTURES_REQUIRED", []) |
| @@ -245,6 +285,18 @@ def fixture_dependencies(tests: list[dict]) -> dict[int, tuple[int, ...]]: | |||
| 245 | )) | 285 | )) |
| 246 | for index, props in enumerate(metadata) | 286 | for index, props in enumerate(metadata) |
| 247 | } | 287 | } |
| 288 | # A cleanup waits for setup and consumers to finish, including failed | ||
| 289 | # or skipped tests. It must not inherit their setup-success gates. | ||
| 290 | cleanup_order = { | ||
| 291 | index: tuple(dict.fromkeys( | ||
| 292 | other | ||
| 293 | for fixture in props.get("FIXTURES_CLEANUP", []) | ||
| 294 | for other in (*setups.get(fixture, ()), *consumers.get(fixture, ())) | ||
| 295 | if other != index | ||
| 296 | )) | ||
| 297 | for index, props in enumerate(metadata) | ||
| 298 | } | ||
| 299 | return required_setups, cleanup_order | ||
| 248 | 300 | ||
| 249 | 301 | ||
| 250 | def truthy(value) -> bool: | 302 | def truthy(value) -> bool: |
| @@ -395,15 +447,13 @@ def stop_running_tests() -> None: | |||
| 395 | 447 | ||
| 396 | 448 | ||
| 397 | def positive_seconds(text: str) -> float: | 449 | def positive_seconds(text: str) -> float: |
| 398 | """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" | 450 | """Parse a positive timeout that fits the subprocess wait on all supported hosts.""" |
| 399 | try: | 451 | try: |
| 400 | value = float(text) | 452 | value = float(text) |
| 401 | except ValueError: | 453 | except ValueError: |
| 402 | raise argparse.ArgumentTypeError(f"invalid float value: {text!r}") from None | 454 | raise argparse.ArgumentTypeError(f"invalid float value: {text!r}") from None |
| 403 | if not math.isfinite(value): | 455 | if not 0 < value <= MAX_TIMEOUT_SECONDS: |
| 404 | raise argparse.ArgumentTypeError("must be a finite number") | 456 | raise argparse.ArgumentTypeError(f"must be positive and no greater than {MAX_TIMEOUT_SECONDS} seconds") |
| 405 | if value <= 0: | ||
| 406 | raise argparse.ArgumentTypeError("must be greater than 0") | ||
| 407 | return value | 457 | return value |
| 408 | 458 | ||
| 409 | 459 | ||
| @@ -435,7 +485,7 @@ def valid_test_property(entry) -> bool: | |||
| 435 | name, value = entry["name"], entry["value"] | 485 | name, value = entry["name"], entry["value"] |
| 436 | if name == "WORKING_DIRECTORY": | 486 | if name == "WORKING_DIRECTORY": |
| 437 | return isinstance(value, str) and "\0" not in value | 487 | return isinstance(value, str) and "\0" not in value |
| 438 | if name in ("PASS_REGULAR_EXPRESSION", "FAIL_REGULAR_EXPRESSION", "SKIP_REGULAR_EXPRESSION"): | 488 | if name in ("PASS_REGULAR_EXPRESSION", "FAIL_REGULAR_EXPRESSION", "SKIP_REGULAR_EXPRESSION", "RESOURCE_LOCK"): |
| 439 | return isinstance(value, str) or (isinstance(value, list) and all(isinstance(p, str) for p in value)) | 489 | return isinstance(value, str) or (isinstance(value, list) and all(isinstance(p, str) for p in value)) |
| 440 | return True | 490 | return True |
| 441 | 491 | ||
| @@ -515,9 +565,10 @@ def main() -> int: | |||
| 515 | ap.add_argument("--root", type=os.path.abspath, default=ROOT, help="the Linux checkout (default: this repository)") | 565 | 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"), | 566 | ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"), |
| 517 | help="Wine command (default: $WINE or wine)") | 567 | help="Wine command (default: $WINE or wine)") |
| 518 | ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") | 568 | 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, | 569 | ap.add_argument("--timeout", type=positive_seconds, default=120.0, |
| 520 | help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") | 570 | help=f"maximum seconds per test (default 120, upper limit {MAX_TIMEOUT_SECONDS}). " |
| 571 | "A shorter CTest TIMEOUT applies.") | ||
| 521 | ap.add_argument("--jobs", type=positive_int, default=1, | 572 | ap.add_argument("--jobs", type=positive_int, default=1, |
| 522 | help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)") | 573 | help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)") |
| 523 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") | 574 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") |
| @@ -529,12 +580,13 @@ def main() -> int: | |||
| 529 | return 2 | 580 | return 2 |
| 530 | names = [test.get("name", "?") for test in tests] | 581 | names = [test.get("name", "?") for test in tests] |
| 531 | indices = {name: index for index, name in enumerate(names)} | 582 | indices = {name: index for index, name in enumerate(names)} |
| 532 | setups = fixture_dependencies(tests) | 583 | setups, cleanup_order = fixture_dependencies(tests) |
| 533 | sorter = TopologicalSorter(setups) | 584 | sorter = TopologicalSorter(setups) |
| 534 | before = {index: set(setups[index]) for index in range(len(tests))} | 585 | before = {index: set(setups[index]) for index in range(len(tests))} |
| 535 | for index, test in enumerate(tests): | 586 | for index, test in enumerate(tests): |
| 536 | # DEPENDS controls order. Only failed fixture setups block a consumer. | 587 | # DEPENDS controls order. Only failed fixture setups block a consumer. |
| 537 | depends = [indices[name] for name in properties(test).get("DEPENDS", []) if name in indices] | 588 | depends = [indices[name] for name in properties(test).get("DEPENDS", []) if name in indices] |
| 589 | depends.extend(cleanup_order[index]) | ||
| 538 | sorter.add(index, *depends) | 590 | sorter.add(index, *depends) |
| 539 | before[index].update(depends) | 591 | before[index].update(depends) |
| 540 | try: | 592 | try: |
| @@ -546,7 +598,6 @@ def main() -> int: | |||
| 546 | # Each test starts in its own CTest working directory. Keep bare commands on PATH. | 598 | # 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]): | 599 | if os.path.dirname(wine[0]) and not os.path.isabs(wine[0]): |
| 548 | wine[0] = os.path.join(os.getcwd(), wine[0]) | 600 | wine[0] = os.path.join(os.getcwd(), wine[0]) |
| 549 | results = {} | ||
| 550 | results_by_index: dict[int, str] = {} | 601 | results_by_index: dict[int, str] = {} |
| 551 | prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") | 602 | prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") |
| 552 | outcomes: dict[int, tuple[str, str]] = {} | 603 | outcomes: dict[int, tuple[str, str]] = {} |
| @@ -557,13 +608,18 @@ def main() -> int: | |||
| 557 | 608 | ||
| 558 | def report(index: int) -> None: | 609 | def report(index: int) -> None: |
| 559 | status, detail = outcomes[index] | 610 | status, detail = outcomes[index] |
| 560 | results[names[index]] = status | ||
| 561 | print(f"[{status.upper()}] {names[index]}", flush=True) | 611 | print(f"[{status.upper()}] {names[index]}", flush=True) |
| 562 | if status != "pass": | 612 | if status != "pass": |
| 563 | for line in detail.rstrip().splitlines()[-40:]: | 613 | for line in detail.rstrip().splitlines()[-40:]: |
| 564 | print(f" {line}") | 614 | print(f" {line}") |
| 565 | 615 | ||
| 566 | with DriveMap(args.windows_root, args.root, prefix) as drive, KeptServer(find_wineserver(wine), wine) as server: | 616 | with ExitStack() as run: |
| 617 | lock_error = run.enter_context(prefix_ownership(prefix)) | ||
| 618 | if lock_error: | ||
| 619 | print(f"ERROR: {lock_error}", file=sys.stderr) | ||
| 620 | return 2 | ||
| 621 | drive = run.enter_context(DriveMap(args.windows_root, args.root, prefix)) | ||
| 622 | server = run.enter_context(KeptServer(find_wineserver(wine), wine)) | ||
| 567 | print(drive.note, flush=True) | 623 | print(drive.note, flush=True) |
| 568 | print(server.note, flush=True) | 624 | print(server.note, flush=True) |
| 569 | if args.jobs == 1: | 625 | if args.jobs == 1: |
| @@ -574,11 +630,12 @@ def main() -> int: | |||
| 574 | else: | 630 | else: |
| 575 | run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) | 631 | run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) |
| 576 | 632 | ||
| 577 | missing = list(dict.fromkeys(n for n in args.require if n not in results)) | 633 | 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"] | 634 | 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")} | 635 | failed_required = [n for n in args.require if n not in indices or n in nonpassing_names] |
| 636 | 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 " | 637 | print(f"\n{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped under Wine " |
| 581 | f"({len(results)} tests)") | 638 | f"({len(results_by_index)} tests)") |
| 582 | for n in missing: | 639 | for n in missing: |
| 583 | print(f"required test not listed by the Windows build: {n}") | 640 | print(f"required test not listed by the Windows build: {n}") |
| 584 | if failed_required: | 641 | if failed_required: |
| @@ -591,7 +648,8 @@ def main() -> int: | |||
| 591 | f.write(f"### Windows tests under {args.label or 'Wine'}\n\n") | 648 | 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") | 649 | f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n") |
| 593 | f.write("| Test | Result | Required |\n|---|---|---|\n") | 650 | f.write("| Test | Result | Required |\n|---|---|---|\n") |
| 594 | for name, status in results.items(): | 651 | for index in order: |
| 652 | name, status = names[index], results_by_index[index] | ||
| 595 | f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n") | 653 | f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n") |
| 596 | for name in missing: | 654 | for name in missing: |
| 597 | # The job fails on these, so the table must name them, not only the log. | 655 | # 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 | ||
| 57 | REQUIRED = ("name", "stage", "statistic", "value") | 58 | REQUIRED = ("name", "stage", "statistic", "value") |
| 58 | 59 | ||
| 59 | 60 | ||
| 61 | def _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 | |||
| 60 | def load_stats(path): | 70 | def 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 | ||
| 83 | def number(raw): | 95 | def 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): | |||
| 149 | USAGE = "usage: shader_stats.py <stats.csv> <disasm dir> [--details]" | 163 | USAGE = "usage: shader_stats.py <stats.csv> <disasm dir> [--details]" |
| 150 | 164 | ||
| 151 | 165 | ||
| 152 | def main(): | 166 | def 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 | |||
| 4 | Validates prerequisites, compiles source trees, enforces clean-room boundaries, | ||
| 5 | and executes fast synthetic smoke tests on Windows, Linux, and macOS without game files. | ||
| 6 | """ | ||
| 7 | |||
| 8 | from __future__ import annotations | ||
| 9 | |||
| 10 | import argparse | ||
| 11 | import compileall | ||
| 12 | import contextlib | ||
| 13 | import io | ||
| 14 | import json | ||
| 15 | import os | ||
| 16 | from pathlib import Path | ||
| 17 | import platform | ||
| 18 | import shutil | ||
| 19 | import subprocess | ||
| 20 | import sys | ||
| 21 | import time | ||
| 22 | |||
| 23 | ROOT = Path(__file__).resolve().parents[1] | ||
| 24 | MIN_PYTHON_VERSION = (3, 10) | ||
| 25 | |||
| 26 | |||
| 27 | def 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 | |||
| 68 | def _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 | |||
| 92 | def _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 | |||
| 103 | def 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 | |||
| 225 | def 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 | |||
| 327 | if __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. | ||
| 9 | param( | ||
| 10 | [ValidateSet('query', 'on', 'off')][string]$State = 'query', | ||
| 11 | [string]$Exe = 'leonida_sm.exe' | ||
| 12 | ) | ||
| 13 | Add-Type -TypeDefinition @' | ||
| 14 | using System; | ||
| 15 | using System.Runtime.InteropServices; | ||
| 16 | using System.Text; | ||
| 17 | |||
| 18 | public 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' } } | ||
| 104 | if ($null -eq $value) { "Smooth Motion for ${Exe}: $was" } else { "Smooth Motion for ${Exe}: $was -> $State (from the next start)" } | ||
diff --git a/scripts/vs_input_survey.py b/scripts/vs_input_survey.py index 0c2326309..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 | """ |
| 19 | import argparse | 19 | import argparse |
| 20 | import json | 20 | import json |
| 21 | import ntpath | ||
| 21 | import os | 22 | import os |
| 23 | import posixpath | ||
| 22 | import re | 24 | import re |
| 23 | import sys | 25 | import sys |
| 26 | import tempfile | ||
| 24 | from collections import Counter | 27 | from collections import Counter |
| 25 | 28 | ||
| 26 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 29 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 27 | sys.path.insert(0, os.path.join(ROOT, "tools")) | 30 | sys.path.insert(0, os.path.join(ROOT, "tools")) |
| 31 | from file_mode import published_mode # noqa: E402 | ||
| 32 | from replace_retry import replace as replace_retry # noqa: E402 | ||
| 33 | from report_paths import same_report_path # noqa: E402 | ||
| 28 | import shader_ir # noqa: E402 | 34 | import shader_ir # noqa: E402 |
| 29 | from shader_meta import SGPR_RMW # noqa: E402 | 35 | from shader_meta import SGPR_RMW # noqa: E402 |
| 30 | 36 | ||
| @@ -84,7 +90,10 @@ def read_before_write(insns): | |||
| 84 | elif op == "v_swap_b32" and len(args) >= 2: | 90 | elif op == "v_swap_b32" and len(args) >= 2: |
| 85 | dsts, srcs = args[:2], args[:2] | 91 | dsts, srcs = args[:2], args[:2] |
| 86 | elif (op.startswith("v_") and ("_co_" in op or op in DUAL_DST_VALU) | 92 | elif (op.startswith("v_") and ("_co_" in op or op in DUAL_DST_VALU) |
| 87 | and len(args) >= 2 and args[1]["k"] in ("sgpr", "special", "slist")): | 93 | and len(args) >= 2 and args[1]["k"] in ("sgpr", "special", "slist") |
| 94 | # the short form v_add_co_ci_u32 vD, src0, src1 (also sub/subrev): carry out and in are an | ||
| 95 | # implicit VCC, and args[1] is src0, a read | ||
| 96 | and not (op.endswith("_co_ci_u32") and len(args) == 3)): | ||
| 88 | dsts, srcs = args[:2], args[2:] # vdst + scalar carry/scale-out dst | 97 | dsts, srcs = args[:2], args[2:] # vdst + scalar carry/scale-out dst |
| 89 | else: | 98 | else: |
| 90 | dst_read = ( | 99 | dst_read = ( |
| @@ -109,21 +118,69 @@ def read_before_write(insns): | |||
| 109 | return read_s, read_v | 118 | return read_s, read_v |
| 110 | 119 | ||
| 111 | 120 | ||
| 112 | def survey(dxbc_dir): | 121 | def _safe_shader_stem(value): |
| 113 | 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 | |||
| 141 | def _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 | |||
| 169 | def _survey_detail(dxbc_dir): | ||
| 170 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8-sig") as f: | ||
| 114 | index = json.load(f) | 171 | index = json.load(f) |
| 115 | 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): |
| 116 | raise ValueError("index.json is not a list of shader entries") | 173 | raise ValueError("index.json is not a list of shader entries") |
| 117 | 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"] |
| 118 | raise ValueError("index.json has a vertex shader entry without a string file") | ||
| 119 | names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"] | ||
| 120 | markers, vgprs, families = Counter(), Counter(), Counter() | 175 | markers, vgprs, families = Counter(), Counter(), Counter() |
| 121 | missing = 0 | 176 | missing = 0 |
| 177 | disasm_paths = [] | ||
| 122 | for n in names: | 178 | for n in names: |
| 123 | path = os.path.join(dxbc_dir, "disasm", n + ".s") | 179 | path = os.path.join(dxbc_dir, "disasm", n + ".s") |
| 124 | if not os.path.isfile(path): | 180 | if not os.path.isfile(path): |
| 125 | missing += 1 | 181 | missing += 1 |
| 126 | continue | 182 | continue |
| 183 | disasm_paths.append(path) | ||
| 127 | with open(path, encoding="utf-8", errors="replace") as f: | 184 | with open(path, encoding="utf-8", errors="replace") as f: |
| 128 | text = f.read() | 185 | text = f.read() |
| 129 | _, read_v = read_before_write(shader_ir.parse_file(path)["insns"]) | 186 | _, read_v = read_before_write(shader_ir.parse_file(path)["insns"]) |
| @@ -143,25 +200,39 @@ def survey(dxbc_dir): | |||
| 143 | 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 |
| 144 | else: | 201 | else: |
| 145 | families["reads neither v0 nor a fetch call"] += 1 | 202 | families["reads neither v0 nor a fetch call"] += 1 |
| 146 | return {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers), | 203 | result = {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers), |
| 147 | "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:]))), |
| 148 | "families": dict(families)} | 205 | "families": dict(families)} |
| 206 | return result, disasm_paths | ||
| 207 | |||
| 208 | |||
| 209 | def survey(dxbc_dir): | ||
| 210 | return _survey_detail(dxbc_dir)[0] | ||
| 149 | 211 | ||
| 150 | 212 | ||
| 151 | def main(): | 213 | def main(argv=None): |
| 152 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | 214 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 153 | 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") |
| 154 | ap.add_argument("--json", help="also write the counts as JSON") | 216 | ap.add_argument("--json", help="also write the counts as JSON") |
| 155 | a = ap.parse_args() | 217 | a = ap.parse_args(argv) |
| 156 | index_path = os.path.join(a.dxbc, "index.json") | 218 | index_path = os.path.join(a.dxbc, "index.json") |
| 157 | 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: |
| 158 | print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr) | 220 | if os.path.isdir(a.json): |
| 159 | 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 | ||
| 160 | try: | 226 | try: |
| 161 | r = survey(a.dxbc) | 227 | r, disasm_paths = _survey_detail(a.dxbc) |
| 162 | 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 |
| 163 | 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) |
| 164 | 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 | ||
| 165 | m = r["markers"] | 236 | m = r["markers"] |
| 166 | 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)") |
| 167 | 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)}") |
| @@ -172,8 +243,7 @@ def main(): | |||
| 172 | 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") |
| 173 | if a.json: | 244 | if a.json: |
| 174 | try: | 245 | try: |
| 175 | with open(a.json, "w", encoding="utf-8", newline="\n") as f: | 246 | _write_json_atomic(a.json, r) |
| 176 | json.dump(r, f, indent=1) | ||
| 177 | except OSError as e: | 247 | except OSError as e: |
| 178 | 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) |
| 179 | return 2 | 249 | return 2 |
diff --git a/scripts/vs_layout_census.py b/scripts/vs_layout_census.py index 1d7174e77..8ba9b8a14 100644 --- a/scripts/vs_layout_census.py +++ b/scripts/vs_layout_census.py | |||
| @@ -23,13 +23,16 @@ import json | |||
| 23 | import os | 23 | import os |
| 24 | import re | 24 | import re |
| 25 | import sys | 25 | import sys |
| 26 | import tempfile | ||
| 26 | from collections import Counter, defaultdict | 27 | from collections import Counter, defaultdict |
| 27 | 28 | ||
| 28 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 29 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 29 | sys.path.insert(0, os.path.join(ROOT, "tools")) | 30 | sys.path.insert(0, os.path.join(ROOT, "tools")) |
| 30 | sys.path.insert(0, os.path.join(ROOT, "scripts")) | 31 | sys.path.insert(0, os.path.join(ROOT, "scripts")) |
| 32 | from file_mode import published_mode # noqa: E402 | ||
| 31 | import fssm_unpack # noqa: E402 | 33 | import fssm_unpack # noqa: E402 |
| 32 | import pal_stages # noqa: E402 | 34 | import pal_stages # noqa: E402 |
| 35 | import replace_retry # noqa: E402 | ||
| 33 | import shader_disasm # noqa: E402 | 36 | import shader_disasm # noqa: E402 |
| 34 | from report_paths import same_report_path # noqa: E402 | 37 | from report_paths import same_report_path # noqa: E402 |
| 35 | import shader_ir # noqa: E402 | 38 | import shader_ir # noqa: E402 |
| @@ -90,8 +93,11 @@ def payloads_of(dxbc_path): | |||
| 90 | 93 | ||
| 91 | def load_index(dxbc_dir): | 94 | def load_index(dxbc_dir): |
| 92 | """(stage by stem, stems in index order) from <dxbc>/index.json.""" | 95 | """(stage by stem, stems in index order) from <dxbc>/index.json.""" |
| 93 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: | 96 | try: |
| 94 | index = json.load(f) | 97 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8-sig") as f: |
| 98 | index = json.load(f) | ||
| 99 | except RecursionError: | ||
| 100 | raise ValueError("invalid JSON: recursion limit exceeded") from None | ||
| 95 | if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): | 101 | if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): |
| 96 | raise ValueError("index.json is not a list of shader entries") | 102 | raise ValueError("index.json is not a list of shader entries") |
| 97 | stages = {} | 103 | stages = {} |
| @@ -111,7 +117,7 @@ def input_paths(dxbc_dir): | |||
| 111 | paths = [os.path.join(dxbc_dir, "index.json")] | 117 | paths = [os.path.join(dxbc_dir, "index.json")] |
| 112 | try: | 118 | try: |
| 113 | _stages, names = load_index(dxbc_dir) | 119 | _stages, names = load_index(dxbc_dir) |
| 114 | except (OSError, ValueError): | 120 | except (OSError, ValueError, RecursionError): |
| 115 | return paths | 121 | return paths |
| 116 | for name in names: | 122 | for name in names: |
| 117 | paths.append(os.path.join(dxbc_dir, name + ".dxbc")) | 123 | paths.append(os.path.join(dxbc_dir, name + ".dxbc")) |
| @@ -121,6 +127,8 @@ def input_paths(dxbc_dir): | |||
| 121 | 127 | ||
| 122 | def survey(dxbc_dir, disasm_fn=None, limit=None): | 128 | def survey(dxbc_dir, disasm_fn=None, limit=None): |
| 123 | """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" | 129 | """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" |
| 130 | if limit is not None and limit < 1: | ||
| 131 | raise ValueError("limit must be at least 1") | ||
| 124 | stages, names = load_index(dxbc_dir) | 132 | stages, names = load_index(dxbc_dir) |
| 125 | if limit is not None: | 133 | if limit is not None: |
| 126 | names = names[:limit] | 134 | names = names[:limit] |
| @@ -199,16 +207,45 @@ def survey(dxbc_dir, disasm_fn=None, limit=None): | |||
| 199 | } | 207 | } |
| 200 | 208 | ||
| 201 | 209 | ||
| 210 | def _write_json_atomic(out_path, payload): | ||
| 211 | dest = os.path.realpath(out_path) | ||
| 212 | dest_dir = os.path.dirname(dest) or "." | ||
| 213 | os.makedirs(dest_dir, exist_ok=True) | ||
| 214 | fd, temp = tempfile.mkstemp(dir=dest_dir, prefix=".vs-layout-", suffix=".tmp") | ||
| 215 | try: | ||
| 216 | try: | ||
| 217 | f = os.fdopen(fd, "w", encoding="utf-8", newline="\n") | ||
| 218 | except BaseException: | ||
| 219 | os.close(fd) | ||
| 220 | raise | ||
| 221 | with f: | ||
| 222 | json.dump(payload, f, indent=1) | ||
| 223 | f.write("\n") | ||
| 224 | f.flush() | ||
| 225 | os.fsync(f.fileno()) | ||
| 226 | os.chmod(temp, published_mode(dest)) | ||
| 227 | replace_retry.replace(temp, dest) | ||
| 228 | except BaseException: | ||
| 229 | try: | ||
| 230 | os.chmod(temp, 0o600) | ||
| 231 | os.unlink(temp) | ||
| 232 | except OSError: | ||
| 233 | pass | ||
| 234 | raise | ||
| 235 | |||
| 236 | |||
| 202 | def main(argv=None): | 237 | def main(argv=None): |
| 203 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | 238 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 204 | ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py") | 239 | ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py") |
| 205 | ap.add_argument("--json", help="also write the counts as JSON") | 240 | ap.add_argument("--json", help="also write the counts as JSON") |
| 206 | ap.add_argument("--limit", type=int, help="stop after this many containers (index order)") | 241 | ap.add_argument("--limit", type=int, help="stop after this many containers (index order)") |
| 207 | a = ap.parse_args(argv) | 242 | a = ap.parse_args(argv) |
| 243 | if a.limit is not None and a.limit < 1: | ||
| 244 | ap.error("--limit must be at least 1") | ||
| 208 | index_path = os.path.join(a.dxbc, "index.json") | 245 | index_path = os.path.join(a.dxbc, "index.json") |
| 209 | if a.json: | 246 | if a.json: |
| 210 | # Refuse before survey(): it reads the whole corpus and runs llvm-mc for every unlisted payload. | 247 | # Refuse before survey(): it reads the whole corpus and runs llvm-mc for every unlisted payload. |
| 211 | if os.path.isdir(a.json): | 248 | if os.path.isdir(a.json) or a.json.endswith(("/", "\\")): |
| 212 | print(f"vs_layout_census: error: --json {a.json} is a directory, not a JSON file", file=sys.stderr) | 249 | print(f"vs_layout_census: error: --json {a.json} is a directory, not a JSON file", file=sys.stderr) |
| 213 | return 2 | 250 | return 2 |
| 214 | for path in input_paths(a.dxbc): | 251 | for path in input_paths(a.dxbc): |
| @@ -217,7 +254,7 @@ def main(argv=None): | |||
| 217 | return 2 | 254 | return 2 |
| 218 | try: | 255 | try: |
| 219 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) | 256 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) |
| 220 | except (OSError, ValueError) as e: | 257 | except (OSError, ValueError, RecursionError) as e: |
| 221 | print(f"vs_layout_census: error: cannot read {index_path}: {e}", file=sys.stderr) | 258 | print(f"vs_layout_census: error: cannot read {index_path}: {e}", file=sys.stderr) |
| 222 | return 2 | 259 | return 2 |
| 223 | print(f"{r['containers']} containers, {r['payloads']} payloads " | 260 | print(f"{r['containers']} containers, {r['payloads']} payloads " |
| @@ -231,8 +268,7 @@ def main(argv=None): | |||
| 231 | f"unlisted payloads disassembled {r['disassembled_unlisted']}") | 268 | f"unlisted payloads disassembled {r['disassembled_unlisted']}") |
| 232 | if a.json: | 269 | if a.json: |
| 233 | try: | 270 | try: |
| 234 | with open(a.json, "w", encoding="utf-8", newline="\n") as f: | 271 | _write_json_atomic(a.json, r) |
| 235 | json.dump(r, f, indent=1) | ||
| 236 | except OSError as e: | 272 | except OSError as e: |
| 237 | print(f"vs_layout_census: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) | 273 | print(f"vs_layout_census: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) |
| 238 | return 2 | 274 | return 2 |
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index 92121a211..1d3328ec8 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md | |||
| @@ -25,6 +25,21 @@ Set `LEONIDA_GAME_DIR`, `LEONIDA_SHADERS` (and `GTA6RT`, `LEONIDA_RUNS` if you u | |||
| 25 | profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this | 25 | profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this |
| 26 | checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`. | 26 | checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`. |
| 27 | The script refuses an output folder inside the repository. | 27 | The script refuses an output folder inside the repository. |
| 28 | The runtime starts in `<out>\work_<name>`, where driver artifacts such as `ucode.elf` can land. Relative path | ||
| 29 | parameters are resolved from the caller's PowerShell location. Use absolute paths for additional runtime switches | ||
| 30 | supplied through `-ExtraArgs` or custom environment variables. | ||
| 31 | |||
| 32 | ### Private crash diagnostics | ||
| 33 | |||
| 34 | Build the `gta6rt_crash_monitor` target in the same x64 Windows build as the runtime, then add | ||
| 35 | `-CrashDump` to your usual boot command. Each invocation reserves a fresh directory under `-OutDir`. | ||
| 36 | An unhandled exception writes `crash.dmp` and `stack.txt` for the faulting thread. An explicit nonzero | ||
| 37 | exit captures the last thread at process exit, which may already be in shutdown. Handled exceptions, | ||
| 38 | successful exits and the boot time limit produce no crash report. | ||
| 39 | |||
| 40 | Keep matching PDBs beside the runtime for local symbol names. Frames without symbols can appear as | ||
| 41 | addresses, and unwinding can stop at manually mapped code. Dumps can contain process memory and stacks | ||
| 42 | can identify private inputs. Keep both on your machine. Share only the outcome, error class and counts. | ||
| 28 | 43 | ||
| 29 | ## What it sets | 44 | ## What it sets |
| 30 | 45 | ||
| @@ -38,8 +53,9 @@ Only when your shell has not set them already (`-DryRun` prints the final list): | |||
| 38 | | `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | | 53 | | `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | |
| 39 | | `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup | | 54 | | `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 | | 55 | | `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\pipeline-cache` | one warmed cache shared by every build you boot | |
| 56 | | `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, `LEONIDA_DEVICE_FAULT=1` puts the diagnostics config into the journal's file names, so the pre-compile and the boot have to agree on it; this script sets `2`, which names them as a pre-compile without the variable does, except with `LEONIDA_AFTERMATH=1` (see `LEONIDA_DEVICE_FAULT`) | | ||
| 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 | | 57 | | `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 | | 58 | | `LEONIDA_DEVICE_FAULT` | `2` | on device loss: `VK_EXT_device_fault` info, NVIDIA checkpoints, last replay steps, without NVIDIA's diagnostics config, so a pre-compiled compute journal still matches (that config is part of every compute journal file name). `1` adds the config (shader debug info in a crash dump); `LEONIDA_DEVICE_FAULT=1` turns it on for a boot, and the script uses `1` by itself when `LEONIDA_AFTERMATH=1` and you did not set this variable. Under `2`, "NVIDIA diagnostics config unavailable" in the runtime's `[rt] device-fault: enabled` line means it was not requested, not a driver problem | |
| 43 | | `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | | 59 | | `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | |
| 44 | | `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | | 60 | | `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | |
| 45 | | `DISABLE_RTSS_LAYER`, `DISABLE_VULKAN_OBS_CAPTURE` | `1` | keep third-party Vulkan overlay layers out of the process | | 61 | | `DISABLE_RTSS_LAYER`, `DISABLE_VULKAN_OBS_CAPTURE` | `1` | keep third-party Vulkan overlay layers out of the process | |
| @@ -68,9 +84,17 @@ faults: none | |||
| 68 | frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00 | 84 | frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00 |
| 69 | ``` | 85 | ``` |
| 70 | 86 | ||
| 71 | `-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The digest holds counts and | 87 | `-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The `faults` row reports whether |
| 72 | states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game | 88 | the log recorded device loss and counts Vulkan address records by type (for example, `WRITE_INVALID=2`). |
| 73 | and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data"). | 89 | Several records can describe one loss. A driver can also report loss without any address records. |
| 90 | Share counts and states on the board. Keep paths, logs, traces, captures and dumps on your machine | ||
| 91 | ([AGENTS.md](../../AGENTS.md), "No game data"). | ||
| 92 | |||
| 93 | When the log contains a device loss, a fault query outcome or checkpoint records, `fault context` shows the first | ||
| 94 | recognized Vulkan API that reported loss and the first observed fault query outcome. An unrecognized operation is | ||
| 95 | shown as `other`. A missing outcome is `not observed`. The queue count includes queries that returned zero | ||
| 96 | checkpoints. `reported` sums the driver counts from the queue headers. `decoded` and `unrecognized` count the | ||
| 97 | two kinds of printed stage records, so a truncated log can have fewer printed records than reported checkpoints. | ||
| 74 | 98 | ||
| 75 | How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing | 99 | How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing |
| 76 | screen waiting for A), `d` after A. | 100 | screen waiting for A), `d` after A. |
| @@ -83,6 +107,10 @@ session=?`. A `LEONIDA_PEEK` of your own still works for the log, but the digest | |||
| 83 | variables name. `docs/linux_proton.md` (the same stages apply natively) | 107 | variables name. `docs/linux_proton.md` (the same stages apply natively) |
| 84 | section 2 has the healthy sequence with times and section 3 "which blank do you have". | 108 | section 2 has the healthy sequence with times and section 3 "which blank do you have". |
| 85 | 109 | ||
| 110 | To pair scripted presses with state changes after a run, use `python -I tools/stage_timeline.py LOG` with the same | ||
| 111 | two environment variables. For a saved log, `--game-state-rva` and `--session-state-rva` override them. If the log | ||
| 112 | also records the loading-screen state, pass its hex RVA with `--load-state-rva` to see when the screen ended. | ||
| 113 | |||
| 86 | ## One game at a time | 114 | ## One game at a time |
| 87 | 115 | ||
| 88 | The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe` | 116 | The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe` |
| @@ -98,3 +126,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 | | 126 | | `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 | 127 | ||
| 100 | Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). | 128 | Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). |
| 129 | |||
| 130 | ## Recover a stack from a manually mapped image | ||
| 131 | |||
| 132 | When the exception stack stops inside the mapped executable, run `mapped_stack.py` on the existing | ||
| 133 | private dump. Supply the exact PE from the crashing build and an x64 CDB from Debugging Tools for | ||
| 134 | Windows. If CDB is on your PATH, omit `--cdb`. The optional `--symbols` takes one local directory | ||
| 135 | containing the matching runtime images and PDBs. | ||
| 136 | |||
| 137 | ```powershell | ||
| 138 | py -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" | ||
| 139 | ``` | ||
| 140 | |||
| 141 | The command derives the mapping base, including a relocated base, by locating a unique captured | ||
| 142 | instruction window in an executable section of the supplied PE. It checks for a file-backed x64 | ||
| 143 | unwind entry at the exception RIP and compares captured bytes from the first header page and that | ||
| 144 | function's unwind metadata when available. | ||
| 145 | A small dump can establish a local code match only. Use the original image even if another build | ||
| 146 | has the same function. Exit-only snapshots, faults outside the supplied image, leaf functions | ||
| 147 | without unwind entries, and missing, patched or ambiguous instruction windows cannot establish | ||
| 148 | this stack. | ||
| 149 | |||
| 150 | CDB reads the exception context and uses the disk image's unwind data to recover callers. The | ||
| 151 | script makes a temporary copy of the PE beside the dump under the debugger alias `leonida_mapped`. | ||
| 152 | It disables network symbols and writes private frame rows to a new `mapped-stack.txt` beside the | ||
| 153 | dump. Use `--output` for a different new file. A successful walk recovers at least one caller and | ||
| 154 | can stop when later stack memory or module information is missing. Keep dumps and reports outside | ||
| 155 | the checkout and share only the outcome and frame count. | ||
| 156 | |||
| 157 | Run the synthetic regression tests with `py -3 -I tests\test_mapped_stack.py`. To include the | ||
| 158 | native 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 7863054b3..98be96e92 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 | |||
| @@ -50,7 +50,8 @@ | |||
| 50 | 50 | ||
| 51 | .PARAMETER InputScript | 51 | .PARAMETER InputScript |
| 52 | LEONIDA_INPUT_SCRIPT: timed pad presses, seconds since the pad's first poll (button@seconds, comma-separated; | 52 | LEONIDA_INPUT_SCRIPT: timed pad presses, seconds since the pad's first poll (button@seconds, comma-separated; |
| 53 | buttons a b x y start back lb rb up down left right). Sets LEONIDA_KEYBOARD_PAD=always. Builds older than | 53 | buttons a b x y start back lb rb up down left right). Each press is held 300 ms; button@seconds:hold holds it |
| 54 | longer, e.g. b@1100:3 for a title that reads its pad only every few seconds. Sets LEONIDA_KEYBOARD_PAD=always. Builds older than | ||
| 54 | main @ 8146ef690 ignore a script longer than 63 characters. Default 'a@45,a@60,a@75,a@90'. | 55 | main @ 8146ef690 ignore a script longer than 63 characters. Default 'a@45,a@60,a@75,a@90'. |
| 55 | 56 | ||
| 56 | .PARAMETER NoInput | 57 | .PARAMETER NoInput |
| @@ -75,6 +76,9 @@ | |||
| 75 | .PARAMETER ExtraArgs | 76 | .PARAMETER ExtraArgs |
| 76 | More gta6rt arguments, appended after the standard ones. | 77 | More gta6rt arguments, appended after the standard ones. |
| 77 | 78 | ||
| 79 | .PARAMETER FirstRunUi | ||
| 80 | Launch with the offline first-run UI profile instead of the generic runtime profile. | ||
| 81 | |||
| 78 | .PARAMETER Python | 82 | .PARAMETER Python |
| 79 | Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3. | 83 | Python 3.12+ used for tools/boot_trace.py. Default: python, else py -3. |
| 80 | 84 | ||
| @@ -87,6 +91,9 @@ | |||
| 87 | .PARAMETER DryRun | 91 | .PARAMETER DryRun |
| 88 | Print the environment and the command line, check the paths, launch nothing. | 92 | Print the environment and the command line, check the paths, launch nothing. |
| 89 | 93 | ||
| 94 | .PARAMETER CrashDump | ||
| 95 | Run under the native Windows crash monitor. A crash dump and stack go into a fresh private folder under -OutDir. | ||
| 96 | |||
| 90 | .PARAMETER DigestOnly | 97 | .PARAMETER DigestOnly |
| 91 | Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir). | 98 | Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir). |
| 92 | 99 | ||
| @@ -116,8 +123,10 @@ param( | |||
| 116 | [string]$Stacks = "", | 123 | [string]$Stacks = "", |
| 117 | [hashtable]$SetEnv = @{}, | 124 | [hashtable]$SetEnv = @{}, |
| 118 | [switch]$NoCapture, | 125 | [switch]$NoCapture, |
| 126 | [switch]$CrashDump, | ||
| 119 | [switch]$NoInput, | 127 | [switch]$NoInput, |
| 120 | [string[]]$ExtraArgs = @(), | 128 | [string[]]$ExtraArgs = @(), |
| 129 | [switch]$FirstRunUi, | ||
| 121 | [string]$Python = "", | 130 | [string]$Python = "", |
| 122 | [int]$SummaryLines = 40, | 131 | [int]$SummaryLines = 40, |
| 123 | [int]$LockWaitSeconds = 3600, | 132 | [int]$LockWaitSeconds = 3600, |
| @@ -139,6 +148,12 @@ function Get-FirstValue { | |||
| 139 | return "" | 148 | return "" |
| 140 | } | 149 | } |
| 141 | 150 | ||
| 151 | function Get-BootPath { | ||
| 152 | param([string]$Path) | ||
| 153 | if ($Path) { return $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) } | ||
| 154 | return "" | ||
| 155 | } | ||
| 156 | |||
| 142 | function Read-SideFile { | 157 | function Read-SideFile { |
| 143 | # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt). | 158 | # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt). |
| 144 | param([string]$Path) | 159 | param([string]$Path) |
| @@ -188,14 +203,14 @@ if (-not $Name) { $Name = "boot-" + (Get-Date -Format "yyyyMMdd-HHmmss") } | |||
| 188 | if ($NoInput) { $InputScript = "" } | 203 | if ($NoInput) { $InputScript = "" } |
| 189 | if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" } | 204 | if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" } |
| 190 | 205 | ||
| 191 | $Runtime = Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe")) | 206 | $Runtime = Get-BootPath (Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe"))) |
| 192 | $RuntimeDir = Split-Path -Parent $Runtime | 207 | $RuntimeDir = Split-Path -Parent $Runtime |
| 193 | $GameDir = Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt"))) | 208 | $GameDir = Get-BootPath (Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt")))) |
| 194 | $Exe = Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" })) | 209 | $Exe = Get-BootPath (Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" }))) |
| 195 | $Shaders = Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS) | 210 | $Shaders = Get-BootPath (Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS)) |
| 196 | $OutDir = Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs")) | 211 | $OutDir = Get-BootPath (Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs"))) |
| 197 | $OutDir = [System.IO.Path]::GetFullPath($OutDir) | 212 | $Overlay = Get-BootPath (Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay"))) |
| 198 | $Overlay = Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay")) | 213 | $RunDirectory = Join-Path $OutDir ("work_" + $Name) |
| 199 | $Capture = Join-Path $OutDir ("cap_" + $Name) | 214 | $Capture = Join-Path $OutDir ("cap_" + $Name) |
| 200 | $LogFile = Join-Path $OutDir ($Name + ".log") | 215 | $LogFile = Join-Path $OutDir ($Name + ".log") |
| 201 | $StdoutFile = Join-Path $OutDir ($Name + ".stdout.log") | 216 | $StdoutFile = Join-Path $OutDir ($Name + ".stdout.log") |
| @@ -209,6 +224,12 @@ if (-not (Test-Path -LiteralPath $Runtime -PathType Leaf)) { $problems.Add("no g | |||
| 209 | elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) { | 224 | elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) { |
| 210 | $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)") | 225 | $problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)") |
| 211 | } | 226 | } |
| 227 | if ($CrashDump) { | ||
| 228 | $monitor = Join-Path $RuntimeDir "gta6rt_crash_monitor.exe" | ||
| 229 | if (-not (Test-Path -LiteralPath $monitor -PathType Leaf)) { | ||
| 230 | $problems.Add("-CrashDump needs the gta6rt_crash_monitor build target beside the runtime") | ||
| 231 | } | ||
| 232 | } | ||
| 212 | if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") } | 233 | if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") } |
| 213 | elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) { | 234 | elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) { |
| 214 | $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives") | 235 | $problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives") |
| @@ -226,7 +247,8 @@ if ($Shaders) { | |||
| 226 | 247 | ||
| 227 | # ------------------------------------------------------------------------------------------ environment | 248 | # ------------------------------------------------------------------------------------------ environment |
| 228 | 249 | ||
| 229 | # Defaults: used only when this shell has not set the variable. They match the Linux harness (scripts/linux-boot/). | 250 | # Defaults: used only when this shell has not set the variable. Some are the Linux harness's too (scripts/linux-boot/); it |
| 251 | # does not set LEONIDA_DEVICE_FAULT. | ||
| 230 | $defaults = [ordered]@{ | 252 | $defaults = [ordered]@{ |
| 231 | LEONIDA_D3D12 = "vulkan" | 253 | LEONIDA_D3D12 = "vulkan" |
| 232 | LEONIDA_DEVICE_TYPE = "6" # Series S identity; the runtime answers the ConsoleMode registry read with it | 254 | LEONIDA_DEVICE_TYPE = "6" # Series S identity; the runtime answers the ConsoleMode registry read with it |
| @@ -237,7 +259,10 @@ $defaults = [ordered]@{ | |||
| 237 | # LEONIDA_PEEK: the game-state and session-state RVAs (measured locally, not kept in the repository) when | 259 | # LEONIDA_PEEK: the game-state and session-state RVAs (measured locally, not kept in the repository) when |
| 238 | # LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA name them; see below. | 260 | # LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA name them; see below. |
| 239 | LEONIDA_PEEK_SECONDS = "5" | 261 | LEONIDA_PEEK_SECONDS = "5" |
| 240 | LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints) | 262 | # 2: the device-loss report and checkpoints without NVIDIA's diagnostics config. =1 adds that config, which is part |
| 263 | # of every compute journal file name, so a journal pre-compiled without it would not match. LEONIDA_AFTERMATH=1 | ||
| 264 | # gets 1 (below). | ||
| 265 | LEONIDA_DEVICE_FAULT = "2" # device-loss report (VK_EXT_device_fault, checkpoints) | ||
| 241 | LEONIDA_CAPTURE_EVERY = "60" | 266 | LEONIDA_CAPTURE_EVERY = "60" |
| 242 | LEONIDA_CAPTURE_LIMIT = "40" | 267 | LEONIDA_CAPTURE_LIMIT = "40" |
| 243 | DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off | 268 | DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off |
| @@ -261,29 +286,117 @@ if ($Shaders) { $perRun["LEONIDA_SHADERS"] = $Shaders } | |||
| 261 | if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks } | 286 | if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks } |
| 262 | 287 | ||
| 263 | $bootEnv = [ordered]@{} | 288 | $bootEnv = [ordered]@{} |
| 289 | $given = @{} # the variables this shell, -SetEnv or KEY=VALUE set, as opposed to the defaults above | ||
| 264 | foreach ($k in $defaults.Keys) { | 290 | foreach ($k in $defaults.Keys) { |
| 265 | $cur = [Environment]::GetEnvironmentVariable($k) | 291 | $cur = [Environment]::GetEnvironmentVariable($k) |
| 266 | if ($cur) { $bootEnv[$k] = $cur } else { $bootEnv[$k] = $defaults[$k] } | 292 | if ($cur) { $bootEnv[$k] = $cur; $given[$k] = $true } else { $bootEnv[$k] = $defaults[$k] } |
| 267 | } | 293 | } |
| 268 | foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] } | 294 | foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] } |
| 269 | # Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below. | 295 | # Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below. |
| 270 | foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) { | 296 | foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) { |
| 271 | if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value } | 297 | if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value } |
| 272 | } | 298 | } |
| 273 | foreach ($k in $SetEnv.Keys) { $bootEnv[[string]$k] = [string]$SetEnv[$k] } | 299 | foreach ($k in $SetEnv.Keys) { $bootEnv[[string]$k] = [string]$SetEnv[$k]; $given[[string]$k] = $true } |
| 274 | foreach ($pair in $EnvPairs) { | 300 | foreach ($pair in $EnvPairs) { |
| 275 | if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" } | 301 | if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" } |
| 276 | $bootEnv[$Matches[1]] = $Matches[2] | 302 | $bootEnv[$Matches[1]] = $Matches[2]; $given[$Matches[1]] = $true |
| 277 | } | 303 | } |
| 304 | # LEONIDA_AFTERMATH=1 wants NVIDIA's diagnostics config (shader debug info in the crash dump). The runtime reads | ||
| 305 | # LEONIDA_DEVICE_FAULT first and leaves the config out for 2 (d3d12_vulkan_device.cpp), so the default becomes 1 then; | ||
| 306 | # a value the user gave is kept. | ||
| 307 | if ($bootEnv["LEONIDA_AFTERMATH"] -eq "1" -and -not $given["LEONIDA_DEVICE_FAULT"]) { $bootEnv["LEONIDA_DEVICE_FAULT"] = "1" } | ||
| 278 | if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] } | 308 | if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] } |
| 309 | # The journal `gta6rt --precompile-pipelines` fills beside gta6rt.exe (when it runs without LEONIDA_PIPELINE_CACHE_DIR) | ||
| 310 | # is read here as the runtime's read-only seed (LEONIDA_PIPELINE_JOURNAL_SEED_DIR, docs/d3d12_vulkan.md), so the pipelines | ||
| 311 | # it holds are not compiled again in the boot's own cache folder. Only when this shell or -SetEnv/KEY= did not decide, and | ||
| 312 | # when the two journals are distinct: the runtime turns its journal off for a seed that is, holds or sits in its writable | ||
| 313 | # journal (pipeline_cache_journal.h, resolve_roots). A relative or unresolvable cache folder gets no automatic seed. | ||
| 314 | if (-not $bootEnv.Contains("LEONIDA_PIPELINE_JOURNAL_SEED_DIR")) { | ||
| 315 | # Windows' final path of a folder (GetFinalPathNameByHandle) sees through junctions, symbolic links, substituted | ||
| 316 | # and mapped drives, short 8.3 names and the \\?\ and \\.\ prefixes, as the runtime's std::filesystem checks do. | ||
| 317 | # A folder that does not exist yet is named from its deepest existing parent. Without the helper (a compile error, | ||
| 318 | # a restricted session), the comparison falls back to the spelled paths. | ||
| 319 | function Get-FinalFolderPath([string]$path) { | ||
| 320 | $plain = ($path -replace '^\\\\[?.]\\UNC\\', '\\' -replace '^\\\\[?.]\\', '').TrimEnd('\', '/') | ||
| 321 | try { | ||
| 322 | if (-not ('LeonidaFinalPath' -as [type])) { | ||
| 323 | Add-Type -ErrorAction Stop -TypeDefinition @' | ||
| 324 | using System; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; | ||
| 325 | public static class LeonidaFinalPath { | ||
| 326 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] | ||
| 327 | static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr sa, uint disposition, uint flags, IntPtr template); | ||
| 328 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] | ||
| 329 | static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder buffer, uint length, uint flags); | ||
| 330 | public static string Of(string path) { | ||
| 331 | // No access asked, all sharing, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS (needed to open a folder). | ||
| 332 | using (SafeFileHandle h = CreateFileW(path, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) { | ||
| 333 | if (h.IsInvalid) return null; | ||
| 334 | StringBuilder b = new StringBuilder(32768); | ||
| 335 | uint n = GetFinalPathNameByHandleW(h, b, (uint)b.Capacity, 0); | ||
| 336 | return (n == 0 || n >= b.Capacity) ? null : b.ToString(); | ||
| 337 | } | ||
| 338 | } | ||
| 339 | } | ||
| 340 | '@ | ||
| 341 | } | ||
| 342 | $existing = $path.TrimEnd('\', '/'); $tail = @() | ||
| 343 | while ($existing -and -not [System.IO.Directory]::Exists($existing)) { | ||
| 344 | $tail = @([System.IO.Path]::GetFileName($existing)) + $tail | ||
| 345 | $existing = [System.IO.Path]::GetDirectoryName($existing) | ||
| 346 | } | ||
| 347 | if (-not $existing) { return $plain } | ||
| 348 | $final = [LeonidaFinalPath]::Of($existing) | ||
| 349 | if (-not $final) { return $plain } | ||
| 350 | $final = $final -replace '^\\\\\?\\UNC\\', '\\' -replace '^\\\\\?\\', '' | ||
| 351 | foreach ($part in $tail) { $final = [System.IO.Path]::Combine($final, $part) } | ||
| 352 | return $final.TrimEnd('\', '/') | ||
| 353 | } catch { return $plain } | ||
| 354 | } | ||
| 355 | $seed = $null | ||
| 356 | try { | ||
| 357 | $runtimeFull = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($RuntimeDir) | ||
| 358 | $precompiled = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($runtimeFull, "pipeline_cache.d")).TrimEnd('\', '/') | ||
| 359 | if (Test-Path -LiteralPath $precompiled -PathType Container) { | ||
| 360 | $cacheDir = $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | ||
| 361 | $ownJournal = $null | ||
| 362 | if (-not $cacheDir) { $ownJournal = $precompiled } # the runtime then keeps its journal beside gta6rt.exe | ||
| 363 | elseif ($cacheDir -match '^([A-Za-z]:[\\/]|[\\/]{2})') { | ||
| 364 | $ownJournal = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($cacheDir, "pipeline_cache.d")).TrimEnd('\', '/') | ||
| 365 | } | ||
| 366 | if ($ownJournal) { | ||
| 367 | $a = Get-FinalFolderPath $ownJournal | ||
| 368 | $b = Get-FinalFolderPath $precompiled | ||
| 369 | $c = [System.StringComparison]::OrdinalIgnoreCase | ||
| 370 | $overlap = $a.Equals($b, $c) -or $a.StartsWith($b + '\', $c) -or $b.StartsWith($a + '\', $c) | ||
| 371 | if (-not $overlap) { $seed = $precompiled } | ||
| 372 | } | ||
| 373 | } | ||
| 374 | } catch { $seed = $null } | ||
| 375 | if ($seed) { $bootEnv["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = $seed } | ||
| 376 | } | ||
| 377 | |||
| 378 | foreach ($key in @("LEONIDA_SHADERS", "LEONIDA_PIPELINE_CACHE_DIR")) { | ||
| 379 | if ($bootEnv[$key]) { $bootEnv[$key] = Get-BootPath $bootEnv[$key] } | ||
| 380 | } | ||
| 381 | foreach ($key in @("LEONIDA_COMPAT_DIR", "LEONIDA_DSTORAGE_HISTORY", "LEONIDA_SAVE_DIR", | ||
| 382 | "LEONIDA_WRITE_DIR", "LEONIDA_XMEM_BACKING_DIR")) { | ||
| 383 | $value = $bootEnv[$key] | ||
| 384 | if ($value -and -not [System.IO.Path]::IsPathRooted($value)) { | ||
| 385 | $bootEnv[$key] = Get-BootPath (Join-Path $RepoRoot $value) | ||
| 386 | } | ||
| 387 | } | ||
| 388 | $Capture = Get-BootPath $Capture | ||
| 389 | if ($bootEnv["LEONIDA_CAPTURE"]) { $bootEnv["LEONIDA_CAPTURE"] = $Capture } | ||
| 279 | 390 | ||
| 280 | $gameArgs = @("--run", $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs | 391 | $launchMode = if ($FirstRunUi) { "--first-run-ui" } else { "--run" } |
| 392 | $gameArgs = @($launchMode, $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs | ||
| 281 | $argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " | 393 | $argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " |
| 282 | 394 | ||
| 283 | if (-not $DigestOnly) { | 395 | if (-not $DigestOnly) { |
| 284 | Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot" | 396 | Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot" |
| 285 | Write-Output "[boot] gta6rt $Runtime" | 397 | Write-Output "[boot] gta6rt $Runtime" |
| 286 | Write-Output "[boot] out $OutDir" | 398 | Write-Output "[boot] out $OutDir" |
| 399 | Write-Output "[boot] cwd $RunDirectory" | ||
| 287 | foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } } | 400 | foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } } |
| 288 | Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine" | 401 | Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine" |
| 289 | } | 402 | } |
| @@ -323,7 +436,7 @@ if (-not $DigestOnly) { | |||
| 323 | } | 436 | } |
| 324 | } | 437 | } |
| 325 | 438 | ||
| 326 | foreach ($d in @($OutDir, $Overlay)) { New-Item -ItemType Directory -Force -Path $d | Out-Null } | 439 | foreach ($d in @($OutDir, $Overlay, $RunDirectory)) { New-Item -ItemType Directory -Force -Path $d | Out-Null } |
| 327 | if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) { | 440 | if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) { |
| 328 | New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null | 441 | New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null |
| 329 | } | 442 | } |
| @@ -345,11 +458,30 @@ if (-not $DigestOnly) { | |||
| 345 | 458 | ||
| 346 | # ------------------------------------------------------------------------------------------- the boot | 459 | # ------------------------------------------------------------------------------------------- the boot |
| 347 | $started = Get-Date | 460 | $started = Get-Date |
| 348 | $proc = Start-Process -FilePath $Runtime -ArgumentList $argLine -WorkingDirectory $RepoRoot -NoNewWindow -PassThru ` | 461 | $launchFile = $Runtime |
| 462 | $launchArgs = $argLine | ||
| 463 | if ($CrashDump) { | ||
| 464 | $crashDir = Join-Path $OutDir ("{0}-crash-{1}" -f $Name, [guid]::NewGuid().ToString("N")) | ||
| 465 | $runtimePath = (Get-Item -LiteralPath $Runtime).FullName | ||
| 466 | $childCommand = "$(ConvertTo-ProcessArgument $runtimePath) $argLine" | ||
| 467 | $launchFile = $monitor | ||
| 468 | $launchArgs = (@($RepoRoot, $crashDir, $Seconds, $runtimePath, $childCommand) | | ||
| 469 | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " | ||
| 470 | } | ||
| 471 | $proc = Start-Process -FilePath $launchFile -ArgumentList $launchArgs -WorkingDirectory $RunDirectory -NoNewWindow -PassThru ` | ||
| 349 | -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile | 472 | -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile |
| 350 | $handle = $proc.Handle # keeps the exit code readable after the process ends | 473 | $handle = $proc.Handle # keeps the exit code readable after the process ends |
| 351 | $stopped = $false | 474 | $stopped = $false |
| 352 | if (-not $proc.WaitForExit($Seconds * 1000)) { | 475 | if ($CrashDump) { |
| 476 | # The monitor owns the deadline so a dump already in progress can finish. | ||
| 477 | $proc.WaitForExit() | ||
| 478 | $stopped = Test-Path -LiteralPath (Join-Path $crashDir "timed-out") | ||
| 479 | if (Test-Path -LiteralPath (Join-Path $crashDir "crash.dmp")) { | ||
| 480 | Write-Output "[boot] private crash diagnostics: $crashDir" | ||
| 481 | } elseif ($proc.ExitCode -ne 0) { | ||
| 482 | Write-Warning "No crash dump was saved. See the monitor diagnostics in $LogFile" | ||
| 483 | } | ||
| 484 | } elseif (-not $proc.WaitForExit($Seconds * 1000)) { | ||
| 353 | $stopped = $true | 485 | $stopped = $true |
| 354 | try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } | 486 | try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } |
| 355 | [void]$proc.WaitForExit(20000) | 487 | [void]$proc.WaitForExit(20000) |
| @@ -369,6 +501,67 @@ if (-not $DigestOnly) { | |||
| 369 | 501 | ||
| 370 | # -------------------------------------------------------------------------------------------- the digest | 502 | # -------------------------------------------------------------------------------------------- the digest |
| 371 | 503 | ||
| 504 | function Get-FaultContext { | ||
| 505 | param([string]$Path) | ||
| 506 | $apis = @("vkAcquireNextImageKHR", "vkBeginCommandBuffer", "vkCreateSwapchainKHR", "vkDeviceWaitIdle", | ||
| 507 | "vkEndCommandBuffer", "vkGetFenceStatus", "vkGetQueryPoolResults", "vkGetSemaphoreCounterValue", | ||
| 508 | "vkQueueBindSparse", "vkQueuePresentKHR", "vkQueueSubmit", "vkQueueWaitIdle", "vkResetFences", | ||
| 509 | "vkSignalSemaphore", "vkWaitForFences", "vkWaitSemaphores") | ||
| 510 | $api = "not observed" | ||
| 511 | $query = "not observed" | ||
| 512 | $lost = $false | ||
| 513 | [long]$queues = 0 | ||
| 514 | [long]$reported = 0 | ||
| 515 | [long]$decoded = 0 | ||
| 516 | [long]$unrecognized = 0 | ||
| 517 | |||
| 518 | # Select-String streams matches, including a report that arrives after a long trace. | ||
| 519 | $prefix = '^\s*\[rt\] (device-fault: |vulkan: the device was lost \()' | ||
| 520 | Select-String -LiteralPath $Path -CaseSensitive -Pattern $prefix | ForEach-Object { | ||
| 521 | $tag = $_.Matches[0] | ||
| 522 | $record = $_.Line.Substring($tag.Length).TrimEnd() | ||
| 523 | if ($tag.Groups[1].Value -eq "vulkan: the device was lost (") { | ||
| 524 | $lost = $true | ||
| 525 | if ($api -in @("not observed", "other")) { | ||
| 526 | if ($record -cmatch '^(vkWaitSemaphores|vkGetSemaphoreCounterValue) in the fence dispatcher returned VK_ERROR_DEVICE_LOST\)') { | ||
| 527 | $api = $Matches[1] | ||
| 528 | } elseif ($record.StartsWith("a fence's counter read UINT64_MAX and vkDeviceWaitIdle then returned VK_ERROR_DEVICE_LOST)")) { | ||
| 529 | $api = "vkDeviceWaitIdle" | ||
| 530 | } | ||
| 531 | } | ||
| 532 | } elseif ($record.StartsWith("VK_ERROR_DEVICE_LOST from ")) { | ||
| 533 | $lost = $true | ||
| 534 | if ($api -in @("not observed", "other")) { | ||
| 535 | $api = "other" | ||
| 536 | if ($record -cmatch '^VK_ERROR_DEVICE_LOST from ([^\s(]+)' -and $apis -ccontains $Matches[1]) { | ||
| 537 | $api = $Matches[1] | ||
| 538 | } | ||
| 539 | } | ||
| 540 | } elseif ($record -cmatch '^queue \S+ checkpoints=([0-9]+)$') { | ||
| 541 | [uint32]$count = 0 | ||
| 542 | if ([uint32]::TryParse($Matches[1], [ref]$count)) { | ||
| 543 | $queues++ | ||
| 544 | $reported += $count | ||
| 545 | } | ||
| 546 | } elseif ($record -cmatch '^stage=0x[0-9a-fA-F]+ submission=[0-9]+ list=[0-9]+ command=[0-9]+ kind=\S+$') { | ||
| 547 | $decoded++ | ||
| 548 | } elseif ($record -cmatch '^stage=0x[0-9a-fA-F]+ marker=\S+ \(unrecognized\)$') { | ||
| 549 | $unrecognized++ | ||
| 550 | } elseif ($query -eq "not observed") { | ||
| 551 | if ($record.StartsWith("description:")) { | ||
| 552 | $query = if ($record.EndsWith(" (partial report)")) { "partial" } else { "complete" } | ||
| 553 | } elseif ($record -cmatch '^vkGetDeviceFaultInfoEXT (counts|data) failed \(-?[0-9]+\)$') { | ||
| 554 | $query = "$($Matches[1]) failed" | ||
| 555 | } elseif ($record -ceq "fault info collection failed") { | ||
| 556 | $query = "collection failed" | ||
| 557 | } | ||
| 558 | } | ||
| 559 | } | ||
| 560 | if ($lost -or $query -ne "not observed" -or $queues -or $decoded -or $unrecognized) { | ||
| 561 | "fault context: api=$api, query=$query, queues=$queues, reported=$reported, decoded=$decoded, unrecognized=$unrecognized" | ||
| 562 | } | ||
| 563 | } | ||
| 564 | |||
| 372 | $py = @(Resolve-Python $Python) | 565 | $py = @(Resolve-Python $Python) |
| 373 | if ($py.Count) { | 566 | if ($py.Count) { |
| 374 | $pyArgs = @() | 567 | $pyArgs = @() |
| @@ -387,10 +580,31 @@ $valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)' | |||
| 387 | $states = New-Object System.Collections.Generic.List[string] | 580 | $states = New-Object System.Collections.Generic.List[string] |
| 388 | $lastPeek = ""; $prevPair = "" | 581 | $lastPeek = ""; $prevPair = "" |
| 389 | $presentOk = 0; $presentFailed = 0; $presses = 0 | 582 | $presentOk = 0; $presentFailed = 0; $presses = 0 |
| 390 | $shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string] | 583 | $shaderLine = "" |
| 584 | $deviceLost = $false | ||
| 585 | # VkDeviceFaultAddressTypeEXT, in enum order. Keep only counters, including one bucket for newer types. | ||
| 586 | $faultNames = @("NONE", "READ_INVALID", "WRITE_INVALID", "EXECUTE_INVALID", "INSTRUCTION_POINTER_UNKNOWN", | ||
| 587 | "INSTRUCTION_POINTER_INVALID", "INSTRUCTION_POINTER_FAULT", "OTHER") | ||
| 588 | $faultCounts = New-Object 'long[]' $faultNames.Length | ||
| 589 | $faultAddressRx = [regex]'^\s*\[rt\] device-fault: address\[\d+\] type=(-?\d+)\s+address=' | ||
| 391 | $wrapped = 0 | 590 | $wrapped = 0 |
| 392 | if (Test-Path -LiteralPath $LogFile) { | 591 | if (Test-Path -LiteralPath $LogFile) { |
| 393 | foreach ($line in [System.IO.File]::ReadLines($LogFile)) { | 592 | foreach ($line in [System.IO.File]::ReadLines($LogFile)) { |
| 593 | if ($line.Contains("[rt] device-fault:")) { | ||
| 594 | if ($line.Contains("[rt] device-fault: VK_ERROR_DEVICE_LOST from ")) { $deviceLost = $true } | ||
| 595 | $m = $faultAddressRx.Match($line) | ||
| 596 | if ($m.Success) { | ||
| 597 | $type = 0 | ||
| 598 | if (-not [int]::TryParse($m.Groups[1].Value, [ref]$type) -or $type -lt 0 -or $type -ge ($faultNames.Length - 1)) { | ||
| 599 | $type = $faultNames.Length - 1 | ||
| 600 | } | ||
| 601 | $faultCounts[$type]++ | ||
| 602 | } | ||
| 603 | continue | ||
| 604 | } | ||
| 605 | if ($line.Contains("[rt] vulkan: the device was lost (") -or $line.Contains("VK_ERROR_DEVICE_LOST")) { | ||
| 606 | $deviceLost = $true | ||
| 607 | } | ||
| 394 | if ($line.Contains("XboxPresentation::PresentX")) { | 608 | if ($line.Contains("XboxPresentation::PresentX")) { |
| 395 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } | 609 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } |
| 396 | continue | 610 | continue |
| @@ -418,8 +632,6 @@ if (Test-Path -LiteralPath $LogFile) { | |||
| 418 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } | 632 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } |
| 419 | continue | 633 | continue |
| 420 | } | 634 | } |
| 421 | if ($line.Contains("[rt] device-fault:") -and -not $line.Contains("device-fault: enabled")) { if ($faults.Count -lt 8) { $faults.Add($line.Trim()) }; continue } | ||
| 422 | if ($line.Contains("VK_ERROR_DEVICE_LOST") -and $faults.Count -lt 8) { $faults.Add($line.Trim()); continue } | ||
| 423 | if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() } | 635 | if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() } |
| 424 | if ($line.Contains("wrapped V#")) { $wrapped++ } | 636 | if ($line.Contains("wrapped V#")) { $wrapped++ } |
| 425 | } | 637 | } |
| @@ -451,9 +663,21 @@ $digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated- | |||
| 451 | $digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })") | 663 | $digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })") |
| 452 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") | 664 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") |
| 453 | $digest.Add("input: $presses presses logged") | 665 | $digest.Add("input: $presses presses logged") |
| 454 | $digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })") | 666 | $faultClasses = @(for ($i = 0; $i -lt $faultNames.Length; $i++) { |
| 455 | foreach ($f in $faults) { $digest.Add(" $f") } | 667 | if ($faultCounts[$i]) { "$($faultNames[$i])=$($faultCounts[$i])" } |
| 668 | }) | ||
| 669 | $faultText = "none" | ||
| 670 | if ($deviceLost -or $faultClasses.Count) { | ||
| 671 | $loss = if ($deviceLost) { "device loss reported" } else { "no device-loss marker" } | ||
| 672 | $records = if ($faultClasses.Count) { $faultClasses -join ", " } else { "none" } | ||
| 673 | $faultText = "$loss, address records: $records" | ||
| 674 | } | ||
| 675 | $digest.Add("faults: $faultText") | ||
| 456 | if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } | 676 | if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } |
| 677 | if (Test-Path -LiteralPath $LogFile) { | ||
| 678 | $faultContext = Get-FaultContext $LogFile | ||
| 679 | if ($faultContext) { $digest.Add($faultContext) } | ||
| 680 | } | ||
| 457 | $digest.Add("frames: $capText") | 681 | $digest.Add("frames: $capText") |
| 458 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") | 682 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") |
| 459 | $digest | Out-File -FilePath $DigestFile -Encoding utf8 | 683 | $digest | Out-File -FilePath $DigestFile -Encoding utf8 |
diff --git a/scripts/windows-boot/crash_monitor.cpp b/scripts/windows-boot/crash_monitor.cpp new file mode 100644 index 000000000..7cabf38ee --- /dev/null +++ b/scripts/windows-boot/crash_monitor.cpp | |||
| @@ -0,0 +1,204 @@ | |||
| 1 | // Optional out-of-process observer used by boot.ps1 on x64 Windows. | ||
| 2 | #define WIN32_LEAN_AND_MEAN | ||
| 3 | #define NOMINMAX | ||
| 4 | #include <windows.h> | ||
| 5 | #include <dbghelp.h> | ||
| 6 | #include <cerrno> | ||
| 7 | #include <cstdio> | ||
| 8 | #include <cstdlib> | ||
| 9 | #include <cwchar> | ||
| 10 | #include <filesystem> | ||
| 11 | #include <fstream> | ||
| 12 | #include <iomanip> | ||
| 13 | #include <string> | ||
| 14 | |||
| 15 | namespace fs = std::filesystem; | ||
| 16 | |||
| 17 | namespace { | ||
| 18 | struct Handle { | ||
| 19 | HANDLE value; | ||
| 20 | ~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); } | ||
| 21 | Handle(const Handle&) = delete; | ||
| 22 | Handle& operator=(const Handle&) = delete; | ||
| 23 | explicit Handle(HANDLE handle) : value(handle) {} | ||
| 24 | }; | ||
| 25 | |||
| 26 | void report_error(const char* operation, DWORD error = GetLastError()) { | ||
| 27 | std::fprintf(stderr, "[crash-monitor] %s failed (%lu)\n", operation, error); | ||
| 28 | } | ||
| 29 | |||
| 30 | bool write_dump(const fs::path& dir, HANDLE process, DWORD pid, MINIDUMP_EXCEPTION_INFORMATION* info) { | ||
| 31 | const auto partial = dir / L"crash.dmp.partial"; | ||
| 32 | { | ||
| 33 | Handle file(CreateFileW(partial.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr)); | ||
| 34 | if (file.value == INVALID_HANDLE_VALUE) { report_error("create dump"); return false; } | ||
| 35 | if (!MiniDumpWriteDump(process, pid, file.value, MiniDumpWithThreadInfo, info, nullptr, nullptr)) { | ||
| 36 | report_error("MiniDumpWriteDump"); | ||
| 37 | return false; | ||
| 38 | } | ||
| 39 | } | ||
| 40 | if (!MoveFileExW(partial.c_str(), (dir / L"crash.dmp").c_str(), MOVEFILE_WRITE_THROUGH)) { | ||
| 41 | report_error("publish dump"); | ||
| 42 | return false; | ||
| 43 | } | ||
| 44 | return true; | ||
| 45 | } | ||
| 46 | |||
| 47 | void write_stack(std::ostream& out, HANDLE process, HANDLE thread, CONTEXT ctx, const fs::path& symbols) { | ||
| 48 | // Only look beside the runtime. Ignore debugger environment paths and embedded build-machine paths. | ||
| 49 | SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_NO_PROMPTS | | ||
| 50 | SYMOPT_IGNORE_NT_SYMPATH | SYMOPT_IGNORE_CVREC | SYMOPT_DISABLE_SYMSRV_AUTODETECT); | ||
| 51 | const bool loaded = SymInitializeW(process, symbols.c_str(), TRUE) != FALSE; | ||
| 52 | STACKFRAME64 frame{}; | ||
| 53 | frame.AddrPC = {ctx.Rip, 0, AddrModeFlat}; | ||
| 54 | frame.AddrStack = {ctx.Rsp, 0, AddrModeFlat}; | ||
| 55 | frame.AddrFrame = {ctx.Rbp, 0, AddrModeFlat}; | ||
| 56 | for (unsigned n = 0; n < 64 && frame.AddrPC.Offset; ++n) { | ||
| 57 | const auto pc = frame.AddrPC.Offset; | ||
| 58 | const auto sp = frame.AddrStack.Offset; | ||
| 59 | out << '#' << std::dec << n << " 0x" << std::hex << pc; | ||
| 60 | IMAGEHLP_MODULE64 module{}; | ||
| 61 | module.SizeOfStruct = sizeof(module); | ||
| 62 | if (loaded && SymGetModuleInfo64(process, pc, &module)) | ||
| 63 | out << ' ' << module.ModuleName << "+0x" << pc - module.BaseOfImage; | ||
| 64 | alignas(SYMBOL_INFO) char storage[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]{}; | ||
| 65 | auto* symbol = reinterpret_cast<SYMBOL_INFO*>(storage); | ||
| 66 | symbol->SizeOfStruct = sizeof(SYMBOL_INFO); | ||
| 67 | symbol->MaxNameLen = MAX_SYM_NAME; | ||
| 68 | DWORD64 displacement = 0; | ||
| 69 | if (loaded && SymFromAddr(process, pc, &displacement, symbol)) | ||
| 70 | out << " (" << symbol->Name << "+0x" << displacement << ')'; | ||
| 71 | out << '\n'; | ||
| 72 | if (!loaded || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr, | ||
| 73 | SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) | ||
| 74 | break; | ||
| 75 | if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) { | ||
| 76 | // The first StackWalk64 call can describe the initial frame again. | ||
| 77 | if (n != 0 || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr, | ||
| 78 | SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) break; | ||
| 79 | if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) break; | ||
| 80 | } | ||
| 81 | } | ||
| 82 | if (loaded) SymCleanup(process); | ||
| 83 | } | ||
| 84 | |||
| 85 | void capture(const fs::path& dir, const fs::path& symbols, HANDLE process, const DEBUG_EVENT& event) { | ||
| 86 | const bool exception = event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT; | ||
| 87 | const DWORD code = exception ? event.u.Exception.ExceptionRecord.ExceptionCode : event.u.ExitProcess.dwExitCode; | ||
| 88 | Handle thread(OpenThread(THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT, FALSE, event.dwThreadId)); | ||
| 89 | CONTEXT ctx{}; | ||
| 90 | ctx.ContextFlags = CONTEXT_ALL; | ||
| 91 | const bool got_context = thread.value && GetThreadContext(thread.value, &ctx); | ||
| 92 | EXCEPTION_RECORD record{}; | ||
| 93 | if (exception) { | ||
| 94 | record = event.u.Exception.ExceptionRecord; | ||
| 95 | record.ExceptionRecord = nullptr; // Nested records belong to the child address space. | ||
| 96 | } | ||
| 97 | EXCEPTION_POINTERS pointers{&record, &ctx}; | ||
| 98 | MINIDUMP_EXCEPTION_INFORMATION info{event.dwThreadId, &pointers, FALSE}; | ||
| 99 | if (!write_dump(dir, process, event.dwProcessId, exception && got_context ? &info : nullptr)) | ||
| 100 | DeleteFileW((dir / L"crash.dmp.partial").c_str()); | ||
| 101 | |||
| 102 | std::ofstream stack(dir / L"stack.txt"); | ||
| 103 | stack << "kind=" << (exception ? "unhandled_exception" : "abnormal_exit") | ||
| 104 | << "\ncode=0x" << std::hex << std::setw(8) << std::setfill('0') << code | ||
| 105 | << "\nthread=" << std::dec << event.dwThreadId << '\n'; | ||
| 106 | if (got_context) write_stack(stack, process, thread.value, ctx, symbols); | ||
| 107 | else stack << "thread context unavailable at this debug event\n"; | ||
| 108 | stack.close(); | ||
| 109 | if (!stack) report_error("write stack.txt", ERROR_WRITE_FAULT); | ||
| 110 | } | ||
| 111 | |||
| 112 | DWORD monitor(HANDLE process, const fs::path& dir, const fs::path& symbols, ULONGLONG deadline) { | ||
| 113 | bool initial_break = true; | ||
| 114 | bool captured = false; | ||
| 115 | bool stopped = false; | ||
| 116 | for (;;) { | ||
| 117 | DEBUG_EVENT event{}; | ||
| 118 | if (!WaitForDebugEventEx(&event, 100)) { | ||
| 119 | if (GetLastError() != ERROR_SEM_TIMEOUT) { report_error("WaitForDebugEventEx"); return 1; } | ||
| 120 | } else { | ||
| 121 | DWORD disposition = DBG_CONTINUE; | ||
| 122 | const bool exiting = event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT; | ||
| 123 | if (event.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT && event.u.CreateProcessInfo.hFile) | ||
| 124 | CloseHandle(event.u.CreateProcessInfo.hFile); | ||
| 125 | if (event.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT && event.u.LoadDll.hFile) | ||
| 126 | CloseHandle(event.u.LoadDll.hFile); | ||
| 127 | if (event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) { | ||
| 128 | const auto& ex = event.u.Exception; | ||
| 129 | if (initial_break && ex.dwFirstChance && ex.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT) | ||
| 130 | initial_break = false; // The loader breakpoint belongs to the debugger. | ||
| 131 | else { | ||
| 132 | disposition = DBG_EXCEPTION_NOT_HANDLED; | ||
| 133 | if (!ex.dwFirstChance && !stopped && !captured) { | ||
| 134 | capture(dir, symbols, process, event); | ||
| 135 | captured = true; | ||
| 136 | } | ||
| 137 | } | ||
| 138 | } else if (exiting && event.u.ExitProcess.dwExitCode && !stopped && !captured) { | ||
| 139 | capture(dir, symbols, process, event); | ||
| 140 | } | ||
| 141 | if (!ContinueDebugEvent(event.dwProcessId, event.dwThreadId, disposition)) { | ||
| 142 | report_error("ContinueDebugEvent"); | ||
| 143 | return 1; | ||
| 144 | } | ||
| 145 | if (exiting) { | ||
| 146 | if (!stopped) return event.u.ExitProcess.dwExitCode; | ||
| 147 | std::ofstream marker(dir / L"timed-out"); | ||
| 148 | marker.close(); | ||
| 149 | return marker ? 0 : 1; | ||
| 150 | } | ||
| 151 | } | ||
| 152 | if (!captured && !stopped && GetTickCount64() >= deadline) { | ||
| 153 | if (TerminateProcess(process, ERROR_TIMEOUT)) stopped = true; | ||
| 154 | else if (GetLastError() != ERROR_ACCESS_DENIED) { report_error("TerminateProcess"); return 1; } | ||
| 155 | } | ||
| 156 | } | ||
| 157 | } | ||
| 158 | } // namespace | ||
| 159 | |||
| 160 | int wmain(int argc, wchar_t** argv) { | ||
| 161 | if (argc != 6) { | ||
| 162 | std::fputs("usage: gta6rt_crash_monitor REPO NEW_REPORT_DIR SECONDS RUNTIME CHILD_COMMAND_LINE\n", stderr); | ||
| 163 | return 2; | ||
| 164 | } | ||
| 165 | wchar_t* end = nullptr; | ||
| 166 | const long seconds = std::wcstol(argv[3], &end, 10); | ||
| 167 | if (end == argv[3] || *end || errno == ERANGE || seconds < 0) return 2; | ||
| 168 | try { | ||
| 169 | const fs::path repo = fs::canonical(argv[1]); | ||
| 170 | const fs::path dir = fs::weakly_canonical(fs::absolute(argv[2])); | ||
| 171 | const fs::path runtime = fs::canonical(argv[4]); | ||
| 172 | // Resolve junctions and compare file identity (Windows path case can differ). | ||
| 173 | for (auto p = dir.parent_path();; p = p.parent_path()) { | ||
| 174 | if (fs::equivalent(p, repo)) { | ||
| 175 | std::fputs("[crash-monitor] private output must be outside the checkout\n", stderr); | ||
| 176 | return 2; | ||
| 177 | } | ||
| 178 | if (p == p.root_path()) break; | ||
| 179 | } | ||
| 180 | if (!fs::create_directory(dir)) { | ||
| 181 | std::fputs("[crash-monitor] report directory already exists\n", stderr); | ||
| 182 | return 2; | ||
| 183 | } | ||
| 184 | STARTUPINFOW startup{}; | ||
| 185 | startup.cb = sizeof(startup); | ||
| 186 | startup.dwFlags = STARTF_USESTDHANDLES; | ||
| 187 | startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); | ||
| 188 | startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); | ||
| 189 | startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); | ||
| 190 | PROCESS_INFORMATION pi{}; | ||
| 191 | std::wstring command(argv[5]); | ||
| 192 | if (!CreateProcessW(runtime.c_str(), command.data(), nullptr, nullptr, TRUE, DEBUG_ONLY_THIS_PROCESS, | ||
| 193 | nullptr, nullptr, &startup, &pi)) { | ||
| 194 | report_error("CreateProcessW"); | ||
| 195 | return 2; | ||
| 196 | } | ||
| 197 | Handle process(pi.hProcess); | ||
| 198 | Handle thread(pi.hThread); | ||
| 199 | return static_cast<int>(monitor(process.value, dir, runtime.parent_path(), GetTickCount64() + seconds * 1000ULL)); | ||
| 200 | } catch (const fs::filesystem_error& e) { | ||
| 201 | report_error("resolve private output or runtime", e.code().value()); | ||
| 202 | return 2; | ||
| 203 | } | ||
| 204 | } | ||
diff --git a/scripts/windows-boot/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.""" | ||
| 2 | import argparse | ||
| 3 | from dataclasses import dataclass | ||
| 4 | import mmap | ||
| 5 | import os | ||
| 6 | from pathlib import Path, PureWindowsPath | ||
| 7 | import re | ||
| 8 | import shutil | ||
| 9 | import struct | ||
| 10 | import subprocess | ||
| 11 | import sys | ||
| 12 | import tempfile | ||
| 13 | |||
| 14 | ROOT = Path(__file__).resolve().parents[2] | ||
| 15 | sys.path.insert(0, str(ROOT / "tools")) | ||
| 16 | from pe_inspect import DIR_EXCEPTION, PeFormatError, PeImage | ||
| 17 | from report_paths import same_report_path | ||
| 18 | |||
| 19 | |||
| 20 | def require(condition, message): | ||
| 21 | if not condition: | ||
| 22 | raise ValueError(message) | ||
| 23 | |||
| 24 | |||
| 25 | def bounds(offset, size, end): | ||
| 26 | require(0 <= offset <= end and 0 <= size <= end - offset, "truncated or invalid binary structure") | ||
| 27 | |||
| 28 | |||
| 29 | def 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 | |||
| 35 | def records(start, count, stride, end): | ||
| 36 | bounds(start, count * stride, end) | ||
| 37 | return range(start, start + count * stride, stride) | ||
| 38 | |||
| 39 | |||
| 40 | def 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 | |||
| 53 | def 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 | |||
| 60 | def 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 | |||
| 72 | def 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 | |||
| 89 | def 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) | ||
| 103 | class Mapping: | ||
| 104 | base: int | ||
| 105 | size: int | ||
| 106 | timestamp: int | ||
| 107 | thread: int | ||
| 108 | rip: int | ||
| 109 | rsp: int | ||
| 110 | |||
| 111 | |||
| 112 | def 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 | |||
| 138 | def 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 | |||
| 170 | def 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 | |||
| 189 | def 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 | |||
| 201 | ROW = 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) | ||
| 202 | BEGIN = "LEONIDA_STACK_BEGIN" | ||
| 203 | END = "LEONIDA_STACK_END" | ||
| 204 | |||
| 205 | |||
| 206 | def 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 | |||
| 226 | def 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 | |||
| 244 | def local_drive(anchor): | ||
| 245 | import ctypes | ||
| 246 | return ctypes.windll.kernel32.GetDriveTypeW(str(anchor)) in (2, 3, 5, 6) | ||
| 247 | |||
| 248 | |||
| 249 | def 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 | |||
| 261 | def 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 | |||
| 292 | def 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 | |||
| 312 | if __name__ == "__main__": | ||
| 313 | main() | ||
diff --git a/scripts/windows-boot/test_crash_monitor.py b/scripts/windows-boot/test_crash_monitor.py new file mode 100644 index 000000000..a28af6380 --- /dev/null +++ b/scripts/windows-boot/test_crash_monitor.py | |||
| @@ -0,0 +1,133 @@ | |||
| 1 | """Exercise the native Windows crash monitor with an entirely synthetic child.""" | ||
| 2 | import os | ||
| 3 | from pathlib import Path | ||
| 4 | import shutil | ||
| 5 | import struct | ||
| 6 | import subprocess | ||
| 7 | import sys | ||
| 8 | import tempfile | ||
| 9 | import unittest | ||
| 10 | |||
| 11 | REPO = Path(__file__).resolve().parents[2] | ||
| 12 | |||
| 13 | |||
| 14 | @unittest.skipUnless(__name__ == "__main__", "run through the windows_crash_monitor CTest target") | ||
| 15 | class CrashMonitorTest(unittest.TestCase): | ||
| 16 | def setUp(self): | ||
| 17 | tmp = tempfile.TemporaryDirectory(prefix="leonida crash test ") | ||
| 18 | self.addCleanup(tmp.cleanup) | ||
| 19 | self.report = Path(tmp.name) / "private run" | ||
| 20 | |||
| 21 | def run_fixture(self, mode, *args, seconds=10): | ||
| 22 | env = dict(os.environ, LEONIDA_TEST_CRASH_MODE=mode) | ||
| 23 | result = subprocess.run( | ||
| 24 | [MONITOR, REPO, self.report, str(seconds), FIXTURE, | ||
| 25 | subprocess.list2cmdline([str(FIXTURE), *args])], | ||
| 26 | env=env, capture_output=True, timeout=30, | ||
| 27 | ) | ||
| 28 | return result.returncode & 0xffffffff | ||
| 29 | |||
| 30 | def check_artifacts(self, code, exception): | ||
| 31 | data = (self.report / "crash.dmp").read_bytes() | ||
| 32 | self.assertEqual(data[:4], b"MDMP") | ||
| 33 | count, offset = struct.unpack_from("<II", data, 8) | ||
| 34 | streams = dict((kind, pos) for kind, size, pos in | ||
| 35 | (struct.unpack_from("<III", data, offset + 12*i) for i in range(count))) | ||
| 36 | self.assertIn(3, streams) # ThreadListStream | ||
| 37 | trace = (self.report / "stack.txt").read_text(encoding="utf-8", errors="replace") # module names may be in the ANSI code page | ||
| 38 | self.assertIn(f"code=0x{code:08x}", trace) | ||
| 39 | if exception: | ||
| 40 | pos = streams[6] # ExceptionStream: thread ID, padding, exception record | ||
| 41 | thread_id, _, actual_code = struct.unpack_from("<III", data, pos) | ||
| 42 | self.assertEqual(actual_code, code) | ||
| 43 | self.assertIn(f"thread={thread_id}\n", trace) | ||
| 44 | self.assertIn("kind=unhandled_exception", trace) | ||
| 45 | self.assertIn("#0 ", trace) | ||
| 46 | else: | ||
| 47 | self.assertNotIn(6, streams) | ||
| 48 | self.assertIn("kind=abnormal_exit", trace) | ||
| 49 | self.assertFalse((self.report / "crash.dmp.partial").exists()) | ||
| 50 | return trace | ||
| 51 | |||
| 52 | def test_worker(self): | ||
| 53 | code = 0xe0421234 | ||
| 54 | self.assertEqual(self.run_fixture("worker"), code) | ||
| 55 | trace = self.check_artifacts(code, True) | ||
| 56 | if FIXTURE.with_suffix(".pdb").exists(): | ||
| 57 | self.assertIn("crash_worker", trace) | ||
| 58 | |||
| 59 | def test_breakpoint(self): | ||
| 60 | self.assertEqual(self.run_fixture("break"), 0x80000003) | ||
| 61 | self.check_artifacts(0x80000003, True) | ||
| 62 | |||
| 63 | def test_explicit_exit(self): | ||
| 64 | self.assertEqual(self.run_fixture("exit"), 23) | ||
| 65 | trace = self.check_artifacts(23, False) | ||
| 66 | self.assertIn("#0 ", trace) | ||
| 67 | |||
| 68 | def test_exit_with_exception_number(self): | ||
| 69 | self.assertEqual(self.run_fixture("numeric"), 0xc0000005) | ||
| 70 | self.check_artifacts(0xc0000005, False) | ||
| 71 | |||
| 72 | def test_handled(self): | ||
| 73 | self.assertEqual(self.run_fixture("handled"), 0) | ||
| 74 | self.assertFalse(any(self.report.iterdir())) | ||
| 75 | |||
| 76 | def test_arguments_and_clean_exit(self): | ||
| 77 | self.assertEqual(self.run_fixture("argv", "a b\\", 'a"b'), 0) | ||
| 78 | self.assertFalse(any(self.report.iterdir())) | ||
| 79 | |||
| 80 | def test_timeout(self): | ||
| 81 | self.assertEqual(self.run_fixture("timer", seconds=1), 0) | ||
| 82 | self.assertEqual([p.name for p in self.report.iterdir()], ["timed-out"]) | ||
| 83 | |||
| 84 | def test_existing_directory(self): | ||
| 85 | self.report.mkdir() | ||
| 86 | sentinel = self.report / "keep" | ||
| 87 | sentinel.write_bytes(b"original") | ||
| 88 | self.assertNotEqual(self.run_fixture("worker"), 0) | ||
| 89 | self.assertEqual(list(self.report.iterdir()), [sentinel]) | ||
| 90 | self.assertEqual(sentinel.read_text(encoding="utf-8"), "original") | ||
| 91 | |||
| 92 | def test_repo_rejected(self): | ||
| 93 | self.report = REPO / (self.report.parent.name + "-forbidden") | ||
| 94 | self.assertNotEqual(self.run_fixture("worker"), 0) | ||
| 95 | self.assertFalse(self.report.exists()) | ||
| 96 | |||
| 97 | def test_boot_entry_point(self): | ||
| 98 | root = self.report.parent | ||
| 99 | (root / "MicrosoftGame.Config").touch() | ||
| 100 | (root / "index.json").write_bytes(b"{}") | ||
| 101 | (root / "exe").mkdir() | ||
| 102 | (root / "exe" / "index.json").write_bytes(b"{}") | ||
| 103 | (root / "gta6rt_tls_host.dll").touch() | ||
| 104 | fixture = shutil.copy2(FIXTURE, root) | ||
| 105 | shutil.copy2(MONITOR, root) | ||
| 106 | out = root / "output" | ||
| 107 | script = REPO / "scripts" / "windows-boot" / "boot.ps1" | ||
| 108 | # Isolate the fixture from a developer's normal boot settings and paths. | ||
| 109 | env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} | ||
| 110 | for mode, expected in (("exit", 23), ("timer", 0)): | ||
| 111 | with self.subTest(mode=mode): | ||
| 112 | result = subprocess.run( | ||
| 113 | ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script, | ||
| 114 | "-CrashDump", "-Name", mode, "-Runtime", fixture, "-Exe", fixture, "-GameDir", root, | ||
| 115 | "-Shaders", root, "-OutDir", out, "-Python", sys.executable, "-Seconds", | ||
| 116 | "1" if mode == "timer" else "10", "-LockWaitSeconds", "1", "-NoInput", "-NoCapture"], | ||
| 117 | env=dict(env, LEONIDA_TEST_CRASH_MODE=mode), capture_output=True, timeout=30, | ||
| 118 | ) | ||
| 119 | self.assertEqual(result.returncode, expected, (result.stdout, result.stderr)) | ||
| 120 | self.assertTrue((out / f"{mode}.digest.txt").is_file()) | ||
| 121 | self.assertIn(b"fixture stdout", (out / f"{mode}.stdout.log").read_bytes()) | ||
| 122 | self.assertIn(b"fixture stderr", (out / f"{mode}.log").read_bytes()) | ||
| 123 | report, = out.glob(f"{mode}-crash-*") | ||
| 124 | if mode == "exit": | ||
| 125 | self.assertTrue((report / "crash.dmp").is_file()) | ||
| 126 | else: | ||
| 127 | self.assertTrue((report / "timed-out").is_file()) | ||
| 128 | self.assertFalse((report / "crash.dmp").exists()) | ||
| 129 | |||
| 130 | |||
| 131 | if __name__ == "__main__": | ||
| 132 | MONITOR, FIXTURE = map(Path, sys.argv[1:3]) | ||
| 133 | unittest.main(argv=sys.argv[:1], verbosity=2) | ||