upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-30 04:36:05 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-30 04:36:05 -0500
commitb8508a974bbd725c5f6cb2ca200583f12085c3ef (patch)
treef0425be7d73365dcf0ae2f05ce96351c1557377f /scripts
parentefc1929908a728d95fa09ffef0a743d2a649b86d (diff)
parent4014af7fe9a479caee2946c1814c11935b24bf60 (diff)
Merge branch 'main' of https://github.com/ProjectLeonida/mandy into fix/rendering-correctness
# Conflicts: # tests/semantic/test_interp_computed_ij_fallback.py
Diffstat (limited to 'scripts')
-rw-r--r--scripts/bench_translate.py1
-rw-r--r--scripts/bench_wave64.py1
-rw-r--r--scripts/carve_all.ps181
-rw-r--r--scripts/meta_to_xml.ps169
-rw-r--r--scripts/play-d3d12.ps111
-rw-r--r--scripts/play.ps12
-rw-r--r--scripts/port_ctl.py320
-rw-r--r--scripts/sync_victory.py94
-rw-r--r--scripts/windows-boot/README.md9
-rw-r--r--scripts/windows-boot/boot.ps1106
-rw-r--r--scripts/windows-boot/test_crash_monitor.py4
11 files changed, 116 insertions, 582 deletions
diff --git a/scripts/bench_translate.py b/scripts/bench_translate.py
index 6c60b3493..5e9ce4f94 100644
--- a/scripts/bench_translate.py
+++ b/scripts/bench_translate.py
@@ -24,7 +24,6 @@ them with a run of the same commit, not with the table in the pull request that
24import argparse 24import argparse
25import json 25import json
26import os 26import os
27import statistics
28import struct 27import struct
29import subprocess 28import subprocess
30import sys 29import sys
diff --git a/scripts/bench_wave64.py b/scripts/bench_wave64.py
index 3a566ebfd..3872c7b37 100644
--- a/scripts/bench_wave64.py
+++ b/scripts/bench_wave64.py
@@ -15,7 +15,6 @@ native 64-wide subgroup, such as Apple Silicon. Every process must complete the
15output hash; there is deliberately no claim that the hash was compared with a native Wave64 device. 15output hash; there is deliberately no claim that the hash was compared with a native Wave64 device.
16""" 16"""
17import argparse 17import argparse
18import json
19import os 18import os
20import re 19import re
21import statistics 20import statistics
diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1
deleted file mode 100644
index 9442f5e08..000000000
--- a/scripts/carve_all.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
1# Carves every .rpf in the game folder into <Out>\<archive path with _>, smallest first (research tool; the
2# build itself doesn't need it). Skips archives that already have an index.json. Summary: <Out>\coverage.json
3param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out)
4$root = Split-Path $PSScriptRoot -Parent
5$tool = Join-Path $root "tools\rpf9_carve.py"
6if (-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))
10if (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
14# -Game may be relative or end in a separator; archive names are cut from a separator-ended prefix.
15$Game = (Resolve-Path -LiteralPath $Game).ProviderPath
16# Resolve-Path preserves 8.3 short components (e.g. RUNNER~1), while Get-ChildItem emits canonical
17# FullName paths. Deriving the prefix from Resolve-Path then cuts the wrong number of characters and
18# re-carves already-caved archives; use the canonical form for both sides of the Substring.
19$prefix = (Get-Item -LiteralPath $Game).FullName.TrimEnd('\') + '\'
20$destinations = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::OrdinalIgnoreCase)
21# Validate every destination before accepting any cached index or starting a carve.
22$archives = foreach ($f in Get-ChildItem -LiteralPath $Game -Recurse -File -Filter *.rpf | Sort-Object Length) {
23 $rel = $f.FullName.Substring($prefix.Length)
24 $name = [IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_"))
25 if ($destinations.ContainsKey($name)) {
26 throw ("Archives '{0}' and '{1}' both map to '{2}'." -f $destinations[$name], $rel, $name)
27 }
28 $destinations.Add($name, $rel)
29 [pscustomobject]@{ file = $f; relative = $rel; destination = Join-Path $outFull $name }
30}
31
32$rows = @()
33foreach ($archive in $archives) {
34 $f = $archive.file
35 $rel = $archive.relative
36 $dest = $archive.destination
37 $index = Join-Path $dest "index.json"
38 if (-not (Test-Path -LiteralPath $index)) {
39 Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB))
40 python -I $tool $f.FullName $dest | Select-Object -Last 1
41 if ($LASTEXITCODE -ne 0) { throw "Carving $rel failed (exit $LASTEXITCODE)" }
42 }
43 try {
44 $s = (Get-Content -LiteralPath $index -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop).summary
45 foreach ($field in 'files', 'bink2_files', 'span', 'compressed_bytes', 'unread_bytes', 'inflated_bytes') {
46 $value = $s.$field
47 if ((($value -isnot [int]) -and ($value -isnot [long])) -or $value -lt 0) {
48 throw "summary.$field must be a non-negative integer."
49 }
50 }
51 if ($s.span -eq 0 -and ($s.compressed_bytes -ne 0 -or $s.unread_bytes -ne 0)) {
52 throw 'A zero summary.span requires zero compressed and unread bytes.'
53 }
54 # Stored streams and unread gaps occupy disjoint parts of the span. Subtract instead of
55 # adding the counters so a total just above Int64.MaxValue cannot lose precision.
56 if ($s.compressed_bytes -gt $s.span -or $s.unread_bytes -gt ($s.span - $s.compressed_bytes)) {
57 throw 'summary.compressed_bytes and summary.unread_bytes must fit within summary.span.'
58 }
59 if ($s.bink2_files -gt $s.files) {
60 throw 'summary.bink2_files must not exceed summary.files.'
61 }
62 } catch {
63 throw "Invalid carve index '$index': $($_.Exception.Message)"
64 }
65 $denominator = [math]::Max(1L, $s.span)
66 $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span
67 readable = [math]::Round($s.compressed_bytes / $denominator, 4)
68 unread = [math]::Round($s.unread_bytes / $denominator, 4); inflated = $s.inflated_bytes }
69}
70$coverageJson = if ($rows.Count -eq 0) { "[]" } else { $rows | ConvertTo-Json }
71$coveragePath = Join-Path $outFull "coverage.json"
72$tmpCoverage = Join-Path $outFull (".coverage.{0}.{1}.tmp" -f $PID, [guid]::NewGuid().ToString("N"))
73try {
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}
79if ($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/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1
deleted file mode 100644
index 38a00837d..000000000
--- a/scripts/meta_to_xml.ps1
+++ /dev/null
@@ -1,69 +0,0 @@
1# Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers.
2# Run in Windows PowerShell 5.1.
3# .\meta_to_xml.ps1 -Carve <work>\carve -Out <work>\meta [-Limit N]
4# Each blob becomes <Out>\<archive>\<offset>.xml. Failures go to <Out>\failures.txt (UTF-8 with BOM) with the error message.
5param(
6 [string]$Carve = "<work>\carve",
7 [string]$Out = "<work>\meta",
8 [string]$CodeWalker = "<ref>\codewalker-gen9",
9 [int]$Limit = 0
10)
11$ErrorActionPreference = "Stop"
12if ($Limit -lt 0) {
13 throw "-Limit must be 0 or greater."
14}
15try { (Get-Process -Id $PID).PriorityClass = "BelowNormal" } catch {}
16Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Mathematics.dll"
17[void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll")
18New-Item -ItemType Directory -Force $Out | Out-Null
19$fail = Join-Path $Out "failures.txt"
20"" | Set-Content -LiteralPath $fail -Encoding utf8
21$ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0
22
23foreach ($dir in Get-ChildItem -LiteralPath $Carve -Directory) {
24 $idx = Join-Path $dir.FullName "index.json"
25 if (-not (Test-Path -LiteralPath $idx)) { continue }
26 $files = (Get-Content -LiteralPath $idx -Raw | ConvertFrom-Json).files |
27 Where-Object {
28 $_.head -is [string] -and (
29 $_.head.StartsWith("5053494e", [StringComparison]::OrdinalIgnoreCase) -or
30 $_.head.StartsWith("52424630", [StringComparison]::OrdinalIgnoreCase)
31 )
32 }
33 if (-not $files) { continue }
34 $dest = Join-Path $Out $dir.Name
35 New-Item -ItemType Directory -Force $dest | Out-Null
36 foreach ($r in $files) {
37 if ($Limit -and $n -ge $Limit) { break }
38 $n++
39 $name = "{0:x12}" -f [int64]$r.off
40 $kind = if ($r.head.StartsWith("5053494e", [StringComparison]::OrdinalIgnoreCase)) { "pso" } else { "rbf" }
41 try {
42 $bytes = [IO.File]::ReadAllBytes((Join-Path $dir.FullName "$name.bin"))
43 if ($kind -eq "pso") {
44 $f = New-Object CodeWalker.GameFiles.PsoFile; $f.Load($bytes)
45 $xml = [CodeWalker.GameFiles.PsoXml]::GetXml($f)
46 } else {
47 $f = New-Object CodeWalker.GameFiles.RbfFile; $f.Load($bytes)
48 $xml = [CodeWalker.GameFiles.RbfXml]::GetXml($f)
49 }
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 }
60 $ok[$kind]++
61 } catch {
62 $bad[$kind]++
63 $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception }
64 "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content -LiteralPath $fail -Encoding utf8
65 }
66 }
67 if ($Limit -and $n -ge $Limit) { break }
68}
69"pso ok $($ok.pso) failed $($bad.pso); rbf ok $($ok.rbf) failed $($bad.rbf) -> $Out"
diff --git a/scripts/play-d3d12.ps1 b/scripts/play-d3d12.ps1
index aed36ce25..2db9a7b2b 100644
--- a/scripts/play-d3d12.ps1
+++ b/scripts/play-d3d12.ps1
@@ -24,6 +24,8 @@
24# on the title's own upscaler, held to 28 shown frames a second. 24# on the title's own upscaler, held to 28 shown frames a second.
25# -NoFrameGen no DLSS frame generation at all, the frames the game renders only 25# -NoFrameGen no DLSS frame generation at all, the frames the game renders only
26# -MotionBlur the game's own motion blur (left out by default: at this frame rate it smears in blocks on turns) 26# -MotionBlur the game's own motion blur (left out by default: at this frame rate it smears in blocks on turns)
27# -FsrFrameGen AMD's FSR 3 frame generation instead (2x), for cards without DLSS frame generation (RTX 20 and 30):
28# needs AMD's two signed FidelityFX DLLs in d3d12\amd-sdk\FidelityFX\bin
27# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9, shown 29# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9, shown
28# centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch). 30# centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch).
29# -Resolution the older path: the game renders at this height and the title's own upscaler does the rest 31# -Resolution the older path: the game renders at this height and the title's own upscaler does the rest
@@ -36,6 +38,8 @@
36# made before the title starts (minutes the first time, seconds after) 38# made before the title starts (minutes the first time, seconds after)
37# -Log the runtime's log goes to a file under %LOCALAPPDATA%\Leonida\logs 39# -Log the runtime's log goes to a file under %LOCALAPPDATA%\Leonida\logs
38# -DryRun prints the settings this start would run with and stops: nothing is built or started 40# -DryRun prints the settings this start would run with and stops: nothing is built or started
41# -PcGlyphs a folder of your own pictures for the keyboard-and-mouse button prompts instead of the built-in key
42# caps (docs/prompt_glyphs.md; both prompt movies are built before the start when missing)
39# 43#
40# Builds d3d12/ when it is missing (d3d12\scripts\build-nvidia.ps1: the diag profile, with DLSS when NVIDIA's files 44# Builds d3d12/ when it is missing (d3d12\scripts\build-nvidia.ps1: the diag profile, with DLSS when NVIDIA's files
41# are there), keeps the caches and saves under -Data, and hands everything else to d3d12\scripts\play-nvidia.ps1: 45# are there), keeps the caches and saves under -Data, and hands everything else to d3d12\scripts\play-nvidia.ps1:
@@ -52,6 +56,7 @@ param(
52 [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0, 56 [ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen = 0,
53 [switch]$NoFrameGen, 57 [switch]$NoFrameGen,
54 [switch]$MotionBlur, 58 [switch]$MotionBlur,
59 [switch]$FsrFrameGen,
55 [string]$Aspect = '', 60 [string]$Aspect = '',
56 [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '', 61 [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '',
57 [string]$Adapter = '', 62 [string]$Adapter = '',
@@ -64,7 +69,8 @@ param(
64 [switch]$Capture, 69 [switch]$Capture,
65 [switch]$NoPrecompile, 70 [switch]$NoPrecompile,
66 [switch]$Log, 71 [switch]$Log,
67 [switch]$DryRun 72 [switch]$DryRun,
73 [string]$PcGlyphs = ''
68) 74)
69 75
70$ErrorActionPreference = "Stop" 76$ErrorActionPreference = "Stop"
@@ -97,10 +103,11 @@ if ($Dlss) { $launch.Dlss = $Dlss }
97if ($FrameGen) { $launch.FrameGen = $FrameGen } 103if ($FrameGen) { $launch.FrameGen = $FrameGen }
98if ($Aspect) { $launch.Aspect = $Aspect } 104if ($Aspect) { $launch.Aspect = $Aspect }
99if ($PresentScale) { $launch.PresentScale = $PresentScale } 105if ($PresentScale) { $launch.PresentScale = $PresentScale }
100foreach ($switch in 'Quality', 'NoDlss', 'NoFrameGen', 'MotionBlur', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun') { 106foreach ($switch in 'Quality', 'NoDlss', 'NoFrameGen', 'MotionBlur', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun', 'FsrFrameGen') {
101 if ($PSBoundParameters[$switch]) { $launch[$switch] = $true } 107 if ($PSBoundParameters[$switch]) { $launch[$switch] = $true }
102} 108}
103if ($Resolution) { $launch.Resolution = $Resolution } 109if ($Resolution) { $launch.Resolution = $Resolution }
104if ($Lowest) { $launch.Lowest = $Lowest } 110if ($Lowest) { $launch.Lowest = $Lowest }
105if ($Adapter) { $launch.Adapter = $Adapter } 111if ($Adapter) { $launch.Adapter = $Adapter }
112if ($PcGlyphs) { $launch.PcGlyphs = (Resolve-Path $PcGlyphs).Path }
106& (Join-Path $runtime "scripts\play-nvidia.ps1") @launch 113& (Join-Path $runtime "scripts\play-nvidia.ps1") @launch
diff --git a/scripts/play.ps1 b/scripts/play.ps1
index 76b9f5139..70a990685 100644
--- a/scripts/play.ps1
+++ b/scripts/play.ps1
@@ -41,7 +41,7 @@ Set-Default "LEONIDA_KEYBOARD_PAD" "1" # keyboard and mouse as a pad wh
41# The title's soft asserts (an int3 the console build carries on from) are stepped over and logged; the one known 41# The title's soft asserts (an int3 the console build carries on from) are stepped over and logged; the one known
42# site is game+0x4ffd879 after the start screen (docs/port_status.md, open items). 42# site is game+0x4ffd879 after the start screen (docs/port_status.md, open items).
43Set-Default "LEONIDA_SKIP_INT3" "1" 43Set-Default "LEONIDA_SKIP_INT3" "1"
44$tables = Join-Path $repo "victory\crates\victory-formats\src\bcpack-tables.bin" 44$tables = Join-Path $repo "d3d12\crates\leonida-formats\src\bcpack-tables.bin"
45if (Test-Path $tables) { Set-Default "LEONIDA_BCPACK_TABLES" $tables } 45if (Test-Path $tables) { Set-Default "LEONIDA_BCPACK_TABLES" $tables }
46 46
47$logs = Join-Path $Work "logs" 47$logs = Join-Path $Work "logs"
diff --git a/scripts/port_ctl.py b/scripts/port_ctl.py
deleted file mode 100644
index 9a7e595d0..000000000
--- a/scripts/port_ctl.py
+++ /dev/null
@@ -1,320 +0,0 @@
1#!/usr/bin/env python3
2"""Drive a VIctory run of the title for testing: start, press, shot, fps, stop.
3
4Everything the run writes (logs, frame captures, saves, caches) goes under a
5work folder outside the repository (``--work``, default ``G:\\gta6port`` or
6``LEONIDA_PORT_WORK``). Nothing from the game is read or written here beyond
7what the runtime itself does.
8
9 python -I scripts/port_ctl.py start --name run1 # launch the title
10 python -I scripts/port_ctl.py press Enter # tap A on the stand-in pad
11 python -I scripts/port_ctl.py press W 3000 # hold left stick up for 3 s
12 python -I scripts/port_ctl.py shot # save the next presented frame
13 python -I scripts/port_ctl.py fps # latest frame-rate lines
14 python -I scripts/port_ctl.py status # running?, fps, last warnings
15 python -I scripts/port_ctl.py stop # end the run
16
17Keys (the stand-in pad's table): sticks W A S D / I J K L, triggers Z C,
18buttons X Y Q E F H, Enter (A), Back (B), Esc (Menu), Tab (View),
19Up Down Left Right (D-pad). The runtime reads the pad file only while no real
20controller is connected.
21"""
22
23import argparse
24import json
25import os
26import re
27import subprocess
28import sys
29import time
30
31REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
32VICTORY = os.path.join(REPO, "victory")
33DEFAULT_WORK = os.environ.get("LEONIDA_PORT_WORK", r"G:\gta6port")
34DEFAULT_GAME = os.environ.get("LEONIDA_GAME_DIR", os.path.expanduser(r"~\Documents\GTA6"))
35TITLE_EXE = "game_scarlett_master.exe"
36
37FPS_RE = re.compile(r"(\d+(?:\.\d+)?) fps, (\d+(?:\.\d+)?) ms/frame")
38ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
39
40
41def read_log(log):
42 try:
43 with open(log, encoding="utf-8", errors="replace") as f:
44 return [ANSI_RE.sub("", ln) for ln in f]
45 except OSError:
46 return []
47
48
49def paths(work):
50 ctl = os.path.join(work, "ctl")
51 return {
52 "work": work,
53 "ctl": ctl,
54 "state": os.path.join(ctl, "state.json"),
55 "pad": os.path.join(ctl, "pad.txt"),
56 "shot": os.path.join(ctl, "shot.txt"),
57 "logs": os.path.join(work, "logs"),
58 "captures": os.path.join(work, "captures"),
59 "cache": os.path.join(work, "cache"),
60 "data": os.path.join(work, "data"),
61 }
62
63
64def load_state(p):
65 try:
66 with open(p["state"], encoding="utf-8") as f:
67 return json.load(f)
68 except (OSError, ValueError):
69 return {}
70
71
72def save_state(p, state):
73 os.makedirs(p["ctl"], exist_ok=True)
74 with open(p["state"], "w", encoding="utf-8", newline="\n") as f:
75 json.dump(state, f, indent=1)
76
77
78def alive(pid):
79 if not pid:
80 return False
81 out = subprocess.run(
82 ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"],
83 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
84 ).stdout
85 return f'"{pid}"' in out
86
87
88def write_atomic(path, text):
89 tmp = path + ".tmp"
90 with open(tmp, "w", encoding="utf-8", newline="\n") as f:
91 f.write(text)
92 os.replace(tmp, path)
93
94
95def cmd_start(args, p):
96 state = load_state(p)
97 if alive(state.get("pid")):
98 print(f"a run is already going: pid {state['pid']} ({state.get('name')}); stop it first")
99 return 1
100 exe = args.exe or os.path.join(VICTORY, "target", args.profile, "victory.exe")
101 if not os.path.isfile(exe):
102 print(f"no runtime at {exe}; build it first (cargo build --release -p victory --features diagnostics --bins)")
103 return 1
104 title = os.path.join(args.game, TITLE_EXE)
105 if not os.path.isfile(title):
106 print(f"no title executable at {title}")
107 return 1
108 name = args.name or time.strftime("run-%Y%m%d-%H%M%S")
109 for key in ("ctl", "logs", "captures", "cache", "data"):
110 os.makedirs(p[key], exist_ok=True)
111 captures = os.path.join(p["captures"], name)
112 os.makedirs(captures, exist_ok=True)
113 data = args.data or p["data"]
114 os.makedirs(data, exist_ok=True)
115 # Fresh command files: the runtime only acts on increasing numbers.
116 for f in (p["pad"], p["shot"]):
117 if os.path.exists(f):
118 os.remove(f)
119 env = dict(os.environ)
120 env.update({
121 "VICTORY_GAME_DIR": args.game,
122 "VICTORY_CACHE_DIR": p["cache"],
123 "VICTORY_DATA_DIR": data,
124 "VICTORY_LOG": args.log,
125 "VICTORY_CAPTURE": captures,
126 "VICTORY_CAPTURE_REQUEST": p["shot"],
127 "VICTORY_MOVEMENT_FILE": p["pad"],
128 })
129 if args.world:
130 env["VICTORY_CAPTURE_WORLD"] = "1"
131 for item in args.env or []:
132 k, _, v = item.partition("=")
133 env[k] = v
134 log = os.path.join(p["logs"], f"{name}.log")
135 cmd = [exe, "run", title, "--execute", "--console", args.console]
136 flags = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
137 # The runtime writes its own bytes here; newline only keeps the repository's line-ending rule.
138 with open(log, "w", encoding="utf-8", newline="\n") as out:
139 proc = subprocess.Popen(cmd, cwd=args.game, env=env, stdout=out, stderr=subprocess.STDOUT,
140 stdin=subprocess.DEVNULL, creationflags=flags)
141 state = {
142 "pid": proc.pid, "name": name, "log": log, "captures": captures, "started": time.time(),
143 "pad_seq": 0, "shot_seq": 0, "cmd": cmd,
144 "env": {k: v for k, v in env.items() if k.startswith("VICTORY_")},
145 }
146 save_state(p, state)
147 print(f"started pid {proc.pid} as {name}\n log {log}\n captures {captures}")
148 return 0
149
150
151def cmd_press(args, p):
152 state = load_state(p)
153 seq = int(time.time() * 1000)
154 seq = max(seq, state.get("pad_seq", 0) + 1)
155 write_atomic(p["pad"], f"{seq} {args.key} {args.ms}")
156 state["pad_seq"] = seq
157 save_state(p, state)
158 print(f"pressed {args.key} for {args.ms} ms (sequence {seq})")
159 if args.wait:
160 time.sleep(args.ms / 1000.0 + 0.4)
161 return 0
162
163
164def newest_png(folder, since):
165 best = None
166 try:
167 for entry in os.scandir(folder):
168 if entry.name.endswith(".png") and entry.stat().st_mtime >= since:
169 if best is None or entry.stat().st_mtime > best.stat().st_mtime:
170 best = entry
171 except OSError:
172 return None
173 return best.path if best else None
174
175
176def shrink(path, width):
177 """A copy of the capture `width` pixels wide beside it (needs Pillow); the capture itself otherwise."""
178 try:
179 from PIL import Image
180 except ImportError:
181 return path
182 with Image.open(path) as im:
183 height = max(1, round(im.height * width / im.width))
184 small = im.resize((width, height), Image.LANCZOS)
185 out = path[:-4] + f"-w{width}.png"
186 small.save(out)
187 return out
188
189
190def cmd_shot(args, p):
191 state = load_state(p)
192 seq = state.get("shot_seq", 0) + 1
193 since = time.time() - 0.5
194 write_atomic(p["shot"], str(seq))
195 state["shot_seq"] = seq
196 save_state(p, state)
197 folder = state.get("captures")
198 deadline = time.time() + args.timeout
199 while time.time() < deadline:
200 found = newest_png(folder, since)
201 if found:
202 time.sleep(0.5) # let the writer finish
203 if args.small:
204 found = shrink(found, args.small)
205 print(found)
206 return 0
207 time.sleep(0.25)
208 print(f"no new frame in {folder} after {args.timeout} s (the title may not be presenting)")
209 return 1
210
211
212def fps_lines(log, count):
213 hits = [ln.rstrip() for ln in read_log(log) if FPS_RE.search(ln)]
214 return hits[-count:]
215
216
217def summarize(line):
218 m = FPS_RE.search(line)
219 if not m:
220 return line
221 tail = line[m.start():]
222 keep = []
223 for pattern in (r"\d+(?:\.\d+)? fps, \d+(?:\.\d+)? ms/frame", r"\(\S+ preparing", r"[\d.]+ on the GPU",
224 r"\d+ draws/frame", r"dropped \d+ without a host pipeline \(\d+ being made\)",
225 r"cpu [\d.]+% gpu \d+% busy ram \d+ MB"):
226 mm = re.search(pattern, tail)
227 if mm:
228 keep.append(mm.group(0))
229 stamp = line[:m.start()].split(" ")[0]
230 return f"{stamp} " + " | ".join(keep)
231
232
233def cmd_fps(args, p):
234 state = load_state(p)
235 log = args.log or state.get("log")
236 if not log:
237 print("no run recorded")
238 return 1
239 for line in fps_lines(log, args.count):
240 print(line if args.full else summarize(line))
241 return 0
242
243
244def cmd_status(args, p):
245 state = load_state(p)
246 if not state:
247 print("no run recorded")
248 return 1
249 up = time.time() - state.get("started", time.time())
250 print(f"{state.get('name')}: pid {state.get('pid')} {'running' if alive(state.get('pid')) else 'NOT running'}, "
251 f"up {int(up // 60)}:{int(up % 60):02d}")
252 for line in fps_lines(state["log"], 3):
253 print(" " + summarize(line))
254 lines = read_log(state["log"])
255 bad = [ln.rstrip() for ln in lines if re.search(r"\b(ERROR|WARN)\b|panicked|crash|DEVICE_HUNG|DEVICE_REMOVED", ln)]
256 for line in bad[-args.warnings:]:
257 print(" ! " + line[:300])
258 return 0
259
260
261def cmd_stop(args, p):
262 state = load_state(p)
263 pid = state.get("pid")
264 if not alive(pid):
265 print("no run is going")
266 return 0
267 subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
268 for _ in range(40):
269 if not alive(pid):
270 break
271 time.sleep(0.25)
272 print(f"stopped pid {pid} ({state.get('name')})")
273 return 0
274
275
276def main():
277 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
278 ap.add_argument("--work", default=DEFAULT_WORK, help="work folder outside the repository")
279 sub = ap.add_subparsers(dest="command", required=True)
280
281 s = sub.add_parser("start", help="launch the title under VIctory")
282 s.add_argument("--name")
283 s.add_argument("--game", default=DEFAULT_GAME)
284 s.add_argument("--exe", help="runtime executable (default: victory/target/<profile>/victory.exe)")
285 s.add_argument("--profile", default="release")
286 s.add_argument("--console", default="series-x", choices=["series-x", "series-s"])
287 s.add_argument("--log", default="info", help="VICTORY_LOG filter")
288 s.add_argument("--data", help="data folder (saves); default <work>/data")
289 s.add_argument("--world", action="store_true", help="also capture world frames (VICTORY_CAPTURE_WORLD)")
290 s.add_argument("--env", action="append", help="extra K=V for the run (repeatable)")
291
292 s = sub.add_parser("press", help="press a stand-in pad key")
293 s.add_argument("key")
294 s.add_argument("ms", nargs="?", type=int, default=200)
295 s.add_argument("--wait", action="store_true", help="return after the hold ends")
296
297 s = sub.add_parser("shot", help="save the next presented frame and print its path")
298 s.add_argument("--timeout", type=float, default=30.0)
299 s.add_argument("--small", type=int, default=0, metavar="WIDTH",
300 help="also write a copy this many pixels wide and print its path (needs Pillow)")
301
302 s = sub.add_parser("fps", help="latest frame-rate lines of the run's log")
303 s.add_argument("--count", type=int, default=5)
304 s.add_argument("--log")
305 s.add_argument("--full", action="store_true")
306
307 s = sub.add_parser("status", help="whether the run is going, its fps and last warnings")
308 s.add_argument("--warnings", type=int, default=5)
309
310 sub.add_parser("stop", help="end the run")
311
312 args = ap.parse_args()
313 p = paths(args.work)
314 return {"start": cmd_start, "press": cmd_press, "shot": cmd_shot, "fps": cmd_fps,
315 "status": cmd_status, "stop": cmd_stop}[args.command](args, p)
316
317
318if __name__ == "__main__":
319 sys.stdout.reconfigure(errors="replace")
320 sys.exit(main())
diff --git a/scripts/sync_victory.py b/scripts/sync_victory.py
deleted file mode 100644
index ccae2c459..000000000
--- a/scripts/sync_victory.py
+++ /dev/null
@@ -1,94 +0,0 @@
1#!/usr/bin/env python3
2"""Check DexNom/VIctory for new commits and optionally merge them into victory/.
3
4VIctory lives in this repository as a git subtree under ``victory/`` (added with
5``git subtree add --prefix=victory victory main``). This tool fetches the
6``victory`` remote, reports the commits that are not merged yet and, with
7``--merge``, pulls them in with ``git subtree pull`` so upstream history is kept
8and local changes under ``victory/`` are merged, not overwritten.
9
10Run from anywhere inside the repository:
11
12 python -I scripts/sync_victory.py # report only
13 python -I scripts/sync_victory.py --merge # report, then merge if clean
14
15Exit codes: 0 up to date or merged, 10 updates waiting (report only),
162 git failure, 3 working tree not clean (merge refused), 4 merge conflict.
17"""
18
19import argparse
20import datetime
21import os
22import subprocess
23import sys
24
25REMOTE = "victory"
26BRANCH = "main"
27PREFIX = "victory"
28
29
30def git(*args, check=True):
31 proc = subprocess.run(
32 ["git", *args],
33 stdout=subprocess.PIPE,
34 stderr=subprocess.STDOUT,
35 text=True,
36 encoding="utf-8",
37 errors="replace",
38 )
39 if check and proc.returncode != 0:
40 print(f"git {' '.join(args)} failed ({proc.returncode}):\n{proc.stdout}")
41 sys.exit(2)
42 return proc
43
44
45def main():
46 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
47 ap.add_argument("--merge", action="store_true", help="merge new commits with git subtree pull")
48 args = ap.parse_args()
49
50 top = git("rev-parse", "--show-toplevel").stdout.strip()
51 os.chdir(top)
52 stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
53
54 git("fetch", "--quiet", REMOTE, BRANCH)
55 upstream = git("rev-parse", f"{REMOTE}/{BRANCH}").stdout.strip()
56 merged = git("merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode == 0
57 if merged:
58 print(f"[{stamp}] {REMOTE}/{BRANCH} {upstream[:9]} is already merged; nothing to do.")
59 return 0
60
61 new = git("log", "--oneline", "--no-decorate", f"HEAD..{upstream}").stdout.strip().splitlines()
62 print(f"[{stamp}] {len(new)} new {REMOTE}/{BRANCH} commit(s) up to {upstream[:9]}:")
63 for line in new:
64 print(f" {line}")
65 if not args.merge:
66 return 10
67
68 dirty = git("status", "--porcelain", "--untracked-files=no").stdout.strip()
69 if dirty:
70 print("Working tree has uncommitted changes; commit or stash them, then run --merge again.")
71 print(dirty)
72 return 3
73
74 msg = (
75 f"Merge {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/ ({len(new)} commit(s))\n\n"
76 "Pulled with scripts/sync_victory.py --merge (git subtree pull).\n"
77 )
78 pull = git("subtree", "pull", f"--prefix={PREFIX}", REMOTE, BRANCH, "-m", msg, check=False)
79 print(pull.stdout.strip())
80 if pull.returncode != 0:
81 conflicts = git("diff", "--name-only", "--diff-filter=U", check=False).stdout.strip()
82 if conflicts:
83 print("Merge stopped on conflicts in:")
84 print(conflicts)
85 return 4
86 print("git subtree pull failed.")
87 return 2
88 print(f"Merged {REMOTE}/{BRANCH} {upstream[:9]} into {PREFIX}/.")
89 return 0
90
91
92if __name__ == "__main__":
93 sys.stdout.reconfigure(errors="replace")
94 sys.exit(main())
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md
index 26493ff8a..1d3328ec8 100644
--- a/scripts/windows-boot/README.md
+++ b/scripts/windows-boot/README.md
@@ -25,6 +25,9 @@ Set `LEONIDA_GAME_DIR`, `LEONIDA_SHADERS` (and `GTA6RT`, `LEONIDA_RUNS` if you u
25profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this 25profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\build\RelWithDebInfo\` of this
26checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`. 26checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`.
27The script refuses an output folder inside the repository. 27The script refuses an output folder inside the repository.
28The runtime starts in `<out>\work_<name>`, where driver artifacts such as `ucode.elf` can land. Relative path
29parameters are resolved from the caller's PowerShell location. Use absolute paths for additional runtime switches
30supplied through `-ExtraArgs` or custom environment variables.
28 31
29### Private crash diagnostics 32### Private crash diagnostics
30 33
@@ -87,6 +90,12 @@ Several records can describe one loss. A driver can also report loss without any
87Share counts and states on the board. Keep paths, logs, traces, captures and dumps on your machine 90Share counts and states on the board. Keep paths, logs, traces, captures and dumps on your machine
88([AGENTS.md](../../AGENTS.md), "No game data"). 91([AGENTS.md](../../AGENTS.md), "No game data").
89 92
93When the log contains a device loss, a fault query outcome or checkpoint records, `fault context` shows the first
94recognized Vulkan API that reported loss and the first observed fault query outcome. An unrecognized operation is
95shown as `other`. A missing outcome is `not observed`. The queue count includes queries that returned zero
96checkpoints. `reported` sums the driver counts from the queue headers. `decoded` and `unrecognized` count the
97two kinds of printed stage records, so a truncated log can have fewer printed records than reported checkpoints.
98
90How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing 99How to read the states: game state goes 1, 2 (init), 3 (running); session state goes 0, 1, 3 (landing
91screen waiting for A), `d` after A. 100screen waiting for A), `d` after A.
92 101
diff --git a/scripts/windows-boot/boot.ps1 b/scripts/windows-boot/boot.ps1
index 42753025c..98be96e92 100644
--- a/scripts/windows-boot/boot.ps1
+++ b/scripts/windows-boot/boot.ps1
@@ -148,6 +148,12 @@ function Get-FirstValue {
148 return "" 148 return ""
149} 149}
150 150
151function Get-BootPath {
152 param([string]$Path)
153 if ($Path) { return $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) }
154 return ""
155}
156
151function Read-SideFile { 157function Read-SideFile {
152 # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt). 158 # One line from a text file make_game.py writes beside gta6rt.exe (game_path.txt, shader_path.txt).
153 param([string]$Path) 159 param([string]$Path)
@@ -197,14 +203,14 @@ if (-not $Name) { $Name = "boot-" + (Get-Date -Format "yyyyMMdd-HHmmss") }
197if ($NoInput) { $InputScript = "" } 203if ($NoInput) { $InputScript = "" }
198if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" } 204if ($Name -notmatch '^[A-Za-z0-9._-]+$') { throw "-Name may hold letters, digits, '.', '_' and '-' only: $Name" }
199 205
200$Runtime = Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe")) 206$Runtime = Get-BootPath (Get-FirstValue @($Runtime, $env:GTA6RT, (Join-Path $RepoRoot "runtime\build\RelWithDebInfo\gta6rt.exe")))
201$RuntimeDir = Split-Path -Parent $Runtime 207$RuntimeDir = Split-Path -Parent $Runtime
202$GameDir = Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt"))) 208$GameDir = Get-BootPath (Get-FirstValue @($GameDir, $env:LEONIDA_GAME_DIR, (Read-SideFile (Join-Path $RuntimeDir "game_path.txt"))))
203$Exe = Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" })) 209$Exe = Get-BootPath (Get-FirstValue @($Exe, $env:LEONIDA_EXE, $(if ($GameDir) { Join-Path $GameDir $ExeName } else { "" })))
204$Shaders = Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS) 210$Shaders = Get-BootPath (Get-FirstValue @($Shaders, $env:LEONIDA_SHADERS))
205$OutDir = Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs")) 211$OutDir = Get-BootPath (Get-FirstValue @($OutDir, $env:LEONIDA_RUNS, (Join-Path $HOME "leonida-runs")))
206$OutDir = [System.IO.Path]::GetFullPath($OutDir) 212$Overlay = Get-BootPath (Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay")))
207$Overlay = Get-FirstValue @($Overlay, (Join-Path $OutDir "overlay")) 213$RunDirectory = Join-Path $OutDir ("work_" + $Name)
208$Capture = Join-Path $OutDir ("cap_" + $Name) 214$Capture = Join-Path $OutDir ("cap_" + $Name)
209$LogFile = Join-Path $OutDir ($Name + ".log") 215$LogFile = Join-Path $OutDir ($Name + ".log")
210$StdoutFile = Join-Path $OutDir ($Name + ".stdout.log") 216$StdoutFile = Join-Path $OutDir ($Name + ".stdout.log")
@@ -304,8 +310,7 @@ if ($bootEnv["LEONIDA_CAPTURE"]) { $Capture = $bootEnv["LEONIDA_CAPTURE"] }
304# is read here as the runtime's read-only seed (LEONIDA_PIPELINE_JOURNAL_SEED_DIR, docs/d3d12_vulkan.md), so the pipelines 310# is read here as the runtime's read-only seed (LEONIDA_PIPELINE_JOURNAL_SEED_DIR, docs/d3d12_vulkan.md), so the pipelines
305# it holds are not compiled again in the boot's own cache folder. Only when this shell or -SetEnv/KEY= did not decide, and 311# it holds are not compiled again in the boot's own cache folder. Only when this shell or -SetEnv/KEY= did not decide, and
306# when the two journals are distinct: the runtime turns its journal off for a seed that is, holds or sits in its writable 312# when the two journals are distinct: the runtime turns its journal off for a seed that is, holds or sits in its writable
307# journal (pipeline_cache_journal.h, resolve_roots). A relative cache folder is resolved by the runtime against its own 313# journal (pipeline_cache_journal.h, resolve_roots). A relative or unresolvable cache folder gets no automatic seed.
308# working folder, so it gets no seed here; a name that cannot be resolved gets none either, rather than a stop.
309if (-not $bootEnv.Contains("LEONIDA_PIPELINE_JOURNAL_SEED_DIR")) { 314if (-not $bootEnv.Contains("LEONIDA_PIPELINE_JOURNAL_SEED_DIR")) {
310 # Windows' final path of a folder (GetFinalPathNameByHandle) sees through junctions, symbolic links, substituted 315 # Windows' final path of a folder (GetFinalPathNameByHandle) sees through junctions, symbolic links, substituted
311 # and mapped drives, short 8.3 names and the \\?\ and \\.\ prefixes, as the runtime's std::filesystem checks do. 316 # and mapped drives, short 8.3 names and the \\?\ and \\.\ prefixes, as the runtime's std::filesystem checks do.
@@ -370,6 +375,19 @@ public static class LeonidaFinalPath {
370 if ($seed) { $bootEnv["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = $seed } 375 if ($seed) { $bootEnv["LEONIDA_PIPELINE_JOURNAL_SEED_DIR"] = $seed }
371} 376}
372 377
378foreach ($key in @("LEONIDA_SHADERS", "LEONIDA_PIPELINE_CACHE_DIR")) {
379 if ($bootEnv[$key]) { $bootEnv[$key] = Get-BootPath $bootEnv[$key] }
380}
381foreach ($key in @("LEONIDA_COMPAT_DIR", "LEONIDA_DSTORAGE_HISTORY", "LEONIDA_SAVE_DIR",
382 "LEONIDA_WRITE_DIR", "LEONIDA_XMEM_BACKING_DIR")) {
383 $value = $bootEnv[$key]
384 if ($value -and -not [System.IO.Path]::IsPathRooted($value)) {
385 $bootEnv[$key] = Get-BootPath (Join-Path $RepoRoot $value)
386 }
387}
388$Capture = Get-BootPath $Capture
389if ($bootEnv["LEONIDA_CAPTURE"]) { $bootEnv["LEONIDA_CAPTURE"] = $Capture }
390
373$launchMode = if ($FirstRunUi) { "--first-run-ui" } else { "--run" } 391$launchMode = if ($FirstRunUi) { "--first-run-ui" } else { "--run" }
374$gameArgs = @($launchMode, $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs 392$gameArgs = @($launchMode, $Exe, "--game-dir", $GameDir, "--overlay", $Overlay, "--trace", $TraceFile, "--trace-d3d12") + $ExtraArgs
375$argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " 393$argLine = ($gameArgs | ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " "
@@ -378,6 +396,7 @@ if (-not $DigestOnly) {
378 Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot" 396 Write-Output "[boot] $Name ${Seconds}s repo $RepoRoot"
379 Write-Output "[boot] gta6rt $Runtime" 397 Write-Output "[boot] gta6rt $Runtime"
380 Write-Output "[boot] out $OutDir" 398 Write-Output "[boot] out $OutDir"
399 Write-Output "[boot] cwd $RunDirectory"
381 foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } } 400 foreach ($k in $bootEnv.Keys) { if ($bootEnv[$k] -ne "") { Write-Output ("[boot] env {0}={1}" -f $k, $bootEnv[$k]) } }
382 Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine" 401 Write-Output "[boot] command $(ConvertTo-ProcessArgument $Runtime) $argLine"
383} 402}
@@ -417,7 +436,7 @@ if (-not $DigestOnly) {
417 } 436 }
418 } 437 }
419 438
420 foreach ($d in @($OutDir, $Overlay)) { New-Item -ItemType Directory -Force -Path $d | Out-Null } 439 foreach ($d in @($OutDir, $Overlay, $RunDirectory)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
421 if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) { 440 if ($bootEnv["LEONIDA_PIPELINE_CACHE_DIR"]) {
422 New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null 441 New-Item -ItemType Directory -Force -Path $bootEnv["LEONIDA_PIPELINE_CACHE_DIR"] | Out-Null
423 } 442 }
@@ -449,7 +468,7 @@ if (-not $DigestOnly) {
449 $launchArgs = (@($RepoRoot, $crashDir, $Seconds, $runtimePath, $childCommand) | 468 $launchArgs = (@($RepoRoot, $crashDir, $Seconds, $runtimePath, $childCommand) |
450 ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " " 469 ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " "
451 } 470 }
452 $proc = Start-Process -FilePath $launchFile -ArgumentList $launchArgs -WorkingDirectory $RepoRoot -NoNewWindow -PassThru ` 471 $proc = Start-Process -FilePath $launchFile -ArgumentList $launchArgs -WorkingDirectory $RunDirectory -NoNewWindow -PassThru `
453 -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile 472 -RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile
454 $handle = $proc.Handle # keeps the exit code readable after the process ends 473 $handle = $proc.Handle # keeps the exit code readable after the process ends
455 $stopped = $false 474 $stopped = $false
@@ -482,6 +501,67 @@ if (-not $DigestOnly) {
482 501
483# -------------------------------------------------------------------------------------------- the digest 502# -------------------------------------------------------------------------------------------- the digest
484 503
504function Get-FaultContext {
505 param([string]$Path)
506 $apis = @("vkAcquireNextImageKHR", "vkBeginCommandBuffer", "vkCreateSwapchainKHR", "vkDeviceWaitIdle",
507 "vkEndCommandBuffer", "vkGetFenceStatus", "vkGetQueryPoolResults", "vkGetSemaphoreCounterValue",
508 "vkQueueBindSparse", "vkQueuePresentKHR", "vkQueueSubmit", "vkQueueWaitIdle", "vkResetFences",
509 "vkSignalSemaphore", "vkWaitForFences", "vkWaitSemaphores")
510 $api = "not observed"
511 $query = "not observed"
512 $lost = $false
513 [long]$queues = 0
514 [long]$reported = 0
515 [long]$decoded = 0
516 [long]$unrecognized = 0
517
518 # Select-String streams matches, including a report that arrives after a long trace.
519 $prefix = '^\s*\[rt\] (device-fault: |vulkan: the device was lost \()'
520 Select-String -LiteralPath $Path -CaseSensitive -Pattern $prefix | ForEach-Object {
521 $tag = $_.Matches[0]
522 $record = $_.Line.Substring($tag.Length).TrimEnd()
523 if ($tag.Groups[1].Value -eq "vulkan: the device was lost (") {
524 $lost = $true
525 if ($api -in @("not observed", "other")) {
526 if ($record -cmatch '^(vkWaitSemaphores|vkGetSemaphoreCounterValue) in the fence dispatcher returned VK_ERROR_DEVICE_LOST\)') {
527 $api = $Matches[1]
528 } elseif ($record.StartsWith("a fence's counter read UINT64_MAX and vkDeviceWaitIdle then returned VK_ERROR_DEVICE_LOST)")) {
529 $api = "vkDeviceWaitIdle"
530 }
531 }
532 } elseif ($record.StartsWith("VK_ERROR_DEVICE_LOST from ")) {
533 $lost = $true
534 if ($api -in @("not observed", "other")) {
535 $api = "other"
536 if ($record -cmatch '^VK_ERROR_DEVICE_LOST from ([^\s(]+)' -and $apis -ccontains $Matches[1]) {
537 $api = $Matches[1]
538 }
539 }
540 } elseif ($record -cmatch '^queue \S+ checkpoints=([0-9]+)$') {
541 [uint32]$count = 0
542 if ([uint32]::TryParse($Matches[1], [ref]$count)) {
543 $queues++
544 $reported += $count
545 }
546 } elseif ($record -cmatch '^stage=0x[0-9a-fA-F]+ submission=[0-9]+ list=[0-9]+ command=[0-9]+ kind=\S+$') {
547 $decoded++
548 } elseif ($record -cmatch '^stage=0x[0-9a-fA-F]+ marker=\S+ \(unrecognized\)$') {
549 $unrecognized++
550 } elseif ($query -eq "not observed") {
551 if ($record.StartsWith("description:")) {
552 $query = if ($record.EndsWith(" (partial report)")) { "partial" } else { "complete" }
553 } elseif ($record -cmatch '^vkGetDeviceFaultInfoEXT (counts|data) failed \(-?[0-9]+\)$') {
554 $query = "$($Matches[1]) failed"
555 } elseif ($record -ceq "fault info collection failed") {
556 $query = "collection failed"
557 }
558 }
559 }
560 if ($lost -or $query -ne "not observed" -or $queues -or $decoded -or $unrecognized) {
561 "fault context: api=$api, query=$query, queues=$queues, reported=$reported, decoded=$decoded, unrecognized=$unrecognized"
562 }
563}
564
485$py = @(Resolve-Python $Python) 565$py = @(Resolve-Python $Python)
486if ($py.Count) { 566if ($py.Count) {
487 $pyArgs = @() 567 $pyArgs = @()
@@ -594,6 +674,10 @@ if ($deviceLost -or $faultClasses.Count) {
594} 674}
595$digest.Add("faults: $faultText") 675$digest.Add("faults: $faultText")
596if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") } 676if ($wrapped) { $digest.Add("wrapped: $wrapped lines mention wrapped V#s") }
677if (Test-Path -LiteralPath $LogFile) {
678 $faultContext = Get-FaultContext $LogFile
679 if ($faultContext) { $digest.Add($faultContext) }
680}
597$digest.Add("frames: $capText") 681$digest.Add("frames: $capText")
598$digest.Add("files: $LogFile, $TraceFile, $SummaryFile") 682$digest.Add("files: $LogFile, $TraceFile, $SummaryFile")
599$digest | Out-File -FilePath $DigestFile -Encoding utf8 683$digest | Out-File -FilePath $DigestFile -Encoding utf8
diff --git a/scripts/windows-boot/test_crash_monitor.py b/scripts/windows-boot/test_crash_monitor.py
index 140a870ab..a28af6380 100644
--- a/scripts/windows-boot/test_crash_monitor.py
+++ b/scripts/windows-boot/test_crash_monitor.py
@@ -34,7 +34,7 @@ class CrashMonitorTest(unittest.TestCase):
34 streams = dict((kind, pos) for kind, size, pos in 34 streams = dict((kind, pos) for kind, size, pos in
35 (struct.unpack_from("<III", data, offset + 12*i) for i in range(count))) 35 (struct.unpack_from("<III", data, offset + 12*i) for i in range(count)))
36 self.assertIn(3, streams) # ThreadListStream 36 self.assertIn(3, streams) # ThreadListStream
37 trace = (self.report / "stack.txt").read_text() 37 trace = (self.report / "stack.txt").read_text(encoding="utf-8", errors="replace") # module names may be in the ANSI code page
38 self.assertIn(f"code=0x{code:08x}", trace) 38 self.assertIn(f"code=0x{code:08x}", trace)
39 if exception: 39 if exception:
40 pos = streams[6] # ExceptionStream: thread ID, padding, exception record 40 pos = streams[6] # ExceptionStream: thread ID, padding, exception record
@@ -87,7 +87,7 @@ class CrashMonitorTest(unittest.TestCase):
87 sentinel.write_bytes(b"original") 87 sentinel.write_bytes(b"original")
88 self.assertNotEqual(self.run_fixture("worker"), 0) 88 self.assertNotEqual(self.run_fixture("worker"), 0)
89 self.assertEqual(list(self.report.iterdir()), [sentinel]) 89 self.assertEqual(list(self.report.iterdir()), [sentinel])
90 self.assertEqual(sentinel.read_text(), "original") 90 self.assertEqual(sentinel.read_text(encoding="utf-8"), "original")
91 91
92 def test_repo_rejected(self): 92 def test_repo_rejected(self):
93 self.report = REPO / (self.report.parent.name + "-forbidden") 93 self.report = REPO / (self.report.parent.name + "-forbidden")