diff options
| author | Tauwni <102470988+Tauwni@users.noreply.github.com> | 2026-11-26 04:01:08 +0100 |
|---|---|---|
| committer | Tauwni <102470988+Tauwni@users.noreply.github.com> | 2026-11-26 04:01:08 +0100 |
| commit | 5af6cd3d69dc69baec78aa06fc418fc4bcbf83b5 (patch) | |
| tree | 4529bc04eac714e9c393fb1085bb1d67169843c0 /scripts | |
| parent | 459cbb9b19193ffd4fbb18442497bc885de8c728 (diff) | |
| parent | 7f3d0095a2d51892bc7048f24505c37168f25c34 (diff) | |
Merge remote-tracking branch 'origin/main' into gpu-results-m3
# Conflicts:
# docs/gpu_test_results.md
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/audit_shader4_regs.py | 19 | ||||
| -rw-r--r-- | scripts/check_compute_journal_overlay.py | 111 | ||||
| -rw-r--r-- | scripts/compute_workers_win.py | 194 | ||||
| -rw-r--r-- | scripts/corpus_watch.py | 199 | ||||
| -rw-r--r-- | scripts/first_look.ps1 | 10 | ||||
| -rwxr-xr-x | scripts/run_game_wine.sh | 293 | ||||
| -rw-r--r-- | scripts/run_gpu_tests.py | 31 | ||||
| -rw-r--r-- | scripts/run_semantic_tests.py | 155 | ||||
| -rw-r--r-- | scripts/translate_pipeline_compute.py | 208 | ||||
| -rw-r--r-- | scripts/vs_layout_census.py | 40 |
10 files changed, 1164 insertions, 96 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py index 59aff3bc6..50fc5500e 100644 --- a/scripts/audit_shader4_regs.py +++ b/scripts/audit_shader4_regs.py | |||
| @@ -263,8 +263,8 @@ def detect_wave64(insns): | |||
| 263 | 263 | ||
| 264 | 264 | ||
| 265 | def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), limit=None, *, report_path=None): | 265 | 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: | 266 | if limit is not None and limit < 1: |
| 267 | raise ValueError("limit must be non-negative") | 267 | raise ValueError("limit must be at least 1") |
| 268 | parent = os.path.dirname(os.path.realpath(disasm_dir)) | 268 | parent = os.path.dirname(os.path.realpath(disasm_dir)) |
| 269 | fssm_dir = fssm_dir or os.path.join(parent, "fssm") | 269 | fssm_dir = fssm_dir or os.path.join(parent, "fssm") |
| 270 | dxbc_dir = dxbc_dir or parent | 270 | dxbc_dir = dxbc_dir or parent |
| @@ -395,16 +395,25 @@ def print_report(rep): | |||
| 395 | print(f" {v:6d} {k}") | 395 | print(f" {v:6d} {k}") |
| 396 | 396 | ||
| 397 | 397 | ||
| 398 | def shader_count(text): | ||
| 399 | """--limit: at least 1; 0 used to mean an audit of nothing that still printed a zero report.""" | ||
| 400 | try: | ||
| 401 | value = int(text, 0) | ||
| 402 | except ValueError: | ||
| 403 | raise argparse.ArgumentTypeError("must be at least 1") from None | ||
| 404 | if value < 1: | ||
| 405 | raise argparse.ArgumentTypeError("must be at least 1") | ||
| 406 | return value | ||
| 407 | |||
| 408 | |||
| 398 | def main(argv=None): | 409 | def main(argv=None): |
| 399 | ap = argparse.ArgumentParser(description="Audit CS/MS/GS RSRC2/PSV0 headers and read-before-write registers.") | 410 | 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") | 411 | 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)") | 412 | 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>/..)") | 413 | 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") | 414 | 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") | 415 | ap.add_argument("--limit", type=shader_count, default=None, help="stop after N .s files (at least 1)") |
| 405 | a = ap.parse_args(argv) | 416 | 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 | 417 | # 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 | 418 | # 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. | 419 | # "(missing fssm)" and print a report that looks right. |
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/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/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/run_game_wine.sh b/scripts/run_game_wine.sh new file mode 100755 index 000000000..ce01b0a07 --- /dev/null +++ b/scripts/run_game_wine.sh | |||
| @@ -0,0 +1,293 @@ | |||
| 1 | #!/usr/bin/env bash | ||
| 2 | # Run the retail game once under Wine on Linux: `gta6rt.exe --run <exe>` with the startup and D3D12 traces on, sound | ||
| 3 | # off, a pinned Vulkan device, a hard time limit and full teardown, then print counts only | ||
| 4 | # (tools/game_run_summary.py). Headless on a private kwin_wayland session by default, or on the current display with | ||
| 5 | # --visible. `scripts/run_game_wine.sh --help` lists the inputs; docs/linux_proton.md has the requirements. | ||
| 6 | # | ||
| 7 | # The run folder's logs can quote what the title prints: they stay on this machine. Share the printed summary. | ||
| 8 | set -u | ||
| 9 | |||
| 10 | ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) | ||
| 11 | SELF=$ROOT/scripts/run_game_wine.sh | ||
| 12 | |||
| 13 | usage() { | ||
| 14 | cat <<'EOF' | ||
| 15 | Usage: scripts/run_game_wine.sh --build DIR --exe FILE --game-dir DIR --out DIR [options] [-- gta6rt arguments] | ||
| 16 | |||
| 17 | Runs `gta6rt.exe --run <exe>` once under Wine, headless or on this display, with sound off, a pinned Vulkan device, | ||
| 18 | a time limit and the startup and D3D12 traces on, then prints counts only. Every path comes from here or from the | ||
| 19 | environment; nothing is assumed. | ||
| 20 | |||
| 21 | Inputs: | ||
| 22 | --build DIR a build folder holding gta6rt.exe and gta6rt_tls_host.dll, or a checkout: its runtime/ is | ||
| 23 | cross-built with clang-cl and xwin (XWIN_DIR must be set) into --build-dir first | ||
| 24 | --build-dir DIR where a checkout is built (default <checkout>/runtime/build/wine-game-run) | ||
| 25 | --exe FILE the game executable (or LEONIDA_GAME_EXE) | ||
| 26 | --game-dir DIR the package folder; the working folder (or LEONIDA_GAME_DIR) | ||
| 27 | --shaders DIR the translated shader library (or LEONIDA_SHADERS; "none" leaves it unset) | ||
| 28 | --out DIR the run folder; it must not hold a run yet (logs, traces, saves, overlay, summary) | ||
| 29 | --prefix DIR the Wine prefix (or WINEPREFIX; default <out>/prefix) | ||
| 30 | |||
| 31 | Options: | ||
| 32 | --seconds N hard time limit of the run (default 600; SIGTERM, then SIGKILL 10 s later) | ||
| 33 | --visible open the window on the current DISPLAY instead of a private headless session | ||
| 34 | --device VID:DID the Vulkan device, as MESA_VK_DEVICE_SELECT=VID:DID! (e.g. 1002:744c); without it Mesa picks | ||
| 35 | --screenshot-every S capture the game window into <out>/shots every S seconds (needs ImageMagick's import and | ||
| 36 | xprop); the shots are game content and stay local | ||
| 37 | --lock FILE the lock that allows one run at a time (default $XDG_RUNTIME_DIR/leonida-run-game-wine.lock, | ||
| 38 | or <out>/run.lock without XDG_RUNTIME_DIR) | ||
| 39 | -h, --help this text | ||
| 40 | -- ARGS further gta6rt arguments, after the fixed ones | ||
| 41 | |||
| 42 | Environment: | ||
| 43 | WINE the wine to use (default wine on PATH; for Proton, its files/bin/wine) | ||
| 44 | LEONIDA_* passed to the runtime unchanged (LEONIDA_INPUT_SCRIPT, LEONIDA_ARENA_MB, ...); the launcher | ||
| 45 | sets LEONIDA_AUDIO=silent, and LEONIDA_D3D12=vulkan, LEONIDA_RUMBLE=0 and LEONIDA_SAVE_DIR | ||
| 46 | unless they are set | ||
| 47 | |||
| 48 | Headless needs kwin_wayland (with Xwayland) and dbus-run-session: Xvfb has no DRI3, so RADV cannot present there. | ||
| 49 | Sound: Wine's audio drivers are disabled, PulseAudio, PipeWire and ALSA point at nothing, and the runtime serves its | ||
| 50 | silent output endpoint (LEONIDA_AUDIO=silent). | ||
| 51 | EOF | ||
| 52 | } | ||
| 53 | |||
| 54 | die() { echo "run_game_wine.sh: $*" >&2; exit 2; } | ||
| 55 | |||
| 56 | if [ "${1:-}" = --inner ]; then | ||
| 57 | # ---- inside the session: DISPLAY is kwin's Xwayland (headless) or the caller's display (--visible) ---- | ||
| 58 | RUN=$2; BUILD=$3; LIMIT=$4; SHOT_EVERY=$5 | ||
| 59 | shift 5 | ||
| 60 | WINE=${WINE:-wine} | ||
| 61 | WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver | ||
| 62 | [ -x "$WINESERVER" ] || WINESERVER=wineserver | ||
| 63 | unset WAYLAND_DISPLAY # Wine's X11 driver on Xwayland, never its Wayland driver | ||
| 64 | { | ||
| 65 | echo "display: ${DISPLAY:-none}" | ||
| 66 | if command -v xdpyinfo >/dev/null 2>&1; then | ||
| 67 | echo "DRI3 extension: $(xdpyinfo 2>/dev/null | grep -c -w DRI3)" | ||
| 68 | fi | ||
| 69 | } >> "$RUN/session.txt" | ||
| 70 | mkdir -p "$WINEPREFIX" | ||
| 71 | "$WINESERVER" -p | ||
| 72 | # 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 | ||
| 74 | SHOTS= | ||
| 75 | if [ "$SHOT_EVERY" != 0 ]; then | ||
| 76 | mkdir -p "$RUN/shots" | ||
| 77 | ( | ||
| 78 | n=0 | ||
| 79 | while sleep "$SHOT_EVERY"; do | ||
| 80 | n=$((n + 1)) | ||
| 81 | # Wine names the window's class after the executable: gta6rt.exe. | ||
| 82 | for id in $(xprop -root _NET_CLIENT_LIST 2>/dev/null | grep -o '0x[0-9a-f]*'); do | ||
| 83 | if xprop -id "$id" WM_CLASS 2>/dev/null | grep -qi 'gta6rt'; then | ||
| 84 | import -window "$id" "$RUN/shots/$(printf '%04d' "$n").png" 2>/dev/null | ||
| 85 | break | ||
| 86 | fi | ||
| 87 | done | ||
| 88 | done | ||
| 89 | ) & | ||
| 90 | SHOTS=$! | ||
| 91 | fi | ||
| 92 | cd "$GAME_DIR" || { echo 2 > "$RUN/exit_code"; exit 0; } | ||
| 93 | t0=$(date +%s) | ||
| 94 | timeout -k 10 "$LIMIT" "$WINE" "$BUILD/gta6rt.exe" --run "Z:$GAME_EXE" --game-dir "Z:$GAME_DIR" \ | ||
| 95 | --overlay "Z:$RUN/overlay" --trace "Z:$RUN/boot.jsonl" --trace-d3d12 "$@" \ | ||
| 96 | </dev/null > "$RUN/stdout.log" 2> "$RUN/stderr.log" | ||
| 97 | code=$? | ||
| 98 | echo "$(( $(date +%s) - t0 ))" > "$RUN/seconds" | ||
| 99 | echo "$code" > "$RUN/exit_code" | ||
| 100 | [ -n "$SHOTS" ] && kill "$SHOTS" 2>/dev/null | ||
| 101 | "$WINESERVER" -k 2>/dev/null | ||
| 102 | exit 0 | ||
| 103 | fi | ||
| 104 | |||
| 105 | # ---- arguments ---- | ||
| 106 | SRC= BUILD_DIR= OUT= PREFIX=${WINEPREFIX:-} LIMIT=600 VISIBLE=0 DEVICE= SHOT_EVERY=0 LOCK= | ||
| 107 | EXE=${LEONIDA_GAME_EXE:-} GAME=${LEONIDA_GAME_DIR:-} SHADERS=${LEONIDA_SHADERS:-} | ||
| 108 | need() { [ $# -ge 2 ] && [ -n "$2" ] || die "$1 needs a value (see --help)"; } | ||
| 109 | while [ $# -gt 0 ]; do | ||
| 110 | case $1 in | ||
| 111 | -h|--help) usage; exit 0 ;; | ||
| 112 | --build) need "$@"; SRC=$2; shift 2 ;; | ||
| 113 | --build-dir) need "$@"; BUILD_DIR=$2; shift 2 ;; | ||
| 114 | --exe) need "$@"; EXE=$2; shift 2 ;; | ||
| 115 | --game-dir) need "$@"; GAME=$2; shift 2 ;; | ||
| 116 | --shaders) need "$@"; SHADERS=$2; shift 2 ;; | ||
| 117 | --out) need "$@"; OUT=$2; shift 2 ;; | ||
| 118 | --prefix) need "$@"; PREFIX=$2; shift 2 ;; | ||
| 119 | --seconds) need "$@"; LIMIT=$2; shift 2 ;; | ||
| 120 | --visible) VISIBLE=1; shift ;; | ||
| 121 | --device) need "$@"; DEVICE=$2; shift 2 ;; | ||
| 122 | --screenshot-every) need "$@"; SHOT_EVERY=$2; shift 2 ;; | ||
| 123 | --lock) need "$@"; LOCK=$2; shift 2 ;; | ||
| 124 | --) shift; break ;; | ||
| 125 | *) die "unknown argument: $1 (see --help)" ;; | ||
| 126 | esac | ||
| 127 | done | ||
| 128 | |||
| 129 | [ -n "$SRC" ] || die "--build is required: a build folder with gta6rt.exe, or a checkout" | ||
| 130 | [ -n "$EXE" ] || die "--exe (or LEONIDA_GAME_EXE) is required: the game executable" | ||
| 131 | [ -n "$GAME" ] || die "--game-dir (or LEONIDA_GAME_DIR) is required: the package folder" | ||
| 132 | [ -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" | ||
| 134 | 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 | ||
| 136 | 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'" | ||
| 138 | fi | ||
| 139 | [ -f "$EXE" ] || die "no game executable at $EXE" | ||
| 140 | [ -d "$GAME" ] || die "no package folder at $GAME" | ||
| 141 | if [ "$SHADERS" != none ]; then | ||
| 142 | SHADERS=${SHADERS#Z:} | ||
| 143 | [ -d "$SHADERS" ] || die "no shader library at $SHADERS" | ||
| 144 | fi | ||
| 145 | EXE=$(readlink -f "$EXE"); GAME=$(readlink -f "$GAME"); SRC=$(readlink -f "$SRC") | ||
| 146 | |||
| 147 | # ---- what the host needs ---- | ||
| 148 | WINE=${WINE:-wine} | ||
| 149 | missing=() | ||
| 150 | command -v "$WINE" >/dev/null 2>&1 || missing+=("$WINE (Wine)") | ||
| 151 | for t in timeout flock setsid python3; do command -v $t >/dev/null 2>&1 || missing+=("$t"); done | ||
| 152 | if [ "$VISIBLE" = 1 ]; then | ||
| 153 | [ -n "${DISPLAY:-}" ] || die "--visible needs DISPLAY: run it from the desktop session (an X11 or Xwayland display)" | ||
| 154 | else | ||
| 155 | for t in kwin_wayland dbus-run-session Xwayland; do command -v $t >/dev/null 2>&1 || missing+=("$t"); done | ||
| 156 | fi | ||
| 157 | if [ "$SHOT_EVERY" != 0 ]; then | ||
| 158 | for t in import xprop; do command -v $t >/dev/null 2>&1 || missing+=("$t (for --screenshot-every)"); done | ||
| 159 | fi | ||
| 160 | if [ ${#missing[@]} -gt 0 ]; then | ||
| 161 | echo "run_game_wine.sh: missing: ${missing[*]}" >&2 | ||
| 162 | [ "$VISIBLE" = 1 ] || echo " headless runs need kwin_wayland with Xwayland: Xvfb has no DRI3, so RADV cannot" \ | ||
| 163 | "present there. Install KWin, or run on your display with --visible." >&2 | ||
| 164 | exit 2 | ||
| 165 | fi | ||
| 166 | |||
| 167 | # ---- the run folder ---- | ||
| 168 | mkdir -p "$OUT" || die "cannot create $OUT" | ||
| 169 | OUT=$(readlink -f "$OUT") | ||
| 170 | RUN=$OUT | ||
| 171 | if [ -e "$RUN/boot.jsonl" ] || [ -e "$RUN/stderr.log" ]; then | ||
| 172 | die "$RUN already holds a run; name a new --out" | ||
| 173 | fi | ||
| 174 | |||
| 175 | # ---- the runtime: a build folder as is, or a checkout built here ---- | ||
| 176 | if [ -f "$SRC/gta6rt.exe" ]; then | ||
| 177 | BUILD=$SRC | ||
| 178 | elif [ -f "$SRC/runtime/CMakeLists.txt" ]; then | ||
| 179 | [ -n "${XWIN_DIR:-}" ] || die "building $SRC needs XWIN_DIR (an xwin splat, docs/linux.md); or pass a build folder" | ||
| 180 | BUILD=$(readlink -f -m "${BUILD_DIR:-$SRC/runtime/build/wine-game-run}") | ||
| 181 | mkdir -p "$BUILD" | ||
| 182 | echo "building the runtime into $BUILD" | ||
| 183 | if [ ! -f "$BUILD/CMakeCache.txt" ]; then | ||
| 184 | cmake -S "$SRC/runtime" -B "$BUILD" --toolchain "$SRC/runtime/cmake/clang-cl-xwin.cmake" \ | ||
| 185 | -DCMAKE_BUILD_TYPE=RelWithDebInfo > "$RUN/configure.log" 2>&1 \ | ||
| 186 | || die "configure failed (see $RUN/configure.log)" | ||
| 187 | fi | ||
| 188 | cmake --build "$BUILD" --parallel --target gta6rt gta6rt_tls_host > "$RUN/build.log" 2>&1 \ | ||
| 189 | || die "build failed (see $RUN/build.log)" | ||
| 190 | else | ||
| 191 | die "$SRC is neither a build folder with gta6rt.exe nor a checkout with runtime/CMakeLists.txt" | ||
| 192 | fi | ||
| 193 | [ -f "$BUILD/gta6rt_tls_host.dll" ] || die "no gta6rt_tls_host.dll next to $BUILD/gta6rt.exe" | ||
| 194 | |||
| 195 | # ---- 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}} | ||
| 197 | LOCK=${LOCK:-$RUN/run.lock} | ||
| 198 | exec 9>"$LOCK" || die "cannot open the lock $LOCK" | ||
| 199 | flock -n 9 || die "another run holds $LOCK" | ||
| 200 | mkdir -p "$RUN/overlay" "$RUN/saves" | ||
| 201 | |||
| 202 | # ---- environment: private session, sound off, pinned device ---- | ||
| 203 | export GAME_EXE=$EXE GAME_DIR=$GAME | ||
| 204 | unset LEONIDA_GAME_EXE LEONIDA_GAME_DIR # launcher inputs; LEONIDA_GAME_DIR also switches the runtime's tests | ||
| 205 | export WINE | ||
| 206 | export XDG_RUNTIME_DIR=$RUN/xdg | ||
| 207 | rm -rf "$XDG_RUNTIME_DIR"; mkdir -p -m 700 "$XDG_RUNTIME_DIR" | ||
| 208 | export XDG_CONFIG_HOME=$RUN/session/config XDG_DATA_HOME=$RUN/session/data XDG_CACHE_HOME=$RUN/session/cache \ | ||
| 209 | XDG_STATE_HOME=$RUN/session/state | ||
| 210 | mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_STATE_HOME" | ||
| 211 | unset WAYLAND_DISPLAY WAYLAND_SOCKET DBUS_SESSION_BUS_ADDRESS | ||
| 212 | if [ "$VISIBLE" = 1 ]; then | ||
| 213 | if command -v xdpyinfo >/dev/null 2>&1 && ! xdpyinfo >/dev/null 2>&1; then | ||
| 214 | die "--visible: cannot open display $DISPLAY (XAUTHORITY=${XAUTHORITY:-unset})" | ||
| 215 | fi | ||
| 216 | else | ||
| 217 | unset DISPLAY XAUTHORITY | ||
| 218 | fi | ||
| 219 | export QT_QPA_PLATFORM=offscreen | ||
| 220 | if [ -n "$DEVICE" ]; then | ||
| 221 | 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. | ||
| 223 | for n in /sys/class/drm/renderD*; do | ||
| 224 | [ "$(cat "$n/device/vendor" 2>/dev/null):$(cat "$n/device/device" 2>/dev/null)" = "0x${DEVICE%%:*}:0x${DEVICE#*:}" ] \ | ||
| 225 | && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} | ||
| 226 | done | ||
| 227 | else | ||
| 228 | unset MESA_VK_DEVICE_SELECT | ||
| 229 | echo "warning: no --device: Mesa picks the Vulkan device (pass --device VID:DID to pin it)" >&2 | ||
| 230 | fi | ||
| 231 | export WINEPREFIX=${PREFIX:-$RUN/prefix} WINEDEBUG=${WINEDEBUG:--all} | ||
| 232 | export WINEDLLOVERRIDES="winedbg.exe=d;winemenubuilder.exe=d;winepulse.drv=d;winealsa.drv=d;wineoss.drv=d;winecoreaudio.drv=d" | ||
| 233 | export PULSE_SERVER=unix:/nonexistent PIPEWIRE_REMOTE=/nonexistent ALSA_CONFIG_PATH=/dev/null SDL_AUDIODRIVER=dummy | ||
| 234 | export LEONIDA_AUDIO=silent | ||
| 235 | export LEONIDA_D3D12=${LEONIDA_D3D12:-vulkan} | ||
| 236 | export LEONIDA_RUMBLE=${LEONIDA_RUMBLE:-0} | ||
| 237 | export LEONIDA_SAVE_DIR=${LEONIDA_SAVE_DIR:-Z:$RUN/saves} | ||
| 238 | if [ "$SHADERS" = none ]; then | ||
| 239 | unset LEONIDA_SHADERS | ||
| 240 | else | ||
| 241 | export LEONIDA_SHADERS=Z:$SHADERS | ||
| 242 | fi | ||
| 243 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" | ||
| 244 | |||
| 245 | WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver | ||
| 246 | [ -x "$WINESERVER" ] || WINESERVER=wineserver | ||
| 247 | SESSION_PID= | ||
| 248 | teardown() { | ||
| 249 | "$WINESERVER" -k 2>/dev/null | ||
| 250 | if [ -n "$SESSION_PID" ] && kill -0 "$SESSION_PID" 2>/dev/null; then | ||
| 251 | pkill -TERM -s "$SESSION_PID" 2>/dev/null; sleep 2; pkill -KILL -s "$SESSION_PID" 2>/dev/null | ||
| 252 | fi | ||
| 253 | rm -rf "$XDG_RUNTIME_DIR" | ||
| 254 | } | ||
| 255 | trap teardown EXIT | ||
| 256 | trap 'exit 130' INT TERM HUP | ||
| 257 | |||
| 258 | # The session command with its arguments baked in (kwin takes one program path). | ||
| 259 | { | ||
| 260 | echo '#!/bin/sh' | ||
| 261 | printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" | ||
| 262 | for a in "$@"; do printf ' %q' "$a"; done | ||
| 263 | echo | ||
| 264 | } > "$RUN/inner.sh" | ||
| 265 | chmod +x "$RUN/inner.sh" | ||
| 266 | |||
| 267 | T0=$(date +%s) | ||
| 268 | # setsid: Wine (and kwin, Xwayland and the private D-Bus when headless) form one session that teardown ends as a | ||
| 269 | # whole, and never the user's desktop. | ||
| 270 | if [ "$VISIBLE" = 1 ]; then | ||
| 271 | setsid "$RUN/inner.sh" > "$RUN/session.log" 2>&1 9>&- & | ||
| 272 | else | ||
| 273 | setsid dbus-run-session -- kwin_wayland --virtual --xwayland --socket leonida-run-game-wine --width 1920 \ | ||
| 274 | --height 1080 --no-lockscreen --no-global-shortcuts --exit-with-session "$RUN/inner.sh" \ | ||
| 275 | > "$RUN/session.log" 2>&1 9>&- & | ||
| 276 | fi | ||
| 277 | SESSION_PID=$! | ||
| 278 | # 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 & | ||
| 280 | WATCH=$! | ||
| 281 | wait "$SESSION_PID" | ||
| 282 | pkill -P "$WATCH" 2>/dev/null; kill "$WATCH" 2>/dev/null | ||
| 283 | teardown; SESSION_PID= | ||
| 284 | T1=$(date +%s) | ||
| 285 | |||
| 286 | echo "== $(tr '\n' ';' < "$RUN/session.txt" 2>/dev/null | sed 's/;$//')" | ||
| 287 | if [ ! -f "$RUN/exit_code" ]; then | ||
| 288 | echo "the run did not start or the session ended early ($((T1 - T0)) s); see $RUN/session.log" >&2 | ||
| 289 | exit 3 | ||
| 290 | fi | ||
| 291 | python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" | ||
| 292 | echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." | ||
| 293 | exit 0 | ||
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 8ba62104d..f87290ec6 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py | |||
| @@ -678,7 +678,8 @@ def check_clip_half(raw_path: str, want_b: float, want_a: float) -> tuple[bool, | |||
| 678 | # Fixtures run by another harness, which needs what these tools do not have (a D3D12 device, the layer's root | 678 | # Fixtures run by another harness, which needs what these tools do not have (a D3D12 device, the layer's root |
| 679 | # arguments and code base). They are still assembled and translated here, so a translator regression shows, but no | 679 | # arguments and code base). They are still assembled and translated here, so a translator regression shows, but no |
| 680 | # checker runs them: the test program that owns them judges them. | 680 | # checker runs them: the test program that owns them judges them. |
| 681 | OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "vs_m15": "d3d12_translated_draw_test", | 681 | OTHER_HARNESS = {"ps_m15": "d3d12_translated_draw_test", "ps_m15_dual": "d3d12_translated_draw_test", |
| 682 | "vs_m15": "d3d12_translated_draw_test", | ||
| 682 | "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", | 683 | "ps_m2": "d3d12_m2_textured_test", "vs_m2": "d3d12_m2_textured_test", "ps_m2_uoff": "d3d12_m2_textured_test", |
| 683 | "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test", | 684 | "ps_m2_literal": "d3d12_m2_textured_test", "ps_m2_array": "d3d12_m2_formats_test", |
| 684 | "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", | 685 | "ps_m3": "d3d12_m3_frame_test", "vs_m3": "d3d12_m3_frame_test", |
| @@ -1100,6 +1101,7 @@ def run_suite(a, work: str) -> int: | |||
| 1100 | elif name == "cs_tbuffer_store": | 1101 | elif name == "cs_tbuffer_store": |
| 1101 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) | 1102 | # tbuffer_store_format_*: the instruction's format, words measured natively on a Radeon 680M (the .asm header) |
| 1102 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) | 1103 | problem = tbuffer_store_test(a.build, spirv_dir, cs_env) |
| 1104 | results.append((name, not problem, problem or "128/128 dumped words exact")) | ||
| 1103 | elif name == "cs_fmt_d16_xyz": | 1105 | elif name == "cs_fmt_d16_xyz": |
| 1104 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) | 1106 | # d16_xyz / d16_xy typed-buffer loads and d16_xyz stores (cs_fmt_d16_xyz.asm header) |
| 1105 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) | 1107 | problem = fmt_d16_xyz_test(a.build, spirv_dir, cs_env) |
| @@ -1209,8 +1211,8 @@ def run_suite(a, work: str) -> int: | |||
| 1209 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", | 1211 | "cs_w64x_branch", "cs_w64x_ballot", "cs_w64x_wg128_branches", "cs_w64x_lds_raw", |
| 1210 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", | 1212 | "cs_w64x_lds_war", "cs_w64x_partial", "cs_w64x_sbarrier", "cs_w64x_load_ballot_load", |
| 1211 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", | 1213 | "cs_w64x_mask_reuse", "cs_w64x_mask_reuse2", "cs_w64x_chain_barrier", "cs_barrier_divergent", |
| 1212 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", | 1214 | "cs_bpermute32", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_barrier_early_end", |
| 1213 | "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", | 1215 | "cs_barrier_loop", "cs_w64x_andn2_exec", "cs_w64x_saveexec_b64", "cs_w64x_cmp_sdst", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_w32_andn2_exec", |
| 1214 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): | 1216 | "cs_mask_vgpr_exec", "cs_w32_exec_computed", "cs_w64_exec_computed"): |
| 1215 | cs_dump_wants = { | 1217 | cs_dump_wants = { |
| 1216 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], | 1218 | "cs_store": [0x400080FF, 0xE00003FF, 0x3C004000, 0xEEEEEEEE, 0x40003C00, 0xBC003800, 0x40FF8000, 0x3FF00000], |
| @@ -1249,6 +1251,12 @@ def run_suite(a, work: str) -> int: | |||
| 1249 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) | 1251 | # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) |
| 1250 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, | 1252 | "cs_lds_xchg64_ext": [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, |
| 1251 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], | 1253 | 0x40302010, 0x70500705, 0x3FC00000, 0x80000000], |
| 1254 | # ds_wrxchg2_rtn_b32's pair cases and ds_wrxchg2st64_rtn_b32 | ||
| 1255 | # (cs_w32_wrxchg2_ext.asm / cs_w32_wrxchg2st64.asm headers) | ||
| 1256 | "cs_w32_wrxchg2_ext": [0x77777777, 0x88880008, 0x99990009, 0xDEADBEEF, | ||
| 1257 | 0xAAAAAAAA, 0xBBBBBBBB, 0x12341234, 0x56785678], | ||
| 1258 | "cs_w32_wrxchg2st64": [0x33333333, 0x44444444, 0x55550005, 0x66660006, | ||
| 1259 | 0xB0B00084, 0xB0B00088, 0xB0B00140, 0xB0B002C0], | ||
| 1252 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) | 1260 | # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) |
| 1253 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, | 1261 | "cs_lds_atomics_ext": [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, |
| 1254 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], | 1262 | 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700], |
| @@ -1295,6 +1303,7 @@ def run_suite(a, work: str) -> int: | |||
| 1295 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], | 1303 | "cs_w64x_lds_war": [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031], |
| 1296 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], | 1304 | "cs_w64x_partial": [40, 40, 528, 0, 0, 532, 539, 524820], |
| 1297 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave | 1305 | "cs_w64x_partial_scmp": [0, 1, 0, 1, 1, 1, 1, 0], # s_cmp mask, -1 in a partial wave |
| 1306 | "cs_w64x_partial_swizzle": [508, 523, 0, 0, 528, 0, 531, 0], # swizzle from a missing lane: 0 | ||
| 1298 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 | 1307 | "cs_w32_partial_scmp": [0, 1, 1, 0, 1, 1, 1, 1], # the same in a 20-thread wave32 |
| 1299 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) | 1308 | # ds_permute_b32 in a 20-thread wave32: a never-launched source lane sends nothing (.asm header) |
| 1300 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], | 1309 | "cs_w32_partial_permute": [0, 29, 127, 0, 1, 0, 134, 113], |
| @@ -1330,21 +1339,23 @@ def run_suite(a, work: str) -> int: | |||
| 1330 | # as check.py does, where the device has none | 1339 | # as check.py does, where the device has none |
| 1331 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were | 1340 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were |
| 1332 | # translated with --wave64-emulate and run on any subgroup size. | 1341 | # translated with --wave64-emulate and run on any subgroup size. |
| 1333 | # cs_w64x_partial and cs_w64x_partial_scmp (40-thread groups) can't have full subgroups: they ask for | 1342 | # cs_w64x_partial, cs_w64x_partial_scmp and cs_w64x_partial_swizzle (40-thread groups) can't have full |
| 1334 | # size 64 without them. | 1343 | # subgroups: they ask for size 64 without them. With LEONIDA_W64_EMULATE=1 they ask for 32, the width the |
| 1344 | # emulation is for, as check.py's partial_wave_test does. RADV defaults compute to 64, and there | ||
| 1345 | # cs_w64x_partial_swizzle came out right even before its missing-lane reads were fixed; at 32 it did not. | ||
| 1335 | emulated = w64_emulated() | 1346 | emulated = w64_emulated() |
| 1336 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp") | 1347 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") |
| 1337 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", | 1348 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", |
| 1338 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", | 1349 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", |
| 1339 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", | 1350 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", |
| 1340 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1351 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1341 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", | 1352 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", |
| 1342 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", | 1353 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", |
| 1343 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", | 1354 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", |
| 1344 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", | 1355 | "cs_dpp_ops", "cs_dpp_bound", "cs_dpp_bank", "cs_dpp_fi", "cs_dpp_cmp", "cs_w32_andn2_exec", |
| 1345 | "cs_w32_exec_computed") and not emulated and not partial | 1356 | "cs_w32_exec_computed") and not emulated and not partial |
| 1346 | if partial and not emulated: | 1357 | if partial: |
| 1347 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="64") | 1358 | cs_env = dict(os.environ, VKC_SUBGROUP_SIZE="32" if emulated else "64") |
| 1348 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) | 1359 | if name in WAVE32_LANE_DUMPS: # 32 lanes even without index.json, as check.py requests (#774) |
| 1349 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) | 1360 | cs_env = dict(os.environ, **WAVE32_LANE_ENV) |
| 1350 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) | 1361 | rc, msg = run_cmd([vk_compute, spv, "1", "dump"] + (["--require-wave64"] if wave64 else []), env=cs_env) |
| @@ -1366,7 +1377,7 @@ def run_suite(a, work: str) -> int: | |||
| 1366 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, | 1377 | ok, detail = judge_cs_dump(rc, msg, want, wave64=wave64, partial=partial, emulated=emulated, |
| 1367 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", | 1378 | hexwords=name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_lds_u8_d16", |
| 1368 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1379 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1369 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_signed_zero_nan")) | 1380 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_signed_zero_nan")) |
| 1370 | if ok and None in want: | 1381 | if ok and None in want: |
| 1371 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) | 1382 | unjudged = ", ".join(str(i) for i, w in enumerate(want) if w is None) |
| 1372 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" | 1383 | detail += f" (words {unjudged} not judged on this device: UNJUDGED_WORDS in check.py)" |
diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 03e0ddab4..514e78133 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py | |||
| @@ -36,10 +36,56 @@ import re | |||
| 36 | import subprocess | 36 | import subprocess |
| 37 | import sys | 37 | import sys |
| 38 | import tempfile | 38 | import tempfile |
| 39 | import threading | ||
| 39 | import time | 40 | import time |
| 40 | 41 | ||
| 41 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 | 42 | MAX_TIMEOUT_SECONDS = 24 * 60 * 60 |
| 42 | 43 | ||
| 44 | # The child processes running right now: on SIGINT / Ctrl+C, the main thread terminates them so no orphans linger. | ||
| 45 | _active_processes = set() | ||
| 46 | _processes_lock = threading.Lock() | ||
| 47 | |||
| 48 | |||
| 49 | def _register_process(proc): | ||
| 50 | with _processes_lock: | ||
| 51 | _active_processes.add(proc) | ||
| 52 | |||
| 53 | |||
| 54 | def _unregister_process(proc): | ||
| 55 | with _processes_lock: | ||
| 56 | _active_processes.discard(proc) | ||
| 57 | |||
| 58 | |||
| 59 | def _kill_process_tree(proc): | ||
| 60 | if proc is None: | ||
| 61 | return | ||
| 62 | if os.name == "nt": | ||
| 63 | try: | ||
| 64 | subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], | ||
| 65 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | ||
| 66 | except OSError: | ||
| 67 | pass | ||
| 68 | try: | ||
| 69 | proc.kill() | ||
| 70 | except OSError: | ||
| 71 | pass | ||
| 72 | |||
| 73 | |||
| 74 | def _terminate_active_processes(): | ||
| 75 | with _processes_lock: | ||
| 76 | procs = list(_active_processes) | ||
| 77 | for p in procs: | ||
| 78 | try: | ||
| 79 | p.terminate() | ||
| 80 | except OSError: | ||
| 81 | pass | ||
| 82 | for p in procs: | ||
| 83 | _kill_process_tree(p) | ||
| 84 | try: | ||
| 85 | p.wait(timeout=0.2) | ||
| 86 | except (subprocess.TimeoutExpired, OSError): | ||
| 87 | pass | ||
| 88 | |||
| 43 | # The child runs the module through unittest's own program and writes the result to a file, so the count of tests | 89 | # The child runs the module through unittest's own program and writes the result to a file, so the count of tests |
| 44 | # comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1 | 90 | # comes from the result object and nothing the module writes can change it. The exit codes are unittest's own: 1 |
| 45 | # when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so | 91 | # when a test failed, 5 when nothing ran at all, 0 otherwise. The module is left unset, as `python -m unittest` leaves it, so |
| @@ -113,22 +159,35 @@ def run_module(directory, module, verbose, timeout=None): | |||
| 113 | with tempfile.TemporaryDirectory() as scratch: | 159 | with tempfile.TemporaryDirectory() as scratch: |
| 114 | count_path = os.path.join(scratch, "count.json") | 160 | count_path = os.path.join(scratch, "count.json") |
| 115 | env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) | 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, | ||
| 163 | text=True, errors="replace") | ||
| 164 | _register_process(proc) | ||
| 116 | try: | 165 | try: |
| 117 | p = subprocess.run(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, | 166 | stdout, stderr = proc.communicate(timeout=timeout) |
| 118 | text=True, errors="replace", timeout=timeout) | 167 | except subprocess.TimeoutExpired: |
| 119 | except subprocess.TimeoutExpired as exc: | 168 | _kill_process_tree(proc) |
| 169 | stdout, stderr = proc.communicate() | ||
| 120 | # TimeoutExpired retains bytes even when text=True. | 170 | # TimeoutExpired retains bytes even when text=True. |
| 121 | parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) | 171 | parts = [chunk.decode(locale.getpreferredencoding(False), errors="replace") if isinstance(chunk, bytes) |
| 122 | else chunk for chunk in (exc.stdout, exc.stderr) if chunk] | 172 | else chunk for chunk in (stdout, stderr) if chunk] |
| 123 | out = "".join(parts) | 173 | out = "".join(parts) |
| 124 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" | 174 | return 1, 0, out + f"\nTIMED OUT after {timeout:g} s: {module}\n" |
| 175 | except BaseException: | ||
| 176 | _kill_process_tree(proc) | ||
| 177 | try: | ||
| 178 | proc.wait(timeout=0.5) | ||
| 179 | except (subprocess.TimeoutExpired, OSError): | ||
| 180 | pass | ||
| 181 | raise | ||
| 182 | finally: | ||
| 183 | _unregister_process(proc) | ||
| 125 | count = read_count(count_path) | 184 | count = read_count(count_path) |
| 126 | out = p.stdout + p.stderr | 185 | out = stdout + stderr |
| 127 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the | 186 | # Discover imports every package initializer, but an empty one has no tests to run. It is included in the |
| 128 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. | 187 | # module list so parallel runs see TestCase classes when there are any; without them, it is not a failure. |
| 129 | if p.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in p.stderr: | 188 | if proc.returncode == 5 and count == 0 and module.endswith(".__init__") and "NO TESTS RAN" in stderr: |
| 130 | return 0, 0, out | 189 | return 0, 0, out |
| 131 | return p.returncode, count, out | 190 | return proc.returncode, count, out |
| 132 | 191 | ||
| 133 | 192 | ||
| 134 | def main(argv=None): | 193 | def main(argv=None): |
| @@ -147,26 +206,76 @@ def main(argv=None): | |||
| 147 | print(f"no {a.pattern} files in {directory}") | 206 | print(f"no {a.pattern} files in {directory}") |
| 148 | return 1 | 207 | return 1 |
| 149 | if a.jobs <= 1: | 208 | if a.jobs <= 1: |
| 209 | cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, | ||
| 210 | "-p", a.pattern, *(["-v"] if a.verbose else [])] | ||
| 211 | proc = subprocess.Popen(cmd) | ||
| 212 | _register_process(proc) | ||
| 213 | start_time = time.monotonic() | ||
| 150 | try: | 214 | try: |
| 151 | return subprocess.call([sys.executable, "-m", "unittest", "discover", "-s", directory, | 215 | while True: |
| 152 | "-p", a.pattern, *(["-v"] if a.verbose else [])], timeout=a.timeout) | 216 | try: |
| 217 | return proc.wait(timeout=0.2) | ||
| 218 | except subprocess.TimeoutExpired: | ||
| 219 | if a.timeout is not None and time.monotonic() - start_time >= a.timeout: | ||
| 220 | raise | ||
| 153 | except subprocess.TimeoutExpired: | 221 | except subprocess.TimeoutExpired: |
| 154 | # Inherited stdout/stderr have already emitted any partial test output. | 222 | _kill_process_tree(proc) |
| 155 | print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) | 223 | print(f"TIMED OUT after {a.timeout:g} s: unittest discover in {directory}", file=sys.stderr) |
| 156 | return 1 | 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) | ||
| 157 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. | 238 | # Largest files first: they tend to run longest, and one started last would set the wall time alone. |
| 158 | modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) | 239 | modules.sort(key=lambda m: -os.path.getsize(module_path(directory, m))) |
| 159 | start, total, failed = time.monotonic(), 0, [] | 240 | start, total, failed = time.monotonic(), 0, [] |
| 160 | with concurrent.futures.ThreadPoolExecutor(a.jobs) as pool: | 241 | pool = concurrent.futures.ThreadPoolExecutor(a.jobs) |
| 161 | jobs = {pool.submit(run_module, directory, m, a.verbose, a.timeout): m for m in modules} | 242 | jobs = {} |
| 162 | for job in concurrent.futures.as_completed(jobs): | 243 | try: |
| 163 | code, ran, out = job.result() | 244 | for m in modules: |
| 164 | total += ran | 245 | jobs[pool.submit(run_module, directory, m, a.verbose, a.timeout)] = m |
| 165 | if code: | 246 | pending = set(jobs) |
| 166 | failed.append(jobs[job]) | 247 | while pending: |
| 167 | print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) | 248 | done, _ = concurrent.futures.wait(pending, timeout=0.2, return_when=concurrent.futures.FIRST_COMPLETED) |
| 168 | elif a.verbose: | 249 | for job in done: |
| 169 | print(f"==== {jobs[job]}\n{out}", flush=True) | 250 | pending.remove(job) |
| 251 | code, ran, out = job.result() | ||
| 252 | total += ran | ||
| 253 | if code: | ||
| 254 | failed.append(jobs[job]) | ||
| 255 | print(f"==== FAILED: {jobs[job]}\n{out}", flush=True) | ||
| 256 | elif a.verbose: | ||
| 257 | print(f"==== {jobs[job]}\n{out}", flush=True) | ||
| 258 | except KeyboardInterrupt: | ||
| 259 | for job in jobs: | ||
| 260 | job.cancel() | ||
| 261 | try: | ||
| 262 | pool.shutdown(wait=False, cancel_futures=True) | ||
| 263 | except TypeError: | ||
| 264 | pool.shutdown(wait=False) | ||
| 265 | _terminate_active_processes() | ||
| 266 | print("interrupted", file=sys.stderr) | ||
| 267 | return 130 | ||
| 268 | except BaseException: | ||
| 269 | for job in jobs: | ||
| 270 | job.cancel() | ||
| 271 | try: | ||
| 272 | pool.shutdown(wait=False, cancel_futures=True) | ||
| 273 | except TypeError: | ||
| 274 | pool.shutdown(wait=False) | ||
| 275 | _terminate_active_processes() | ||
| 276 | raise | ||
| 277 | else: | ||
| 278 | pool.shutdown(wait=True) | ||
| 170 | took = time.monotonic() - start | 279 | took = time.monotonic() - start |
| 171 | summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" | 280 | summary = f"{len(modules)} files, {total} tests, {len(failed)} files failed in {took:.0f} s with {a.jobs} jobs" |
| 172 | print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) | 281 | print(summary + (": " + ", ".join(sorted(failed)) if failed else "")) |
| @@ -183,4 +292,8 @@ if __name__ == "__main__": | |||
| 183 | sys.stdout.reconfigure(errors="replace") | 292 | sys.stdout.reconfigure(errors="replace") |
| 184 | except (AttributeError, ValueError, OSError): | 293 | except (AttributeError, ValueError, OSError): |
| 185 | pass | 294 | pass |
| 186 | sys.exit(main()) | 295 | try: |
| 296 | sys.exit(main()) | ||
| 297 | except KeyboardInterrupt: | ||
| 298 | print("interrupted", file=sys.stderr) | ||
| 299 | sys.exit(130) | ||
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_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: |