diff options
| author | MoonEyes <14891700+MoonEyes@users.noreply.github.com> | 2026-11-28 21:24:37 +0100 |
|---|---|---|
| committer | MoonEyes <14891700+MoonEyes@users.noreply.github.com> | 2026-11-28 21:24:37 +0100 |
| commit | f4112fca9f3e5e52fdc7e09233ee95219e1e1071 (patch) | |
| tree | 17ea75d05dd315fde16dc549e25843672de6d42e /scripts | |
| parent | b8b192ea2246ba6d51f278481301364fa3aed638 (diff) | |
| parent | 30fc2d68cc509ae9eeb2e39a900dbe1a98b2e745 (diff) | |
Merge main into codex/semantic-runner-serial-deadline (resolve conflict in scripts/run_semantic_tests.py)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'scripts')
44 files changed, 3867 insertions, 353 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..b639098b9 --- /dev/null +++ b/scripts/bench_translate.py | |||
| @@ -0,0 +1,309 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Throughput of the translator (tools/rdna2spirv.py): microseconds per instruction, so a slowdown is visible. | ||
| 3 | |||
| 4 | python -I scripts/bench_translate.py # fixtures + synthetic programs, best of 3 | ||
| 5 | python -I scripts/bench_translate.py --json # the same numbers as JSON | ||
| 6 | python -I scripts/bench_translate.py --runs 5 --max-slowdown 1.5 | ||
| 7 | |||
| 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 statistics | ||
| 28 | import struct | ||
| 29 | import subprocess | ||
| 30 | import sys | ||
| 31 | import tempfile | ||
| 32 | import time | ||
| 33 | import warnings | ||
| 34 | |||
| 35 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 36 | TOOLS = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 37 | FIXTURES = os.path.join(ROOT, "tests", "semantic", "fixtures", "disasm") | ||
| 38 | sys.dont_write_bytecode = True | ||
| 39 | sys.path.insert(0, TOOLS) | ||
| 40 | import rdna2spirv # noqa: E402 | ||
| 41 | |||
| 42 | # A DXBC container with zero parts declares no inputs, which is enough for a listing that reads no attribute | ||
| 43 | # (tests/semantic/support.py uses the same stub). | ||
| 44 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 45 | |||
| 46 | ALU_BODY = ("\tv_add_f32 v1, v1, 1.0\n" | ||
| 47 | "\tv_mul_f32 v2, v1, 2.0\n" | ||
| 48 | "\tv_cndmask_b32 v3, v1, v2, vcc\n" | ||
| 49 | "\tv_and_b32 v4, v3, 0xff\n") | ||
| 50 | NOP_BODY = "\ts_nop 0\n" | ||
| 51 | |||
| 52 | |||
| 53 | def synthetic(name, body, instructions): | ||
| 54 | """A whole pixel shader: comment, the repeated body, and the export the stage needs to be a shader.""" | ||
| 55 | lines = [f"; ps_{name} synthetic benchmark program\n"] | ||
| 56 | lines.extend([body] * ((instructions + body.count("\n") - 1) // body.count("\n"))) | ||
| 57 | lines.extend(["\tv_mov_b32 v1, 1\n", | ||
| 58 | "\texp mrt0 v1, v1, v1, v1 done\n", | ||
| 59 | "\ts_waitcnt expcnt(0)\n", | ||
| 60 | "\ts_endpgm\n"]) | ||
| 61 | return "".join(lines).encode("utf-8") | ||
| 62 | |||
| 63 | |||
| 64 | def translate_bytes(stem, listing, runs): | ||
| 65 | """Best of `runs` wall-clock seconds for one translate() of this listing, and the instruction count.""" | ||
| 66 | with tempfile.TemporaryDirectory() as tmp: | ||
| 67 | os.mkdir(os.path.join(tmp, "disasm")) | ||
| 68 | with open(os.path.join(tmp, "disasm", stem + ".s"), "wb") as f: | ||
| 69 | f.write(listing) | ||
| 70 | with open(os.path.join(tmp, stem + ".dxbc"), "wb") as f: | ||
| 71 | f.write(STUB_DXBC) | ||
| 72 | path = os.path.join(tmp, "disasm", stem + ".s") | ||
| 73 | best = None | ||
| 74 | for _ in range(runs): | ||
| 75 | start = time.perf_counter() | ||
| 76 | with warnings.catch_warnings(): | ||
| 77 | # The translator leaves its .dxbc handle to the garbage collector; that is its own business here. | ||
| 78 | warnings.simplefilter("ignore") | ||
| 79 | rdna2spirv.translate(path) | ||
| 80 | elapsed = time.perf_counter() - start | ||
| 81 | best = elapsed if best is None else min(best, elapsed) | ||
| 82 | return best | ||
| 83 | |||
| 84 | |||
| 85 | def instruction_count(listing): | ||
| 86 | return sum(1 for line in listing.decode("utf-8", "replace").splitlines() | ||
| 87 | if line.startswith("\t") and line.strip()) | ||
| 88 | |||
| 89 | |||
| 90 | def corpus_rows(runs): | ||
| 91 | """Time every fixture that translates on its own, and count the ones that need an FSSM header.""" | ||
| 92 | rows, skipped = [], [] | ||
| 93 | for name in sorted(os.listdir(FIXTURES)): | ||
| 94 | if not name.endswith(".s"): | ||
| 95 | continue | ||
| 96 | stem = name[:-2] | ||
| 97 | if stem.startswith("cs_"): | ||
| 98 | # A compute listing reads its group size and RSRC2 out of the FSSM header, which translate() takes from | ||
| 99 | # <dir>/../fssm/<stem>.fssm; the semantic tests pass it per fixture (tests/semantic/support.py). | ||
| 100 | skipped.append(f"{stem}: compute listing, needs a FSSM header") | ||
| 101 | continue | ||
| 102 | with open(os.path.join(FIXTURES, name), "rb") as f: | ||
| 103 | listing = f.read() | ||
| 104 | try: | ||
| 105 | seconds = translate_bytes(stem, listing, runs) | ||
| 106 | except Exception as error: # a listing this run cannot translate: report it, never count it as fast | ||
| 107 | skipped.append(f"{stem}: {type(error).__name__}: {error}") | ||
| 108 | continue | ||
| 109 | instructions = instruction_count(listing) | ||
| 110 | rows.append({"name": stem, "instructions": instructions, "seconds": seconds, | ||
| 111 | "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0}) | ||
| 112 | return rows, skipped | ||
| 113 | |||
| 114 | |||
| 115 | def synthetic_rows(runs, size): | ||
| 116 | rows = [] | ||
| 117 | for name, body, instructions in (("alu", ALU_BODY, size), ("nop", NOP_BODY, size)): | ||
| 118 | listing = synthetic(name, body, instructions) | ||
| 119 | seconds = translate_bytes("ps_" + name, listing, runs) | ||
| 120 | count = instruction_count(listing) | ||
| 121 | rows.append({"name": name, "instructions": count, "seconds": seconds, | ||
| 122 | "us_per_instruction": seconds / count * 1e6}) | ||
| 123 | return rows | ||
| 124 | |||
| 125 | |||
| 126 | def summarise(rows): | ||
| 127 | if not rows: | ||
| 128 | return {"programs": 0, "instructions": 0, "seconds": 0.0, "us_per_instruction": 0.0} | ||
| 129 | instructions = sum(r["instructions"] for r in rows) | ||
| 130 | seconds = sum(r["seconds"] for r in rows) | ||
| 131 | return {"programs": len(rows), "instructions": instructions, "seconds": seconds, | ||
| 132 | "us_per_instruction": seconds / instructions * 1e6 if instructions else 0.0} | ||
| 133 | |||
| 134 | |||
| 135 | # Recorded on this machine (AMD Ryzen 9 desktop, Windows 11, Python 3.12.4, commit 1cc6e3c) with --runs 3: the numbers | ||
| 136 | # to compare a later run against on the same machine. A different machine moves the absolute value; the shape does not. | ||
| 137 | BASELINE = {"corpus_us_per_instruction": 55.4, "alu_us_per_instruction": 32.3, "nop_us_per_instruction": 14.0} | ||
| 138 | |||
| 139 | |||
| 140 | def compare(reference, candidate, runs, size, rounds, max_slowdown=None): | ||
| 141 | """Interleaved A/B over two tools/ trees: each round measures both, and the best per side is kept. | ||
| 142 | |||
| 143 | Loading the tree is the subprocess's job (LEONIDA_TOOLS_DIR, as tests/semantic/support.py does it), so the two | ||
| 144 | versions never share a module. Alternating the two in the same round is the point: a machine that slows down or | ||
| 145 | speeds up between measurements moves both sides, not just one. | ||
| 146 | """ | ||
| 147 | def measure(path): | ||
| 148 | env = dict(os.environ, LEONIDA_TOOLS_DIR=os.path.abspath(path)) | ||
| 149 | result = subprocess.run([sys.executable, "-I", os.path.abspath(__file__), "--json", | ||
| 150 | "--runs", str(runs), "--size", str(size)], | ||
| 151 | capture_output=True, text=True, env=env) | ||
| 152 | if result.returncode != 0: | ||
| 153 | raise SystemExit(f"{path}: the benchmark failed\n{result.stderr.strip()}") | ||
| 154 | return json.loads(result.stdout)["measured"] | ||
| 155 | |||
| 156 | best = {"reference": {}, "candidate": {}} | ||
| 157 | measured_any = False | ||
| 158 | for round_index in range(rounds + 1): # the first round warms the caches and is not counted | ||
| 159 | order = [("reference", reference), ("candidate", candidate)] | ||
| 160 | if round_index % 2: | ||
| 161 | order.reverse() # whoever runs first pays the cold file cache, so the order alternates | ||
| 162 | for side, path in order: | ||
| 163 | measured = measure(path) | ||
| 164 | measured_any = measured_any or bool(measured) | ||
| 165 | if round_index == 0: | ||
| 166 | continue | ||
| 167 | for key, value in measured.items(): | ||
| 168 | best[side][key] = min(best[side].get(key, value), value) | ||
| 169 | if not measured_any: | ||
| 170 | raise SystemExit("both trees measured nothing (an empty corpus?); nothing to compare") | ||
| 171 | if sorted(best["reference"]) != sorted(best["candidate"]): | ||
| 172 | only_reference = sorted(set(best["reference"]) - set(best["candidate"])) | ||
| 173 | only_candidate = sorted(set(best["candidate"]) - set(best["reference"])) | ||
| 174 | raise SystemExit("the two trees do not cover the same measurements" | ||
| 175 | + (f"; only in the reference: {', '.join(only_reference)}" if only_reference else "") | ||
| 176 | + (f"; only in the candidate: {', '.join(only_candidate)}" if only_candidate else "") | ||
| 177 | + "; a missing program would read as a ratio that looks like a win") | ||
| 178 | rows = [] | ||
| 179 | for key in best["reference"]: | ||
| 180 | ref = best["reference"][key] | ||
| 181 | cand = best["candidate"].get(key, float("nan")) | ||
| 182 | rows.append({"name": key, "reference": ref, "candidate": cand, "ratio": cand / ref if ref else None}) | ||
| 183 | print(f"{'measurement':<32} {'reference':>10} {'candidate':>10} {'ratio':>7}") | ||
| 184 | for row in rows: | ||
| 185 | ratio = f"{row['ratio']:>6.2f}x" if row["ratio"] is not None else " n/a" | ||
| 186 | print(f"{row['name']:<32} {row['reference']:>10.1f} {row['candidate']:>10.1f} {ratio}") | ||
| 187 | print(f"\nreference {os.path.abspath(reference)}\ncandidate {os.path.abspath(candidate)}") | ||
| 188 | print("ratio below 1.00 is the candidate being faster; rounds %d, min per side" % rounds) | ||
| 189 | if max_slowdown is not None: | ||
| 190 | # The limit means here what it means against a baseline: a measurement over it is a failure. The ratio is | ||
| 191 | # already candidate/reference, so the limit applies to it directly. | ||
| 192 | slow = [row for row in rows if row["ratio"] is not None and row["ratio"] > max_slowdown] | ||
| 193 | if slow: | ||
| 194 | for row in slow: | ||
| 195 | print(f"slower than the reference by {row['ratio']:.2f}x (limit {max_slowdown:.2f}x): {row['name']}", | ||
| 196 | file=sys.stderr) | ||
| 197 | return 1 | ||
| 198 | return 0 | ||
| 199 | |||
| 200 | |||
| 201 | def main(argv=None): | ||
| 202 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 203 | parser.add_argument("--runs", type=int, default=3, help="translate() calls per program, best one counted") | ||
| 204 | parser.add_argument("--size", type=int, default=2000, help="instructions in each synthetic program") | ||
| 205 | parser.add_argument("--json", action="store_true", help="print one JSON object instead of the tables") | ||
| 206 | parser.add_argument("--max-slowdown", type=float, default=None, | ||
| 207 | help="exit 1 when a per-instruction time exceeds the baseline by this factor, in every output " | ||
| 208 | "format") | ||
| 209 | parser.add_argument("--baseline", metavar="FILE", default=None, | ||
| 210 | help="compare against a baseline written by --write-baseline instead of the committed one; " | ||
| 211 | "the committed numbers are from one machine and mean nothing on another") | ||
| 212 | parser.add_argument("--write-baseline", metavar="FILE", default=None, | ||
| 213 | help="write this run's numbers to FILE as a baseline for --baseline") | ||
| 214 | parser.add_argument("--compare", nargs=2, metavar=("REFERENCE", "CANDIDATE"), default=None, | ||
| 215 | help="time two tools/ trees against each other, interleaved; prints a ratio per measurement") | ||
| 216 | parser.add_argument("--rounds", type=int, default=3, help="rounds of --compare; the best per side is kept") | ||
| 217 | arguments = parser.parse_args(argv) | ||
| 218 | if arguments.rounds < 1: | ||
| 219 | parser.error("--rounds must be at least 1") | ||
| 220 | if arguments.baseline and arguments.write_baseline and \ | ||
| 221 | os.path.abspath(arguments.baseline) == os.path.abspath(arguments.write_baseline): | ||
| 222 | # One file for both: a run that fails the limit would still replace the reference it failed against, and the | ||
| 223 | # same workload would pass on the retry. | ||
| 224 | parser.error("--baseline and --write-baseline name the same file; write to a different one") | ||
| 225 | if arguments.compare: | ||
| 226 | for flag, value in (("--json", arguments.json), ("--write-baseline", arguments.write_baseline), | ||
| 227 | ("--baseline", arguments.baseline)): | ||
| 228 | if value: | ||
| 229 | parser.error(f"{flag} does not apply to --compare, which times two trees and prints its own table") | ||
| 230 | return compare(*arguments.compare, arguments.runs, arguments.size, arguments.rounds, | ||
| 231 | arguments.max_slowdown) | ||
| 232 | if arguments.baseline and not os.path.isfile(arguments.baseline): | ||
| 233 | parser.error(f"--baseline {arguments.baseline} does not exist; --write-baseline records one") | ||
| 234 | if arguments.runs < 1: | ||
| 235 | parser.error("--runs must be at least 1") | ||
| 236 | if arguments.size < 1: | ||
| 237 | parser.error("--size must be at least 1") | ||
| 238 | |||
| 239 | corpus, skipped = corpus_rows(arguments.runs) | ||
| 240 | synthetic_programs = synthetic_rows(arguments.runs, arguments.size) | ||
| 241 | corpus_summary = summarise(corpus) | ||
| 242 | synthetic_summary = summarise(synthetic_programs) | ||
| 243 | |||
| 244 | measured = {"corpus_us_per_instruction": corpus_summary["us_per_instruction"]} | ||
| 245 | measured.update({f"{row['name']}_us_per_instruction": row["us_per_instruction"] | ||
| 246 | for row in synthetic_programs}) | ||
| 247 | |||
| 248 | baseline, baseline_source = BASELINE, "committed" | ||
| 249 | if arguments.baseline: | ||
| 250 | with open(arguments.baseline, encoding="utf-8") as handle: | ||
| 251 | loaded = json.load(handle) | ||
| 252 | baseline = {key: float(value) for key, value in (loaded.get("measured") or loaded).items()} | ||
| 253 | baseline_source = os.path.abspath(arguments.baseline) | ||
| 254 | if arguments.write_baseline: | ||
| 255 | with open(arguments.write_baseline, "w", encoding="utf-8", newline="\n") as handle: | ||
| 256 | json.dump({"measured": measured, "runs": arguments.runs, "size": arguments.size}, handle, | ||
| 257 | indent=2, sort_keys=True) | ||
| 258 | handle.write("\n") | ||
| 259 | print(f"baseline written to {os.path.abspath(arguments.write_baseline)}", file=sys.stderr) | ||
| 260 | |||
| 261 | # The limit is part of the contract of every output format: a job that collects --json must not read a success | ||
| 262 | # code for a run whose numbers are over the limit. It is evaluated here, once, before either format prints. | ||
| 263 | slow = {} | ||
| 264 | if arguments.max_slowdown is not None: | ||
| 265 | slow = {key: value / baseline[key] for key, value in measured.items() | ||
| 266 | if baseline.get(key) and value > baseline[key] * arguments.max_slowdown} | ||
| 267 | |||
| 268 | if arguments.json: | ||
| 269 | print(json.dumps({ | ||
| 270 | "runs": arguments.runs, | ||
| 271 | "corpus": {"summary": corpus_summary, "programs": corpus, "skipped": skipped}, | ||
| 272 | "synthetic": {"summary": synthetic_summary, "programs": synthetic_programs, "size": arguments.size}, | ||
| 273 | "baseline": baseline, | ||
| 274 | "baseline_source": baseline_source, | ||
| 275 | "measured": measured, | ||
| 276 | "slowdown": {k: (measured[k] / baseline[k] if baseline.get(k) else None) for k in measured}, | ||
| 277 | "over_limit": sorted(slow), | ||
| 278 | "max_slowdown": arguments.max_slowdown, | ||
| 279 | }, indent=2, sort_keys=True)) | ||
| 280 | return 1 if slow else 0 | ||
| 281 | |||
| 282 | print(f"corpus: {corpus_summary['programs']} fixtures, {corpus_summary['instructions']} instructions, " | ||
| 283 | f"{corpus_summary['seconds']:.3f} s, {corpus_summary['us_per_instruction']:.1f} us/instruction " | ||
| 284 | f"({len(skipped)} skipped)") | ||
| 285 | worst = sorted(corpus, key=lambda r: -r["us_per_instruction"])[:5] | ||
| 286 | for row in worst: | ||
| 287 | print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms " | ||
| 288 | f"{row['us_per_instruction']:>6.1f} us/instr") | ||
| 289 | print(f"\nsynthetic ({arguments.size} instructions):") | ||
| 290 | for row in synthetic_programs: | ||
| 291 | reference = baseline.get(row["name"] + "_us_per_instruction") | ||
| 292 | compared = (f"({measured[row['name'] + '_us_per_instruction'] / reference:.2f}x the {baseline_source} baseline)" | ||
| 293 | if reference else "(no baseline for this measurement)") | ||
| 294 | print(f" {row['name']:<28} {row['instructions']:>5} instr {row['seconds'] * 1e3:>8.2f} ms " | ||
| 295 | f"{row['us_per_instruction']:>6.1f} us/instr {compared}") | ||
| 296 | if skipped: | ||
| 297 | print("\nskipped (need the FSSM header, which these runs do not pass):") | ||
| 298 | for line in skipped: | ||
| 299 | print(" " + line) | ||
| 300 | |||
| 301 | if slow: | ||
| 302 | for name, factor in sorted(slow.items()): | ||
| 303 | print(f"slower than baseline ({baseline_source}) by {factor:.2f}x: {name}", file=sys.stderr) | ||
| 304 | return 1 | ||
| 305 | return 0 | ||
| 306 | |||
| 307 | |||
| 308 | if __name__ == "__main__": | ||
| 309 | sys.exit(main()) | ||
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py index 57253cb57..3a566ebfd 100644 --- a/scripts/bench_wave64.py +++ b/scripts/bench_wave64.py | |||
| @@ -97,7 +97,8 @@ def main(): | |||
| 97 | ap = argparse.ArgumentParser() | 97 | ap = argparse.ArgumentParser() |
| 98 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), | 98 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), |
| 99 | help="CMake build directory or a configuration directory such as RelWithDebInfo") | 99 | help="CMake build directory or a configuration directory such as RelWithDebInfo") |
| 100 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc")) | 100 | # Empty means unset to build.py: mc_command() then finds llvm-mc on PATH or a versioned llvm-mc-<N>. |
| 101 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "")) | ||
| 101 | # Vulkan guarantees support for at least 65,535 groups along X in one dispatch. | 102 | # Vulkan guarantees support for at least 65,535 groups along X in one dispatch. |
| 102 | ap.add_argument("--groups", type=positive_int, default=65535) | 103 | ap.add_argument("--groups", type=positive_int, default=65535) |
| 103 | ap.add_argument("--reps", type=positive_int, default=30) | 104 | ap.add_argument("--reps", type=positive_int, default=30) |
diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 5dd8bd389..d386ba052 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" | 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 index e7de9e4d9..9442f5e08 100644 --- a/scripts/carve_all.ps1 +++ b/scripts/carve_all.ps1 | |||
| @@ -3,6 +3,14 @@ | |||
| 3 | param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) | 3 | param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) |
| 4 | $root = Split-Path $PSScriptRoot -Parent | 4 | $root = Split-Path $PSScriptRoot -Parent |
| 5 | $tool = Join-Path $root "tools\rpf9_carve.py" | 5 | $tool = Join-Path $root "tools\rpf9_carve.py" |
| 6 | if (-not (Test-Path -LiteralPath $Game -PathType Container)) { | ||
| 7 | throw "Game folder '$Game' does not exist or is not a directory." | ||
| 8 | } | ||
| 9 | $outFull = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Out)) | ||
| 10 | if (Test-Path -LiteralPath $outFull -PathType Leaf) { | ||
| 11 | throw "Output path '$Out' is a file, not a directory." | ||
| 12 | } | ||
| 13 | [System.IO.Directory]::CreateDirectory($outFull) | Out-Null | ||
| 6 | # -Game may be relative or end in a separator; archive names are cut from a separator-ended prefix. | 14 | # -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 | 15 | $Game = (Resolve-Path -LiteralPath $Game).ProviderPath |
| 8 | # Resolve-Path preserves 8.3 short components (e.g. RUNNER~1), while Get-ChildItem emits canonical | 16 | # Resolve-Path preserves 8.3 short components (e.g. RUNNER~1), while Get-ChildItem emits canonical |
| @@ -11,14 +19,14 @@ $Game = (Resolve-Path -LiteralPath $Game).ProviderPath | |||
| 11 | $prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\' | 19 | $prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\' |
| 12 | $destinations = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::OrdinalIgnoreCase) | 20 | $destinations = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::OrdinalIgnoreCase) |
| 13 | # Validate every destination before accepting any cached index or starting a carve. | 21 | # 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) { | 22 | $archives = foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -File -Filter *.rpf | Sort-Object Length) { |
| 15 | $rel = $f.FullName.Substring($prefix.Length) | 23 | $rel = $f.FullName.Substring($prefix.Length) |
| 16 | $name = [IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_")) | 24 | $name = [IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_")) |
| 17 | if ($destinations.ContainsKey($name)) { | 25 | if ($destinations.ContainsKey($name)) { |
| 18 | throw ("Archives '{0}' and '{1}' both map to '{2}'." -f $destinations[$name], $rel, $name) | 26 | throw ("Archives '{0}' and '{1}' both map to '{2}'." -f $destinations[$name], $rel, $name) |
| 19 | } | 27 | } |
| 20 | $destinations.Add($name, $rel) | 28 | $destinations.Add($name, $rel) |
| 21 | [pscustomobject]@{ file = $f; relative = $rel; destination = Join-Path $Out $name } | 29 | [pscustomobject]@{ file = $f; relative = $rel; destination = Join-Path $outFull $name } |
| 22 | } | 30 | } |
| 23 | 31 | ||
| 24 | $rows = @() | 32 | $rows = @() |
| @@ -59,5 +67,15 @@ foreach ($archive in $archives) { | |||
| 59 | readable = [math]::Round($s.compressed_bytes / $denominator, 4) | 67 | readable = [math]::Round($s.compressed_bytes / $denominator, 4) |
| 60 | unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes } | 68 | unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes } |
| 61 | } | 69 | } |
| 62 | $rows | ConvertTo-Json | Set-Content -Encoding utf8 -LiteralPath (Join-Path $Out "coverage.json") | 70 | $coverageJson = if ($rows.Count -eq 0) { "[]" } else { $rows | ConvertTo-Json } |
| 63 | $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 | 71 | $coveragePath = Join-Path $outFull "coverage.json" |
| 72 | $tmpCoverage = Join-Path $outFull (".coverage.{0}.{1}.tmp" -f $PID, [guid]::NewGuid().ToString("N")) | ||
| 73 | try { | ||
| 74 | [System.IO.File]::WriteAllText($tmpCoverage, $coverageJson + "`n", [System.Text.UTF8Encoding]::new($false)) | ||
| 75 | Move-Item -LiteralPath $tmpCoverage -Destination $coveragePath -Force | ||
| 76 | } finally { | ||
| 77 | if (Test-Path -LiteralPath $tmpCoverage) { Remove-Item -LiteralPath $tmpCoverage -Force -ErrorAction SilentlyContinue } | ||
| 78 | } | ||
| 79 | if ($rows.Count -gt 0) { | ||
| 80 | $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 | ||
| 81 | } | ||
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..4ea23f84c --- /dev/null +++ b/scripts/check_compute_journal_overlay.py | |||
| @@ -0,0 +1,111 @@ | |||
| 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 | out = {} | ||
| 29 | for p in d.iterdir(): | ||
| 30 | require(re.fullmatch(r"cs-[0-9a-f]{16}\.bin", p.name) and p.is_file() and | ||
| 31 | 32 < p.stat().st_size <= 8 << 20, "unexpected file in one-PSO journal") | ||
| 32 | out[p.name] = (hashlib.sha256(p.read_bytes()).digest(), p.stat().st_mtime_ns) | ||
| 33 | return out | ||
| 34 | |||
| 35 | |||
| 36 | def run(exe, root, device, strict): | ||
| 37 | seed = root / "cold" | ||
| 38 | before = None | ||
| 39 | results = {} | ||
| 40 | adapter = None | ||
| 41 | for label, second in (("cold", False), ("external-A", False), | ||
| 42 | ("new-B", True), ("local-B", True)): | ||
| 43 | cache = root / label | ||
| 44 | cache.mkdir() | ||
| 45 | if label == "local-B": | ||
| 46 | # Bring only B into a fresh process; no session or shared cache crosses this boundary. | ||
| 47 | (cache / "pipeline_cache.d").mkdir() | ||
| 48 | src, = (root / "new-B" / "pipeline_cache.d").iterdir() | ||
| 49 | shutil.copy2(src, cache / "pipeline_cache.d" / src.name) | ||
| 50 | local_before = entries(cache) | ||
| 51 | env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")} | ||
| 52 | env.update(LEONIDA_PIPELINE_CACHE_DIR=str(cache), LEONIDA_TRACE_PIPELINE_COMPILE="1", | ||
| 53 | LEONIDA_PIPELINE_CACHE_BYTES=str(8 << 20), LEONIDA_PIPELINE_JOURNAL_BYTES=str(8 << 20), | ||
| 54 | LEONIDA_PIPELINE_JOURNAL="1") | ||
| 55 | if device: | ||
| 56 | env["LEONIDA_VK_DEVICE"] = device | ||
| 57 | if label != "cold": | ||
| 58 | env["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = str(seed / "pipeline_cache.d") | ||
| 59 | p = subprocess.run([str(exe)] + (["--second-shader"] if second else []), | ||
| 60 | stdin=subprocess.DEVNULL, capture_output=True, text=True, errors="replace", | ||
| 61 | cwd=cache, env=env, timeout=60) | ||
| 62 | if p.returncode == 77: | ||
| 63 | print("SKIP: the authored compute fixture is unsupported on this device") | ||
| 64 | return 77 | ||
| 65 | expected = 14 if second else 10 | ||
| 66 | require(p.returncode == 0 and | ||
| 67 | f"compute journal: direct Dispatch(4,1,1) copied both expected words (4,{expected})" | ||
| 68 | in p.stdout.splitlines(), f"{label}: GPU readback did not match") | ||
| 69 | devices = [x.removeprefix("device: ") for x in p.stdout.splitlines() if x.startswith("device: ")] | ||
| 70 | require(len(devices) == 1 and (adapter is None or adapter == devices[0]), "inconsistent GPU selection") | ||
| 71 | adapter = devices[0] | ||
| 72 | calls = [x for x in p.stderr.splitlines() if x.startswith("[rt] pipeline-compile trigger=")] | ||
| 73 | require(len(calls) == 1, f"{label}: expected one compute creation") | ||
| 74 | m = re.search(r" hit=(-1|0|1) bytes=\d+ variant=\d+ result=0 ", calls[0]) | ||
| 75 | require(m is not None, f"{label}: missing feedback field or unsuccessful create") | ||
| 76 | hit = int(m[1]) | ||
| 77 | local = entries(cache) | ||
| 78 | if label == "cold": | ||
| 79 | require(len(local) == 1, "cold A was not journaled") | ||
| 80 | source, = (seed / "pipeline_cache.d").iterdir() | ||
| 81 | # Make an erroneous hourly LRU touch observable without making the probe depend on system time. | ||
| 82 | old = time.time_ns() - 48 * 3600 * 10**9 | ||
| 83 | os.utime(source, ns=(old, old)) | ||
| 84 | before = entries(seed) | ||
| 85 | elif label == "new-B": | ||
| 86 | require(len(local) == 1 and not (local.keys() & before.keys()), "missing distinct local B") | ||
| 87 | else: | ||
| 88 | if strict: | ||
| 89 | require(hit == 1, f"{label}: driver reported no application-cache hit") | ||
| 90 | if hit == 1: | ||
| 91 | require(local == local_before, f"{label}: cache hit changed disposable journal") | ||
| 92 | require(entries(seed) == before, f"{label}: seed contents or last-write time changed") | ||
| 93 | results[label] = {"readback": [4, expected], "driver_hit": hit, "local_entries": len(local)} | ||
| 94 | print(json.dumps({"device": adapter, "runs": results}, sort_keys=True)) | ||
| 95 | return 0 | ||
| 96 | |||
| 97 | |||
| 98 | if __name__ == "__main__": | ||
| 99 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 100 | sys.stdout.reconfigure(errors="replace") | ||
| 101 | except (AttributeError, ValueError, OSError): | ||
| 102 | pass | ||
| 103 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 104 | parser.add_argument("executable", type=Path, help="built d3d12_compute_journal_test.exe") | ||
| 105 | parser.add_argument("--device", help="optional LEONIDA_VK_DEVICE selector") | ||
| 106 | parser.add_argument("--require-hit", action="store_true") | ||
| 107 | args = parser.parse_args() | ||
| 108 | exe = args.executable.resolve(strict=True) | ||
| 109 | require(exe.name.lower() == "d3d12_compute_journal_test.exe", "expected the compute test, not the game") | ||
| 110 | with tempfile.TemporaryDirectory(prefix="leonida-authored-journal-") as tmp: | ||
| 111 | raise SystemExit(run(exe, Path(tmp), args.device, args.require_hit)) | ||
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py index ae3d06e77..92097253c 100644 --- a/scripts/check_no_game_data.py +++ b/scripts/check_no_game_data.py | |||
| @@ -3,6 +3,10 @@ | |||
| 3 | python3 -I scripts/check_no_game_data.py # every file `git ls-files` lists | 3 | python3 -I scripts/check_no_game_data.py # every file `git ls-files` lists |
| 4 | python3 -I scripts/check_no_game_data.py PATH... # only these files | 4 | python3 -I scripts/check_no_game_data.py PATH... # only these files |
| 5 | 5 | ||
| 6 | Explicit PATH inputs must be regular files, not directories or symlinks. A missing, unreadable or non-regular | ||
| 7 | explicit input is reported on stderr and causes exit 2 unless another input matches game data (exit 1). | ||
| 8 | Default git enumeration still skips symlinks, submodules and files deleted from the working tree. | ||
| 9 | |||
| 6 | The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable | 10 | The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable |
| 7 | as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the | 11 | as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the |
| 8 | files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader | 12 | files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader |
| @@ -14,8 +18,8 @@ notes). Text formats (disassembly, .obj, .spvasm) | |||
| 14 | have no magic and stay with the extension check. | 18 | have no magic and stay with the extension check. |
| 15 | 19 | ||
| 16 | A compressed file hides those magics from both checks, so the script looks inside what the standard library opens: | 20 | A compressed file hides those magics from both checks, so the script looks inside what the standard library opens: |
| 17 | each member of a zip (found by its central directory too, so with bytes in front of it) or a tar, and the stream of | 21 | each member of a zip (found by its central directory too, so with bytes in front of it) or a tar (including V7), and |
| 18 | a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory | 22 | the stream of a gzip, bzip2 or xz file, nested up to three levels, is matched the same way. What's inside is read into memory |
| 19 | under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long. | 23 | under a budget per checked file (64 MiB expanded, 10,000 members), so a zip bomb can't make the check run long. |
| 20 | 7-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are | 24 | 7-Zip, Zstandard and RAR files, which it can't open, archives that fail to open and archives over the budget are |
| 21 | reported as archives that can't be checked. | 25 | reported as archives that can't be checked. |
| @@ -25,10 +29,12 @@ exits 1 if there is any. It exits 2 when a file cannot be read or git cannot lis | |||
| 25 | repository, or git not installed). Standard library only, no game files. | 29 | repository, or git not installed). Standard library only, no game files. |
| 26 | """ | 30 | """ |
| 27 | import bz2 | 31 | import bz2 |
| 32 | import errno | ||
| 28 | import gzip | 33 | import gzip |
| 29 | import io | 34 | import io |
| 30 | import lzma | 35 | import lzma |
| 31 | import os | 36 | import os |
| 37 | import stat | ||
| 32 | import subprocess | 38 | import subprocess |
| 33 | import sys | 39 | import sys |
| 34 | import tarfile | 40 | import tarfile |
| @@ -184,6 +190,13 @@ def archive_kind(f, head): | |||
| 184 | return stream[0] | 190 | return stream[0] |
| 185 | if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]: | 191 | if head[TAR_MAGIC[0]:TAR_MAGIC[0] + len(TAR_MAGIC[1])] == TAR_MAGIC[1]: |
| 186 | return "tar archive" | 192 | return "tar archive" |
| 193 | # V7 tar has no ustar marker. Validate only its first header here; member reads still use the shared budget. | ||
| 194 | try: | ||
| 195 | tarfile.TarInfo.frombuf(head[:tarfile.BLOCKSIZE], tarfile.ENCODING, "surrogateescape") | ||
| 196 | except tarfile.HeaderError: | ||
| 197 | pass | ||
| 198 | else: | ||
| 199 | return "tar archive" | ||
| 187 | # is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting | 200 | # is_zipfile finds the end-of-central-directory record, so a zip with bytes in front of it (a self-extracting |
| 188 | # archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it. | 201 | # archive, a spanned zip starting PK\x07\x08) is found as zipfile itself would open it. |
| 189 | if head.startswith(ZIP) or zipfile.is_zipfile(f): | 202 | if head.startswith(ZIP) or zipfile.is_zipfile(f): |
| @@ -267,15 +280,19 @@ def git_error(e): | |||
| 267 | return e.strerror or str(e) | 280 | return e.strerror or str(e) |
| 268 | 281 | ||
| 269 | 282 | ||
| 270 | def check(paths, unreadable=None): | 283 | def check(paths, unreadable=None, *, explicit=False): |
| 271 | """[(path, format)] for every regular file in `paths` that starts like game data. | 284 | """[(path, format)] for every regular file in `paths` that starts like game data. |
| 272 | 285 | ||
| 273 | A file that exists but cannot be opened or read is appended to `unreadable` (when given) as (path, error).""" | 286 | Files that cannot be opened or read are appended to `unreadable` (when given) as (path, error). |
| 287 | Explicit inputs also report missing paths and non-regular entries instead of silently skipping them.""" | ||
| 274 | found = [] | 288 | found = [] |
| 275 | for path in paths: | 289 | for path in paths: |
| 276 | if os.path.islink(path) or not os.path.isfile(path): | ||
| 277 | continue # submodules, symlinks, files deleted in the working tree | ||
| 278 | try: | 290 | try: |
| 291 | if explicit: | ||
| 292 | if not stat.S_ISREG(os.lstat(path).st_mode): | ||
| 293 | raise OSError(errno.EINVAL, "not a regular file", path) | ||
| 294 | elif os.path.islink(path) or not os.path.isfile(path): | ||
| 295 | continue # submodules, symlinks, files deleted in the working tree | ||
| 279 | name = classify_file(path) | 296 | name = classify_file(path) |
| 280 | except OSError as e: | 297 | except OSError as e: |
| 281 | if unreadable is not None: | 298 | if unreadable is not None: |
| @@ -304,7 +321,7 @@ def main(argv): | |||
| 304 | print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr) | 321 | print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr) |
| 305 | return 2 # not 1: that is the 'game data found' code | 322 | return 2 # not 1: that is the 'game data found' code |
| 306 | unreadable = [] | 323 | unreadable = [] |
| 307 | found = check(paths, unreadable) | 324 | found = check(paths, unreadable, explicit=bool(argv)) |
| 308 | for path, name in found: | 325 | for path, name in found: |
| 309 | print(f"{display(path)}: {name}") | 326 | print(f"{display(path)}: {name}") |
| 310 | for path, e in unreadable: | 327 | for path, e in unreadable: |
diff --git a/scripts/ci_expected_failures.py b/scripts/ci_expected_failures.py index f398020f7..866706ddd 100644 --- a/scripts/ci_expected_failures.py +++ b/scripts/ci_expected_failures.py | |||
| @@ -24,12 +24,13 @@ def judge(failed: list[str], status: int, expected: list[str]) -> tuple[int, lis | |||
| 24 | return 1, lines | 24 | return 1, lines |
| 25 | if status != 0 and not failed: | 25 | if status != 0 and not failed: |
| 26 | lines.append(f"::error::the test runner exited with {status} without naming a failed test") | 26 | lines.append(f"::error::the test runner exited with {status} without naming a failed test") |
| 27 | return 1, lines | ||
| 27 | for name in expected: | 28 | for name in expected: |
| 28 | if name in failed: | 29 | if name in failed: |
| 29 | lines.append(f"::warning::{name} failed, as expected until its fix is merged") | 30 | lines.append(f"::warning::{name} failed, as expected until its fix is merged") |
| 30 | else: | 31 | else: |
| 31 | lines.append(f"::notice::{name} passed: drop it from the expected failures") | 32 | lines.append(f"::notice::{name} passed: drop it from the expected failures") |
| 32 | return (1 if unexpected or (status != 0 and not failed) else 0), lines | 33 | return (1 if unexpected else 0), lines |
| 33 | 34 | ||
| 34 | 35 | ||
| 35 | def main(argv: list[str]) -> int: | 36 | def main(argv: list[str]) -> int: |
diff --git a/scripts/compute_workers_win.py b/scripts/compute_workers_win.py new file mode 100644 index 000000000..1ab6915ca --- /dev/null +++ b/scripts/compute_workers_win.py | |||
| @@ -0,0 +1,194 @@ | |||
| 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 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 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 | @contextlib.contextmanager | ||
| 123 | def start(request, mib, lock): | ||
| 124 | with job(mib, True) as h: | ||
| 125 | si = subprocess.STARTUPINFO(lpAttributeList={"handle_list": [lock]}) | ||
| 126 | os.set_handle_inheritable(lock, True) | ||
| 127 | try: | ||
| 128 | p = subprocess.Popen([sys.executable, "-I", "-B", str(Path(__file__).resolve()), "--shard"], | ||
| 129 | stdin=subprocess.PIPE, startupinfo=si, close_fds=True, creationflags=LOW) | ||
| 130 | finally: | ||
| 131 | os.set_handle_inheritable(lock, False) | ||
| 132 | attached = False | ||
| 133 | try: | ||
| 134 | check(assign(h, int(p._handle))) | ||
| 135 | attached = True | ||
| 136 | verify(h, int(p._handle), mib, True) | ||
| 137 | # A single framed gate. EOF, even after a short write, is not permission to start. | ||
| 138 | gate = (json.dumps([str(request), mib, lock])+"\n").encode("ascii") | ||
| 139 | if len(gate)>65536: | ||
| 140 | raise ValueError("compute worker gate too large") | ||
| 141 | p.stdin.write(gate) | ||
| 142 | p.stdin.close() | ||
| 143 | yield p | ||
| 144 | finally: | ||
| 145 | try: | ||
| 146 | if attached: | ||
| 147 | drain(h) # also stop/wait for a descendant if the Python worker died early | ||
| 148 | elif p.poll() is None: | ||
| 149 | p.kill() # gated bootstrap, no descendant or input path | ||
| 150 | finally: | ||
| 151 | try: | ||
| 152 | if not p.stdin.closed: | ||
| 153 | p.stdin.close() | ||
| 154 | finally: | ||
| 155 | p.wait(timeout=10) | ||
| 156 | |||
| 157 | |||
| 158 | def run(requests, mib, lock): | ||
| 159 | with contextlib.ExitStack() as stack: | ||
| 160 | procs = [stack.enter_context(start(p, mib, lock)) for p in requests] | ||
| 161 | while True: | ||
| 162 | codes = [p.poll() for p in procs] | ||
| 163 | if any(rc not in (None, 0) for rc in codes): | ||
| 164 | raise RuntimeError(f"Windows translation worker failed: {codes}") | ||
| 165 | if all(rc == 0 for rc in codes): | ||
| 166 | return | ||
| 167 | time.sleep(.05) | ||
| 168 | |||
| 169 | |||
| 170 | def child(): | ||
| 171 | line = sys.stdin.buffer.readline(65537) | ||
| 172 | if not line.endswith(b"\n") or len(line)>65536: | ||
| 173 | raise ValueError("no complete Windows compute gate") | ||
| 174 | request, mib, lock = json.loads(line) | ||
| 175 | # NULL queries this worker's immediate job. No job handle in a worker can keep it alive after | ||
| 176 | # coordinator death. No library/source inputs touched before membership and effective limits. | ||
| 177 | verify(None, current(), mib, True) | ||
| 178 | os.set_handle_inheritable(lock, False) | ||
| 179 | try: | ||
| 180 | sys.path.insert(0, str(Path(__file__).resolve().parent)) | ||
| 181 | from translate_pipeline_compute import run_request | ||
| 182 | run_request(Path(request)) | ||
| 183 | finally: | ||
| 184 | check(close(lock)) | ||
| 185 | |||
| 186 | |||
| 187 | if __name__ == "__main__": | ||
| 188 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 189 | sys.stdout.reconfigure(errors="replace") | ||
| 190 | except (AttributeError, ValueError, OSError): | ||
| 191 | pass | ||
| 192 | if sys.argv[1:] != ["--shard"]: | ||
| 193 | raise SystemExit(2) | ||
| 194 | child() | ||
diff --git a/scripts/corpus_watch.py b/scripts/corpus_watch.py new file mode 100644 index 000000000..a09bf8ab9 --- /dev/null +++ b/scripts/corpus_watch.py | |||
| @@ -0,0 +1,199 @@ | |||
| 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 os | ||
| 22 | import shutil | ||
| 23 | import subprocess | ||
| 24 | import sys | ||
| 25 | import time | ||
| 26 | from datetime import datetime, timezone | ||
| 27 | |||
| 28 | # -I removes the script folder from sys.path, so add tools/ explicitly. | ||
| 29 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools")) | ||
| 30 | from report_paths import same_report_path # noqa: E402 | ||
| 31 | |||
| 32 | MIN_FREE = 40 * 1024**3 | ||
| 33 | |||
| 34 | |||
| 35 | def corpus_counts(work): | ||
| 36 | """Return counts-only dict, or None when the shader stage produced no indexes. | ||
| 37 | |||
| 38 | Mirrors tools/progress_dashboard.py: entries in dxbc/index.json are carved; | ||
| 39 | entries in spirv/index.json without an 'error' key passed spirv-val. | ||
| 40 | """ | ||
| 41 | dxbc = os.path.join(work, "shaders", "dxbc", "index.json") | ||
| 42 | spirv_path = os.path.join(work, "shaders", "spirv", "index.json") | ||
| 43 | if not os.path.isfile(dxbc): | ||
| 44 | old_dxbc = os.path.join(work, "dxbc", "index.json") | ||
| 45 | if not os.path.isfile(old_dxbc): | ||
| 46 | return None | ||
| 47 | dxbc = old_dxbc | ||
| 48 | spirv_path = os.path.join(work, "spirv", "index.json") | ||
| 49 | |||
| 50 | with open(dxbc, encoding="utf-8") as f: | ||
| 51 | carved = json.load(f) | ||
| 52 | entries = carved if isinstance(carved, list) else list(carved.values()) | ||
| 53 | |||
| 54 | per_stage = {} | ||
| 55 | validated = 0 | ||
| 56 | spirv_entries = 0 | ||
| 57 | if os.path.isfile(spirv_path): | ||
| 58 | with open(spirv_path, encoding="utf-8") as f: | ||
| 59 | spirv = json.load(f) | ||
| 60 | spirv_entries = len(spirv) | ||
| 61 | for meta in spirv.values(): | ||
| 62 | if isinstance(meta, dict) and "error" not in meta: | ||
| 63 | stage = meta.get("stage") or "unknown" | ||
| 64 | per_stage.setdefault(stage, [0, 0])[1] += 1 | ||
| 65 | validated += 1 | ||
| 66 | for entry in entries: | ||
| 67 | stage = (entry.get("stage") if isinstance(entry, dict) else None) or "unknown" | ||
| 68 | per_stage.setdefault(stage, [0, 0])[0] += 1 | ||
| 69 | |||
| 70 | return {"carved": len(entries), "spirv_entries": spirv_entries, | ||
| 71 | "validated": validated, "per_stage": per_stage} | ||
| 72 | |||
| 73 | |||
| 74 | def outputs_collide(work, report, results, log): | ||
| 75 | """Refuse an output that names an input or another output.""" | ||
| 76 | outputs = [p for p in (report, results, log) if p] | ||
| 77 | for i, first in enumerate(outputs): | ||
| 78 | for second in outputs[i + 1:]: | ||
| 79 | if same_report_path(first, second): | ||
| 80 | return True | ||
| 81 | for out in outputs: | ||
| 82 | if same_report_path(out, work): | ||
| 83 | return True | ||
| 84 | return False | ||
| 85 | |||
| 86 | |||
| 87 | def main(): | ||
| 88 | ap = argparse.ArgumentParser(description=__doc__) | ||
| 89 | ap.add_argument("--game", required=True, help="your package folder") | ||
| 90 | ap.add_argument("--work", required=True, help="work folder (outside the repo)") | ||
| 91 | ap.add_argument("--out", required=True, help="built port folder (outside the repo)") | ||
| 92 | ap.add_argument("--report", required=True, help="progress dashboard folder (outside the repo)") | ||
| 93 | ap.add_argument("--results", required=True, help="counts-only JSONL file") | ||
| 94 | ap.add_argument("--log", help="local diagnostic log (may contain paths; never publish)") | ||
| 95 | ap.add_argument("--stages", default="check,shaders") | ||
| 96 | ap.add_argument("--interval", type=float, metavar="HOURS", default=0) | ||
| 97 | ap.add_argument("--once", action="store_true") | ||
| 98 | ap.add_argument("--pull", action="store_true", help="git pull --ff-only before each run") | ||
| 99 | ap.add_argument("--github", action="store_true", help="also refresh dashboard PR/CI panels") | ||
| 100 | ap.add_argument("--jobs", type=int) | ||
| 101 | a = ap.parse_args() | ||
| 102 | if not a.once and a.interval <= 0: | ||
| 103 | ap.error("use --once or --interval HOURS") | ||
| 104 | |||
| 105 | repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 106 | log_path = a.log | ||
| 107 | |||
| 108 | def log(msg): | ||
| 109 | line = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {msg}" | ||
| 110 | print(line, flush=True) | ||
| 111 | if log_path: | ||
| 112 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: | ||
| 113 | f.write(line + "\n") | ||
| 114 | |||
| 115 | if outputs_collide(a.work, a.report, a.results, log_path): | ||
| 116 | ap.error("an output names the work folder or another output") | ||
| 117 | |||
| 118 | for tool in ("llvm-mc", "spirv-val", "git"): | ||
| 119 | if not shutil.which(tool): | ||
| 120 | ap.error(f"missing tool: {tool}") | ||
| 121 | if not os.path.isdir(a.game): | ||
| 122 | ap.error("game folder not found") | ||
| 123 | probe = subprocess.run( | ||
| 124 | ["llvm-mc", "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1013", | ||
| 125 | "-filetype=obj", "-o", os.devnull], | ||
| 126 | input="s_nop 0\n", text=True, capture_output=True) | ||
| 127 | if probe.returncode != 0: | ||
| 128 | ap.error("llvm-mc cannot assemble gfx1013 (AMDGPU target missing)") | ||
| 129 | |||
| 130 | def run(cmd, timeout): | ||
| 131 | return subprocess.run(cmd, cwd=repo, text=True, stdout=subprocess.PIPE, | ||
| 132 | stderr=subprocess.STDOUT, timeout=timeout) | ||
| 133 | |||
| 134 | def run_once(): | ||
| 135 | if a.pull: | ||
| 136 | r = run(["git", "pull", "--ff-only"], 300) | ||
| 137 | if r.returncode != 0: | ||
| 138 | log("git pull failed:\n" + r.stdout[-2000:]) | ||
| 139 | return 1 | ||
| 140 | sha = run(["git", "rev-parse", "HEAD"], 60).stdout.strip() | ||
| 141 | log(f"commit {sha}") | ||
| 142 | for folder in (a.work, a.out, a.report): | ||
| 143 | os.makedirs(folder, exist_ok=True) | ||
| 144 | cmd = [sys.executable, "-I", "make_game.py", "--game", a.game, | ||
| 145 | "--work", a.work, "--out", a.out, "--stages", a.stages] | ||
| 146 | if a.jobs: | ||
| 147 | cmd += ["--jobs", str(a.jobs)] | ||
| 148 | log("running make_game.py (paths omitted from the local log)") | ||
| 149 | r = run(cmd, 6 * 3600) | ||
| 150 | if log_path: | ||
| 151 | with open(log_path, "a", encoding="utf-8", newline="\n") as f: | ||
| 152 | f.write(r.stdout + "\n") | ||
| 153 | log(f"make_game.py exit {r.returncode}") | ||
| 154 | |||
| 155 | counts = corpus_counts(a.work) | ||
| 156 | record = {"time": datetime.now(timezone.utc).isoformat(), "commit": sha, | ||
| 157 | "make_game_exit": r.returncode, "counts": counts} | ||
| 158 | with open(a.results, "a", encoding="utf-8", newline="\n") as f: | ||
| 159 | f.write(json.dumps(record, sort_keys=True) + "\n") | ||
| 160 | |||
| 161 | dash = [sys.executable, "-I", "tools/progress_dashboard.py", | ||
| 162 | "--work", a.work, "--out", a.report, "--run-tests"] | ||
| 163 | if a.github: | ||
| 164 | dash.append("--github") | ||
| 165 | d = run(dash, 900) | ||
| 166 | log(f"dashboard exit {d.returncode}") | ||
| 167 | |||
| 168 | if counts: | ||
| 169 | log(f"COUNTS carved={counts['carved']} spirv={counts['spirv_entries']} " | ||
| 170 | f"validated={counts['validated']}") | ||
| 171 | for stage, (nc, nv) in sorted(counts["per_stage"].items()): | ||
| 172 | log(f" {stage}: {nv}/{nc} validated") | ||
| 173 | with open(a.results, encoding="utf-8") as f: | ||
| 174 | previous = [json.loads(x) for x in f if x.strip()] | ||
| 175 | if len(previous) >= 2: | ||
| 176 | before = previous[-2].get("counts") or {} | ||
| 177 | log(f"DELTA validated {before.get('validated')} -> {counts['validated']}, " | ||
| 178 | f"carved {before.get('carved')} -> {counts['carved']}") | ||
| 179 | if counts["validated"] < before.get("validated", 0): | ||
| 180 | log("REGRESSION: validated count decreased") | ||
| 181 | else: | ||
| 182 | log("no corpus indexes produced") | ||
| 183 | log(f"counts-only record: {a.results}") | ||
| 184 | return 0 | ||
| 185 | |||
| 186 | rc = run_once() | ||
| 187 | if a.once or a.interval <= 0: | ||
| 188 | return rc | ||
| 189 | while True: | ||
| 190 | time.sleep(a.interval * 3600) | ||
| 191 | run_once() | ||
| 192 | |||
| 193 | |||
| 194 | if __name__ == "__main__": | ||
| 195 | try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode | ||
| 196 | sys.stdout.reconfigure(errors="replace") | ||
| 197 | except (AttributeError, ValueError, OSError): | ||
| 198 | pass | ||
| 199 | 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..66d99f1ac --- /dev/null +++ b/scripts/export_old_pr_manifest.py | |||
| @@ -0,0 +1,123 @@ | |||
| 1 | """Write a portable, verifiable manifest of the original repository's surviving history (issue #563). | ||
| 2 | |||
| 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.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..f302d5701 100644 --- a/scripts/first_look.ps1 +++ b/scripts/first_look.ps1 | |||
| @@ -105,9 +105,19 @@ $dryRunExitCode = $LASTEXITCODE | |||
| 105 | $report = Get-Content -LiteralPath (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json | 105 | $report = Get-Content -LiteralPath (Join-Path $out "$([IO.Path]::GetFileName($Exe)).json") -Raw | ConvertFrom-Json |
| 106 | $todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } | 106 | $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 } | 107 | $lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } |
| 108 | # "unverified" only comes from a host that isn't Windows and has no Wine prefix (pe_inspect.py, classify_dll): most | ||
| 109 | # are system DLLs, but a console DLL the shims don't serve yet is among them, so they follow the list, marked. | ||
| 110 | $unverified = @($report.imports | Where-Object { $_.where -eq "unverified" } | Sort-Object { -$_.functions.Count }) | ||
| 111 | if ($unverified.Count -gt 0) { | ||
| 112 | $lines = @(foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count }) + | ||
| 113 | @(foreach ($t in $unverified) { "{0,-40} {1,5} system (unverified)" -f $t.dll, $t.functions.Count }) | ||
| 114 | } | ||
| 108 | Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines | 115 | Set-Content -LiteralPath (Join-Path $out "shim-todo.txt") -Value $lines |
| 109 | Write-Host "`n== Shim to-do (DLL, function count)" | 116 | Write-Host "`n== Shim to-do (DLL, function count)" |
| 110 | $lines | 117 | $lines |
| 118 | if ($unverified.Count -gt 0) { | ||
| 119 | Write-Warning "$($unverified.Count) DLLs could not be checked against system DLLs (no Wine prefix): set WINEPREFIX and run again" | ||
| 120 | } | ||
| 111 | $enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } | 121 | $enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } |
| 112 | if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } | 122 | if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } |
| 113 | Write-Host "`nReports: $out" | 123 | 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/play-d3d12.ps1 b/scripts/play-d3d12.ps1 new file mode 100644 index 000000000..6c6396fc2 --- /dev/null +++ b/scripts/play-d3d12.ps1 | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | # Starts the title on Leonida's D3D12 runtime (d3d12/, from trustno1-coder/VIctory-NVIDIA) on Windows. | ||
| 2 | # The Vulkan renderer stays scripts\play.ps1; Linux uses scripts\play-linux.sh (docs/linux.md). | ||
| 3 | # | ||
| 4 | # powershell -ExecutionPolicy Bypass -File scripts\play-d3d12.ps1 -Game <folder with game_scarlett_master.exe> | ||
| 5 | # | ||
| 6 | # By default the game runs as on an Xbox Series X, rendering 2560x1440 (render scale 2/3 of its 3840x2160 output) | ||
| 7 | # with its own temporal upscaler; -SeriesS runs the lighter Series S profile instead, where the game renders its own | ||
| 8 | # 720p picture and DLSS takes it to 1080p. -Resolution sets the rendered height (Series X: 1080 or 1440). DLSS and DLSS | ||
| 9 | # frame generation need a few of NVIDIA's own files that no repository may carry: d3d12\Get-NVIDIA-DLSS.cmd fetches | ||
| 10 | # them from NVIDIA's GitHub once (about 70 MB). Without them the picture is stretched to the screen instead. | ||
| 11 | # In the game: F1 = settings (frame generation, frame-rate cap, DLSS preset ...), F3 = the numbers panel. | ||
| 12 | # | ||
| 13 | # -SmoothMotion starts leonida_sm.exe, the copy NVIDIA's Smooth Motion profile is set for (scripts\smooth-motion.ps1 | ||
| 14 | # -State on sets it): the driver shows twice the frames the game renders (RTX 40 and 50). Not the | ||
| 15 | # default: the one start made that way on 2026-11-27 ended 2.4 s in with the title's own breakpoint | ||
| 16 | # (0x80000003 in its main loop), and the next start without it ran. Not looked into yet. | ||
| 17 | # -NoDlss the picture is stretched instead of going through DLSS | ||
| 18 | # -Dlss DLSS makes the output, on Series X too: quality (rendered at 1440 lines of the 2160), balanced | ||
| 19 | # (1296), performance (1080) or ultra (720). Leave -Resolution out with it. | ||
| 20 | # -FrameGen DLSS frame generation: 2 shows twice the frames rendered (up to 6 where the card does more). On | ||
| 21 | # Series X it needs the DLSS upscale and turns -Dlss quality on unless a mode is given. | ||
| 22 | # -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9, shown | ||
| 23 | # centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch). | ||
| 24 | # -Resolution the older path: the game renders at this height and the title's own upscaler does the rest | ||
| 25 | # -RayTracing the title's real ray tracing (slower; shaders build for minutes the first time) | ||
| 26 | # -Capture F9 in the game saves that frame and the pictures it drew | ||
| 27 | # -NoPrecompile start at once: by default every shader is translated and the pipelines earlier runs drew with are | ||
| 28 | # made before the title starts (minutes the first time, seconds after) | ||
| 29 | # -Log the runtime's log goes to a file under %LOCALAPPDATA%\Leonida\logs | ||
| 30 | # -DryRun prints the settings this start would run with and stops: nothing is built or started | ||
| 31 | # | ||
| 32 | # Builds d3d12/ when it is missing (d3d12\scripts\build-nvidia.ps1: the diag profile, with DLSS when NVIDIA's files | ||
| 33 | # are there), keeps the caches and saves under -Data, and hands everything else to d3d12\scripts\play-nvidia.ps1: | ||
| 34 | # -SeriesX, -Quality, -Adapter and -More pass through. Nothing goes online. | ||
| 35 | param( | ||
| 36 | [Parameter(Mandatory = $true)][string]$Game, | ||
| 37 | [string]$Data = (Join-Path $env:LOCALAPPDATA "Leonida\d3d12"), | ||
| 38 | [switch]$SeriesX, | ||
| 39 | [switch]$SeriesS, | ||
| 40 | [switch]$Quality, | ||
| 41 | [ValidateSet('', '2160', '1440', '1080', '720', '540', '480')][string]$Resolution = '', | ||
| 42 | [ValidateSet('', 'quality', 'balanced', 'performance', 'ultra')][string]$Dlss = '', | ||
| 43 | [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0, | ||
| 44 | [string]$Aspect = '', | ||
| 45 | [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '', | ||
| 46 | [string]$Adapter = '', | ||
| 47 | [hashtable]$More = @{}, | ||
| 48 | [switch]$Rebuild, | ||
| 49 | [switch]$SmoothMotion, | ||
| 50 | [switch]$NoSmoothMotion, | ||
| 51 | [switch]$NoDlss, | ||
| 52 | [switch]$RayTracing, | ||
| 53 | [switch]$Capture, | ||
| 54 | [switch]$NoPrecompile, | ||
| 55 | [switch]$Log, | ||
| 56 | [switch]$DryRun | ||
| 57 | ) | ||
| 58 | |||
| 59 | $ErrorActionPreference = "Stop" | ||
| 60 | $repo = Split-Path -Parent $PSScriptRoot | ||
| 61 | $runtime = Join-Path $repo "d3d12" | ||
| 62 | $exe = Join-Path $runtime "target\diag\leonida.exe" | ||
| 63 | $title = Join-Path $Game "game_scarlett_master.exe" | ||
| 64 | if (-not (Test-Path $title)) { throw "missing: $title" } | ||
| 65 | if (-not $DryRun -and ($Rebuild -or -not (Test-Path $exe))) { | ||
| 66 | & (Join-Path $runtime "scripts\build-nvidia.ps1") | ||
| 67 | if ($LASTEXITCODE -ne 0) { throw "cargo build failed ($LASTEXITCODE)" } | ||
| 68 | } | ||
| 69 | # A shader cache of its own: one filled before the renderer changed (cache\) does not fit its pipelines. | ||
| 70 | New-Item -ItemType Directory -Force (Join-Path $Data "cache-2"), (Join-Path $Data "data") | Out-Null | ||
| 71 | $env:LEONIDA_GAME_DIR = (Resolve-Path $Game).Path | ||
| 72 | $env:LEONIDA_CACHE_DIR = Join-Path $Data "cache-2" | ||
| 73 | $env:LEONIDA_DATA_DIR = Join-Path $Data "data" | ||
| 74 | |||
| 75 | # Leonida: Smooth Motion only with -SmoothMotion (it was the default for one start, which the title did not | ||
| 76 | # survive; -NoSmoothMotion is kept and means the same as leaving -SmoothMotion out). | ||
| 77 | $launch = @{ Exe = $title; Build = 'diag'; NoSmoothMotion = (-not $SmoothMotion); More = $More } | ||
| 78 | # Leonida: the Series X profile is the default (the user's call: 1080p-1440p as on the bigger consoles). | ||
| 79 | if (-not $SeriesS) { | ||
| 80 | $launch.SeriesX = $true | ||
| 81 | # 1440 lines and the title's own upscaler, unless DLSS (which frame generation brings with it) makes the output. | ||
| 82 | if (-not $Resolution -and -not $Dlss -and -not $FrameGen) { $Resolution = '1440' } | ||
| 83 | } | ||
| 84 | if ($Dlss) { $launch.Dlss = $Dlss } | ||
| 85 | if ($FrameGen) { $launch.FrameGen = $FrameGen } | ||
| 86 | if ($Aspect) { $launch.Aspect = $Aspect } | ||
| 87 | if ($PresentScale) { $launch.PresentScale = $PresentScale } | ||
| 88 | foreach ($switch in 'Quality', 'NoDlss', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun') { | ||
| 89 | if ($PSBoundParameters[$switch]) { $launch[$switch] = $true } | ||
| 90 | } | ||
| 91 | if ($Resolution) { $launch.Resolution = $Resolution } | ||
| 92 | if ($Adapter) { $launch.Adapter = $Adapter } | ||
| 93 | & (Join-Path $runtime "scripts\play-nvidia.ps1") @launch | ||
diff --git a/scripts/play-linux.sh b/scripts/play-linux.sh new file mode 100755 index 000000000..e7d48d78e --- /dev/null +++ b/scripts/play-linux.sh | |||
| @@ -0,0 +1,71 @@ | |||
| 1 | #!/bin/sh | ||
| 2 | # Starts Leonida's D3D12 runtime (d3d12/, a Windows program) on Linux under Wine, with the VKD3D-Proton that comes in | ||
| 3 | # the package (scripts/fetch_vkd3d_proton.py puts it in vkd3d-proton/ beside this script), so nothing else needs to be | ||
| 4 | # downloaded for Direct3D 12. Wine itself and a Vulkan driver (Mesa or NVIDIA's) are the system's. | ||
| 5 | # | ||
| 6 | # ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] | ||
| 7 | # | ||
| 8 | # Leonida keeps its own Wine prefix (LEONIDA_WINEPREFIX, default ~/.local/share/leonida/prefix): the bundled | ||
| 9 | # d3d12.dll and d3d12core.dll are installed there and preferred over Wine's (WINEDLLOVERRIDES), so no other prefix | ||
| 10 | # is changed. LEONIDA_* variables already set win over the defaults below. | ||
| 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..76b9f5139 --- /dev/null +++ b/scripts/play.ps1 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | # Starts the title on Leonida's Vulkan renderer with the settings that work today. | ||
| 2 | # | ||
| 3 | # powershell -ExecutionPolicy Bypass -File scripts\play.ps1 -Game <game folder> -Work <make_game work folder> | ||
| 4 | # | ||
| 5 | # Every setting is an environment variable the runtime reads (docs/port_status.md); one already set in the shell wins | ||
| 6 | # over the default here. Nothing is downloaded and nothing goes online. | ||
| 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 "victory\crates\victory-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/port_ctl.py b/scripts/port_ctl.py new file mode 100644 index 000000000..9a7e595d0 --- /dev/null +++ b/scripts/port_ctl.py | |||
| @@ -0,0 +1,320 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Drive a VIctory run of the title for testing: start, press, shot, fps, stop. | ||
| 3 | |||
| 4 | Everything the run writes (logs, frame captures, saves, caches) goes under a | ||
| 5 | work folder outside the repository (``--work``, default ``G:\\gta6port`` or | ||
| 6 | ``LEONIDA_PORT_WORK``). Nothing from the game is read or written here beyond | ||
| 7 | what the runtime itself does. | ||
| 8 | |||
| 9 | python -I scripts/port_ctl.py start --name run1 # launch the title | ||
| 10 | python -I scripts/port_ctl.py press Enter # tap A on the stand-in pad | ||
| 11 | python -I scripts/port_ctl.py press W 3000 # hold left stick up for 3 s | ||
| 12 | python -I scripts/port_ctl.py shot # save the next presented frame | ||
| 13 | python -I scripts/port_ctl.py fps # latest frame-rate lines | ||
| 14 | python -I scripts/port_ctl.py status # running?, fps, last warnings | ||
| 15 | python -I scripts/port_ctl.py stop # end the run | ||
| 16 | |||
| 17 | Keys (the stand-in pad's table): sticks W A S D / I J K L, triggers Z C, | ||
| 18 | buttons X Y Q E F H, Enter (A), Back (B), Esc (Menu), Tab (View), | ||
| 19 | Up Down Left Right (D-pad). The runtime reads the pad file only while no real | ||
| 20 | controller is connected. | ||
| 21 | """ | ||
| 22 | |||
| 23 | import argparse | ||
| 24 | import json | ||
| 25 | import os | ||
| 26 | import re | ||
| 27 | import subprocess | ||
| 28 | import sys | ||
| 29 | import time | ||
| 30 | |||
| 31 | REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 32 | VICTORY = os.path.join(REPO, "victory") | ||
| 33 | DEFAULT_WORK = os.environ.get("LEONIDA_PORT_WORK", r"G:\gta6port") | ||
| 34 | DEFAULT_GAME = os.environ.get("LEONIDA_GAME_DIR", os.path.expanduser(r"~\Documents\GTA6")) | ||
| 35 | TITLE_EXE = "game_scarlett_master.exe" | ||
| 36 | |||
| 37 | FPS_RE = re.compile(r"(\d+(?:\.\d+)?) fps, (\d+(?:\.\d+)?) ms/frame") | ||
| 38 | ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") | ||
| 39 | |||
| 40 | |||
| 41 | def read_log(log): | ||
| 42 | try: | ||
| 43 | with open(log, encoding="utf-8", errors="replace") as f: | ||
| 44 | return [ANSI_RE.sub("", ln) for ln in f] | ||
| 45 | except OSError: | ||
| 46 | return [] | ||
| 47 | |||
| 48 | |||
| 49 | def paths(work): | ||
| 50 | ctl = os.path.join(work, "ctl") | ||
| 51 | return { | ||
| 52 | "work": work, | ||
| 53 | "ctl": ctl, | ||
| 54 | "state": os.path.join(ctl, "state.json"), | ||
| 55 | "pad": os.path.join(ctl, "pad.txt"), | ||
| 56 | "shot": os.path.join(ctl, "shot.txt"), | ||
| 57 | "logs": os.path.join(work, "logs"), | ||
| 58 | "captures": os.path.join(work, "captures"), | ||
| 59 | "cache": os.path.join(work, "cache"), | ||
| 60 | "data": os.path.join(work, "data"), | ||
| 61 | } | ||
| 62 | |||
| 63 | |||
| 64 | def load_state(p): | ||
| 65 | try: | ||
| 66 | with open(p["state"], encoding="utf-8") as f: | ||
| 67 | return json.load(f) | ||
| 68 | except (OSError, ValueError): | ||
| 69 | return {} | ||
| 70 | |||
| 71 | |||
| 72 | def save_state(p, state): | ||
| 73 | os.makedirs(p["ctl"], exist_ok=True) | ||
| 74 | with open(p["state"], "w", encoding="utf-8", newline="\n") as f: | ||
| 75 | json.dump(state, f, indent=1) | ||
| 76 | |||
| 77 | |||
| 78 | def alive(pid): | ||
| 79 | if not pid: | ||
| 80 | return False | ||
| 81 | out = subprocess.run( | ||
| 82 | ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"], | ||
| 83 | stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, | ||
| 84 | ).stdout | ||
| 85 | return f'"{pid}"' in out | ||
| 86 | |||
| 87 | |||
| 88 | def write_atomic(path, text): | ||
| 89 | tmp = path + ".tmp" | ||
| 90 | with open(tmp, "w", encoding="utf-8", newline="\n") as f: | ||
| 91 | f.write(text) | ||
| 92 | os.replace(tmp, path) | ||
| 93 | |||
| 94 | |||
| 95 | def cmd_start(args, p): | ||
| 96 | state = load_state(p) | ||
| 97 | if alive(state.get("pid")): | ||
| 98 | print(f"a run is already going: pid {state['pid']} ({state.get('name')}); stop it first") | ||
| 99 | return 1 | ||
| 100 | exe = args.exe or os.path.join(VICTORY, "target", args.profile, "victory.exe") | ||
| 101 | if not os.path.isfile(exe): | ||
| 102 | print(f"no runtime at {exe}; build it first (cargo build --release -p victory --features diagnostics --bins)") | ||
| 103 | return 1 | ||
| 104 | title = os.path.join(args.game, TITLE_EXE) | ||
| 105 | if not os.path.isfile(title): | ||
| 106 | print(f"no title executable at {title}") | ||
| 107 | return 1 | ||
| 108 | name = args.name or time.strftime("run-%Y%m%d-%H%M%S") | ||
| 109 | for key in ("ctl", "logs", "captures", "cache", "data"): | ||
| 110 | os.makedirs(p[key], exist_ok=True) | ||
| 111 | captures = os.path.join(p["captures"], name) | ||
| 112 | os.makedirs(captures, exist_ok=True) | ||
| 113 | data = args.data or p["data"] | ||
| 114 | os.makedirs(data, exist_ok=True) | ||
| 115 | # Fresh command files: the runtime only acts on increasing numbers. | ||
| 116 | for f in (p["pad"], p["shot"]): | ||
| 117 | if os.path.exists(f): | ||
| 118 | os.remove(f) | ||
| 119 | env = dict(os.environ) | ||
| 120 | env.update({ | ||
| 121 | "VICTORY_GAME_DIR": args.game, | ||
| 122 | "VICTORY_CACHE_DIR": p["cache"], | ||
| 123 | "VICTORY_DATA_DIR": data, | ||
| 124 | "VICTORY_LOG": args.log, | ||
| 125 | "VICTORY_CAPTURE": captures, | ||
| 126 | "VICTORY_CAPTURE_REQUEST": p["shot"], | ||
| 127 | "VICTORY_MOVEMENT_FILE": p["pad"], | ||
| 128 | }) | ||
| 129 | if args.world: | ||
| 130 | env["VICTORY_CAPTURE_WORLD"] = "1" | ||
| 131 | for item in args.env or []: | ||
| 132 | k, _, v = item.partition("=") | ||
| 133 | env[k] = v | ||
| 134 | log = os.path.join(p["logs"], f"{name}.log") | ||
| 135 | cmd = [exe, "run", title, "--execute", "--console", args.console] | ||
| 136 | flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | ||
| 137 | # The runtime writes its own bytes here; newline only keeps the repository's line-ending rule. | ||
| 138 | with open(log, "w", encoding="utf-8", newline="\n") as out: | ||
| 139 | proc = subprocess.Popen(cmd, cwd=args.game, env=env, stdout=out, stderr=subprocess.STDOUT, | ||
| 140 | stdin=subprocess.DEVNULL, creationflags=flags) | ||
| 141 | state = { | ||
| 142 | "pid": proc.pid, "name": name, "log": log, "captures": captures, "started": time.time(), | ||
| 143 | "pad_seq": 0, "shot_seq": 0, "cmd": cmd, | ||
| 144 | "env": {k: v for k, v in env.items() if k.startswith("VICTORY_")}, | ||
| 145 | } | ||
| 146 | save_state(p, state) | ||
| 147 | print(f"started pid {proc.pid} as {name}\n log {log}\n captures {captures}") | ||
| 148 | return 0 | ||
| 149 | |||
| 150 | |||
| 151 | def cmd_press(args, p): | ||
| 152 | state = load_state(p) | ||
| 153 | seq = int(time.time() * 1000) | ||
| 154 | seq = max(seq, state.get("pad_seq", 0) + 1) | ||
| 155 | write_atomic(p["pad"], f"{seq} {args.key} {args.ms}") | ||
| 156 | state["pad_seq"] = seq | ||
| 157 | save_state(p, state) | ||
| 158 | print(f"pressed {args.key} for {args.ms} ms (sequence {seq})") | ||
| 159 | if args.wait: | ||
| 160 | time.sleep(args.ms / 1000.0 + 0.4) | ||
| 161 | return 0 | ||
| 162 | |||
| 163 | |||
| 164 | def newest_png(folder, since): | ||
| 165 | best = None | ||
| 166 | try: | ||
| 167 | for entry in os.scandir(folder): | ||
| 168 | if entry.name.endswith(".png") and entry.stat().st_mtime >= since: | ||
| 169 | if best is None or entry.stat().st_mtime > best.stat().st_mtime: | ||
| 170 | best = entry | ||
| 171 | except OSError: | ||
| 172 | return None | ||
| 173 | return best.path if best else None | ||
| 174 | |||
| 175 | |||
| 176 | def shrink(path, width): | ||
| 177 | """A copy of the capture `width` pixels wide beside it (needs Pillow); the capture itself otherwise.""" | ||
| 178 | try: | ||
| 179 | from PIL import Image | ||
| 180 | except ImportError: | ||
| 181 | return path | ||
| 182 | with Image.open(path) as im: | ||
| 183 | height = max(1, round(im.height * width / im.width)) | ||
| 184 | small = im.resize((width, height), Image.LANCZOS) | ||
| 185 | out = path[:-4] + f"-w{width}.png" | ||
| 186 | small.save(out) | ||
| 187 | return out | ||
| 188 | |||
| 189 | |||
| 190 | def cmd_shot(args, p): | ||
| 191 | state = load_state(p) | ||
| 192 | seq = state.get("shot_seq", 0) + 1 | ||
| 193 | since = time.time() - 0.5 | ||
| 194 | write_atomic(p["shot"], str(seq)) | ||
| 195 | state["shot_seq"] = seq | ||
| 196 | save_state(p, state) | ||
| 197 | folder = state.get("captures") | ||
| 198 | deadline = time.time() + args.timeout | ||
| 199 | while time.time() < deadline: | ||
| 200 | found = newest_png(folder, since) | ||
| 201 | if found: | ||
| 202 | time.sleep(0.5) # let the writer finish | ||
| 203 | if args.small: | ||
| 204 | found = shrink(found, args.small) | ||
| 205 | print(found) | ||
| 206 | return 0 | ||
| 207 | time.sleep(0.25) | ||
| 208 | print(f"no new frame in {folder} after {args.timeout} s (the title may not be presenting)") | ||
| 209 | return 1 | ||
| 210 | |||
| 211 | |||
| 212 | def fps_lines(log, count): | ||
| 213 | hits = [ln.rstrip() for ln in read_log(log) if FPS_RE.search(ln)] | ||
| 214 | return hits[-count:] | ||
| 215 | |||
| 216 | |||
| 217 | def summarize(line): | ||
| 218 | m = FPS_RE.search(line) | ||
| 219 | if not m: | ||
| 220 | return line | ||
| 221 | tail = line[m.start():] | ||
| 222 | keep = [] | ||
| 223 | for pattern in (r"\d+(?:\.\d+)? fps, \d+(?:\.\d+)? ms/frame", r"\(\S+ preparing", r"[\d.]+ on the GPU", | ||
| 224 | r"\d+ draws/frame", r"dropped \d+ without a host pipeline \(\d+ being made\)", | ||
| 225 | r"cpu [\d.]+% gpu \d+% busy ram \d+ MB"): | ||
| 226 | mm = re.search(pattern, tail) | ||
| 227 | if mm: | ||
| 228 | keep.append(mm.group(0)) | ||
| 229 | stamp = line[:m.start()].split(" ")[0] | ||
| 230 | return f"{stamp} " + " | ".join(keep) | ||
| 231 | |||
| 232 | |||
| 233 | def cmd_fps(args, p): | ||
| 234 | state = load_state(p) | ||
| 235 | log = args.log or state.get("log") | ||
| 236 | if not log: | ||
| 237 | print("no run recorded") | ||
| 238 | return 1 | ||
| 239 | for line in fps_lines(log, args.count): | ||
| 240 | print(line if args.full else summarize(line)) | ||
| 241 | return 0 | ||
| 242 | |||
| 243 | |||
| 244 | def cmd_status(args, p): | ||
| 245 | state = load_state(p) | ||
| 246 | if not state: | ||
| 247 | print("no run recorded") | ||
| 248 | return 1 | ||
| 249 | up = time.time() - state.get("started", time.time()) | ||
| 250 | print(f"{state.get('name')}: pid {state.get('pid')} {'running' if alive(state.get('pid')) else 'NOT running'}, " | ||
| 251 | f"up {int(up // 60)}:{int(up % 60):02d}") | ||
| 252 | for line in fps_lines(state["log"], 3): | ||
| 253 | print(" " + summarize(line)) | ||
| 254 | lines = read_log(state["log"]) | ||
| 255 | bad = [ln.rstrip() for ln in lines if re.search(r"\b(ERROR|WARN)\b|panicked|crash|DEVICE_HUNG|DEVICE_REMOVED", ln)] | ||
| 256 | for line in bad[-args.warnings:]: | ||
| 257 | print(" ! " + line[:300]) | ||
| 258 | return 0 | ||
| 259 | |||
| 260 | |||
| 261 | def cmd_stop(args, p): | ||
| 262 | state = load_state(p) | ||
| 263 | pid = state.get("pid") | ||
| 264 | if not alive(pid): | ||
| 265 | print("no run is going") | ||
| 266 | return 0 | ||
| 267 | subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | ||
| 268 | for _ in range(40): | ||
| 269 | if not alive(pid): | ||
| 270 | break | ||
| 271 | time.sleep(0.25) | ||
| 272 | print(f"stopped pid {pid} ({state.get('name')})") | ||
| 273 | return 0 | ||
| 274 | |||
| 275 | |||
| 276 | def main(): | ||
| 277 | ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 278 | ap.add_argument("--work", default=DEFAULT_WORK, help="work folder outside the repository") | ||
| 279 | sub = ap.add_subparsers(dest="command", required=True) | ||
| 280 | |||
| 281 | s = sub.add_parser("start", help="launch the title under VIctory") | ||
| 282 | s.add_argument("--name") | ||
| 283 | s.add_argument("--game", default=DEFAULT_GAME) | ||
| 284 | s.add_argument("--exe", help="runtime executable (default: victory/target/<profile>/victory.exe)") | ||
| 285 | s.add_argument("--profile", default="release") | ||
| 286 | s.add_argument("--console", default="series-x", choices=["series-x", "series-s"]) | ||
| 287 | s.add_argument("--log", default="info", help="VICTORY_LOG filter") | ||
| 288 | s.add_argument("--data", help="data folder (saves); default <work>/data") | ||
| 289 | s.add_argument("--world", action="store_true", help="also capture world frames (VICTORY_CAPTURE_WORLD)") | ||
| 290 | s.add_argument("--env", action="append", help="extra K=V for the run (repeatable)") | ||
| 291 | |||
| 292 | s = sub.add_parser("press", help="press a stand-in pad key") | ||
| 293 | s.add_argument("key") | ||
| 294 | s.add_argument("ms", nargs="?", type=int, default=200) | ||
| 295 | s.add_argument("--wait", action="store_true", help="return after the hold ends") | ||
| 296 | |||
| 297 | s = sub.add_parser("shot", help="save the next presented frame and print its path") | ||
| 298 | s.add_argument("--timeout", type=float, default=30.0) | ||
| 299 | s.add_argument("--small", type=int, default=0, metavar="WIDTH", | ||
| 300 | help="also write a copy this many pixels wide and print its path (needs Pillow)") | ||
| 301 | |||
| 302 | s = sub.add_parser("fps", help="latest frame-rate lines of the run's log") | ||
| 303 | s.add_argument("--count", type=int, default=5) | ||
| 304 | s.add_argument("--log") | ||
| 305 | s.add_argument("--full", action="store_true") | ||
| 306 | |||
| 307 | s = sub.add_parser("status", help="whether the run is going, its fps and last warnings") | ||
| 308 | s.add_argument("--warnings", type=int, default=5) | ||
| 309 | |||
| 310 | sub.add_parser("stop", help="end the run") | ||
| 311 | |||
| 312 | args = ap.parse_args() | ||
| 313 | p = paths(args.work) | ||
| 314 | return {"start": cmd_start, "press": cmd_press, "shot": cmd_shot, "fps": cmd_fps, | ||
| 315 | "status": cmd_status, "stop": cmd_stop}[args.command](args, p) | ||
| 316 | |||
| 317 | |||
| 318 | if __name__ == "__main__": | ||
| 319 | sys.stdout.reconfigure(errors="replace") | ||
| 320 | sys.exit(main()) | ||
diff --git a/scripts/run_address_guard_gpu_test.py b/scripts/run_address_guard_gpu_test.py 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..9d8f19a37 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,17 @@ 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 | dev_lc=${DEVICE,,} |
| 224 | [ "$(cat "$n/device/vendor" 2>/dev/null):$(cat "$n/device/device" 2>/dev/null)" = "0x${DEVICE%%:*}:0x${DEVICE#*:}" ] \ | 232 | for n in "$DRM_SYSFS"/renderD*; do |
| 233 | [ -e "$n" ] || continue | ||
| 234 | ven=$(cat "$n/device/vendor" 2>/dev/null || true) | ||
| 235 | did=$(cat "$n/device/device" 2>/dev/null || true) | ||
| 236 | ven=${ven//$'\r'/}; did=${did//$'\r'/} | ||
| 237 | [ "${ven,,}:${did,,}" = "0x${dev_lc%%:*}:0x${dev_lc#*:}" ] \ | ||
| 225 | && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} | 238 | && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} |
| 226 | done | 239 | done |
| 227 | else | 240 | else |
| @@ -242,8 +255,9 @@ else | |||
| 242 | fi | 255 | fi |
| 243 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" | 256 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" |
| 244 | 257 | ||
| 245 | WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver | 258 | wine_bin=$(command -v "$WINE" 2>/dev/null || true) |
| 246 | [ -x "$WINESERVER" ] || WINESERVER=wineserver | 259 | WINESERVER=${wine_bin:+$(dirname "$wine_bin")/wineserver} |
| 260 | [ -n "$WINESERVER" ] && [ -x "$WINESERVER" ] || WINESERVER=wineserver | ||
| 247 | SESSION_PID= | 261 | SESSION_PID= |
| 248 | teardown() { | 262 | teardown() { |
| 249 | "$WINESERVER" -k 2>/dev/null | 263 | "$WINESERVER" -k 2>/dev/null |
| @@ -257,7 +271,7 @@ trap 'exit 130' INT TERM HUP | |||
| 257 | 271 | ||
| 258 | # The session command with its arguments baked in (kwin takes one program path). | 272 | # The session command with its arguments baked in (kwin takes one program path). |
| 259 | { | 273 | { |
| 260 | echo '#!/bin/sh' | 274 | echo '#!/usr/bin/env bash' |
| 261 | printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" | 275 | printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" |
| 262 | for a in "$@"; do printf ' %q' "$a"; done | 276 | for a in "$@"; do printf ' %q' "$a"; done |
| 263 | echo | 277 | echo |
| @@ -276,10 +290,17 @@ else | |||
| 276 | fi | 290 | fi |
| 277 | SESSION_PID=$! | 291 | SESSION_PID=$! |
| 278 | # The session ends when the inner run returns; this outer limit adds a margin for the start-up. | 292 | # 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 & | 293 | ( trap 'kill "${watch_sleep_pid:-}" 2>/dev/null || true; exit 0' TERM INT |
| 294 | watch_sleep_pid="" | ||
| 295 | sleep $((LIMIT + 180)) & | ||
| 296 | watch_sleep_pid=$! | ||
| 297 | wait "$watch_sleep_pid" 2>/dev/null || exit 0 | ||
| 298 | kill -TERM "$SESSION_PID" 2>/dev/null ) 9>&- </dev/null >/dev/null 2>&1 & | ||
| 280 | WATCH=$! | 299 | WATCH=$! |
| 281 | wait "$SESSION_PID" | 300 | wait "$SESSION_PID" |
| 282 | pkill -P "$WATCH" 2>/dev/null; kill "$WATCH" 2>/dev/null | 301 | pkill -P "$WATCH" 2>/dev/null || true |
| 302 | kill "$WATCH" 2>/dev/null || true | ||
| 303 | wait "$WATCH" 2>/dev/null || true | ||
| 283 | teardown; SESSION_PID= | 304 | teardown; SESSION_PID= |
| 284 | T1=$(date +%s) | 305 | T1=$(date +%s) |
| 285 | 306 | ||
| @@ -289,5 +310,6 @@ if [ ! -f "$RUN/exit_code" ]; then | |||
| 289 | exit 3 | 310 | exit 3 |
| 290 | fi | 311 | fi |
| 291 | python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" | 312 | python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" |
| 313 | summary_rc=${PIPESTATUS[0]} | ||
| 292 | echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." | 314 | echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." |
| 293 | exit 0 | 315 | exit "$summary_rc" |
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index a9d18b6ea..1b1c9d492 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py | |||
| @@ -29,7 +29,7 @@ from check import (Skip, clip_test, fmt_1010102_test, fmt_d16_xyz_test, fmt_int_ | |||
| 29 | fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported) | 29 | fmt_sint32_test, fmt_xy_xyz_test, tbuffer_store_test, compute_unsupported) |
| 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() |
| @@ -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 |
| @@ -365,7 +380,9 @@ def _device_per_vertex(): | |||
| 365 | try: | 380 | try: |
| 366 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | 381 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], |
| 367 | capture_output=True, text=True, timeout=60) | 382 | capture_output=True, text=True, timeout=60) |
| 368 | answer = json.loads(r.stdout.strip().splitlines()[-1]).get("per_vertex_inputs") | 383 | report = json.loads(r.stdout.strip().splitlines()[-1]) |
| 384 | if isinstance(report, dict): | ||
| 385 | answer = report.get("per_vertex_inputs") | ||
| 369 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | 386 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): |
| 370 | pass | 387 | pass |
| 371 | _PER_VERTEX.append(answer) | 388 | _PER_VERTEX.append(answer) |
| @@ -380,7 +397,9 @@ def _device_barycentric_fallback(): | |||
| 380 | try: | 397 | try: |
| 381 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], | 398 | r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "vk_subgroup_info.py")], |
| 382 | capture_output=True, text=True, timeout=60) | 399 | capture_output=True, text=True, timeout=60) |
| 383 | answer = json.loads(r.stdout.strip().splitlines()[-1]).get("barycentric_fallback") | 400 | report = json.loads(r.stdout.strip().splitlines()[-1]) |
| 401 | if isinstance(report, dict): | ||
| 402 | answer = report.get("barycentric_fallback") | ||
| 384 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): | 403 | except (OSError, ValueError, IndexError, subprocess.SubprocessError): |
| 385 | pass | 404 | pass |
| 386 | _BARYCENTRIC_FALLBACK.append(answer) | 405 | _BARYCENTRIC_FALLBACK.append(answer) |
| @@ -762,8 +781,11 @@ def native_folder(path: str, ansi: str = "mbcs") -> str | None: | |||
| 762 | 781 | ||
| 763 | def main() -> int: | 782 | def main() -> int: |
| 764 | ap = argparse.ArgumentParser() | 783 | ap = argparse.ArgumentParser() |
| 765 | ap.add_argument("--llvm-mc", default=os.environ.get("LLVM_MC", "llvm-mc"), | 784 | # No literal default: unset, mc_command() reads LLVM_MC and then finds llvm-mc on PATH or a versioned |
| 766 | help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'") | 785 | # Debian/Ubuntu install (llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc), as the not-found message promises. |
| 786 | ap.add_argument("--llvm-mc", default=None, | ||
| 787 | help="llvm-mc path, or a whole command such as 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' " | ||
| 788 | "(default: LLVM_MC, then llvm-mc on PATH, then the newest llvm-mc-<N>)") | ||
| 767 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), | 789 | ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build"), |
| 768 | help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " | 790 | help="CMake build folder; with the Visual Studio generator the RelWithDebInfo/Release/... " |
| 769 | "subfolder that has the test programs is found by itself") | 791 | "subfolder that has the test programs is found by itself") |
| @@ -895,6 +917,8 @@ def run_suite(a, work: str) -> int: | |||
| 895 | ]) | 917 | ]) |
| 896 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): | 918 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_f16_pack"): |
| 897 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) | 919 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 64, 64, 2))]) |
| 920 | elif name in ("ms_w64x_wave_votes", "ms_w64x_wave_loops"): # vertex 64 comes from the second wave: 128 output vertices | ||
| 921 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(128, 128, 64, 2))]) | ||
| 898 | elif name == "ms_v5_workgroup": | 922 | elif name == "ms_v5_workgroup": |
| 899 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) | 923 | dxbc = make_dxbc([(b"PSV0", make_ms_psv0(32, 3, 1, group_shared=128))]) |
| 900 | elif name == "ms_clip": | 924 | elif name == "ms_clip": |
| @@ -945,6 +969,8 @@ def run_suite(a, work: str) -> int: | |||
| 945 | cmd.append("--texel-offset-fallback") | 969 | cmd.append("--texel-offset-fallback") |
| 946 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py | 970 | if MESH_COMPUTE: # mesh shaders as compute writing to a buffer, drawn by tools/mesh_compute_vs.py |
| 947 | cmd.append("--mesh-compute") | 971 | cmd.append("--mesh-compute") |
| 972 | if os.environ.get("LEONIDA_MESH_SERIAL_WAVES") == "1": # with --wave64-emulate: one pass per wave | ||
| 973 | cmd.append("--mesh-serial-waves") | ||
| 948 | if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 | 974 | if pc_tail_ubo(): # 128 push-constant bytes; heap base and code base from a uniform block at set 1 |
| 949 | cmd.append("--pc-tail-ubo") | 975 | cmd.append("--pc-tail-ubo") |
| 950 | if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) | 976 | if os.environ.get("LEONIDA_FMA") in ("glsl", "khr", "exact"): # GLSL Fma, OpFmaKHR or emulated (docs/design.md) |
| @@ -1057,7 +1083,8 @@ def run_suite(a, work: str) -> int: | |||
| 1057 | # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. | 1083 | # load reads 0, so thread 0's four output words are fixed. One thread, no wave64 requirement. |
| 1058 | # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either. | 1084 | # cs_cmpx_class_f32 and cs_cvt_pk_u8 are per-lane and need no particular subgroup width either. |
| 1059 | # The other four pin the SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm). | 1085 | # The other four pin the SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm). |
| 1060 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=cs_env) | 1086 | env = dict(cs_env or os.environ, **PK_MUL_LO_ENV) if name == "cs_pk_mul_lo_const" else cs_env |
| 1087 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=env) | ||
| 1061 | want = { | 1088 | want = { |
| 1062 | "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], | 1089 | "cs_bounds": [0x12345678, 0x12345678, 0, 0xEEEEEEEE], |
| 1063 | "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], | 1090 | "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], |
| @@ -1081,10 +1108,7 @@ def run_suite(a, work: str) -> int: | |||
| 1081 | "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], | 1108 | "cs_buf_load_sub": [0x80, 0xFFFFFF80, 0x1FF, 0xFFFF807F, 0xAB01, 0xCD, 0, 0], |
| 1082 | "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], | 1109 | "cs_buf_fmt8": [0x7F, 0x80, 0xFF, 0x01, 0, 0, 0xFF, 1], |
| 1083 | }[name] | 1110 | }[name] |
| 1084 | words = dump_words(msg) | 1111 | results.append((name,) + dump_result(rc, msg, want)) |
| 1085 | vals = words[:len(want)] if words else [] | ||
| 1086 | results.append((name,) + compute_result(rc, msg, rc == 0 and vals == want, | ||
| 1087 | " ".join(hex(x) for x in vals) if vals else msg)) | ||
| 1088 | elif name == "cs_fmt_1010102": | 1112 | elif name == "cs_fmt_1010102": |
| 1089 | problem = fmt_1010102_test(a.build, spirv_dir, cs_env) | 1113 | problem = fmt_1010102_test(a.build, spirv_dir, cs_env) |
| 1090 | results.append((name, not problem, problem or "64/64 dumped words exact")) | 1114 | results.append((name, not problem, problem or "64/64 dumped words exact")) |
| @@ -1101,6 +1125,7 @@ def run_suite(a, work: str) -> int: | |||
| 1101 | elif name == "cs_tbuffer_store": | 1125 | elif name == "cs_tbuffer_store": |
| 1102 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) | 1126 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) |
| 1103 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) | 1127 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) |
| 1128 | results.append((name, not problem, problem or "128/128 dumped words exact")) | ||
| 1104 | elif name == "cs_fmt_d16_xyz": | 1129 | elif name == "cs_fmt_d16_xyz": |
| 1105 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) | 1130 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) |
| 1106 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) | 1131 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) |
| @@ -1118,17 +1143,11 @@ def run_suite(a, work: str) -> int: | |||
| 1118 | elif name == "cs_heap_init": | 1143 | elif name == "cs_heap_init": |
| 1119 | # vk_compute_test copies VKC_HEAP_INIT's file into the heap; the shader copies its words at 0x100 to 0. | 1144 | # vk_compute_test copies VKC_HEAP_INIT's file into the heap; the shader copies its words at 0x100 to 0. |
| 1120 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env())) | 1145 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **heap_init_env())) |
| 1121 | words = dump_words(msg) | 1146 | results.append((name,) + dump_result(rc, msg, HEAP_INIT_EXPECTED)) |
| 1122 | vals = words[:len(HEAP_INIT_EXPECTED)] if words else [] | ||
| 1123 | results.append((name,) + compute_result(rc, msg, rc == 0 and vals == HEAP_INIT_EXPECTED, | ||
| 1124 | " ".join(hex(x) for x in vals) if vals else msg)) | ||
| 1125 | elif name == "cs_user_sgprs": | 1147 | elif name == "cs_user_sgprs": |
| 1126 | # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. | 1148 | # vk_compute_test seeds s4..s7 from VKC_SGPRS; the shader stores them back. |
| 1127 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) | 1149 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"], env=dict(cs_env or os.environ, **USER_SGPRS_ENV)) |
| 1128 | words = dump_words(msg) | 1150 | results.append((name,) + dump_result(rc, msg, USER_SGPRS_WORDS)) |
| 1129 | vals = words[:len(USER_SGPRS_WORDS)] if words else [] | ||
| 1130 | results.append((name,) + compute_result(rc, msg, rc == 0 and vals == USER_SGPRS_WORDS, | ||
| 1131 | " ".join(hex(x) for x in vals) if vals else msg)) | ||
| 1132 | elif name == "cs_w32_salu_ext": | 1151 | elif name == "cs_w32_salu_ext": |
| 1133 | detail = salu_ext_test(a.build, spirv_dir, cs_env) | 1152 | detail = salu_ext_test(a.build, spirv_dir, cs_env) |
| 1134 | results.append((name, None if isinstance(detail, Skip) else not detail, | 1153 | results.append((name, None if isinstance(detail, Skip) else not detail, |
| @@ -1138,7 +1157,7 @@ def run_suite(a, work: str) -> int: | |||
| 1138 | if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names | 1157 | if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names |
| 1139 | results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) | 1158 | results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) |
| 1140 | else: | 1159 | else: |
| 1141 | ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, | 1160 | ok, detail = judge_cs_dump(rc, msg, [0, 0x3FF40000], wave64=False, partial=False, emulated=False, |
| 1142 | hexwords=True) | 1161 | hexwords=True) |
| 1143 | results.append((name, ok, detail)) | 1162 | results.append((name, ok, detail)) |
| 1144 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): | 1163 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): |
| @@ -1203,15 +1222,15 @@ def run_suite(a, work: str) -> int: | |||
| 1203 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. | 1222 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. |
| 1204 | results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) | 1223 | results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) |
| 1205 | elif name in ("cs_smem_vcc_base", "cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", | 1224 | elif name in ("cs_smem_vcc_base", "cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", |
| 1206 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", | 1225 | "cs_w32_cvt_f16_mods", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", |
| 1207 | "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_w64", | 1226 | "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_dpp_w64", |
| 1208 | "cs_w64_mask_detect", | 1227 | "cs_w64_mask_detect", |
| 1209 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", | 1228 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", |
| 1210 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", | 1229 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", |
| 1211 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", | 1230 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", |
| 1212 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", | 1231 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", |
| 1213 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", | 1232 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", |
| 1214 | "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", | 1233 | "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", |
| 1215 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): | 1234 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): |
| 1216 | cs_dump_wants = { | 1235 | cs_dump_wants = { |
| 1217 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], | 1236 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], |
| @@ -1237,6 +1256,7 @@ def run_suite(a, work: str) -> int: | |||
| 1237 | # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) | 1256 | # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) |
| 1238 | "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], | 1257 | "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], |
| 1239 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], | 1258 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], |
| 1259 | "cs_w32_cvt_f16_mods": CVT_F16_MODS_WORDS, | ||
| 1240 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], | 1260 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], |
| 1241 | "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], | 1261 | "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], |
| 1242 | # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) | 1262 | # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) |
| @@ -1250,6 +1270,12 @@ def run_suite(a, work: str) -> int: | |||
| 1250 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) | 1270 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) |
| 1251 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, | 1271 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, |
| 1252 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], | 1272 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], |
| 1273 | # ds_wrxchg2_rtn_b32's pair cases and ds_wrxchg2st64_rtn_b32 | ||
| 1274 | # (cs_w32_wrxchg2_ext.asm / cs_w32_wrxchg2st64.asm headers) | ||
| 1275 | "cs_w32_wrxchg2_ext": [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF, | ||
| 1276 | 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678], | ||
| 1277 | "cs_w32_wrxchg2st64": [0x33333333, 0x44444444, 0x55550005, 0x66660006, | ||
| 1278 | 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0], | ||
| 1253 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) | 1279 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) |
| 1254 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, | 1280 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, |
| 1255 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], | 1281 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], |
| @@ -1267,6 +1293,7 @@ def run_suite(a, work: str) -> int: | |||
| 1267 | "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], | 1293 | "cs_dpp_bank": [0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFC, 7, 7, 7, 7], |
| 1268 | "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], | 1294 | "cs_dpp_fi": [1, 2, 3, 0x7777, 5, 6, 7, 0x7777], |
| 1269 | "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0], | 1295 | "cs_dpp_cmp": [3, 2, 3, 2, 1, 0, 1, 0], |
| 1296 | "cs_dpp_cmpx": [1, 1, 0, 0, 3, 3, 2, 2], | ||
| 1270 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], | 1297 | "cs_dpp_w64": [1, 0, 3, 2, 5, 4, 7, 6], |
| 1271 | # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] | 1298 | # SHADER-99: -0 and NaN survive (SignedZeroInfNanPreserve, cs_signed_zero_nan.asm); 0 in out[4..7] |
| 1272 | # without it | 1299 | # without it |
| @@ -1296,6 +1323,7 @@ def run_suite(a, work: str) -> int: | |||
| 1296 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], | 1323 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], |
| 1297 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], | 1324 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], |
| 1298 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave | 1325 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave |
| 1326 | "cs_w64x_partial_swizzle": [508, 523, 0, 0, 528, 0, 531, 0], # swizzle from a missing lane: 0 | ||
| 1299 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 | 1327 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 |
| 1300 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) | 1328 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) |
| 1301 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], | 1329 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], |
| @@ -1327,25 +1355,28 @@ def run_suite(a, work: str) -> int: | |||
| 1327 | want = cs_dump_wants[name] | 1355 | want = cs_dump_wants[name] |
| 1328 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / | 1356 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / |
| 1329 | # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops / cs_signed_zero_nan, the wave32 | 1357 | # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops / cs_signed_zero_nan, the wave32 |
| 1330 | # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, | 1358 | # cs_w32_cvt_f16_mods / cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: |
| 1359 | # ask for a 64-wide subgroup and skip, | ||
| 1331 | # as check.py does, where the device has none | 1360 | # as check.py does, where the device has none |
| 1332 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were | 1361 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were |
| 1333 | # translated with --wave64-emulate and run on any subgroup size. | 1362 | # translated with --wave64-emulate and run on any subgroup size. |
| 1334 | # cs_w64x_partial and cs_w64x_partial_scmp (40-thread groups) can't have full subgroups: they ask for | 1363 | # cs_w64x_partial, cs_w64x_partial_scmp and cs_w64x_partial_swizzle (40-thread groups) can't have full |
| 1335 | # size 64 without them. | 1364 | # subgroups: they ask for size 64 without them. With LEONIDA_W64_EMULATE=1 they ask for 32, the width the |
| 1365 | # emulation is for, as check.py's partial_wave_test does. RADV defaults compute to 64, and there | ||
| 1366 | # cs_w64x_partial_swizzle came out right even before its missing-lane reads were fixed; at 32 it did not. | ||
| 1336 | emulated = w64_emulated() | 1367 | emulated = w64_emulated() |
| 1337 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp") | 1368 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") |
| 1338 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", | 1369 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", |
| 1339 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", | 1370 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", |
| 1340 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", | 1371 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_cvt_f16_mods", |
| 1341 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1372 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1342 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", | 1373 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", |
| 1343 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", | 1374 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", |
| 1344 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", | 1375 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", |
| 1345 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", | 1376 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_w32_andn2_exec", |
| 1346 | "cs_w32_exec_computed") and not emulated and not partial | 1377 | "cs_w32_exec_computed") and not emulated and not partial |
| 1347 | if partial and not emulated: | 1378 | if partial: |
| 1348 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") | 1379 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") |
| 1349 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) | 1380 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) |
| 1350 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) | 1381 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) |
| 1351 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) | 1382 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) |
| @@ -1367,7 +1398,7 @@ def run_suite(a, work: str) -> int: | |||
| 1367 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, | 1398 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, |
| 1368 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", | 1399 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", |
| 1369 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1400 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1370 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_signed_zero_nan")) | 1401 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_signed_zero_nan")) |
| 1371 | if ok and None in want: | 1402 | if ok and None in want: |
| 1372 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) | 1403 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) |
| 1373 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" | 1404 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" |
| @@ -1504,6 +1535,7 @@ def run_suite(a, work: str) -> int: | |||
| 1504 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), | 1535 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), |
| 1505 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), | 1536 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), |
| 1506 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), | 1537 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), |
| 1538 | "ps_exp_f32_denorm": (0x01000000, 0x00800000, 0x00000000, 0x00000000), | ||
| 1507 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), | 1539 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), |
| 1508 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) | 1540 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) |
| 1509 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) | 1541 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) |
| @@ -1512,7 +1544,7 @@ def run_suite(a, work: str) -> int: | |||
| 1512 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), | 1544 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), |
| 1513 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), | 1545 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), |
| 1514 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), | 1546 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), |
| 1515 | "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 | 1547 | "ps_f64_mods": (0x3FF40000, 0x3FF00000, 0x3FF00000, 0x3FD00000), # needs shaderFloat64 |
| 1516 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 | 1548 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 |
| 1517 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), | 1549 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), |
| 1518 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) | 1550 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) |
| @@ -1595,6 +1627,9 @@ def run_suite(a, work: str) -> int: | |||
| 1595 | elif name == "ps_ij_computed": | 1627 | elif name == "ps_ij_computed": |
| 1596 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | 1628 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) |
| 1597 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" | 1629 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" |
| 1630 | elif name == "ps_exp_f32_denorm_rt": | ||
| 1631 | problem = exp_f32_denorm_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | ||
| 1632 | ok, detail = not problem, problem or "4096 pixels exact across 64 runtime-dependent inputs" | ||
| 1598 | elif name == "ps_mandelbrot": | 1633 | elif name == "ps_mandelbrot": |
| 1599 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] | 1634 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] |
| 1600 | problem = frame_problem(px) or mandelbrot_problem(px) | 1635 | problem = frame_problem(px) or mandelbrot_problem(px) |
| @@ -1621,13 +1656,13 @@ def run_suite(a, work: str) -> int: | |||
| 1621 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") | 1656 | problem = mesh_v5_test(a.build, spirv_dir, Path(raw_dir) / f"{name}.raw") |
| 1622 | results.append((name, None if isinstance(problem, Skip) else not problem, | 1657 | results.append((name, None if isinstance(problem, Skip) else not problem, |
| 1623 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) | 1658 | problem or "24/24 workgroup coordinates exact (2 x 3 x 4)")) |
| 1624 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3"): | 1659 | elif name in ("ms_tri", "ms_w64x_ballot", "ms_wave_info_s3", "ms_w64x_wave_votes", "ms_w64x_wave_loops"): |
| 1625 | raw = os.path.join(raw_dir, f"{name}.raw") | 1660 | raw = os.path.join(raw_dir, f"{name}.raw") |
| 1626 | env = mesh_env(spirv_dir, name, gfx_env) | 1661 | env = mesh_env(spirv_dir, name, gfx_env) |
| 1627 | rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) | 1662 | rc, msg = run_readback(raw, run_cmd, [vk_harness, spv, fs_passthru, raw], env=env) |
| 1628 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as | 1663 | # ms_w64x_ballot needs exact wave64 (a 64-wide subgroup, or --wave64-emulate): skip it elsewhere, as |
| 1629 | # the wave64 compute dumps are. | 1664 | # the wave64 compute dumps are. |
| 1630 | no64 = (name == "ms_w64x_ballot" and not w64_emulated() and | 1665 | no64 = (name in ("ms_w64x_ballot", "ms_w64x_wave_votes", "ms_w64x_wave_loops") and not w64_emulated() and |
| 1631 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) | 1666 | not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", msg))) |
| 1632 | if rc == UNSUPPORTED: | 1667 | if rc == UNSUPPORTED: |
| 1633 | results.append((name, None, unsupported_skip(msg))) | 1668 | results.append((name, None, unsupported_skip(msg))) |
| @@ -1679,14 +1714,15 @@ def run_suite(a, work: str) -> int: | |||
| 1679 | ok, detail = check_flat(raw) | 1714 | ok, detail = check_flat(raw) |
| 1680 | results.append((name, ok, detail)) | 1715 | results.append((name, ok, detail)) |
| 1681 | 1716 | ||
| 1682 | if a.filter and not results: # the filter matched only inputs/partners: say so rather than "0/0 passed" | 1717 | if (a.filter or disasm_src is not None) and not results: |
| 1683 | names = [os.path.splitext(f)[0] for f in asm_files] | 1718 | names = [os.path.splitext(f)[0] for f in asm_files] |
| 1684 | partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) | 1719 | partners = {os.path.splitext(f)[0] for f in DRAWN_WITH.values()} | set(TEXTURE_MIP_DEPENDENCIES) |
| 1685 | shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") | 1720 | shown = ", ".join(names[:5]) + (", ..." if len(names) > 5 else "") |
| 1686 | role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" | 1721 | role = "partners built for other tests" if partners.issuperset(names) else "inputs without a GPU test row" |
| 1687 | hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" | 1722 | hint = ("; cs_bench_* shaders are benchmark inputs, run them with the benchmark tool" |
| 1688 | if all(n.startswith("cs_bench_") for n in names) else "") | 1723 | if all(n.startswith("cs_bench_") for n in names) else "") |
| 1689 | print(f"error: --filter {a.filter!r} selected {shown} but no runnable GPU test cases ({role}){hint}", | 1724 | selected_by = f"--filter {a.filter!r}" if a.filter else f"--disasm-dir {disasm_src!r}" |
| 1725 | print(f"error: {selected_by} selected {shown} but no runnable GPU test cases ({role}){hint}", | ||
| 1690 | file=sys.stderr) | 1726 | file=sys.stderr) |
| 1691 | return 2 | 1727 | return 2 |
| 1692 | 1728 | ||
diff --git a/scripts/run_guest_scene.py b/scripts/run_guest_scene.py index 60d5ded90..55f770c8b 100644 --- a/scripts/run_guest_scene.py +++ b/scripts/run_guest_scene.py | |||
| @@ -256,12 +256,13 @@ def negative_controls(session: Session, out: Path) -> dict: | |||
| 256 | 256 | ||
| 257 | 257 | ||
| 258 | def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: | 258 | def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: |
| 259 | session = Session(args, out) | ||
| 259 | try: | 260 | try: |
| 260 | out.mkdir(parents=True, exist_ok=True) # parse_args has checked that it is new or empty | 261 | out.mkdir(parents=True, exist_ok=True) # parse_args has checked that it is new or empty |
| 262 | session.logs.mkdir() # Reserve the output even if another run passed the same check. | ||
| 261 | except OSError as exc: | 263 | except OSError as exc: |
| 262 | print(f"error: could not create output directory {out}: {exc}", file=sys.stderr) | 264 | print(f"error: could not create output directory {out}: {exc}", file=sys.stderr) |
| 263 | return 1 | 265 | return 1 |
| 264 | session = Session(args, out) | ||
| 265 | report: dict = {"status": "fail", "frames": FRAMES, "headless": True, "wine": args.wine, "temporary": temporary, | 266 | 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")} | 267 | "audio_mode": "winmm" if args.play_audio else "offline", "report": str(out / "report.json")} |
| 267 | try: | 268 | try: |
| @@ -271,7 +272,7 @@ def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: | |||
| 271 | "guest": {"path": str(args.guest), "sha256": sha256(args.guest.read_bytes())}, | 272 | "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)}, | 273 | "shaders": {"path": str(args.shaders), "files": len(shader_files), "tree_sha256": tree_hash(shader_files)}, |
| 273 | "scene.bin": sha256(scene_bytes())} | 274 | "scene.bin": sha256(scene_bytes())} |
| 274 | for sub in ("logs", "package", *MODES): | 275 | for sub in ("package", *MODES): |
| 275 | (out / sub).mkdir() | 276 | (out / sub).mkdir() |
| 276 | package = out / "package" | 277 | package = out / "package" |
| 277 | write_new(package / "scene.bin", scene_bytes()) | 278 | write_new(package / "scene.bin", scene_bytes()) |
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 1965e0106..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,6 +36,7 @@ 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 |
| @@ -59,7 +63,7 @@ def _unregister_process(proc): | |||
| 59 | def _kill_process_tree(proc): | 63 | def _kill_process_tree(proc): |
| 60 | if proc is None: | 64 | if proc is None: |
| 61 | return | 65 | return |
| 62 | if os.name == "nt": | 66 | if os.name == "nt" and proc.poll() is None: |
| 63 | try: | 67 | try: |
| 64 | subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], | 68 | subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], |
| 65 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | 69 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| @@ -74,11 +78,13 @@ def _kill_process_tree(proc): | |||
| 74 | def _terminate_active_processes(): | 78 | def _terminate_active_processes(): |
| 75 | with _processes_lock: | 79 | with _processes_lock: |
| 76 | procs = list(_active_processes) | 80 | procs = list(_active_processes) |
| 77 | for p in procs: | 81 | if os.name != "nt": |
| 78 | try: | 82 | for p in procs: |
| 79 | p.terminate() | 83 | try: |
| 80 | except OSError: | 84 | p.terminate() |
| 81 | pass | 85 | except OSError: |
| 86 | pass | ||
| 87 | # On Windows taskkill /T needs the root process alive to find its descendants. | ||
| 82 | for p in procs: | 88 | for p in procs: |
| 83 | _kill_process_tree(p) | 89 | _kill_process_tree(p) |
| 84 | try: | 90 | try: |
| @@ -94,13 +100,44 @@ CHILD_PROGRAM = ( | |||
| 94 | "import json, os, sys, unittest\n" | 100 | "import json, os, sys, unittest\n" |
| 95 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" | 101 | "program = unittest.TestProgram(module=None, argv=['unittest'] + sys.argv[1:], exit=False)\n" |
| 96 | "result = program.result\n" | 102 | "result = program.result\n" |
| 97 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8') as handle:\n" | 103 | "code = 1 if not result.wasSuccessful() else 5 if not result.testsRun and not result.skipped else 0\n" |
| 98 | " json.dump({'testsRun': result.testsRun}, handle)\n" | 104 | "with open(os.environ['LEONIDA_TEST_COUNT'], 'w', encoding='utf-8', newline='\\n') as handle:\n" |
| 99 | "if not result.wasSuccessful():\n" | 105 | " json.dump({'testsRun': result.testsRun, 'exitCode': code}, handle)\n" |
| 100 | " sys.exit(1)\n" | 106 | "sys.exit(code)\n") |
| 101 | "elif result.testsRun == 0 and len(result.skipped) == 0:\n" | 107 | |
| 102 | " sys.exit(5)\n" | 108 | # Windows NTSTATUS codes python.exe exits with when it crashes. A file that dies this way prints nothing, so the code |
| 103 | "sys.exit(0)\n") | 109 | # is the only clue there is (an access violation in a pure-Python test points at the machine, not at the test). |
| 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}" | ||
| 104 | 141 | ||
| 105 | 142 | ||
| 106 | def module_path(directory, module): | 143 | def module_path(directory, module): |
| @@ -139,14 +176,69 @@ def positive_seconds(value): | |||
| 139 | return seconds | 176 | return seconds |
| 140 | 177 | ||
| 141 | 178 | ||
| 142 | def read_count(path): | 179 | def read_result(path, process_code): |
| 143 | """The number of tests the child ran, as unittest's own result object reported it.""" | 180 | """Return the effective exit code, completed test count, and any diagnostic.""" |
| 144 | try: | 181 | try: |
| 145 | with open(path, encoding="utf-8") as handle: | 182 | with open(path, encoding="utf-8") as handle: |
| 146 | return int(json.load(handle)["testsRun"]) | 183 | result = json.load(handle) |
| 184 | count, test_code = result["testsRun"], result["exitCode"] | ||
| 185 | if type(count) is not int or count < 0 or type(test_code) is not int or test_code not in (0, 1, 5): | ||
| 186 | raise ValueError("invalid unittest result") | ||
| 147 | except (OSError, ValueError, KeyError, TypeError): | 187 | except (OSError, ValueError, KeyError, TypeError): |
| 148 | # The child wrote no result: it did not finish, so no test is known to have run. | 188 | if process_code == 0: |
| 149 | return 0 | 189 | return 1, 0, "process exited without a unittest result" |
| 190 | return process_code, None, "" | ||
| 191 | if process_code in (0, 5) and process_code != test_code: | ||
| 192 | return 1, count, f"process exited with status {process_code} but unittest reported {test_code}" | ||
| 193 | return process_code, count, "" | ||
| 194 | |||
| 195 | |||
| 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 | ||
| 150 | 242 | ||
| 151 | 243 | ||
| 152 | def run_module(directory, module, verbose, timeout=None): | 244 | def run_module(directory, module, verbose, timeout=None): |
| @@ -157,8 +249,7 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 157 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module | 249 | target = module[:-len(".__init__")] if module.endswith(".__init__") else module |
| 158 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] | 250 | cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target] |
| 159 | with tempfile.TemporaryDirectory() as scratch: | 251 | with tempfile.TemporaryDirectory() as scratch: |
| 160 | count_path = os.path.join(scratch, "count.json") | 252 | result_path, env = result_environment(scratch) |
| 161 | env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) | ||
| 162 | proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, | 253 | proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 163 | text=True, errors="replace") | 254 | text=True, errors="replace") |
| 164 | _register_process(proc) | 255 | _register_process(proc) |
| @@ -181,13 +272,14 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 181 | raise | 272 | raise |
| 182 | finally: | 273 | finally: |
| 183 | _unregister_process(proc) | 274 | _unregister_process(proc) |
| 184 | count = read_count(count_path) | 275 | code, count, diagnostic = read_result(result_path, proc.returncode) |
| 185 | out = stdout + stderr | 276 | out = stdout + stderr |
| 186 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the | 277 | if diagnostic: |
| 187 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. | 278 | out += f"\n{diagnostic}\n" |
| 188 | if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: | 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__"): | ||
| 189 | return 0, 0, out | 281 | return 0, 0, out |
| 190 | return proc.returncode, count, out | 282 | return code, count or 0, out |
| 191 | 283 | ||
| 192 | 284 | ||
| 193 | def main(argv=None): | 285 | def main(argv=None): |
| @@ -206,40 +298,7 @@ def main(argv=None): | |||
| 206 | print(f"no {a.pattern} files in {directory}") | 298 | print(f"no {a.pattern} files in {directory}") |
| 207 | return 1 | 299 | return 1 |
| 208 | if a.jobs <= 1: | 300 | if a.jobs <= 1: |
| 209 | cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, | 301 | return run_discover(directory, a.pattern, a.verbose, a.timeout) |
| 210 | "-p", a.pattern, *(["-v"] if a.verbose else [])] | ||
| 211 | proc = subprocess.Popen(cmd) | ||
| 212 | _register_process(proc) | ||
| 213 | try: | ||
| 214 | deadline = None if a.timeout is None else time.monotonic() + a.timeout | ||
| 215 | while True: | ||
| 216 | wait_seconds = 0.2 | ||
| 217 | if deadline is not None: | ||
| 218 | remaining = deadline - time.monotonic() | ||
| 219 | if remaining <= 0: | ||
| 220 | raise subprocess.TimeoutExpired(cmd, a.timeout) | ||
| 221 | wait_seconds = min(wait_seconds, remaining) | ||
| 222 | try: | ||
| 223 | return proc.wait(timeout=wait_seconds) | ||
| 224 | except subprocess.TimeoutExpired: | ||
| 225 | continue | ||
| 226 | except subprocess.TimeoutExpired: | ||
| 227 | _kill_process_tree(proc) | ||
| 228 | print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) | ||
| 229 | return 1 | ||
| 230 | except KeyboardInterrupt: | ||
| 231 | _kill_process_tree(proc) | ||
| 232 | try: | ||
| 233 | proc.wait(timeout=0.5) | ||
| 234 | except (subprocess.TimeoutExpired, OSError): | ||
| 235 | pass | ||
| 236 | print("interrupted", file=sys.stderr) | ||
| 237 | return 130 | ||
| 238 | except BaseException: | ||
| 239 | _kill_process_tree(proc) | ||
| 240 | raise | ||
| 241 | finally: | ||
| 242 | _unregister_process(proc) | ||
| 243 | # 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. |
| 244 | 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))) |
| 245 | start, total, failed = time.monotonic(), 0, [] | 304 | start, total, failed = time.monotonic(), 0, [] |
| @@ -257,7 +316,8 @@ def main(argv=None): | |||
| 257 | total += ran | 316 | total += ran |
| 258 | if code: | 317 | if code: |
| 259 | failed.append(jobs[job]) | 318 | failed.append(jobs[job]) |
| 260 | print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) | 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) | ||
| 261 | elif a.verbose: | 321 | elif a.verbose: |
| 262 | print(f"==== {jobs[job]}\n{out}", flush=True) | 322 | print(f"==== {jobs[job]}\n{out}", flush=True) |
| 263 | except KeyboardInterrupt: | 323 | except KeyboardInterrupt: |
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..acd933ee3 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 | ||
| @@ -190,6 +218,14 @@ class KeptServer: | |||
| 190 | except (OSError, subprocess.TimeoutExpired): | 218 | except (OSError, subprocess.TimeoutExpired): |
| 191 | return None | 219 | return None |
| 192 | 220 | ||
| 221 | def _warmup(self) -> None: | ||
| 222 | env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) | ||
| 223 | try: | ||
| 224 | subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, | ||
| 225 | stderr=subprocess.DEVNULL, env=env, timeout=120) | ||
| 226 | except (OSError, subprocess.TimeoutExpired): | ||
| 227 | pass # the tests start the services then, as without a kept server | ||
| 228 | |||
| 193 | def __enter__(self): | 229 | def __enter__(self): |
| 194 | if not self.command: | 230 | if not self.command: |
| 195 | self.note = "no wineserver found: each test starts its own" | 231 | self.note = "no wineserver found: each test starts its own" |
| @@ -200,18 +236,14 @@ class KeptServer: | |||
| 200 | code = self._run("-p") | 236 | code = self._run("-p") |
| 201 | else: | 237 | else: |
| 202 | self.note = "a wineserver already runs for this prefix: used and left running" | 238 | self.note = "a wineserver already runs for this prefix: used and left running" |
| 239 | self._warmup() | ||
| 203 | return self | 240 | return self |
| 204 | self.started = code == 0 | 241 | self.started = code == 0 |
| 205 | if not self.started: | 242 | if not self.started: |
| 206 | self.note = f"could not start {self.command} -p: each test starts its own server" | 243 | self.note = f"could not start {self.command} -p: each test starts its own server" |
| 207 | return self | 244 | return self |
| 208 | self.note = "wineserver kept alive for the run" | 245 | self.note = "wineserver kept alive for the run" |
| 209 | env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) | 246 | 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 | 247 | return self |
| 216 | 248 | ||
| 217 | def __exit__(self, *exc): | 249 | def __exit__(self, *exc): |
| @@ -395,15 +427,13 @@ def stop_running_tests() -> None: | |||
| 395 | 427 | ||
| 396 | 428 | ||
| 397 | def positive_seconds(text: str) -> float: | 429 | 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.""" | 430 | """Parse a positive timeout that fits the subprocess wait on all supported hosts.""" |
| 399 | try: | 431 | try: |
| 400 | value = float(text) | 432 | value = float(text) |
| 401 | except ValueError: | 433 | except ValueError: |
| 402 | raise argparse.ArgumentTypeError(f"invalid float value: {text!r}") from None | 434 | raise argparse.ArgumentTypeError(f"invalid float value: {text!r}") from None |
| 403 | if not math.isfinite(value): | 435 | if not 0 < value <= MAX_TIMEOUT_SECONDS: |
| 404 | raise argparse.ArgumentTypeError("must be a finite number") | 436 | 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 | 437 | return value |
| 408 | 438 | ||
| 409 | 439 | ||
| @@ -435,7 +465,7 @@ def valid_test_property(entry) -> bool: | |||
| 435 | name, value = entry["name"], entry["value"] | 465 | name, value = entry["name"], entry["value"] |
| 436 | if name == "WORKING_DIRECTORY": | 466 | if name == "WORKING_DIRECTORY": |
| 437 | return isinstance(value, str) and "\0" not in value | 467 | return isinstance(value, str) and "\0" not in value |
| 438 | if name in ("PASS_REGULAR_EXPRESSION", "FAIL_REGULAR_EXPRESSION", "SKIP_REGULAR_EXPRESSION"): | 468 | 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)) | 469 | return isinstance(value, str) or (isinstance(value, list) and all(isinstance(p, str) for p in value)) |
| 440 | return True | 470 | return True |
| 441 | 471 | ||
| @@ -515,9 +545,10 @@ def main() -> int: | |||
| 515 | ap.add_argument("--root", type=os.path.abspath, default=ROOT, help="the Linux checkout (default: this repository)") | 545 | 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"), | 546 | ap.add_argument("--wine", type=wine_command, default=os.environ.get("WINE", "wine"), |
| 517 | help="Wine command (default: $WINE or wine)") | 547 | help="Wine command (default: $WINE or wine)") |
| 518 | ap.add_argument("--require", action="append", default=[], help="a test that must pass (repeatable)") | 548 | 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, | 549 | ap.add_argument("--timeout", type=positive_seconds, default=120.0, |
| 520 | help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") | 550 | help=f"maximum seconds per test (default 120, upper limit {MAX_TIMEOUT_SECONDS}). " |
| 551 | "A shorter CTest TIMEOUT applies.") | ||
| 521 | ap.add_argument("--jobs", type=positive_int, default=1, | 552 | 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)") | 553 | 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)") | 554 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") |
| @@ -546,7 +577,6 @@ def main() -> int: | |||
| 546 | # Each test starts in its own CTest working directory. Keep bare commands on PATH. | 577 | # 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]): | 578 | if os.path.dirname(wine[0]) and not os.path.isabs(wine[0]): |
| 548 | wine[0] = os.path.join(os.getcwd(), wine[0]) | 579 | wine[0] = os.path.join(os.getcwd(), wine[0]) |
| 549 | results = {} | ||
| 550 | results_by_index: dict[int, str] = {} | 580 | results_by_index: dict[int, str] = {} |
| 551 | prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") | 581 | prefix = os.environ.get("WINEPREFIX") or os.path.join(os.path.expanduser("~"), ".wine") |
| 552 | outcomes: dict[int, tuple[str, str]] = {} | 582 | outcomes: dict[int, tuple[str, str]] = {} |
| @@ -557,13 +587,18 @@ def main() -> int: | |||
| 557 | 587 | ||
| 558 | def report(index: int) -> None: | 588 | def report(index: int) -> None: |
| 559 | status, detail = outcomes[index] | 589 | status, detail = outcomes[index] |
| 560 | results[names[index]] = status | ||
| 561 | print(f"[{status.upper()}] {names[index]}", flush=True) | 590 | print(f"[{status.upper()}] {names[index]}", flush=True) |
| 562 | if status != "pass": | 591 | if status != "pass": |
| 563 | for line in detail.rstrip().splitlines()[-40:]: | 592 | for line in detail.rstrip().splitlines()[-40:]: |
| 564 | print(f" {line}") | 593 | print(f" {line}") |
| 565 | 594 | ||
| 566 | with DriveMap(args.windows_root, args.root, prefix) as drive, KeptServer(find_wineserver(wine), wine) as server: | 595 | with ExitStack() as run: |
| 596 | lock_error = run.enter_context(prefix_ownership(prefix)) | ||
| 597 | if lock_error: | ||
| 598 | print(f"ERROR: {lock_error}", file=sys.stderr) | ||
| 599 | return 2 | ||
| 600 | drive = run.enter_context(DriveMap(args.windows_root, args.root, prefix)) | ||
| 601 | server = run.enter_context(KeptServer(find_wineserver(wine), wine)) | ||
| 567 | print(drive.note, flush=True) | 602 | print(drive.note, flush=True) |
| 568 | print(server.note, flush=True) | 603 | print(server.note, flush=True) |
| 569 | if args.jobs == 1: | 604 | if args.jobs == 1: |
| @@ -574,11 +609,12 @@ def main() -> int: | |||
| 574 | else: | 609 | else: |
| 575 | run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) | 610 | run_parallel(tests, order, before, args.jobs, run_one, outcomes, results_by_index, report) |
| 576 | 611 | ||
| 577 | missing = list(dict.fromkeys(n for n in args.require if n not in results)) | 612 | 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"] | 613 | 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")} | 614 | failed_required = [n for n in args.require if n not in indices or n in nonpassing_names] |
| 615 | 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 " | 616 | print(f"\n{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped under Wine " |
| 581 | f"({len(results)} tests)") | 617 | f"({len(results_by_index)} tests)") |
| 582 | for n in missing: | 618 | for n in missing: |
| 583 | print(f"required test not listed by the Windows build: {n}") | 619 | print(f"required test not listed by the Windows build: {n}") |
| 584 | if failed_required: | 620 | if failed_required: |
| @@ -591,7 +627,8 @@ def main() -> int: | |||
| 591 | f.write(f"### Windows tests under {args.label or 'Wine'}\n\n") | 627 | 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") | 628 | f.write(f"{counts['pass']} passed, {counts['fail']} failed, {counts['skip']} skipped.\n\n") |
| 593 | f.write("| Test | Result | Required |\n|---|---|---|\n") | 629 | f.write("| Test | Result | Required |\n|---|---|---|\n") |
| 594 | for name, status in results.items(): | 630 | for index in order: |
| 631 | name, status = names[index], results_by_index[index] | ||
| 595 | f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n") | 632 | f.write(f"| `{name}` | {status} | {'yes' if name in args.require else ''} |\n") |
| 596 | for name in missing: | 633 | for name in missing: |
| 597 | # The job fails on these, so the table must name them, not only the log. | 634 | # 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/sync_victory.py b/scripts/sync_victory.py new file mode 100644 index 000000000..ccae2c459 --- /dev/null +++ b/scripts/sync_victory.py | |||
| @@ -0,0 +1,94 @@ | |||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Check DexNom/VIctory for new commits and optionally merge them into victory/. | ||
| 3 | |||
| 4 | VIctory lives in this repository as a git subtree under ``victory/`` (added with | ||
| 5 | ``git subtree add --prefix=victory victory main``). This tool fetches the | ||
| 6 | ``victory`` remote, reports the commits that are not merged yet and, with | ||
| 7 | ``--merge``, pulls them in with ``git subtree pull`` so upstream history is kept | ||
| 8 | and local changes under ``victory/`` are merged, not overwritten. | ||
| 9 | |||
| 10 | Run from anywhere inside the repository: | ||
| 11 | |||
| 12 | python -I scripts/sync_victory.py # report only | ||
| 13 | python -I scripts/sync_victory.py --merge # report, then merge if clean | ||
| 14 | |||
| 15 | Exit codes: 0 up to date or merged, 10 updates waiting (report only), | ||
| 16 | 2 git failure, 3 working tree not clean (merge refused), 4 merge conflict. | ||
| 17 | """ | ||
| 18 | |||
| 19 | import argparse | ||
| 20 | import datetime | ||
| 21 | import os | ||
| 22 | import subprocess | ||
| 23 | import sys | ||
| 24 | |||
| 25 | REMOTE = "victory" | ||
| 26 | BRANCH = "main" | ||
| 27 | PREFIX = "victory" | ||
| 28 | |||
| 29 | |||
| 30 | def git(*args, check=True): | ||
| 31 | proc = subprocess.run( | ||
| 32 | ["git", *args], | ||
| 33 | stdout=subprocess.PIPE, | ||
| 34 | stderr=subprocess.STDOUT, | ||
| 35 | text=True, | ||
| 36 | encoding="utf-8", | ||
| 37 | errors="replace", | ||
| 38 | ) | ||
| 39 | if check and proc.returncode != 0: | ||
| 40 | print(f"git {' '.join(args)} failed ({proc.returncode}):\n{proc.stdout}") | ||
| 41 | sys.exit(2) | ||
| 42 | return proc | ||
| 43 | |||
| 44 | |||
| 45 | def main(): | ||
| 46 | ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 47 | ap.add_argument("--merge", action="store_true", help="merge new commits with git subtree pull") | ||
| 48 | args = ap.parse_args() | ||
| 49 | |||
| 50 | top = git("rev-parse", "--show-toplevel").stdout.strip() | ||
| 51 | os.chdir(top) | ||
| 52 | stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") | ||
| 53 | |||
| 54 | git("fetch", "--quiet", REMOTE, BRANCH) | ||
| 55 | upstream = git("rev-parse", f"{REMOTE}/{BRANCH}").stdout.strip() | ||
| 56 | merged = git("merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode == 0 | ||
| 57 | if merged: | ||
| 58 | print(f"[{stamp}] {REMOTE}/{BRANCH} {upstream[:9]} is already merged; nothing to do.") | ||
| 59 | return 0 | ||
| 60 | |||
| 61 | new = git("log", "--oneline", "--no-decorate", f"HEAD..{upstream}").stdout.strip().splitlines() | ||
| 62 | print(f"[{stamp}] {len(new)} new {REMOTE}/{BRANCH} commit(s) up to {upstream[:9]}:") | ||
| 63 | for line in new: | ||
| 64 | print(f" {line}") | ||
| 65 | if not args.merge: | ||
| 66 | return 10 | ||
| 67 | |||
| 68 | dirty = git("status", "--porcelain", "--untracked-files=no").stdout.strip() | ||
| 69 | if dirty: | ||
| 70 | print("Working tree has uncommitted changes; commit or stash them, then run --merge again.") | ||
| 71 | print(dirty) | ||
| 72 | return 3 | ||
| 73 | |||
| 74 | msg = ( | ||
| 75 | f"Merge {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/ ({len(new)} commit(s))\n\n" | ||
| 76 | "Pulled with scripts/sync_victory.py --merge (git subtree pull).\n" | ||
| 77 | ) | ||
| 78 | pull = git("subtree", "pull", f"--prefix={PREFIX}", REMOTE, BRANCH, "-m", msg, check=False) | ||
| 79 | print(pull.stdout.strip()) | ||
| 80 | if pull.returncode != 0: | ||
| 81 | conflicts = git("diff", "--name-only", "--diff-filter=U", check=False).stdout.strip() | ||
| 82 | if conflicts: | ||
| 83 | print("Merge stopped on conflicts in:") | ||
| 84 | print(conflicts) | ||
| 85 | return 4 | ||
| 86 | print("git subtree pull failed.") | ||
| 87 | return 2 | ||
| 88 | print(f"Merged {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/.") | ||
| 89 | return 0 | ||
| 90 | |||
| 91 | |||
| 92 | if __name__ == "__main__": | ||
| 93 | sys.stdout.reconfigure(errors="replace") | ||
| 94 | sys.exit(main()) | ||
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..1d7174e77 100644 --- a/scripts/vs_layout_census.py +++ b/scripts/vs_layout_census.py | |||
| @@ -31,6 +31,7 @@ sys.path.insert(0, os.path.join(ROOT, "scripts")) | |||
| 31 | import fssm_unpack # noqa: E402 | 31 | import fssm_unpack # noqa: E402 |
| 32 | import pal_stages # noqa: E402 | 32 | import pal_stages # noqa: E402 |
| 33 | import shader_disasm # noqa: E402 | 33 | import shader_disasm # noqa: E402 |
| 34 | from report_paths import same_report_path # noqa: E402 | ||
| 34 | import shader_ir # noqa: E402 | 35 | import shader_ir # noqa: E402 |
| 35 | from vs_input_survey import (FETCH_CALL, MBCNT, PARAM_EXPORT, POS0_EXPORT, PRIM_EXPORT, SENDMSG, # noqa: E402 | 36 | from vs_input_survey import (FETCH_CALL, MBCNT, PARAM_EXPORT, POS0_EXPORT, PRIM_EXPORT, SENDMSG, # noqa: E402 |
| 36 | read_before_write) | 37 | read_before_write) |
| @@ -87,10 +88,9 @@ def payloads_of(dxbc_path): | |||
| 87 | for i, blob in enumerate(blobs)] | 88 | for i, blob in enumerate(blobs)] |
| 88 | 89 | ||
| 89 | 90 | ||
| 90 | def survey(dxbc_dir, disasm_fn=None, limit=None): | 91 | def load_index(dxbc_dir): |
| 91 | """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" | 92 | """(stage by stem, stems in index order) from <dxbc>/index.json.""" |
| 92 | index_path = os.path.join(dxbc_dir, "index.json") | 93 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: |
| 93 | with open(index_path, encoding="utf-8") as f: | ||
| 94 | index = json.load(f) | 94 | index = json.load(f) |
| 95 | if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): | 95 | 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") | 96 | raise ValueError("index.json is not a list of shader entries") |
| @@ -102,6 +102,26 @@ def survey(dxbc_dir, disasm_fn=None, limit=None): | |||
| 102 | if stem not in stages: | 102 | if stem not in stages: |
| 103 | names.append(stem) | 103 | names.append(stem) |
| 104 | stages[stem] = e.get("stage") | 104 | stages[stem] = e.get("stage") |
| 105 | return stages, names | ||
| 106 | |||
| 107 | |||
| 108 | def input_paths(dxbc_dir): | ||
| 109 | """Every file the census may read: index.json, then each indexed container and its disasm/<stem>.s listing. | ||
| 110 | An index that cannot be read names no more; survey() reports it.""" | ||
| 111 | paths = [os.path.join(dxbc_dir, "index.json")] | ||
| 112 | try: | ||
| 113 | _stages, names = load_index(dxbc_dir) | ||
| 114 | except (OSError, ValueError): | ||
| 115 | return paths | ||
| 116 | for name in names: | ||
| 117 | paths.append(os.path.join(dxbc_dir, name + ".dxbc")) | ||
| 118 | paths.append(os.path.join(dxbc_dir, "disasm", name + ".s")) | ||
| 119 | return paths | ||
| 120 | |||
| 121 | |||
| 122 | def survey(dxbc_dir, disasm_fn=None, limit=None): | ||
| 123 | """The census over <dxbc>: counts by stage, hardware id, markers and VS entry VGPRs.""" | ||
| 124 | stages, names = load_index(dxbc_dir) | ||
| 105 | if limit is not None: | 125 | if limit is not None: |
| 106 | names = names[:limit] | 126 | names = names[:limit] |
| 107 | 127 | ||
| @@ -186,9 +206,15 @@ def main(argv=None): | |||
| 186 | ap.add_argument("--limit", type=int, help="stop after this many containers (index order)") | 206 | ap.add_argument("--limit", type=int, help="stop after this many containers (index order)") |
| 187 | a = ap.parse_args(argv) | 207 | a = ap.parse_args(argv) |
| 188 | index_path = os.path.join(a.dxbc, "index.json") | 208 | 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): | 209 | if a.json: |
| 190 | print(f"vs_layout_census: error: --json would overwrite the input {index_path}", file=sys.stderr) | 210 | # Refuse before survey(): it reads the whole corpus and runs llvm-mc for every unlisted payload. |
| 191 | return 2 | 211 | if os.path.isdir(a.json): |
| 212 | print(f"vs_layout_census: error: --json {a.json} is a directory, not a JSON file", file=sys.stderr) | ||
| 213 | return 2 | ||
| 214 | for path in input_paths(a.dxbc): | ||
| 215 | if same_report_path(a.json, path): | ||
| 216 | print(f"vs_layout_census: error: --json would overwrite the input {path}", file=sys.stderr) | ||
| 217 | return 2 | ||
| 192 | try: | 218 | try: |
| 193 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) | 219 | r = survey(a.dxbc, disasm_fn=default_disasm, limit=a.limit) |
| 194 | except (OSError, ValueError) as e: | 220 | except (OSError, ValueError) as e: |
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index 3a875af4b..8734cb6b5 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 |
| @@ -38,7 +38,8 @@ Only when your shell has not set them already (`-DryRun` prints the final list): | |||
| 38 | | `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | | 38 | | `LEONIDA_PIPELINE_CACHE_BYTES` | `4294967296` | pipeline cache size limit | |
| 39 | | `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup | | 39 | | `LEONIDA_STARTUP_CACHE_CHECKPOINTS` | `1` | save the pipeline cache during startup | |
| 40 | | `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\pipeline-cache` | one warmed cache shared by every build you boot | | 40 | | `LEONIDA_PIPELINE_CACHE_DIR` | `<out>\pipeline-cache` | one warmed cache shared by every build you boot | |
| 41 | | `LEONIDA_PEEK` / `_SECONDS` | `0x7446510,0x98f828c` / `5` | game state and session state (low dword), the two numbers every RESULT reports | | 41 | | `LEONIDA_PIPELINE_JOURNAL_SEED_DIR` | `pipeline_cache.d` beside `gta6rt.exe`, when it exists | the journal `gta6rt --precompile-pipelines` fills there when it runs without `LEONIDA_PIPELINE_CACHE_DIR`, read-only, so its pipelines are not compiled again. Not set when the boot's own journal (`<cache folder>\pipeline_cache.d`, or beside `gta6rt.exe` when the cache folder is empty) is that folder or one holds the other, compared through Windows' final paths (so a junction, symbolic link, substituted or mapped drive, 8.3 name or `\\?\` / `\\.\` prefix counts as the same folder), or when the cache folder is a relative path. `LEONIDA_PIPELINE_JOURNAL_SEED_DIR=` (empty) turns the seed off. If the runtime still logs `[rt] d3d12: invalid or overlapping compute journal directories; journal disabled`, set it so. On NVIDIA, run the pre-compile with the same `LEONIDA_DEVICE_FAULT` as the boot (this script sets `1`): the diagnostics config is part of the journal's file names | |
| 42 | | `LEONIDA_PEEK` / `_SECONDS` | the game-state and session-state RVAs from `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (measured locally, not kept here; unset: no peek) / `5` | game state and session state (low dword), the two numbers every RESULT reports | | ||
| 42 | | `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps | | 43 | | `LEONIDA_DEVICE_FAULT` | `1` | on device loss: `VK_EXT_device_fault` info, checkpoints, last replay steps | |
| 43 | | `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | | 44 | | `LEONIDA_KEYBOARD_PAD` | `always` (with an input script) | keyboard as a pad even unfocused, so the script's presses arrive | |
| 44 | | `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | | 45 | | `LEONIDA_CAPTURE_EVERY` / `_LIMIT` | `60` / `40` | a swapchain read-back every 60 presents, at most 40 | |
| @@ -68,12 +69,21 @@ 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 | 69 | frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00 |
| 69 | ``` | 70 | ``` |
| 70 | 71 | ||
| 71 | `-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The digest holds counts and | 72 | `-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 | 73 | 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"). | 74 | Several records can describe one loss. A driver can also report loss without any address records. |
| 74 | 75 | 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 | 76 | ([AGENTS.md](../../AGENTS.md), "No game data"). |
| 76 | screen waiting for A), `d` after A. `docs/linux_proton.md` (the same stages apply natively) | 77 | |
| 78 | How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing | ||
| 79 | screen waiting for A), `d` after A. | ||
| 80 | |||
| 81 | **Changed: the states need two variables now.** The script used to set `LEONIDA_PEEK` to the game-state and | ||
| 82 | session-state RVAs by default. Those addresses of the retail executable are no longer kept in the repository, so set | ||
| 83 | `LEONIDA_GAME_STATE_RVA` and `LEONIDA_SESSION_STATE_RVA` (hex, measured locally) in the shell before the boot. | ||
| 84 | Without them the script warns, sets no `LEONIDA_PEEK`, and the `states:` line and the RESULT show `game=? | ||
| 85 | session=?`. A `LEONIDA_PEEK` of your own still works for the log, but the digest reads only the two RVAs those | ||
| 86 | 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". | 87 | section 2 has the healthy sequence with times and section 3 "which blank do you have". |
| 78 | 88 | ||
| 79 | ## One game at a time | 89 | ## One game at a time |
| @@ -91,3 +101,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 | | 101 | | `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 | 102 | ||
| 93 | Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). | 103 | Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). |
| 104 | |||
| 105 | ## Recover a stack from a manually mapped image | ||
| 106 | |||
| 107 | When the exception stack stops inside the mapped executable, run `mapped_stack.py` on the existing | ||
| 108 | private dump. Supply the exact PE from the crashing build and an x64 CDB from Debugging Tools for | ||
| 109 | Windows. If CDB is on your PATH, omit `--cdb`. The optional `--symbols` takes one local directory | ||
| 110 | containing the matching runtime images and PDBs. | ||
| 111 | |||
| 112 | ```powershell | ||
| 113 | 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" | ||
| 114 | ``` | ||
| 115 | |||
| 116 | The command derives the mapping base, including a relocated base, by locating a unique captured | ||
| 117 | instruction window in an executable section of the supplied PE. It checks for a file-backed x64 | ||
| 118 | unwind entry at the exception RIP and compares captured bytes from the first header page and that | ||
| 119 | function's unwind metadata when available. | ||
| 120 | A small dump can establish a local code match only. Use the original image even if another build | ||
| 121 | has the same function. Exit-only snapshots, faults outside the supplied image, leaf functions | ||
| 122 | without unwind entries, and missing, patched or ambiguous instruction windows cannot establish | ||
| 123 | this stack. | ||
| 124 | |||
| 125 | CDB reads the exception context and uses the disk image's unwind data to recover callers. The | ||
| 126 | script makes a temporary copy of the PE beside the dump under the debugger alias `leonida_mapped`. | ||
| 127 | It disables network symbols and writes private frame rows to a new `mapped-stack.txt` beside the | ||
| 128 | dump. Use `--output` for a different new file. A successful walk recovers at least one caller and | ||
| 129 | can stop when later stack memory or module information is missing. Keep dumps and reports outside | ||
| 130 | the checkout and share only the outcome and frame count. | ||
| 131 | |||
| 132 | Run the synthetic regression tests with `py -3 -I tests\test_mapped_stack.py`. To include the | ||
| 133 | 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..801867f11 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 | ||
| @@ -97,7 +101,7 @@ | |||
| 97 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv | 101 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name first -Seconds 200 -GameDir D:\GTA6pkg -Shaders E:\leonida-work\shaders\spirv |
| 98 | 102 | ||
| 99 | .EXAMPLE | 103 | .EXAMPLE |
| 100 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=0x7446510,0x75e8eb0,0x75e8ea0,0x9844898" | 104 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -Name stall -Seconds 90 -Stacks 40,80 "LEONIDA_PEEK=<rva>,<rva>" |
| 101 | 105 | ||
| 102 | .EXAMPLE | 106 | .EXAMPLE |
| 103 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first | 107 | powershell -NoProfile -File scripts\windows-boot\boot.ps1 -DigestOnly -Name first |
| @@ -118,6 +122,7 @@ param( | |||
| 118 | [switch]$NoCapture, | 122 | [switch]$NoCapture, |
| 119 | [switch]$NoInput, | 123 | [switch]$NoInput, |
| 120 | [string[]]$ExtraArgs = @(), | 124 | [string[]]$ExtraArgs = @(), |
| 125 | [switch]$FirstRunUi, | ||
| 121 | [string]$Python = "", | 126 | [string]$Python = "", |
| 122 | [int]$SummaryLines = 40, | 127 | [int]$SummaryLines = 40, |
| 123 | [int]$LockWaitSeconds = 3600, | 128 | [int]$LockWaitSeconds = 3600, |
| @@ -234,7 +239,8 @@ $defaults = [ordered]@{ | |||
| 234 | LEONIDA_PIPELINE_CACHE_BYTES = "4294967296" | 239 | LEONIDA_PIPELINE_CACHE_BYTES = "4294967296" |
| 235 | LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1" | 240 | LEONIDA_STARTUP_CACHE_CHECKPOINTS = "1" |
| 236 | LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache") | 241 | LEONIDA_PIPELINE_CACHE_DIR = (Join-Path $OutDir "pipeline-cache") |
| 237 | LEONIDA_PEEK = "0x7446510,0x98f828c" # game state, session state (low dword) | 242 | # LEONIDA_PEEK: the game-state and session-state RVAs (measured locally, not kept in the repository) when |
| 243 | # LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA name them; see below. | ||
| 238 | LEONIDA_PEEK_SECONDS = "5" | 244 | LEONIDA_PEEK_SECONDS = "5" |
| 239 | LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints) | 245 | LEONIDA_DEVICE_FAULT = "1" # device-loss report (VK_EXT_device_fault, checkpoints) |
| 240 | LEONIDA_CAPTURE_EVERY = "60" | 246 | LEONIDA_CAPTURE_EVERY = "60" |
| @@ -243,6 +249,14 @@ $defaults = [ordered]@{ | |||
| 243 | DISABLE_VULKAN_OBS_CAPTURE = "1" | 249 | DISABLE_VULKAN_OBS_CAPTURE = "1" |
| 244 | } | 250 | } |
| 245 | if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } | 251 | if ($InputScript) { $defaults["LEONIDA_KEYBOARD_PAD"] = "always" } |
| 252 | $gameStateRva = "$env:LEONIDA_GAME_STATE_RVA".ToLowerInvariant() -replace '^0x', '' | ||
| 253 | $sessionStateRva = "$env:LEONIDA_SESSION_STATE_RVA".ToLowerInvariant() -replace '^0x', '' | ||
| 254 | if ($gameStateRva -and $sessionStateRva) { $defaults["LEONIDA_PEEK"] = "0x$gameStateRva,0x$sessionStateRva" } | ||
| 255 | else { | ||
| 256 | # The two RVAs were built in until they were taken out of the repository; say so rather than report "?" silently. | ||
| 257 | Write-Warning ("LEONIDA_GAME_STATE_RVA and LEONIDA_SESSION_STATE_RVA are not both set: no LEONIDA_PEEK by default, " + | ||
| 258 | "so the RESULT game and session states read '?' (scripts/windows-boot/README.md)") | ||
| 259 | } | ||
| 246 | # Per-run values: always this script's (from its parameters), whatever the shell has. | 260 | # Per-run values: always this script's (from its parameters), whatever the shell has. |
| 247 | $perRun = [ordered]@{ | 261 | $perRun = [ordered]@{ |
| 248 | LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) | 262 | LEONIDA_CAPTURE = $(if ($NoCapture) { "" } else { $Capture }) |
| @@ -267,8 +281,78 @@ foreach ($pair in $EnvPairs) { | |||
| 267 | $bootEnv[$Matches[1]] = $Matches[2] | 281 | $bootEnv[$Matches[1]] = $Matches[2] |
| 268 | } | 282 | } |
| 269 | if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] } | 283 | if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] } |
| 284 | # The journal `gta6rt --precompile-pipelines` fills beside gta6rt.exe (when it runs without LEONIDA_PIPELINE_CACHE_DIR) | ||
| 285 | # is read here as the runtime's read-only seed (LEONIDA_PIPELINE_JOURNAL_SEED_DIR, docs/d3d12_vulkan.md), so the pipelines | ||
| 286 | # it holds are not compiled again in the boot's own cache folder. Only when this shell or -SetEnv/KEY= did not decide, and | ||
| 287 | # when the two journals are distinct: the runtime turns its journal off for a seed that is, holds or sits in its writable | ||
| 288 | # journal (pipeline_cache_journal.h, resolve_roots). A relative cache folder is resolved by the runtime against its own | ||
| 289 | # working folder, so it gets no seed here; a name that cannot be resolved gets none either, rather than a stop. | ||
| 290 | if (-not $bootEnv.Contains("LEONIDA_PIPELINE_JOURNAL_SEED_DIR")) { | ||
| 291 | # Windows' final path of a folder (GetFinalPathNameByHandle) sees through junctions, symbolic links, substituted | ||
| 292 | # and mapped drives, short 8.3 names and the \\?\ and \\.\ prefixes, as the runtime's std::filesystem checks do. | ||
| 293 | # A folder that does not exist yet is named from its deepest existing parent. Without the helper (a compile error, | ||
| 294 | # a restricted session), the comparison falls back to the spelled paths. | ||
| 295 | function Get-FinalFolderPath([string]$path) { | ||
| 296 | $plain = ($path -replace '^\\\\[?.]\\UNC\\', '\\' -replace '^\\\\[?.]\\', '').TrimEnd('\', '/') | ||
| 297 | try { | ||
| 298 | if (-not ('LeonidaFinalPath' -as [type])) { | ||
| 299 | Add-Type -ErrorAction Stop -TypeDefinition @' | ||
| 300 | using System; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; | ||
| 301 | public static class LeonidaFinalPath { | ||
| 302 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] | ||
| 303 | static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr sa, uint disposition, uint flags, IntPtr template); | ||
| 304 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] | ||
| 305 | static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder buffer, uint length, uint flags); | ||
| 306 | public static string Of(string path) { | ||
| 307 | // No access asked, all sharing, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS (needed to open a folder). | ||
| 308 | using (SafeFileHandle h = CreateFileW(path, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) { | ||
| 309 | if (h.IsInvalid) return null; | ||
| 310 | StringBuilder b = new StringBuilder(32768); | ||
| 311 | uint n = GetFinalPathNameByHandleW(h, b, (uint)b.Capacity, 0); | ||
| 312 | return (n == 0 || n >= b.Capacity) ? null : b.ToString(); | ||
| 313 | } | ||
| 314 | } | ||
| 315 | } | ||
| 316 | '@ | ||
| 317 | } | ||
| 318 | $existing = $path.TrimEnd('\', '/'); $tail = @() | ||
| 319 | while ($existing -and -not [System.IO.Directory]::Exists($existing)) { | ||
| 320 | $tail = @([System.IO.Path]::GetFileName($existing)) + $tail | ||
| 321 | $existing = [System.IO.Path]::GetDirectoryName($existing) | ||
| 322 | } | ||
| 323 | if (-not $existing) { return $plain } | ||
| 324 | $final = [LeonidaFinalPath]::Of($existing) | ||
| 325 | if (-not $final) { return $plain } | ||
| 326 | $final = $final -replace '^\\\\\?\\UNC\\', '\\' -replace '^\\\\\?\\', '' | ||
| 327 | foreach ($part in $tail) { $final = [System.IO.Path]::Combine($final, $part) } | ||
| 328 | return $final.TrimEnd('\', '/') | ||
| 329 | } catch { return $plain } | ||
| 330 | } | ||
| 331 | $seed = $null | ||
| 332 | try { | ||
| 333 | $runtimeFull = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($RuntimeDir) | ||
| 334 | $precompiled = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($runtimeFull, "pipeline_cache.d")).TrimEnd('\', '/') | ||
| 335 | if (Test-Path -LiteralPath $precompiled -PathType Container) { | ||
| 336 | $cacheDir = $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | ||
| 337 | $ownJournal = $null | ||
| 338 | if (-not $cacheDir) { $ownJournal = $precompiled } # the runtime then keeps its journal beside gta6rt.exe | ||
| 339 | elseif ($cacheDir -match '^([A-Za-z]:[\\/]|[\\/]{2})') { | ||
| 340 | $ownJournal = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($cacheDir, "pipeline_cache.d")).TrimEnd('\', '/') | ||
| 341 | } | ||
| 342 | if ($ownJournal) { | ||
| 343 | $a = Get-FinalFolderPath $ownJournal | ||
| 344 | $b = Get-FinalFolderPath $precompiled | ||
| 345 | $c = [System.StringComparison]::OrdinalIgnoreCase | ||
| 346 | $overlap = $a.Equals($b, $c) -or $a.StartsWith($b + '\', $c) -or $b.StartsWith($a + '\', $c) | ||
| 347 | if (-not $overlap) { $seed = $precompiled } | ||
| 348 | } | ||
| 349 | } | ||
| 350 | } catch { $seed = $null } | ||
| 351 | if ($seed) { $bootEnv["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = $seed } | ||
| 352 | } | ||
| 270 | 353 | ||
| 271 | $gameArgs = @("--run", $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs | 354 | $launchMode = if ($FirstRunUi) { "--first-run-ui" } else { "--run" } |
| 355 | $gameArgs = @($launchMode, $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs | ||
| 272 | $argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " | 356 | $argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " |
| 273 | 357 | ||
| 274 | if (-not $DigestOnly) { | 358 | if (-not $DigestOnly) { |
| @@ -378,10 +462,31 @@ $valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)' | |||
| 378 | $states = New-Object System.Collections.Generic.List[string] | 462 | $states = New-Object System.Collections.Generic.List[string] |
| 379 | $lastPeek = ""; $prevPair = "" | 463 | $lastPeek = ""; $prevPair = "" |
| 380 | $presentOk = 0; $presentFailed = 0; $presses = 0 | 464 | $presentOk = 0; $presentFailed = 0; $presses = 0 |
| 381 | $shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string] | 465 | $shaderLine = "" |
| 466 | $deviceLost = $false | ||
| 467 | # VkDeviceFaultAddressTypeEXT, in enum order. Keep only counters, including one bucket for newer types. | ||
| 468 | $faultNames = @("NONE", "READ_INVALID", "WRITE_INVALID", "EXECUTE_INVALID", "INSTRUCTION_POINTER_UNKNOWN", | ||
| 469 | "INSTRUCTION_POINTER_INVALID", "INSTRUCTION_POINTER_FAULT", "OTHER") | ||
| 470 | $faultCounts = New-Object 'long[]' $faultNames.Length | ||
| 471 | $faultAddressRx = [regex]'^\s*\[rt\] device-fault: address\[\d+\] type=(-?\d+)\s+address=' | ||
| 382 | $wrapped = 0 | 472 | $wrapped = 0 |
| 383 | if (Test-Path -LiteralPath $LogFile) { | 473 | if (Test-Path -LiteralPath $LogFile) { |
| 384 | foreach ($line in [System.IO.File]::ReadLines($LogFile)) { | 474 | foreach ($line in [System.IO.File]::ReadLines($LogFile)) { |
| 475 | if ($line.Contains("[rt] device-fault:")) { | ||
| 476 | if ($line.Contains("[rt] device-fault: VK_ERROR_DEVICE_LOST from ")) { $deviceLost = $true } | ||
| 477 | $m = $faultAddressRx.Match($line) | ||
| 478 | if ($m.Success) { | ||
| 479 | $type = 0 | ||
| 480 | if (-not [int]::TryParse($m.Groups[1].Value, [ref]$type) -or $type -lt 0 -or $type -ge ($faultNames.Length - 1)) { | ||
| 481 | $type = $faultNames.Length - 1 | ||
| 482 | } | ||
| 483 | $faultCounts[$type]++ | ||
| 484 | } | ||
| 485 | continue | ||
| 486 | } | ||
| 487 | if ($line.Contains("[rt] vulkan: the device was lost (") -or $line.Contains("VK_ERROR_DEVICE_LOST")) { | ||
| 488 | $deviceLost = $true | ||
| 489 | } | ||
| 385 | if ($line.Contains("XboxPresentation::PresentX")) { | 490 | if ($line.Contains("XboxPresentation::PresentX")) { |
| 386 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } | 491 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } |
| 387 | continue | 492 | continue |
| @@ -393,8 +498,8 @@ if (Test-Path -LiteralPath $LogFile) { | |||
| 393 | $game = "?"; $session = "?" | 498 | $game = "?"; $session = "?" |
| 394 | foreach ($v in $valRx.Matches($m.Groups[2].Value)) { | 499 | foreach ($v in $valRx.Matches($m.Groups[2].Value)) { |
| 395 | $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value | 500 | $rva = $v.Groups[1].Value; $val = $v.Groups[2].Value |
| 396 | if ($rva -eq "7446510") { $game = $val } | 501 | if ($gameStateRva -and $rva -eq $gameStateRva) { $game = $val } |
| 397 | elseif ($rva -eq "98f828c" -and $val -ne "?") { | 502 | 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 | 503 | $low = $val.PadLeft(16, '0').Substring(8).TrimStart('0') # the session state is the low dword |
| 399 | $session = $(if ($low) { $low } else { "0" }) | 504 | $session = $(if ($low) { $low } else { "0" }) |
| 400 | } | 505 | } |
| @@ -409,8 +514,6 @@ if (Test-Path -LiteralPath $LogFile) { | |||
| 409 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } | 514 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } |
| 410 | continue | 515 | continue |
| 411 | } | 516 | } |
| 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() } | 517 | 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++ } | 518 | if ($line.Contains("wrapped V#")) { $wrapped++ } |
| 416 | } | 519 | } |
| @@ -442,8 +545,16 @@ $digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated- | |||
| 442 | $digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })") | 545 | $digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })") |
| 443 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") | 546 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") |
| 444 | $digest.Add("input: $presses presses logged") | 547 | $digest.Add("input: $presses presses logged") |
| 445 | $digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })") | 548 | $faultClasses = @(for ($i = 0; $i -lt $faultNames.Length; $i++) { |
| 446 | foreach ($f in $faults) { $digest.Add(" $f") } | 549 | if ($faultCounts[$i]) { "$($faultNames[$i])=$($faultCounts[$i])" } |
| 550 | }) | ||
| 551 | $faultText = "none" | ||
| 552 | if ($deviceLost -or $faultClasses.Count) { | ||
| 553 | $loss = if ($deviceLost) { "device loss reported" } else { "no device-loss marker" } | ||
| 554 | $records = if ($faultClasses.Count) { $faultClasses -join ", " } else { "none" } | ||
| 555 | $faultText = "$loss, address records: $records" | ||
| 556 | } | ||
| 557 | $digest.Add("faults: $faultText") | ||
| 447 | if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } | 558 | if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } |
| 448 | $digest.Add("frames: $capText") | 559 | $digest.Add("frames: $capText") |
| 449 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") | 560 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") |
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() | ||