diff options
| author | Zack <zmasi21@gmail.com> | 2026-11-28 13:59:35 -0800 |
|---|---|---|
| committer | Zack <zmasi21@gmail.com> | 2026-11-28 13:59:35 -0800 |
| commit | 06e5327291abf9ab43e85c6e08ab2bb4f3a7ac2d (patch) | |
| tree | ee03ea999daa390dcf669fe3d83a701d9c354b07 /scripts | |
| parent | f77b4d80d0483027a978511d1d77d58a9523e43a (diff) | |
| parent | c7753ed98a56677f10e34078b37eab0540e190ec (diff) | |
Merge origin/main into fix/rdna2spirv-f16-interp-computed-ij
Diffstat (limited to 'scripts')
| -rw-r--r-- | scripts/audit_shader4_regs.py | 62 | ||||
| -rw-r--r-- | scripts/carve_all.ps1 | 26 | ||||
| -rw-r--r-- | scripts/check_no_game_data.py | 20 | ||||
| -rw-r--r-- | scripts/ci_expected_failures.py | 3 | ||||
| -rw-r--r-- | scripts/dev.py | 11 | ||||
| -rwxr-xr-x | scripts/fetch_vkd3d_proton.py | 1 | ||||
| -rw-r--r-- | scripts/launcher_python.sh | 40 | ||||
| -rwxr-xr-x | scripts/linux-boot/boot-digest.sh | 31 | ||||
| -rwxr-xr-x | scripts/linux-boot/boot-inner.sh | 117 | ||||
| -rwxr-xr-x | scripts/linux-boot/boot.sh | 77 | ||||
| -rwxr-xr-x | scripts/linux-boot/configure-worktree.sh | 51 | ||||
| -rwxr-xr-x | scripts/linux-boot/run-boot.sh | 30 | ||||
| -rw-r--r-- | scripts/meta_to_xml.ps1 | 23 | ||||
| -rw-r--r-- | scripts/port_ctl.py | 1 | ||||
| -rwxr-xr-x | scripts/run_game_wine.sh | 48 | ||||
| -rw-r--r-- | scripts/run_gpu_tests.py | 19 | ||||
| -rw-r--r-- | scripts/run_guest_scene.py | 5 | ||||
| -rwxr-xr-x | scripts/run_wine_session.sh | 18 | ||||
| -rw-r--r-- | scripts/run_wine_tests.py | 65 | ||||
| -rw-r--r-- | scripts/sync_victory.py | 1 | ||||
| -rw-r--r-- | scripts/vs_input_survey.py | 104 | ||||
| -rw-r--r-- | scripts/windows-boot/README.md | 42 | ||||
| -rw-r--r-- | scripts/windows-boot/boot.ps1 | 37 | ||||
| -rw-r--r-- | scripts/windows-boot/mapped_stack.py | 313 |
24 files changed, 1002 insertions, 143 deletions
diff --git a/scripts/audit_shader4_regs.py b/scripts/audit_shader4_regs.py index 50fc5500e..9f651fbe5 100644 --- a/scripts/audit_shader4_regs.py +++ b/scripts/audit_shader4_regs.py | |||
| @@ -11,15 +11,19 @@ Directory layout defaults match make_game.py / tools/rdna2spirv.py: | |||
| 11 | <disasm_dir>/../index.json (optional stage map; otherwise stage is inferred from filename prefix) | 11 | <disasm_dir>/../index.json (optional stage map; otherwise stage is inferred from filename prefix) |
| 12 | """ | 12 | """ |
| 13 | import argparse | 13 | import argparse |
| 14 | import errno | ||
| 14 | import json | 15 | import json |
| 15 | import os | 16 | import os |
| 16 | import re | 17 | import re |
| 17 | import struct | 18 | import struct |
| 18 | import sys | 19 | import sys |
| 20 | import tempfile | ||
| 19 | from collections import Counter | 21 | from collections import Counter |
| 20 | 22 | ||
| 21 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 23 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 22 | sys.path.insert(0, os.path.join(ROOT, "tools")) | 24 | sys.path.insert(0, os.path.join(ROOT, "tools")) |
| 25 | from file_mode import published_mode # noqa: E402 | ||
| 26 | from replace_retry import replace as replace_retry # noqa: E402 | ||
| 23 | from report_paths import same_report_path # noqa: E402 | 27 | from report_paths import same_report_path # noqa: E402 |
| 24 | import shader_ir # noqa: E402 | 28 | import shader_ir # noqa: E402 |
| 25 | from shader_meta import SGPR_RMW # noqa: E402 | 29 | from shader_meta import SGPR_RMW # noqa: E402 |
| @@ -64,13 +68,21 @@ def load_stage_map(disasm_dir, *, report_path=None): | |||
| 64 | for cand in candidates: | 68 | for cand in candidates: |
| 65 | if os.path.isfile(cand): | 69 | if os.path.isfile(cand): |
| 66 | try: | 70 | try: |
| 67 | with open(cand, encoding="utf-8") as _f: | 71 | with open(cand, encoding="utf-8-sig") as _f: |
| 68 | data = json.load(_f) | 72 | data = json.load(_f) |
| 69 | if isinstance(data, list): | 73 | if isinstance(data, list): |
| 70 | return {os.path.splitext(e["file"])[0]: e.get("stage", "?") for e in data if "file" in e} | 74 | return { |
| 75 | os.path.splitext(e["file"])[0]: e["stage"] if isinstance(e.get("stage"), str) else "?" | ||
| 76 | for e in data | ||
| 77 | if isinstance(e, dict) and isinstance(e.get("file"), str) | ||
| 78 | } | ||
| 71 | if isinstance(data, dict): | 79 | if isinstance(data, dict): |
| 72 | return {k: v.get("stage", "?") for k, v in data.items() if isinstance(v, dict)} | 80 | return { |
| 73 | except (OSError, ValueError, KeyError, TypeError): | 81 | k: v["stage"] if isinstance(v.get("stage"), str) else "?" |
| 82 | for k, v in data.items() | ||
| 83 | if isinstance(v, dict) | ||
| 84 | } | ||
| 85 | except (OSError, ValueError, KeyError, TypeError, RecursionError): | ||
| 74 | pass | 86 | pass |
| 75 | return {} | 87 | return {} |
| 76 | 88 | ||
| @@ -98,10 +110,14 @@ def read_psv0(dxbc_path): | |||
| 98 | off = struct.unpack_from("<I", d, 32 + 4 * k)[0] | 110 | off = struct.unpack_from("<I", d, 32 + 4 * k)[0] |
| 99 | if off + 8 <= len(d) and d[off:off + 4] == b"PSV0": | 111 | if off + 8 <= len(d) and d[off:off + 4] == b"PSV0": |
| 100 | plen = struct.unpack_from("<I", d, off + 4)[0] | 112 | plen = struct.unpack_from("<I", d, off + 4)[0] |
| 113 | if off + 8 + plen > len(d): | ||
| 114 | return None | ||
| 101 | p = d[off + 8:off + 8 + plen] | 115 | p = d[off + 8:off + 8 + plen] |
| 102 | if len(p) < 4: | 116 | if len(p) < 4: |
| 103 | return None | 117 | return None |
| 104 | rsize = struct.unpack_from("<I", p, 0)[0] | 118 | rsize = struct.unpack_from("<I", p, 0)[0] |
| 119 | if 4 + rsize > len(p): | ||
| 120 | return None | ||
| 105 | r = p[4:4 + rsize] | 121 | r = p[4:4 + rsize] |
| 106 | if len(r) < 48: | 122 | if len(r) < 48: |
| 107 | return {"rsize": rsize} | 123 | return {"rsize": rsize} |
| @@ -215,10 +231,13 @@ def rbw_registers(insns): | |||
| 215 | is_dual_dst = op.startswith("v_") and ( | 231 | is_dual_dst = op.startswith("v_") and ( |
| 216 | "_co_" in op or op.startswith(("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) | 232 | "_co_" in op or op.startswith(("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) |
| 217 | ) | 233 | ) |
| 234 | # The assembler's short form v_add_co_ci_u32 vD, src0, src1 (also sub/subrev) has VCC as its carry-out and | ||
| 235 | # carry-in and names neither: args[1] is src0, read, not a carry-out destination. | ||
| 236 | is_short_co_ci = op.endswith("_co_ci_u32") and len(args) == 3 | ||
| 218 | # Carry-out / scale-out forms write the VGPR and scalar mask first, even when they also take a carry-in source. | 237 | # Carry-out / scale-out forms write the VGPR and scalar mask first, even when they also take a carry-in source. |
| 219 | if is_lds_load: | 238 | if is_lds_load: |
| 220 | dsts, srcs = [], args | 239 | dsts, srcs = [], args |
| 221 | elif not is_no_dest and is_dual_dst and len(args) >= 2: | 240 | elif not is_no_dest and is_dual_dst and len(args) >= 2 and not is_short_co_ci: |
| 222 | dsts = args[:2] | 241 | dsts = args[:2] |
| 223 | srcs = args[2:] | 242 | srcs = args[2:] |
| 224 | elif is_no_dest: | 243 | elif is_no_dest: |
| @@ -370,6 +389,32 @@ def audit(disasm_dir, fssm_dir=None, dxbc_dir=None, stages=("cs", "ms", "gs"), l | |||
| 370 | return out | 389 | return out |
| 371 | 390 | ||
| 372 | 391 | ||
| 392 | def write_json(path, report): | ||
| 393 | """Atomically write LF-only JSON, preserving file permissions and cleaning up temp files on error.""" | ||
| 394 | target = os.path.abspath(path) | ||
| 395 | parent = os.path.dirname(target) or "." | ||
| 396 | os.makedirs(parent, exist_ok=True) | ||
| 397 | if os.path.isdir(target): | ||
| 398 | raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), path) | ||
| 399 | payload = (json.dumps(report, indent=2, allow_nan=False) + "\n").encode("utf-8") | ||
| 400 | fd, tmp_path = tempfile.mkstemp(prefix=".audit_shader4_regs_", suffix=".tmp", dir=parent) | ||
| 401 | try: | ||
| 402 | with os.fdopen(fd, "wb") as f: | ||
| 403 | f.write(payload) | ||
| 404 | os.chmod(tmp_path, published_mode(target)) | ||
| 405 | replace_retry(tmp_path, target) | ||
| 406 | except BaseException: | ||
| 407 | try: | ||
| 408 | os.chmod(tmp_path, 0o600) | ||
| 409 | except OSError: | ||
| 410 | pass | ||
| 411 | try: | ||
| 412 | os.unlink(tmp_path) | ||
| 413 | except OSError: | ||
| 414 | pass | ||
| 415 | raise | ||
| 416 | |||
| 417 | |||
| 373 | def print_report(rep): | 418 | def print_report(rep): |
| 374 | for st, rec in rep.items(): | 419 | for st, rec in rep.items(): |
| 375 | print(f"=== {st.upper()} ({rec['count']} shaders; wave64={rec['wave64_heuristic']}, wave32={rec['wave32_heuristic']}) ===") | 420 | print(f"=== {st.upper()} ({rec['count']} shaders; wave64={rec['wave64_heuristic']}, wave32={rec['wave32_heuristic']}) ===") |
| @@ -427,7 +472,7 @@ def main(argv=None): | |||
| 427 | print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) | 472 | print(f"ERROR: {label}{path}: not a folder", file=sys.stderr) |
| 428 | return 2 | 473 | return 2 |
| 429 | 474 | ||
| 430 | report_path = a.json_out if a.json_out and os.path.isfile(a.json_out) else None | 475 | report_path = a.json_out or None |
| 431 | try: | 476 | try: |
| 432 | rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit, report_path=report_path) | 477 | rep = audit(a.disasm_dir, fssm_dir=a.fssm, dxbc_dir=a.dxbc, limit=a.limit, report_path=report_path) |
| 433 | except ReportInputCollision as error: | 478 | except ReportInputCollision as error: |
| @@ -436,10 +481,7 @@ def main(argv=None): | |||
| 436 | print_report(rep) | 481 | print_report(rep) |
| 437 | if a.json_out: | 482 | if a.json_out: |
| 438 | try: | 483 | try: |
| 439 | os.makedirs(os.path.dirname(os.path.abspath(a.json_out)), exist_ok=True) | 484 | write_json(a.json_out, rep) |
| 440 | with open(a.json_out, "w", encoding="utf-8", newline="\n") as f: | ||
| 441 | json.dump(rep, f, indent=2) | ||
| 442 | f.write("\n") | ||
| 443 | except OSError as e: | 485 | except OSError as e: |
| 444 | print(f"ERROR: {a.json_out}: cannot write: {e.strerror or e}", file=sys.stderr) | 486 | print(f"ERROR: {a.json_out}: cannot write: {e.strerror or e}", file=sys.stderr) |
| 445 | return 1 | 487 | return 1 |
diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1 index e7de9e4d9..9442f5e08 100644 --- a/scripts/carve_all.ps1 +++ b/scripts/carve_all.ps1 | |||
| @@ -3,6 +3,14 @@ | |||
| 3 | param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) | 3 | param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) |
| 4 | $root = Split-Path $PSScriptRoot -Parent | 4 | $root = Split-Path $PSScriptRoot -Parent |
| 5 | $tool = Join-Path $root "tools\rpf9_carve.py" | 5 | $tool = Join-Path $root "tools\rpf9_carve.py" |
| 6 | if (-not (Test-Path -LiteralPath $Game -PathType Container)) { | ||
| 7 | throw "Game folder '$Game' does not exist or is not a directory." | ||
| 8 | } | ||
| 9 | $outFull = [IO.Path]::GetFullPath($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Out)) | ||
| 10 | if (Test-Path -LiteralPath $outFull -PathType Leaf) { | ||
| 11 | throw "Output path '$Out' is a file, not a directory." | ||
| 12 | } | ||
| 13 | [System.IO.Directory]::CreateDirectory($outFull) | Out-Null | ||
| 6 | # -Game may be relative or end in a separator; archive names are cut from a separator-ended prefix. | 14 | # -Game may be relative or end in a separator; archive names are cut from a separator-ended prefix. |
| 7 | $Game = (Resolve-Path -LiteralPath $Game).ProviderPath | 15 | $Game = (Resolve-Path -LiteralPath $Game).ProviderPath |
| 8 | # Resolve-Path preserves 8.3 short components (e.g. RUNNER~1), while Get-ChildItem emits canonical | 16 | # Resolve-Path preserves 8.3 short components (e.g. RUNNER~1), while Get-ChildItem emits canonical |
| @@ -11,14 +19,14 @@ $Game = (Resolve-Path -LiteralPath $Game).ProviderPath | |||
| 11 | $prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\' | 19 | $prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\' |
| 12 | $destinations = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::OrdinalIgnoreCase) | 20 | $destinations = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::OrdinalIgnoreCase) |
| 13 | # Validate every destination before accepting any cached index or starting a carve. | 21 | # Validate every destination before accepting any cached index or starting a carve. |
| 14 | $archives = foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -Filter *.rpf | Sort-Object Length) { | 22 | $archives = foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -File -Filter *.rpf | Sort-Object Length) { |
| 15 | $rel = $f.FullName.Substring($prefix.Length) | 23 | $rel = $f.FullName.Substring($prefix.Length) |
| 16 | $name = [IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_")) | 24 | $name = [IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_")) |
| 17 | if ($destinations.ContainsKey($name)) { | 25 | if ($destinations.ContainsKey($name)) { |
| 18 | throw ("Archives '{0}' and '{1}' both map to '{2}'." -f $destinations[$name], $rel, $name) | 26 | throw ("Archives '{0}' and '{1}' both map to '{2}'." -f $destinations[$name], $rel, $name) |
| 19 | } | 27 | } |
| 20 | $destinations.Add($name, $rel) | 28 | $destinations.Add($name, $rel) |
| 21 | [pscustomobject]@{ file = $f; relative = $rel; destination = Join-Path $Out $name } | 29 | [pscustomobject]@{ file = $f; relative = $rel; destination = Join-Path $outFull $name } |
| 22 | } | 30 | } |
| 23 | 31 | ||
| 24 | $rows = @() | 32 | $rows = @() |
| @@ -59,5 +67,15 @@ foreach ($archive in $archives) { | |||
| 59 | readable = [math]::Round($s.compressed_bytes / $denominator, 4) | 67 | readable = [math]::Round($s.compressed_bytes / $denominator, 4) |
| 60 | unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes } | 68 | unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes } |
| 61 | } | 69 | } |
| 62 | $rows | ConvertTo-Json | Set-Content -Encoding utf8 -LiteralPath (Join-Path $Out "coverage.json") | 70 | $coverageJson = if ($rows.Count -eq 0) { "[]" } else { $rows | ConvertTo-Json } |
| 63 | $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 | 71 | $coveragePath = Join-Path $outFull "coverage.json" |
| 72 | $tmpCoverage = Join-Path $outFull (".coverage.{0}.{1}.tmp" -f $PID, [guid]::NewGuid().ToString("N")) | ||
| 73 | try { | ||
| 74 | [System.IO.File]::WriteAllText($tmpCoverage, $coverageJson + "`n", [System.Text.UTF8Encoding]::new($false)) | ||
| 75 | Move-Item -LiteralPath $tmpCoverage -Destination $coveragePath -Force | ||
| 76 | } finally { | ||
| 77 | if (Test-Path -LiteralPath $tmpCoverage) { Remove-Item -LiteralPath $tmpCoverage -Force -ErrorAction SilentlyContinue } | ||
| 78 | } | ||
| 79 | if ($rows.Count -gt 0) { | ||
| 80 | $rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 | ||
| 81 | } | ||
diff --git a/scripts/check_no_game_data.py b/scripts/check_no_game_data.py index 595fc7b1c..92097253c 100644 --- a/scripts/check_no_game_data.py +++ b/scripts/check_no_game_data.py | |||
| @@ -3,6 +3,10 @@ | |||
| 3 | python3 -I scripts/check_no_game_data.py # every file `git ls-files` lists | 3 | python3 -I scripts/check_no_game_data.py # every file `git ls-files` lists |
| 4 | python3 -I scripts/check_no_game_data.py PATH... # only these files | 4 | python3 -I scripts/check_no_game_data.py PATH... # only these files |
| 5 | 5 | ||
| 6 | Explicit PATH inputs must be regular files, not directories or symlinks. A missing, unreadable or non-regular | ||
| 7 | explicit input is reported on stderr and causes exit 2 unless another input matches game data (exit 1). | ||
| 8 | Default git enumeration still skips symlinks, submodules and files deleted from the working tree. | ||
| 9 | |||
| 6 | The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable | 10 | The extension check in .github/workflows/no-game-data.yml misses a renamed file: a DDS saved as .bin, an executable |
| 7 | as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the | 11 | as .txt. This reads the first bytes of each file and matches the magic numbers of the package's formats and the |
| 8 | files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader | 12 | files the build extracts from it: RPF9 archives, TTPF texture pools, RAGE resources, XBCH/FSSM/DXBC shader |
| @@ -25,10 +29,12 @@ exits 1 if there is any. It exits 2 when a file cannot be read or git cannot lis | |||
| 25 | repository, or git not installed). Standard library only, no game files. | 29 | repository, or git not installed). Standard library only, no game files. |
| 26 | """ | 30 | """ |
| 27 | import bz2 | 31 | import bz2 |
| 32 | import errno | ||
| 28 | import gzip | 33 | import gzip |
| 29 | import io | 34 | import io |
| 30 | import lzma | 35 | import lzma |
| 31 | import os | 36 | import os |
| 37 | import stat | ||
| 32 | import subprocess | 38 | import subprocess |
| 33 | import sys | 39 | import sys |
| 34 | import tarfile | 40 | import tarfile |
| @@ -274,15 +280,19 @@ def git_error(e): | |||
| 274 | return e.strerror or str(e) | 280 | return e.strerror or str(e) |
| 275 | 281 | ||
| 276 | 282 | ||
| 277 | def check(paths, unreadable=None): | 283 | def check(paths, unreadable=None, *, explicit=False): |
| 278 | """[(path, format)] for every regular file in `paths` that starts like game data. | 284 | """[(path, format)] for every regular file in `paths` that starts like game data. |
| 279 | 285 | ||
| 280 | A file that exists but cannot be opened or read is appended to `unreadable` (when given) as (path, error).""" | 286 | Files that cannot be opened or read are appended to `unreadable` (when given) as (path, error). |
| 287 | Explicit inputs also report missing paths and non-regular entries instead of silently skipping them.""" | ||
| 281 | found = [] | 288 | found = [] |
| 282 | for path in paths: | 289 | for path in paths: |
| 283 | if os.path.islink(path) or not os.path.isfile(path): | ||
| 284 | continue # submodules, symlinks, files deleted in the working tree | ||
| 285 | try: | 290 | try: |
| 291 | if explicit: | ||
| 292 | if not stat.S_ISREG(os.lstat(path).st_mode): | ||
| 293 | raise OSError(errno.EINVAL, "not a regular file", path) | ||
| 294 | elif os.path.islink(path) or not os.path.isfile(path): | ||
| 295 | continue # submodules, symlinks, files deleted in the working tree | ||
| 286 | name = classify_file(path) | 296 | name = classify_file(path) |
| 287 | except OSError as e: | 297 | except OSError as e: |
| 288 | if unreadable is not None: | 298 | if unreadable is not None: |
| @@ -311,7 +321,7 @@ def main(argv): | |||
| 311 | print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr) | 321 | print(f"check_no_game_data: cannot list the tracked files with git: {git_error(e)}", file=sys.stderr) |
| 312 | return 2 # not 1: that is the 'game data found' code | 322 | return 2 # not 1: that is the 'game data found' code |
| 313 | unreadable = [] | 323 | unreadable = [] |
| 314 | found = check(paths, unreadable) | 324 | found = check(paths, unreadable, explicit=bool(argv)) |
| 315 | for path, name in found: | 325 | for path, name in found: |
| 316 | print(f"{display(path)}: {name}") | 326 | print(f"{display(path)}: {name}") |
| 317 | for path, e in unreadable: | 327 | for path, e in unreadable: |
diff --git a/scripts/ci_expected_failures.py b/scripts/ci_expected_failures.py index f398020f7..866706ddd 100644 --- a/scripts/ci_expected_failures.py +++ b/scripts/ci_expected_failures.py | |||
| @@ -24,12 +24,13 @@ def judge(failed: list[str], status: int, expected: list[str]) -> tuple[int, lis | |||
| 24 | return 1, lines | 24 | return 1, lines |
| 25 | if status != 0 and not failed: | 25 | if status != 0 and not failed: |
| 26 | lines.append(f"::error::the test runner exited with {status} without naming a failed test") | 26 | lines.append(f"::error::the test runner exited with {status} without naming a failed test") |
| 27 | return 1, lines | ||
| 27 | for name in expected: | 28 | for name in expected: |
| 28 | if name in failed: | 29 | if name in failed: |
| 29 | lines.append(f"::warning::{name} failed, as expected until its fix is merged") | 30 | lines.append(f"::warning::{name} failed, as expected until its fix is merged") |
| 30 | else: | 31 | else: |
| 31 | lines.append(f"::notice::{name} passed: drop it from the expected failures") | 32 | lines.append(f"::notice::{name} passed: drop it from the expected failures") |
| 32 | return (1 if unexpected or (status != 0 and not failed) else 0), lines | 33 | return (1 if unexpected else 0), lines |
| 33 | 34 | ||
| 34 | 35 | ||
| 35 | def main(argv: list[str]) -> int: | 36 | def main(argv: list[str]) -> int: |
diff --git a/scripts/dev.py b/scripts/dev.py index 4170aac63..00bf1bb21 100644 --- a/scripts/dev.py +++ b/scripts/dev.py | |||
| @@ -90,15 +90,15 @@ def guest_scene(args: list[str]) -> int: | |||
| 90 | parser.add_argument("-h", "--help", action="store_true") | 90 | parser.add_argument("-h", "--help", action="store_true") |
| 91 | parser.add_argument("--out", metavar="PATH") | 91 | parser.add_argument("--out", metavar="PATH") |
| 92 | options, _ = parser.parse_known_args(args) | 92 | options, _ = parser.parse_known_args(args) |
| 93 | if not options.help and not options.out: | 93 | if not options.help and not (options.out and options.out.strip()): |
| 94 | parser.error("--out PATH is required to keep the scene results") | 94 | parser.error("--out PATH is required to keep the scene results") |
| 95 | 95 | ||
| 96 | return run_producer(GUEST_SCENE, args) | 96 | return run_producer(GUEST_SCENE, args) |
| 97 | 97 | ||
| 98 | 98 | ||
| 99 | def main() -> int: | 99 | def main(argv: list[str] | None = None) -> int: |
| 100 | # The producer owns its arguments and help. Forward before argparse handles them. | 100 | # The producer owns its arguments and help. Forward before argparse handles them. |
| 101 | argv = sys.argv[1:] | 101 | argv = sys.argv[1:] if argv is None else list(argv) |
| 102 | if argv[:1] == ["boot-trace"]: | 102 | if argv[:1] == ["boot-trace"]: |
| 103 | return run_producer(BOOT_TRACE, argv[1:]) | 103 | return run_producer(BOOT_TRACE, argv[1:]) |
| 104 | if argv[:1] == ["guest-scene"]: | 104 | if argv[:1] == ["guest-scene"]: |
| @@ -119,7 +119,10 @@ def main() -> int: | |||
| 119 | if args.json: | 119 | if args.json: |
| 120 | print(json.dumps(result, indent=2)) | 120 | print(json.dumps(result, indent=2)) |
| 121 | else: | 121 | else: |
| 122 | sys.stdout.reconfigure(encoding="utf-8") | 122 | try: |
| 123 | sys.stdout.reconfigure(encoding="utf-8") | ||
| 124 | except (AttributeError, ValueError, OSError): | ||
| 125 | pass | ||
| 123 | print("Paths and help commands are relative to the Leonida checkout root.") | 126 | print("Paths and help commands are relative to the Leonida checkout root.") |
| 124 | for tool in result["tools"]: | 127 | for tool in result["tools"]: |
| 125 | status = "present" if tool["present"] else "missing" | 128 | status = "present" if tool["present"] else "missing" |
diff --git a/scripts/fetch_vkd3d_proton.py b/scripts/fetch_vkd3d_proton.py index 1c3fe22d5..bf4bb9c5d 100755 --- a/scripts/fetch_vkd3d_proton.py +++ b/scripts/fetch_vkd3d_proton.py | |||
| @@ -72,4 +72,5 @@ def main(): | |||
| 72 | 72 | ||
| 73 | 73 | ||
| 74 | if __name__ == "__main__": | 74 | if __name__ == "__main__": |
| 75 | sys.stdout.reconfigure(errors="replace") | ||
| 75 | sys.exit(main()) | 76 | sys.exit(main()) |
diff --git a/scripts/launcher_python.sh b/scripts/launcher_python.sh new file mode 100644 index 000000000..a469f34ec --- /dev/null +++ b/scripts/launcher_python.sh | |||
| @@ -0,0 +1,40 @@ | |||
| 1 | # Sourced by the POSIX launchers. Search for versioned Python names on PATH so a new Python minor | ||
| 2 | # release works even if the system's unversioned python3 still points to an older interpreter. | ||
| 3 | exec_leonida_python() { | ||
| 4 | remaining=${PATH-} | ||
| 5 | best_minor=11 | ||
| 6 | best_python= | ||
| 7 | while :; do | ||
| 8 | directory=${remaining%%:*} | ||
| 9 | for candidate in "${directory:-.}"/python3.*; do | ||
| 10 | [ -f "$candidate" ] && [ -x "$candidate" ] || continue | ||
| 11 | name=${candidate##*/} | ||
| 12 | minor=${name#python3.} | ||
| 13 | case $minor in | ||
| 14 | 0*|''|*[!0-9]*) continue ;; | ||
| 15 | esac | ||
| 16 | # Invoke by name to keep PATH precedence if that version appears in more than one directory. | ||
| 17 | if [ "$minor" -gt "$best_minor" ] 2>/dev/null && leonida_python_is_supported "$name"; then | ||
| 18 | best_minor=$minor | ||
| 19 | best_python=$name | ||
| 20 | fi | ||
| 21 | done | ||
| 22 | case $remaining in | ||
| 23 | *:*) remaining=${remaining#*:} ;; | ||
| 24 | *) break ;; | ||
| 25 | esac | ||
| 26 | done | ||
| 27 | |||
| 28 | if [ -n "$best_python" ]; then | ||
| 29 | exec "$best_python" -I "$@" | ||
| 30 | fi | ||
| 31 | for name in python3 python; do | ||
| 32 | if leonida_python_is_supported "$name"; then | ||
| 33 | exec "$name" -I "$@" | ||
| 34 | fi | ||
| 35 | done | ||
| 36 | } | ||
| 37 | |||
| 38 | leonida_python_is_supported() { | ||
| 39 | "$1" -I -c 'import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)' >/dev/null 2>&1 | ||
| 40 | } | ||
diff --git a/scripts/linux-boot/boot-digest.sh b/scripts/linux-boot/boot-digest.sh index dd2289e30..9a7c06d68 100755 --- a/scripts/linux-boot/boot-digest.sh +++ b/scripts/linux-boot/boot-digest.sh | |||
| @@ -3,14 +3,23 @@ | |||
| 3 | # Writes /opt/leonida/work/<agent>/boot-<n>.digest.txt and appends a line to /opt/leonida/work/boots.tsv. | 3 | # Writes /opt/leonida/work/<agent>/boot-<n>.digest.txt and appends a line to /opt/leonida/work/boots.tsv. |
| 4 | # Local only: digests quote trace lines, so they never go into commits or PRs. | 4 | # Local only: digests quote trace lines, so they never go into commits or PRs. |
| 5 | set -u | 5 | set -u |
| 6 | AGENT=$1; N=$2; WORK=/opt/leonida/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | 6 | AGENT=${1:?agent}; N=${2:?n} |
| 7 | META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=/opt/leonida/work/boots.tsv | 7 | if [ "$AGENT" = "." ] || [ "$AGENT" = ".." ] || ! [[ "$AGENT" =~ ^[A-Za-z0-9._-]+$ ]]; then |
| 8 | echo "boot-digest: invalid agent: $AGENT" >&2; exit 2 | ||
| 9 | fi | ||
| 10 | if ! [[ "$N" =~ ^[0-9]+$ ]]; then | ||
| 11 | echo "boot-digest: invalid boot number: $N" >&2; exit 2 | ||
| 12 | fi | ||
| 13 | ROOT=${LEONIDA_BOOT_ROOT:-/opt/leonida} | ||
| 14 | WORK=$ROOT/work/$AGENT; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | ||
| 15 | META=$WORK/boot-$N.meta; OUT=$WORK/boot-$N.digest.txt; LEDGER=$ROOT/work/boots.tsv | ||
| 16 | mkdir -p "$WORK" "$(dirname "$LEDGER")" | ||
| 8 | START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null) | 17 | START=$(sed -n 's/^start_epoch=//p' "$META" 2>/dev/null); BOOT=$(sed -n 's/^boot_epoch=//p' "$META" 2>/dev/null) |
| 9 | START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s) | 18 | START=${START:-$(date +%s)}; BOOT=${BOOT:-$START}; END=$(date +%s) |
| 10 | RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?} | 19 | RESULT=${SERVICE_RESULT:-?}; ECODE=${EXIT_CODE:-?}; ESTAT=${EXIT_STATUS:-?} |
| 11 | D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2) | 20 | D3D=$(grep -o 'd3d12=[^ ]*' "$LOG" 2>/dev/null | tail -1 | cut -d= -f2) |
| 12 | STDOUT=${D3D/d3d12-run-/stdout-run-} | 21 | STDOUT=${D3D/d3d12-run-/stdout-run-} |
| 13 | CAP=/opt/leonida/capture/$AGENT-$N | 22 | CAP=$ROOT/capture/$AGENT-$N |
| 14 | 23 | ||
| 15 | verdict=OK | 24 | verdict=OK |
| 16 | # systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own). | 25 | # systemd-oomd can kill the unit's processes without the unit ending in "oom-kill" (boot.sh then exits on its own). |
| @@ -39,15 +48,15 @@ cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0 | |||
| 39 | grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120 | 48 | grep -a 'present-probe: source frame .* via' "$D3D" 2>/dev/null | tail -1 | sed 's/.*via/source via/' | cut -c1-120 |
| 40 | echo | 49 | echo |
| 41 | echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)" | 50 | echo "-- frames (swapchain; then the title's own backbuffer when LEONIDA_CAPTURE_SOURCE=1)" |
| 42 | [ -f "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index" | 51 | [ -s "$CAP/index.txt" ] && { echo "$(wc -l < "$CAP/index.txt") captured; last: $(tail -1 "$CAP/index.txt" | cut -c1-110)"; awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print n+0 " of " NR " frames non-black"}' "$CAP/index.txt"; } || echo "no capture index" |
| 43 | grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140 | 52 | grep -a 'present-probe: source frame .* mean' "$D3D" 2>/dev/null | tail -2 | sed 's/.*source frame/source frame/' | cut -c1-140 |
| 44 | echo | 53 | echo |
| 45 | echo "-- resources (2 s samples)" | 54 | echo "-- resources (2 s samples)" |
| 46 | [ -s "$RES" ] && awk -F'\t' 'NR>1{ if(min==""||$2<min)min=$2; if($3>sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm}' "$RES" || echo "no samples" | 55 | [ -s "$RES" ] && awk -F'\t' 'NR>1{ c++; if(min==""||$2<min)min=$2; if($3>sw)sw=$3; if($4>um)um=$4; if($5>us)us=$5; if($6+0>gm)gm=$6 } END{ if(c>0) printf "min RAM available %s MB, max swap used %s MB, game peak %s MB RAM + %s MB swap, VRAM peak %s MB\n",min,sw,um,us,gm; else print "no samples" }' "$RES" || echo "no samples" |
| 47 | journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200 | 56 | journalctl --user -u "leonida-boot-$AGENT-$N" --since "@$START" -q --no-pager 2>/dev/null | grep -E 'Consumed|oom|Failed' | sed 's/^.*\]: //' | sort -u | cut -c1-200 |
| 48 | # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of | 57 | # Compare with other boots instead of guessing: on the console (Series S) path the title itself grows to ~20 GB of |
| 49 | # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well. | 58 | # RAM+swap by ~130 s (fsdraw-6: 9.9 GB + 11.2 GB), mostly zero pages that zram compresses well. |
| 50 | [ -s "$RES" ] && awk -F'\t' 'NR>1{t=$4+$5; if(t>m)m=t} END{printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024}' "$RES" | 59 | [ -s "$RES" ] && awk -F'\t' 'NR>1{ c++; t=$4+$5; if(t>m)m=t } END{ if(c>0) printf "game peak RAM+swap %.1f GB (console-path baseline ~20 GB at 130 s; oomd kills when zram swap passes 98%%)\n", m/1024 }' "$RES" |
| 51 | echo | 60 | echo |
| 52 | echo "-- system events during the boot (OOM, GPU Xid, segfaults)" | 61 | echo "-- system events during the boot (OOM, GPU Xid, segfaults)" |
| 53 | { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15 | 62 | { journalctl --since "@$BOOT" -q --no-pager 2>/dev/null | grep -i -E 'systemd-oomd.*(Marked|killed)|oom-kill|out of memory|NVRM: Xid|segfault|gta6rt|wineserver.*crash' ; } | cut -c1-200 | tail -15 |
| @@ -63,13 +72,13 @@ cnt() { local c=0; [ -f "$D3D" ] && c=$(grep -a -c -E "$@" "$D3D"); echo "${c:-0 | |||
| 63 | [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200 | 72 | [ -f "$D3D" ] && tail -n 8 "$D3D" | cut -c1-200 |
| 64 | } > "$OUT" 2>&1 | 73 | } > "$OUT" 2>&1 |
| 65 | 74 | ||
| 66 | frames=$( [ -f "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-") | 75 | frames=$( [ -s "$CAP/index.txt" ] && awk '{m=$(NF-2)+$(NF-1)+$NF; if (m>0) n++} END{print (n+0) "/" NR}' "$CAP/index.txt" || echo "-") |
| 67 | peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{if($4>u)u=$4} END{print u+0}' "$RES" || echo "-") | 76 | peak=$( [ -s "$RES" ] && awk -F'\t' 'NR>1{c++; if($4>u)u=$4} END{if(c>0) print u+0; else print "-"}' "$RES" || echo "-") |
| 68 | exec 7>>"$LEDGER"; flock 7 | 77 | exec 7>>"$LEDGER"; if command -v flock >/dev/null 2>&1; then flock 7; fi |
| 69 | # Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot. | 78 | # Both the unit's ExecStopPost and the outer wrapper call this; the first one to finish records the boot. |
| 70 | grep -q -P "^[^\t]*\t$AGENT\t$N\t" "$LEDGER" 2>/dev/null && exit 0 | 79 | awk -F'\t' -v a="$AGENT" -v n="$N" 'NR>1 && $2==a && $3==n {found=1; exit} END{exit !found}' "$LEDGER" 2>/dev/null && exit 0 |
| 71 | [ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7 | 80 | [ -s "$LEDGER" ] || printf 'end\tagent\tn\tresult\tran_s\tpresentx_ok\tpso_failed\tfspx_miss\tnonblack_frames\tpeak_mb\tgta6rt\n' >&7 |
| 72 | printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \ | 81 | printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date '+%F %T')" "$AGENT" "$N" "$RESULT" "$((END-BOOT))" \ |
| 73 | "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \ | 82 | "$(cnt 'XboxPresentation::PresentX ok')" "$(cnt 'CreatePipelineState failed')" "$(cnt 'no translated compute shader for FSPX')" \ |
| 74 | "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META")" >&7 | 83 | "$frames" "$peak" "$(sed -n 's/^unit=.*gta6rt=\([^ ]*\).*/\1/p' "$META" 2>/dev/null)" >&7 |
| 75 | exit 0 | 84 | exit 0 |
diff --git a/scripts/linux-boot/boot-inner.sh b/scripts/linux-boot/boot-inner.sh index e52d3daef..aa5f1147f 100755 --- a/scripts/linux-boot/boot-inner.sh +++ b/scripts/linux-boot/boot-inner.sh | |||
| @@ -1,44 +1,125 @@ | |||
| 1 | #!/bin/bash | 1 | #!/bin/bash |
| 2 | # Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots. | 2 | # Runs inside the leonida-boot-* unit (see run-boot.sh). Waits for memory, takes the locks, samples resources, boots. |
| 3 | set -u | 3 | set -u |
| 4 | WORK=/opt/leonida/work/$BOOT_AGENT; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | 4 | |
| 5 | die() { | ||
| 6 | echo "ERROR: $*" >&2 | ||
| 7 | exit 2 | ||
| 8 | } | ||
| 9 | |||
| 10 | OUT=${LEONIDA_BOOT_ROOT:-${LEONIDA_OUT:-/opt/leonida}} | ||
| 11 | BOOT_AGENT=${BOOT_AGENT:-} | ||
| 12 | BOOT_N=${BOOT_N:-} | ||
| 13 | BOOT_SECS=${BOOT_SECS:-} | ||
| 14 | GTA6RT=${GTA6RT:-} | ||
| 15 | BOOT_SH=${BOOT_SH:-$OUT/boot.sh} | ||
| 16 | NVIDIA_SMI=${NVIDIA_SMI:-nvidia-smi} | ||
| 17 | PROC_MEMINFO=${LEONIDA_MEMINFO_PATH:-/proc/meminfo} | ||
| 18 | CGROUP_SELF=${LEONIDA_SELF_CGROUP_PATH:-/proc/self/cgroup} | ||
| 19 | CGROUP_ROOT=${LEONIDA_CGROUP_ROOT:-/sys/fs/cgroup} | ||
| 20 | WAIT_SLEEP=${LEONIDA_WAIT_SLEEP_SECS:-15} | ||
| 21 | SAMPLE_SLEEP=${LEONIDA_SAMPLE_SLEEP_SECS:-2} | ||
| 22 | WAIT_ITERS=${LEONIDA_WAIT_ITERS:-40} | ||
| 23 | |||
| 24 | [ -n "$BOOT_AGENT" ] || die "BOOT_AGENT must be set" | ||
| 25 | [ -n "$BOOT_N" ] || die "BOOT_N must be set" | ||
| 26 | [ -n "$BOOT_SECS" ] || die "BOOT_SECS must be set" | ||
| 27 | [ -n "$GTA6RT" ] || die "GTA6RT must be set" | ||
| 28 | case "$BOOT_AGENT" in | ||
| 29 | .|..|*/*|*\\*|*..*) die "BOOT_AGENT must be a single path segment: $BOOT_AGENT" ;; | ||
| 30 | esac | ||
| 31 | case "$BOOT_N" in | ||
| 32 | .|..|*/*|*\\*|*..*) die "BOOT_N must be a single path segment: $BOOT_N" ;; | ||
| 33 | esac | ||
| 34 | [[ "$BOOT_SECS" =~ ^[0-9]+$ ]] || die "BOOT_SECS must be a non-negative integer: $BOOT_SECS" | ||
| 35 | [[ "$WAIT_ITERS" =~ ^[0-9]+$ ]] || die "WAIT_ITERS must be a non-negative integer: $WAIT_ITERS" | ||
| 36 | |||
| 37 | NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500} | ||
| 38 | [[ "$NEED" =~ ^[0-9]+$ ]] || die "LEONIDA_BOOT_MIN_FREE_MB must be a non-negative integer: $NEED" | ||
| 39 | |||
| 40 | WORK=${LEONIDA_BOOT_WORK:-$OUT/work/$BOOT_AGENT}; N=$BOOT_N; LOG=$WORK/boot-$N.log; RES=$WORK/boot-$N.resources.tsv | ||
| 5 | META=$WORK/boot-$N.meta | 41 | META=$WORK/boot-$N.meta |
| 42 | mkdir -p "$OUT" "$WORK" || die "cannot create work directory: $WORK" | ||
| 6 | : > "$LOG" | 43 | : > "$LOG" |
| 7 | echo "start_epoch=$(date +%s)" > "$META" | 44 | echo "start_epoch=$(date +%s)" > "$META" |
| 8 | echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META" | 45 | echo "unit=leonida-boot-$BOOT_AGENT-$N gta6rt=$GTA6RT secs=$BOOT_SECS" >> "$META" |
| 9 | env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META" | 46 | env | grep -E '^(LEONIDA_|WINEDEBUG=)' | sort >> "$META" || true |
| 10 | 47 | ||
| 11 | mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1) | 48 | mem_free_mb() { # RAM available plus a third of free zram swap (zram pages cost RAM, roughly 3:1) |
| 12 | awk '/^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' /proc/meminfo | 49 | [ -r "$PROC_MEMINFO" ] || { echo 0; return; } |
| 50 | awk 'BEGIN{a=0; s=0} /^MemAvailable:/{a=$2} /^SwapFree:/{s=$2} END{printf "%d", (a + s/3)/1024}' "$PROC_MEMINFO" | ||
| 13 | } | 51 | } |
| 14 | NEED=${LEONIDA_BOOT_MIN_FREE_MB:-6500} | 52 | swap_pct() { |
| 15 | swap_pct() { awk '/^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{printf "%d", t ? (t-f)*100/t : 0}' /proc/meminfo; } | 53 | [ -r "$PROC_MEMINFO" ] || { echo 0; return; } |
| 54 | awk 'BEGIN{t=0; f=0} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{pct=(t>0 ? (t-f)*100/t : 0); printf "%d", pct}' "$PROC_MEMINFO" | ||
| 55 | } | ||
| 56 | read_uint() { | ||
| 57 | local v="" | ||
| 58 | if [ -r "$1" ]; then | ||
| 59 | v=$(cat "$1" 2>/dev/null || true) | ||
| 60 | v=${v//$'\r'/} | ||
| 61 | fi | ||
| 62 | [[ "$v" =~ ^[0-9]+$ ]] || v=0 | ||
| 63 | printf '%s' "$v" | ||
| 64 | } | ||
| 65 | |||
| 66 | SAMPLER="" | ||
| 67 | cleanup() { | ||
| 68 | if [ -n "${SAMPLER:-}" ]; then | ||
| 69 | kill "$SAMPLER" 2>/dev/null || true | ||
| 70 | wait "$SAMPLER" 2>/dev/null || true | ||
| 71 | SAMPLER="" | ||
| 72 | fi | ||
| 73 | } | ||
| 74 | trap cleanup EXIT INT TERM | ||
| 16 | 75 | ||
| 17 | exec 8>/opt/leonida/.gpu.lock; flock 8 # one boot at a time | 76 | exec 8>"$OUT/.gpu.lock" |
| 77 | if command -v flock >/dev/null 2>&1; then flock 8; fi # one boot at a time | ||
| 18 | echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG" | 78 | echo "[run-boot] $(date +%T) got the GPU lock" >> "$LOG" |
| 19 | for i in $(seq 1 40); do # up to 10 min for memory headroom | 79 | for ((i = 1; i <= WAIT_ITERS; i++)); do # up to 10 min for memory headroom |
| 20 | f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break | 80 | f=$(mem_free_mb); sp=$(swap_pct); [ "$f" -ge "$NEED" ] && [ "$sp" -lt 70 ] && break |
| 21 | echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep 15 | 81 | echo "[run-boot] $(date +%T) waiting for memory: ${f} MB free (need ${NEED}), swap ${sp}% (need < 70%)" >> "$LOG"; sleep "$WAIT_SLEEP" |
| 22 | done | 82 | done |
| 23 | echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG" | 83 | echo "[run-boot] $(date +%T) memory before boot: $(mem_free_mb) MB free, swap $(swap_pct)%" >> "$LOG" |
| 24 | exec 9>/opt/leonida/.build.lock; flock 9 # no compiles while the game runs | 84 | exec 9>"$OUT/.build.lock" |
| 85 | if command -v flock >/dev/null 2>&1; then flock 9; fi # no compiles while the game runs | ||
| 25 | echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG" | 86 | echo "[run-boot] $(date +%T) got the build lock; booting" >> "$LOG" |
| 26 | echo "boot_epoch=$(date +%s)" >> "$META" | 87 | echo "boot_epoch=$(date +%s)" >> "$META" |
| 27 | 88 | ||
| 28 | CG=/sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup) | 89 | cg_rel="" |
| 29 | ( printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n' | 90 | if [ -r "$CGROUP_SELF" ]; then |
| 91 | cg_rel=$(awk -F: '$1=="0"{print $3; exit}' "$CGROUP_SELF" 2>/dev/null || true) | ||
| 92 | [ -n "$cg_rel" ] || cg_rel=$(awk -F: 'NF>=3{p=$3} END{print p}' "$CGROUP_SELF" 2>/dev/null || true) | ||
| 93 | cg_rel=${cg_rel//$'\r'/} | ||
| 94 | fi | ||
| 95 | CG=$CGROUP_ROOT$cg_rel | ||
| 96 | ( trap 'kill "${sleep_pid:-}" 2>/dev/null || true; exit 0' TERM INT | ||
| 97 | sleep_pid="" | ||
| 98 | printf 'time\tmem_avail_mb\tswap_used_mb\tunit_mem_mb\tunit_swap_mb\tgpu_mem_mb\tgpu_util\n' | ||
| 30 | while :; do | 99 | while :; do |
| 31 | read -r ma su < <(awk '/^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{print int(a/1024), int((t-f)/1024)}' /proc/meminfo) | 100 | ma=0; su=0 |
| 32 | um=$(( $(cat "$CG/memory.current" 2>/dev/null || echo 0) / 1048576 )); us=$(( $(cat "$CG/memory.swap.current" 2>/dev/null || echo 0) / 1048576 )) | 101 | if [ -r "$PROC_MEMINFO" ]; then |
| 33 | g=$(nvidia-smi --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | tr -d ' ' | tr ',' '\t') | 102 | read -r ma su < <(awk 'BEGIN{a=0; t=0; f=0} /^MemAvailable:/{a=$2} /^SwapTotal:/{t=$2} /^SwapFree:/{f=$2} END{u=(t>f ? t-f : 0); print int(a/1024), int(u/1024)}' "$PROC_MEMINFO") |
| 103 | fi | ||
| 104 | um=$(( $(read_uint "$CG/memory.current") / 1048576 )) | ||
| 105 | us=$(( $(read_uint "$CG/memory.swap.current") / 1048576 )) | ||
| 106 | g=$("$NVIDIA_SMI" --query-gpu=memory.used,utilization.gpu --format=csv,noheader,nounits 2>/dev/null | head -n 1 | tr -d ' \r' | tr ',' '\t') | ||
| 34 | printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}" | 107 | printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$(date +%T)" "$ma" "$su" "$um" "$us" "${g:-? ?}" |
| 35 | sleep 2 | 108 | sleep "$SAMPLE_SLEEP" & |
| 109 | sleep_pid=$! | ||
| 110 | wait "$sleep_pid" 2>/dev/null || break | ||
| 111 | sleep_pid="" | ||
| 36 | done ) > "$RES" 2>/dev/null & | 112 | done ) > "$RES" 2>/dev/null & |
| 37 | SAMPLER=$! | 113 | SAMPLER=$! |
| 38 | 114 | ||
| 39 | /opt/leonida/boot.sh run "$BOOT_SECS" >> "$LOG" 2>&1 | 115 | if [ -f "$BOOT_SH" ]; then |
| 40 | rc=$? | 116 | "$BOOT_SH" run "$BOOT_SECS" >> "$LOG" 2>&1 |
| 41 | kill $SAMPLER 2>/dev/null | 117 | rc=$? |
| 118 | else | ||
| 119 | echo "[run-boot] missing boot script: $BOOT_SH" >> "$LOG" | ||
| 120 | rc=127 | ||
| 121 | fi | ||
| 122 | cleanup | ||
| 42 | echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG" | 123 | echo "[run-boot] $(date +%T) boot.sh exit $rc" >> "$LOG" |
| 43 | # boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here. | 124 | # boot.sh stops the title with timeout(1) at the time limit: 124 means it ran the whole time, which is success here. |
| 44 | [ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; } | 125 | [ "$rc" = 124 ] && { echo "[run-boot] time limit reached" >> "$LOG"; rc=0; } |
diff --git a/scripts/linux-boot/boot.sh b/scripts/linux-boot/boot.sh index 55f84f019..6a2268f27 100755 --- a/scripts/linux-boot/boot.sh +++ b/scripts/linux-boot/boot.sh | |||
| @@ -3,13 +3,65 @@ | |||
| 3 | # usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped) | 3 | # usage: boot.sh dry-run|init|run [seconds] (run defaults to 150 s, then the title is stopped) |
| 4 | # Traces stay local in /opt/leonida/traces: they can quote game data, never post them. | 4 | # Traces stay local in /opt/leonida/traces: they can quote game data, never post them. |
| 5 | set -u | 5 | set -u |
| 6 | MODE=${1:?dry-run|init|run}; SECS=${2:-150} | 6 | usage() { |
| 7 | OUT=/opt/leonida | 7 | echo "usage: boot.sh dry-run|init|run [seconds]" |
| 8 | } | ||
| 9 | |||
| 10 | if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then | ||
| 11 | usage | ||
| 12 | exit 0 | ||
| 13 | fi | ||
| 14 | if [ $# -lt 1 ] || [ $# -gt 2 ]; then | ||
| 15 | usage >&2 | ||
| 16 | exit 2 | ||
| 17 | fi | ||
| 18 | |||
| 19 | MODE=$1 | ||
| 20 | SECS=${2:-150} | ||
| 21 | case "$MODE" in | ||
| 22 | dry-run|init|run) ;; | ||
| 23 | *) | ||
| 24 | echo "boot.sh: invalid mode: $MODE (expected dry-run, init, or run)" >&2 | ||
| 25 | exit 2 | ||
| 26 | ;; | ||
| 27 | esac | ||
| 28 | if ! [[ "$SECS" =~ ^[1-9][0-9]*$ ]]; then | ||
| 29 | echo "boot.sh: invalid seconds: $SECS (expected positive integer)" >&2 | ||
| 30 | exit 2 | ||
| 31 | fi | ||
| 32 | |||
| 33 | OUT=${LEONIDA_OUT:-/opt/leonida} | ||
| 8 | REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in | 34 | REPO=${LEONIDA_REPO:-$(cd "$(dirname "$(readlink -f "$0")")/../.." && pwd)} # the checkout this script is in |
| 35 | WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx | ||
| 36 | PYTHON3=${PYTHON3:-python3} | ||
| 37 | UNSHARE=${UNSHARE:-unshare} | ||
| 38 | TIMEOUT=${TIMEOUT:-timeout} | ||
| 39 | GAME_DIR=${LEONIDA_GAME_DIR:-/opt/gta6/GTA6.Xbox.v1.0.2.1} | ||
| 40 | GAME_WIN=${LEONIDA_GAME_WIN:-'Z:\opt\gta6\GTA6.Xbox.v1.0.2.1'} | ||
| 41 | EXE=${LEONIDA_EXE:-$GAME_DIR/game_scarlett_master.exe} | ||
| 42 | OVERLAY_WIN=${LEONIDA_OVERLAY_WIN:-'Z:\opt\leonida\overlay'} | ||
| 43 | GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=<your build>/gta6rt.exe boots a private build without installing it | ||
| 44 | |||
| 45 | if [ ! -f "$GTA6RT" ]; then | ||
| 46 | echo "boot.sh: missing gta6rt executable: $GTA6RT" >&2 | ||
| 47 | exit 2 | ||
| 48 | fi | ||
| 49 | if ! command -v "$UNSHARE" >/dev/null 2>&1; then | ||
| 50 | echo "boot.sh: missing required command: $UNSHARE" >&2 | ||
| 51 | exit 2 | ||
| 52 | fi | ||
| 53 | if [ "$MODE" = run ] && ! command -v "$TIMEOUT" >/dev/null 2>&1; then | ||
| 54 | echo "boot.sh: missing required command: $TIMEOUT" >&2 | ||
| 55 | exit 2 | ||
| 56 | fi | ||
| 57 | if ! command -v "$WINE" >/dev/null 2>&1; then | ||
| 58 | echo "boot.sh: missing required Wine binary: $WINE" >&2 | ||
| 59 | exit 2 | ||
| 60 | fi | ||
| 61 | |||
| 9 | STAMP=$(date +%H%M%S) | 62 | STAMP=$(date +%H%M%S) |
| 10 | T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv" | 63 | T=$OUT/traces; mkdir -p "$T" "$OUT/overlay" "$OUT/cache/nv" |
| 11 | 64 | ||
| 12 | WINE=${WINE:-wine} # e.g. WINE=".../Proton - Experimental/files/bin/wine" WINEPREFIX=~/.local/share/leonida-proton/pfx | ||
| 13 | export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml=" | 65 | export WINEPREFIX=${WINEPREFIX:-$HOME/.local/share/leonida-wine} WINEDEBUG=${WINEDEBUG:--all} WINEDLLOVERRIDES="mscoree,mshtml=" |
| 14 | export LEONIDA_D3D12=vulkan | 66 | export LEONIDA_D3D12=vulkan |
| 15 | export LEONIDA_SHADERS=$OUT/work/shaders/spirv | 67 | export LEONIDA_SHADERS=$OUT/work/shaders/spirv |
| @@ -20,23 +72,22 @@ export __GL_SHADER_DISK_CACHE=1 __GL_SHADER_DISK_CACHE_PATH=$OUT/cache/nv __GL_S | |||
| 20 | export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 | 72 | export __GL_SHADER_DISK_CACHE_SKIP_CLEANUP=1 |
| 21 | [ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1 | 73 | [ -n "${SKIP_INT3:-}" ] && export LEONIDA_SKIP_INT3=1 |
| 22 | 74 | ||
| 23 | GAME_WIN='Z:\opt\gta6\GTA6.Xbox.v1.0.2.1' | 75 | TRACE_WIN=${LEONIDA_TRACE_WIN:-"Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl"} |
| 24 | EXE=/opt/gta6/GTA6.Xbox.v1.0.2.1/game_scarlett_master.exe | ||
| 25 | TRACE_WIN="Z:\\opt\\leonida\\traces\\boot-$MODE-$STAMP.jsonl" | ||
| 26 | D3D=$T/d3d12-$MODE-$STAMP.log | 76 | D3D=$T/d3d12-$MODE-$STAMP.log |
| 27 | GTA6RT=${GTA6RT:-$OUT/gta6rt.exe}; [ -f "$GTA6RT" ] || GTA6RT=$REPO/runtime/build/boot/gta6rt.exe # GTA6RT=<your build>/gta6rt.exe boots a private build without installing it | ||
| 28 | 77 | ||
| 29 | args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay 'Z:\opt\leonida\overlay' --trace "$TRACE_WIN") | 78 | args=(--"$MODE" "$EXE" --game-dir "$GAME_WIN" --overlay "$OVERLAY_WIN" --trace "$TRACE_WIN") |
| 30 | [ "$MODE" = run ] && args+=(--trace-d3d12) | 79 | [ "$MODE" = run ] && args+=(--trace-d3d12) |
| 31 | echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D" | 80 | echo "[boot] $MODE gta6rt=$GTA6RT trace=$T/boot-$MODE-$STAMP.jsonl d3d12=$D3D" |
| 32 | # unshare: new user + network namespace, so the title has no network at all | 81 | # unshare: new user + network namespace, so the title has no network at all |
| 33 | if [ "$MODE" = run ]; then | 82 | if [ "$MODE" = run ]; then |
| 34 | timeout --signal=INT --kill-after=20 "$SECS" unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" | 83 | "$TIMEOUT" --signal=INT --kill-after=20 "$SECS" "$UNSHARE" -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" |
| 35 | else | 84 | else |
| 36 | unshare -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" | 85 | "$UNSHARE" -rn "$WINE" "$GTA6RT" "${args[@]}" > "$T/stdout-$MODE-$STAMP.log" 2> "$D3D" |
| 37 | fi | 86 | fi |
| 38 | rc=$?; echo "[boot] exit=$rc" | 87 | rc=$?; echo "[boot] exit=$rc" |
| 39 | sleep 0 | 88 | sleep 0 |
| 40 | python3 -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1 | 89 | if [ -f "$REPO/tools/boot_trace.py" ]; then |
| 41 | echo "[boot] summary: $T/summary-$MODE-$STAMP.txt" | 90 | "$PYTHON3" -I "$REPO/tools/boot_trace.py" "$T/boot-$MODE-$STAMP.jsonl" --d3d12 "$D3D" > "$T/summary-$MODE-$STAMP.txt" 2>&1 || true |
| 42 | exit $rc | 91 | echo "[boot] summary: $T/summary-$MODE-$STAMP.txt" |
| 92 | fi | ||
| 93 | exit "$rc" | ||
diff --git a/scripts/linux-boot/configure-worktree.sh b/scripts/linux-boot/configure-worktree.sh index c983b3357..ef94973a9 100755 --- a/scripts/linux-boot/configure-worktree.sh +++ b/scripts/linux-boot/configure-worktree.sh | |||
| @@ -2,8 +2,49 @@ | |||
| 2 | # usage: configure-worktree.sh <worktree> | 2 | # usage: configure-worktree.sh <worktree> |
| 3 | # Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default | 3 | # Configures a Windows build of the runtime on Linux with clang-cl and an xwin SDK (XWIN_DIR, default |
| 4 | # ~/.local/share/xwin-sdk). SDL3_SRC=<an SDL3 source tree> makes the configure work offline. | 4 | # ~/.local/share/xwin-sdk). SDL3_SRC=<an SDL3 source tree> makes the configure work offline. |
| 5 | set -eu; W=$(realpath "$1") | 5 | set -eu |
| 6 | cmake -S "$W/runtime" -B "$W/runtime/build/boot" -G Ninja -DCMAKE_BUILD_TYPE=Release \ | 6 | |
| 7 | -DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" \ | 7 | usage() { |
| 8 | -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON -DLEONIDA_SDL3=ON \ | 8 | echo "usage: configure-worktree.sh <worktree>" |
| 9 | ${SDL3_SRC:+-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC"} | 9 | } |
| 10 | |||
| 11 | die() { | ||
| 12 | echo "ERROR: $*" >&2 | ||
| 13 | exit 2 | ||
| 14 | } | ||
| 15 | |||
| 16 | if [ "$#" -ge 1 ] && { [ "$1" = "-h" ] || [ "$1" = "--help" ]; }; then | ||
| 17 | usage | ||
| 18 | exit 0 | ||
| 19 | fi | ||
| 20 | |||
| 21 | [ "$#" -eq 1 ] || { usage >&2; exit 2; } | ||
| 22 | [ -n "$1" ] || die "worktree path must not be empty" | ||
| 23 | [ -d "$1" ] || die "worktree directory does not exist: $1" | ||
| 24 | |||
| 25 | W=$(realpath "$1") | ||
| 26 | [ -f "$W/runtime/CMakeLists.txt" ] || die "not a runtime worktree (missing runtime/CMakeLists.txt): $W" | ||
| 27 | [ -f "$W/runtime/cmake/clang-cl-xwin.cmake" ] || die "missing toolchain file: $W/runtime/cmake/clang-cl-xwin.cmake" | ||
| 28 | |||
| 29 | CMAKE=${CMAKE:-cmake} | ||
| 30 | command -v "$CMAKE" >/dev/null 2>&1 || die "cmake executable not found: $CMAKE" | ||
| 31 | |||
| 32 | if [ -n "${SDL3_SRC:-}" ] && [ ! -d "$SDL3_SRC" ]; then | ||
| 33 | die "SDL3_SRC directory does not exist: $SDL3_SRC" | ||
| 34 | fi | ||
| 35 | |||
| 36 | cmake_args=( | ||
| 37 | -S "$W/runtime" | ||
| 38 | -B "$W/runtime/build/boot" | ||
| 39 | -G Ninja | ||
| 40 | -DCMAKE_BUILD_TYPE=Release | ||
| 41 | -DCMAKE_TOOLCHAIN_FILE="$W/runtime/cmake/clang-cl-xwin.cmake" | ||
| 42 | -DXWIN_DIR="${XWIN_DIR:-$HOME/.local/share/xwin-sdk}" | ||
| 43 | -DLEONIDA_BUILD_WINDOWS_RUNTIME=ON | ||
| 44 | -DLEONIDA_SDL3=ON | ||
| 45 | ) | ||
| 46 | if [ -n "${SDL3_SRC:-}" ]; then | ||
| 47 | cmake_args+=(-DFETCHCONTENT_SOURCE_DIR_SDL3="$SDL3_SRC") | ||
| 48 | fi | ||
| 49 | |||
| 50 | "$CMAKE" "${cmake_args[@]}" | ||
diff --git a/scripts/linux-boot/run-boot.sh b/scripts/linux-boot/run-boot.sh index 523d17795..b23036ccb 100755 --- a/scripts/linux-boot/run-boot.sh +++ b/scripts/linux-boot/run-boot.sh | |||
| @@ -16,10 +16,26 @@ | |||
| 16 | # Outputs (in /opt/leonida/work/<agent>/): boot-<n>.log boot-<n>.resources.tsv boot-<n>.digest.txt | 16 | # Outputs (in /opt/leonida/work/<agent>/): boot-<n>.log boot-<n>.resources.tsv boot-<n>.digest.txt |
| 17 | set -u | 17 | set -u |
| 18 | AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# )) | 18 | AGENT=${1:?agent}; N=${2:?n}; EXE=${3:?gta6rt.exe}; SECS=${4:-150}; shift $(( $# >= 4 ? 4 : $# )) |
| 19 | if [ "$AGENT" = "." ] || [ "$AGENT" = ".." ] || ! [[ "$AGENT" =~ ^[A-Za-z0-9._-]+$ ]]; then | ||
| 20 | echo "run-boot: invalid agent: $AGENT" >&2; exit 2 | ||
| 21 | fi | ||
| 22 | if ! [[ "$N" =~ ^[0-9]+$ ]]; then | ||
| 23 | echo "run-boot: invalid boot number: $N" >&2; exit 2 | ||
| 24 | fi | ||
| 25 | if ! [[ "$SECS" =~ ^[1-9][0-9]*$ ]]; then | ||
| 26 | echo "run-boot: invalid seconds (expected positive integer): $SECS" >&2; exit 2 | ||
| 27 | fi | ||
| 28 | for kv in "$@"; do | ||
| 29 | if ! [[ "$kv" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then | ||
| 30 | echo "run-boot: invalid environment override (expected KEY=VALUE): $kv" >&2; exit 2 | ||
| 31 | fi | ||
| 32 | done | ||
| 19 | [ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; } | 33 | [ -f "$EXE" ] || { echo "run-boot: no such gta6rt: $EXE" >&2; exit 2; } |
| 20 | # gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once. | 34 | # gta6rt loads gta6rt_tls_host.dll from its own folder; without it the title gets no module TLS index and exits at once. |
| 21 | [ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; } | 35 | [ -f "$(dirname "$EXE")/gta6rt_tls_host.dll" ] || { echo "run-boot: $(dirname "$EXE")/gta6rt_tls_host.dll is missing: copy it next to the exe (build it with the gta6rt target) or boot the exe from its build folder" >&2; exit 2; } |
| 22 | WORK=/opt/leonida/work/$AGENT; mkdir -p "$WORK" | 36 | ROOT=${LEONIDA_BOOT_ROOT:-/opt/leonida} |
| 37 | WIN_ROOT=${ROOT#/}; WIN_ROOT="Z:\\${WIN_ROOT//\//\\}" | ||
| 38 | WORK=$ROOT/work/$AGENT; mkdir -p "$WORK" | ||
| 23 | UNIT=leonida-boot-$AGENT-$N | 39 | UNIT=leonida-boot-$AGENT-$N |
| 24 | if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi | 40 | if systemctl --user is-active --quiet "$UNIT"; then echo "run-boot: $UNIT is already running" >&2; exit 2; fi |
| 25 | 41 | ||
| @@ -28,10 +44,10 @@ declare -A ENV=( | |||
| 28 | [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx" | 44 | [WINEPREFIX]="$HOME/.local/share/leonida-proton/pfx" |
| 29 | [WINEDEBUG]="-all,err+all" | 45 | [WINEDEBUG]="-all,err+all" |
| 30 | [GTA6RT]="$EXE" | 46 | [GTA6RT]="$EXE" |
| 31 | [LEONIDA_CAPTURE]="Z:\\opt\\leonida\\capture\\$AGENT-$N" | 47 | [LEONIDA_CAPTURE]="$WIN_ROOT\\capture\\$AGENT-$N" |
| 32 | [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1 | 48 | [LEONIDA_CAPTURE_EVERY]=4800 [LEONIDA_CAPTURE_LIMIT]=24 [LEONIDA_CAPTURE_SOURCE]=1 |
| 33 | [LEONIDA_DEVICE_TYPE]=6 | 49 | [LEONIDA_DEVICE_TYPE]=6 |
| 34 | [LEONIDA_PIPELINE_CACHE_DIR]="Z:\\opt\\leonida\\cache\\pipelines" | 50 | [LEONIDA_PIPELINE_CACHE_DIR]="$WIN_ROOT\\cache\\pipelines" |
| 35 | ) | 51 | ) |
| 36 | for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done | 52 | for kv in "$@"; do ENV[${kv%%=*}]="${kv#*=}"; done |
| 37 | args=() | 53 | args=() |
| @@ -39,16 +55,16 @@ for k in "${!ENV[@]}"; do args+=(--setenv="$k=${ENV[$k]}"); done | |||
| 39 | 55 | ||
| 40 | echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)" | 56 | echo "run-boot: $UNIT starting (queues for memory headroom, the GPU lock and the build lock)" |
| 41 | rm -f "$WORK/boot-$N.digest.txt" | 57 | rm -f "$WORK/boot-$N.digest.txt" |
| 42 | systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory=/opt/leonida \ | 58 | systemd-run --user --collect --quiet --unit="$UNIT" -p WorkingDirectory="$ROOT" \ |
| 43 | --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \ | 59 | --setenv=BOOT_AGENT="$AGENT" --setenv=BOOT_N="$N" --setenv=BOOT_SECS="$SECS" "${args[@]}" \ |
| 44 | /opt/leonida/boot-inner.sh || { echo "run-boot: could not start $UNIT" >&2; exit 2; } | 60 | "$ROOT/boot-inner.sh" || { echo "run-boot: could not start $UNIT" >&2; exit 2; } |
| 45 | # The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the | 61 | # The digest is written by a separate, tiny watcher unit: it survives systemd-oomd killing the boot's cgroup and the |
| 46 | # caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest. | 62 | # caller's shell going away. It waits for the boot unit to end, reads its result from the journal and writes the digest. |
| 47 | systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \ | 63 | systemd-run --user --collect --quiet --unit="leonida-digest-$AGENT-$N" -p MemoryMax=256M \ |
| 48 | /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done | 64 | /bin/bash -c 'while systemctl --user is-active --quiet "$0" || systemctl --user is-activating --quiet "$0"; do sleep 3; done |
| 49 | START=$(sed -n "s/^start_epoch=//p" "/opt/leonida/work/$1/boot-$2.meta" 2>/dev/null) | 65 | START=$(sed -n "s/^start_epoch=//p" "$3/work/$1/boot-$2.meta" 2>/dev/null) |
| 50 | RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //") | 66 | RES=$(journalctl --user -u "$0" ${START:+--since "@$START"} -q --no-pager 2>/dev/null | grep -o "Failed with result .[a-z-]*." | tail -1 | tr -d "\x27" | sed "s/Failed with result //") |
| 51 | SERVICE_RESULT=${RES:-success} exec /opt/leonida/boot-digest.sh "$1" "$2"' "$UNIT" "$AGENT" "$N" | 67 | SERVICE_RESULT=${RES:-success} exec "$3/boot-digest.sh" "$1" "$2"' "$UNIT" "$AGENT" "$N" "$ROOT" |
| 52 | # Block until the digest exists (so a caller that waits on this script gets the result), then print it. | 68 | # Block until the digest exists (so a caller that waits on this script gets the result), then print it. |
| 53 | while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done | 69 | while [ ! -s "$WORK/boot-$N.digest.txt" ] || systemctl --user is-active --quiet "leonida-digest-$AGENT-$N"; do sleep 5; done |
| 54 | echo "run-boot: $UNIT finished. Digest:" | 70 | echo "run-boot: $UNIT finished. Digest:" |
diff --git a/scripts/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1 index 28c6575f6..38a00837d 100644 --- a/scripts/meta_to_xml.ps1 +++ b/scripts/meta_to_xml.ps1 | |||
| @@ -9,6 +9,9 @@ param( | |||
| 9 | [int]$Limit = 0 | 9 | [int]$Limit = 0 |
| 10 | ) | 10 | ) |
| 11 | $ErrorActionPreference = "Stop" | 11 | $ErrorActionPreference = "Stop" |
| 12 | if ($Limit -lt 0) { | ||
| 13 | throw "-Limit must be 0 or greater." | ||
| 14 | } | ||
| 12 | try { (Get-Process -Id $PID).PriorityClass = "BelowNormal" } catch {} | 15 | try { (Get-Process -Id $PID).PriorityClass = "BelowNormal" } catch {} |
| 13 | Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Mathematics.dll" | 16 | Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Mathematics.dll" |
| 14 | [void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") | 17 | [void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") |
| @@ -21,7 +24,12 @@ foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { | |||
| 21 | $idx = Join-Path $dir.FullName "index.json" | 24 | $idx = Join-Path $dir.FullName "index.json" |
| 22 | if (-not (Test-Path -LiteralPath $idx)) { continue } | 25 | if (-not (Test-Path -LiteralPath $idx)) { continue } |
| 23 | $files = (Get-Content -LiteralPath $idx -Raw | ConvertFrom-Json).files | | 26 | $files = (Get-Content -LiteralPath $idx -Raw | ConvertFrom-Json).files | |
| 24 | Where-Object { $_.head.StartsWith("5053494e") -or $_.head.StartsWith("52424630") } | 27 | Where-Object { |
| 28 | $_.head -is [string] -and ( | ||
| 29 | $_.head.StartsWith("5053494e", [StringComparison]::OrdinalIgnoreCase) -or | ||
| 30 | $_.head.StartsWith("52424630", [StringComparison]::OrdinalIgnoreCase) | ||
| 31 | ) | ||
| 32 | } | ||
| 25 | if (-not $files) { continue } | 33 | if (-not $files) { continue } |
| 26 | $dest = Join-Path $Out $dir.Name | 34 | $dest = Join-Path $Out $dir.Name |
| 27 | New-Item -ItemType Directory -Force $dest | Out-Null | 35 | New-Item -ItemType Directory -Force $dest | Out-Null |
| @@ -29,7 +37,7 @@ foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { | |||
| 29 | if ($Limit -and $n -ge $Limit) { break } | 37 | if ($Limit -and $n -ge $Limit) { break } |
| 30 | $n++ | 38 | $n++ |
| 31 | $name = "{0:x12}" -f [int64]$r.off | 39 | $name = "{0:x12}" -f [int64]$r.off |
| 32 | $kind = if ($r.head.StartsWith("5053494e")) { "pso" } else { "rbf" } | 40 | $kind = if ($r.head.StartsWith("5053494e", [StringComparison]::OrdinalIgnoreCase)) { "pso" } else { "rbf" } |
| 33 | try { | 41 | try { |
| 34 | $bytes = [IO.File]::ReadAllBytes((Join-Path $dir.FullName "$name.bin")) | 42 | $bytes = [IO.File]::ReadAllBytes((Join-Path $dir.FullName "$name.bin")) |
| 35 | if ($kind -eq "pso") { | 43 | if ($kind -eq "pso") { |
| @@ -39,7 +47,16 @@ foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) { | |||
| 39 | $f = New-Object CodeWalker.GameFiles.RbfFile; $f.Load($bytes) | 47 | $f = New-Object CodeWalker.GameFiles.RbfFile; $f.Load($bytes) |
| 40 | $xml = [CodeWalker.GameFiles.RbfXml]::GetXml($f) | 48 | $xml = [CodeWalker.GameFiles.RbfXml]::GetXml($f) |
| 41 | } | 49 | } |
| 42 | [IO.File]::WriteAllText((Join-Path $dest "$name.$kind.xml"), $xml) | 50 | $xmlPath = Join-Path $dest "$name.$kind.xml" |
| 51 | $tmpXml = "$xmlPath.$PID.tmp" | ||
| 52 | try { | ||
| 53 | [IO.File]::WriteAllText($tmpXml, $xml) | ||
| 54 | Move-Item -LiteralPath $tmpXml -Destination $xmlPath -Force | ||
| 55 | } finally { | ||
| 56 | if (Test-Path -LiteralPath $tmpXml) { | ||
| 57 | Remove-Item -LiteralPath $tmpXml -Force -ErrorAction SilentlyContinue | ||
| 58 | } | ||
| 59 | } | ||
| 43 | $ok[$kind]++ | 60 | $ok[$kind]++ |
| 44 | } catch { | 61 | } catch { |
| 45 | $bad[$kind]++ | 62 | $bad[$kind]++ |
diff --git a/scripts/port_ctl.py b/scripts/port_ctl.py index 97db0537e..9a7e595d0 100644 --- a/scripts/port_ctl.py +++ b/scripts/port_ctl.py | |||
| @@ -316,4 +316,5 @@ def main(): | |||
| 316 | 316 | ||
| 317 | 317 | ||
| 318 | if __name__ == "__main__": | 318 | if __name__ == "__main__": |
| 319 | sys.stdout.reconfigure(errors="replace") | ||
| 319 | sys.exit(main()) | 320 | sys.exit(main()) |
diff --git a/scripts/run_game_wine.sh b/scripts/run_game_wine.sh index ce01b0a07..9d8f19a37 100755 --- a/scripts/run_game_wine.sh +++ b/scripts/run_game_wine.sh | |||
| @@ -55,11 +55,13 @@ die() { echo "run_game_wine.sh: $*" >&2; exit 2; } | |||
| 55 | 55 | ||
| 56 | if [ "${1:-}" = --inner ]; then | 56 | if [ "${1:-}" = --inner ]; then |
| 57 | # ---- inside the session: DISPLAY is kwin's Xwayland (headless) or the caller's display (--visible) ---- | 57 | # ---- inside the session: DISPLAY is kwin's Xwayland (headless) or the caller's display (--visible) ---- |
| 58 | [ "$#" -ge 5 ] || die "--inner requires RUN BUILD LIMIT SHOT_EVERY" | ||
| 58 | RUN=$2; BUILD=$3; LIMIT=$4; SHOT_EVERY=$5 | 59 | RUN=$2; BUILD=$3; LIMIT=$4; SHOT_EVERY=$5 |
| 59 | shift 5 | 60 | shift 5 |
| 60 | WINE=${WINE:-wine} | 61 | WINE=${WINE:-wine} |
| 61 | WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver | 62 | wine_bin=$(command -v "$WINE" 2>/dev/null || true) |
| 62 | [ -x "$WINESERVER" ] || WINESERVER=wineserver | 63 | WINESERVER=${wine_bin:+$(dirname "$wine_bin")/wineserver} |
| 64 | [ -n "$WINESERVER" ] && [ -x "$WINESERVER" ] || WINESERVER=wineserver | ||
| 63 | unset WAYLAND_DISPLAY # Wine's X11 driver on Xwayland, never its Wayland driver | 65 | unset WAYLAND_DISPLAY # Wine's X11 driver on Xwayland, never its Wayland driver |
| 64 | { | 66 | { |
| 65 | echo "display: ${DISPLAY:-none}" | 67 | echo "display: ${DISPLAY:-none}" |
| @@ -70,7 +72,7 @@ if [ "${1:-}" = --inner ]; then | |||
| 70 | mkdir -p "$WINEPREFIX" | 72 | mkdir -p "$WINEPREFIX" |
| 71 | "$WINESERVER" -p | 73 | "$WINESERVER" -p |
| 72 | # Warm-up: starts the prefix's services; no Mono/Gecko prompts in a new prefix. | 74 | # Warm-up: starts the prefix's services; no Mono/Gecko prompts in a new prefix. |
| 73 | WINEDLLOVERRIDES="$WINEDLLOVERRIDES;mscoree,mshtml=" "$WINE" wineboot -u </dev/null >/dev/null 2>&1 | 75 | WINEDLLOVERRIDES="${WINEDLLOVERRIDES:+$WINEDLLOVERRIDES;}mscoree,mshtml=" "$WINE" wineboot -u </dev/null >/dev/null 2>&1 |
| 74 | SHOTS= | 76 | SHOTS= |
| 75 | if [ "$SHOT_EVERY" != 0 ]; then | 77 | if [ "$SHOT_EVERY" != 0 ]; then |
| 76 | mkdir -p "$RUN/shots" | 78 | mkdir -p "$RUN/shots" |
| @@ -97,7 +99,10 @@ if [ "${1:-}" = --inner ]; then | |||
| 97 | code=$? | 99 | code=$? |
| 98 | echo "$(( $(date +%s) - t0 ))" > "$RUN/seconds" | 100 | echo "$(( $(date +%s) - t0 ))" > "$RUN/seconds" |
| 99 | echo "$code" > "$RUN/exit_code" | 101 | echo "$code" > "$RUN/exit_code" |
| 100 | [ -n "$SHOTS" ] && kill "$SHOTS" 2>/dev/null | 102 | if [ -n "$SHOTS" ]; then |
| 103 | kill "$SHOTS" 2>/dev/null || true | ||
| 104 | wait "$SHOTS" 2>/dev/null || true | ||
| 105 | fi | ||
| 101 | "$WINESERVER" -k 2>/dev/null | 106 | "$WINESERVER" -k 2>/dev/null |
| 102 | exit 0 | 107 | exit 0 |
| 103 | fi | 108 | fi |
| @@ -132,10 +137,11 @@ done | |||
| 132 | [ -n "$OUT" ] || die "--out is required: the run folder" | 137 | [ -n "$OUT" ] || die "--out is required: the run folder" |
| 133 | [ -n "$SHADERS" ] || die "--shaders (or LEONIDA_SHADERS) is required: the translated shader library, or none" | 138 | [ -n "$SHADERS" ] || die "--shaders (or LEONIDA_SHADERS) is required: the translated shader library, or none" |
| 134 | case $LIMIT in ''|*[!0-9]*|0*) die "--seconds must be a whole number of seconds above 0, not '$LIMIT'" ;; esac | 139 | case $LIMIT in ''|*[!0-9]*|0*) die "--seconds must be a whole number of seconds above 0, not '$LIMIT'" ;; esac |
| 135 | case $SHOT_EVERY in ''|*[!0-9]*) die "--screenshot-every must be a whole number of seconds, not '$SHOT_EVERY'" ;; esac | 140 | case $SHOT_EVERY in ''|*[!0-9]*|0?*) die "--screenshot-every must be a whole number of seconds, not '$SHOT_EVERY'" ;; esac |
| 136 | if [ -n "$DEVICE" ] && ! [[ $DEVICE =~ ^[0-9a-fA-F]{4}:[0-9a-fA-F]{4}$ ]]; then | 141 | if [ -n "$DEVICE" ] && ! [[ $DEVICE =~ ^[0-9a-fA-F]{4}:[0-9a-fA-F]{4}$ ]]; then |
| 137 | die "--device takes VID:DID in hex, as lspci -nn prints it (e.g. 1002:744c), not '$DEVICE'" | 142 | die "--device takes VID:DID in hex, as lspci -nn prints it (e.g. 1002:744c), not '$DEVICE'" |
| 138 | fi | 143 | fi |
| 144 | [ -e "$SRC" ] || die "no build path at $SRC" | ||
| 139 | [ -f "$EXE" ] || die "no game executable at $EXE" | 145 | [ -f "$EXE" ] || die "no game executable at $EXE" |
| 140 | [ -d "$GAME" ] || die "no package folder at $GAME" | 146 | [ -d "$GAME" ] || die "no package folder at $GAME" |
| 141 | if [ "$SHADERS" != none ]; then | 147 | if [ "$SHADERS" != none ]; then |
| @@ -195,6 +201,7 @@ fi | |||
| 195 | # ---- one run at a time: a shared prefix has one wineserver ---- | 201 | # ---- one run at a time: a shared prefix has one wineserver ---- |
| 196 | LOCK=${LOCK:-${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/leonida-run-game-wine.lock}} | 202 | LOCK=${LOCK:-${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/leonida-run-game-wine.lock}} |
| 197 | LOCK=${LOCK:-$RUN/run.lock} | 203 | LOCK=${LOCK:-$RUN/run.lock} |
| 204 | mkdir -p "$(dirname "$LOCK")" || die "cannot create lock parent for $LOCK" | ||
| 198 | exec 9>"$LOCK" || die "cannot open the lock $LOCK" | 205 | exec 9>"$LOCK" || die "cannot open the lock $LOCK" |
| 199 | flock -n 9 || die "another run holds $LOCK" | 206 | flock -n 9 || die "another run holds $LOCK" |
| 200 | mkdir -p "$RUN/overlay" "$RUN/saves" | 207 | mkdir -p "$RUN/overlay" "$RUN/saves" |
| @@ -217,11 +224,17 @@ else | |||
| 217 | unset DISPLAY XAUTHORITY | 224 | unset DISPLAY XAUTHORITY |
| 218 | fi | 225 | fi |
| 219 | export QT_QPA_PLATFORM=offscreen | 226 | export QT_QPA_PLATFORM=offscreen |
| 227 | DRM_SYSFS=${LEONIDA_DRM_SYSFS_DIR:-/sys/class/drm} | ||
| 220 | if [ -n "$DEVICE" ]; then | 228 | if [ -n "$DEVICE" ]; then |
| 221 | export MESA_VK_DEVICE_SELECT="$DEVICE!" | 229 | export MESA_VK_DEVICE_SELECT="$DEVICE!" |
| 222 | # kwin and Xwayland's glamor on the card that renders, so the present path stays on one device. | 230 | # kwin and Xwayland's glamor on the card that renders, so the present path stays on one device. |
| 223 | for n in /sys/class/drm/renderD*; do | 231 | dev_lc=${DEVICE,,} |
| 224 | [ "$(cat "$n/device/vendor" 2>/dev/null):$(cat "$n/device/device" 2>/dev/null)" = "0x${DEVICE%%:*}:0x${DEVICE#*:}" ] \ | 232 | for n in "$DRM_SYSFS"/renderD*; do |
| 233 | [ -e "$n" ] || continue | ||
| 234 | ven=$(cat "$n/device/vendor" 2>/dev/null || true) | ||
| 235 | did=$(cat "$n/device/device" 2>/dev/null || true) | ||
| 236 | ven=${ven//$'\r'/}; did=${did//$'\r'/} | ||
| 237 | [ "${ven,,}:${did,,}" = "0x${dev_lc%%:*}:0x${dev_lc#*:}" ] \ | ||
| 225 | && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} | 238 | && export KWIN_DRM_DEVICES=/dev/dri/${n##*/} |
| 226 | done | 239 | done |
| 227 | else | 240 | else |
| @@ -242,8 +255,9 @@ else | |||
| 242 | fi | 255 | fi |
| 243 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" | 256 | env | grep -E '^(LEONIDA_|MESA_VK|WINEDLL|KWIN_DRM)' | sort > "$RUN/env.txt" |
| 244 | 257 | ||
| 245 | WINESERVER=$(dirname "$(command -v "$WINE")")/wineserver | 258 | wine_bin=$(command -v "$WINE" 2>/dev/null || true) |
| 246 | [ -x "$WINESERVER" ] || WINESERVER=wineserver | 259 | WINESERVER=${wine_bin:+$(dirname "$wine_bin")/wineserver} |
| 260 | [ -n "$WINESERVER" ] && [ -x "$WINESERVER" ] || WINESERVER=wineserver | ||
| 247 | SESSION_PID= | 261 | SESSION_PID= |
| 248 | teardown() { | 262 | teardown() { |
| 249 | "$WINESERVER" -k 2>/dev/null | 263 | "$WINESERVER" -k 2>/dev/null |
| @@ -257,7 +271,7 @@ trap 'exit 130' INT TERM HUP | |||
| 257 | 271 | ||
| 258 | # The session command with its arguments baked in (kwin takes one program path). | 272 | # The session command with its arguments baked in (kwin takes one program path). |
| 259 | { | 273 | { |
| 260 | echo '#!/bin/sh' | 274 | echo '#!/usr/bin/env bash' |
| 261 | printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" | 275 | printf 'exec %q --inner %q %q %q %q' "$SELF" "$RUN" "$BUILD" "$LIMIT" "$SHOT_EVERY" |
| 262 | for a in "$@"; do printf ' %q' "$a"; done | 276 | for a in "$@"; do printf ' %q' "$a"; done |
| 263 | echo | 277 | echo |
| @@ -276,10 +290,17 @@ else | |||
| 276 | fi | 290 | fi |
| 277 | SESSION_PID=$! | 291 | SESSION_PID=$! |
| 278 | # The session ends when the inner run returns; this outer limit adds a margin for the start-up. | 292 | # The session ends when the inner run returns; this outer limit adds a margin for the start-up. |
| 279 | ( sleep $((LIMIT + 180)); kill -TERM "$SESSION_PID" 2>/dev/null ) 9>&- 2>/dev/null & | 293 | ( trap 'kill "${watch_sleep_pid:-}" 2>/dev/null || true; exit 0' TERM INT |
| 294 | watch_sleep_pid="" | ||
| 295 | sleep $((LIMIT + 180)) & | ||
| 296 | watch_sleep_pid=$! | ||
| 297 | wait "$watch_sleep_pid" 2>/dev/null || exit 0 | ||
| 298 | kill -TERM "$SESSION_PID" 2>/dev/null ) 9>&- </dev/null >/dev/null 2>&1 & | ||
| 280 | WATCH=$! | 299 | WATCH=$! |
| 281 | wait "$SESSION_PID" | 300 | wait "$SESSION_PID" |
| 282 | pkill -P "$WATCH" 2>/dev/null; kill "$WATCH" 2>/dev/null | 301 | pkill -P "$WATCH" 2>/dev/null || true |
| 302 | kill "$WATCH" 2>/dev/null || true | ||
| 303 | wait "$WATCH" 2>/dev/null || true | ||
| 283 | teardown; SESSION_PID= | 304 | teardown; SESSION_PID= |
| 284 | T1=$(date +%s) | 305 | T1=$(date +%s) |
| 285 | 306 | ||
| @@ -289,5 +310,6 @@ if [ ! -f "$RUN/exit_code" ]; then | |||
| 289 | exit 3 | 310 | exit 3 |
| 290 | fi | 311 | fi |
| 291 | python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" | 312 | python3 -I "$ROOT/tools/game_run_summary.py" "$RUN" --limit-seconds "$LIMIT" | tee "$RUN/summary.txt" |
| 313 | summary_rc=${PIPESTATUS[0]} | ||
| 292 | echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." | 314 | echo "output: $RUN (stderr.log, boot.jsonl, summary.txt); total $((T1 - T0)) s. The logs stay on this machine." |
| 293 | exit 0 | 315 | exit "$summary_rc" |
diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index e0303951e..4b7321b3d 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py | |||
| @@ -37,6 +37,7 @@ from check import cbv_modulate_test | |||
| 37 | from check import IMAGE_STORE_CASES, texture_uav_test | 37 | from check import IMAGE_STORE_CASES, texture_uav_test |
| 38 | from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS | 38 | from check import salu_ext_test # 38 scalar ALU ops on operands seeded through VKC_SGPRS |
| 39 | from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT | 39 | from check import HEAP_INIT_EXPECTED, heap_init_env # cs_heap_init: vk_compute_test's VKC_HEAP_INIT |
| 40 | from check import CVT_F16_MODS_WORDS | ||
| 40 | from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations | 41 | from check import shift64_test # dynamic 64-bit vector shifts and overlapping destinations |
| 41 | from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands | 42 | from check import cmp_f64_test # the 32 binary64 vector compares on memory-fed operands |
| 42 | from check import round_f64_test # the four binary64 roundings on memory-fed inputs | 43 | from check import round_f64_test # the four binary64 roundings on memory-fed inputs |
| @@ -50,7 +51,7 @@ from check import run_readback | |||
| 50 | from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS | 51 | from check import MESH_COMPUTE, mesh_env # LEONIDA_MESH_COMPUTE=1: mesh shaders as compute + a generated VS |
| 51 | from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, | 52 | from check import (WAVE32_LANE_DUMPS, WAVE32_LANE_ENV, bitmask_perm_narrow_skip, narrow_subgroup_skip, |
| 52 | unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py | 53 | unpinned_subgroup_skip, vcmpx_forms_narrow_skip, wave32_lane_skip) # as in check.py |
| 53 | from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem # pixel producers and checks | 54 | from check import PIXEL_VERTEX, VINT_ENV, interp_f16_high_problem, ij_computed_problem, mandelbrot_problem, exp_f32_denorm_problem # pixel producers and checks |
| 54 | from check import barycentric_problem | 55 | from check import barycentric_problem |
| 55 | from check import NAN_PAYLOAD_TEST, nan_payload_problem | 56 | from check import NAN_PAYLOAD_TEST, nan_payload_problem |
| 56 | from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries | 57 | from check import GET_LOD_TESTS, STORE_WORDS, get_lod_test, store_words_problem # TEST-184: image atomics and queries |
| @@ -1156,7 +1157,7 @@ def run_suite(a, work: str) -> int: | |||
| 1156 | if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names | 1157 | if rc == 77: # Float64, or Int64 where the module declares both: quote whichever it names |
| 1157 | results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) | 1158 | results.append((name, None, compute_unsupported(rc, msg) or "SKIP (no shaderFloat64 on this device)")) |
| 1158 | else: | 1159 | else: |
| 1159 | ok, detail = judge_cs_dump(rc, msg, [0, 0x40040000], wave64=False, partial=False, emulated=False, | 1160 | ok, detail = judge_cs_dump(rc, msg, [0, 0x3FF40000], wave64=False, partial=False, emulated=False, |
| 1160 | hexwords=True) | 1161 | hexwords=True) |
| 1161 | results.append((name, ok, detail)) | 1162 | results.append((name, ok, detail)) |
| 1162 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): | 1163 | elif name in ("cs_div_fmas_f64", "cs_div_fmas_f64_rt"): |
| @@ -1221,7 +1222,7 @@ def run_suite(a, work: str) -> int: | |||
| 1221 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. | 1222 | # With LEONIDA_W64_EMULATE=1 it was translated with --wave64-emulate and runs on any subgroup size. |
| 1222 | results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) | 1223 | results.append((name,) + wavemask_check(vk_compute, spv, cs_env, w64_emulated())) |
| 1223 | elif name in ("cs_smem_vcc_base", "cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", | 1224 | elif name in ("cs_smem_vcc_base", "cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", "cs_exec_const", "cs_w32_mask_imm", "cs_w64_mask_imm", "cs_w32_lds_u8_d16", "cs_w32_lds_subdword", "cs_w32_lds_wide", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_wave64_ballot", "cs_wm_half_ops", "cs_wm_half_cmp", "cs_wm_bfm64", "cs_wm_scc_rfl", "cs_wqm_w64", "cs_wqm_w32", "cs_wqm_w64_half", |
| 1224 | "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", | 1225 | "cs_w32_cvt_f16_mods", "cs_dpp", "cs_dpp_row", "cs_dpp_mask", "cs_dpp8", "cs_dpp_ops", "cs_dpp_bank", "cs_dpp_fi", |
| 1225 | "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_dpp_w64", | 1226 | "cs_dpp_bound", "cs_dpp_cmp", "cs_dpp_cmpx", "cs_dpp_w64", |
| 1226 | "cs_w64_mask_detect", | 1227 | "cs_w64_mask_detect", |
| 1227 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", | 1228 | "cs_w64x_readlane", "cs_w64x_writelane", "cs_w64x_readfirstlane", "cs_w64x_bpermute", "cs_w64x_permute", |
| @@ -1255,6 +1256,7 @@ def run_suite(a, work: str) -> int: | |||
| 1255 | # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) | 1256 | # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) |
| 1256 | "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], | 1257 | "cs_w32_fcmpswap": [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000], |
| 1257 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], | 1258 | "cs_w32_new_ops": [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234], |
| 1259 | "cs_w32_cvt_f16_mods": CVT_F16_MODS_WORDS, | ||
| 1258 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], | 1260 | "cs_w32_misc_ext": [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D], |
| 1259 | "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], | 1261 | "cs_w32_salu64": [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE], |
| 1260 | # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) | 1262 | # SHADER-85: ds_read_u8/i8_d16[_hi] (cs_w32_lds_u8_d16.asm header) |
| @@ -1353,7 +1355,8 @@ def run_suite(a, work: str) -> int: | |||
| 1353 | want = cs_dump_wants[name] | 1355 | want = cs_dump_wants[name] |
| 1354 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / | 1356 | # Every dump but cs_store / cs_smem_soffset_imm / cs_w32_lane_wrap / cs_movrelsd_2 / cs_w32_permute / |
| 1355 | # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops / cs_signed_zero_nan, the wave32 | 1357 | # cs_w32_lds_u8_d16 / cs_w32_sincos / cs_w32_int_ext / cs_w32_salu64 / cs_w32_misc_ext / cs_w32_new_ops / cs_signed_zero_nan, the wave32 |
| 1356 | # cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: ask for a 64-wide subgroup and skip, | 1358 | # cs_w32_cvt_f16_mods / cs_wqm_w32 / cs_bpermute32 and the DPP tests is a whole-wave (wave64) mask test: |
| 1359 | # ask for a 64-wide subgroup and skip, | ||
| 1357 | # as check.py does, where the device has none | 1360 | # as check.py does, where the device has none |
| 1358 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were | 1361 | # (vk_compute_test exits 77) instead of reporting a failure. With LEONIDA_W64_EMULATE=1 they were |
| 1359 | # translated with --wave64-emulate and run on any subgroup size. | 1362 | # translated with --wave64-emulate and run on any subgroup size. |
| @@ -1365,7 +1368,7 @@ def run_suite(a, work: str) -> int: | |||
| 1365 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") | 1368 | partial = name in ("cs_w64x_partial", "cs_w64x_partial_scmp", "cs_w64x_partial_swizzle") |
| 1366 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", | 1369 | wave64 = name not in ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", |
| 1367 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", | 1370 | "cs_w32_permute", "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", |
| 1368 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", | 1371 | "cs_w32_lds_u8_d16", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_cvt_f16_mods", |
| 1369 | "cs_w32_lds_subdword", "cs_w32_lds_wide", | 1372 | "cs_w32_lds_subdword", "cs_w32_lds_wide", |
| 1370 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", | 1373 | "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_w32_permlane_fi", "cs_w32_sincos", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", |
| 1371 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", | 1374 | "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_wrxchg2_ext", "cs_w32_wrxchg2st64", "cs_exec_const", "cs_w32_mask_imm", "cs_mask_vgpr_exec", |
| @@ -1532,6 +1535,7 @@ def run_suite(a, work: str) -> int: | |||
| 1532 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), | 1535 | "ps_ops7": (0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003), |
| 1533 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), | 1536 | "ps_ops8": (0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F), |
| 1534 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), | 1537 | "ps_f32_mods": (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000), |
| 1538 | "ps_exp_f32_denorm": (0x01000000, 0x00800000, 0x00000000, 0x00000000), | ||
| 1535 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), | 1539 | "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), |
| 1536 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) | 1540 | "ps_vcmpx_forms": (0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000), # 14 v_cmpx forms (.asm header) |
| 1537 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) | 1541 | "ps_vcmp_int32": (0x963E52E8, 0x984DCEE8, 0xB9458EE8, 0xB73612E8), # u32/i32 compares (.asm header) |
| @@ -1540,7 +1544,7 @@ def run_suite(a, work: str) -> int: | |||
| 1540 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), | 1544 | "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), |
| 1541 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), | 1545 | "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), |
| 1542 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), | 1546 | "ps_fma_literal": (0x41B80000, 0x41800000, 0x40E00000, 0x41A40000), |
| 1543 | "ps_f64_mods": (0x40040000, 0x3FF00000, 0x3FE40000, 0x3FF00000), # needs shaderFloat64 | 1547 | "ps_f64_mods": (0x3FF40000, 0x3FF00000, 0x3FF00000, 0x3FD00000), # needs shaderFloat64 |
| 1544 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 | 1548 | "ps_f64_round": (0xC12AF665, 0x3FE7FFFF, 0xBFFFFFFF, 0xC12AF666), # needs shaderFloat64 |
| 1545 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), | 1549 | "ps_outmods_f16": (0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000), |
| 1546 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) | 1550 | # f16 op_sel / partial writes / inline constants: RDNA2 hardware words (see the .asm headers) |
| @@ -1623,6 +1627,9 @@ def run_suite(a, work: str) -> int: | |||
| 1623 | elif name == "ps_ij_computed": | 1627 | elif name == "ps_ij_computed": |
| 1624 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | 1628 | problem = ij_computed_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) |
| 1625 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" | 1629 | ok, detail = not problem, problem or "computed I/J pair words and v/2 within 1e-6" |
| 1630 | elif name == "ps_exp_f32_denorm_rt": | ||
| 1631 | problem = exp_f32_denorm_problem(read_raw_u32(raw) if os.path.isfile(raw) else []) | ||
| 1632 | ok, detail = not problem, problem or "4096 pixels exact across 64 runtime-dependent inputs" | ||
| 1626 | elif name == "ps_mandelbrot": | 1633 | elif name == "ps_mandelbrot": |
| 1627 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] | 1634 | px = read_raw_u32(raw) if os.path.isfile(raw) else [] |
| 1628 | problem = frame_problem(px) or mandelbrot_problem(px) | 1635 | problem = frame_problem(px) or mandelbrot_problem(px) |
diff --git a/scripts/run_guest_scene.py b/scripts/run_guest_scene.py index 60d5ded90..55f770c8b 100644 --- a/scripts/run_guest_scene.py +++ b/scripts/run_guest_scene.py | |||
| @@ -256,12 +256,13 @@ def negative_controls(session: Session, out: Path) -> dict: | |||
| 256 | 256 | ||
| 257 | 257 | ||
| 258 | def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: | 258 | def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: |
| 259 | session = Session(args, out) | ||
| 259 | try: | 260 | try: |
| 260 | out.mkdir(parents=True, exist_ok=True) # parse_args has checked that it is new or empty | 261 | out.mkdir(parents=True, exist_ok=True) # parse_args has checked that it is new or empty |
| 262 | session.logs.mkdir() # Reserve the output even if another run passed the same check. | ||
| 261 | except OSError as exc: | 263 | except OSError as exc: |
| 262 | print(f"error: could not create output directory {out}: {exc}", file=sys.stderr) | 264 | print(f"error: could not create output directory {out}: {exc}", file=sys.stderr) |
| 263 | return 1 | 265 | return 1 |
| 264 | session = Session(args, out) | ||
| 265 | report: dict = {"status": "fail", "frames": FRAMES, "headless": True, "wine": args.wine, "temporary": temporary, | 266 | report: dict = {"status": "fail", "frames": FRAMES, "headless": True, "wine": args.wine, "temporary": temporary, |
| 266 | "audio_mode": "winmm" if args.play_audio else "offline", "report": str(out / "report.json")} | 267 | "audio_mode": "winmm" if args.play_audio else "offline", "report": str(out / "report.json")} |
| 267 | try: | 268 | try: |
| @@ -271,7 +272,7 @@ def execute(args: argparse.Namespace, out: Path, temporary: bool) -> int: | |||
| 271 | "guest": {"path": str(args.guest), "sha256": sha256(args.guest.read_bytes())}, | 272 | "guest": {"path": str(args.guest), "sha256": sha256(args.guest.read_bytes())}, |
| 272 | "shaders": {"path": str(args.shaders), "files": len(shader_files), "tree_sha256": tree_hash(shader_files)}, | 273 | "shaders": {"path": str(args.shaders), "files": len(shader_files), "tree_sha256": tree_hash(shader_files)}, |
| 273 | "scene.bin": sha256(scene_bytes())} | 274 | "scene.bin": sha256(scene_bytes())} |
| 274 | for sub in ("logs", "package", *MODES): | 275 | for sub in ("package", *MODES): |
| 275 | (out / sub).mkdir() | 276 | (out / sub).mkdir() |
| 276 | package = out / "package" | 277 | package = out / "package" |
| 277 | write_new(package / "scene.bin", scene_bytes()) | 278 | write_new(package / "scene.bin", scene_bytes()) |
diff --git a/scripts/run_wine_session.sh b/scripts/run_wine_session.sh index 72ace4407..437e18c3c 100755 --- a/scripts/run_wine_session.sh +++ b/scripts/run_wine_session.sh | |||
| @@ -1,9 +1,23 @@ | |||
| 1 | #!/usr/bin/env bash | 1 | #!/usr/bin/env bash |
| 2 | # Run CI tests on the display that initialized their dedicated Wine prefix. | 2 | # Run CI tests on the display that initialized their dedicated Wine prefix. |
| 3 | # | ||
| 4 | # The prefix is initialized and stopped with the Wine the tests use: $WINE (default: wine), as | ||
| 5 | # run_wine_tests.py does, so Proton's or UMU-Proton's files/bin/wine also works on a host without a | ||
| 6 | # system Wine. The wineserver is $WINESERVER, else the one next to $WINE, else wineserver on PATH. | ||
| 3 | set -e | 7 | set -e |
| 4 | : "${WINEPREFIX:?Set WINEPREFIX to a dedicated test prefix}" | 8 | : "${WINEPREFIX:?Set WINEPREFIX to a dedicated test prefix}" |
| 5 | 9 | ||
| 10 | wine=${WINE:-wine} | ||
| 11 | if ! wine_path=$(command -v -- "$wine"); then | ||
| 12 | echo "run_wine_session.sh: Wine not found: $wine (set WINE to the wine executable)" >&2 | ||
| 13 | exit 127 | ||
| 14 | fi | ||
| 15 | if [[ -z ${WINESERVER:-} ]]; then | ||
| 16 | WINESERVER=$(dirname -- "$wine_path")/wineserver | ||
| 17 | [[ -x $WINESERVER ]] || WINESERVER=wineserver | ||
| 18 | fi | ||
| 19 | |||
| 6 | # Stop this prefix's Wine processes before Xvfb tears down the display. | 20 | # Stop this prefix's Wine processes before Xvfb tears down the display. |
| 7 | trap 'wineserver -k || true' EXIT | 21 | trap '"$WINESERVER" -k || true' EXIT |
| 8 | timeout 5m wineboot --init </dev/null | 22 | timeout 5m "$wine_path" wineboot --init </dev/null |
| 9 | "$@" </dev/null | 23 | "$@" </dev/null |
diff --git a/scripts/run_wine_tests.py b/scripts/run_wine_tests.py index 393b17ce9..acd933ee3 100644 --- a/scripts/run_wine_tests.py +++ b/scripts/run_wine_tests.py | |||
| @@ -21,11 +21,13 @@ Each test gets WINEDLLOVERRIDES with winedbg.exe and winemenubuilder.exe disable | |||
| 21 | waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One | 21 | waiting in the debugger until the timeout; an entry of the caller's or the test's for the same program wins. One |
| 22 | wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command, | 22 | wineserver is kept alive for the whole run (`wineserver -p`: $WINESERVER, else the one next to the --wine command, |
| 23 | else the one on PATH) and stopped at the end, instead of a new one starting for every test. | 23 | else the one on PATH) and stopped at the end, instead of a new one starting for every test. |
| 24 | Separate runs under Wine must use different prefixes or run one after the other. | ||
| 24 | --jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and | 25 | --jobs N runs N tests at a time. Tests marked RUN_SERIAL run alone, tests sharing a RESOURCE_LOCK never overlap, and |
| 25 | DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default). | 26 | DEPENDS and fixtures are kept; the report is in the same order as with --jobs 1 (the default). |
| 26 | """ | 27 | """ |
| 27 | import argparse | 28 | import argparse |
| 28 | from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait | 29 | from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait |
| 30 | from contextlib import ExitStack, contextmanager | ||
| 29 | from graphlib import CycleError, TopologicalSorter | 31 | from graphlib import CycleError, TopologicalSorter |
| 30 | import json | 32 | import json |
| 31 | import math | 33 | import math |
| @@ -42,6 +44,8 @@ import threading | |||
| 42 | import time | 44 | import time |
| 43 | 45 | ||
| 44 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 46 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 47 | # subprocess uses poll on Linux, whose timeout is a signed int in milliseconds. | ||
| 48 | MAX_TIMEOUT_SECONDS = (2**31 - 1) // 1_000 | ||
| 45 | 49 | ||
| 46 | 50 | ||
| 47 | def _make_parent(path: str) -> None: | 51 | def _make_parent(path: str) -> None: |
| @@ -69,6 +73,30 @@ def map_path(arg: str, windows_root: str, root: str) -> str | None: | |||
| 69 | return None | 73 | return None |
| 70 | 74 | ||
| 71 | 75 | ||
| 76 | @contextmanager | ||
| 77 | def prefix_ownership(prefix: str): | ||
| 78 | """Keep another runner from sharing this run's temporary drive or kept server.""" | ||
| 79 | if os.name != "posix": | ||
| 80 | yield None # Native Windows only runs the synthetic harness tests. | ||
| 81 | return | ||
| 82 | |||
| 83 | import fcntl | ||
| 84 | |||
| 85 | with ExitStack() as cleanup: | ||
| 86 | try: | ||
| 87 | os.makedirs(prefix, mode=0o700, exist_ok=True) | ||
| 88 | # Lock the directory itself so aliases share one lock, with no stale lock file after an interruption. | ||
| 89 | fd = os.open(prefix, os.O_RDONLY | os.O_DIRECTORY) | ||
| 90 | cleanup.callback(os.close, fd) | ||
| 91 | fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
| 92 | except BlockingIOError: | ||
| 93 | yield f"a Wine test runner is already running in {prefix}; use another WINEPREFIX or retry after it ends" | ||
| 94 | except OSError as exc: | ||
| 95 | yield f"cannot lock Wine prefix {prefix}: {exc.strerror or exc}" | ||
| 96 | else: | ||
| 97 | yield None | ||
| 98 | |||
| 99 | |||
| 72 | class DriveMap: | 100 | class DriveMap: |
| 73 | """Points the drive of the Windows checkout at the Linux one inside the Wine prefix, for the run. | 101 | """Points the drive of the Windows checkout at the Linux one inside the Wine prefix, for the run. |
| 74 | 102 | ||
| @@ -190,6 +218,14 @@ class KeptServer: | |||
| 190 | except (OSError, subprocess.TimeoutExpired): | 218 | except (OSError, subprocess.TimeoutExpired): |
| 191 | return None | 219 | return None |
| 192 | 220 | ||
| 221 | def _warmup(self) -> None: | ||
| 222 | env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) | ||
| 223 | try: | ||
| 224 | subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, | ||
| 225 | stderr=subprocess.DEVNULL, env=env, timeout=120) | ||
| 226 | except (OSError, subprocess.TimeoutExpired): | ||
| 227 | pass # the tests start the services then, as without a kept server | ||
| 228 | |||
| 193 | def __enter__(self): | 229 | def __enter__(self): |
| 194 | if not self.command: | 230 | if not self.command: |
| 195 | self.note = "no wineserver found: each test starts its own" | 231 | self.note = "no wineserver found: each test starts its own" |
| @@ -200,18 +236,14 @@ class KeptServer: | |||
| 200 | code = self._run("-p") | 236 | code = self._run("-p") |
| 201 | else: | 237 | else: |
| 202 | self.note = "a wineserver already runs for this prefix: used and left running" | 238 | self.note = "a wineserver already runs for this prefix: used and left running" |
| 239 | self._warmup() | ||
| 203 | return self | 240 | return self |
| 204 | self.started = code == 0 | 241 | self.started = code == 0 |
| 205 | if not self.started: | 242 | if not self.started: |
| 206 | self.note = f"could not start {self.command} -p: each test starts its own server" | 243 | self.note = f"could not start {self.command} -p: each test starts its own server" |
| 207 | return self | 244 | return self |
| 208 | self.note = "wineserver kept alive for the run" | 245 | self.note = "wineserver kept alive for the run" |
| 209 | env = dict(os.environ, WINEDLLOVERRIDES=merge_dll_overrides(os.environ.get("WINEDLLOVERRIDES"))) | 246 | self._warmup() |
| 210 | try: | ||
| 211 | subprocess.run(self.wine + ["wineboot"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, | ||
| 212 | stderr=subprocess.DEVNULL, env=env, timeout=120) | ||
| 213 | except (OSError, subprocess.TimeoutExpired): | ||
| 214 | pass # the tests start the services then, as without a kept server | ||
| 215 | return self | 247 | return self |
| 216 | 248 | ||
| 217 | def __exit__(self, *exc): | 249 | def __exit__(self, *exc): |
| @@ -395,15 +427,13 @@ def stop_running_tests() -> None: | |||
| 395 | 427 | ||
| 396 | 428 | ||
| 397 | def positive_seconds(text: str) -> float: | 429 | def positive_seconds(text: str) -> float: |
| 398 | """--timeout: a finite value greater than 0, so subprocess.run never gets a bad timeout to raise on.""" | 430 | """Parse a positive timeout that fits the subprocess wait on all supported hosts.""" |
| 399 | try: | 431 | try: |
| 400 | value = float(text) | 432 | value = float(text) |
| 401 | except ValueError: | 433 | except ValueError: |
| 402 | raise argparse.ArgumentTypeError(f"invalid float value: {text!r}") from None | 434 | raise argparse.ArgumentTypeError(f"invalid float value: {text!r}") from None |
| 403 | if not math.isfinite(value): | 435 | if not 0 < value <= MAX_TIMEOUT_SECONDS: |
| 404 | raise argparse.ArgumentTypeError("must be a finite number") | 436 | raise argparse.ArgumentTypeError(f"must be positive and no greater than {MAX_TIMEOUT_SECONDS} seconds") |
| 405 | if value <= 0: | ||
| 406 | raise argparse.ArgumentTypeError("must be greater than 0") | ||
| 407 | return value | 437 | return value |
| 408 | 438 | ||
| 409 | 439 | ||
| @@ -435,7 +465,7 @@ def valid_test_property(entry) -> bool: | |||
| 435 | name, value = entry["name"], entry["value"] | 465 | name, value = entry["name"], entry["value"] |
| 436 | if name == "WORKING_DIRECTORY": | 466 | if name == "WORKING_DIRECTORY": |
| 437 | return isinstance(value, str) and "\0" not in value | 467 | return isinstance(value, str) and "\0" not in value |
| 438 | if name in ("PASS_REGULAR_EXPRESSION", "FAIL_REGULAR_EXPRESSION", "SKIP_REGULAR_EXPRESSION"): | 468 | if name in ("PASS_REGULAR_EXPRESSION", "FAIL_REGULAR_EXPRESSION", "SKIP_REGULAR_EXPRESSION", "RESOURCE_LOCK"): |
| 439 | return isinstance(value, str) or (isinstance(value, list) and all(isinstance(p, str) for p in value)) | 469 | return isinstance(value, str) or (isinstance(value, list) and all(isinstance(p, str) for p in value)) |
| 440 | return True | 470 | return True |
| 441 | 471 | ||
| @@ -517,7 +547,8 @@ def main() -> int: | |||
| 517 | help="Wine command (default: $WINE or wine)") | 547 | help="Wine command (default: $WINE or wine)") |
| 518 | ap.add_argument("--require", action="append", default=[], help="a test name whose entries must all pass (repeatable)") | 548 | ap.add_argument("--require", action="append", default=[], help="a test name whose entries must all pass (repeatable)") |
| 519 | ap.add_argument("--timeout", type=positive_seconds, default=120.0, | 549 | ap.add_argument("--timeout", type=positive_seconds, default=120.0, |
| 520 | help="maximum seconds per test; a shorter CTest TIMEOUT applies (default 120)") | 550 | help=f"maximum seconds per test (default 120, upper limit {MAX_TIMEOUT_SECONDS}). " |
| 551 | "A shorter CTest TIMEOUT applies.") | ||
| 521 | ap.add_argument("--jobs", type=positive_int, default=1, | 552 | ap.add_argument("--jobs", type=positive_int, default=1, |
| 522 | help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)") | 553 | help="tests run at a time; RUN_SERIAL and RESOURCE_LOCK are kept (default 1)") |
| 523 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") | 554 | ap.add_argument("--summary", help="append a Markdown table to this file (e.g. $GITHUB_STEP_SUMMARY)") |
| @@ -561,7 +592,13 @@ def main() -> int: | |||
| 561 | for line in detail.rstrip().splitlines()[-40:]: | 592 | for line in detail.rstrip().splitlines()[-40:]: |
| 562 | print(f" {line}") | 593 | print(f" {line}") |
| 563 | 594 | ||
| 564 | with DriveMap(args.windows_root, args.root, prefix) as drive, KeptServer(find_wineserver(wine), wine) as server: | 595 | with ExitStack() as run: |
| 596 | lock_error = run.enter_context(prefix_ownership(prefix)) | ||
| 597 | if lock_error: | ||
| 598 | print(f"ERROR: {lock_error}", file=sys.stderr) | ||
| 599 | return 2 | ||
| 600 | drive = run.enter_context(DriveMap(args.windows_root, args.root, prefix)) | ||
| 601 | server = run.enter_context(KeptServer(find_wineserver(wine), wine)) | ||
| 565 | print(drive.note, flush=True) | 602 | print(drive.note, flush=True) |
| 566 | print(server.note, flush=True) | 603 | print(server.note, flush=True) |
| 567 | if args.jobs == 1: | 604 | if args.jobs == 1: |
diff --git a/scripts/sync_victory.py b/scripts/sync_victory.py index 764384163..ccae2c459 100644 --- a/scripts/sync_victory.py +++ b/scripts/sync_victory.py | |||
| @@ -90,4 +90,5 @@ def main(): | |||
| 90 | 90 | ||
| 91 | 91 | ||
| 92 | if __name__ == "__main__": | 92 | if __name__ == "__main__": |
| 93 | sys.stdout.reconfigure(errors="replace") | ||
| 93 | sys.exit(main()) | 94 | sys.exit(main()) |
diff --git a/scripts/vs_input_survey.py b/scripts/vs_input_survey.py index 0c2326309..a4807249c 100644 --- a/scripts/vs_input_survey.py +++ b/scripts/vs_input_survey.py | |||
| @@ -18,13 +18,19 @@ Standard library only. Nothing from the game is printed or written beyond counts | |||
| 18 | """ | 18 | """ |
| 19 | import argparse | 19 | import argparse |
| 20 | import json | 20 | import json |
| 21 | import ntpath | ||
| 21 | import os | 22 | import os |
| 23 | import posixpath | ||
| 22 | import re | 24 | import re |
| 23 | import sys | 25 | import sys |
| 26 | import tempfile | ||
| 24 | from collections import Counter | 27 | from collections import Counter |
| 25 | 28 | ||
| 26 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 29 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 27 | sys.path.insert(0, os.path.join(ROOT, "tools")) | 30 | sys.path.insert(0, os.path.join(ROOT, "tools")) |
| 31 | from file_mode import published_mode # noqa: E402 | ||
| 32 | from replace_retry import replace as replace_retry # noqa: E402 | ||
| 33 | from report_paths import same_report_path # noqa: E402 | ||
| 28 | import shader_ir # noqa: E402 | 34 | import shader_ir # noqa: E402 |
| 29 | from shader_meta import SGPR_RMW # noqa: E402 | 35 | from shader_meta import SGPR_RMW # noqa: E402 |
| 30 | 36 | ||
| @@ -84,7 +90,10 @@ def read_before_write(insns): | |||
| 84 | elif op == "v_swap_b32" and len(args) >= 2: | 90 | elif op == "v_swap_b32" and len(args) >= 2: |
| 85 | dsts, srcs = args[:2], args[:2] | 91 | dsts, srcs = args[:2], args[:2] |
| 86 | elif (op.startswith("v_") and ("_co_" in op or op in DUAL_DST_VALU) | 92 | elif (op.startswith("v_") and ("_co_" in op or op in DUAL_DST_VALU) |
| 87 | and len(args) >= 2 and args[1]["k"] in ("sgpr", "special", "slist")): | 93 | and len(args) >= 2 and args[1]["k"] in ("sgpr", "special", "slist") |
| 94 | # the short form v_add_co_ci_u32 vD, src0, src1 (also sub/subrev): carry out and in are an | ||
| 95 | # implicit VCC, and args[1] is src0, a read | ||
| 96 | and not (op.endswith("_co_ci_u32") and len(args) == 3)): | ||
| 88 | dsts, srcs = args[:2], args[2:] # vdst + scalar carry/scale-out dst | 97 | dsts, srcs = args[:2], args[2:] # vdst + scalar carry/scale-out dst |
| 89 | else: | 98 | else: |
| 90 | dst_read = ( | 99 | dst_read = ( |
| @@ -109,21 +118,69 @@ def read_before_write(insns): | |||
| 109 | return read_s, read_v | 118 | return read_s, read_v |
| 110 | 119 | ||
| 111 | 120 | ||
| 112 | def survey(dxbc_dir): | 121 | def _safe_shader_stem(value): |
| 113 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8") as f: | 122 | """Validate an index.json 'file' basename against path traversal and return its stem.""" |
| 123 | if ( | ||
| 124 | not isinstance(value, str) | ||
| 125 | or not value | ||
| 126 | or any(ord(c) < 32 or ord(c) == 127 for c in value) | ||
| 127 | or ":" in value | ||
| 128 | or "/" in value | ||
| 129 | or "\\" in value | ||
| 130 | or ntpath.splitdrive(value)[0] | ||
| 131 | or ntpath.basename(value) != value | ||
| 132 | or posixpath.basename(value) != value | ||
| 133 | ): | ||
| 134 | raise ValueError(f"index.json has an invalid shader filename: {value!r}") | ||
| 135 | stem = os.path.splitext(value)[0] | ||
| 136 | if not stem or stem in (".", ".."): | ||
| 137 | raise ValueError(f"index.json has an invalid shader filename: {value!r}") | ||
| 138 | return stem | ||
| 139 | |||
| 140 | |||
| 141 | def _write_json_atomic(path, payload): | ||
| 142 | """Write JSON to a sibling staging file and rename atomically, cleaning up read-only staging on error.""" | ||
| 143 | dest = os.path.abspath(path) | ||
| 144 | parent = os.path.dirname(dest) or "." | ||
| 145 | staged = None | ||
| 146 | try: | ||
| 147 | with tempfile.NamedTemporaryFile( | ||
| 148 | mode="w", encoding="utf-8", newline="\n", delete=False, | ||
| 149 | dir=parent, prefix=".vs_input_survey-", suffix=".tmp", | ||
| 150 | ) as f: | ||
| 151 | staged = f.name | ||
| 152 | json.dump(payload, f, indent=1) | ||
| 153 | f.write("\n") | ||
| 154 | os.chmod(staged, published_mode(dest)) | ||
| 155 | replace_retry(staged, dest) | ||
| 156 | staged = None | ||
| 157 | finally: | ||
| 158 | if staged is not None: | ||
| 159 | try: | ||
| 160 | os.chmod(staged, 0o600) | ||
| 161 | except OSError: | ||
| 162 | pass | ||
| 163 | try: | ||
| 164 | os.unlink(staged) | ||
| 165 | except OSError: | ||
| 166 | pass | ||
| 167 | |||
| 168 | |||
| 169 | def _survey_detail(dxbc_dir): | ||
| 170 | with open(os.path.join(dxbc_dir, "index.json"), encoding="utf-8-sig") as f: | ||
| 114 | index = json.load(f) | 171 | index = json.load(f) |
| 115 | if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): | 172 | if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): |
| 116 | raise ValueError("index.json is not a list of shader entries") | 173 | raise ValueError("index.json is not a list of shader entries") |
| 117 | if not all(isinstance(e.get("file"), str) for e in index if e.get("stage") == "vs"): | 174 | names = [_safe_shader_stem(e.get("file")) for e in index if e.get("stage") == "vs"] |
| 118 | raise ValueError("index.json has a vertex shader entry without a string file") | ||
| 119 | names = [os.path.splitext(e["file"])[0] for e in index if e.get("stage") == "vs"] | ||
| 120 | markers, vgprs, families = Counter(), Counter(), Counter() | 175 | markers, vgprs, families = Counter(), Counter(), Counter() |
| 121 | missing = 0 | 176 | missing = 0 |
| 177 | disasm_paths = [] | ||
| 122 | for n in names: | 178 | for n in names: |
| 123 | path = os.path.join(dxbc_dir, "disasm", n + ".s") | 179 | path = os.path.join(dxbc_dir, "disasm", n + ".s") |
| 124 | if not os.path.isfile(path): | 180 | if not os.path.isfile(path): |
| 125 | missing += 1 | 181 | missing += 1 |
| 126 | continue | 182 | continue |
| 183 | disasm_paths.append(path) | ||
| 127 | with open(path, encoding="utf-8", errors="replace") as f: | 184 | with open(path, encoding="utf-8", errors="replace") as f: |
| 128 | text = f.read() | 185 | text = f.read() |
| 129 | _, read_v = read_before_write(shader_ir.parse_file(path)["insns"]) | 186 | _, read_v = read_before_write(shader_ir.parse_file(path)["insns"]) |
| @@ -143,25 +200,39 @@ def survey(dxbc_dir): | |||
| 143 | families["reads v0 (vertex id)" + (" and v3 (instance id)" if 3 in read_v else "")] += 1 | 200 | families["reads v0 (vertex id)" + (" and v3 (instance id)" if 3 in read_v else "")] += 1 |
| 144 | else: | 201 | else: |
| 145 | families["reads neither v0 nor a fetch call"] += 1 | 202 | families["reads neither v0 nor a fetch call"] += 1 |
| 146 | return {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers), | 203 | result = {"vertex_shaders": len(names), "missing_listings": missing, "markers": dict(markers), |
| 147 | "input_vgprs_read": dict(sorted(vgprs.items(), key=lambda kv: int(kv[0][1:]))), | 204 | "input_vgprs_read": dict(sorted(vgprs.items(), key=lambda kv: int(kv[0][1:]))), |
| 148 | "families": dict(families)} | 205 | "families": dict(families)} |
| 206 | return result, disasm_paths | ||
| 207 | |||
| 208 | |||
| 209 | def survey(dxbc_dir): | ||
| 210 | return _survey_detail(dxbc_dir)[0] | ||
| 149 | 211 | ||
| 150 | 212 | ||
| 151 | def main(): | 213 | def main(argv=None): |
| 152 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | 214 | ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) |
| 153 | ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py") | 215 | ap.add_argument("dxbc", help="<work>/shaders/dxbc from make_game.py") |
| 154 | ap.add_argument("--json", help="also write the counts as JSON") | 216 | ap.add_argument("--json", help="also write the counts as JSON") |
| 155 | a = ap.parse_args() | 217 | a = ap.parse_args(argv) |
| 156 | index_path = os.path.join(a.dxbc, "index.json") | 218 | index_path = os.path.join(a.dxbc, "index.json") |
| 157 | if a.json and os.path.exists(a.json) and os.path.exists(index_path) and os.path.samefile(a.json, index_path): | 219 | if a.json: |
| 158 | print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr) | 220 | if os.path.isdir(a.json): |
| 159 | return 2 | 221 | print(f"vs_input_survey: error: --json is a directory: {a.json}", file=sys.stderr) |
| 222 | return 2 | ||
| 223 | if same_report_path(a.json, index_path) or same_report_path(a.json, a.dxbc): | ||
| 224 | print(f"vs_input_survey: error: --json would overwrite the input {index_path}", file=sys.stderr) | ||
| 225 | return 2 | ||
| 160 | try: | 226 | try: |
| 161 | r = survey(a.dxbc) | 227 | r, disasm_paths = _survey_detail(a.dxbc) |
| 162 | except (OSError, ValueError) as e: # missing or non-folder <dxbc>, unreadable, non-UTF-8 or malformed index.json | 228 | except (OSError, ValueError) as e: # missing or non-folder <dxbc>, unreadable, non-UTF-8 or malformed index.json |
| 163 | print(f"vs_input_survey: error: cannot read {index_path}: {e}", file=sys.stderr) | 229 | print(f"vs_input_survey: error: cannot read {index_path}: {e}", file=sys.stderr) |
| 164 | return 2 | 230 | return 2 |
| 231 | if a.json: | ||
| 232 | for src_path in disasm_paths: | ||
| 233 | if same_report_path(a.json, src_path): | ||
| 234 | print(f"vs_input_survey: error: --json would overwrite the input {src_path}", file=sys.stderr) | ||
| 235 | return 2 | ||
| 165 | m = r["markers"] | 236 | m = r["markers"] |
| 166 | print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)") | 237 | print(f"{r['vertex_shaders']} vertex shaders ({r['missing_listings']} without a listing)") |
| 167 | print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}") | 238 | print(f"NGG markers: exp prim {m.get('exp prim', 0)}, s_sendmsg {m.get('s_sendmsg', 0)}, v_mbcnt {m.get('v_mbcnt', 0)}") |
| @@ -172,8 +243,7 @@ def main(): | |||
| 172 | print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout") | 243 | print("layout:", "legacy (non-NGG) VS" if legacy else "NGG markers present: check the VS input layout") |
| 173 | if a.json: | 244 | if a.json: |
| 174 | try: | 245 | try: |
| 175 | with open(a.json, "w", encoding="utf-8", newline="\n") as f: | 246 | _write_json_atomic(a.json, r) |
| 176 | json.dump(r, f, indent=1) | ||
| 177 | except OSError as e: | 247 | except OSError as e: |
| 178 | print(f"vs_input_survey: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) | 248 | print(f"vs_input_survey: error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) |
| 179 | return 2 | 249 | return 2 |
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md index ac76ecdaa..8fbba6182 100644 --- a/scripts/windows-boot/README.md +++ b/scripts/windows-boot/README.md | |||
| @@ -69,9 +69,11 @@ faults: none | |||
| 69 | frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00 | 69 | frames: 14 captured, 0 non-black; last mean rgb 0.00 0.00 0.00; brightest 0.00 0.00 0.00 |
| 70 | ``` | 70 | ``` |
| 71 | 71 | ||
| 72 | `-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The digest holds counts and | 72 | `-DigestOnly -Name <name>` writes the summary and digest again for an earlier run. The `faults` row reports whether |
| 73 | states only, which is what goes into a RESULT on the board; the logs, traces, captures and dumps can quote the game | 73 | the log recorded device loss and counts Vulkan address records by type (for example, `WRITE_INVALID=2`). |
| 74 | and stay on your machine ([AGENTS.md](../../AGENTS.md), "No game data"). | 74 | Several records can describe one loss. A driver can also report loss without any address records. |
| 75 | Share counts and states on the board. Keep paths, logs, traces, captures and dumps on your machine | ||
| 76 | ([AGENTS.md](../../AGENTS.md), "No game data"). | ||
| 75 | 77 | ||
| 76 | How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing | 78 | How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing |
| 77 | screen waiting for A), `d` after A. | 79 | screen waiting for A), `d` after A. |
| @@ -84,6 +86,10 @@ session=?`. A `LEONIDA_PEEK` of your own still works for the log, but the digest | |||
| 84 | variables name. `docs/linux_proton.md` (the same stages apply natively) | 86 | variables name. `docs/linux_proton.md` (the same stages apply natively) |
| 85 | section 2 has the healthy sequence with times and section 3 "which blank do you have". | 87 | section 2 has the healthy sequence with times and section 3 "which blank do you have". |
| 86 | 88 | ||
| 89 | To pair scripted presses with state changes after a run, use `python -I tools/stage_timeline.py LOG` with the same | ||
| 90 | two environment variables. For a saved log, `--game-state-rva` and `--session-state-rva` override them. If the log | ||
| 91 | also records the loading-screen state, pass its hex RVA with `--load-state-rva` to see when the screen ended. | ||
| 92 | |||
| 87 | ## One game at a time | 93 | ## One game at a time |
| 88 | 94 | ||
| 89 | The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe` | 95 | The script holds the named mutex `Local\LeonidaGameBoot` for the whole boot and also waits while any `gta6rt.exe` |
| @@ -99,3 +105,33 @@ game processes on one GPU make both runs meaningless and can take the driver dow | |||
| 99 | | `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only | | 105 | | `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only | |
| 100 | 106 | ||
| 101 | Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). | 107 | Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). |
| 108 | |||
| 109 | ## Recover a stack from a manually mapped image | ||
| 110 | |||
| 111 | When the exception stack stops inside the mapped executable, run `mapped_stack.py` on the existing | ||
| 112 | private dump. Supply the exact PE from the crashing build and an x64 CDB from Debugging Tools for | ||
| 113 | Windows. If CDB is on your PATH, omit `--cdb`. The optional `--symbols` takes one local directory | ||
| 114 | containing the matching runtime images and PDBs. | ||
| 115 | |||
| 116 | ```powershell | ||
| 117 | py -3 -I scripts\windows-boot\mapped_stack.py D:\runs\fault\crash.dmp D:\package\title.exe --symbols D:\build\RelWithDebInfo --cdb "C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe" | ||
| 118 | ``` | ||
| 119 | |||
| 120 | The command derives the mapping base, including a relocated base, by locating a unique captured | ||
| 121 | instruction window in an executable section of the supplied PE. It checks for a file-backed x64 | ||
| 122 | unwind entry at the exception RIP and compares captured bytes from the first header page and that | ||
| 123 | function's unwind metadata when available. | ||
| 124 | A small dump can establish a local code match only. Use the original image even if another build | ||
| 125 | has the same function. Exit-only snapshots, faults outside the supplied image, leaf functions | ||
| 126 | without unwind entries, and missing, patched or ambiguous instruction windows cannot establish | ||
| 127 | this stack. | ||
| 128 | |||
| 129 | CDB reads the exception context and uses the disk image's unwind data to recover callers. The | ||
| 130 | script makes a temporary copy of the PE beside the dump under the debugger alias `leonida_mapped`. | ||
| 131 | It disables network symbols and writes private frame rows to a new `mapped-stack.txt` beside the | ||
| 132 | dump. Use `--output` for a different new file. A successful walk recovers at least one caller and | ||
| 133 | can stop when later stack memory or module information is missing. Keep dumps and reports outside | ||
| 134 | the checkout and share only the outcome and frame count. | ||
| 135 | |||
| 136 | Run the synthetic regression tests with `py -3 -I tests\test_mapped_stack.py`. To include the | ||
| 137 | native CDB walk, put x64 CDB on PATH or set `LEONIDA_TEST_CDB` to its full path. | ||
diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1 index 9b218d63e..801867f11 100644 --- a/scripts/windows-boot/boot.ps1 +++ b/scripts/windows-boot/boot.ps1 | |||
| @@ -462,10 +462,31 @@ $valRx = [regex]'0x([0-9a-f]+)=([0-9a-f?]+)' | |||
| 462 | $states = New-Object System.Collections.Generic.List[string] | 462 | $states = New-Object System.Collections.Generic.List[string] |
| 463 | $lastPeek = ""; $prevPair = "" | 463 | $lastPeek = ""; $prevPair = "" |
| 464 | $presentOk = 0; $presentFailed = 0; $presses = 0 | 464 | $presentOk = 0; $presentFailed = 0; $presses = 0 |
| 465 | $shaderLine = ""; $faults = New-Object System.Collections.Generic.List[string] | 465 | $shaderLine = "" |
| 466 | $deviceLost = $false | ||
| 467 | # VkDeviceFaultAddressTypeEXT, in enum order. Keep only counters, including one bucket for newer types. | ||
| 468 | $faultNames = @("NONE", "READ_INVALID", "WRITE_INVALID", "EXECUTE_INVALID", "INSTRUCTION_POINTER_UNKNOWN", | ||
| 469 | "INSTRUCTION_POINTER_INVALID", "INSTRUCTION_POINTER_FAULT", "OTHER") | ||
| 470 | $faultCounts = New-Object 'long[]' $faultNames.Length | ||
| 471 | $faultAddressRx = [regex]'^\s*\[rt\] device-fault: address\[\d+\] type=(-?\d+)\s+address=' | ||
| 466 | $wrapped = 0 | 472 | $wrapped = 0 |
| 467 | if (Test-Path -LiteralPath $LogFile) { | 473 | if (Test-Path -LiteralPath $LogFile) { |
| 468 | foreach ($line in [System.IO.File]::ReadLines($LogFile)) { | 474 | foreach ($line in [System.IO.File]::ReadLines($LogFile)) { |
| 475 | if ($line.Contains("[rt] device-fault:")) { | ||
| 476 | if ($line.Contains("[rt] device-fault: VK_ERROR_DEVICE_LOST from ")) { $deviceLost = $true } | ||
| 477 | $m = $faultAddressRx.Match($line) | ||
| 478 | if ($m.Success) { | ||
| 479 | $type = 0 | ||
| 480 | if (-not [int]::TryParse($m.Groups[1].Value, [ref]$type) -or $type -lt 0 -or $type -ge ($faultNames.Length - 1)) { | ||
| 481 | $type = $faultNames.Length - 1 | ||
| 482 | } | ||
| 483 | $faultCounts[$type]++ | ||
| 484 | } | ||
| 485 | continue | ||
| 486 | } | ||
| 487 | if ($line.Contains("[rt] vulkan: the device was lost (") -or $line.Contains("VK_ERROR_DEVICE_LOST")) { | ||
| 488 | $deviceLost = $true | ||
| 489 | } | ||
| 469 | if ($line.Contains("XboxPresentation::PresentX")) { | 490 | if ($line.Contains("XboxPresentation::PresentX")) { |
| 470 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } | 491 | if ($line.EndsWith(" ok")) { $presentOk++ } elseif ($line.EndsWith(" failed")) { $presentFailed++ } |
| 471 | continue | 492 | continue |
| @@ -493,8 +514,6 @@ if (Test-Path -LiteralPath $LogFile) { | |||
| 493 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } | 514 | if ($line -notmatch 'gameinput: press [lr]s') { $presses++ } |
| 494 | continue | 515 | continue |
| 495 | } | 516 | } |
| 496 | if ($line.Contains("[rt] device-fault:") -and -not $line.Contains("device-fault: enabled")) { if ($faults.Count -lt 8) { $faults.Add($line.Trim()) }; continue } | ||
| 497 | if ($line.Contains("VK_ERROR_DEVICE_LOST") -and $faults.Count -lt 8) { $faults.Add($line.Trim()); continue } | ||
| 498 | if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() } | 517 | if (-not $shaderLine -and $line.Contains(" translated shaders (")) { $shaderLine = $line.Substring([Math]::Max(0, $line.IndexOf("[rt]"))).Trim() } |
| 499 | if ($line.Contains("wrapped V#")) { $wrapped++ } | 518 | if ($line.Contains("wrapped V#")) { $wrapped++ } |
| 500 | } | 519 | } |
| @@ -526,8 +545,16 @@ $digest.Add("shaders: $(if ($shaderLine) { $shaderLine } else { 'no translated- | |||
| 526 | $digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })") | 545 | $digest.Add("states: $(if ($states.Count) { $states -join ' | ' } else { 'no peek lines' })") |
| 527 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") | 546 | $digest.Add("presents: PresentX ok $presentOk, failed $presentFailed") |
| 528 | $digest.Add("input: $presses presses logged") | 547 | $digest.Add("input: $presses presses logged") |
| 529 | $digest.Add("faults: $(if ($faults.Count) { $faults.Count.ToString() + ' device-fault lines' } else { 'none' })") | 548 | $faultClasses = @(for ($i = 0; $i -lt $faultNames.Length; $i++) { |
| 530 | foreach ($f in $faults) { $digest.Add(" $f") } | 549 | if ($faultCounts[$i]) { "$($faultNames[$i])=$($faultCounts[$i])" } |
| 550 | }) | ||
| 551 | $faultText = "none" | ||
| 552 | if ($deviceLost -or $faultClasses.Count) { | ||
| 553 | $loss = if ($deviceLost) { "device loss reported" } else { "no device-loss marker" } | ||
| 554 | $records = if ($faultClasses.Count) { $faultClasses -join ", " } else { "none" } | ||
| 555 | $faultText = "$loss, address records: $records" | ||
| 556 | } | ||
| 557 | $digest.Add("faults: $faultText") | ||
| 531 | if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } | 558 | if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } |
| 532 | $digest.Add("frames: $capText") | 559 | $digest.Add("frames: $capText") |
| 533 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") | 560 | $digest.Add("files: $LogFile, $TraceFile, $SummaryFile") |
diff --git a/scripts/windows-boot/mapped_stack.py b/scripts/windows-boot/mapped_stack.py new file mode 100644 index 000000000..b88a4eb19 --- /dev/null +++ b/scripts/windows-boot/mapped_stack.py | |||
| @@ -0,0 +1,313 @@ | |||
| 1 | """Recover a private x64 exception stack with an explicitly supplied, manually mapped PE.""" | ||
| 2 | import argparse | ||
| 3 | from dataclasses import dataclass | ||
| 4 | import mmap | ||
| 5 | import os | ||
| 6 | from pathlib import Path, PureWindowsPath | ||
| 7 | import re | ||
| 8 | import shutil | ||
| 9 | import struct | ||
| 10 | import subprocess | ||
| 11 | import sys | ||
| 12 | import tempfile | ||
| 13 | |||
| 14 | ROOT = Path(__file__).resolve().parents[2] | ||
| 15 | sys.path.insert(0, str(ROOT / "tools")) | ||
| 16 | from pe_inspect import DIR_EXCEPTION, PeFormatError, PeImage | ||
| 17 | from report_paths import same_report_path | ||
| 18 | |||
| 19 | |||
| 20 | def require(condition, message): | ||
| 21 | if not condition: | ||
| 22 | raise ValueError(message) | ||
| 23 | |||
| 24 | |||
| 25 | def bounds(offset, size, end): | ||
| 26 | require(0 <= offset <= end and 0 <= size <= end - offset, "truncated or invalid binary structure") | ||
| 27 | |||
| 28 | |||
| 29 | def read(data, fmt, offset): | ||
| 30 | fmt = "<" + fmt | ||
| 31 | bounds(offset, struct.calcsize(fmt), len(data)) | ||
| 32 | return struct.unpack_from(fmt, data, offset) | ||
| 33 | |||
| 34 | |||
| 35 | def records(start, count, stride, end): | ||
| 36 | bounds(start, count * stride, end) | ||
| 37 | return range(start, start + count * stride, stride) | ||
| 38 | |||
| 39 | |||
| 40 | def dump_streams(dump): | ||
| 41 | magic, version, count, directory = read(dump, "4sIII", 0) | ||
| 42 | require(magic == b"MDMP" and version & 0xffff == 0xa793, "expected a Windows minidump") | ||
| 43 | streams = {} | ||
| 44 | for pos in records(directory, count, 12, len(dump)): | ||
| 45 | kind, size, offset = read(dump, "III", pos) | ||
| 46 | if kind in (4, 5, 6, 7, 9): | ||
| 47 | require(kind not in streams, "duplicate minidump stream") | ||
| 48 | bounds(offset, size, len(dump)) | ||
| 49 | streams[kind] = (offset, offset + size) | ||
| 50 | return streams | ||
| 51 | |||
| 52 | |||
| 53 | def stream(streams, kind, minimum): | ||
| 54 | require(kind in streams, "required minidump stream missing") | ||
| 55 | start, end = streams[kind] | ||
| 56 | bounds(start, minimum, end) | ||
| 57 | return start, end | ||
| 58 | |||
| 59 | |||
| 60 | def exception_context(dump, streams): | ||
| 61 | system, _ = stream(streams, 7, 2) | ||
| 62 | require(read(dump, "H", system)[0] == 9, "expected an AMD64 dump") | ||
| 63 | require(6 in streams, "dump has no exception context (exit snapshots are unsupported)") | ||
| 64 | exc, _ = stream(streams, 6, 168) | ||
| 65 | size, offset = read(dump, "II", exc + 160) | ||
| 66 | bounds(offset, size, len(dump)) | ||
| 67 | require(size >= 256 and read(dump, "I", offset + 48)[0] & 0x100001 == 0x100001, | ||
| 68 | "missing AMD64 control context") | ||
| 69 | return read(dump, "I", exc)[0], read(dump, "Q", offset + 248)[0], read(dump, "Q", offset + 152)[0] | ||
| 70 | |||
| 71 | |||
| 72 | def captured_ranges(dump, streams): | ||
| 73 | if 5 in streams: # MINIDUMP_MEMORY_LIST | ||
| 74 | pos, end = stream(streams, 5, 4) | ||
| 75 | for entry in records(pos + 4, read(dump, "I", pos)[0], 16, end): | ||
| 76 | address, size, offset = read(dump, "QII", entry) | ||
| 77 | bounds(offset, size, len(dump)) | ||
| 78 | yield address, size, offset | ||
| 79 | if 9 in streams: # MINIDUMP_MEMORY64_LIST stores all bytes consecutively | ||
| 80 | pos, end = stream(streams, 9, 16) | ||
| 81 | count, offset = read(dump, "QQ", pos) | ||
| 82 | for entry in records(pos + 16, count, 16, end): | ||
| 83 | address, size = read(dump, "QQ", entry) | ||
| 84 | bounds(offset, size, len(dump)) | ||
| 85 | yield address, size, offset | ||
| 86 | offset += size | ||
| 87 | |||
| 88 | |||
| 89 | def instruction_window(dump, streams, rip): | ||
| 90 | window = None | ||
| 91 | for address, size, offset in captured_ranges(dump, streams): | ||
| 92 | if address <= rip < address + size: | ||
| 93 | start, end = max(rip - 128, address), min(rip + 128, address + size) | ||
| 94 | sample = (start, dump[offset + start - address:offset + end - address]) | ||
| 95 | require(window is None or sample == window, "ambiguous instruction capture") | ||
| 96 | window = sample | ||
| 97 | require(window is not None, "exception instructions were not captured") | ||
| 98 | require(len(window[1]) >= 32 and len(set(window[1])) >= 8, "insufficient distinctive instruction bytes") | ||
| 99 | return window | ||
| 100 | |||
| 101 | |||
| 102 | @dataclass(frozen=True) | ||
| 103 | class Mapping: | ||
| 104 | base: int | ||
| 105 | size: int | ||
| 106 | timestamp: int | ||
| 107 | thread: int | ||
| 108 | rip: int | ||
| 109 | rsp: int | ||
| 110 | |||
| 111 | |||
| 112 | def mapping_base(pe, address, sample): | ||
| 113 | # Locate the captured instructions in executable disk bytes. This gives the | ||
| 114 | # actual mapping even after rebasing, without trusting the PE preferred base. | ||
| 115 | base = None | ||
| 116 | previous_end = pe.size_of_headers | ||
| 117 | bounds(0, previous_end, min(pe.size_of_image, len(pe.data))) | ||
| 118 | for section in sorted(pe.sections, key=lambda item: item["rva"]): | ||
| 119 | rva, raw, raw_size = section["rva"], section["rawptr"], section["rawsize"] | ||
| 120 | span = section["vsize"] or raw_size | ||
| 121 | require(rva >= previous_end, "overlapping PE sections") | ||
| 122 | bounds(rva, span, pe.size_of_image) | ||
| 123 | bounds(raw, raw_size, len(pe.data)) | ||
| 124 | previous_end = rva + span | ||
| 125 | if not section["exec"]: | ||
| 126 | continue | ||
| 127 | raw_end = raw + min(span, raw_size) | ||
| 128 | pos = pe.data.find(sample, raw, raw_end) | ||
| 129 | if pos >= 0: | ||
| 130 | require(base is None and pe.data.find(sample, pos + 1, raw_end) < 0, | ||
| 131 | "instructions match multiple locations in the image") | ||
| 132 | base = address - (rva + pos - raw) | ||
| 133 | require(base is not None, "exception instructions do not match this PE") | ||
| 134 | require(base > 0 and base % 0x10000 == 0 and base + pe.size_of_image <= 2**64, "invalid inferred mapping base") | ||
| 135 | return base | ||
| 136 | |||
| 137 | |||
| 138 | def verify_unwind(dump, streams, pe, base, rip): | ||
| 139 | # A synthetic module label alone does not prove that CDB has unwind data. | ||
| 140 | # Require a file-backed RUNTIME_FUNCTION for the fault, and cross-check its | ||
| 141 | # metadata and the PE headers wherever the dump actually captured them. | ||
| 142 | pdata, pdata_size = pe.directory(DIR_EXCEPTION) | ||
| 143 | pdata_off = pe.offset(pdata, pdata_size) | ||
| 144 | require(pdata >= pe.size_of_headers and pdata_off is not None and pdata_size % 12 == 0, | ||
| 145 | "missing or invalid x64 exception directory") | ||
| 146 | metadata = [(base, min(pe.size_of_headers, 4096), 0)] | ||
| 147 | function_found = False | ||
| 148 | for entry in range(pdata_off, pdata_off + pdata_size, 12): | ||
| 149 | begin, end, unwind = read(pe.data, "III", entry) | ||
| 150 | if begin <= rip - base < end: | ||
| 151 | require(not function_found, "ambiguous x64 function entry") | ||
| 152 | function_found = True | ||
| 153 | unwind_off = pe.offset(unwind, 4) | ||
| 154 | require(unwind >= pe.size_of_headers and unwind_off is not None | ||
| 155 | and pe.data[unwind_off] & 7 in (1, 2), "unsupported x64 unwind information") | ||
| 156 | # The header is followed by an array of 2-byte unwind codes. | ||
| 157 | unwind_size = 4 + pe.data[unwind_off + 2] * 2 | ||
| 158 | require(pe.offset(unwind, unwind_size) is not None, "truncated x64 unwind codes") | ||
| 159 | metadata.extend([(base + pdata + entry - pdata_off, 12, entry), (base + unwind, unwind_size, unwind_off)]) | ||
| 160 | require(function_found, "no x64 unwind entry covers the exception instructions") | ||
| 161 | for address, length, offset in captured_ranges(dump, streams): | ||
| 162 | for start, count, raw in metadata: | ||
| 163 | lo, hi = max(address, start), min(address + length, start + count) | ||
| 164 | if lo < hi: | ||
| 165 | disk = pe.data[raw + lo - start:raw + hi - start] | ||
| 166 | require(dump[offset + lo - address:offset + hi - address] == disk, | ||
| 167 | "captured image metadata differs from the supplied PE") | ||
| 168 | |||
| 169 | |||
| 170 | def check_registered_modules(dump, streams, base, size): | ||
| 171 | modules, end = stream(streams, 4, 4) | ||
| 172 | for entry in records(modules + 4, read(dump, "I", modules)[0], 108, end): | ||
| 173 | loaded, extent = read(dump, "QI", entry) | ||
| 174 | require(base + size <= loaded or base >= loaded + extent, "mapping overlaps a registered module") | ||
| 175 | name_rva = read(dump, "I", entry + 20)[0] | ||
| 176 | length = read(dump, "I", name_rva)[0] | ||
| 177 | require(0 < length <= 65534 and length % 2 == 0, "invalid registered module name") | ||
| 178 | start = name_rva + 4 | ||
| 179 | bounds(start, length, len(dump)) | ||
| 180 | name = PureWindowsPath(dump[start:start + length].decode("utf-16-le")) | ||
| 181 | require(name.stem.casefold() != "leonida_mapped", "staging name already used by a registered module") | ||
| 182 | require((len(name.parts) == 1 and not name.anchor) | ||
| 183 | or re.fullmatch(r"[A-Za-z]:", name.drive) and name.is_absolute(), | ||
| 184 | "dump contains a nonlocal module path") | ||
| 185 | if os.name == "nt" and name.drive: | ||
| 186 | require(local_drive(name.anchor), "dump references a module on a nonlocal drive") | ||
| 187 | |||
| 188 | |||
| 189 | def identify(dump, image): | ||
| 190 | streams = dump_streams(dump) | ||
| 191 | thread, rip, rsp = exception_context(dump, streams) | ||
| 192 | address, sample = instruction_window(dump, streams, rip) | ||
| 193 | pe = PeImage(image) | ||
| 194 | require(pe.machine == 0x8664 and pe.is64, "expected an AMD64 PE32+ image") | ||
| 195 | base = mapping_base(pe, address, sample) | ||
| 196 | check_registered_modules(dump, streams, base, pe.size_of_image) | ||
| 197 | verify_unwind(dump, streams, pe, base, rip) | ||
| 198 | return Mapping(base, pe.size_of_image, pe.timestamp, thread, rip, rsp) | ||
| 199 | |||
| 200 | |||
| 201 | ROW = re.compile(r"^\s*([0-9a-f]+)\s+[0-9a-f]{8}\x60[0-9a-f]{8}\s+[0-9a-f]{8}\x60[0-9a-f]{8}\s+(.+)", re.I) | ||
| 202 | BEGIN = "LEONIDA_STACK_BEGIN" | ||
| 203 | END = "LEONIDA_STACK_END" | ||
| 204 | |||
| 205 | |||
| 206 | def stack_rows(output, mapping): | ||
| 207 | lines = output.splitlines() | ||
| 208 | require(lines.count(BEGIN) == 1 and lines.count(END) == 1, "CDB did not finish the stack walk") | ||
| 209 | report = lines[lines.index(BEGIN) + 1:lines.index(END)] | ||
| 210 | require(report and report[0].strip().lower() == f"{mapping.rip:x} {mapping.rsp:x}", | ||
| 211 | "CDB could not select the dump's exception context") | ||
| 212 | rows = [] | ||
| 213 | for line in report[1:]: | ||
| 214 | if "following frames may be wrong" in line.lower(): | ||
| 215 | break | ||
| 216 | frame = ROW.match(line) | ||
| 217 | if frame: | ||
| 218 | require(int(frame[1], 16) == len(rows), "unexpected CDB frame sequence") | ||
| 219 | if not rows: | ||
| 220 | require(re.match(r"leonida_mapped(?:[+!]|$)", frame[2], re.I), "CDB did not load the mapped image") | ||
| 221 | rows.append(line.strip()) | ||
| 222 | require(len(rows) >= 2, "CDB could not recover a caller") | ||
| 223 | return rows | ||
| 224 | |||
| 225 | |||
| 226 | def debugger_stack(cdb, dump, symbols, scratch, mapping): | ||
| 227 | # CDB parses its own command language. Only parsed integers enter it. The | ||
| 228 | # PE always has the same safe filename in a new, private working directory. | ||
| 229 | command = (f".reload /f leonida_mapped.exe={mapping.base:x},{mapping.size:x},{mapping.timestamp:x}; " | ||
| 230 | f'~~[{mapping.thread:x}]s; .ecxr; .echo {BEGIN}; ' | ||
| 231 | f'.printf "%I64x %I64x\\n", @rip, @rsp; kn 40; .echo {END}; q') | ||
| 232 | require(not any(c in str(scratch) for c in ";*"), "temporary directory cannot form a debugger search path") | ||
| 233 | search = str(scratch) if symbols is None else str(scratch) + ";" + str(symbols) | ||
| 234 | env = {key: value for key, value in os.environ.items() if key.upper() in {"SYSTEMROOT", "WINDIR", "SYSTEMDRIVE"}} | ||
| 235 | env.update(dict.fromkeys(("TEMP", "TMP", "LOCALAPPDATA", "APPDATA", "USERPROFILE"), str(scratch))) | ||
| 236 | run = subprocess.run([str(cdb), "-sins", "-sicv", "-netsyms:no", "-nosqm", "-noshell", "-y", search, | ||
| 237 | "-i", search, "-srcpath", str(scratch), "-z", str(dump), "-c", command], | ||
| 238 | cwd=scratch, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, | ||
| 239 | stderr=subprocess.STDOUT, timeout=90) | ||
| 240 | require(run.returncode == 0, "CDB failed to analyze the dump") | ||
| 241 | return stack_rows(run.stdout.decode("utf-8", errors="replace"), mapping) | ||
| 242 | |||
| 243 | |||
| 244 | def local_drive(anchor): | ||
| 245 | import ctypes | ||
| 246 | return ctypes.windll.kernel32.GetDriveTypeW(str(anchor)) in (2, 3, 5, 6) | ||
| 247 | |||
| 248 | |||
| 249 | def local_path(path): | ||
| 250 | # Reject UNC, device namespace and mapped network drives before opening | ||
| 251 | # inputs or using a directory as a debugger search path. | ||
| 252 | absolute = Path(os.path.abspath(path)) | ||
| 253 | require(re.fullmatch(r"[A-Za-z]:", absolute.drive) and local_drive(absolute.anchor), | ||
| 254 | "expected a local filesystem path") | ||
| 255 | resolved = absolute.resolve() | ||
| 256 | require(re.fullmatch(r"[A-Za-z]:", resolved.drive) and local_drive(resolved.anchor), | ||
| 257 | "path resolves outside the local filesystem") | ||
| 258 | return resolved | ||
| 259 | |||
| 260 | |||
| 261 | def recover(args): | ||
| 262 | require(os.name == "nt", "the x64 Windows debugger is required") | ||
| 263 | dump, image = local_path(args.dump), local_path(args.image) | ||
| 264 | report = local_path(args.output) if args.output else dump.with_name("mapped-stack.txt") | ||
| 265 | require(not report.is_relative_to(ROOT) and not dump.parent.is_relative_to(ROOT), | ||
| 266 | "keep the dump and the private report outside the checkout") | ||
| 267 | require(not any(same_report_path(report, path) for path in (dump, image)), "report collides with an input") | ||
| 268 | require(not report.exists(), "output already exists; choose a fresh report path") | ||
| 269 | debugger = args.cdb or shutil.which("cdb.exe") | ||
| 270 | require(debugger, "x64 CDB not found; provide --cdb") | ||
| 271 | cdb = local_path(debugger) | ||
| 272 | symbols = local_path(args.symbols) if args.symbols else None | ||
| 273 | require(symbols is None or symbols.is_dir() and not any(c in str(symbols) for c in ";*"), | ||
| 274 | "--symbols requires a single local directory") | ||
| 275 | with tempfile.TemporaryDirectory(dir=dump.parent) as scratch: | ||
| 276 | staged = Path(scratch) / "leonida_mapped.exe" | ||
| 277 | shutil.copyfile(image, staged) | ||
| 278 | with dump.open("rb") as df, staged.open("rb") as ef: | ||
| 279 | with mmap.mmap(df.fileno(), 0, access=mmap.ACCESS_READ) as md, \ | ||
| 280 | mmap.mmap(ef.fileno(), 0, access=mmap.ACCESS_READ) as pe: | ||
| 281 | mapping = identify(md, pe) | ||
| 282 | rows = debugger_stack(cdb, dump, symbols, scratch, mapping) | ||
| 283 | # On Windows rename publishes the completed report and refuses an existing | ||
| 284 | # destination, including one created by a concurrent analysis. | ||
| 285 | with tempfile.TemporaryDirectory(dir=report.parent) as pending: | ||
| 286 | finished = Path(pending) / "stack.txt" | ||
| 287 | finished.write_text("\n".join(rows) + "\n", encoding="utf-8", newline="\n") | ||
| 288 | finished.rename(report) | ||
| 289 | print(f"Recovered {len(rows)} frames. Keep the stack report private.") | ||
| 290 | |||
| 291 | |||
| 292 | def main(): | ||
| 293 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 294 | parser.add_argument("dump", type=Path, help="private Windows exception minidump") | ||
| 295 | parser.add_argument("image", type=Path, help="the exact mapped PE from the crashing build") | ||
| 296 | parser.add_argument("--symbols", type=Path, help="local directory with matching runtime images and PDBs") | ||
| 297 | parser.add_argument("--cdb", type=Path, help="path to the trusted x64 cdb.exe (default: search PATH)") | ||
| 298 | parser.add_argument("--output", type=Path, help="new private output path (default: mapped-stack.txt beside dump)") | ||
| 299 | args = parser.parse_args() | ||
| 300 | try: | ||
| 301 | recover(args) | ||
| 302 | except PeFormatError: | ||
| 303 | parser.exit(1, "invalid PE image\n") | ||
| 304 | except ValueError as error: | ||
| 305 | parser.exit(1, f"{error}\n") | ||
| 306 | except subprocess.TimeoutExpired: | ||
| 307 | parser.exit(1, "CDB timed out\n") | ||
| 308 | except OSError as error: | ||
| 309 | parser.exit(1, f"local file or debugger operation failed ({type(error).__name__})\n") | ||
| 310 | |||
| 311 | |||
| 312 | if __name__ == "__main__": | ||
| 313 | main() | ||