diff options
| author | OreoFR <tony37160@hotmail.fr> | 2026-11-30 11:29:46 +0100 |
|---|---|---|
| committer | OreoFR <tony37160@hotmail.fr> | 2026-11-30 11:29:46 +0100 |
| commit | ca71fd7f5c04ca3ec269fd3983e7201ac3344b8b (patch) | |
| tree | c92cfb77f76f7fd422f7efefcc8468526384af17 /scripts | |
| parent | e76cabc17a7400d6ab73da0e2689554b182df52a (diff) | |
| parent | 012b79a6787cd47d31dcf023eb2b67a1eac6d77f (diff) | |
Merge remote-tracking branch 'origin/main' into reprise-1837
Diffstat (limited to 'scripts')
46 files changed, 4312 insertions, 498 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py index 59aff3bc6..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: |
| @@ -263,8 +282,8 @@ def detect_wave64(insns): | |||
| 263 | 282 | ||
| 264 | 283 | ||
| 265 | def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None, *, report_path=None): | 284 | def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None, *, report_path=None): |
| 266 | if limit is not None and limit < 0: | 285 | if limit is not None and limit < 1: |
| 267 | raise ValueError("limit must be non-negative") | 286 | raise ValueError("limit must be at least 1") |
| 268 | parent = os.path.dirname(os.path.realpath(disasm_dir)) | 287 | parent = os.path.dirname(os.path.realpath(disasm_dir)) |
| 269 | fssm_dir = fssm_dir or os.path.join(parent, "fssm") | 288 | fssm_dir = fssm_dir or os.path.join(parent, "fssm") |
| 270 | dxbc_dir = dxbc_dir or parent | 289 | dxbc_dir = dxbc_dir or parent |
| @@ -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']}) ===") |
| @@ -395,16 +440,25 @@ def print_report(rep): | |||
| 395 | print(f" {v:6d} {k}") | 440 | print(f" {v:6d} {k}") |
| 396 | 441 | ||
| 397 | 442 | ||
| 443 | def shader_count(text): | ||
| 444 | """--limit: at least 1; 0 used to mean an audit of nothing that still printed a zero report.""" | ||
| 445 | try: | ||
| 446 | value = int(text, 0) | ||
| 447 | except ValueError: | ||
| 448 | raise argparse.ArgumentTypeError("must be at least 1") from None | ||
| 449 | if value < 1: | ||
| 450 | raise argparse.ArgumentTypeError("must be at least 1") | ||
| 451 | return value | ||
| 452 | |||
| 453 | |||
| 398 | def main(argv=None): | 454 | def main(argv=None): |
| 399 | ap = argparse.ArgumentParser(description="Audit CS/MS/GS RSRC2/PSV0 headers and read-before-write registers.") | 455 | ap = argparse.ArgumentParser(description="Audit CS/MS/GS RSRC2/PSV0 headers and read-before-write registers.") |
| 400 | ap.add_argument("disasm_dir", help="directory of disassembled .s files") | 456 | ap.add_argument("disasm_dir", help="directory of disassembled .s files") |
| 401 | ap.add_argument("--fssm", default=None, help="directory of .fssm files (default: <disasm_dir>/../fssm)") | 457 | ap.add_argument("--fssm", default=None, help="directory of .fssm files (default: <disasm_dir>/../fssm)") |
| 402 | ap.add_argument("--dxbc", default=None, help="directory of .dxbc files (default: <disasm_dir>/..)") | 458 | ap.add_argument("--dxbc", default=None, help="directory of .dxbc files (default: <disasm_dir>/..)") |
| 403 | ap.add_argument("--json", dest="json_out", default=None, help="optional path to write full JSON report") | 459 | ap.add_argument("--json", dest="json_out", default=None, help="optional path to write full JSON report") |
| 404 | ap.add_argument("--limit", type=int, default=None, help="stop after N .s files") | 460 | ap.add_argument("--limit", type=shader_count, default=None, help="stop after N .s files (at least 1)") |
| 405 | a = ap.parse_args(argv) | 461 | a = ap.parse_args(argv) |
| 406 | if a.limit is not None and a.limit < 0: | ||
| 407 | ap.exit(2, f"{ap.prog}: error: --limit must be non-negative\n") | ||
| 408 | # A bad path is one ERROR line, not a traceback out of os.listdir: the audit of a whole corpus can | 462 | # A bad path is one ERROR line, not a traceback out of os.listdir: the audit of a whole corpus can |
| 409 | # run for minutes, and an explicit --fssm/--dxbc that does not exist would otherwise be counted as | 463 | # run for minutes, and an explicit --fssm/--dxbc that does not exist would otherwise be counted as |
| 410 | # "(missing fssm)" and print a report that looks right. | 464 | # "(missing fssm)" and print a report that looks right. |
| @@ -418,7 +472,7 @@ def main(argv=None): | |||
| 418 | print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) | 472 | print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) |
| 419 | return 2 | 473 | return 2 |
| 420 | 474 | ||
| 421 | 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 |
| 422 | try: | 476 | try: |
| 423 | 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) |
| 424 | except ReportInputCollision as error: | 478 | except ReportInputCollision as error: |
| @@ -427,10 +481,7 @@ def main(argv=None): | |||
| 427 | print_report(rep) | 481 | print_report(rep) |
| 428 | if a.json_out: | 482 | if a.json_out: |
| 429 | try: | 483 | try: |
| 430 | os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True) | 484 | write_json(a.json_out, rep) |
| 431 | with open(a.json_out, "w", encoding="utf-8", newline="\n") as f: | ||
| 432 | json.dump(rep, f, indent=2) | ||
| 433 | f.write("\n") | ||
| 434 | except OSError as e: | 485 | except OSError as e: |
| 435 | 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) |
| 436 | 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..387a77d83 100644 --- a/scripts/build_llvm_mc.ps1 +++ b/scripts/build_llvm_mc.ps1 | |||
| @@ -19,12 +19,17 @@ param( | |||
| 19 | ) | 19 | ) |
| 20 | $ErrorActionPreference = "Stop" | 20 | $ErrorActionPreference = "Stop" |
| 21 | 21 | ||
| 22 | if ([string]::IsNullOrWhiteSpace($Version) -or $Version -match '[\s\x00-\x1f%]') { | ||
| 23 | throw "-Version '$Version' is not a valid LLVM release version." | ||
| 24 | } | ||
| 25 | |||
| 22 | # cmd.exe expands %...% on every line of _build.cmd (twice on a CALL line), so a -Temp with % in it breaks the build. | 26 | # 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 %). | 27 | # 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)) | 28 | $fullTemp = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Temp)) |
| 25 | if ($fullTemp.Contains('%')) { | 29 | 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." | 30 | throw "-Temp '$fullTemp' contains '%', which cmd.exe expands in the generated _build.cmd. Choose a -Temp folder without % in its path." |
| 27 | } | 31 | } |
| 32 | $Temp = $fullTemp | ||
| 28 | 33 | ||
| 29 | if (-not $Keep) { | 34 | if (-not $Keep) { |
| 30 | # Compare directory boundaries, including when the paths do not exist yet. | 35 | # Compare directory boundaries, including when the paths do not exist yet. |
| @@ -40,19 +45,26 @@ foreach ($t in "git", "python") { | |||
| 40 | if (-not (Get-Command $t -ErrorAction SilentlyContinue)) { throw "$t wasn't found on PATH." } | 45 | if (-not (Get-Command $t -ErrorAction SilentlyContinue)) { throw "$t wasn't found on PATH." } |
| 41 | } | 46 | } |
| 42 | $installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer" | 47 | $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 | 48 | $vswhere = Join-Path $installer "vswhere.exe" |
| 49 | if (-not (Test-Path -LiteralPath $vswhere -PathType Leaf)) { throw "Visual Studio with the C++ x64 tools wasn't found." } | ||
| 50 | $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." } | 51 | if (-not $vs) { throw "Visual Studio with the C++ x64 tools wasn't found." } |
| 45 | $vcvars = Join-Path $vs "VC\Auxiliary\Build\vcvars64.bat" | 52 | $vcvars = Join-Path $vs "VC\Auxiliary\Build\vcvars64.bat" |
| 53 | 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)) | 54 | $jobs = [Math]::Max(1, [int]([Environment]::ProcessorCount / 2)) |
| 47 | 55 | ||
| 48 | $cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake" | 56 | $cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake" |
| 49 | $cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" | 57 | $cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" |
| 58 | if (-not (Test-Path -LiteralPath $cmake -PathType Leaf)) { | ||
| 59 | $cmakeCmd = Get-Command cmake -ErrorAction SilentlyContinue | ||
| 60 | $cmake = if ($cmakeCmd) { $cmakeCmd.Source } else { $null } | ||
| 61 | } | ||
| 50 | $ninja = Join-Path $cmakeDir "Ninja\ninja.exe" | 62 | $ninja = Join-Path $cmakeDir "Ninja\ninja.exe" |
| 51 | if (-not ((Test-Path $cmake) -and (Test-Path $ninja))) { | 63 | if (-not (Test-Path -LiteralPath $ninja -PathType Leaf)) { |
| 52 | $cmake = (Get-Command cmake -ErrorAction SilentlyContinue).Source | 64 | $ninjaCmd = Get-Command ninja -ErrorAction SilentlyContinue |
| 53 | $ninja = (Get-Command ninja -ErrorAction SilentlyContinue).Source | 65 | $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 | } | 66 | } |
| 67 | if (-not ($cmake -and $ninja)) { throw "CMake and Ninja weren't found (install VS's 'C++ CMake tools' or put them on PATH)." } | ||
| 56 | 68 | ||
| 57 | $src = Join-Path $Temp "src" | 69 | $src = Join-Path $Temp "src" |
| 58 | $out = Join-Path $Temp "build" | 70 | $out = Join-Path $Temp "build" |
| @@ -144,14 +156,14 @@ if ($p.ExitCode -ne 0) { throw "build failed ($($p.ExitCode)); the build folder | |||
| 144 | $exe = Join-Path $out "bin\llvm-mc.exe" | 156 | $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. | 157 | # 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" | 158 | $probeFile = Join-Path $Temp "probe.txt" |
| 147 | [IO.File]::WriteAllText($probeFile, "0x00 0x00 0x81 0xbf`n") | 159 | [IO.File]::WriteAllText($probeFile, "0x00 0x00 0x81 0xbf`n", [System.Text.UTF8Encoding]::new($false)) |
| 148 | $probe = & $exe --disassemble -triple=amdgcn -mcpu=gfx1013 $probeFile | 160 | $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" } | 161 | if ($LASTEXITCODE -ne 0 -or -not ($probe -match "s_endpgm")) { throw "the built llvm-mc didn't disassemble an s_endpgm" } |
| 150 | 162 | ||
| 151 | New-Item -ItemType Directory -Force $Dest | Out-Null | 163 | New-Item -ItemType Directory -Force $Dest | Out-Null |
| 152 | # LLVM_MC is saved for future terminals, whose working directory can differ from this one. | 164 | # 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")) | 165 | $final = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath((Join-Path $Dest "llvm-mc.exe")) |
| 154 | Copy-Item -Force $exe $final | 166 | Copy-Item -LiteralPath $exe -Destination $final -Force |
| 155 | if (-not $Keep) { | 167 | if (-not $Keep) { |
| 156 | Remove-DirectoryRobust $Temp | 168 | Remove-DirectoryRobust $Temp |
| 157 | if (Test-Path -LiteralPath $Temp) { | 169 | 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 new file mode 100644 index 000000000..1ef6eb501 --- /dev/null +++ b/scripts/check_compute_journal_overlay.py | |||
| @@ -0,0 +1,134 @@ | |||
| 1 | """Check a disposable journal against two locally generated compute PSOs. No game files needed. | ||
| 2 | |||
| 3 | Build d3d12_compute_journal_test first, then run this script with the path to that executable. | ||
| 4 | --require-hit also requires the driver's application-cache-hit bit (not a timing heuristic). | ||
| 5 | """ | ||
| 6 | import argparse | ||
| 7 | import hashlib | ||
| 8 | import json | ||
| 9 | import os | ||
| 10 | from pathlib import Path | ||
| 11 | import re | ||
| 12 | import shutil | ||
| 13 | import subprocess | ||
| 14 | import sys | ||
| 15 | import tempfile | ||
| 16 | import time | ||
| 17 | |||
| 18 | |||
| 19 | def require(ok, message): | ||
| 20 | if not ok: | ||
| 21 | raise RuntimeError(message) | ||
| 22 | |||
| 23 | |||
| 24 | def entries(cache): | ||
| 25 | d = cache / "pipeline_cache.d" | ||
| 26 | if not d.exists(): | ||
| 27 | return {} | ||
| 28 | require(d.is_dir(), "pipeline_cache.d is not a directory") | ||
| 29 | out = {} | ||
| 30 | for p in d.iterdir(): | ||
| 31 | require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and | ||
| 32 | 32 < p.stat().st_size <= 8 << 20, "unexpected file in one-PSO journal") | ||
| 33 | out[p.name] = (hashlib.sha256(p.read_bytes()).digest(), p.stat().st_mtime_ns) | ||
| 34 | return out | ||
| 35 | |||
| 36 | |||
| 37 | def run(exe, root, device, strict): | ||
| 38 | seed = root / "cold" | ||
| 39 | before = None | ||
| 40 | results = {} | ||
| 41 | adapter = None | ||
| 42 | for label, second in (("cold", False), ("external-A", False), | ||
| 43 | ("new-B", True), ("local-B", True)): | ||
| 44 | cache = root / label | ||
| 45 | cache.mkdir() | ||
| 46 | if label == "local-B": | ||
| 47 | # Bring only B into a fresh process; no session or shared cache crosses this boundary. | ||
| 48 | (cache / "pipeline_cache.d").mkdir() | ||
| 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] | ||
| 53 | shutil.copy2(src, cache / "pipeline_cache.d" / src.name) | ||
| 54 | local_before = entries(cache) | ||
| 55 | env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} | ||
| 56 | env.update(LEONIDA_PIPELINE_CACHE_DIR=str(cache), LEONIDA_TRACE_PIPELINE_COMPILE="1", | ||
| 57 | LEONIDA_PIPELINE_CACHE_BYTES=str(8 << 20), LEONIDA_PIPELINE_JOURNAL_BYTES=str(8 << 20), | ||
| 58 | LEONIDA_PIPELINE_JOURNAL="1") | ||
| 59 | if device: | ||
| 60 | env["LEONIDA_VK_DEVICE"] = device | ||
| 61 | if label != "cold": | ||
| 62 | env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d") | ||
| 63 | p = subprocess.run([str(exe)] + (["--second-shader"] if second else []), | ||
| 64 | stdin=subprocess.DEVNULL, capture_output=True, text=True, | ||
| 65 | encoding="utf-8", errors="replace", | ||
| 66 | cwd=cache, env=env, timeout=60) | ||
| 67 | if p.returncode == 77: | ||
| 68 | print("SKIP: the authored compute fixture is unsupported on this device") | ||
| 69 | return 77 | ||
| 70 | expected = 14 if second else 10 | ||
| 71 | require(p.returncode == 0 and | ||
| 72 | f"compute journal: direct Dispatch(4,1,1) copied both expected words (4,{expected})" | ||
| 73 | in p.stdout.splitlines(), f"{label}: GPU readback did not match") | ||
| 74 | devices = [x.removeprefix("device: ") for x in p.stdout.splitlines() if x.startswith("device: ")] | ||
| 75 | require(len(devices) == 1 and (adapter is None or adapter == devices[0]), "inconsistent GPU selection") | ||
| 76 | adapter = devices[0] | ||
| 77 | calls = [x for x in p.stderr.splitlines() if x.startswith("[rt] pipeline-compile trigger=")] | ||
| 78 | require(len(calls) == 1, f"{label}: expected one compute creation") | ||
| 79 | m = re.search(r" hit=(-1|0|1) bytes=\d+ variant=\d+ result=0 ", calls[0]) | ||
| 80 | require(m is not None, f"{label}: missing feedback field or unsuccessful create") | ||
| 81 | hit = int(m[1]) | ||
| 82 | local = entries(cache) | ||
| 83 | if label == "cold": | ||
| 84 | require(len(local) == 1, "cold A was not journaled") | ||
| 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] | ||
| 90 | # Make an erroneous hourly LRU touch observable without making the probe depend on system time. | ||
| 91 | old = time.time_ns() - 48 * 3600 * 10**9 | ||
| 92 | os.utime(source, ns=(old, old)) | ||
| 93 | before = entries(seed) | ||
| 94 | elif label == "new-B": | ||
| 95 | require(len(local) == 1 and not (local.keys() & before.keys()), "missing distinct local B") | ||
| 96 | else: | ||
| 97 | if strict: | ||
| 98 | require(hit == 1, f"{label}: driver reported no application-cache hit") | ||
| 99 | if hit == 1: | ||
| 100 | require(local == local_before, f"{label}: cache hit changed disposable journal") | ||
| 101 | require(entries(seed) == before, f"{label}: seed contents or last-write time changed") | ||
| 102 | results[label] = {"readback": [4, expected], "driver_hit": hit, "local_entries": len(local)} | ||
| 103 | print(json.dumps({"device": adapter, "runs": results}, sort_keys=True)) | ||
| 104 | return 0 | ||
| 105 | |||
| 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 | |||
| 129 | if __name__ == "__main__": | ||
| 130 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 131 | sys.stdout.reconfigure(errors="replace") | ||
| 132 | except (AttributeError, ValueError, OSError): | ||
| 133 | pass | ||
| 134 | raise SystemExit(main()) | ||
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 new file mode 100644 index 000000000..860d91bf3 --- /dev/null +++ b/scripts/compute_workers_win.py | |||
| @@ -0,0 +1,223 @@ | |||
| 1 | """Windows process/lock adapter for translate_pipeline_compute.py (CPython, no extra packages). | ||
| 2 | |||
| 3 | Only a small bootstrap runs before job assignment. It receives no input path or work until the | ||
| 4 | parent verifies its job and opens the gate. Parent death closes the gate or the kill-on-close job. | ||
| 5 | """ | ||
| 6 | import contextlib | ||
| 7 | import ctypes as c | ||
| 8 | from ctypes import wintypes as w | ||
| 9 | import json | ||
| 10 | import os | ||
| 11 | from pathlib import Path | ||
| 12 | import subprocess | ||
| 13 | import sys | ||
| 14 | import time | ||
| 15 | |||
| 16 | kernel = c.WinDLL("kernel32", use_last_error=True) | ||
| 17 | H, D, Z = w.HANDLE, w.DWORD, c.c_size_t | ||
| 18 | |||
| 19 | |||
| 20 | def api(name, result, *args): | ||
| 21 | f = getattr(kernel, name) | ||
| 22 | f.argtypes, f.restype = args, result | ||
| 23 | return f | ||
| 24 | |||
| 25 | |||
| 26 | def check(value): | ||
| 27 | if not value: | ||
| 28 | raise c.WinError(c.get_last_error()) | ||
| 29 | return value | ||
| 30 | |||
| 31 | |||
| 32 | class Basic(c.Structure): | ||
| 33 | _fields_ = [("time", c.c_int64 * 2), ("flags", D), ("min_ws", Z), ("max_ws", Z), | ||
| 34 | ("processes", D), ("affinity", Z), ("priority", D), ("scheduling", D)] | ||
| 35 | |||
| 36 | |||
| 37 | class Extended(c.Structure): | ||
| 38 | _fields_ = [("basic", Basic), ("io", c.c_uint64 * 6), ("process_mem", Z), | ||
| 39 | ("job_mem", Z), ("peak_process", Z), ("peak_job", Z)] | ||
| 40 | |||
| 41 | |||
| 42 | class Accounting(c.Structure): | ||
| 43 | _fields_ = [("time", c.c_int64 * 4), ("faults", D), ("total", D), ("active", D), ("ended", D)] | ||
| 44 | |||
| 45 | |||
| 46 | close = api("CloseHandle", w.BOOL, H) | ||
| 47 | create_job = api("CreateJobObjectW", H, H, w.LPCWSTR) | ||
| 48 | set_job = api("SetInformationJobObject", w.BOOL, H, D, H, D) | ||
| 49 | query_job = api("QueryInformationJobObject", w.BOOL, H, D, H, D, H) | ||
| 50 | assign = api("AssignProcessToJobObject", w.BOOL, H, H) | ||
| 51 | inside = api("IsProcessInJob", w.BOOL, H, H, c.POINTER(w.BOOL)) | ||
| 52 | terminate = api("TerminateJobObject", w.BOOL, H, D) | ||
| 53 | current = api("GetCurrentProcess", H) | ||
| 54 | priority = api("GetPriorityClass", D, H) | ||
| 55 | create_file = api("CreateFileW", H, w.LPCWSTR, D, D, H, D, D, H) | ||
| 56 | LOW = subprocess.BELOW_NORMAL_PRIORITY_CLASS | ||
| 57 | PROCESS_MEMORY, PRIORITY, TWO_ACTIVE, KILL_ON_CLOSE = 0x100, 0x20, 0x8, 0x2000 | ||
| 58 | |||
| 59 | |||
| 60 | def flags(worker): | ||
| 61 | return PROCESS_MEMORY | PRIORITY | ((TWO_ACTIVE | KILL_ON_CLOSE) if worker else 0) | ||
| 62 | |||
| 63 | |||
| 64 | def verify(job, process, mib, worker): | ||
| 65 | info, member = Extended(), w.BOOL() | ||
| 66 | check(inside(process, job, c.byref(member))) | ||
| 67 | check(query_job(job, 9, c.byref(info), c.sizeof(info), None)) | ||
| 68 | if (not member.value or info.basic.flags != flags(worker) or info.process_mem != mib << 20 or | ||
| 69 | info.basic.priority != LOW or priority(process) != LOW or | ||
| 70 | (worker and info.basic.processes != 2)): | ||
| 71 | raise RuntimeError("Windows compute job limits not in force") | ||
| 72 | |||
| 73 | |||
| 74 | @contextlib.contextmanager | ||
| 75 | def job(mib, worker): | ||
| 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") | ||
| 78 | h = check(create_job(None, None)) # unnamed, never inherited; no breakaway | ||
| 79 | try: | ||
| 80 | info = Extended() | ||
| 81 | info.basic.flags, info.basic.priority = flags(worker), LOW | ||
| 82 | info.basic.processes, info.process_mem = (2 if worker else 0), mib << 20 | ||
| 83 | check(set_job(h, 9, c.byref(info), c.sizeof(info))) | ||
| 84 | yield h | ||
| 85 | finally: | ||
| 86 | check(close(h)) | ||
| 87 | |||
| 88 | |||
| 89 | def budget_coordinator(mib): | ||
| 90 | # No KILL_ON_CLOSE for the caller itself. Its limits survive handle close until process exit. | ||
| 91 | with job(mib, False) as h: | ||
| 92 | check(assign(h, current())) | ||
| 93 | verify(h, current(), mib, False) | ||
| 94 | |||
| 95 | |||
| 96 | @contextlib.contextmanager | ||
| 97 | def output_lock(path): | ||
| 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. | ||
| 100 | h = create_file(str(path), 0xc0000000, 0, None, 4, 0x80, None) | ||
| 101 | if not h or h == H(-1).value: | ||
| 102 | raise c.WinError(c.get_last_error()) | ||
| 103 | try: | ||
| 104 | yield h | ||
| 105 | finally: | ||
| 106 | check(close(h)) | ||
| 107 | |||
| 108 | |||
| 109 | def drain(h): | ||
| 110 | check(terminate(h, 1)) | ||
| 111 | end = time.monotonic()+10 | ||
| 112 | while True: | ||
| 113 | a = Accounting() | ||
| 114 | check(query_job(h, 1, c.byref(a), c.sizeof(a), None)) | ||
| 115 | if not a.active: | ||
| 116 | return | ||
| 117 | if time.monotonic() >= end: | ||
| 118 | raise RuntimeError("Windows compute job did not drain") | ||
| 119 | time.sleep(.02) | ||
| 120 | |||
| 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 | |||
| 131 | @contextlib.contextmanager | ||
| 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") | ||
| 141 | with job(mib, True) as h: | ||
| 142 | si = subprocess.STARTUPINFO(lpAttributeList={"handle_list": [lock]}) | ||
| 143 | os.set_handle_inheritable(lock, True) | ||
| 144 | try: | ||
| 145 | p = subprocess.Popen([_worker_executable(), "-I", "-B", str(Path(__file__).resolve()), "--shard"], | ||
| 146 | stdin=subprocess.PIPE, startupinfo=si, close_fds=True, creationflags=LOW) | ||
| 147 | finally: | ||
| 148 | os.set_handle_inheritable(lock, False) | ||
| 149 | attached = False | ||
| 150 | try: | ||
| 151 | check(assign(h, int(p._handle))) | ||
| 152 | attached = True | ||
| 153 | verify(h, int(p._handle), mib, True) | ||
| 154 | # EOF, even after a short write, is not permission to start. | ||
| 155 | p.stdin.write(gate) | ||
| 156 | p.stdin.close() | ||
| 157 | yield p | ||
| 158 | finally: | ||
| 159 | try: | ||
| 160 | if attached: | ||
| 161 | drain(h) # also stop/wait for a descendant if the Python worker died early | ||
| 162 | elif p.poll() is None: | ||
| 163 | p.kill() # gated bootstrap, no descendant or input path | ||
| 164 | finally: | ||
| 165 | try: | ||
| 166 | if not p.stdin.closed: | ||
| 167 | p.stdin.close() | ||
| 168 | finally: | ||
| 169 | p.wait(timeout=10) | ||
| 170 | |||
| 171 | |||
| 172 | def run(requests, mib, lock): | ||
| 173 | with contextlib.ExitStack() as stack: | ||
| 174 | procs = [stack.enter_context(start(p, mib, lock)) for p in requests] | ||
| 175 | while True: | ||
| 176 | codes = [p.poll() for p in procs] | ||
| 177 | if any(rc not in (None, 0) for rc in codes): | ||
| 178 | raise RuntimeError(f"Windows translation worker failed: {codes}") | ||
| 179 | if all(rc == 0 for rc in codes): | ||
| 180 | return | ||
| 181 | time.sleep(.05) | ||
| 182 | |||
| 183 | |||
| 184 | def child(): | ||
| 185 | line = sys.stdin.buffer.readline(65537) | ||
| 186 | if not line.endswith(b"\n") or len(line) > 65536: | ||
| 187 | raise ValueError("no complete Windows compute gate") | ||
| 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) | ||
| 209 | sys.path.insert(0, str(Path(__file__).resolve().parent)) | ||
| 210 | from translate_pipeline_compute import run_request | ||
| 211 | run_request(Path(request)) | ||
| 212 | finally: | ||
| 213 | check(close(lock)) | ||
| 214 | |||
| 215 | |||
| 216 | if __name__ == "__main__": | ||
| 217 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 218 | sys.stdout.reconfigure(errors="replace") | ||
| 219 | except (AttributeError, ValueError, OSError): | ||
| 220 | pass | ||
| 221 | if sys.argv[1:] != ["--shard"]: | ||
| 222 | raise SystemExit(2) | ||
| 223 | child() | ||
diff --git a/scripts/corpus_watch.py b/scripts/corpus_watch.py new file mode 100644 index 000000000..fdc48b7aa --- /dev/null +++ b/scripts/corpus_watch.py | |||
| @@ -0,0 +1,226 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Counts-only corpus regression watch. | ||
| 3 | |||
| 4 | Runs `make_game.py --stages check,shaders` against your own copy, then records | ||
| 5 | COUNTS ONLY (carved / translated / spirv-val-validated, per stage) against the | ||
| 6 | checked-out commit. This is the same counting the progress dashboard uses, so | ||
| 7 | a drop between snapshots is a regression. | ||
| 8 | |||
| 9 | Nothing derived from game data is written to the results file: no shader names, | ||
| 10 | no carved file names, no paths into the game copy. Diagnostic logs stay local | ||
| 11 | and may contain paths; never publish them. | ||
| 12 | |||
| 13 | python3 -I scripts/corpus_watch.py --game <pkg> --work <work> --out <out> \ | ||
| 14 | --report <folder outside the repo> --results <counts.jsonl> --once | ||
| 15 | python3 -I scripts/corpus_watch.py ... --interval 6 --pull | ||
| 16 | |||
| 17 | Standard library only; all text writes name their line ending. | ||
| 18 | """ | ||
| 19 | import argparse | ||
| 20 | import json | ||
| 21 | import math | ||
| 22 | import os | ||
| 23 | import shutil | ||
| 24 | import subprocess | ||
| 25 | import sys | ||
| 26 | import time | ||
| 27 | from datetime import datetime, timezone | ||
| 28 | |||
| 29 | # -I removes the script folder from sys.path, so add tools/ explicitly. | ||
| 30 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools")) | ||
| 31 | from report_paths import same_report_path # noqa: E402 | ||
| 32 | |||
| 33 | MIN_FREE = 40 * 1024**3 | ||
| 34 | |||
| 35 | |||
| 36 | def corpus_counts(work): | ||
| 37 | """Return counts-only dict, or None when the shader stage produced no indexes. | ||
| 38 | |||
| 39 | Mirrors tools/progress_dashboard.py: entries in dxbc/index.json are carved; | ||
| 40 | entries in spirv/index.json without an 'error' key passed spirv-val. | ||
| 41 | """ | ||
| 42 | dxbc = os.path.join(work, "shaders", "dxbc", "index.json") | ||
| 43 | spirv_path = os.path.join(work, "shaders", "spirv", "index.json") | ||
| 44 | if not os.path.isfile(dxbc): | ||
| 45 | old_dxbc = os.path.join(work, "dxbc", "index.json") | ||
| 46 | if not os.path.isfile(old_dxbc): | ||
| 47 | return None | ||
| 48 | dxbc = old_dxbc | ||
| 49 | spirv_path = os.path.join(work, "spirv", "index.json") | ||
| 50 | |||
| 51 | with open(dxbc, encoding="utf-8-sig") as f: | ||
| 52 | carved = json.load(f) | ||
| 53 | if not isinstance(carved, (list, dict)): | ||
| 54 | raise ValueError(f"{dxbc}: expected a JSON list or object") | ||
| 55 | entries = carved if isinstance(carved, list) else list(carved.values()) | ||
| 56 | |||
| 57 | per_stage = {} | ||
| 58 | validated = 0 | ||
| 59 | spirv_entries = 0 | ||
| 60 | if os.path.isfile(spirv_path): | ||
| 61 | with open(spirv_path, encoding="utf-8-sig") as f: | ||
| 62 | spirv = json.load(f) | ||
| 63 | if not isinstance(spirv, dict): | ||
| 64 | raise ValueError(f"{spirv_path}: expected a JSON object") | ||
| 65 | spirv_entries = len(spirv) | ||
| 66 | for meta in spirv.values(): | ||
| 67 | if isinstance(meta, dict) and "error" not in meta: | ||
| 68 | stage = meta.get("stage") or "unknown" | ||
| 69 | per_stage.setdefault(stage, [0, 0])[1] += 1 | ||
| 70 | validated += 1 | ||
| 71 | for entry in entries: | ||
| 72 | stage = (entry.get("stage") if isinstance(entry, dict) else None) or "unknown" | ||
| 73 | per_stage.setdefault(stage, [0, 0])[0] += 1 | ||
| 74 | |||
| 75 | return {"carved": len(entries), "spirv_entries": spirv_entries, | ||
| 76 | "validated": validated, "per_stage": per_stage} | ||
| 77 | |||
| 78 | |||
| 79 | def outputs_collide(work, report, results, log, game=None, out=None): | ||
| 80 | """Refuse an output that names an input or another output.""" | ||
| 81 | outputs = [p for p in (report, results, log, out) if p] | ||
| 82 | for i, first in enumerate(outputs): | ||
| 83 | for second in outputs[i + 1:]: | ||
| 84 | if same_report_path(first, second): | ||
| 85 | return True | ||
| 86 | inputs = [p for p in (work, game) if p] | ||
| 87 | if work: | ||
| 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 | ||
| 98 | return False | ||
| 99 | |||
| 100 | |||
| 101 | def main(argv=None): | ||
| 102 | ap = argparse.ArgumentParser(description=__doc__) | ||
| 103 | ap.add_argument("--game", required=True, help="your package folder") | ||
| 104 | ap.add_argument("--work", required=True, help="work folder (outside the repo)") | ||
| 105 | ap.add_argument("--out", required=True, help="built port folder (outside the repo)") | ||
| 106 | ap.add_argument("--report", required=True, help="progress dashboard folder (outside the repo)") | ||
| 107 | ap.add_argument("--results", required=True, help="counts-only JSONL file") | ||
| 108 | ap.add_argument("--log", help="local diagnostic log (may contain paths; never publish)") | ||
| 109 | ap.add_argument("--stages", default="check,shaders") | ||
| 110 | ap.add_argument("--interval", type=float, metavar="HOURS", default=0) | ||
| 111 | ap.add_argument("--once", action="store_true") | ||
| 112 | ap.add_argument("--pull", action="store_true", help="git pull --ff-only before each run") | ||
| 113 | ap.add_argument("--github", action="store_true", help="also refresh dashboard PR/CI panels") | ||
| 114 | ap.add_argument("--jobs", type=int) | ||
| 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") | ||
| 118 | if not a.once and a.interval <= 0: | ||
| 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}") | ||
| 125 | |||
| 126 | repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 127 | log_path = a.log | ||
| 128 | |||
| 129 | def log(msg): | ||
| 130 | line = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}" | ||
| 131 | print(line, flush=True) | ||
| 132 | if log_path: | ||
| 133 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: | ||
| 134 | f.write(line + "\n") | ||
| 135 | |||
| 136 | if outputs_collide(a.work, a.report, a.results, log_path, game=a.game, out=a.out): | ||
| 137 | ap.error("an output names the work folder or another output") | ||
| 138 | |||
| 139 | for tool in ("llvm-mc", "spirv-val", "git"): | ||
| 140 | if not shutil.which(tool): | ||
| 141 | ap.error(f"missing tool: {tool}") | ||
| 142 | if not os.path.isdir(a.game): | ||
| 143 | ap.error("game folder not found") | ||
| 144 | probe = subprocess.run( | ||
| 145 | ["llvm-mc", "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1013", | ||
| 146 | "-filetype=obj", "-o", os.devnull], | ||
| 147 | input="s_nop 0\n", text=True, encoding="utf-8", errors="replace", capture_output=True) | ||
| 148 | if probe.returncode != 0: | ||
| 149 | ap.error("llvm-mc cannot assemble gfx1013 (AMDGPU target missing)") | ||
| 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 | |||
| 157 | def run(cmd, timeout): | ||
| 158 | return subprocess.run(cmd, cwd=repo, text=True, encoding="utf-8", errors="replace", | ||
| 159 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout) | ||
| 160 | |||
| 161 | def run_once(): | ||
| 162 | if a.pull: | ||
| 163 | r = run(["git", "pull", "--ff-only"], 300) | ||
| 164 | if r.returncode != 0: | ||
| 165 | log("git pull failed:\n" + r.stdout[-2000:]) | ||
| 166 | return 1 | ||
| 167 | sha = run(["git", "rev-parse", "HEAD"], 60).stdout.strip() | ||
| 168 | log(f"commit {sha}") | ||
| 169 | for folder in (a.work, a.out, a.report): | ||
| 170 | os.makedirs(folder, exist_ok=True) | ||
| 171 | cmd = [sys.executable, "-I", "make_game.py", "--game", a.game, | ||
| 172 | "--work", a.work, "--out", a.out, "--stages", a.stages] | ||
| 173 | if a.jobs: | ||
| 174 | cmd += ["--jobs", str(a.jobs)] | ||
| 175 | log("running make_game.py (paths omitted from the local log)") | ||
| 176 | r = run(cmd, 6 * 3600) | ||
| 177 | if log_path: | ||
| 178 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: | ||
| 179 | f.write(r.stdout + "\n") | ||
| 180 | log(f"make_game.py exit {r.returncode}") | ||
| 181 | |||
| 182 | counts = corpus_counts(a.work) | ||
| 183 | record = {"time": datetime.now(timezone.utc).isoformat(), "commit": sha, | ||
| 184 | "make_game_exit": r.returncode, "counts": counts} | ||
| 185 | with open(a.results, "a", encoding="utf-8", newline="\n") as f: | ||
| 186 | f.write(json.dumps(record, sort_keys=True) + "\n") | ||
| 187 | |||
| 188 | dash = [sys.executable, "-I", "tools/progress_dashboard.py", | ||
| 189 | "--work", a.work, "--out", a.report, "--run-tests"] | ||
| 190 | if a.github: | ||
| 191 | dash.append("--github") | ||
| 192 | d = run(dash, 900) | ||
| 193 | log(f"dashboard exit {d.returncode}") | ||
| 194 | |||
| 195 | if counts: | ||
| 196 | log(f"COUNTS carved={counts['carved']} spirv={counts['spirv_entries']} " | ||
| 197 | f"validated={counts['validated']}") | ||
| 198 | for stage, (nc, nv) in sorted(counts["per_stage"].items()): | ||
| 199 | log(f" {stage}: {nv}/{nc} validated") | ||
| 200 | with open(a.results, encoding="utf-8-sig") as f: | ||
| 201 | previous = [json.loads(x) for x in f if x.strip()] | ||
| 202 | if len(previous) >= 2: | ||
| 203 | before = previous[-2].get("counts") or {} | ||
| 204 | log(f"DELTA validated {before.get('validated')} -> {counts['validated']}, " | ||
| 205 | f"carved {before.get('carved')} -> {counts['carved']}") | ||
| 206 | if counts["validated"] < before.get("validated", 0): | ||
| 207 | log("REGRESSION: validated count decreased") | ||
| 208 | else: | ||
| 209 | log("no corpus indexes produced") | ||
| 210 | log(f"counts-only record: {a.results}") | ||
| 211 | return 0 | ||
| 212 | |||
| 213 | rc = run_once() | ||
| 214 | if a.once or a.interval <= 0: | ||
| 215 | return rc | ||
| 216 | while True: | ||
| 217 | time.sleep(a.interval * 3600) | ||
| 218 | run_once() | ||
| 219 | |||
| 220 | |||
| 221 | if __name__ == "__main__": | ||
| 222 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 223 | sys.stdout.reconfigure(errors="replace") | ||
| 224 | except (AttributeError, ValueError, OSError): | ||
| 225 | pass | ||
| 226 | sys.exit(main()) | ||
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 6fb7ca36b..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,12 +118,23 @@ 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 } |
| 125 | # "unverified" only comes from a host that isn't Windows and has no Wine prefix (pe_inspect.py, classify_dll): most | ||
| 126 | # are system DLLs, but a console DLL the shims don't serve yet is among them, so they follow the list, marked. | ||
| 127 | $unverified = @($report.imports | Where-Object { $_.where -eq "unverified" } | Sort-Object { -$_.functions.Count }) | ||
| 128 | if ($unverified.Count -gt 0) { | ||
| 129 | $lines = @(foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count }) + | ||
| 130 | @(foreach ($t in $unverified) { "{0,-40} {1,5} system (unverified)" -f $t.dll, $t.functions.Count }) | ||
| 131 | } | ||
| 108 | Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines | 132 | Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines |
| 109 | Write-Host "`n== Shim to-do (DLL, function count)" | 133 | Write-Host "`n== Shim to-do (DLL, function count)" |
| 110 | $lines | 134 | $lines |
| 135 | if ($unverified.Count -gt 0) { | ||
| 136 | Write-Warning "$($unverified.Count) DLLs could not be checked against system DLLs (no Wine prefix): set WINEPREFIX and run again" | ||
| 137 | } | ||
| 111 | $enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } | 138 | $enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } |
| 112 | if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } | 139 | if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } |
| 113 | Write-Host "`nReports: $out" | 140 | Write-Host "`nReports: $out" |
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 e270cbe00..5499da29c 100644 --- a/scripts/merge_check.py +++ b/scripts/merge_check.py | |||
| @@ -41,13 +41,13 @@ class GitError(Exception): | |||
| 41 | pass | 41 | pass |
| 42 | 42 | ||
| 43 | 43 | ||
| 44 | def git(repo, *args, check=True): | 44 | def git(repo, *args, check=True, stdout_errors="replace"): |
| 45 | try: | 45 | try: |
| 46 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True) | 46 | r = subprocess.run(["git", "-C", repo, *args], capture_output=True) |
| 47 | except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback | 47 | except OSError as e: # git is not on PATH, or cannot be executed: a usage error (exit 2), not a traceback |
| 48 | raise GitError(f"cannot run git: {e.strerror or e}") from None | 48 | raise GitError(f"cannot run git: {e.strerror or e}") from None |
| 49 | # Decode without universal-newline translation: a bare CR inside a Git line is content. | 49 | # Decode without universal-newline translation: a bare CR inside a Git line is content. |
| 50 | r.stdout = r.stdout.decode("utf-8", "replace") | 50 | r.stdout = r.stdout.decode("utf-8", stdout_errors) |
| 51 | r.stderr = r.stderr.decode("utf-8", "replace") | 51 | r.stderr = r.stderr.decode("utf-8", "replace") |
| 52 | if check and r.returncode != 0: | 52 | if check and r.returncode != 0: |
| 53 | raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}") | 53 | raise GitError(f"git {' '.join(args)}: {r.stderr.strip() or r.returncode}") |
| @@ -132,7 +132,8 @@ def duplicates(repo, main, tree, min_length, block=3): | |||
| 132 | 132 | ||
| 133 | def windows(rev, path): | 133 | def windows(rev, path): |
| 134 | # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. | 134 | # New files are already left out above (--- /dev/null), so a failed read is a real Git error, not a new file. |
| 135 | r = git(repo, "show", f"{rev}:{path}", "--") | 135 | # Keep undecodable bytes distinct while comparing lines from legacy-encoded documents. |
| 136 | r = git(repo, "show", f"{rev}:{path}", "--", stdout_errors="surrogateescape") | ||
| 136 | lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] | 137 | lines = [(number, text) for number, raw in enumerate(r.stdout.split("\n"), 1) if (text := raw.strip())] |
| 137 | content = [text for _, text in lines] | 138 | content = [text for _, text in lines] |
| 138 | return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) | 139 | return lines, Counter(tuple(content[i:i + block]) for i in range(len(content) - block + 1)) |
| @@ -153,7 +154,8 @@ def duplicates(repo, main, tree, min_length, block=3): | |||
| 153 | if before[run] and after[run] > before[run]: | 154 | if before[run] and after[run] > before[run]: |
| 154 | marked.update(number for number, _ in window) | 155 | marked.update(number for number, _ in window) |
| 155 | if marked: | 156 | if marked: |
| 156 | found[path] = [text for number, text in after_lines if number in marked] | 157 | found[path] = [text.encode("utf-8", "surrogateescape").decode("utf-8", "replace") |
| 158 | for number, text in after_lines if number in marked] | ||
| 157 | return found | 159 | return found |
| 158 | 160 | ||
| 159 | 161 | ||
diff --git a/scripts/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..2db9a7b2b --- /dev/null +++ b/scripts/play-d3d12.ps1 | |||
| @@ -0,0 +1,113 @@ | |||
| 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 | # -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 | ||
| 30 | # centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch). | ||
| 31 | # -Resolution the older path: the game renders at this height and the title's own upscaler does the rest | ||
| 32 | # -Lowest the lowest height of the title's own dynamic resolution (1080 by default on Series X): it renders | ||
| 33 | # between this and 1440 lines. Same save, RTX 4060 Ti (2026-11-29): 57.0 and 59.6 ms a frame (median, | ||
| 34 | # two series) against 66.0 and 67.9 at -Resolution 1440; the frames sat at 1080 there. | ||
| 35 | # -RayTracing the title's real ray tracing (slower; shaders build for minutes the first time) | ||
| 36 | # -Capture F9 in the game saves that frame and the pictures it drew | ||
| 37 | # -NoPrecompile start at once: by default every shader is translated and the pipelines earlier runs drew with are | ||
| 38 | # made before the title starts (minutes the first time, seconds after) | ||
| 39 | # -Log the runtime's log goes to a file under %LOCALAPPDATA%\Leonida\logs | ||
| 40 | # -DryRun prints the settings this start would run with and stops: nothing is built or started | ||
| 41 | # -PcGlyphs a folder of your own pictures for the keyboard-and-mouse button prompts instead of the built-in key | ||
| 42 | # caps (docs/prompt_glyphs.md; both prompt movies are built before the start when missing) | ||
| 43 | # | ||
| 44 | # Builds d3d12/ when it is missing (d3d12\scripts\build-nvidia.ps1: the diag profile, with DLSS when NVIDIA's files | ||
| 45 | # are there), keeps the caches and saves under -Data, and hands everything else to d3d12\scripts\play-nvidia.ps1: | ||
| 46 | # -SeriesX, -Quality, -Adapter and -More pass through. Nothing goes online. | ||
| 47 | param( | ||
| 48 | [Parameter(Mandatory = $true)][string]$Game, | ||
| 49 | [string]$Data = (Join-Path $env:LOCALAPPDATA "Leonida\d3d12"), | ||
| 50 | [switch]$SeriesX, | ||
| 51 | [switch]$SeriesS, | ||
| 52 | [switch]$Quality, | ||
| 53 | [ValidateSet('', '2160', '1440', '1080', '720', '540', '480')][string]$Resolution = '', | ||
| 54 | [ValidateSet('', '1440', '1080', '720', '540', '480')][string]$Lowest = '', | ||
| 55 | [ValidateSet('', 'quality', 'balanced', 'performance', 'ultra')][string]$Dlss = '', | ||
| 56 | [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0, | ||
| 57 | [switch]$NoFrameGen, | ||
| 58 | [switch]$MotionBlur, | ||
| 59 | [switch]$FsrFrameGen, | ||
| 60 | [string]$Aspect = '', | ||
| 61 | [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '', | ||
| 62 | [string]$Adapter = '', | ||
| 63 | [hashtable]$More = @{}, | ||
| 64 | [switch]$Rebuild, | ||
| 65 | [switch]$SmoothMotion, | ||
| 66 | [switch]$NoSmoothMotion, | ||
| 67 | [switch]$NoDlss, | ||
| 68 | [switch]$RayTracing, | ||
| 69 | [switch]$Capture, | ||
| 70 | [switch]$NoPrecompile, | ||
| 71 | [switch]$Log, | ||
| 72 | [switch]$DryRun, | ||
| 73 | [string]$PcGlyphs = '' | ||
| 74 | ) | ||
| 75 | |||
| 76 | $ErrorActionPreference = "Stop" | ||
| 77 | $repo = Split-Path -Parent $PSScriptRoot | ||
| 78 | $runtime = Join-Path $repo "d3d12" | ||
| 79 | $exe = Join-Path $runtime "target\diag\leonida.exe" | ||
| 80 | $title = Join-Path $Game "game_scarlett_master.exe" | ||
| 81 | if (-not (Test-Path $title)) { throw "missing: $title" } | ||
| 82 | if (-not $DryRun -and ($Rebuild -or -not (Test-Path $exe))) { | ||
| 83 | & (Join-Path $runtime "scripts\build-nvidia.ps1") | ||
| 84 | if ($LASTEXITCODE -ne 0) { throw "cargo build failed ($LASTEXITCODE)" } | ||
| 85 | } | ||
| 86 | # A shader cache of its own: one filled before the renderer changed (cache\) does not fit its pipelines. | ||
| 87 | New-Item -ItemType Directory -Force (Join-Path $Data "cache-2"), (Join-Path $Data "data") | Out-Null | ||
| 88 | $env:LEONIDA_GAME_DIR = (Resolve-Path $Game).Path | ||
| 89 | $env:LEONIDA_CACHE_DIR = Join-Path $Data "cache-2" | ||
| 90 | $env:LEONIDA_DATA_DIR = Join-Path $Data "data" | ||
| 91 | |||
| 92 | # Leonida: Smooth Motion only with -SmoothMotion (it was the default for one start, which the title did not | ||
| 93 | # survive; -NoSmoothMotion is kept and means the same as leaving -SmoothMotion out). | ||
| 94 | $launch = @{ Exe = $title; Build = 'diag'; NoSmoothMotion = (-not $SmoothMotion); More = $More } | ||
| 95 | # Leonida: the Series X profile is the default (the user's call: 1080p-1440p as on the bigger consoles). | ||
| 96 | if (-not $SeriesS) { | ||
| 97 | $launch.SeriesX = $true | ||
| 98 | # 1080 to 1440 lines by the title's own dynamic resolution and its own upscaler, unless a height is held | ||
| 99 | # (-Resolution) or DLSS (which -FrameGen brings with it) makes the output. | ||
| 100 | if (-not $Resolution -and -not $Lowest -and -not $Dlss -and -not $FrameGen) { $Lowest = '1080' } | ||
| 101 | } | ||
| 102 | if ($Dlss) { $launch.Dlss = $Dlss } | ||
| 103 | if ($FrameGen) { $launch.FrameGen = $FrameGen } | ||
| 104 | if ($Aspect) { $launch.Aspect = $Aspect } | ||
| 105 | if ($PresentScale) { $launch.PresentScale = $PresentScale } | ||
| 106 | foreach ($switch in 'Quality', 'NoDlss', 'NoFrameGen', 'MotionBlur', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun', 'FsrFrameGen') { | ||
| 107 | if ($PSBoundParameters[$switch]) { $launch[$switch] = $true } | ||
| 108 | } | ||
| 109 | if ($Resolution) { $launch.Resolution = $Resolution } | ||
| 110 | if ($Lowest) { $launch.Lowest = $Lowest } | ||
| 111 | if ($Adapter) { $launch.Adapter = $Adapter } | ||
| 112 | if ($PcGlyphs) { $launch.PcGlyphs = (Resolve-Path $PcGlyphs).Path } | ||
| 113 | & (Join-Path $runtime "scripts\play-nvidia.ps1") @launch | ||
diff --git a/scripts/play-linux.sh b/scripts/play-linux.sh new file mode 100755 index 000000000..e7d48d78e --- /dev/null +++ b/scripts/play-linux.sh | |||
| @@ -0,0 +1,71 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | # Starts Leonida's D3D12 runtime (d3d12/, a Windows program) on Linux under Wine, with the VKD3D-Proton that comes in | ||
| 3 | # the package (scripts/fetch_vkd3d_proton.py puts it in vkd3d-proton/ beside this script), so nothing else needs to be | ||
| 4 | # downloaded for Direct3D 12. Wine itself and a Vulkan driver (Mesa or NVIDIA's) are the system's. | ||
| 5 | # | ||
| 6 | # ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] | ||
| 7 | # | ||
| 8 | # Leonida keeps its own Wine prefix (LEONIDA_WINEPREFIX, default ~/.local/share/leonida/prefix): the bundled | ||
| 9 | # d3d12.dll and d3d12core.dll are installed there and preferred over Wine's (WINEDLLOVERRIDES), so no other prefix | ||
| 10 | # is changed. LEONIDA_* variables already set win over the defaults below. | ||
| 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 | |||
| 70 | echo "Leonida: $console under Wine with the bundled VKD3D-Proton ($(head -n 1 "$vkd3d/SOURCE.txt" 2>/dev/null || echo bundled))" | ||
| 71 | 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/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 8ba62104d..92d0e61b5 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,7 +51,7 @@ 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 |
| @@ -102,7 +103,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" | 103 | TEXT_ONLY_MARK = "; run_gpu_tests: text only, llvm-mc has no gfx1013 encoding for an instruction here" |
| 103 | 104 | ||
| 104 | 105 | ||
| 105 | def assemble_to_s(llvm_mc: str, asm_path: str, s_path: str, name: str) -> None: | 106 | 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.""" | 107 | """Assemble raw RDNA2 .asm with llvm-mc -show-encoding into .s format for rdna2spirv.py.""" |
| 107 | with open(asm_path, encoding="utf-8") as source: | 108 | with open(asm_path, encoding="utf-8") as source: |
| 108 | raw = source.read() | 109 | raw = source.read() |
| @@ -169,7 +170,7 @@ def spirv_as(asm_text: str, out_spv: str, assembler: str = "spirv-as") -> None: | |||
| 169 | return | 170 | return |
| 170 | try: | 171 | try: |
| 171 | p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], | 172 | p = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", out_spv, "-"], |
| 172 | input=asm_text, capture_output=True, text=True) | 173 | input=asm_text, capture_output=True, encoding="utf-8", errors="backslashreplace") |
| 173 | except FileNotFoundError: | 174 | except FileNotFoundError: |
| 174 | raise RuntimeError("spirv-as not found on PATH (use --assembler python to assemble with tools/spirv_asm.py)") from None | 175 | 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: | 176 | except OSError as exc: |
| @@ -316,13 +317,27 @@ def compute_result(rc: int, msg: str, ok: bool, detail: str) -> tuple[bool | Non | |||
| 316 | return (None, skip) if skip else (ok, detail) | 317 | return (None, skip) if skip else (ok, detail) |
| 317 | 318 | ||
| 318 | 319 | ||
| 320 | def dump_result(rc: int, msg: str, want: list[int]) -> tuple[bool | None, str]: | ||
| 321 | """(ok, detail) for a vk_compute_test "dump" run whose first len(want) words must be exact. A non-zero exit fails | ||
| 322 | with the program's output even when it printed the words: validation errors come with the right words.""" | ||
| 323 | words = dump_words(msg) | ||
| 324 | vals = words[:len(want)] if words else [] | ||
| 325 | if rc != 0: | ||
| 326 | detail = f"exit {rc}: {msg or 'no test output'}" | ||
| 327 | else: | ||
| 328 | detail = " ".join(hex(x) for x in vals) if vals else msg | ||
| 329 | return compute_result(rc, msg, rc == 0 and vals == want, detail) | ||
| 330 | |||
| 331 | |||
| 319 | def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *, | 332 | def run_cmd(cmd: list[str], env: dict | None = None, gpu: bool = True, *, |
| 320 | cwd: str | None = None) -> tuple[int, str]: | 333 | cwd: str | None = None) -> tuple[int, str]: |
| 321 | # A hung GPU test program fails its test instead of stalling the suite (check.py, LEONIDA_GPU_TEST_TIMEOUT). | 334 | # A hung GPU test program fails its test instead of stalling the suite (check.py, LEONIDA_GPU_TEST_TIMEOUT). |
| 322 | # gpu=False (the translator over the whole suite) runs without a limit. | 335 | # gpu=False (the translator over the whole suite) runs without a limit. |
| 323 | limit = gpu_test_timeout() if gpu else None | 336 | limit = gpu_test_timeout() if gpu else None |
| 324 | try: | 337 | try: |
| 325 | p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=limit, cwd=cwd) | 338 | # Keep the exit status and the rest of the log if a tool emits bytes outside the host encoding. |
| 339 | p = subprocess.run(cmd, capture_output=True, text=True, errors="backslashreplace", | ||
| 340 | env=env, timeout=limit, cwd=cwd) | ||
| 326 | except subprocess.TimeoutExpired: | 341 | except subprocess.TimeoutExpired: |
| 327 | return 1, timed_out(cmd[0], limit) | 342 | return 1, timed_out(cmd[0], limit) |
| 328 | except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others | 343 | except OSError as e: # e.g. Smart App Control blocked a fresh build: fail this test, keep running the others |
| @@ -354,8 +369,15 @@ def f16_interp_fallback() -> bool: | |||
| 354 | return _device_per_vertex() is False | 369 | return _device_per_vertex() is False |
| 355 | 370 | ||
| 356 | 371 | ||
| 372 | def no_ftz32() -> bool: | ||
| 373 | """Translate with --no-ftz32 when tools/vk_subgroup_info.py reports denorm_flush_to_zero_f32: false | ||
| 374 | (drivers such as NVIDIA Vulkan that do not advertise DenormFlushToZero 32).""" | ||
| 375 | return _device_denorm_ftz_f32() is False | ||
| 376 | |||
| 377 | |||
| 357 | _PER_VERTEX = [] | 378 | _PER_VERTEX = [] |
| 358 | _BARYCENTRIC_FALLBACK = [] | 379 | _BARYCENTRIC_FALLBACK = [] |
| 380 | _DENORM_FTZ_F32 = [] | ||
| 359 | 381 | ||
| 360 | 382 | ||
| 361 | def _device_per_vertex(): | 383 | def _device_per_vertex(): |
| @@ -365,7 +387,9 @@ def _device_per_vertex(): | |||
| 365 | try: | 387 | try: |
| 366 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | 388 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], |
| 367 | capture_output=True, text=True, timeout=60) | 389 | capture_output=True, text=True, timeout=60) |
| 368 | answer = json.loads(r.stdout.strip().splitlines()[-1]).get("per_vertex_inputs") | 390 | report = json.loads(r.stdout.strip().splitlines()[-1]) |
| 391 | if isinstance(report, dict): | ||
| 392 | answer = report.get("per_vertex_inputs") | ||
| 369 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | 393 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): |
| 370 | pass | 394 | pass |
| 371 | _PER_VERTEX.append(answer) | 395 | _PER_VERTEX.append(answer) |
| @@ -380,13 +404,31 @@ def _device_barycentric_fallback(): | |||
| 380 | try: | 404 | try: |
| 381 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | 405 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], |
| 382 | capture_output=True, text=True, timeout=60) | 406 | capture_output=True, text=True, timeout=60) |
| 383 | answer = json.loads(r.stdout.strip().splitlines()[-1]).get("barycentric_fallback") | 407 | report = json.loads(r.stdout.strip().splitlines()[-1]) |
| 408 | if isinstance(report, dict): | ||
| 409 | answer = report.get("barycentric_fallback") | ||
| 384 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | 410 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): |
| 385 | pass | 411 | pass |
| 386 | _BARYCENTRIC_FALLBACK.append(answer) | 412 | _BARYCENTRIC_FALLBACK.append(answer) |
| 387 | return _BARYCENTRIC_FALLBACK[0] | 413 | return _BARYCENTRIC_FALLBACK[0] |
| 388 | 414 | ||
| 389 | 415 | ||
| 416 | def _device_denorm_ftz_f32(): | ||
| 417 | """denorm_flush_to_zero_f32 from tools/vk_subgroup_info.py for the device the tests run on (cached), or None.""" | ||
| 418 | if not _DENORM_FTZ_F32: | ||
| 419 | answer = None | ||
| 420 | try: | ||
| 421 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | ||
| 422 | capture_output=True, text=True, timeout=60) | ||
| 423 | report = json.loads(r.stdout.strip().splitlines()[-1]) | ||
| 424 | if isinstance(report, dict) and isinstance(report.get("denorm_flush_to_zero_f32"), bool): | ||
| 425 | answer = report["denorm_flush_to_zero_f32"] | ||
| 426 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | ||
| 427 | pass | ||
| 428 | _DENORM_FTZ_F32.append(answer) | ||
| 429 | return _DENORM_FTZ_F32[0] | ||
| 430 | |||
| 431 | |||
| 390 | def w64_emulated() -> bool: | 432 | def w64_emulated() -> bool: |
| 391 | # Wave64 emulation on: the suite runs every wave64 check without asking for a 64-wide | 433 | # 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 | 434 | # subgroup, matching check.py (W64_EMULATED). Accepts "1"/"true"/"yes"/"on" and tolerates |
| @@ -678,7 +720,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, | |||
| 678 | # Fixtures run by another harness, which needs what these tools do not have (a D3D12 device, the layer's root | 720 | # Fixtures run by another harness, which needs what these tools do not have (a D3D12 device, the layer's root |
| 679 | # arguments and code base). They are still assembled and translated here, so a translator regression shows, but no | 721 | # arguments and code base). They are still assembled and translated here, so a translator regression shows, but no |
| 680 | # checker runs them: the test program that owns them judges them. | 722 | # checker runs them: the test program that owns them judges them. |
| 681 | OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", | 723 | OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "ps_m15_dual": "d3d12_translated_draw_test", |
| 724 | "vs_m15": "d3d12_translated_draw_test", | ||
| 682 | "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", | 725 | "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", |
| 683 | "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test", | 726 | "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test", |
| 684 | "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", | 727 | "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", |
| @@ -761,8 +804,11 @@ def native_folder(path: str, ansi: str = "mbcs") -> str | None: | |||
| 761 | 804 | ||
| 762 | def main() -> int: | 805 | def main() -> int: |
| 763 | ap = argparse.ArgumentParser() | 806 | ap = argparse.ArgumentParser() |
| 764 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), | 807 | # No literal default: unset, mc_command() reads LLVM_MC and then finds llvm-mc on PATH or a versioned |
| 765 | help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") | 808 | # Debian/Ubuntu install (llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc), as the not-found message promises. |
| 809 | ap.add_argument("--llvm-mc", default=None, | ||
| 810 | help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' " | ||
| 811 | "(default: LLVM_MC, then llvm-mc on PATH, then the newest llvm-mc-<N>)") | ||
| 766 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), | 812 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), |
| 767 | help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " | 813 | help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " |
| 768 | "subfolder that has the test programs is found by itself") | 814 | "subfolder that has the test programs is found by itself") |
| @@ -775,6 +821,9 @@ def main() -> int: | |||
| 775 | ap.add_argument("--no-validate", action="store_true", | 821 | ap.add_argument("--no-validate", action="store_true", |
| 776 | help="skip spirv-val during translation (automatic when --assembler resolves to python " | 822 | help="skip spirv-val during translation (automatic when --assembler resolves to python " |
| 777 | "and spirv-val is not on PATH)") | 823 | "and spirv-val is not on PATH)") |
| 824 | ap.add_argument("--no-ftz32", action="store_true", | ||
| 825 | help="translate shaders with --no-ftz32 (automatic when tools/vk_subgroup_info.py reports " | ||
| 826 | "denorm_flush_to_zero_f32: false)") | ||
| 778 | ap.add_argument("--disasm-dir", default=None, | 827 | ap.add_argument("--disasm-dir", default=None, |
| 779 | help="folder of pre-disassembled <name>.s listings (e.g. tests/semantic/fixtures/disasm); " | 828 | help="folder of pre-disassembled <name>.s listings (e.g. tests/semantic/fixtures/disasm); " |
| 780 | "skips llvm-mc and runs only fixtures present there") | 829 | "skips llvm-mc and runs only fixtures present there") |
| @@ -894,6 +943,8 @@ def run_suite(a, work: str) -> int: | |||
| 894 | ]) | 943 | ]) |
| 895 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): | 944 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): |
| 896 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) | 945 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) |
| 946 | elif name in ("ms_w64x_wave_votes", "ms_w64x_wave_loops"): # vertex 64 comes from the second wave: 128 output vertices | ||
| 947 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 128, 64, 2))]) | ||
| 897 | elif name == "ms_v5_workgroup": | 948 | elif name == "ms_v5_workgroup": |
| 898 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) | 949 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) |
| 899 | elif name == "ms_clip": | 950 | elif name == "ms_clip": |
| @@ -924,9 +975,18 @@ def run_suite(a, work: str) -> int: | |||
| 924 | Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) | 975 | Path(spirv_dir, f"{name}.spv").unlink(missing_ok=True) |
| 925 | 976 | ||
| 926 | # 2. Translate this run's inputs only. The translator looks for metadata one level above the input directory. | 977 | # 2. Translate this run's inputs only. The translator looks for metadata one level above the input directory. |
| 927 | with tempfile.TemporaryDirectory(prefix="disasm-", dir=work) as selected_disasm: | 978 | try: |
| 928 | for path in disasm_files: | 979 | staging = tempfile.TemporaryDirectory(prefix="disasm-", dir=work) |
| 929 | shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path))) | 980 | except OSError as exc: |
| 981 | print(f"error: cannot create a disassembly staging directory in {work}: {exc}", file=sys.stderr) | ||
| 982 | return 2 | ||
| 983 | with staging as selected_disasm: | ||
| 984 | try: | ||
| 985 | for path in disasm_files: | ||
| 986 | shutil.copyfile(path, os.path.join(selected_disasm, os.path.basename(path))) | ||
| 987 | except OSError as exc: | ||
| 988 | print(f"error: cannot stage disassembly for translation: {exc}", file=sys.stderr) | ||
| 989 | return 2 | ||
| 930 | cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir] | 990 | cmd = [sys.executable, "-I", TRANSLATOR, selected_disasm, "--out", spirv_dir] |
| 931 | if assembler == "python": | 991 | if assembler == "python": |
| 932 | cmd += ["--assembler", "python"] | 992 | cmd += ["--assembler", "python"] |
| @@ -940,10 +1000,14 @@ def run_suite(a, work: str) -> int: | |||
| 940 | cmd.append("--bary-fallback") | 1000 | cmd.append("--bary-fallback") |
| 941 | if f16_interp_fallback(): # *_f16 interps from decoded-half inputs, no PerVertexKHR (MoltenVK) | 1001 | if f16_interp_fallback(): # *_f16 interps from decoded-half inputs, no PerVertexKHR (MoltenVK) |
| 942 | cmd.append("--f16-interp-fallback") | 1002 | cmd.append("--f16-interp-fallback") |
| 1003 | if getattr(a, "no_ftz32", False) or no_ftz32(): # no DenormFlushToZero 32 (e.g. NVIDIA Vulkan) | ||
| 1004 | cmd.append("--no-ftz32") | ||
| 943 | if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 | 1005 | if TEXOFF_FALLBACK: # image_sample*_o: offset folded into the coordinate, no VK_KHR_maintenance8 |
| 944 | cmd.append("--texel-offset-fallback") | 1006 | cmd.append("--texel-offset-fallback") |
| 945 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py | 1007 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py |
| 946 | cmd.append("--mesh-compute") | 1008 | cmd.append("--mesh-compute") |
| 1009 | if os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1": # with --wave64-emulate: one pass per wave | ||
| 1010 | cmd.append("--mesh-serial-waves") | ||
| 947 | if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 | 1011 | if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 |
| 948 | cmd.append("--pc-tail-ubo") | 1012 | cmd.append("--pc-tail-ubo") |
| 949 | if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) | 1013 | if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) |
| @@ -987,11 +1051,11 @@ def run_suite(a, work: str) -> int: | |||
| 987 | for fname in asm_files: | 1051 | for fname in asm_files: |
| 988 | name = os.path.splitext(fname)[0] | 1052 | name = os.path.splitext(fname)[0] |
| 989 | spv = os.path.join(spirv_dir, f"{name}.spv") | 1053 | spv = os.path.join(spirv_dir, f"{name}.spv") |
| 990 | if name == "ps_ij_computed" and (bary_fallback() or f16_interp_fallback()): | 1054 | if name == "ps_ij_computed" and bary_fallback(): |
| 991 | # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair, so there | 1055 | # Before the .spv check: under --bary-fallback the translator refuses a computed I/J pair, so there |
| 992 | # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). | 1056 | # is no .spv (--f16-interp-fallback alone lowers it via DerivativeControl + BaryCoordKHR). |
| 993 | results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs: " | 1057 | results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; " |
| 994 | "no --bary-fallback / --f16-interp-fallback)")) | 1058 | "unsupported under --bary-fallback)")) |
| 995 | continue | 1059 | continue |
| 996 | if not os.path.isfile(spv): | 1060 | if not os.path.isfile(spv): |
| 997 | results.append((name, False, "missing .spv (translation failed)")) | 1061 | results.append((name, False, "missing .spv (translation failed)")) |
| @@ -1056,7 +1120,8 @@ def run_suite(a, work: str) -> int: | |||
| 1056 | # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. | 1120 | # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. |
| 1057 | # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either. | 1121 | # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either. |
| 1058 | # The other four pin the SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm). | 1122 | # The other four pin the SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm). |
| 1059 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) | 1123 | env = dict(cs_env or os.environ, **PK_MUL_LO_ENV) if name == "cs_pk_mul_lo_const" else cs_env |
| 1124 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env) | ||
| 1060 | want = { | 1125 | want = { |
| 1061 | "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], | 1126 | "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], |
| 1062 | "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], | 1127 | "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], |
| @@ -1080,10 +1145,25 @@ def run_suite(a, work: str) -> int: | |||
| 1080 | "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], | 1145 | "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], |
| 1081 | "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], | 1146 | "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], |
| 1082 | }[name] | 1147 | }[name] |
| 1083 | words = dump_words(msg) | 1148 | results.append((name,) + dump_result(rc, msg, want)) |
| 1084 | vals = words[:len(want)] if words else [] | 1149 | elif name == "cs_w64x_dynamic_r32_uint": |
| 1085 | results.append((name,) + compute_result(rc, msg, rc == 0 and vals == want, | 1150 | word = 0x8A600250 |
| 1086 | " ".join(hex(x) for x in vals) if vals else msg)) | 1151 | descriptor_at, value_at = 0x100, 0x180 |
| 1152 | with tempfile.TemporaryDirectory(prefix="dynamic-r32-", dir=work) as scratch: | ||
| 1153 | heap = os.path.join(scratch, "heap.bin") | ||
| 1154 | with open(heap, "wb") as stream: | ||
| 1155 | descriptor = struct.pack("<4I", value_at, 4 << 16, 1, (2 << 28) | (20 << 12) | 4) | ||
| 1156 | stream.write(descriptor) | ||
| 1157 | stream.write(bytes(value_at - descriptor_at - len(descriptor))) | ||
| 1158 | stream.write(struct.pack("<I", word)) | ||
| 1159 | env = dict(cs_env or os.environ, VKC_SGPRS=f"0,{descriptor_at}", | ||
| 1160 | VKC_HEAP_FILE=f"{heap}@{descriptor_at}") | ||
| 1161 | command = [vk_compute, spv, "1", "dump"] | ||
| 1162 | if not w64_emulated(): | ||
| 1163 | command.append("--require-wave64") | ||
| 1164 | rc, msg = run_cmd(command, env=env) | ||
| 1165 | results.append((name,) + judge_cs_dump(rc, msg, [word] * 8, wave64=not w64_emulated(), | ||
| 1166 | partial=False, emulated=w64_emulated())) | ||
| 1087 | elif name == "cs_fmt_1010102": | 1167 | elif name == "cs_fmt_1010102": |
| 1088 | problem = fmt_1010102_test(a.build, spirv_dir, cs_env) | 1168 | problem = fmt_1010102_test(a.build, spirv_dir, cs_env) |
| 1089 | results.append((name, not problem, problem or "64/64 dumped words exact")) | 1169 | results.append((name, not problem, problem or "64/64 dumped words exact")) |
| @@ -1100,6 +1180,7 @@ def run_suite(a, work: str) -> int: | |||
| 1100 | elif name == "cs_tbuffer_store": | 1180 | elif name == "cs_tbuffer_store": |
| 1101 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) | 1181 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) |
| 1102 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) | 1182 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) |
| 1183 | results.append((name, not problem, problem or "128/128 dumped words exact")) | ||
| 1103 | elif name == "cs_fmt_d16_xyz": | 1184 | elif name == "cs_fmt_d16_xyz": |
| 1104 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) | 1185 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) |
| 1105 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) | 1186 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) |
| @@ -1117,17 +1198,11 @@ def run_suite(a, work: str) -> int: | |||
| 1117 | elif name == "cs_heap_init": | 1198 | elif name == "cs_heap_init": |
| 1118 | # vk_compute_test copies VKC_HEAP_INIT's file into the heap; the shader copies its words at 0x100 to 0. | 1199 | # vk_compute_test copies VKC_HEAP_INIT's file into the heap; the shader copies its words at 0x100 to 0. |
| 1119 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env())) | 1200 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env())) |
| 1120 | words = dump_words(msg) | 1201 | results.append((name,) + dump_result(rc, msg, HEAP_INIT_EXPECTED)) |
| 1121 | vals = words[:len(HEAP_INIT_EXPECTED)] if words else [] | ||
| 1122 | results.append((name,) + compute_result(rc, msg, rc == 0 and vals == HEAP_INIT_EXPECTED, | ||
| 1123 | " ".join(hex(x) for x in vals) if vals else msg)) | ||
| 1124 | elif name == "cs_user_sgprs": | 1202 | elif name == "cs_user_sgprs": |
| 1125 | # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. | 1203 | # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. |
| 1126 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) | 1204 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) |
| 1127 | words = dump_words(msg) | 1205 | results.append((name,) + dump_result(rc, msg, USER_SGPRS_WORDS)) |
| 1128 | vals = words[:len(USER_SGPRS_WORDS)] if words else [] | ||
| 1129 | results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS, | ||
| 1130 | " ".join(hex(x) for x in vals) if vals else msg)) | ||
| 1131 | elif name == "cs_w32_salu_ext": | 1206 | elif name == "cs_w32_salu_ext": |
| 1132 | detail = salu_ext_test(a.build, spirv_dir, cs_env) | 1207 | detail = salu_ext_test(a.build, spirv_dir, cs_env) |
| 1133 | results.append((name, None if isinstance(detail, Skip) else not detail, | 1208 | results.append((name, None if isinstance(detail, Skip) else not detail, |
| @@ -1137,7 +1212,7 @@ def run_suite(a, work: str) -> int: | |||
| 1137 | if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names | 1212 | if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names |
| 1138 | results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) | 1213 | results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) |
| 1139 | else: | 1214 | else: |
| 1140 | ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, | 1215 | ok, detail = judge_cs_dump(rc, msg, [0, 0x3FF40000], wave64=False, partial=False, emulated=False, |
| 1141 | hexwords=True) | 1216 | hexwords=True) |
| 1142 | results.append((name, ok, detail)) | 1217 | results.append((name, ok, detail)) |
| 1143 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): | 1218 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): |
| @@ -1202,15 +1277,15 @@ def run_suite(a, work: str) -> int: | |||
| 1202 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. | 1277 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. |
| 1203 | results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) | 1278 | results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) |
| 1204 | elif name in ("cs_smem_vcc_base", "cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", | 1279 | 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", |
| 1205 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", | 1280 | "cs_w32_cvt_f16_mods", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", |
| 1206 | "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64", | 1281 | "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_dpp_w64", |
| 1207 | "cs_w64_mask_detect", | 1282 | "cs_w64_mask_detect", |
| 1208 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", | 1283 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", |
| 1209 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", | 1284 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", |
| 1210 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", | 1285 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", |
| 1211 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", | 1286 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", |
| 1212 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", | 1287 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", |
| 1213 | "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", | 1288 | "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", |
| 1214 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): | 1289 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): |
| 1215 | cs_dump_wants = { | 1290 | cs_dump_wants = { |
| 1216 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], | 1291 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], |
| @@ -1236,6 +1311,7 @@ def run_suite(a, work: str) -> int: | |||
| 1236 | # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) | 1311 | # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) |
| 1237 | "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], | 1312 | "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], |
| 1238 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], | 1313 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], |
| 1314 | "cs_w32_cvt_f16_mods": CVT_F16_MODS_WORDS, | ||
| 1239 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], | 1315 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], |
| 1240 | "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], | 1316 | "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], |
| 1241 | # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) | 1317 | # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) |
| @@ -1249,6 +1325,12 @@ def run_suite(a, work: str) -> int: | |||
| 1249 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) | 1325 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) |
| 1250 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, | 1326 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, |
| 1251 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], | 1327 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], |
| 1328 | # ds_wrxchg2_rtn_b32's pair cases and ds_wrxchg2st64_rtn_b32 | ||
| 1329 | # (cs_w32_wrxchg2_ext.asm / cs_w32_wrxchg2st64.asm headers) | ||
| 1330 | "cs_w32_wrxchg2_ext": [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF, | ||
| 1331 | 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678], | ||
| 1332 | "cs_w32_wrxchg2st64": [0x33333333, 0x44444444, 0x55550005, 0x66660006, | ||
| 1333 | 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0], | ||
| 1252 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) | 1334 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) |
| 1253 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, | 1335 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, |
| 1254 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], | 1336 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], |
| @@ -1266,6 +1348,7 @@ def run_suite(a, work: str) -> int: | |||
| 1266 | "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], | 1348 | "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], |
| 1267 | "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], | 1349 | "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], |
| 1268 | "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0], | 1350 | "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0], |
| 1351 | "cs_dpp_cmpx": [1, 1, 0, 0, 3, 3, 2, 2], | ||
| 1269 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], | 1352 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], |
| 1270 | # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] | 1353 | # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] |
| 1271 | # without it | 1354 | # without it |
| @@ -1295,6 +1378,7 @@ def run_suite(a, work: str) -> int: | |||
| 1295 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], | 1378 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], |
| 1296 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], | 1379 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], |
| 1297 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave | 1380 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave |
| 1381 | "cs_w64x_partial_swizzle": [508, 523, 0, 0, 528, 0, 531, 0], # swizzle from a missing lane: 0 | ||
| 1298 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 | 1382 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 |
| 1299 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) | 1383 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) |
| 1300 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], | 1384 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], |
| @@ -1326,25 +1410,28 @@ def run_suite(a, work: str) -> int: | |||
| 1326 | want = cs_dump_wants[name] | 1410 | want = cs_dump_wants[name] |
| 1327 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / | 1411 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / |
| 1328 | # 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 | 1412 | # 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 |
| 1329 | # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, | 1413 | # cs_w32_cvt_f16_mods / cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: |
| 1414 | # ask for a 64-wide subgroup and skip, | ||
| 1330 | # as check.py does, where the device has none | 1415 | # as check.py does, where the device has none |
| 1331 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were | 1416 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were |
| 1332 | # translated with --wave64-emulate and run on any subgroup size. | 1417 | # translated with --wave64-emulate and run on any subgroup size. |
| 1333 | # cs_w64x_partial and cs_w64x_partial_scmp (40-thread groups) can't have full subgroups: they ask for | 1418 | # cs_w64x_partial, cs_w64x_partial_scmp and cs_w64x_partial_swizzle (40-thread groups) can't have full |
| 1334 | # size 64 without them. | 1419 | # subgroups: they ask for size 64 without them. With LEONIDA_W64_EMULATE=1 they ask for 32, the width the |
| 1420 | # emulation is for, as check.py's partial_wave_test does. RADV defaults compute to 64, and there | ||
| 1421 | # cs_w64x_partial_swizzle came out right even before its missing-lane reads were fixed; at 32 it did not. | ||
| 1335 | emulated = w64_emulated() | 1422 | emulated = w64_emulated() |
| 1336 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp") | 1423 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") |
| 1337 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", | 1424 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", |
| 1338 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", | 1425 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", |
| 1339 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", | 1426 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_cvt_f16_mods", |
| 1340 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1427 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1341 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", | 1428 | "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", |
| 1342 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", | 1429 | "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", |
| 1343 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", | 1430 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", |
| 1344 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", | 1431 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_w32_andn2_exec", |
| 1345 | "cs_w32_exec_computed") and not emulated and not partial | 1432 | "cs_w32_exec_computed") and not emulated and not partial |
| 1346 | if partial and not emulated: | 1433 | if partial: |
| 1347 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") | 1434 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") |
| 1348 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) | 1435 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) |
| 1349 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) | 1436 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) |
| 1350 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) | 1437 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) |
| @@ -1366,7 +1453,7 @@ def run_suite(a, work: str) -> int: | |||
| 1366 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, | 1453 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, |
| 1367 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", | 1454 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", |
| 1368 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1455 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1369 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_signed_zero_nan")) | 1456 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_signed_zero_nan")) |
| 1370 | if ok and None in want: | 1457 | if ok and None in want: |
| 1371 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) | 1458 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) |
| 1372 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" | 1459 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" |
| @@ -1503,6 +1590,7 @@ def run_suite(a, work: str) -> int: | |||
| 1503 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), | 1590 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), |
| 1504 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), | 1591 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), |
| 1505 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), | 1592 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), |
| 1593 | "ps_exp_f32_denorm": (0x01000000, 0x00800000, 0x00000000, 0x00000000), | ||
| 1506 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), | 1594 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), |
| 1507 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) | 1595 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) |
| 1508 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) | 1596 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) |
| @@ -1511,7 +1599,7 @@ def run_suite(a, work: str) -> int: | |||
| 1511 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), | 1599 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), |
| 1512 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), | 1600 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), |
| 1513 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), | 1601 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), |
| 1514 | "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 | 1602 | "ps_f64_mods": (0x3FF40000, 0x3FF00000, 0x3FF00000, 0x3FD00000), # needs shaderFloat64 |
| 1515 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 | 1603 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 |
| 1516 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), | 1604 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), |
| 1517 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) | 1605 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) |
| @@ -1594,6 +1682,9 @@ def run_suite(a, work: str) -> int: | |||
| 1594 | elif name == "ps_ij_computed": | 1682 | elif name == "ps_ij_computed": |
| 1595 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | 1683 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) |
| 1596 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" | 1684 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" |
| 1685 | elif name == "ps_exp_f32_denorm_rt": | ||
| 1686 | problem = exp_f32_denorm_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | ||
| 1687 | ok, detail = not problem, problem or "4096 pixels exact across 64 runtime-dependent inputs" | ||
| 1597 | elif name == "ps_mandelbrot": | 1688 | elif name == "ps_mandelbrot": |
| 1598 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] | 1689 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] |
| 1599 | problem = frame_problem(px) or mandelbrot_problem(px) | 1690 | problem = frame_problem(px) or mandelbrot_problem(px) |
| @@ -1620,13 +1711,13 @@ def run_suite(a, work: str) -> int: | |||
| 1620 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") | 1711 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") |
| 1621 | results.append((name, None if isinstance(problem, Skip) else not problem, | 1712 | results.append((name, None if isinstance(problem, Skip) else not problem, |
| 1622 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) | 1713 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) |
| 1623 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): | 1714 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_w64x_wave_votes", "ms_w64x_wave_loops"): |
| 1624 | raw = os.path.join(raw_dir, f"{name}.raw") | 1715 | raw = os.path.join(raw_dir, f"{name}.raw") |
| 1625 | env = mesh_env(spirv_dir, name, gfx_env) | 1716 | env = mesh_env(spirv_dir, name, gfx_env) |
| 1626 | rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) | 1717 | rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) |
| 1627 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as | 1718 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as |
| 1628 | # the wave64 compute dumps are. | 1719 | # the wave64 compute dumps are. |
| 1629 | no64 = (name == "ms_w64x_ballot" and not w64_emulated() and | 1720 | no64 = (name in ("ms_w64x_ballot", "ms_w64x_wave_votes", "ms_w64x_wave_loops") and not w64_emulated() and |
| 1630 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) | 1721 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) |
| 1631 | if rc == UNSUPPORTED: | 1722 | if rc == UNSUPPORTED: |
| 1632 | results.append((name, None, unsupported_skip(msg))) | 1723 | results.append((name, None, unsupported_skip(msg))) |
| @@ -1678,14 +1769,15 @@ def run_suite(a, work: str) -> int: | |||
| 1678 | ok, detail = check_flat(raw) | 1769 | ok, detail = check_flat(raw) |
| 1679 | results.append((name, ok, detail)) | 1770 | results.append((name, ok, detail)) |
| 1680 | 1771 | ||
| 1681 | if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed" | 1772 | if (a.filter or disasm_src is not None) and not results: |
| 1682 | names = [os.path.splitext(f)[0] for f in asm_files] | 1773 | names = [os.path.splitext(f)[0] for f in asm_files] |
| 1683 | partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) | 1774 | partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) |
| 1684 | shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") | 1775 | shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") |
| 1685 | role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" | 1776 | role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" |
| 1686 | hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" | 1777 | hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" |
| 1687 | if all(n.startswith("cs_bench_") for n in names) else "") | 1778 | if all(n.startswith("cs_bench_") for n in names) else "") |
| 1688 | print(f"error: --filter {a.filter!r} selected {shown} but no runnable GPU test cases ({role}){hint}", | 1779 | selected_by = f"--filter {a.filter!r}" if a.filter else f"--disasm-dir {disasm_src!r}" |
| 1780 | print(f"error: {selected_by} selected {shown} but no runnable GPU test cases ({role}){hint}", | ||
| 1689 | file=sys.stderr) | 1781 | file=sys.stderr) |
| 1690 | return 2 | 1782 | return 2 |
| 1691 | 1783 | ||
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 03e0ddab4..f41602ef4 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py | |||
| @@ -15,10 +15,13 @@ error in serial and parallel runs. | |||
| 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. |
| 16 | 16 | ||
| 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, | 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 | or on a single core, it runs that discover command itself. Prints the output of every failing file and one summary | 18 | 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. | 19 | exit code (a POSIX signal by name, a known Windows NTSTATUS with its meaning, e.g. 0xC0000005 access violation, |
| 20 | since a file that crashes prints nothing), and one summary line, and exits 1 if a file fails, none is found, or no | ||
| 21 | test ran. Standard library only. | ||
| 20 | 22 | ||
| 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. | 23 | The test count and verdict come from unittest's result, not from printed summaries. A child exiting with status 0 |
| 24 | without a completed result, or after unittest reported failure, fails the run. | ||
| 22 | 25 | ||
| 23 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with | 26 | `--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with |
| 24 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. | 27 | `-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits. |
| @@ -33,13 +36,62 @@ import locale | |||
| 33 | import math | 36 | import math |
| 34 | import os | 37 | import os |
| 35 | import re | 38 | import re |
| 39 | import signal | ||
| 36 | import subprocess | 40 | import subprocess |
| 37 | import sys | 41 | import sys |
| 38 | import tempfile | 42 | import tempfile |
| 43 | import threading | ||
| 39 | import time | 44 | import time |
| 40 | 45 | ||
| 41 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 | 46 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 |
| 42 | 47 | ||
| 48 | # The child processes running right now: on SIGINT / Ctrl+C, the main thread terminates them so no orphans linger. | ||
| 49 | _active_processes = set() | ||
| 50 | _processes_lock = threading.Lock() | ||
| 51 | |||
| 52 | |||
| 53 | def _register_process(proc): | ||
| 54 | with _processes_lock: | ||
| 55 | _active_processes.add(proc) | ||
| 56 | |||
| 57 | |||
| 58 | def _unregister_process(proc): | ||
| 59 | with _processes_lock: | ||
| 60 | _active_processes.discard(proc) | ||
| 61 | |||
| 62 | |||
| 63 | def _kill_process_tree(proc): | ||
| 64 | if proc is None: | ||
| 65 | return | ||
| 66 | if os.name == "nt" and proc.poll() is None: | ||
| 67 | try: | ||
| 68 | subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], | ||
| 69 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | ||
| 70 | except OSError: | ||
| 71 | pass | ||
| 72 | try: | ||
| 73 | proc.kill() | ||
| 74 | except OSError: | ||
| 75 | pass | ||
| 76 | |||
| 77 | |||
| 78 | def _terminate_active_processes(): | ||
| 79 | with _processes_lock: | ||
| 80 | procs = list(_active_processes) | ||
| 81 | if os.name != "nt": | ||
| 82 | for p in procs: | ||
| 83 | try: | ||
| 84 | p.terminate() | ||
| 85 | except OSError: | ||
| 86 | pass | ||
| 87 | # On Windows taskkill /T needs the root process alive to find its descendants. | ||
| 88 | for p in procs: | ||
| 89 | _kill_process_tree(p) | ||
| 90 | try: | ||
| 91 | p.wait(timeout=0.2) | ||
| 92 | except (subprocess.TimeoutExpired, OSError): | ||
| 93 | pass | ||
| 94 | |||
| 43 | # The child runs the module through unittest's own program and writes the result to a file, so the count of tests | 95 | # The child runs the module through unittest's own program and writes the result to a file, so the count of tests |
| 44 | # comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1 | 96 | # comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1 |
| 45 | # when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so | 97 | # when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so |
| @@ -48,13 +100,44 @@ CHILD_PROGRAM = ( | |||
| 48 | "import json, os, sys, unittest\n" | 100 | "import json, os, sys, unittest\n" |
| 49 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" | 101 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" |
| 50 | "result = program.result\n" | 102 | "result = program.result\n" |
| 51 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" | 103 | "code = 1 if not result.wasSuccessful() else 5 if not result.testsRun and not result.skipped else 0\n" |
| 52 | " json.dump({'testsRun': result.testsRun}, handle)\n" | 104 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8', newline='\\n') as handle:\n" |
| 53 | "if not result.wasSuccessful():\n" | 105 | " json.dump({'testsRun': result.testsRun, 'exitCode': code}, handle)\n" |
| 54 | " sys.exit(1)\n" | 106 | "sys.exit(code)\n") |
| 55 | "elif result.testsRun == 0 and len(result.skipped) == 0:\n" | 107 | |
| 56 | " sys.exit(5)\n" | 108 | # Windows NTSTATUS codes python.exe exits with when it crashes. A file that dies this way prints nothing, so the code |
| 57 | "sys.exit(0)\n") | 109 | # is the only clue there is (an access violation in a pure-Python test points at the machine, not at the test). |
| 110 | NTSTATUS_CRASHES = { | ||
| 111 | 0xC0000005: "access violation", | ||
| 112 | 0xC000001D: "illegal instruction", | ||
| 113 | 0xC0000017: "out of memory", | ||
| 114 | 0xC00000FD: "stack overflow", | ||
| 115 | 0xC0000374: "heap corruption", | ||
| 116 | 0xC0000409: "fail fast / stack buffer overrun", | ||
| 117 | } | ||
| 118 | # Known statuses that end a process without it crashing. | ||
| 119 | NTSTATUS_OTHER = { | ||
| 120 | 0xC000013A: "interrupted with Ctrl+C", | ||
| 121 | } | ||
| 122 | |||
| 123 | |||
| 124 | def describe_exit(code): | ||
| 125 | """A failed module's exit code in words: `exit code 1`, `killed by SIGSEGV (-11)` for a POSIX signal, or for a | ||
| 126 | known Windows NTSTATUS its hexadecimal value and meaning (3221225477 -> 0xC0000005, access violation). Only the | ||
| 127 | statuses in NTSTATUS_CRASHES are called a crash: a process can also exit with any 32-bit value on purpose, so an | ||
| 128 | unknown one is reported as just its value.""" | ||
| 129 | if code < 0: | ||
| 130 | try: | ||
| 131 | return f"killed by {signal.Signals(-code).name} ({code})" | ||
| 132 | except ValueError: | ||
| 133 | return f"killed by signal {-code} ({code})" | ||
| 134 | if code in NTSTATUS_CRASHES: | ||
| 135 | return f"exit code 0x{code:08X}, {NTSTATUS_CRASHES[code]} (the process crashed)" | ||
| 136 | if code in NTSTATUS_OTHER: | ||
| 137 | return f"exit code 0x{code:08X}, {NTSTATUS_OTHER[code]}" | ||
| 138 | if code > 0xFFFF: # an NTSTATUS-sized value reads better in hexadecimal | ||
| 139 | return f"exit code 0x{code:08X}" | ||
| 140 | return f"exit code {code}" | ||
| 58 | 141 | ||
| 59 | 142 | ||
| 60 | def module_path(directory, module): | 143 | def module_path(directory, module): |
| @@ -93,14 +176,69 @@ def positive_seconds(value): | |||
| 93 | return seconds | 176 | return seconds |
| 94 | 177 | ||
| 95 | 178 | ||
| 96 | def read_count(path): | 179 | def read_result(path, process_code): |
| 97 | """The number of tests the child ran, as unittest's own result object reported it.""" | 180 | """Return the effective exit code, completed test count, and any diagnostic.""" |
| 98 | try: | 181 | try: |
| 99 | with open(path, encoding="utf-8") as handle: | 182 | with open(path, encoding="utf-8") as handle: |
| 100 | return int(json.load(handle)["testsRun"]) | 183 | result = json.load(handle) |
| 184 | count, test_code = result["testsRun"], result["exitCode"] | ||
| 185 | if type(count) is not int or count < 0 or type(test_code) is not int or test_code not in (0, 1, 5): | ||
| 186 | raise ValueError("invalid unittest result") | ||
| 101 | except (OSError, ValueError, KeyError, TypeError): | 187 | except (OSError, ValueError, KeyError, TypeError): |
| 102 | # The child wrote no result: it did not finish, so no test is known to have run. | 188 | if process_code == 0: |
| 103 | return 0 | 189 | return 1, 0, "process exited without a unittest result" |
| 190 | return process_code, None, "" | ||
| 191 | if process_code in (0, 5) and process_code != test_code: | ||
| 192 | return 1, count, f"process exited with status {process_code} but unittest reported {test_code}" | ||
| 193 | return process_code, count, "" | ||
| 194 | |||
| 195 | |||
| 196 | def result_environment(scratch): | ||
| 197 | result_path = os.path.join(scratch, "count.json") | ||
| 198 | return result_path, dict(os.environ, LEONIDA_TEST_COUNT=result_path) | ||
| 199 | |||
| 200 | |||
| 201 | def run_discover(directory, pattern, verbose, timeout): | ||
| 202 | args = ["discover", "-s", directory, "-p", pattern, *(["-v"] if verbose else [])] | ||
| 203 | with tempfile.TemporaryDirectory() as scratch: | ||
| 204 | path, env = result_environment(scratch) | ||
| 205 | proc = subprocess.Popen([sys.executable, "-c", CHILD_PROGRAM, *args], env=env) | ||
| 206 | _register_process(proc) | ||
| 207 | try: | ||
| 208 | deadline = None if timeout is None else time.monotonic() + timeout | ||
| 209 | while True: | ||
| 210 | wait_seconds = 0.2 | ||
| 211 | if deadline is not None: | ||
| 212 | remaining = deadline - time.monotonic() | ||
| 213 | if remaining <= 0: | ||
| 214 | raise subprocess.TimeoutExpired(proc.args, timeout) | ||
| 215 | wait_seconds = min(wait_seconds, remaining) | ||
| 216 | try: | ||
| 217 | code = proc.wait(timeout=wait_seconds) | ||
| 218 | break | ||
| 219 | except subprocess.TimeoutExpired: | ||
| 220 | continue | ||
| 221 | except subprocess.TimeoutExpired: | ||
| 222 | _kill_process_tree(proc) | ||
| 223 | print(f"TIMED OUT after {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 | code, _, diagnostic = read_result(path, code) | ||
| 239 | if diagnostic: | ||
| 240 | print(f"unittest discover in {directory}: {diagnostic}", file=sys.stderr) | ||
| 241 | return code | ||
| 104 | 242 | ||
| 105 | 243 | ||
| 106 | def run_module(directory, module, verbose, timeout=None): | 244 | def run_module(directory, module, verbose, timeout=None): |
| @@ -111,24 +249,37 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 111 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module | 249 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module |
| 112 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] | 250 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] |
| 113 | with tempfile.TemporaryDirectory() as scratch: | 251 | with tempfile.TemporaryDirectory() as scratch: |
| 114 | count_path = os.path.join(scratch, "count.json") | 252 | result_path, env = result_environment(scratch) |
| 115 | env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) | 253 | proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 254 | text=True, errors="replace") | ||
| 255 | _register_process(proc) | ||
| 116 | try: | 256 | try: |
| 117 | p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, | 257 | stdout, stderr = proc.communicate(timeout=timeout) |
| 118 | text=True, errors="replace", timeout=timeout) | 258 | except subprocess.TimeoutExpired: |
| 119 | except subprocess.TimeoutExpired as exc: | 259 | _kill_process_tree(proc) |
| 260 | stdout, stderr = proc.communicate() | ||
| 120 | # TimeoutExpired retains bytes even when text=True. | 261 | # TimeoutExpired retains bytes even when text=True. |
| 121 | parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) | 262 | parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) |
| 122 | else chunk for chunk in (exc.stdout, exc.stderr) if chunk] | 263 | else chunk for chunk in (stdout, stderr) if chunk] |
| 123 | out = "".join(parts) | 264 | out = "".join(parts) |
| 124 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" | 265 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" |
| 125 | count = read_count(count_path) | 266 | except BaseException: |
| 126 | out = p.stdout + p.stderr | 267 | _kill_process_tree(proc) |
| 127 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the | 268 | try: |
| 128 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. | 269 | proc.wait(timeout=0.5) |
| 129 | if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stderr: | 270 | except (subprocess.TimeoutExpired, OSError): |
| 271 | pass | ||
| 272 | raise | ||
| 273 | finally: | ||
| 274 | _unregister_process(proc) | ||
| 275 | code, count, diagnostic = read_result(result_path, proc.returncode) | ||
| 276 | out = stdout + stderr | ||
| 277 | if diagnostic: | ||
| 278 | out += f"\n{diagnostic}\n" | ||
| 279 | # A package initializer that completed with no tests isn't a failed module. | ||
| 280 | if code == 5 and count == 0 and module.endswith(".__init__"): | ||
| 130 | return 0, 0, out | 281 | return 0, 0, out |
| 131 | return p.returncode, count, out | 282 | return code, count or 0, out |
| 132 | 283 | ||
| 133 | 284 | ||
| 134 | def main(argv=None): | 285 | def main(argv=None): |
| @@ -147,26 +298,49 @@ def main(argv=None): | |||
| 147 | print(f"no {a.pattern} files in {directory}") | 298 | print(f"no {a.pattern} files in {directory}") |
| 148 | return 1 | 299 | return 1 |
| 149 | if a.jobs <= 1: | 300 | if a.jobs <= 1: |
| 150 | try: | 301 | return run_discover(directory, a.pattern, a.verbose, a.timeout) |
| 151 | return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, | ||
| 152 | "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) | ||
| 153 | except subprocess.TimeoutExpired: | ||
| 154 | # Inherited stdout/stderr have already emitted any partial test output. | ||
| 155 | print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) | ||
| 156 | return 1 | ||
| 157 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. | 302 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. |
| 158 | modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) | 303 | modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) |
| 159 | start, total, failed = time.monotonic(), 0, [] | 304 | start, total, failed = time.monotonic(), 0, [] |
| 160 | with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: | 305 | pool = concurrent.futures.ThreadPoolExecutor(a.jobs) |
| 161 | jobs = {pool.submit(run_module, directory, m, a.verbose, a.timeout): m for m in modules} | 306 | jobs = {} |
| 162 | for job in concurrent.futures.as_completed(jobs): | 307 | try: |
| 163 | code, ran, out = job.result() | 308 | for m in modules: |
| 164 | total += ran | 309 | jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m |
| 165 | if code: | 310 | pending = set(jobs) |
| 166 | failed.append(jobs[job]) | 311 | while pending: |
| 167 | print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) | 312 | done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED) |
| 168 | elif a.verbose: | 313 | for job in done: |
| 169 | print(f"==== {jobs[job]}\n{out}", flush=True) | 314 | pending.remove(job) |
| 315 | code, ran, out = job.result() | ||
| 316 | total += ran | ||
| 317 | if code: | ||
| 318 | failed.append(jobs[job]) | ||
| 319 | silent = "" if out.strip() else "(no output: the process ended before printing anything)\n" | ||
| 320 | print(f"==== FAILED: {jobs[job]} ({describe_exit(code)})\n{silent}{out}", flush=True) | ||
| 321 | elif a.verbose: | ||
| 322 | print(f"==== {jobs[job]}\n{out}", flush=True) | ||
| 323 | except KeyboardInterrupt: | ||
| 324 | for job in jobs: | ||
| 325 | job.cancel() | ||
| 326 | try: | ||
| 327 | pool.shutdown(wait=False, cancel_futures=True) | ||
| 328 | except TypeError: | ||
| 329 | pool.shutdown(wait=False) | ||
| 330 | _terminate_active_processes() | ||
| 331 | print("interrupted", file=sys.stderr) | ||
| 332 | return 130 | ||
| 333 | except BaseException: | ||
| 334 | for job in jobs: | ||
| 335 | job.cancel() | ||
| 336 | try: | ||
| 337 | pool.shutdown(wait=False, cancel_futures=True) | ||
| 338 | except TypeError: | ||
| 339 | pool.shutdown(wait=False) | ||
| 340 | _terminate_active_processes() | ||
| 341 | raise | ||
| 342 | else: | ||
| 343 | pool.shutdown(wait=True) | ||
| 170 | took = time.monotonic() - start | 344 | took = time.monotonic() - start |
| 171 | summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" | 345 | summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" |
| 172 | print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) | 346 | print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) |
| @@ -183,4 +357,8 @@ if __name__ == "__main__": | |||
| 183 | sys.stdout.reconfigure(errors="replace") | 357 | sys.stdout.reconfigure(errors="replace") |
| 184 | except (AttributeError, ValueError, OSError): | 358 | except (AttributeError, ValueError, OSError): |
| 185 | pass | 359 | pass |
| 186 | sys.exit(main()) | 360 | try: |
| 361 | sys.exit(main()) | ||
| 362 | except KeyboardInterrupt: | ||
| 363 | print("interrupted", file=sys.stderr) | ||
| 364 | sys.exit(130) | ||
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/translate_pipeline_compute.py b/scripts/translate_pipeline_compute.py index 4e691110b..cb6e17768 100644 --- a/scripts/translate_pipeline_compute.py +++ b/scripts/translate_pipeline_compute.py | |||
| @@ -1,26 +1,70 @@ | |||
| 1 | """Build an interrupted or new pipeline compute pack from shader_library.py output (Linux). | 1 | """Build an interrupted or new pipeline compute pack from shader_library.py output (Linux or Windows). |
| 2 | 2 | ||
| 3 | Two translation processes, including the parent, each run at most one SPIRV-Tools process. | 3 | Up to two translation processes each run at most one SPIRV-Tools process. |
| 4 | Validated modules and their receipts survive interruption. The runtime index is published last. | 4 | Validated modules and their receipts survive interruption. The runtime index is published last. |
| 5 | """ | 5 | """ |
| 6 | import argparse | 6 | import argparse |
| 7 | import fcntl | 7 | import contextlib |
| 8 | from dataclasses import dataclass, asdict | ||
| 8 | import hashlib | 9 | import hashlib |
| 10 | import inspect | ||
| 9 | import json | 11 | import json |
| 10 | import os | 12 | import os |
| 11 | import resource | ||
| 12 | import shutil | 13 | import shutil |
| 13 | import sys | 14 | import sys |
| 14 | import tempfile | 15 | import tempfile |
| 15 | from pathlib import Path | 16 | from pathlib import Path |
| 16 | 17 | ||
| 17 | ROOT = Path(__file__).resolve().parents[1] | 18 | ROOT = Path(__file__).resolve().parents[1] |
| 18 | sys.path[:0] = [str(ROOT / "tools"), str(ROOT)] | 19 | sys.path[:0] = [str(ROOT / "tools"), str(ROOT), str(ROOT / "scripts")] |
| 19 | from make_game import file_sha256 as digest, translation_sources_digest | 20 | from make_game import file_sha256 as digest, translation_sources_digest |
| 20 | import rdna2spirv as translator | 21 | import rdna2spirv as translator |
| 21 | 22 | ||
| 22 | 23 | ||
| 24 | @dataclass(frozen=True) | ||
| 25 | class Options: | ||
| 26 | wave64_emulate: bool | ||
| 27 | loop_limit: int | ||
| 28 | descriptor_hash: str | ||
| 29 | compact_spirv: bool | ||
| 30 | |||
| 31 | def __post_init__(self): | ||
| 32 | if (type(self.wave64_emulate) is not bool or type(self.compact_spirv) is not bool or | ||
| 33 | type(self.loop_limit) is not int or not 0 <= self.loop_limit <= 0xffffffff or | ||
| 34 | self.descriptor_hash not in translator.DESCRIPTOR_HASHES): | ||
| 35 | raise ValueError("invalid compute options") | ||
| 36 | |||
| 37 | def apply(self): | ||
| 38 | translator.WAVE64_EMULATE = self.wave64_emulate | ||
| 39 | translator.LOOP_LIMIT = self.loop_limit | ||
| 40 | translator.DESCRIPTOR_HASH = self.descriptor_hash | ||
| 41 | |||
| 42 | |||
| 43 | def observed(compact): | ||
| 44 | return asdict(Options(translator.WAVE64_EMULATE, translator.LOOP_LIMIT, translator.DESCRIPTOR_HASH, compact)) | ||
| 45 | |||
| 46 | |||
| 47 | def recipe(options): | ||
| 48 | if options.compact_spirv and "compact" not in inspect.signature(translator.assemble_spirv).parameters: | ||
| 49 | raise ValueError("this translator does not implement --compact-spirv") | ||
| 50 | binaries = {} | ||
| 51 | for tool in ["spirv-as", "spirv-val"] + (["spirv-opt"] if options.compact_spirv else []): | ||
| 52 | binary = shutil.which(tool) | ||
| 53 | if not binary: | ||
| 54 | raise ValueError(tool + " is required") | ||
| 55 | binaries[tool] = digest(Path(binary)) | ||
| 56 | return {"sources": translation_sources_digest(), "builder": digest(Path(__file__)), | ||
| 57 | "windows_adapter": digest(Path(__file__).with_name("compute_workers_win.py")), | ||
| 58 | "tools": binaries, "options": asdict(options)} | ||
| 59 | |||
| 60 | |||
| 61 | def object_digest(value): | ||
| 62 | return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest() | ||
| 63 | |||
| 64 | |||
| 23 | def build_one(src, out, name, settings, compact=False): | 65 | def build_one(src, out, name, settings, compact=False): |
| 66 | if observed(compact) != settings["options"]: | ||
| 67 | raise ValueError("translation options differ from cache recipe") | ||
| 24 | listing = src / "disasm" / (name + ".s") | 68 | listing = src / "disasm" / (name + ".s") |
| 25 | side = src / "fspx" / name | 69 | side = src / "fspx" / name |
| 26 | code, state = (Path(str(side) + suffix) for suffix in (".code", ".state")) | 70 | code, state = (Path(str(side) + suffix) for suffix in (".code", ".state")) |
| @@ -28,12 +72,13 @@ def build_one(src, out, name, settings, compact=False): | |||
| 28 | container = src / (name + ".dxbc") | 72 | container = src / (name + ".dxbc") |
| 29 | inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")), | 73 | inputs = [settings, name, code_key, state_key, digest(listing), digest(Path(str(side) + ".json")), |
| 30 | digest(container) if container.is_file() else None] | 74 | digest(container) if container.is_file() else None] |
| 31 | key = hashlib.sha256(json.dumps(inputs).encode()).hexdigest() | 75 | key = object_digest(inputs) |
| 32 | receipt = out / ".compute-cache" / (key + ".json") | 76 | receipt = out / ".compute-cache" / (key + ".json") |
| 33 | if receipt.exists(): | 77 | if receipt.exists(): |
| 34 | try: | 78 | try: |
| 35 | row = json.loads(receipt.read_text(encoding="utf-8")) | 79 | row = json.loads(receipt.read_text(encoding="utf-8")) |
| 36 | if (row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key): | 80 | if row["options"] == settings["options"] and ( |
| 81 | row["meta"]["fspx_code_sha256"], row["meta"]["fspx_state_sha256"]) == (code_key, state_key): | ||
| 37 | module_hash = row["module"] | 82 | module_hash = row["module"] |
| 38 | if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash): | 83 | if len(module_hash) == 64 and all(c in "0123456789abcdef" for c in module_hash): |
| 39 | if digest(out / (name + "_" + module_hash + ".spv")) == module_hash: | 84 | if digest(out / (name + "_" + module_hash + ".spv")) == module_hash: |
| @@ -45,7 +90,9 @@ def build_one(src, out, name, settings, compact=False): | |||
| 45 | with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp: | 90 | with tempfile.TemporaryDirectory(dir=out / ".compute-cache") as tmp: |
| 46 | sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv" | 91 | sa, sv = Path(tmp) / "module.spvasm", Path(tmp) / "module.spv" |
| 47 | sa.write_text(asm, encoding="utf-8", newline="\n") | 92 | sa.write_text(asm, encoding="utf-8", newline="\n") |
| 48 | result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, compact=compact) | 93 | # Older translators support ordinary assembly but do not accept the compact keyword. |
| 94 | # Explicit compact is gated by recipe() before either worker starts; never drop it. | ||
| 95 | result = translator.assemble_spirv(str(sa), str(sv), asm_text=asm, **({"compact": True} if compact else {})) | ||
| 49 | if result.returncode: | 96 | if result.returncode: |
| 50 | raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0]) | 97 | raise translator.Unsupported((result.stderr.splitlines() or ["SPIR-V tool failed"])[0]) |
| 51 | meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing)) | 98 | meta = translator.shader_meta(translator.translate.last_gen, asm, src_path=str(listing)) |
| @@ -53,50 +100,97 @@ def build_one(src, out, name, settings, compact=False): | |||
| 53 | "cs", code_key, state_key): | 100 | "cs", code_key, state_key): |
| 54 | raise ValueError("compute stage or FSPX identity mismatch") | 101 | raise ValueError("compute stage or FSPX identity mismatch") |
| 55 | module_hash = digest(sv) | 102 | module_hash = digest(sv) |
| 56 | sv.replace(out / (name + "_" + module_hash + ".spv")) | 103 | translator.replace_retry(sv, out / (name + "_" + module_hash + ".spv")) |
| 57 | row = {"meta": meta, "module": module_hash} | 104 | row = {"meta": meta, "module": module_hash, "options": observed(compact)} |
| 58 | translator.write_index(str(receipt), row) | 105 | translator.write_index(str(receipt), row) |
| 59 | return row | 106 | return row |
| 60 | 107 | ||
| 61 | 108 | ||
| 62 | def build_part(src, out, names, settings, report, compact=False): | 109 | def build_part(src, out, names, settings, report, shard): |
| 110 | options = Options(**settings["options"]) | ||
| 111 | options.apply() # identically on the POSIX parent/fork child and a newly spawned Windows interpreter | ||
| 112 | if recipe(options) != settings or observed(options.compact_spirv) != settings["options"]: | ||
| 113 | raise RuntimeError("compute worker recipe differs from coordinator") | ||
| 63 | rows, failures = {}, {} | 114 | rows, failures = {}, {} |
| 64 | for number, name in enumerate(names, 1): | 115 | for number, name in enumerate(names, 1): |
| 65 | try: | 116 | try: |
| 66 | rows[name] = build_one(src, out, name, settings, compact) | 117 | rows[name] = build_one(src, out, name, settings, options.compact_spirv) |
| 67 | except (translator.Unsupported, MemoryError) as e: | 118 | except (translator.Unsupported, MemoryError) as e: |
| 68 | failures[name] = str(e) or type(e).__name__ | 119 | failures[name] = str(e) or type(e).__name__ |
| 69 | if number % 100 == 0 or number == len(names): | 120 | if number % 100 == 0 or number == len(names): |
| 70 | print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True) | 121 | print(f"worker {os.getpid()}: {number}/{len(names)}, {len(failures)} failed", flush=True) |
| 71 | translator.write_index(str(report), {"rows": rows, "failures": failures}) | 122 | audit = {"shard": shard, "recipe_sha256": object_digest(settings), "names_sha256": object_digest(names), |
| 123 | "options": observed(options.compact_spirv), "accepted": len(rows), "failed": len(failures)} | ||
| 124 | translator.write_index(str(report), {"audit": audit, "rows": rows, "failures": failures}) | ||
| 125 | |||
| 126 | |||
| 127 | def run_request(path): | ||
| 128 | q = json.loads(path.read_text(encoding="utf-8")) | ||
| 129 | build_part(Path(q["src"]), Path(q["out"]), q["names"], q["settings"], Path(q["report"]), q["shard"]) | ||
| 72 | 130 | ||
| 73 | 131 | ||
| 74 | def build(src, out, names, settings, jobs, compact=False): | 132 | @contextlib.contextmanager |
| 133 | def output_lock(path): | ||
| 134 | if os.name == "nt": | ||
| 135 | import compute_workers_win as win | ||
| 136 | with win.output_lock(path) as lock: | ||
| 137 | yield lock | ||
| 138 | else: | ||
| 139 | import fcntl | ||
| 140 | with path.open("ab") as lock: | ||
| 141 | fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 142 | yield lock | ||
| 143 | |||
| 144 | |||
| 145 | def run_parts(src, out, names, settings, jobs, reports, mib, lock): | ||
| 146 | if os.name == "nt": | ||
| 147 | import compute_workers_win as win | ||
| 148 | requests = [] | ||
| 149 | for i, report in enumerate(reports): | ||
| 150 | request = report.with_suffix(".request") | ||
| 151 | translator.write_index(str(request), {"src": str(src), "out": str(out), "names": names[i::jobs], | ||
| 152 | "settings": settings, "report": str(report), "shard": i}) | ||
| 153 | requests.append(request) | ||
| 154 | win.run(requests, mib, lock) | ||
| 155 | return | ||
| 156 | pid = os.fork() if jobs == 2 else None | ||
| 157 | if pid == 0: | ||
| 158 | try: | ||
| 159 | build_part(src, out, names[1::2], settings, reports[1], 1) | ||
| 160 | except BaseException: | ||
| 161 | import traceback | ||
| 162 | traceback.print_exc() | ||
| 163 | os._exit(1) | ||
| 164 | os._exit(0) | ||
| 165 | try: | ||
| 166 | build_part(src, out, names[::jobs], settings, reports[0], 0) | ||
| 167 | finally: | ||
| 168 | if pid and os.waitpid(pid, 0)[1]: | ||
| 169 | raise RuntimeError("second translation worker failed") | ||
| 170 | |||
| 171 | |||
| 172 | def build(src, out, names, settings, jobs, mib): | ||
| 75 | cache = out / ".compute-cache" | 173 | cache = out / ".compute-cache" |
| 76 | cache.mkdir(exist_ok=True) | 174 | cache.mkdir(exist_ok=True) |
| 77 | with (cache / "lock").open("ab") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp: | 175 | with output_lock(cache / "lock") as lock, tempfile.TemporaryDirectory(dir=cache) as tmp: |
| 78 | fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 79 | reports = [Path(tmp) / str(i) for i in range(jobs)] | 176 | reports = [Path(tmp) / str(i) for i in range(jobs)] |
| 80 | pid = os.fork() if jobs == 2 else None | 177 | run_parts(src, out, names, settings, jobs, reports, mib, lock) |
| 81 | if pid == 0: | ||
| 82 | try: | ||
| 83 | build_part(src, out, names[1::2], settings, reports[1], compact) | ||
| 84 | except BaseException: | ||
| 85 | import traceback | ||
| 86 | traceback.print_exc() | ||
| 87 | os._exit(1) | ||
| 88 | os._exit(0) | ||
| 89 | try: | ||
| 90 | build_part(src, out, names[::jobs], settings, reports[0], compact) | ||
| 91 | finally: | ||
| 92 | if pid and os.waitpid(pid, 0)[1]: | ||
| 93 | raise RuntimeError("second translation worker failed") | ||
| 94 | 178 | ||
| 95 | index, failures, pairs = {}, {}, {} | 179 | index, failures, pairs = {}, {}, {} |
| 96 | for report in reports: | 180 | audits = [] |
| 181 | for i, report in enumerate(reports): | ||
| 97 | part = json.loads(report.read_text(encoding="utf-8")) | 182 | part = json.loads(report.read_text(encoding="utf-8")) |
| 183 | accepted, failed = set(part["rows"]), set(part["failures"]) | ||
| 184 | expected = names[i::jobs] | ||
| 185 | audit = {"shard": i, "recipe_sha256": object_digest(settings), "names_sha256": object_digest(expected), | ||
| 186 | "options": settings["options"], "accepted": len(accepted), "failed": len(failed)} | ||
| 187 | if part["audit"] != audit or accepted & failed or accepted | failed != set(expected): | ||
| 188 | raise ValueError("compute shard options or coverage mismatch") | ||
| 189 | audits.append(audit) | ||
| 98 | failures.update(part["failures"]) | 190 | failures.update(part["failures"]) |
| 99 | for name, row in part["rows"].items(): | 191 | for name, row in part["rows"].items(): |
| 192 | if row["options"] != settings["options"]: | ||
| 193 | raise ValueError("cached compute row options mismatch") | ||
| 100 | module, meta = row["module"], row["meta"] | 194 | module, meta = row["module"], row["meta"] |
| 101 | pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"] | 195 | pair = meta["fspx_code_sha256"], meta["fspx_state_sha256"] |
| 102 | if pairs.setdefault(pair, module) != module: | 196 | if pairs.setdefault(pair, module) != module: |
| @@ -110,7 +204,13 @@ def build(src, out, names, settings, jobs, compact=False): | |||
| 110 | state = digest(src / "fspx" / (name + ".state")) | 204 | state = digest(src / "fspx" / (name + ".state")) |
| 111 | by_hash.setdefault(code, {})[state] = reason | 205 | by_hash.setdefault(code, {})[state] = reason |
| 112 | translator.write_index(str(out / "failures.json"), by_hash) | 206 | translator.write_index(str(out / "failures.json"), by_hash) |
| 113 | translator.write_index(str(out / "index.json"), index) | 207 | # An audit, not a publication marker. Associate it with the actual index bytes after commit. |
| 208 | candidate = Path(tmp)/"final-index.json" | ||
| 209 | translator.write_index(str(candidate), index) | ||
| 210 | index_hash = digest(candidate) | ||
| 211 | translator.write_index(str(cache / "worker-receipt.json"), | ||
| 212 | {"schema": 1, "recipe": settings, "index_sha256": index_hash, "shards": audits}) | ||
| 213 | translator.replace_retry(candidate, out / "index.json") | ||
| 114 | print(f"{len(index)}/{len(names)} valid, {len(failures)} failed") | 214 | print(f"{len(index)}/{len(names)} valid, {len(failures)} failed") |
| 115 | return int(bool(failures)) | 215 | return int(bool(failures)) |
| 116 | 216 | ||
| @@ -120,7 +220,8 @@ def main(): | |||
| 120 | ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/") | 220 | ap.add_argument("inputs", type=Path, help="unpacked library with index.json, disasm/ and fspx/") |
| 121 | ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory") | 221 | ap.add_argument("--out", type=Path, required=True, help="dedicated runtime library subdirectory") |
| 122 | ap.add_argument("--jobs", type=int, choices=(1, 2), default=2) | 222 | ap.add_argument("--jobs", type=int, choices=(1, 2), default=2) |
| 123 | ap.add_argument("--memory-mib", type=int, default=768, help="virtual memory per process (default 768 MiB)") | 223 | ap.add_argument("--memory-mib", type=int, default=768, |
| 224 | help="per-process limit: virtual space (Linux) or committed memory (Windows); default 768 MiB") | ||
| 124 | ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a", | 225 | ap.add_argument("--descriptor-hash", choices=translator.DESCRIPTOR_HASHES, default="fnv1a", |
| 125 | help="bindless descriptor table hash shared with the runtime") | 226 | help="bindless descriptor table hash shared with the runtime") |
| 126 | ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit, | 227 | ap.add_argument("--loop-limit", type=translator.spirv_loop_guard.parse_limit, |
| @@ -133,21 +234,21 @@ def main(): | |||
| 133 | src, out = args.inputs.resolve(), args.out.resolve() | 234 | src, out = args.inputs.resolve(), args.out.resolve() |
| 134 | if out == src or src in out.parents or out in src.parents: | 235 | if out == src or src in out.parents or out in src.parents: |
| 135 | ap.error("input and output directories must be separate") | 236 | ap.error("input and output directories must be separate") |
| 136 | os.setpriority(os.PRIO_PROCESS, 0, 19) | 237 | if os.name == "nt": |
| 137 | soft, hard = resource.getrlimit(resource.RLIMIT_AS) | 238 | import compute_workers_win as win |
| 138 | bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY) | 239 | win.budget_coordinator(args.memory_mib) |
| 139 | resource.setrlimit(resource.RLIMIT_AS, (bound, hard)) | 240 | else: |
| 140 | versions = [] | 241 | import resource |
| 141 | required_tools = ["spirv-as", "spirv-val"] | 242 | os.setpriority(os.PRIO_PROCESS, 0, 19) |
| 142 | if args.compact_spirv: | 243 | soft, hard = resource.getrlimit(resource.RLIMIT_AS) |
| 143 | required_tools.append("spirv-opt") | 244 | bound = min(n for n in (args.memory_mib << 20, soft, hard) if n != resource.RLIM_INFINITY) |
| 144 | for tool in required_tools: | 245 | resource.setrlimit(resource.RLIMIT_AS, (bound, hard)) |
| 145 | binary = shutil.which(tool) | 246 | options = Options(args.wave64_emulate, args.loop_limit, args.descriptor_hash, args.compact_spirv) |
| 146 | if not binary: | 247 | options.apply() |
| 147 | ap.error(tool + " is required") | 248 | try: |
| 148 | versions.append(digest(Path(binary))) | 249 | settings = recipe(options) |
| 149 | settings = [translation_sources_digest(), digest(Path(__file__)), versions, args.wave64_emulate, | 250 | except ValueError as e: |
| 150 | args.loop_limit, args.descriptor_hash] | 251 | ap.error(str(e)) |
| 151 | rows = json.loads((src / "index.json").read_text(encoding="utf-8")) | 252 | rows = json.loads((src / "index.json").read_text(encoding="utf-8")) |
| 152 | names = [] | 253 | names = [] |
| 153 | for row in rows: | 254 | for row in rows: |
| @@ -156,14 +257,15 @@ def main(): | |||
| 156 | filename = row["file"] | 257 | filename = row["file"] |
| 157 | if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename: | 258 | if Path(filename).name != filename or not filename.endswith(".dxbc") or "\\" in filename: |
| 158 | ap.error("invalid compute filename in input index") | 259 | ap.error("invalid compute filename in input index") |
| 260 | if os.name == "nt" and (any(ord(c)<32 or c in '<>:"|?*' for c in filename) or | ||
| 261 | (os.path.isreserved(filename) if hasattr(os.path, "isreserved") | ||
| 262 | else Path(filename).is_reserved())): | ||
| 263 | ap.error("invalid Windows compute filename in input index") | ||
| 159 | names.append(filename[:-5]) | 264 | names.append(filename[:-5]) |
| 160 | if not names or len(set(names)) != len(names): | 265 | if not names or len({os.path.normcase(n) for n in names}) != len(names): |
| 161 | ap.error("expected unique compute filenames in the input index") | 266 | ap.error("expected unique compute filenames in the input index") |
| 162 | out.mkdir(parents=True, exist_ok=True) | 267 | out.mkdir(parents=True, exist_ok=True) |
| 163 | translator.DESCRIPTOR_HASH = args.descriptor_hash | 268 | return build(src, out, sorted(names), settings, args.jobs, args.memory_mib) |
| 164 | translator.LOOP_LIMIT = args.loop_limit | ||
| 165 | translator.WAVE64_EMULATE = args.wave64_emulate | ||
| 166 | return build(src, out, sorted(names), settings, args.jobs, args.compact_spirv) | ||
| 167 | 269 | ||
| 168 | 270 | ||
| 169 | if __name__ == "__main__": | 271 | if __name__ == "__main__": |
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 249a9c74e..8ba9b8a14 100644 --- a/scripts/vs_layout_census.py +++ b/scripts/vs_layout_census.py | |||
| @@ -23,14 +23,18 @@ 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 |
| 37 | from report_paths import same_report_path # noqa: E402 | ||
| 34 | import shader_ir # noqa: E402 | 38 | import shader_ir # noqa: E402 |
| 35 | from vs_input_survey import (FETCH_CALL, MBCNT, PARAM_EXPORT, POS0_EXPORT, PRIM_EXPORT, SENDMSG, # noqa: E402 | 39 | from vs_input_survey import (FETCH_CALL, MBCNT, PARAM_EXPORT, POS0_EXPORT, PRIM_EXPORT, SENDMSG, # noqa: E402 |
| 36 | read_before_write) | 40 | read_before_write) |
| @@ -87,11 +91,13 @@ def payloads_of(dxbc_path): | |||
| 87 | for i, blob in enumerate(blobs)] | 91 | for i, blob in enumerate(blobs)] |
| 88 | 92 | ||
| 89 | 93 | ||
| 90 | def survey(dxbc_dir, disasm_fn=None, limit=None): | 94 | def load_index(dxbc_dir): |
| 91 | """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" | 95 | """(stage by stem, stems in index order) from <dxbc>/index.json.""" |
| 92 | index_path = os.path.join(dxbc_dir, "index.json") | 96 | try: |
| 93 | with open(index_path, encoding="utf-8") as f: | 97 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8-sig") as f: |
| 94 | index = json.load(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 = {} |
| @@ -102,6 +108,28 @@ def survey(dxbc_dir, disasm_fn=None, limit=None): | |||
| 102 | if stem not in stages: | 108 | if stem not in stages: |
| 103 | names.append(stem) | 109 | names.append(stem) |
| 104 | stages[stem] = e.get("stage") | 110 | stages[stem] = e.get("stage") |
| 111 | return stages, names | ||
| 112 | |||
| 113 | |||
| 114 | def input_paths(dxbc_dir): | ||
| 115 | """Every file the census may read: index.json, then each indexed container and its disasm/<stem>.s listing. | ||
| 116 | An index that cannot be read names no more; survey() reports it.""" | ||
| 117 | paths = [os.path.join(dxbc_dir, "index.json")] | ||
| 118 | try: | ||
| 119 | _stages, names = load_index(dxbc_dir) | ||
| 120 | except (OSError, ValueError, RecursionError): | ||
| 121 | return paths | ||
| 122 | for name in names: | ||
| 123 | paths.append(os.path.join(dxbc_dir, name + ".dxbc")) | ||
| 124 | paths.append(os.path.join(dxbc_dir, "disasm", name + ".s")) | ||
| 125 | return paths | ||
| 126 | |||
| 127 | |||
| 128 | def survey(dxbc_dir, disasm_fn=None, limit=None): | ||
| 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") | ||
| 132 | stages, names = load_index(dxbc_dir) | ||
| 105 | if limit is not None: | 133 | if limit is not None: |
| 106 | names = names[:limit] | 134 | names = names[:limit] |
| 107 | 135 | ||
| @@ -179,19 +207,54 @@ def survey(dxbc_dir, disasm_fn=None, limit=None): | |||
| 179 | } | 207 | } |
| 180 | 208 | ||
| 181 | 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 | |||
| 182 | def main(argv=None): | 237 | def main(argv=None): |
| 183 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | 238 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 184 | 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") |
| 185 | ap.add_argument("--json", help="also write the counts as JSON") | 240 | ap.add_argument("--json", help="also write the counts as JSON") |
| 186 | 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)") |
| 187 | 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") | ||
| 188 | index_path = os.path.join(a.dxbc, "index.json") | 245 | index_path = os.path.join(a.dxbc, "index.json") |
| 189 | if a.json and os.path.exists(a.json) and os.path.exists(index_path) and os.path.samefile(a.json, index_path): | 246 | if a.json: |
| 190 | print(f"vs_layout_census: error: --json would overwrite the input {index_path}", file=sys.stderr) | 247 | # Refuse before survey(): it reads the whole corpus and runs llvm-mc for every unlisted payload. |
| 191 | return 2 | 248 | if os.path.isdir(a.json) or a.json.endswith(("/", "\\")): |
| 249 | print(f"vs_layout_census: error: --json {a.json} is a directory, not a JSON file", file=sys.stderr) | ||
| 250 | return 2 | ||
| 251 | for path in input_paths(a.dxbc): | ||
| 252 | if same_report_path(a.json, path): | ||
| 253 | print(f"vs_layout_census: error: --json would overwrite the input {path}", file=sys.stderr) | ||
| 254 | return 2 | ||
| 192 | try: | 255 | try: |
| 193 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) | 256 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) |
| 194 | except (OSError, ValueError) as e: | 257 | except (OSError, ValueError, RecursionError) as e: |
| 195 | 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) |
| 196 | return 2 | 259 | return 2 |
| 197 | print(f"{r['containers']} containers, {r['payloads']} payloads " | 260 | print(f"{r['containers']} containers, {r['payloads']} payloads " |
| @@ -205,8 +268,7 @@ def main(argv=None): | |||
| 205 | f"unlisted payloads disassembled {r['disassembled_unlisted']}") | 268 | f"unlisted payloads disassembled {r['disassembled_unlisted']}") |
| 206 | if a.json: | 269 | if a.json: |
| 207 | try: | 270 | try: |
| 208 | with open(a.json, "w", encoding="utf-8", newline="\n") as f: | 271 | _write_json_atomic(a.json, r) |
| 209 | json.dump(r, f, indent=1) | ||
| 210 | except OSError as e: | 272 | except OSError as e: |
| 211 | 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) |
| 212 | return 2 | 274 | return 2 |
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index 3a875af4b..1d3328ec8 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md | |||
| @@ -15,7 +15,7 @@ powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DryRun -GameDir D:\GT | |||
| 15 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv | 15 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv |
| 16 | 16 | ||
| 17 | # Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them. | 17 | # Extra or changed switches: trailing KEY=VALUE arguments (KEY= removes one), as run-boot.sh takes them. |
| 18 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x98f828c,0x78b2818" | 18 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name split -Seconds 120 LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=<rva>,<rva>,<rva>" |
| 19 | 19 | ||
| 20 | # Every parameter. | 20 | # Every parameter. |
| 21 | Get-Help -Full .\scripts\windows-boot\boot.ps1 | 21 | Get-Help -Full .\scripts\windows-boot\boot.ps1 |
| @@ -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 | |
| 41 | | `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports | | 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`) | |
| 42 | | `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps | | 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 | |
| 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,14 +84,33 @@ 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. |
| 74 | 90 | Share counts and states on the board. Keep paths, logs, traces, captures and dumps on your machine | |
| 75 | How to read the states: game state `0x7446510` goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing | 91 | ([AGENTS.md](../../AGENTS.md), "No game data"). |
| 76 | screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively) | 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. | ||
| 98 | |||
| 99 | How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing | ||
| 100 | screen waiting for A), `d` after A. | ||
| 101 | |||
| 102 | **Changed: the states need two variables now.** The script used to set `LEONIDA_PEEK` to the game-state and | ||
| 103 | session-state RVAs by default. Those addresses of the retail executable are no longer kept in the repository, so set | ||
| 104 | `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (hex, measured locally) in the shell before the boot. | ||
| 105 | Without them the script warns, sets no `LEONIDA_PEEK`, and the `states:` line and the RESULT show `game=? | ||
| 106 | session=?`. A `LEONIDA_PEEK` of your own still works for the log, but the digest reads only the two RVAs those | ||
| 107 | variables name. `docs/linux_proton.md` (the same stages apply natively) | ||
| 77 | 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". |
| 78 | 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 | |||
| 79 | ## One game at a time | 114 | ## One game at a time |
| 80 | 115 | ||
| 81 | 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` |
| @@ -91,3 +126,33 @@ game processes on one GPU make both runs meaningless and can take the driver dow | |||
| 91 | | `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only | | 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 | |
| 92 | 127 | ||
| 93 | 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 d052a79da..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 |
| @@ -66,7 +67,7 @@ | |||
| 66 | 67 | ||
| 67 | .PARAMETER EnvPairs | 68 | .PARAMETER EnvPairs |
| 68 | Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with | 69 | Any further arguments, each KEY=VALUE, as scripts/linux-boot/run-boot.sh takes them. These work with |
| 69 | powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=0x7446510,0x75e8eb0". | 70 | powershell -File too: ... -Name x LEONIDA_PRESENT_PLANE1=0 "LEONIDA_PEEK=<rva>,<rva>". |
| 70 | Applied after -SetEnv. KEY= removes the variable for this boot. | 71 | Applied after -SetEnv. KEY= removes the variable for this boot. |
| 71 | 72 | ||
| 72 | .PARAMETER NoCapture | 73 | .PARAMETER NoCapture |
| @@ -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 | ||
| @@ -97,7 +104,7 @@ | |||
| 97 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv | 104 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv |
| 98 | 105 | ||
| 99 | .EXAMPLE | 106 | .EXAMPLE |
| 100 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=0x7446510,0x75e8eb0,0x75e8ea0,0x9844898" | 107 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=<rva>,<rva>" |
| 101 | 108 | ||
| 102 | .EXAMPLE | 109 | .EXAMPLE |
| 103 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first | 110 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first |
| @@ -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 |
| @@ -234,15 +256,27 @@ $defaults = [ordered]@{ | |||
| 234 | LEONIDA_PIPELINE_CACHE_BYTES = "4294967296" | 256 | LEONIDA_PIPELINE_CACHE_BYTES = "4294967296" |
| 235 | LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1" | 257 | LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1" |
| 236 | LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache") | 258 | LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache") |
| 237 | LEONIDA_PEEK = "0x7446510,0x98f828c" # game state, session state (low dword) | 259 | # LEONIDA_PEEK: the game-state and session-state RVAs (measured locally, not kept in the repository) when |
| 260 | # LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA name them; see below. | ||
| 238 | LEONIDA_PEEK_SECONDS = "5" | 261 | LEONIDA_PEEK_SECONDS = "5" |
| 239 | 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) | ||
| 240 | LEONIDA_CAPTURE_EVERY = "60" | 266 | LEONIDA_CAPTURE_EVERY = "60" |
| 241 | LEONIDA_CAPTURE_LIMIT = "40" | 267 | LEONIDA_CAPTURE_LIMIT = "40" |
| 242 | DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off | 268 | DISABLE_RTSS_LAYER = "1" # third-party Vulkan overlay layers off |
| 243 | DISABLE_VULKAN_OBS_CAPTURE = "1" | 269 | DISABLE_VULKAN_OBS_CAPTURE = "1" |
| 244 | } | 270 | } |
| 245 | if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } | 271 | if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } |
| 272 | $gameStateRva = "$env:LEONIDA_GAME_STATE_RVA".ToLowerInvariant() -replace '^0x', '' | ||
| 273 | $sessionStateRva = "$env:LEONIDA_SESSION_STATE_RVA".ToLowerInvariant() -replace '^0x', '' | ||
| 274 | if ($gameStateRva -and $sessionStateRva) { $defaults["LEONIDA_PEEK"] = "0x$gameStateRva,0x$sessionStateRva" } | ||
| 275 | else { | ||
| 276 | # The two RVAs were built in until they were taken out of the repository; say so rather than report "?" silently. | ||
| 277 | Write-Warning ("LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA are not both set: no LEONIDA_PEEK by default, " + | ||
| 278 | "so the RESULT game and session states read '?' (scripts/windows-boot/README.md)") | ||
| 279 | } | ||
| 246 | # Per-run values: always this script's (from its parameters), whatever the shell has. | 280 | # Per-run values: always this script's (from its parameters), whatever the shell has. |
| 247 | $perRun = [ordered]@{ | 281 | $perRun = [ordered]@{ |
| 248 | LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) | 282 | LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) |
| @@ -252,29 +286,117 @@ if ($Shaders) { $perRun["LEONIDA_SHADERS"] = $Shaders } | |||
| 252 | if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks } | 286 | if ($Stacks) { $perRun["LEONIDA_STACKS"] = $Stacks } |
| 253 | 287 | ||
| 254 | $bootEnv = [ordered]@{} | 288 | $bootEnv = [ordered]@{} |
| 289 | $given = @{} # the variables this shell, -SetEnv or KEY=VALUE set, as opposed to the defaults above | ||
| 255 | foreach ($k in $defaults.Keys) { | 290 | foreach ($k in $defaults.Keys) { |
| 256 | $cur = [Environment]::GetEnvironmentVariable($k) | 291 | $cur = [Environment]::GetEnvironmentVariable($k) |
| 257 | if ($cur) { $bootEnv[$k] = $cur } else { $bootEnv[$k] = $defaults[$k] } | 292 | if ($cur) { $bootEnv[$k] = $cur; $given[$k] = $true } else { $bootEnv[$k] = $defaults[$k] } |
| 258 | } | 293 | } |
| 259 | foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] } | 294 | foreach ($k in $perRun.Keys) { $bootEnv[$k] = $perRun[$k] } |
| 260 | # Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below. | 295 | # Other LEONIDA_* switches already set in this shell are passed through as they are; they are listed below. |
| 261 | foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) { | 296 | foreach ($item in (Get-ChildItem Env: | Where-Object { $_.Name -like "LEONIDA_*" })) { |
| 262 | if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value } | 297 | if (-not $bootEnv.Contains($item.Name)) { $bootEnv[$item.Name] = $item.Value } |
| 263 | } | 298 | } |
| 264 | 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 } |
| 265 | foreach ($pair in $EnvPairs) { | 300 | foreach ($pair in $EnvPairs) { |
| 266 | if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" } | 301 | if ($pair -notmatch '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { throw "not a parameter and not KEY=VALUE: '$pair' (Get-Help $PSCommandPath -Full)" } |
| 267 | $bootEnv[$Matches[1]] = $Matches[2] | 302 | $bootEnv[$Matches[1]] = $Matches[2]; $given[$Matches[1]] = $true |
| 268 | } | 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" } | ||
| 269 | 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 } | ||
| 270 | 390 | ||
| 271 | $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 | ||
| 272 | $argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " | 393 | $argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " |
| 273 | 394 | ||
| 274 | if (-not $DigestOnly) { | 395 | if (-not $DigestOnly) { |
| 275 | Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot" | 396 | Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot" |
| 276 | Write-Output "[boot] gta6rt $Runtime" | 397 | Write-Output "[boot] gta6rt $Runtime" |
| 277 | Write-Output "[boot] out $OutDir" | 398 | Write-Output "[boot] out $OutDir" |
| 399 | Write-Output "[boot] cwd $RunDirectory" | ||
| 278 | 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]) } } |
| 279 | Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine" | 401 | Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine" |
| 280 | } | 402 | } |
| @@ -314,7 +436,7 @@ if (-not $DigestOnly) { | |||
| 314 | } | 436 | } |
| 315 | } | 437 | } |
| 316 | 438 | ||
| 317 | 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 } |
| 318 | if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) { | 440 | if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) { |
| 319 | 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 |
| 320 | } | 442 | } |
| @@ -336,11 +458,30 @@ if (-not $DigestOnly) { | |||
| 336 | 458 | ||
| 337 | # ------------------------------------------------------------------------------------------- the boot | 459 | # ------------------------------------------------------------------------------------------- the boot |
| 338 | $started = Get-Date | 460 | $started = Get-Date |
| 339 | $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 ` | ||
| 340 | -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile | 472 | -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile |
| 341 | $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 |
| 342 | $stopped = $false | 474 | $stopped = $false |
| 343 | 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)) { | ||
| 344 | $stopped = $true | 485 | $stopped = $true |
| 345 | try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } | 486 | try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { } |
| 346 | [void]$proc.WaitForExit(20000) | 487 | [void]$proc.WaitForExit(20000) |
| @@ -360,6 +501,67 @@ if (-not $DigestOnly) { | |||
| 360 | 501 | ||
| 361 | # -------------------------------------------------------------------------------------------- the digest | 502 | # -------------------------------------------------------------------------------------------- the digest |
| 362 | 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 | |||
| 363 | $py = @(Resolve-Python $Python) | 565 | $py = @(Resolve-Python $Python) |
| 364 | if ($py.Count) { | 566 | if ($py.Count) { |
| 365 | $pyArgs = @() | 567 | $pyArgs = @() |
| @@ -378,10 +580,31 @@ $valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)' | |||
| 378 | $states = New-Object System.Collections.Generic.List[string] | 580 | $states = New-Object System.Collections.Generic.List[string] |
| 379 | $lastPeek = ""; $prevPair = "" | 581 | $lastPeek = ""; $prevPair = "" |
| 380 | $presentOk = 0; $presentFailed = 0; $presses = 0 | 582 | $presentOk = 0; $presentFailed = 0; $presses = 0 |
| 381 | $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=' | ||
| 382 | $wrapped = 0 | 590 | $wrapped = 0 |
| 383 | if (Test-Path -LiteralPath $LogFile) { | 591 | if (Test-Path -LiteralPath $LogFile) { |
| 384 | 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 | } | ||
| 385 | if ($line.Contains("XboxPresentation::PresentX")) { | 608 | if ($line.Contains("XboxPresentation::PresentX")) { |
| 386 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } | 609 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } |
| 387 | continue | 610 | continue |
| @@ -393,8 +616,8 @@ if (Test-Path -LiteralPath $LogFile) { | |||
| 393 | $game = "?"; $session = "?" | 616 | $game = "?"; $session = "?" |
| 394 | foreach ($v in $valRx.Matches($m.Groups[2].Value)) { | 617 | foreach ($v in $valRx.Matches($m.Groups[2].Value)) { |
| 395 | $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value | 618 | $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value |
| 396 | if ($rva -eq "7446510") { $game = $val } | 619 | if ($gameStateRva -and $rva -eq $gameStateRva) { $game = $val } |
| 397 | elseif ($rva -eq "98f828c" -and $val -ne "?") { | 620 | elseif ($sessionStateRva -and $rva -eq $sessionStateRva -and $val -ne "?") { |
| 398 | $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword | 621 | $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword |
| 399 | $session = $(if ($low) { $low } else { "0" }) | 622 | $session = $(if ($low) { $low } else { "0" }) |
| 400 | } | 623 | } |
| @@ -409,8 +632,6 @@ if (Test-Path -LiteralPath $LogFile) { | |||
| 409 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } | 632 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } |
| 410 | continue | 633 | continue |
| 411 | } | 634 | } |
| 412 | if ($line.Contains("[rt] device-fault:") -and -not $line.Contains("device-fault: enabled")) { if ($faults.Count -lt 8) { $faults.Add($line.Trim()) }; continue } | ||
| 413 | if ($line.Contains("VK_ERROR_DEVICE_LOST") -and $faults.Count -lt 8) { $faults.Add($line.Trim()); continue } | ||
| 414 | if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() } | 635 | if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() } |
| 415 | if ($line.Contains("wrapped V#")) { $wrapped++ } | 636 | if ($line.Contains("wrapped V#")) { $wrapped++ } |
| 416 | } | 637 | } |
| @@ -442,9 +663,21 @@ $digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated- | |||
| 442 | $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' })") |
| 443 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") | 664 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") |
| 444 | $digest.Add("input: $presses presses logged") | 665 | $digest.Add("input: $presses presses logged") |
| 445 | $digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })") | 666 | $faultClasses = @(for ($i = 0; $i -lt $faultNames.Length; $i++) { |
| 446 | 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") | ||
| 447 | 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 | } | ||
| 448 | $digest.Add("frames: $capText") | 681 | $digest.Add("frames: $capText") |
| 449 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") | 682 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") |
| 450 | $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) | ||