upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMoonEyes <14891700+MoonEyes@users.noreply.github.com>2026-12-02 11:51:40 +0100
committerMoonEyes <14891700+MoonEyes@users.noreply.github.com>2026-12-02 11:51:40 +0100
commitfff970e616bf965729cd08a4e86bc6264494de73 (patch)
tree03cdc30677fbe1ddaaf33d160150c9afbcfe73c5
parent7c245a359b8bdb6d9985c6d3ffd2bee0609de911 (diff)
parent895c472faa1c3d44a1358640f09c1f10e6a6a876 (diff)
Merge origin/main into carry/1346
-rw-r--r--docs/game_gate.md16
-rw-r--r--docs/testing.md29
-rw-r--r--scripts/game-gate.ps144
-rw-r--r--scripts/red_green.py347
-rw-r--r--tests/test_awc_shorts.py40
-rw-r--r--tests/test_game_gate.py246
-rw-r--r--tests/test_pe_inspect.py346
-rw-r--r--tests/test_red_green.py382
-rw-r--r--tools/awc_shorts.py12
-rw-r--r--tools/game_gate.py133
-rw-r--r--tools/pe_inspect.py416
11 files changed, 1924 insertions, 87 deletions
diff --git a/docs/game_gate.md b/docs/game_gate.md
index 4849a85f6..ec6e3eece 100644
--- a/docs/game_gate.md
+++ b/docs/game_gate.md
@@ -27,7 +27,13 @@ pwsh -NoProfile -File scripts\game-gate.ps1 stop -RunDir <run folder>
27- **The play script's switches.** `-PlayArgs` passes them on as they are, for example `-SeriesS -NoFrameGen`. 27- **The play script's switches.** `-PlayArgs` passes them on as they are, for example `-SeriesS -NoFrameGen`.
28- **Reaching the world.** The gate does not drive the menus. Pass key presses with `LEONIDA_KEYS`; they are timed from the start of the process, so allow for the precompile. 28- **Reaching the world.** The gate does not drive the menus. Pass key presses with `LEONIDA_KEYS`; they are timed from the start of the process, so allow for the precompile.
29- **The caches.** `-Data` keeps its caches (`cache-2`); only the saves are copied. The first start after a translator change translates every shader again: run once before measuring. 29- **The caches.** `-Data` keeps its caches (`cache-2`); only the saves are copied. The first start after a translator change translates every shader again: run once before measuring.
30- **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45). 30- **Ending the run.** It stops when the time in the world reaches `-WorldSeconds`, when a `STOP` file appears in the run folder (`stop`), or after `-MaxMinutes` (45). It checks every 5 s. When two reasons come at the same check, the first of these wins: the title relaunched, the world time (`target`), the memory stop (below), the `STOP` file, the time limit. So a `STOP` file and the world time at the same check give `target`.
31- **Memory stop.** It also stops the run, the same clean way and with the reason `memory`, before memory runs out. A memory pile-up has taken a PC's whole Windows down, not only the device. It reads the runtime's memory lines (every 5 s, builds with diagnostics) and stops when:
32 - the game's private bytes pass `-StopPrivateMB` (default: the lower of 90 % of this PC's commit limit and 1.25 times its physical memory; with a large page file the limit is far above what a PC survives, and two Windows crashes came at about 100 GB private on a PC with 64 GB);
33 - the PC has less than `-StopCommitLeftMB` left to commit for 20 s (default: the larger of 128 MB and 0.25 % of the limit; on a PC with no page file a normal run can leave a few hundred MB);
34 - video memory stays over the system's budget for `-StopOverBudgetSeconds` (60).
35
36 0 turns a limit off. The limits go into `run.json` (`memory_stop`) and the summary (`memory.stop_limits`). A run that reaches `-WorldSeconds` at the same check as a limit stops with `target`: it is a measurement, and its memory peaks are in the summary all the same.
31- **How it stops.** With `WM_SYSCOMMAND`/`SC_CLOSE`, the runtime's own end: the title is suspended and the pipeline cache saved. It kills the game only if it has not ended 60 s later. 37- **How it stops.** With `WM_SYSCOMMAND`/`SC_CLOSE`, the runtime's own end: the title is suspended and the pipeline cache saved. It kills the game only if it has not ended 60 s later.
32- **Exit code.** 0 PASS, 1 FAIL, 2 ERROR. `start` exits when the detached run is created. 38- **Exit code.** 0 PASS, 1 FAIL, 2 ERROR. `start` exits when the detached run is created.
33 39
@@ -44,6 +50,7 @@ The run folder (under `-RunRoot`, by default `<Data>\gate-runs`, refused inside
44| `events.jsonl` | What the gate did and saw: the game found, the stop asked for and why, a kill, the exit code | 50| `events.jsonl` | What the gate did and saw: the game found, the stop asked for and why, a kill, the exit code |
45| `data\` | The run's copy of the template, and the runtime's `crashes.log` | 51| `data\` | The run's copy of the template, and the runtime's `crashes.log` |
46| `summary.json` | The result, below | 52| `summary.json` | The result, below |
53| `memory.csv` | One row per runtime memory line (every 5 s, builds with diagnostics): time, private bytes, of them in physical memory, the PC's memory free and left to commit, the card's video memory budget and in use, the shared memory in use, the objects let go that wait for their submissions, and the reaper thread's queue. Its header is `t_s,private_mb,in_memory_mb,pc_free_mb,pc_commit_left_mb,vram_budget_mb,vram_in_use_mb,shared_in_use_mb,waiting_objects,reaper_queue`. The video memory columns come from the video memory line nearest the memory line, and the last two from the census line nearest it, each within 2 s; a cell is empty when there is none. Only when the run has memory lines: a summary made again from a log without them removes an older `memory.csv` |
47 54
48## summary.json (`leonida-gate-summary/1`) 55## summary.json (`leonida-gate-summary/1`)
49 56
@@ -59,10 +66,10 @@ Times are seconds since the run started. The summary holds numbers, switch names
59| `times.world_s` | Seconds from `world_at_s` to the stop request | 66| `times.world_s` | Seconds from `world_at_s` to the stop request |
60| `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning | 67| `fps` | From the presents, after the first 60 s in the world: frames, median, p5, frame p95 (ms), median of the last 60 s (`end_median`), the first second with fewer than 2 frames, from 60 s in the world on too (`under_2_at_s`), the longest gap with no frame presented from the world on (`longest_present_gap_s`, `longest_gap_at_s`; on purpose from the world on: a freeze on pipeline compiles comes right after arrival, and 10 s with no frame is what a player sees), draws a frame. Without the present lines (a build without diagnostics), the median and p5 come from the frame lines, with a warning |
61| `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once | 68| `pipelines` | Waits that ran out (`missed_waits`), the most pipelines being made at once |
62| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card | 69| `memory` | Peaks over the whole run, from the runtime's memory line and video memory line (every 5 s; builds with diagnostics only, otherwise `source` is null): the process's private bytes and when (`private_max_mb`, `private_max_at_s`), the most of them in physical memory, the least the PC had left to commit and when, the card's video memory in use at its most and when, with the budget the system gave then (`vram_in_use_max_mb`, `vram_max_at_s`, `vram_budget_at_max_mb`), the seconds spent over that budget, and the most of the PC's memory shared with the card in use. The video memory is what the system counts for this process, less than a tool like `nvidia-smi` shows for the whole card. `stop_limits` holds the memory stop's limits from `run.json` (null from a gate without the memory stop). Also, from the runtime's census line, the reaper thread's queue at its longest and when (`reaper_queue_max`, `reaper_queue_max_at_s`) and the most objects let go that wait for their submissions (`waiting_objects_max`); how fast the private bytes grew in the world in MB a minute (`private_mb_per_min_in_world`, a least-squares slope over the memory lines from `world_at_s` to the stop request: on a short run it is the loading's climb, on a long one a pile-up's slope; null with fewer than 3 lines there); and `series`, the name of `memory.csv` (null without memory lines, or when the file could not be written, for example open in another program: `game_gate.py` says so on stderr and writes `summary.json` all the same). The video memory peak and the time over the budget count every video memory line: the one written with each memory line, and the ones the runtime writes right before and after it makes the swap chain, right after the swap chain's buffers are made again for another size or format, and right after the system changes the card's budget by 256 MB or more. `memory.csv` has only the one nearest each memory line, so the summary's peak can come from a line with no row there |
63| `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes | 70| `crash` | `kind` is `none`, `device_lost`, `panic` or `fault`. It also gives the time, the code, the module kind (`runtime`, `title`, `driver`, `system`, `unknown`) and the access (read/write). `title_watchdog` marks a write at address 0 in the title more than 25 s after the last frame line. `count` is the number of crashes |
64| `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` | 71| `exit` | The game's exit code, and its kind: `clean`, `device_lost` (0x887A0005), `killed` or `other` |
65| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched`), whether it was killed, whether the cache was saved, whether the suspend was in time | 72| `stop` | Why it was stopped (`target`, `stop_file`, `timeout`, `relaunched` or `memory`), whether it was killed, whether the cache was saved, whether the suspend was in time. After a memory stop, `memory_why` is the gate's whole sentence for it, with its numbers: `private bytes 31000 MB, over 30000 MB`, `the PC had under 200 MB left to commit for 25 s` or `video memory over its budget for 60 s`, for example. It is null for the other reasons |
66| `verdict` | `result`, `reasons`, `warnings`, `min_world_s` | 73| `verdict` | `result`, `reasons`, `warnings`, `min_world_s` |
67 74
68## The verdict 75## The verdict
@@ -81,6 +88,7 @@ Times are seconds since the run started. The summary holds numbers, switch names
81- `exited_before_stop`; 88- `exited_before_stop`;
82- `present_gap`; 89- `present_gap`;
83- `world_time_short`: the time limit came first; 90- `world_time_short`: the time limit came first;
91- `memory_stop`: the memory stop ended the run, which was on its way to running out. `world_time_short` and `world_not_reached` are not added to it: the stop is why the run was short;
84- `not_alive_at_stop`; 92- `not_alive_at_stop`;
85- `world_not_reached`, when the game ended before reaching the world. 93- `world_not_reached`, when the game ended before reaching the world.
86 94
@@ -96,8 +104,6 @@ A crash after the stop request is a warning, except a device loss or a panic, wh
96 104
97- A driver for the menus and a fixed route (a Lua mod). 105- A driver for the menus and a fixed route (a Lua mod).
98- An ABBA runner over several runs. 106- An ABBA runner over several runs.
99- A time series beside the summary (memory, census, reaping queue).
100- A "memory rising" warning. 107- A "memory rising" warning.
101- VRAM and RAM peaks.
102- The distance walked. 108- The distance walked.
103- The Vulkan runtime (`gta6rt`). 109- The Vulkan runtime (`gta6rt`).
diff --git a/docs/testing.md b/docs/testing.md
index a5686330c..31ab93653 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -144,10 +144,12 @@ python -I scripts/red_green.py <pull request number>
144 cherry-picked with a 3-way merge. A conflict, or a pull request that changes no test, is "red not constructible". 144 cherry-picked with a 3-way merge. A conflict, or a pull request that changes no test, is "red not constructible".
145 A hunk that mixes test and other code stays on the green side only. 145 A hunk that mixes test and other code stays on the green side only.
146- It runs `cargo test --no-fail-fast` for the crates under `d3d12/crates` and `d3d12/apps` the pull request touches, 146- It runs `cargo test --no-fail-fast` for the crates under `d3d12/crates` and `d3d12/apps` the pull request touches,
147 from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest. Both 147 from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest, after
148 sides run in one worktree with one cargo target dir, red first, under `<git common dir>/red-green` (`--work-dir` 148 removing the worktree's `__pycache__` folders so that no test runs stale bytecode. Both sides run in one worktree
149 to move it). The worktree and the target dir stay for the next run, which then builds only what changed. The 149 with one cargo target dir, red first, under `<git common dir>/red-green` (`--work-dir` to move it). The worktree
150 target dir takes several GB; delete the folder (and run `git worktree prune`) when done. 150 and the target dir stay for the next run, which then builds only what changed. The target dir takes several GB.
151 The worktree stays registered in git, in the default folder as with `--work-dir`: when done, run
152 `git worktree remove --force <folder>/tree` and delete the folder, or delete the folder and run `git worktree prune`.
151- It prints the tests that go from red to green, those that pass on red and fail on green, those that fail on both 153- It prints the tests that go from red to green, those that pass on red and fail on green, those that fail on both
152 (failing on `main` too), and those found on one side only. The verdict is one of: `red then green` (exit 0), 154 (failing on `main` too), and those found on one side only. The verdict is one of: `red then green` (exit 0),
153 `no red`, `red does not build`, `green fails`, `red not constructible`, `green not constructible`, `no tests ran`, 155 `no red`, `red does not build`, `green fails`, `red not constructible`, `green not constructible`, `no tests ran`,
@@ -157,6 +159,25 @@ python -I scripts/red_green.py <pull request number>
157 and the report says so; a second crash gives `compiler crashed`. Run it again later, or on another machine. 159 and the report says so; a second crash gives `compiler crashed`. Run it again later, or on another machine.
158- `red does not build` is the case the fork-CI steps above call "does not build without the pull request's new 160- `red does not build` is the case the fork-CI steps above call "does not build without the pull request's new
159 file": the test needs the new code, which does not show that it catches the bug. 161 file": the test needs the new code, which does not show that it catches the bug.
162- `--mutate` also checks that the tests catch the change itself, what verifiers do by hand by removing a line of the
163 fix. After the green side, it undoes each hunk of the pull request's code alone (Rust and Python files it changes,
164 outside the tests and `#[cfg(test)]` code) and runs the tests again. A hunk is `caught` when a test that went red
165 then green fails, `not caught` when they all still pass, `does not build` when those tests no longer run,
166 `compiler crashed` when the compiler crashed twice, or `does not apply` when `main` moved those lines since. Each
167 mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It
168 tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past --mutate-max`
169 (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not change the
170 verdict.
171- Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it.
172 The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not
173 read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no
174 Rust or Python code outside its tests (a test-only one, whose `no red` then says nothing against its test), or
175 `not run` when no test went red then green. `--json` has these in `mutations_not_run` and `added_not_mutated`.
176- Each command of a mutated run (`cargo test`, one Python test file) is stopped with the processes it started after
177 `--mutate-timeout` seconds (600). The hunk is then `caught by timeout` when a test was running (the undone code
178 made it hang), or `timed out building` when cargo had not started a test yet, which says nothing about the tests
179 (raise the option for a crate that builds slowly). When the command ends, the processes it left behind are
180 stopped too (a Windows job object, the process group elsewhere).
160- `--crate <name>` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base <ref>` tests on another 181- `--crate <name>` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base <ref>` tests on another
161 base, and `--no-fetch` uses the refs as they are. 182 base, and `--no-fetch` uses the refs as they are.
162 183
diff --git a/scripts/game-gate.ps1 b/scripts/game-gate.ps1
index 6ab0c11a9..1a153a8ae 100644
--- a/scripts/game-gate.ps1
+++ b/scripts/game-gate.ps1
@@ -15,6 +15,11 @@
15# saved) when -WorldSeconds were spent in the world, when a STOP file appears in the run folder, or after 15# saved) when -WorldSeconds were spent in the world, when a STOP file appears in the run folder, or after
16# -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR. 16# -MaxMinutes; it kills the game only if it has not ended 60 s later. Exit code: 0 PASS, 1 FAIL, 2 ERROR.
17# Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'. 17# Options: -WorldSeconds (300), -MaxMinutes (45), -More 'LEONIDA_X=1;LEONIDA_Y=2', -PlayArgs '-SeriesS -NoFrameGen'.
18# Memory stop (from the runtime's memory lines, every 5 s, builds with diagnostics): the run is stopped the same
19# clean way, with the reason `memory`, when the game's private bytes pass -StopPrivateMB (the lower of 90 % of this
20# PC's commit limit and 1.25 x its memory), when the PC has less than -StopCommitLeftMB left to commit for 20 s
21# (the larger of 128 MB and 0.25 % of the limit), or when video memory stays over the system's budget for
22# -StopOverBudgetSeconds (60). 0 turns one off. A run that reaches -WorldSeconds at the same poll stops with `target`.
18param( 23param(
19 [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb, 24 [Parameter(Mandatory, Position = 0)][ValidateSet('run', 'start', 'stop')][string]$Verb,
20 [string]$Game = '', 25 [string]$Game = '',
@@ -27,7 +32,10 @@ param(
27 [int]$MaxMinutes = 45, 32 [int]$MaxMinutes = 45,
28 [string]$More = '', 33 [string]$More = '',
29 [string]$PlayArgs = '', 34 [string]$PlayArgs = '',
30 [string]$Python = '' 35 [string]$Python = '',
36 [int]$StopPrivateMB = -1,
37 [int]$StopCommitLeftMB = -1,
38 [int]$StopOverBudgetSeconds = 60
31) 39)
32$ErrorActionPreference = 'Stop' 40$ErrorActionPreference = 'Stop'
33$repo = Split-Path -Parent $PSScriptRoot 41$repo = Split-Path -Parent $PSScriptRoot
@@ -96,7 +104,8 @@ if ($Verb -eq 'start') {
96 $line = @(& $quote $pwsh; '-NoProfile'; '-ExecutionPolicy'; 'Bypass'; '-File'; & $quote $PSCommandPath; 'run' 104 $line = @(& $quote $pwsh; '-NoProfile'; '-ExecutionPolicy'; 'Bypass'; '-File'; & $quote $PSCommandPath; 'run'
97 '-Game'; & $quote $Game; '-Data'; & $quote $Data; '-DataTemplate'; & $quote $DataTemplate; '-Name'; & $quote $Name 105 '-Game'; & $quote $Game; '-Data'; & $quote $Data; '-DataTemplate'; & $quote $DataTemplate; '-Name'; & $quote $Name
98 '-RunRoot'; & $quote $RunRoot; '-RunDir'; & $quote $RunDir; '-WorldSeconds'; $WorldSeconds; '-MaxMinutes'; $MaxMinutes 106 '-RunRoot'; & $quote $RunRoot; '-RunDir'; & $quote $RunDir; '-WorldSeconds'; $WorldSeconds; '-MaxMinutes'; $MaxMinutes
99 '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python) -join ' ' 107 '-More'; & $quote $More; '-PlayArgs'; & $quote $PlayArgs; '-Python'; & $quote $Python
108 '-StopPrivateMB'; $StopPrivateMB; '-StopCommitLeftMB'; $StopCommitLeftMB; '-StopOverBudgetSeconds'; $StopOverBudgetSeconds) -join ' '
100 # Created by Windows, not as a child of this shell: an agent's or a console's end does not end the run. 109 # Created by Windows, not as a child of this shell: an agent's or a console's end does not end the run.
101 $startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 } 110 $startup = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 }
102 $made = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ 111 $made = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{
@@ -140,6 +149,14 @@ $moreText
140& '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args 149& '$play' -Game '$Game' -Data '$Data' -More `$settings $PlayArgs @args
141"@ 150"@
142 151
152# The memory stop's limits, from this PC's commit limit unless given (0 turns one off). On a PC with no page file a
153# normal run can leave a few hundred MB to commit: the floor is low and must hold for 20 s.
154$commitLimitMB = [math]::Floor((Get-CimInstance Win32_OperatingSystem).TotalVirtualMemorySize / 1KB)
155$physicalMB = [math]::Floor((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB)
156# With a large page file the commit limit is far above what the PC survives: two Windows crashes (0x10E) came at
157# about 100 GB private on a PC with 64 GB of memory and a 175 GB limit. So also no more than 1.25 x the memory.
158if ($StopPrivateMB -lt 0) { $StopPrivateMB = [int][math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25) }
159if ($StopCommitLeftMB -lt 0) { $StopCommitLeftMB = [int][math]::Max(128, $commitLimitMB * 0.0025) }
143$gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1 160$gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterRAM } -Descending | Select-Object -First 1
144[ordered]@{ 161[ordered]@{
145 name = $Name 162 name = $Name
@@ -155,6 +172,7 @@ $gpu = Get-CimInstance Win32_VideoController | Sort-Object { [uint64]$_.AdapterR
155 world_seconds = $WorldSeconds 172 world_seconds = $WorldSeconds
156 max_minutes = $MaxMinutes 173 max_minutes = $MaxMinutes
157 f1_settings_file = $hadMenuFile 174 f1_settings_file = $hadMenuFile
175 memory_stop = [ordered]@{ private_max_mb = $StopPrivateMB; commit_left_min_mb = $StopCommitLeftMB; over_budget_s = $StopOverBudgetSeconds }
158} | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json') 176} | ConvertTo-Json | Set-Content (Join-Path $RunDir 'run.json')
159 177
160& pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt') 178& pwsh -NoProfile -ExecutionPolicy Bypass -File $launch -DryRun *> (Join-Path $RunDir 'settings.txt')
@@ -193,9 +211,20 @@ public static class GateWindow {
193'@ 211'@
194} 212}
195 213
214# Why this poll stops the run, or nothing. The target comes before the memory stop: a run that reached its world time
215# in the same poll as a memory limit is a measurement, and its memory peaks are in the summary all the same.
216function Get-StopReason($Poll, [bool]$StopFile, [double]$Minutes, [int]$TargetSeconds, [int]$LimitMinutes) {
217 if ($Poll.relaunched) { 'relaunched' }
218 elseif ($Poll.world_s -ge $TargetSeconds) { 'target' }
219 elseif ($Poll.memory_stop) { 'memory' }
220 elseif ($StopFile) { 'stop_file' }
221 elseif ($Minutes -ge $LimitMinutes) { 'timeout' }
222}
223
196$began = Get-Date 224$began = Get-Date
197$title = $null # the game process ($Game, the same name in any case, is its folder) 225$title = $null # the game process ($Game, the same name in any case, is its folder)
198$stopReason = $null 226$stopReason = $null
227$memoryWhy = $null
199try { 228try {
200while ($true) { 229while ($true) {
201 Start-Sleep -Seconds 5 230 Start-Sleep -Seconds 5
@@ -210,15 +239,14 @@ while ($true) {
210 if ($title -and $title.HasExited) { break } 239 if ($title -and $title.HasExited) { break }
211 if (-not $title -and $launcher.HasExited) { break } 240 if (-not $title -and $launcher.HasExited) { break }
212 $state = & $Python -I $tool state $RunDir | ConvertFrom-Json 241 $state = & $Python -I $tool state $RunDir | ConvertFrom-Json
213 if ($state.relaunched) { $stopReason = 'relaunched' } 242 $stopReason = Get-StopReason -Poll $state -StopFile (Test-Path (Join-Path $RunDir 'STOP')) `
214 elseif (Test-Path (Join-Path $RunDir 'STOP')) { $stopReason = 'stop_file' } 243 -Minutes ((Get-Date) - $began).TotalMinutes -TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes
215 elseif ($state.world_s -ge $WorldSeconds) { $stopReason = 'target' } 244 if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }
216 elseif (((Get-Date) - $began).TotalMinutes -ge $MaxMinutes) { $stopReason = 'timeout' }
217 if ($stopReason) { break } 245 if ($stopReason) { break }
218} 246}
219 247
220if ($stopReason -and $title -and -not $title.HasExited) { 248if ($stopReason -and $title -and -not $title.HasExited) {
221 Add-Event 'stop_requested' @{ reason = $stopReason } 249 Add-Event 'stop_requested' @{ reason = $stopReason; why = $memoryWhy }
222 if ([GateWindow]::Close($title.Id)) { Add-Event 'close_sent' } 250 if ([GateWindow]::Close($title.Id)) { Add-Event 'close_sent' }
223 if (-not $title.WaitForExit(60000)) { 251 if (-not $title.WaitForExit(60000)) {
224 Stop-Process -Id $title.Id -Force 252 Stop-Process -Id $title.Id -Force
@@ -226,7 +254,7 @@ if ($stopReason -and $title -and -not $title.HasExited) {
226 $title.WaitForExit() 254 $title.WaitForExit()
227 } 255 }
228} elseif ($stopReason) { 256} elseif ($stopReason) {
229 Add-Event 'stop_requested' @{ reason = $stopReason } 257 Add-Event 'stop_requested' @{ reason = $stopReason; why = $memoryWhy }
230} 258}
231if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } } 259if ($title) { Add-Event 'game_exited' @{ exit_code = $title.ExitCode } }
232if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force } 260if (-not $launcher.WaitForExit(30000)) { Stop-Process -Id $launcher.Id -Force }
diff --git a/scripts/red_green.py b/scripts/red_green.py
index 7d8305f45..e15b1c23f 100644
--- a/scripts/red_green.py
+++ b/scripts/red_green.py
@@ -3,6 +3,7 @@
3 3
4 python -I scripts/red_green.py <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch] 4 python -I scripts/red_green.py <pull request number | git ref> [--base REF] [--remote NAME] [--no-fetch]
5 [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] 5 [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json]
6 [--mutate [--mutate-max N] [--mutate-timeout SECONDS]]
6 7
7Green is the base (`<remote>/main` after a fetch, by default) with the pull request merged. Red is the base with 8Green is the base (`<remote>/main` after a fetch, by default) with the pull request merged. Red is the base with
8only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it 9only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it
@@ -30,11 +31,16 @@ from __future__ import annotations
30 31
31import argparse 32import argparse
32import json 33import json
34import math
33import os 35import os
34import re 36import re
37import shutil
38import signal
39import stat
35import subprocess 40import subprocess
36import sys 41import sys
37import tempfile 42import tempfile
43from collections import Counter
38from pathlib import Path 44from pathlib import Path
39 45
40IDENTITY = { 46IDENTITY = {
@@ -51,6 +57,98 @@ def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None
51 return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) 57 return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True)
52 58
53 59
60if os.name == "nt":
61 import ctypes
62 from ctypes import wintypes
63
64 class _JobLimits(ctypes.Structure):
65 """JOBOBJECT_EXTENDED_LIMIT_INFORMATION; only LimitFlags is set."""
66 _fields_ = [("per_process_user_time", ctypes.c_int64), ("per_job_user_time", ctypes.c_int64),
67 ("limit_flags", wintypes.DWORD), ("min_working_set", ctypes.c_size_t),
68 ("max_working_set", ctypes.c_size_t), ("active_process_limit", wintypes.DWORD),
69 ("affinity", ctypes.c_size_t), ("priority_class", wintypes.DWORD),
70 ("scheduling_class", wintypes.DWORD), ("io_counters", ctypes.c_uint64 * 6),
71 ("process_memory_limit", ctypes.c_size_t), ("job_memory_limit", ctypes.c_size_t),
72 ("peak_process_memory_used", ctypes.c_size_t), ("peak_job_memory_used", ctypes.c_size_t)]
73
74 _KERNEL32 = ctypes.WinDLL("kernel32", use_last_error=True)
75 _KERNEL32.CreateJobObjectW.restype = wintypes.HANDLE
76 _KERNEL32.CreateJobObjectW.argtypes = (ctypes.c_void_p, wintypes.LPCWSTR)
77 _KERNEL32.SetInformationJobObject.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD)
78 _KERNEL32.OpenProcess.restype = wintypes.HANDLE
79 _KERNEL32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
80 _KERNEL32.AssignProcessToJobObject.argtypes = (wintypes.HANDLE, wintypes.HANDLE)
81 _KERNEL32.TerminateJobObject.argtypes = (wintypes.HANDLE, wintypes.UINT)
82 _KERNEL32.CloseHandle.argtypes = (wintypes.HANDLE,)
83
84
85_JOB_WARNED = False # job_of() says once that it has no job object
86
87
88def job_of(p: subprocess.Popen):
89 """On Windows, a job object holding `p`, or None. The processes `p` starts join it, and closing it stops every
90 process in it (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE): a process that outlives `p` is stopped with the job, where
91 `taskkill /T` no longer finds it once `p` has ended. A process `p` starts before it joins (its first instants)
92 stays out. Without one, it says so on stderr once."""
93 global _JOB_WARNED
94 job = _KERNEL32.CreateJobObjectW(None, None)
95 limits = _JobLimits(limit_flags=0x2000) # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
96 handle = job and _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA
97 # 9: JobObjectExtendedLimitInformation
98 joined = (handle and _KERNEL32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits))
99 and _KERNEL32.AssignProcessToJobObject(job, handle))
100 error = ctypes.get_last_error()
101 if handle:
102 _KERNEL32.CloseHandle(handle)
103 if joined:
104 return job
105 if job:
106 _KERNEL32.CloseHandle(job)
107 if not _JOB_WARNED:
108 _JOB_WARNED = True
109 print(f"red_green: no Windows job object for the mutated runs (error {error}): a process one leaves behind "
110 "is not stopped", file=sys.stderr)
111 return None
112
113
114def stop_all(p: subprocess.Popen, job) -> None:
115 """Stops `p` and every process it started, still running or left behind: the job on Windows, the process group
116 elsewhere."""
117 if job is not None:
118 _KERNEL32.TerminateJobObject(job, 1)
119 _KERNEL32.CloseHandle(job)
120 elif os.name != "nt":
121 try:
122 os.killpg(p.pid, signal.SIGKILL)
123 except ProcessLookupError:
124 pass
125 if p.poll() is None:
126 p.kill()
127
128
129def run_output(cmd: list[str], cwd: Path, env: dict | None = None,
130 timeout: float | None = None) -> tuple[int | None, str]:
131 """The exit code and the output (error output included) of `cmd`. With a timeout, the output goes to a file, so
132 that a process left behind holding it does not hold the run; once `cmd` ends, or after `timeout` seconds (then
133 the exit code is None), it is stopped with every process it started."""
134 if timeout is None:
135 r = subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
136 return r.returncode, r.stdout.decode("utf-8", "replace")
137 with tempfile.TemporaryFile() as log:
138 p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT,
139 start_new_session=os.name != "nt")
140 job = job_of(p) if os.name == "nt" else None
141 try:
142 code = p.wait(timeout=timeout)
143 except subprocess.TimeoutExpired:
144 code = None
145 finally: # Ctrl+C too: on POSIX the new session keeps it from the processes started
146 stop_all(p, job)
147 p.wait()
148 log.seek(0)
149 return code, log.read().decode("utf-8", "replace")
150
151
54def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: 152def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str:
55 r = run(["git", *args], cwd, env, data) 153 r = run(["git", *args], cwd, env, data)
56 if check and r.returncode != 0: 154 if check and r.returncode != 0:
@@ -180,17 +278,24 @@ def hunks(diff: str) -> list[tuple[int, int, int, int]]:
180 return out 278 return out
181 279
182 280
183def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: 281def test_hunk_flags(old: bytes, new: bytes, diff: str) -> list[bool]:
184 """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" 282 """For each hunk of `diff` (a Rust file's, made with -U0), in order, whether it changes only test code: each line
283 it removes or adds is in a `#[cfg(test)]` item, blank or a comment, and one at least is in such an item. The red
284 side takes these hunks, and a mutation leaves them alone."""
185 old_lines, new_lines = lines_of(old), lines_of(new) 285 old_lines, new_lines = lines_of(old), lines_of(new)
186 old_tests, new_tests = test_lines(old), test_lines(new) 286 old_tests, new_tests = test_lines(old), test_lines(new)
187 keep = [] 287 flags = []
188 for a, b, c, d in hunks(diff): 288 for a, b, c, d in hunks(diff):
189 removed = range(a - 1, a - 1 + b) 289 lines = [(i in old_tests, old_lines[i]) for i in range(a - 1, a - 1 + b)] + \
190 added = range(c - 1, c - 1 + d) 290 [(i in new_tests, new_lines[i]) for i in range(c - 1, c - 1 + d)]
191 lines = [(i in old_tests, old_lines[i]) for i in removed] + [(i in new_tests, new_lines[i]) for i in added] 291 flags.append(bool(lines) and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines))
192 if lines and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines): 292 return flags
193 keep.append((a, b, c, d)) 293
294
295def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None:
296 """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none."""
297 old_lines, new_lines = lines_of(old), lines_of(new)
298 keep = [h for h, test in zip(hunks(diff), test_hunk_flags(old, new, diff)) if test]
194 if not keep: 299 if not keep:
195 return None 300 return None
196 out = list(old_lines) 301 out = list(old_lines)
@@ -282,36 +387,38 @@ COMPILER_CRASH = re.compile(
282 r"|(internal compiler error)|(the compiler unexpectedly panicked)|(memory allocation of \d+ bytes failed)") 387 r"|(internal compiler error)|(the compiler unexpectedly panicked)|(memory allocation of \d+ bytes failed)")
283 388
284 389
285def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: 390def cargo_once(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict:
286 cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] 391 cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo]
287 cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] 392 cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)]
288 env = dict(os.environ, CARGO_TARGET_DIR=str(target)) 393 env = dict(os.environ, CARGO_TARGET_DIR=str(target))
289 r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 394 code, out = run_output(cmd, tree / "d3d12", env, timeout)
290 out = r.stdout.decode("utf-8", "replace") 395 tests, unit, error, ran = {}, "?", None, False
291 tests, unit, error = {}, "?", None
292 for line in out.splitlines(): 396 for line in out.splitlines():
293 m = UNIT.match(line) 397 m = UNIT.match(line)
294 if m: 398 if m:
295 unit = m.group(1) or "doc:" + m.group(2) 399 unit, ran = m.group(1) or "doc:" + m.group(2), True
296 continue 400 continue
297 m = CARGO_TEST.match(line) 401 m = CARGO_TEST.match(line)
298 if m: 402 if m:
299 tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] 403 tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)]
300 elif error is None and CARGO_ERROR.match(line): 404 elif error is None and CARGO_ERROR.match(line):
301 error = line.strip() 405 error = line.strip()
302 no_build = r.returncode != 0 and not tests 406 no_build = code is not None and code != 0 and not tests
303 crash = COMPILER_CRASH.search(out) if no_build else None 407 crash = COMPILER_CRASH.search(out) if no_build else None
304 return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build and not crash else None, 408 # Stopped by the timeout: while building (no test binary had started) or while running the tests.
305 "crash": next(g for g in crash.groups() if g) if crash else None} 409 timed_out = None if code is not None else "running" if ran else "building"
410 return {"tests": tests, "no_build": (error or f"cargo exit {code}") if no_build and not crash else None,
411 "crash": next(g for g in crash.groups() if g) if crash else None, "timed_out": timed_out}
306 412
307 413
308def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: 414def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path, timeout: float | None) -> dict:
309 first = cargo_once(tree, crates, cargo, target) 415 first = cargo_once(tree, crates, cargo, target, timeout)
310 if not first["crash"]: 416 if not first["crash"]:
311 return {"tests": first["tests"], "no_build": first["no_build"]} 417 return {"tests": first["tests"], "no_build": first["no_build"], "timed_out": first["timed_out"]}
312 print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr) 418 print(f"red_green: the compiler crashed ({first['crash']}), running again", file=sys.stderr)
313 again = cargo_once(tree, crates, cargo, target) 419 again = cargo_once(tree, crates, cargo, target, timeout)
314 result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"]} 420 result = {"tests": again["tests"], "no_build": again["no_build"], "rerun_after": first["crash"],
421 "timed_out": again["timed_out"]}
315 if again["crash"]: 422 if again["crash"]:
316 result["compiler_crashed"] = again["crash"] 423 result["compiler_crashed"] = again["crash"]
317 return result 424 return result
@@ -321,13 +428,43 @@ PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|s
321 re.M) 428 re.M)
322 429
323 430
324def python_tests(tree: Path, files: list[str]) -> dict: 431def drop_bytecode(tree: Path) -> None:
325 tests, no_build = {}, [] 432 """Removes every `__pycache__` folder of the work tree. Python runs a .pyc instead of its source when the source
433 time and size it records still match (an undone change of the same size within the same second) or when it is an
434 unchecked-hash one, and `git clean` keeps them (they are ignored). An option of the run's own Python, such as
435 `-X pycache_prefix`, would not reach the processes its tests start. Links (symbolic links, and junctions, which
436 `is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's. A folder it
437 cannot list is skipped: Python cannot import from it either. A `__pycache__` it cannot remove stops the run."""
438 folders, todo = [], [tree]
439 while todo:
440 try:
441 with os.scandir(todo.pop()) as entries:
442 for e in entries:
443 if not e.is_dir(follow_symlinks=False) or e.is_symlink():
444 continue
445 if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) \
446 & stat.FILE_ATTRIBUTE_REPARSE_POINT:
447 continue # a junction (Windows)
448 (folders if e.name == "__pycache__" else todo).append(e.path)
449 except OSError:
450 continue
451 for folder in folders:
452 try:
453 shutil.rmtree(folder)
454 except OSError as e:
455 raise Failure(f"cannot remove {folder}, whose bytecode could run instead of the code: {e}") from None
456
457
458def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict:
459 tests, no_build, timed_out = {}, [], None
460 drop_bytecode(tree)
326 for f in files: 461 for f in files:
327 start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) 462 start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent)
328 r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], 463 # -B only stops writing bytecode, not reading it: drop_bytecode() above keeps stale bytecode out.
329 cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 464 code, out = run_output([sys.executable, "-I", "-B", "-m", "unittest", "discover", "-s", start,
330 out = r.stdout.decode("utf-8", "replace") 465 "-p", Path(f).name, "-v"], tree, timeout=timeout)
466 if code is None:
467 timed_out = "running"
331 found = 0 468 found = 0
332 for name, where, status in PY_TEST.findall(out): 469 for name, where, status in PY_TEST.findall(out):
333 if "_FailedTest" in where: 470 if "_FailedTest" in where:
@@ -336,20 +473,27 @@ def python_tests(tree: Path, files: list[str]) -> dict:
336 key = where if where.endswith("." + name) else f"{where}.{name}" 473 key = where if where.endswith("." + name) else f"{where}.{name}"
337 tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") 474 tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed")
338 found += 1 475 found += 1
339 if not found and r.returncode != 0 and f"{f}: does not import" not in no_build: 476 if not found and code not in (0, None) and f"{f}: does not import" not in no_build:
340 no_build.append(f"{f}: exit {r.returncode}") 477 no_build.append(f"{f}: exit {code}")
341 return {"tests": tests, "no_build": "; ".join(no_build) or None} 478 return {"tests": tests, "no_build": "; ".join(no_build) or None, "timed_out": timed_out}
342 479
343 480
344def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: 481def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path,
345 result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None} 482 timeout: float | None = None) -> dict:
346 for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ 483 """The tests of one side: the crates, and those of the Python test files that this tree has. With a timeout (the
347 ([python_tests(tree, py_files)] if py_files else []): 484 mutated runs), a command that runs past it is stopped and `timed_out` says when: "building" (cargo, before any
485 test binary ran) or "running"."""
486 py_files = [f for f in py_files if (tree / f).is_file()]
487 result = {"tests": {}, "no_build": [], "compiler_crashed": None, "rerun_after": None, "timed_out": None}
488 for part in ([cargo_tests(tree, crates, cargo, target, timeout)] if crates else []) + \
489 ([python_tests(tree, py_files, timeout)] if py_files else []):
348 result["tests"].update(part["tests"]) 490 result["tests"].update(part["tests"])
349 if part["no_build"]: 491 if part["no_build"]:
350 result["no_build"].append(part["no_build"]) 492 result["no_build"].append(part["no_build"])
351 for key in ("compiler_crashed", "rerun_after"): 493 for key in ("compiler_crashed", "rerun_after"):
352 result[key] = result[key] or part.get(key) 494 result[key] = result[key] or part.get(key)
495 if part.get("timed_out") and result["timed_out"] != "running": # a test stopped running outweighs a build
496 result["timed_out"] = part["timed_out"]
353 return result 497 return result
354 498
355 499
@@ -423,6 +567,19 @@ def report(r: dict) -> str:
423 if len(rows[key]) > 40: 567 if len(rows[key]) > 40:
424 out.append(f" ... {len(rows[key]) - 40} more") 568 out.append(f" ... {len(rows[key]) - 40} more")
425 out.append(f"pass on both: {rows['pass_on_both']}") 569 out.append(f"pass on both: {rows['pass_on_both']}")
570 if r.get("mutations") is not None:
571 if r.get("mutations_not_run"):
572 out.append(f"mutations: {r['mutations_not_run']}")
573 else:
574 counts = Counter(m["result"] for m in r["mutations"])
575 out.append(f"mutations ({len(r['mutations'])} hunks undone one at a time): "
576 + ", ".join(f"{n} {k}" for k, n in sorted(counts.items())))
577 out += [f" {m['file']}:{m['line']}: {m['result']}" for m in r["mutations"]]
578 if r.get("mutations_skipped"):
579 out.append("not tried, past --mutate-max: "
580 + ", ".join(f"{m['file']}:{m['line']}" for m in r["mutations_skipped"]))
581 if r.get("added_not_mutated"):
582 out.append("not mutated, added by the pull request: " + ", ".join(r["added_not_mutated"]))
426 out.append(f"verdict: {r['verdict']}") 583 out.append(f"verdict: {r['verdict']}")
427 return "\n".join(out) 584 return "\n".join(out)
428 585
@@ -439,7 +596,21 @@ def main(argv: list[str] | None = None) -> int:
439 p.add_argument("--no-python", action="store_true", help="skip the Python tests") 596 p.add_argument("--no-python", action="store_true", help="skip the Python tests")
440 p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") 597 p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)")
441 p.add_argument("--json", action="store_true", help="print the result as JSON") 598 p.add_argument("--json", action="store_true", help="print the result as JSON")
599 p.add_argument("--mutate", action="store_true",
600 help="undo each code hunk alone on green and run the tests again (caught or not)")
601 p.add_argument("--mutate-max", type=int, help="the most hunks --mutate tries, 1 or more (10)")
602 p.add_argument("--mutate-timeout", type=float, metavar="SECONDS",
603 help="stop a command of a mutated run (cargo test, one Python test file) after this long: the hunk "
604 "is caught by timeout, or timed out building if cargo had not started a test (600)")
442 a = p.parse_args(argv) 605 a = p.parse_args(argv)
606 if not a.mutate and (a.mutate_max is not None or a.mutate_timeout is not None):
607 p.error("--mutate-max and --mutate-timeout go with --mutate")
608 if a.mutate_max is not None and a.mutate_max < 1:
609 p.error("--mutate-max must be 1 or more")
610 if a.mutate_timeout is not None and not (math.isfinite(a.mutate_timeout) and a.mutate_timeout > 0):
611 p.error("--mutate-timeout must be a number of seconds above 0")
612 a.mutate_max = 10 if a.mutate_max is None else a.mutate_max
613 a.mutate_timeout = 600.0 if a.mutate_timeout is None else a.mutate_timeout
443 try: 614 try:
444 repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) 615 repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel"))
445 common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) 616 common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir"))
@@ -463,6 +634,14 @@ def main(argv: list[str] | None = None) -> int:
463 os.close(fd) 634 os.close(fd)
464 try: 635 try:
465 result = check(repo, work, a, base, base_commit, head, merge_base) 636 result = check(repo, work, a, base, base_commit, head, merge_base)
637 except Failure:
638 # Stopped midway (a side, a mutation): the tree goes back on the base, as at the end of a run.
639 if (work / "tree" / ".git").exists():
640 try:
641 checkout(repo, work / "tree", base_commit)
642 except Failure:
643 pass
644 raise
466 finally: 645 finally:
467 lock.unlink(missing_ok=True) 646 lock.unlink(missing_ok=True)
468 except Failure as e: 647 except Failure as e:
@@ -492,26 +671,114 @@ def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, mer
492 red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) 671 red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck)
493 else: 672 else:
494 print("red_green: red side...", file=sys.stderr) 673 print("red_green: red side...", file=sys.stderr)
495 red = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) 674 red = side(tree, crates, py_files, a.cargo, target)
496 675
497 green, green_why = None, None 676 green, green_why, green_commit = None, None, None
498 checkout(repo, tree, base_commit) 677 checkout(repo, tree, base_commit)
499 git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) 678 git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False)
500 stuck = conflicts(tree) 679 stuck = conflicts(tree)
501 if stuck: 680 if stuck:
502 green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) 681 green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck)
503 else: 682 else:
683 if a.mutate: # the merge as it is now, before a test can write into the tree: each mutation starts from it
684 green_commit = git(tree, "commit-tree", git(tree, "write-tree"), "-p", base_commit, "-p", head,
685 "-m", f"red_green: {head[:12]} merged", env=env)
504 print("red_green: green side...", file=sys.stderr) 686 print("red_green: green side...", file=sys.stderr)
505 green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) 687 green = side(tree, crates, py_files, a.cargo, target)
688 rows = compare(red, green)
689 # With --mutate, `mutations` is a list (empty when no hunk was undone, and `mutations_not_run` says why).
690 mutations, not_run, skipped, added = None, None, None, None
691 if a.mutate:
692 hunks, added, mutations = code_hunks(repo, merge_base, head), code_files(repo, merge_base, head, "A"), []
693 if green is None:
694 not_run = "not run: there is no green side"
695 elif not hunks:
696 not_run = ("nothing to undo in the files it modifies: its code changes are in files it adds" if added else
697 "nothing to undo: the diff changes no Rust or Python code outside its tests")
698 elif not rows["red_to_green"]:
699 not_run = "not run: no test went red then green, so none can catch a hunk"
700 else:
701 print("red_green: mutations...", file=sys.stderr)
702 mutations = mutate(tree, green_commit, hunks[:a.mutate_max], rows["red_to_green"], crates, py_files,
703 a.cargo, target, a.mutate_timeout)
704 skipped = [{"file": path, "line": line} for path, line, _ in hunks[a.mutate_max:]]
506 checkout(repo, tree, base_commit) 705 checkout(repo, tree, base_commit)
507 706
508 rows = compare(red, green)
509 return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, 707 return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base,
510 "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, 708 "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates,
511 "python_files": py_files, "red": red, "green": green, "rows": rows, 709 "python_files": py_files, "red": red, "green": green, "rows": rows, "mutations": mutations,
710 "mutations_not_run": not_run, "mutations_skipped": skipped, "added_not_mutated": added,
512 "verdict": verdict(red_why, green_why, red, green, rows)} 711 "verdict": verdict(red_why, green_why, red, green, rows)}
513 712
514 713
714def code_files(repo: Path, merge_base: str, head: str, status: str) -> list[str]:
715 """The Rust and Python files outside the tests that the pull request changes with git status `status` (M
716 modified, A added). Added files are not mutated: undoing one deletes it, which only shows that something uses it."""
717 paths = git(repo, "diff", "--name-only", "--no-renames", f"--diff-filter={status}", merge_base, head).splitlines()
718 return [p for p in paths if not is_test_file(p)
719 and (p.endswith(".rs") or (p.endswith(".py") and not p.startswith("tests/")))]
720
721
722def code_hunks(repo: Path, merge_base: str, head: str) -> list[tuple[str, int, str]]:
723 """(file, first changed line in the pull request, patch) for each hunk of its code outside its tests in the files
724 it modifies: the hunks a mutation undoes one at a time. Without context, so that a test changed next to the code is
725 a hunk of its own (a hunk does not apply where `main` moved the lines since)."""
726 out = []
727 for path in code_files(repo, merge_base, head, "M"):
728 diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path)
729 lines = diff.split("\n")
730 first = next((i for i, line in enumerate(lines) if line.startswith("@@")), None)
731 if first is None:
732 continue
733 header = "\n".join(lines[:first])
734 blocks: list[list[str]] = []
735 for line in lines[first:]:
736 if line.startswith("@@"):
737 blocks.append([line])
738 else:
739 blocks[-1].append(line)
740 # A hunk of test code only is the tests' own, not the fix: the same rule as the red side's.
741 tests_only = (test_hunk_flags(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff)
742 if path.endswith(".rs") else [False] * len(blocks))
743 for block, test in zip(blocks, tests_only):
744 m = HUNK.match(block[0])
745 if m and not test:
746 out.append((path, int(m.group(3)), header + "\n" + "\n".join(block).rstrip("\n") + "\n"))
747 return out
748
749
750def mutate(tree: Path, green: str, hunks: list[tuple[str, int, str]], targets: list[str], crates: list[str],
751 py_files: list[str], cargo: str, target: Path, timeout: float) -> list[dict]:
752 """Undoes each code hunk alone on the green tree and runs the tests again: a hunk is caught when one of the tests
753 that went red then green fails, or caught by timeout when a command runs past `timeout` seconds. Each one starts
754 from the commit `green`, reset and cleaned, so what a test wrote into the tree changes no other."""
755 results = []
756 for path, line, patch in hunks:
757 entry = {"file": path, "line": line, "result": None}
758 git(tree, "reset", "--hard", "-q", green)
759 git(tree, "clean", "-fdq")
760 undo = run(["git", "apply", "-R", "--unidiff-zero", "-"], tree, data=patch.encode())
761 if undo.returncode != 0:
762 entry["result"] = "does not apply"
763 results.append(entry)
764 continue
765 s = side(tree, crates, py_files, cargo, target, timeout)
766 if s.get("compiler_crashed"):
767 entry["result"] = "compiler crashed"
768 elif any(s["tests"].get(t) == "failed" for t in targets):
769 entry["result"] = "caught"
770 elif s["timed_out"] == "building": # no answer: the build was too slow, or the undone code made it hang
771 entry["result"] = "timed out building"
772 elif s["timed_out"]:
773 entry["result"] = "caught by timeout"
774 elif not any(t in s["tests"] for t in targets):
775 entry["result"] = "does not build"
776 else:
777 entry["result"] = "not caught"
778 results.append(entry)
779 return results
780
781
515if __name__ == "__main__": 782if __name__ == "__main__":
516 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode 783 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
517 sys.stdout.reconfigure(errors="replace") 784 sys.stdout.reconfigure(errors="replace")
diff --git a/tests/test_awc_shorts.py b/tests/test_awc_shorts.py
index 9540dc218..7d34ce1d6 100644
--- a/tests/test_awc_shorts.py
+++ b/tests/test_awc_shorts.py
@@ -322,6 +322,46 @@ class ShortsTest(unittest.TestCase):
322 shorts._write_catalog(path, []) 322 shorts._write_catalog(path, [])
323 self.assertTrue(len(chmod_calls) > 0) 323 self.assertTrue(len(chmod_calls) > 0)
324 324
325 def test_catalog_collision_with_input_bank_rejected(self):
326 bank = os.path.join(self.tmp.name, "shorts.csv")
327 with open(bank, "wb") as f:
328 f.write(b"original input bank data")
329 out = self.tmp.name
330 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
331 rc = shorts.main([bank, out, "--jobs", "1"])
332 self.assertEqual(rc, 2)
333 self.assertIn("catalog would overwrite the input bank", err.getvalue())
334 self.assertEqual(len(err.getvalue().splitlines()), 1)
335 with open(bank, "rb") as f:
336 self.assertEqual(f.read(), b"original input bank data")
337
338 def test_catalog_collision_with_bank_export_directory_rejected(self):
339 bank = os.path.join(self.tmp.name, "shorts.csv.awc")
340 with open(bank, "wb") as f:
341 f.write(b"bank data")
342 out = self.tmp.name
343 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
344 rc = shorts.main([bank, out, "--jobs", "1"])
345 self.assertEqual(rc, 2)
346 self.assertIn("catalog would collide with bank export directory", err.getvalue())
347 self.assertEqual(len(err.getvalue().splitlines()), 1)
348 with open(bank, "rb") as f:
349 self.assertEqual(f.read(), b"bank data")
350
351 def test_catalog_collision_refusal_creates_no_output_folder(self):
352 src = os.path.join(self.tmp.name, "src")
353 os.makedirs(src)
354 out = os.path.join(self.tmp.name, "out")
355 bank = os.path.join(src, "shorts.csv.awc")
356 with open(bank, "wb") as f:
357 f.write(b"bank data")
358 # The bank exports to out/shorts.csv, the catalog's own path: refused before out/ exists.
359 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
360 rc = shorts.main([bank, out, "--jobs", "1"])
361 self.assertEqual(rc, 2)
362 self.assertIn("catalog would collide with bank export directory", err.getvalue())
363 self.assertFalse(os.path.exists(out))
364
325 365
326if __name__ == "__main__": 366if __name__ == "__main__":
327 unittest.main(verbosity=2) 367 unittest.main(verbosity=2)
diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py
index 9873a95bf..b842660f9 100644
--- a/tests/test_game_gate.py
+++ b/tests/test_game_gate.py
@@ -1,6 +1,9 @@
1"""tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's 1"""tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's
2formats (no game data). The contract test checks that those formats are still in the runtime's source.""" 2formats (no game data). The contract test checks that those formats are still in the runtime's source."""
3import contextlib
4import csv
3import datetime as dt 5import datetime as dt
6import io
4import json 7import json
5import os 8import os
6import re 9import re
@@ -50,8 +53,14 @@ class Fake:
50 self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1") 53 self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1")
51 t += gap 54 t += gap
52 55
53 def memory(self, t, private, used, budget=8000, left=3000, shared=500): 56 def memory(self, t, private, used, budget=8000, left=3000, shared=500, waiting=0, reaper=0):
54 """The runtime's video memory line and memory line, as a diagnostics build writes them every 5 s.""" 57 """The runtime's video memory line, census line and memory line, as a diagnostics build writes them every 5 s."""
58 self.log.append(f"{stamp(t)} INFO leonida_gpu::census: memory, what waits to be let go: {waiting} objects let "
59 f"go that wait for the submissions that may use them (LEONIDA_BURY_LAG), {reaper} retired "
60 f"objects, landed host lists and lists' fronts handed to the thread that lets them go and not "
61 f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread); 0 let go by the thread done "
62 f"with them instead, since the start, the reaper thread's line holding LEONIDA_REAPER_LIMIT=0 or "
63 f"more (0: no bound)")
55 self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " 64 self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory "
56 f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " 65 f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, "
57 f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could " 66 f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could "
@@ -66,6 +75,11 @@ class Fake:
66 self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title") 75 self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title")
67 self.event(t + 0.5, "game_exited", exit_code=exit_code) 76 self.event(t + 0.5, "game_exited", exit_code=exit_code)
68 77
78 def state(self):
79 """What the supervisor reads during the run (`game_gate.py state`)."""
80 self.summarize()
81 return game_gate.state(game_gate.Run(self.dir))
82
69 def summarize(self): 83 def summarize(self):
70 self.log.sort(key=lambda l: l[:27]) 84 self.log.sort(key=lambda l: l[:27])
71 files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n", 85 files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n",
@@ -235,12 +249,177 @@ class Measures(unittest.TestCase):
235 self.assertEqual(m["vram_over_budget_s"], 185.0) 249 self.assertEqual(m["vram_over_budget_s"], 185.0)
236 self.assertEqual(m["shared_in_use_max_mb"], 563) 250 self.assertEqual(m["shared_in_use_max_mb"], 563)
237 251
252 def memory_run(self, limits, rows):
253 """A run in the world with memory lines every 5 s from 70 s: rows of (private, video in use, PC left)."""
254 f = Fake()
255 f.meta["memory_stop"] = limits
256 f.event(1, "game", pid=1)
257 f.frames(10, 70, 60.0, 13)
258 f.frames(70, 70 + 5 * len(rows), 30.0, 4000)
259 for i, (private, used, left) in enumerate(rows):
260 f.memory(70 + 5 * i, private, used, budget=8000, left=left)
261 return f
262
263 def test_the_memory_stop_asks_for_a_stop_past_each_limit(self):
264 limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60}
265 calm = [(24000, 7000, 3000)] * 10
266 cases = {
267 "private bytes 31000 MB, over 30000 MB": calm + [(31000, 7000, 3000)],
268 "the PC had under 200 MB left to commit for 25 s": calm + [(24000, 7000, 150)] * 6,
269 # Exactly 20 s under the floor (five lines 5 s apart) is enough: the floor's boundary, as 60 s is the
270 # video memory's.
271 "the PC had under 200 MB left to commit for 20 s": calm + [(24000, 7000, 150)] * 5,
272 "video memory over its budget for 60 s": calm + [(24000, 9000, 3000)] * 13,
273 }
274 for why, rows in cases.items():
275 self.assertEqual(self.memory_run(limits, rows).state()["memory_stop"], why)
276 # Under each limit, at the private limit itself, or not for long enough: no stop.
277 for rows in (calm, calm + [(30000, 7000, 3000)], calm + [(24000, 7000, 150)] * 4,
278 calm + [(24000, 9000, 3000)] * 12):
279 self.assertIsNone(self.memory_run(limits, rows).state()["memory_stop"])
280 # 0 turns a limit off, and a run.json without limits (an older gate) never stops for memory.
281 off = {"private_max_mb": 0, "commit_left_min_mb": 0, "over_budget_s": 0}
282 self.assertIsNone(self.memory_run(off, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"])
283 self.assertIsNone(self.memory_run(None, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"])
284 # A negative limit is off too, not a stop at the first line (`-StopOverBudgetSeconds -1` stopped every run).
285 for name in limits:
286 self.assertIsNone(self.memory_run(dict(limits, **{name: -1}), calm).state()["memory_stop"], name)
287
288 def test_a_run_stopped_for_memory_fails_with_its_reason(self):
289 limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60}
290 f = self.memory_run(limits, [(24000, 7000, 3000)] * 10 + [(31000, 7000, 3000)])
291 f.event(121, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB")
292 f.log.append(f"{stamp(121.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title")
293 f.event(121.5, "game_exited", exit_code=0)
294 s = f.summarize()
295 self.assertEqual(s["verdict"]["result"], "FAIL")
296 self.assertEqual(s["verdict"]["reasons"], ["memory_stop"])
297 self.assertEqual(s["stop"]["reason"], "memory")
298 self.assertEqual(s["stop"]["memory_why"], "private bytes 31000 MB, over 30000 MB")
299 self.assertEqual(s["memory"]["stop_limits"], limits)
300 # Stopped before the world (seen in a real run with a low cap): the memory stop is the one reason.
301 f = Fake()
302 f.meta["memory_stop"] = limits
303 f.event(1, "game", pid=1)
304 f.frames(10, 80, 60.0, 13)
305 f.memory(75, 31000, 4000)
306 f.event(80, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB")
307 f.event(83, "game_exited", exit_code=0)
308 self.assertEqual(f.summarize()["verdict"]["reasons"], ["memory_stop"])
309
310 def test_the_memory_series_and_a_pile_ups_slope(self):
311 f = passing()
312 for t in range(10, 390, 5):
313 # From the world on (70 s) the private bytes grow 10 MB every 5 s and the reaper's queue grows.
314 grown = max(0, t - 70) // 5
315 f.memory(t, 20000 + 10 * grown, 7000, waiting=3, reaper=100 * grown)
316 s = f.summarize()
317 m = s["memory"]
318 self.assertEqual(m["private_mb_per_min_in_world"], 120.0)
319 self.assertEqual((m["reaper_queue_max"], m["reaper_queue_max_at_s"]), (100 * 63, 385.0))
320 self.assertEqual(m["waiting_objects_max"], 3)
321 self.assertEqual(m["series"], "memory.csv")
322 # `summary` writes the series beside summary.json, one row per memory line, numbers only.
323 with contextlib.redirect_stdout(io.StringIO()):
324 game_gate.main(["game_gate.py", "summary", f.dir])
325 with open(os.path.join(f.dir, "memory.csv"), encoding="utf-8") as fh:
326 rows = list(csv.DictReader(fh))
327 self.assertEqual(len(rows), 76)
328 self.assertEqual(tuple(rows[0]), game_gate.SERIES_COLUMNS)
329 self.assertEqual(rows[-1]["private_mb"], "20630")
330 self.assertEqual(rows[-1]["reaper_queue"], "6300")
331 self.assertEqual(rows[-1]["vram_in_use_mb"], "7000")
332 # The same bytes on every machine: LF line ends, never CRLF.
333 with open(os.path.join(f.dir, "memory.csv"), "rb") as fh:
334 self.assertNotIn(b"\r", fh.read())
335
336 def summary_files(self, f):
337 """`game_gate.py summary` on the folder: (exit code, summary.json, memory.csv rows or None, stderr)."""
338 f.summarize()
339 err = io.StringIO()
340 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
341 code = game_gate.main(["game_gate.py", "summary", f.dir])
342 with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh:
343 s = json.load(fh)
344 path = os.path.join(f.dir, "memory.csv")
345 rows = None
346 if os.path.isfile(path):
347 with open(path, encoding="utf-8") as fh:
348 rows = list(csv.DictReader(fh))
349 return code, s, rows, err.getvalue()
350
351 def test_the_series_takes_the_lines_within_2_s_of_each_memory_line(self):
352 f = passing()
353 f.memory(100, 20000, 7000, waiting=3, reaper=40) # the three lines at once, as the runtime writes them
354 f.memory(200, 21000, 7500, waiting=5, reaper=50)
355 census, video, memory = f.log[-3:]
356 # The video memory line 2 s before (taken), the census line 2.5 s after (too far: empty cells).
357 f.log[-3:] = [census.replace(stamp(200), stamp(202.5)), video.replace(stamp(200), stamp(198)), memory]
358 f.memory(300, 22000, 8000)
359 f.log[-3:] = f.log[-1:] # a memory line alone
360 _, _, rows, _ = self.summary_files(f)
361 got = [(r["t_s"], r["vram_in_use_mb"], r["shared_in_use_mb"], r["waiting_objects"], r["reaper_queue"])
362 for r in rows]
363 self.assertEqual(got, [("100.0", "7000", "500", "3", "40"), ("200.0", "7500", "500", "", ""),
364 ("300.0", "", "", "", "")])
365
366 def test_the_slope_counts_the_world_up_to_the_stop(self):
367 f = Fake()
368 f.event(1, "game", pid=1)
369 f.frames(10, 70, 60.0, 13)
370 f.frames(70, 420, 50.0, 4000)
371 for t in range(70, 420, 5):
372 # 120 MB a minute in the world, then a jump while the title ends after the stop request (390 s).
373 f.memory(t, 20000 + 2 * (t - 70) if t <= 390 else 40000, 7000)
374 f.event(390, "stop_requested", reason="target")
375 f.event(420, "game_exited", exit_code=0)
376 self.assertEqual(f.summarize()["memory"]["private_mb_per_min_in_world"], 120.0)
377 # Fewer than 3 memory lines in the world: no slope.
378 f = passing()
379 for t in (40, 50, 60, 100, 200):
380 f.memory(t, 20000 + t, 7000)
381 self.assertIsNone(f.summarize()["memory"]["private_mb_per_min_in_world"])
382
383 def test_a_series_it_cannot_write_still_leaves_the_summary(self):
384 # memory.csv held by another program: the summary is written all the same, with no series named.
385 f = passing()
386 for t in range(70, 390, 5):
387 f.memory(t, 20000, 7000)
388 os.makedirs(os.path.join(f.dir, "memory.csv")) # opening it to write fails, as a locked file does
389 code, s, _, err = self.summary_files(f)
390 self.assertEqual(code, 0)
391 self.assertEqual(s["verdict"]["result"], "PASS")
392 self.assertIsNone(s["memory"]["series"])
393 self.assertEqual(s["memory"]["lines"], 64)
394 self.assertIn("memory.csv not written or removed", err)
395
238 def test_a_build_without_memory_lines_gives_no_memory_peaks(self): 396 def test_a_build_without_memory_lines_gives_no_memory_peaks(self):
239 m = passing().summarize()["memory"] 397 f = passing()
398 m = f.summarize()["memory"]
240 self.assertIsNone(m["source"]) 399 self.assertIsNone(m["source"])
241 self.assertEqual(m["lines"], 0) 400 self.assertEqual(m["lines"], 0)
242 self.assertIsNone(m["private_max_mb"]) 401 self.assertIsNone(m["private_max_mb"])
243 self.assertIsNone(m["vram_in_use_max_mb"]) 402 self.assertIsNone(m["vram_in_use_max_mb"])
403 self.assertIsNone(m["series"])
404 self.assertIsNone(m["reaper_queue_max"])
405 self.assertIsNone(m["private_mb_per_min_in_world"])
406 # And `summary` writes no series file: not even a header alone.
407 with contextlib.redirect_stdout(io.StringIO()):
408 game_gate.main(["game_gate.py", "summary", f.dir])
409 self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv")))
410
411 def test_a_folder_summarized_again_without_memory_lines_keeps_no_old_series(self):
412 # A memory.csv from an earlier summary, and a log that has no memory lines now: the old rows must not sit
413 # beside `series: null`.
414 f = passing()
415 f.summarize()
416 with open(os.path.join(f.dir, "memory.csv"), "w", encoding="utf-8", newline="\n") as fh:
417 fh.write(",".join(game_gate.SERIES_COLUMNS) + "\n70.0,1000,500,15000,4000,8000,7000,500,0,0\n")
418 with contextlib.redirect_stdout(io.StringIO()):
419 game_gate.main(["game_gate.py", "summary", f.dir])
420 with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh:
421 self.assertIsNone(json.load(fh)["memory"]["series"])
422 self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv")))
244 423
245 def test_without_present_lines_the_frame_lines_give_the_rate(self): 424 def test_without_present_lines_the_frame_lines_give_the_rate(self):
246 f = Fake() 425 f = Fake()
@@ -317,6 +496,67 @@ class Script(unittest.TestCase):
317 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: 496 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
318 self.assertEqual(f.readline().strip(), "#Requires -Version 7.0") 497 self.assertEqual(f.readline().strip(), "#Requires -Version 7.0")
319 498
499 def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self):
500 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
501 text = f.read()
502 for name in ("StopPrivateMB", "StopCommitLeftMB", "StopOverBudgetSeconds"):
503 self.assertIn(f"[int]${name} = ", text)
504 # `start` rebuilds the command line of the detached `run`: a limit left out would be lost there.
505 self.assertIn(f"'-{name}'; ${name}", text)
506 self.assertIn("memory_stop = [ordered]@{", text)
507 # The private default follows the PC's memory too, not only its commit limit (a large page file).
508 self.assertIn("TotalPhysicalMemory", text)
509 self.assertIn("[math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25)", text)
510
511 # What one poll of the supervisor reads (`game_gate.py state`, a STOP file, the minutes since the start) and the
512 # reason it stops the run for, with -WorldSeconds 300 and -MaxMinutes 45.
513 POLLS = [
514 # The world time reached in the same poll as a memory limit: a measurement, not a memory stop.
515 ({"relaunched": False, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
516 "target"),
517 ({"relaunched": False, "world_s": 295.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
518 "memory"),
519 ({"relaunched": True, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
520 "relaunched"),
521 ({"relaunched": False, "world_s": 100.0, "memory_stop": "video memory over its budget for 60 s"}, True, 20,
522 "memory"),
523 ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, True, 20, "stop_file"),
524 # A memory limit at the time limit: the memory stop names the real reason.
525 ({"relaunched": False, "world_s": 100.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 45,
526 "memory"),
527 ({"relaunched": False, "world_s": 0.0, "memory_stop": None}, False, 45, "timeout"),
528 ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, False, 20, "none"),
529 ]
530
531 def test_a_poll_stops_for_the_target_before_the_memory_stop(self):
532 # The supervisor's own function is taken out of the script and put to PowerShell 7 with each poll above.
533 with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
534 text = f.read()
535 self.assertIn("$stopReason = Get-StopReason -Poll $state ", text)
536 self.assertIn("-TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes", text)
537 self.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function
538 # The memory stop's sentence goes into the stop_requested event (`stop.memory_why`).
539 self.assertIn("if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }", text)
540 pwsh = shutil.which("pwsh")
541 if not pwsh:
542 self.skipTest("no PowerShell 7 here")
543 script = ("$ErrorActionPreference = 'Stop'; "
544 "$language = 'System.Management.Automation.Language'; "
545 "$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); "
546 "$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and "
547 "$args[0].Name -eq 'Get-StopReason' }, $true); "
548 "if (-not $fn) { throw 'the gate has no Get-StopReason' }; "
549 ". ([scriptblock]::Create($fn.Extent.Text)); "
550 "foreach ($p in ($env:GATE_POLLS | ConvertFrom-Json)) "
551 "{ $r = Get-StopReason -Poll $p[0] -StopFile $p[1] -Minutes $p[2] -TargetSeconds 300 "
552 "-LimitMinutes 45; if ($r) { $r } else { 'none' } }")
553 env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"),
554 GATE_POLLS=json.dumps([p[:3] for p in self.POLLS]))
555 done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True,
556 text=True, timeout=120, env=env)
557 self.assertEqual(done.returncode, 0, done.stderr)
558 self.assertEqual(done.stdout.split(), [p[3] for p in self.POLLS])
559
320 def test_no_variable_takes_a_parameters_name_in_another_case(self): 560 def test_no_variable_takes_a_parameters_name_in_another_case(self):
321 # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name, 561 # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name,
322 # and the stop could not wait for it. 562 # and the stop could not wait for it.
diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py
index 4c0cb1228..f9312dc1d 100644
--- a/tests/test_pe_inspect.py
+++ b/tests/test_pe_inspect.py
@@ -1383,5 +1383,351 @@ class HostClassesTest(unittest.TestCase):
1383 self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset()) 1383 self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset())
1384 1384
1385 1385
1386class TestExportForwarders(unittest.TestCase):
1387 def inspect_buf(self, buf: bytes) -> dict:
1388 return pe_inspect._inspect_exports(pe_inspect.PeImage(buf))
1389
1390 def test_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarder(self):
1391 """The directory is [begin, end): an RVA equal to the end is past it, as in runtime/src/pe_loader.cpp."""
1392 end = 0x1800 # the export directory of with_exports() is [0x1700, 0x1800)
1393 data = with_exports([end], {0: "AtTheEnd"}, base=1)
1394 exp = self.inspect_buf(data)
1395 self.assertEqual(exp["forwarders"], {})
1396 self.assertEqual(exp["exports"], ["AtTheEnd"])
1397 last = with_exports([end - 1], {0: "LastByte"}, base=1)
1398 self.assertIn("LastByte", self.inspect_buf(last)["forwarders"])
1399
1400 def test_case1_normal_exports_and_unused_slots(self):
1401 """Case 1: Normal code exports + unused zero-RVA slot skipped (forwarders empty, invalid_export_count 0)."""
1402 data = with_exports([0x1000, 0, 0x1010], {0: "Alpha", 2: "Beta"}, base=1)
1403 exp = self.inspect_buf(data)
1404 self.assertEqual(exp["exports"], ["Alpha", "Beta"])
1405 self.assertEqual(exp["forwarders"], {})
1406 self.assertEqual(exp["invalid_export_count"], 0)
1407 self.assertEqual(exp["invalid_exports"], [])
1408
1409 def test_case2_named_forwarded_export(self):
1410 """Case 2: Named forwarded export (RVA inside export directory [0x1700, 0x1800))."""
1411 data = with_exports([0x1000, FORWARDER], {0: "NormalFunc", 1: "Sleep"}, base=10)
1412 exp = self.inspect_buf(data)
1413 self.assertEqual(exp["exports"], ["NormalFunc", "Sleep"])
1414 self.assertEqual(exp["forwarders"], {"Sleep": "other.Target"})
1415 self.assertEqual(exp["invalid_export_count"], 0)
1416
1417 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1418 f.write(data)
1419 f.flush()
1420 tmp_path = f.name
1421 try:
1422 report = pe_inspect.inspect(tmp_path, None)
1423 md = pe_inspect.to_markdown(report)
1424 self.assertIn("(1 forwarded)", md)
1425 self.assertIn("## Forwarded Exports", md)
1426 self.assertIn("| `Sleep` | `other.Target` |", md)
1427 finally:
1428 os.unlink(tmp_path)
1429
1430 def test_case3_ordinal_only_forwarder(self):
1431 """Case 3: Ordinal-only forwarded export (index not in named)."""
1432 data = with_exports([0x1000, FORWARDER], {0: "Func"}, base=10)
1433 exp = self.inspect_buf(data)
1434 self.assertEqual(exp["exports"], ["Func", "#11"])
1435 self.assertEqual(exp["forwarders"], {"#11": "other.Target"})
1436 self.assertEqual(exp["invalid_export_count"], 0)
1437
1438 def test_case4_aliased_named_forwarders(self):
1439 """Case 4: Two export names mapping to the same forwarded EAT index."""
1440 data = with_exports([FORWARDER], {0: "AliasA"}, base=1)
1441 buf = bytearray(data)
1442 place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 2,
1443 EXPORT_FUNCS, 0x1C00, 0x1C80))
1444 place(buf, 0x1C00, struct.pack("<II", 0x1D00, 0x1D10))
1445 place(buf, 0x1C80, struct.pack("<HH", 0, 0))
1446 place(buf, 0x1D00, b"AliasA\0")
1447 place(buf, 0x1D10, b"AliasB\0")
1448 exp = self.inspect_buf(bytes(buf))
1449 self.assertEqual(exp["exports"], ["AliasA", "AliasB"])
1450 self.assertEqual(exp["forwarders"], {"AliasA": "other.Target", "AliasB": "other.Target"})
1451 self.assertEqual(exp["invalid_export_count"], 0)
1452
1453 def test_case5_out_of_bounds_export_rva(self):
1454 """Case 5: Out-of-bounds export RVA (>= size_of_image)."""
1455 data = with_exports([0x3000], {0: "BadFunc"}, base=10)
1456 exp = self.inspect_buf(data)
1457 self.assertEqual(exp["exports"], ["BadFunc"])
1458 self.assertEqual(exp["invalid_export_count"], 1)
1459 self.assertEqual(len(exp["invalid_exports"]), 1)
1460 self.assertEqual(exp["invalid_exports"][0]["symbol"], "BadFunc")
1461 self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_bounds")
1462
1463 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1464 f.write(data)
1465 f.flush()
1466 tmp_path = f.name
1467 try:
1468 report = pe_inspect.inspect(tmp_path, None)
1469 md = pe_inspect.to_markdown(report)
1470 self.assertIn("INVALID: 1 invalid: BadFunc (out_of_bounds)", md)
1471 finally:
1472 os.unlink(tmp_path)
1473
1474 def test_case6_unreadable_forwarder_and_error_cap(self):
1475 """Case 6: Unreadable forwarder string and invalid error cap at <= 5."""
1476 buf = bytearray(build_image())
1477 dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8
1478 struct.pack_into("<II", buf, dir_entry, 0x1700, 0x2000)
1479 place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 1,
1480 EXPORT_FUNCS, 0x1C00, 0x1C80))
1481 place(buf, EXPORT_FUNCS, struct.pack("<I", 0x3500))
1482 place(buf, 0x1C00, struct.pack("<I", 0x1D00))
1483 place(buf, 0x1C80, struct.pack("<H", 0))
1484 place(buf, 0x1D00, b"BrokenFwd\0")
1485 exp = self.inspect_buf(bytes(buf))
1486 self.assertEqual(exp["forwarders"], {"BrokenFwd": "?"})
1487 self.assertEqual(exp["invalid_export_count"], 1)
1488 self.assertEqual(exp["invalid_exports"][0]["reason"], "unreadable_forwarder")
1489
1490 bad_slots = [0x4000 + i * 0x100 for i in range(8)]
1491 bad_names = {i: f"Bad{i}" for i in range(8)}
1492 data_bad = with_exports(bad_slots, bad_names, base=1)
1493 exp_bad = self.inspect_buf(data_bad)
1494 self.assertEqual(exp_bad["invalid_export_count"], 8)
1495 self.assertEqual(len(exp_bad["invalid_exports"]), 5)
1496
1497 def test_case7_combined_forwarder_and_invalid_summary(self):
1498 """Case 7: DLL with both valid forwarder and invalid export displays both in markdown."""
1499 data = with_exports([0x1000, FORWARDER, 0x3000], {1: "Fwd|Func", 2: "BadFunc"}, base=10)
1500 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1501 f.write(data)
1502 f.flush()
1503 tmp_path = f.name
1504 try:
1505 report = pe_inspect.inspect(tmp_path, None)
1506 md = pe_inspect.to_markdown(report)
1507 self.assertIn("(1 forwarded; INVALID: 1 invalid: BadFunc (out_of_bounds))", md)
1508 self.assertIn("| `Fwd\\|Func` | `other.Target` |", md)
1509 finally:
1510 os.unlink(tmp_path)
1511
1512 def test_case8_out_of_range_ordinal_and_small_dir_size(self):
1513 """Case 8: Ordinal index >= functions recorded as invalid, dir_size < 40 returns empty."""
1514 data = with_exports([0x1000], {0: "NormalFunc"}, base=1)
1515 buf = bytearray(data)
1516 # Point the ordinal table to index 5 while NumberOfFunctions is 1
1517 place(buf, 0x1C80, struct.pack("<H", 5))
1518 exp = self.inspect_buf(bytes(buf))
1519 self.assertNotIn("NormalFunc", exp["exports"])
1520 self.assertEqual(exp["exports"], ["#1"])
1521 self.assertEqual(exp["forwarders"], {})
1522 self.assertEqual(exp["invalid_export_count"], 1)
1523 self.assertEqual(len(exp["invalid_exports"]), 1)
1524 self.assertEqual(exp["invalid_exports"][0]["symbol"], "NormalFunc")
1525 self.assertEqual(exp["invalid_exports"][0]["ordinal"], 6)
1526 self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_range_ordinal")
1527
1528 # When slot is 0, exports is empty, but out-of-range ordinal is still recorded
1529 data_zero = with_exports([0], {0: "NormalFunc"}, base=1)
1530 buf_zero = bytearray(data_zero)
1531 place(buf_zero, 0x1C80, struct.pack("<H", 5))
1532 exp_zero = self.inspect_buf(bytes(buf_zero))
1533 self.assertEqual(exp_zero["exports"], [])
1534 self.assertEqual(exp_zero["invalid_export_count"], 1)
1535
1536 # dir_size < 40 returns empty dict
1537 dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8
1538 struct.pack_into("<II", buf, dir_entry, 0x1700, 39)
1539 exp_small = self.inspect_buf(bytes(buf))
1540 self.assertEqual(exp_small["exports"], [])
1541 self.assertEqual(exp_small["forwarders"], {})
1542 self.assertEqual(exp_small["invalid_export_count"], 0)
1543
1544 def test_case9_out_of_range_ordinal_markdown_report(self):
1545 """Case 9: Markdown report includes out_of_range_ordinal invalid export."""
1546 data = with_exports([0x1000], {0: "NormalFunc"}, base=1)
1547 buf = bytearray(data)
1548 place(buf, 0x1C80, struct.pack("<H", 5))
1549 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1550 f.write(buf)
1551 f.flush()
1552 tmp_path = f.name
1553 try:
1554 report = pe_inspect.inspect(tmp_path, None)
1555 md = pe_inspect.to_markdown(report)
1556 self.assertIn("INVALID: 1 invalid: NormalFunc (out_of_range_ordinal)", md)
1557 finally:
1558 os.unlink(tmp_path)
1559
1560 def test_case10_malformed_forwarder_targets(self):
1561 """Case 10: Malformed forwarder target strings recorded as malformed_forwarder."""
1562 bad_targets = [
1563 b"nodot\0",
1564 b".leadingdot\0",
1565 b"trailingdot.\0",
1566 b"other.#\0",
1567 b"other.#notanumber\0",
1568 b"other.#0\0",
1569 b"other.#70000\0",
1570 b"bad\x01target.Func\0",
1571 ]
1572 for target_bytes in bad_targets:
1573 with self.subTest(target=target_bytes):
1574 data = bytearray(with_exports([FORWARDER], {0: "TestFunc"}, base=1))
1575 place(data, FORWARDER, target_bytes)
1576 exp = self.inspect_buf(bytes(data))
1577 self.assertEqual(exp["invalid_export_count"], 1)
1578 self.assertEqual(exp["invalid_exports"][0]["symbol"], "TestFunc")
1579 self.assertEqual(exp["invalid_exports"][0]["reason"], "malformed_forwarder")
1580
1581 def test_case11_intra_module_forwarder_self_loop(self):
1582 """Case 11: Forwarder targeting itself in the same module is recorded as forwarder_loop."""
1583 # sample.dll exporting Sleep -> sample.Sleep or sample.dll.Sleep
1584 for target in (b"sample.Sleep\0", b"sample.dll.Sleep\0"):
1585 with self.subTest(target=target):
1586 data = bytearray(with_exports([FORWARDER], {0: "Sleep"}, base=1))
1587 place(data, FORWARDER, target)
1588 exp = self.inspect_buf(bytes(data))
1589 self.assertEqual(exp["invalid_export_count"], 1)
1590 self.assertEqual(exp["invalid_exports"][0]["symbol"], "Sleep")
1591 self.assertEqual(exp["invalid_exports"][0]["reason"], "forwarder_loop")
1592
1593 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1594 f.write(data)
1595 f.flush()
1596 tmp_path = f.name
1597 try:
1598 report = pe_inspect.inspect(tmp_path, None)
1599 md = pe_inspect.to_markdown(report)
1600 self.assertIn("INVALID: 1 invalid: Sleep (forwarder_loop)", md)
1601 finally:
1602 os.unlink(tmp_path)
1603
1604 def test_case12_intra_module_forwarder_cyclic_loop(self):
1605 """Case 12: Mutual/cyclic intra-module forwarders (Alpha -> Beta, Beta -> Alpha)."""
1606 fwd_a = 0x1790
1607 fwd_b = 0x17B0
1608 data = bytearray(with_exports([fwd_a, fwd_b], {0: "Alpha", 1: "Beta"}, base=1))
1609 place(data, fwd_a, b"sample.Beta\0")
1610 place(data, fwd_b, b"sample.Alpha\0")
1611 exp = self.inspect_buf(bytes(data))
1612 self.assertEqual(exp["invalid_export_count"], 2)
1613 symbols = {inv["symbol"] for inv in exp["invalid_exports"]}
1614 self.assertEqual(symbols, {"Alpha", "Beta"})
1615 for inv in exp["invalid_exports"]:
1616 self.assertEqual(inv["reason"], "forwarder_loop")
1617
1618 def test_case13_intra_module_forwarder_depth_limit(self):
1619 """Case 13: Forwarder chain >= 8 within the same module is detected as a loop."""
1620 # Chain F0 -> F1 -> ... -> F8
1621 slots = []
1622 names = {}
1623 base_addr = 0x1790
1624 for k in range(9):
1625 addr = base_addr + k * 11
1626 slots.append(addr)
1627 names[k] = f"F{k}"
1628 data = bytearray(with_exports(slots, names, base=1))
1629 for k in range(8):
1630 addr = base_addr + k * 11
1631 place(data, addr, f"sample.F{k+1}\0".encode())
1632 # The 9th points to an external module (valid in isolation)
1633 place(data, base_addr + 8 * 11, b"kernel32.Sleep\0")
1634
1635 exp = self.inspect_buf(bytes(data))
1636 # F0's chain length reaches 8, so F0 triggers forwarder_loop
1637 f0_inv = [inv for inv in exp["invalid_exports"] if inv["symbol"] == "F0"]
1638 self.assertEqual(len(f0_inv), 1)
1639 self.assertEqual(f0_inv[0]["reason"], "forwarder_loop")
1640
1641 def test_case14_pe_header_edge_cases(self):
1642 """Case 14: e_lfanew overlapping DOS header, SizeOfImage 0, SizeOfHeaders > SizeOfImage."""
1643 base_data = build_image()
1644
1645 # e_lfanew < 0x40
1646 data_short_nt = bytearray(base_data)
1647 struct.pack_into("<I", data_short_nt, 0x3C, 0x20)
1648 with self.assertRaisesRegex(pe_inspect.PeFormatError, "overlaps the 64-byte MS-DOS header"):
1649 pe_inspect.PeImage(bytes(data_short_nt))
1650
1651 # SizeOfImage == 0
1652 data_zero_img = bytearray(base_data)
1653 struct.pack_into("<I", data_zero_img, 0x58 + 56, 0)
1654 with self.assertRaisesRegex(pe_inspect.PeFormatError, "invalid SizeOfImage 0"):
1655 pe_inspect.PeImage(bytes(data_zero_img))
1656
1657 # SizeOfHeaders > SizeOfImage
1658 data_hdr_overflow = bytearray(base_data)
1659 struct.pack_into("<I", data_hdr_overflow, 0x58 + 60, 0x4000)
1660 with self.assertRaisesRegex(pe_inspect.PeFormatError, "exceeds SizeOfImage"):
1661 pe_inspect.PeImage(bytes(data_hdr_overflow))
1662
1663
1664class TestExceptionDirectoryArchitectureValidation(unittest.TestCase):
1665 """Clean-room unit tests ensuring non-x64 machine architectures (e.g. i386, ARM64)
1666 gracefully reject 12-byte RUNTIME_FUNCTION parsing with informative diagnostics."""
1667
1668 def test_x86_machine_exception_directory_rejected_as_non_x64(self):
1669 # 32-bit x86 image (IMAGE_FILE_MACHINE_I386 = 0x14C)
1670 data = build_image(is64=False, with_directories=True)
1671 img = pe_inspect.PeImage(data)
1672 pdata = pe_inspect._inspect_pdata(img)
1673 self.assertTrue(pdata["present"])
1674 self.assertEqual(pdata["format"], "non-x64")
1675 self.assertEqual(pdata["parsed_count"], 0)
1676 self.assertIn("x86", pdata["rejection_reason"])
1677 self.assertIn("stack-based SEH", pdata["rejection_reason"])
1678
1679 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1680 f.write(data)
1681 f.flush()
1682 tmp_path = f.name
1683 try:
1684 report = pe_inspect.inspect(tmp_path, None)
1685 md = pe_inspect.to_markdown(report)
1686 self.assertIn("(non-x64)", md)
1687 self.assertNotIn("(OK)", md)
1688 finally:
1689 os.unlink(tmp_path)
1690
1691 def test_arm64_machine_exception_directory_rejected_as_arm64(self):
1692 # ARM64 image (IMAGE_FILE_MACHINE_ARM64 = 0xAA64)
1693 buf = bytearray(build_image(is64=True, with_directories=True))
1694 # Change machine to ARM64 (0xAA64) at FileHeader + 0 (0x44)
1695 struct.pack_into("<H", buf, 0x44, 0xAA64)
1696 # Give 32 bytes of pdata (4 entries of 8-byte ARM64 records)
1697 dir_entry = 0x58 + 112 + pe_inspect.DIR_EXCEPTION * 8
1698 struct.pack_into("<II", buf, dir_entry, 0x1800, 32)
1699 img = pe_inspect.PeImage(bytes(buf))
1700 pdata = pe_inspect._inspect_pdata(img)
1701 self.assertTrue(pdata["present"])
1702 self.assertEqual(pdata["format"], "arm64")
1703 self.assertEqual(pdata["entry_count"], 4) # 32 // 8
1704 self.assertEqual(pdata["parsed_count"], 0)
1705 self.assertIn("ARM64", pdata["rejection_reason"])
1706 self.assertIn("8-byte", pdata["rejection_reason"])
1707
1708 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1709 f.write(buf)
1710 f.flush()
1711 tmp_path = f.name
1712 try:
1713 report = pe_inspect.inspect(tmp_path, None)
1714 md = pe_inspect.to_markdown(report)
1715 self.assertIn("(arm64)", md)
1716 self.assertNotIn("(OK)", md)
1717 finally:
1718 os.unlink(tmp_path)
1719
1720 def test_unknown_architecture_exception_directory_rejected(self):
1721 # ARM Thumb-2 (0x1C4)
1722 buf = bytearray(build_image(is64=False, with_directories=True))
1723 struct.pack_into("<H", buf, 0x44, 0x01C4)
1724 img = pe_inspect.PeImage(bytes(buf))
1725 pdata = pe_inspect._inspect_pdata(img)
1726 self.assertTrue(pdata["present"])
1727 self.assertIn("unsupported", pdata["format"])
1728 self.assertEqual(pdata["parsed_count"], 0)
1729 self.assertIn("unsupported machine", pdata["rejection_reason"])
1730
1731
1386if __name__ == "__main__": 1732if __name__ == "__main__":
1387 unittest.main() 1733 unittest.main()
diff --git a/tests/test_red_green.py b/tests/test_red_green.py
index 5f4b89529..85ccae0ee 100644
--- a/tests/test_red_green.py
+++ b/tests/test_red_green.py
@@ -2,11 +2,15 @@
2import io 2import io
3import json 3import json
4import os 4import os
5import py_compile
5import subprocess 6import subprocess
6import sys 7import sys
7import tempfile 8import tempfile
9import time
8import unittest 10import unittest
9from contextlib import redirect_stderr, redirect_stdout 11from contextlib import redirect_stderr, redirect_stdout
12from pathlib import Path
13from unittest import mock
10 14
11ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 15ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
12sys.path.insert(0, os.path.join(ROOT, "scripts")) 16sys.path.insert(0, os.path.join(ROOT, "scripts"))
@@ -66,6 +70,18 @@ runpy.run_path(os.path.join(here, "cargo_stub.py"), run_name="__main__")
66''' 70'''
67 71
68 72
73def hang_stub(repo, where):
74 """STUB_CARGO that sleeps when value() is 2 and spare() is 5 (Mutation.BASE's second hunk undone alone): before
75 its `Running` line, as a build that hangs, or after it, as a test that hangs."""
76 hang = "sys.stdout.flush()\nif fns.get('value') == '2' and fns.get('spare') == '5':\n __import__('time').sleep(120)\n"
77 text = STUB_CARGO.replace('print(" Running', (hang if where == "build" else "") + 'print(" Running')
78 text = text.replace("failed = False\n", "failed = False\n" + (hang if where == "test" else ""))
79 path = os.path.join(repo.tmp.name, f"cargo_hang_{where}.py")
80 with open(path, "w", encoding="utf-8", newline="\n") as f:
81 f.write(text)
82 return path
83
84
69class Repo: 85class Repo:
70 def crash_stub(self, mode): 86 def crash_stub(self, mode):
71 path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py") 87 path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py")
@@ -235,6 +251,372 @@ class Python(unittest.TestCase):
235 self.assertIn("does not import", r["red"]["no_build"][0]) 251 self.assertIn("does not import", r["red"]["no_build"][0])
236 self.assertEqual(code, 1) 252 self.assertEqual(code, 1)
237 253
254 # The same test, and once more in a process it starts, as the tests of a command-line tool do.
255 CHILD_TEST = TEST + (
256 "\n def test_two_in_a_child(self):\n"
257 " import subprocess\n"
258 " tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n"
259 " code = 'import sys; sys.path.insert(0, sys.argv[1]); import bar; print(bar.two())'\n"
260 " out = subprocess.run([sys.executable, '-I', '-c', code, tools], capture_output=True, text=True)\n"
261 " self.assertEqual(out.stdout.strip(), '2')\n")
262
263 def test_stale_bytecode_in_the_work_tree_is_never_run(self):
264 repo = Repo(self)
265 repo.commit("base", {".gitignore": "__pycache__/\n", "tools/bar.py": "def two():\n return 1\n"})
266 repo.git("switch", "-q", "-c", "pr")
267 repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.CHILD_TEST})
268 self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green")
269 # An ignored .pyc of the fixed bar.py left in the work tree (`git clean` keeps ignored files). An unchecked-hash
270 # .pyc is taken without looking at the source, like a timestamp one whose time and size still match.
271 tools = os.path.join(repo.dir, ".git", "red-green", "tree", "tools")
272 src = os.path.join(repo.tmp.name, "bar_fixed.py")
273 with open(src, "w", encoding="utf-8", newline="\n") as f:
274 f.write("def two():\n return 2\n")
275 py_compile.compile(src, cfile=os.path.join(tools, "__pycache__", f"bar.{sys.implementation.cache_tag}.pyc"),
276 doraise=True, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH)
277 code, r, _ = repo.run("--no-cargo", "--mutate")
278 # Read, it would make red pass in both processes and the undone fix not caught.
279 self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
280 self.assertEqual(r["rows"]["red_to_green"], ["tests/test_bar.py::test_bar.T.test_two",
281 "tests/test_bar.py::test_bar.T.test_two_in_a_child"])
282 self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")])
283
284 def test_bytecode_it_cannot_remove_stops_the_run_with_the_tree_put_back(self):
285 repo = Repo(self)
286 repo.commit("base", {".gitignore": "__pycache__/\n", "tools/bar.py": "def two():\n return 1\n"})
287 repo.git("switch", "-q", "-c", "pr")
288 repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.TEST})
289 self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green")
290 tree = os.path.join(repo.dir, ".git", "red-green", "tree")
291 cache = os.path.join(tree, "tools", "__pycache__")
292 os.makedirs(cache, exist_ok=True)
293 block_removal(self, cache)
294 code, r, err = repo.run("--no-cargo")
295 self.assertEqual((code, r), (2, None), err)
296 self.assertIn("cannot remove", err)
297 self.assertIn(os.path.join("tools", "__pycache__"), err)
298 # The red side had begun: the tree is back on the base all the same.
299 status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout
300 self.assertEqual(status, "")
301
302
303def link_dir(test, link, target):
304 """A directory junction on Windows (no privilege needed), a symbolic link elsewhere; removed at the end of `test`
305 before its temporary folder, so that the folder's cleanup does not go through it."""
306 if os.name == "nt":
307 subprocess.run(["cmd", "/c", "mklink", "/J", link, target], check=True, capture_output=True)
308 test.addCleanup(os.rmdir, link)
309 else:
310 os.symlink(target, link, target_is_directory=True)
311 test.addCleanup(os.unlink, link)
312
313
314def deny_listing(test, folder):
315 """Takes away the right to list `folder` (a deny entry for Everyone on Windows, mode 0 elsewhere) until the end of
316 `test`."""
317 if os.name == "nt":
318 subprocess.run(["icacls", folder, "/deny", "*S-1-1-0:(RD)"], check=True, capture_output=True)
319 test.addCleanup(subprocess.run, ["icacls", folder, "/remove:d", "*S-1-1-0"], check=True, capture_output=True)
320 else:
321 if os.geteuid() == 0:
322 test.skipTest("root lists any folder")
323 os.chmod(folder, 0)
324 test.addCleanup(os.chmod, folder, 0o700)
325
326
327def block_removal(test, folder):
328 """Keeps `folder` from being removed until the end of `test`: a file in it held open on Windows, the folder
329 read-only elsewhere."""
330 path = os.path.join(folder, "held.pyc")
331 if os.name == "nt":
332 held = open(path, "wb")
333 test.addCleanup(held.close)
334 else:
335 if os.geteuid() == 0:
336 test.skipTest("root removes any file")
337 open(path, "wb").close()
338 os.chmod(folder, 0o500)
339 test.addCleanup(os.chmod, folder, 0o700)
340
341
342class DropBytecode(unittest.TestCase):
343 def setUp(self):
344 tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True)
345 self.addCleanup(tmp.cleanup)
346 self.tree, self.outside = os.path.join(tmp.name, "tree"), os.path.join(tmp.name, "outside")
347 for folder in (os.path.join(self.tree, "tools", "__pycache__"), os.path.join(self.outside, "__pycache__")):
348 os.makedirs(folder)
349 with open(os.path.join(folder, "x.pyc"), "wb") as f:
350 f.write(b"x")
351
352 def check(self):
353 rg.drop_bytecode(Path(self.tree))
354 self.assertFalse(os.path.exists(os.path.join(self.tree, "tools", "__pycache__")))
355 self.assertTrue(os.path.isfile(os.path.join(self.outside, "__pycache__", "x.pyc")))
356
357 def test_a_link_out_of_the_tree_is_not_followed(self):
358 link_dir(self, os.path.join(self.tree, "tools", "link"), self.outside)
359 self.check()
360
361 def test_a_link_named_pycache_is_left_alone(self):
362 link_dir(self, os.path.join(self.tree, "__pycache__"), os.path.join(self.outside, "__pycache__"))
363 self.check()
364
365 def test_a_folder_it_cannot_list_is_skipped(self):
366 locked = os.path.join(self.tree, "locked")
367 os.makedirs(os.path.join(locked, "__pycache__"))
368 deny_listing(self, locked)
369 self.check()
370
371
372@unittest.skipUnless(os.name == "nt", "job objects are Windows'")
373class Job(unittest.TestCase):
374 def test_a_job_object_that_cannot_be_joined_is_said_once(self):
375 err = io.StringIO()
376 with mock.patch.object(rg._KERNEL32, "AssignProcessToJobObject", return_value=0), \
377 mock.patch.object(rg, "_JOB_WARNED", False, create=True), redirect_stderr(err):
378 runs = [rg.run_output([sys.executable, "-c", "print(1)"], Path(ROOT), timeout=60) for _ in range(2)]
379 self.assertEqual([(code, out.strip()) for code, out in runs], [(0, "1"), (0, "1")])
380 self.assertEqual(err.getvalue().count("no Windows job object"), 1, err.getvalue())
381
382
383class Mutation(unittest.TestCase):
384 # Two code changes far enough apart to be two hunks: the tested one and one no test looks at.
385 BASE = ("pub fn value() -> u32 {\n 1\n}\n\n" + "".join(f"// padding line {i}\n" for i in range(10))
386 + "\npub fn spare() -> u32 {\n 5\n}\n" + LIB[LIB.index("\n#[cfg(test)]"):])
387
388 def test_each_code_hunk_undone_alone_is_caught_or_not(self):
389 repo = Repo(self)
390 repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
391 "d3d12/crates/foo/src/lib.rs": self.BASE})
392 repo.git("switch", "-q", "-c", "pr")
393 repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace(
394 " 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);",
395 "fn value_is_two() {\n assert_eq!(super::value(), 2);")})
396 code, r, _ = repo.run("--mutate")
397 self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
398 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "not caught")])
399 text = rg.report(r)
400 self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 not caught", text)
401 self.assertIn("d3d12/crates/foo/src/lib.rs:17: not caught", text)
402 # The worktree is back on the base afterwards: the mutations left nothing behind.
403 tree = os.path.join(repo.dir, ".git", "red-green", "tree")
404 status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout
405 self.assertEqual(status, "")
406
407 def test_a_cargo_run_that_hangs_is_stopped_and_said_where(self):
408 repo = Repo(self)
409 repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
410 "d3d12/crates/foo/src/lib.rs": self.BASE})
411 repo.git("switch", "-q", "-c", "pr")
412 repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace(
413 " 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);",
414 "fn value_is_two() {\n assert_eq!(super::value(), 2);")})
415 # A test binary that hangs is caught; a build that hangs (no `Running` line yet) is no answer.
416 for where, result in (("test", "caught by timeout"), ("build", "timed out building")):
417 _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, where))
418 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, result)], where)
419
420 def test_a_test_stopped_running_outweighs_a_build_stopped(self):
421 # Undone alone, the second hunk makes cargo hang in its build and a Python test hang while running: the hunk
422 # is caught by timeout, since a test did hang.
423 watch = ("import os, time, unittest\n\n\nclass T(unittest.TestCase):\n def test_lib(self):\n"
424 " root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n"
425 " with open(os.path.join(root, 'd3d12', 'crates', 'foo', 'src', 'lib.rs'), encoding='utf-8') as f:\n"
426 " text = f.read()\n"
427 " if ' 2\\n' in text and ' 5\\n' in text:\n"
428 " time.sleep(120)\n")
429 repo = Repo(self)
430 repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
431 "d3d12/crates/foo/src/lib.rs": self.BASE})
432 repo.git("switch", "-q", "-c", "pr")
433 repo.commit("fix", {"tests/test_watch.py": watch,
434 "d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace(
435 " 5\n", " 6\n").replace(
436 "fn value_is_one() {\n assert_eq!(super::value(), 1);",
437 "fn value_is_two() {\n assert_eq!(super::value(), 2);")})
438 _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, "build"))
439 self.assertEqual(r["verdict"], "red then green", r)
440 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "caught by timeout")])
441
442 def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self):
443 # The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the
444 # other test. Neither is mutated; only the fix is.
445 spare_test = "\n #[test]\n fn spare_is_five() {\n assert_eq!(super::spare(), 5);\n }\n"
446 base = ("pub fn value() -> u32 {\n 1\n}\n\npub fn spare() -> u32 {\n 5\n}\n"
447 + LIB[LIB.index("\n#[cfg(test)]"):LIB.rindex("}")]
448 + "".join(f" // padding line {i}\n" for i in range(10)) + spare_test + "}\n")
449 repo = Repo(self)
450 repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
451 "d3d12/crates/foo/src/lib.rs": base})
452 repo.git("switch", "-q", "-c", "pr")
453 repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": base.replace(" 1\n", " 2\n").replace(spare_test, "")
454 .replace("fn value_is_one() {\n assert_eq!(super::value(), 1);",
455 "fn value_is_two() {\n assert_eq!(super::value(), 2);")})
456 code, r, _ = repo.run("--mutate")
457 self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
458 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")])
459
460 def test_a_python_fix_undone_is_caught(self):
461 repo = Repo(self)
462 repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"})
463 repo.git("switch", "-q", "-c", "pr")
464 repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST})
465 code, r, _ = repo.run("--no-cargo", "--mutate")
466 self.assertEqual(r["verdict"], "red then green", r)
467 self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")])
468
469 # tools/bar.py with two hunks far apart, two() at line 2 (the fix) and settled() at line 15; a test of two().
470 BAR = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10))
471 + "\ndef settled():\n return False\n")
472
473 def bar_repo(self, body, base_files=None):
474 test = ("import os, subprocess, sys, unittest\n"
475 "tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n"
476 "sys.path.insert(0, tools)\n"
477 "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + body
478 + " self.assertEqual(bar.two(), 2)\n")
479 repo = Repo(self)
480 repo.commit("base", {"tools/bar.py": self.BAR, **(base_files or {})})
481 repo.git("switch", "-q", "-c", "pr")
482 repo.commit("fix", {"tools/bar.py": self.BAR.replace("return 1", "return 2").replace("False", "True"),
483 "tests/test_bar.py": test})
484 return repo
485
486 def test_a_mutated_run_that_hangs_is_caught_by_timeout(self):
487 # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does
488 # not hang there.
489 repo = self.bar_repo(" if bar.two() == 2 and not bar.settled():\n"
490 " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n")
491 start = time.monotonic()
492 _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "5")
493 self.assertEqual(r["verdict"], "red then green", r)
494 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "caught by timeout")])
495 self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 caught by timeout", rg.report(r))
496 # The run did not wait for the sleeping process.
497 self.assertLess(time.monotonic() - start, 60)
498
499 def test_a_process_left_behind_does_not_hold_a_mutated_run(self):
500 # Undone alone, the fix makes the test leave a process behind that outlives it with its output; the test still
501 # fails, so the hunk is caught, as soon as the test ends and not when the timeout runs out. The process left
502 # behind is stopped then: 5 s later, it would write a file beside the work tree. (Kept in T, so that no
503 # ResourceWarning cuts the test's line in the verbose output.)
504 repo = self.bar_repo(
505 " if bar.two() != 2 and bar.settled():\n"
506 " mark = os.path.join(os.path.dirname(os.path.dirname(tools)), 'left-behind')\n"
507 " T.left = subprocess.Popen([sys.executable, '-c', 'import sys, time; time.sleep(5); "
508 "open(sys.argv[1], \"w\").close()', mark])\n")
509 start = time.monotonic()
510 _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "20")
511 self.assertEqual(r["verdict"], "red then green", r)
512 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")])
513 self.assertLess(time.monotonic() - start, 20)
514 time.sleep(6) # it started before the run ended
515 self.assertFalse(os.path.exists(os.path.join(repo.dir, ".git", "red-green", "left-behind")))
516
517 def test_a_test_that_dirties_the_tree_does_not_change_the_next_hunk(self):
518 # When it finds two() wrong, the test writes into a tracked file that it also checks. Each mutation starts from
519 # the green tree, so the second hunk (settled(), which no test looks at) is not caught for that.
520 repo = self.bar_repo(" flag = os.path.join(tools, 'flag.txt')\n"
521 " if bar.two() != 2:\n"
522 " with open(flag, 'w', encoding='utf-8', newline='\\n') as f:\n"
523 " f.write('dirty\\n')\n"
524 " with open(flag, encoding='utf-8') as f:\n"
525 " self.assertEqual(f.read(), 'clean\\n')\n", {"tools/flag.txt": "clean\n"})
526 code, r, _ = repo.run("--no-cargo", "--mutate")
527 self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
528 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")])
529 tree = os.path.join(repo.dir, ".git", "red-green", "tree")
530 status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout
531 self.assertEqual(status, "")
532
533 def test_hunks_past_mutate_max_are_listed_as_not_tried(self):
534 base = "".join(f"def f{n}():\n return 1\n" + "# padding\n" * 4 for n in range(1, 5))
535 test = Python.TEST.replace("bar.two(), 2", "bar.f1(), 2")
536 repo = Repo(self)
537 repo.commit("base", {"tools/bar.py": base})
538 repo.git("switch", "-q", "-c", "pr")
539 repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2"), "tests/test_bar.py": test})
540 code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-max", "2")
541 self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
542 self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (8, "not caught")])
543 self.assertEqual(r["mutations_skipped"], [{"file": "tools/bar.py", "line": 14},
544 {"file": "tools/bar.py", "line": 20}])
545 self.assertIn("not tried, past --mutate-max: tools/bar.py:14, tools/bar.py:20", rg.report(r))
546
547 def test_a_test_only_pull_request_has_nothing_to_undo(self):
548 repo = Repo(self)
549 repo.commit("base", {"tools/bar.py": "def two():\n return 2\n"})
550 repo.git("switch", "-q", "-c", "pr")
551 repo.commit("test", {"tests/test_bar.py": Python.TEST})
552 code, r, _ = repo.run("--no-cargo", "--mutate")
553 # The verdict and exit code are those of any test that passes on both.
554 self.assertEqual((code, r["verdict"]), (1, "no red"), r)
555 self.assertEqual(r["mutations"], [])
556 self.assertEqual(r["mutations_not_run"], "nothing to undo: the diff changes no Rust or Python code outside its "
557 "tests")
558 self.assertIn("mutations: nothing to undo: the diff changes no Rust or Python code outside its tests",
559 rg.report(r))
560
561 def test_code_only_in_added_files_has_nothing_to_undo_in_the_files_it_modifies(self):
562 repo = Repo(self)
563 repo.commit("base", {"README.md": "base\n"})
564 repo.git("switch", "-q", "-c", "pr")
565 repo.commit("new tool", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST})
566 code, r, _ = repo.run("--no-cargo", "--mutate")
567 self.assertEqual((code, r["verdict"]), (1, "red does not build"), r)
568 self.assertEqual((r["mutations"], r["added_not_mutated"]), ([], ["tools/bar.py"]))
569 text = rg.report(r)
570 self.assertIn("mutations: nothing to undo in the files it modifies: its code changes are in files it adds", text)
571 self.assertIn("not mutated, added by the pull request: tools/bar.py", text)
572
573 def test_code_with_no_test_gone_red_is_not_mutated_and_said_so(self):
574 repo = Repo(self)
575 repo.commit("base", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 3\n"})
576 repo.git("switch", "-q", "-c", "pr")
577 repo.commit("change", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 4\n",
578 "tests/test_bar.py": Python.TEST})
579 code, r, _ = repo.run("--no-cargo", "--mutate")
580 self.assertEqual((code, r["verdict"]), (1, "no red"), r)
581 self.assertEqual(r["mutations"], [])
582 self.assertIn("mutations: not run: no test went red then green", rg.report(r))
583
584 def test_files_the_pull_request_adds_are_listed_as_not_mutated(self):
585 repo = Repo(self)
586 repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"})
587 repo.git("switch", "-q", "-c", "pr")
588 repo.commit("fix", {"tools/helper.py": "def value():\n return 2\n",
589 "tools/bar.py": "from helper import value\n\n\ndef two():\n return value()\n",
590 "tests/test_bar.py": Python.TEST})
591 code, r, _ = repo.run("--no-cargo", "--mutate")
592 self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
593 self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]],
594 [("tools/bar.py", "caught"), ("tools/bar.py", "caught")])
595 # helper.py holds the change and is never undone: the report says so rather than read as full coverage.
596 self.assertEqual(r["added_not_mutated"], ["tools/helper.py"])
597 self.assertIn("not mutated, added by the pull request: tools/helper.py", rg.report(r))
598
599 def test_mutate_options_are_checked(self):
600 for args, why in ((["--mutate", "--mutate-max", "0"], "--mutate-max"),
601 (["--mutate", "--mutate-timeout", "0"], "--mutate-timeout"),
602 (["--mutate", "--mutate-timeout", "nan"], "--mutate-timeout"),
603 (["--mutate", "--mutate-timeout", "inf"], "--mutate-timeout"),
604 (["--mutate-max", "3"], "--mutate"), (["--mutate-timeout", "60"], "--mutate")):
605 err = io.StringIO()
606 with redirect_stderr(err), self.assertRaises(SystemExit) as stop:
607 rg.main(["pr", "--no-fetch", *args])
608 self.assertEqual(stop.exception.code, 2, args)
609 self.assertIn(why, err.getvalue().splitlines()[-1], args)
610
611 def test_no_mutation_without_the_option(self):
612 repo = Repo(self)
613 repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"})
614 repo.git("switch", "-q", "-c", "pr")
615 repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST})
616 _code, r, _ = repo.run("--no-cargo")
617 self.assertIsNone(r["mutations"])
618 self.assertNotIn("mutations", rg.report(r))
619
238 620
239class CompilerCrash(unittest.TestCase): 621class CompilerCrash(unittest.TestCase):
240 def fixed_repo(self): 622 def fixed_repo(self):
diff --git a/tools/awc_shorts.py b/tools/awc_shorts.py
index aab36a366..82f3b4a73 100644
--- a/tools/awc_shorts.py
+++ b/tools/awc_shorts.py
@@ -27,7 +27,7 @@ import awc_opus as awc # noqa: E402
27from file_mode import published_mode # noqa: E402 27from file_mode import published_mode # noqa: E402
28from pool_workers import process_workers # noqa: E402 28from pool_workers import process_workers # noqa: E402
29from replace_retry import replace as replace_retry # noqa: E402 29from replace_retry import replace as replace_retry # noqa: E402
30from report_paths import path_key # noqa: E402 30from report_paths import path_key, same_report_path # noqa: E402
31 31
32FIELDS = ("bank", "stream", "duration_s", "channels", "packets", "file") 32FIELDS = ("bank", "stream", "duration_s", "channels", "packets", "file")
33 33
@@ -160,6 +160,16 @@ def main(argv=None) -> int:
160 except OSError as e: 160 except OSError as e:
161 print(f"awc_shorts: cannot list {e.filename or a.src}: {e.strerror or e}", file=sys.stderr) 161 print(f"awc_shorts: cannot list {e.filename or a.src}: {e.strerror or e}", file=sys.stderr)
162 return 2 162 return 2
163 catalog = os.path.join(a.out, "shorts.csv")
164 # Both refusals run before the output folder is created, so a refused run leaves nothing behind.
165 for path, bank in banks:
166 if same_report_path(catalog, path):
167 print(f"awc_shorts: error: catalog would overwrite the input bank {path}", file=sys.stderr)
168 return 2
169 target = os.path.join(a.out, bank)
170 if same_report_path(catalog, target):
171 print(f"awc_shorts: error: catalog would collide with bank export directory {target}", file=sys.stderr)
172 return 2
163 try: 173 try:
164 os.makedirs(a.out, exist_ok=True) 174 os.makedirs(a.out, exist_ok=True)
165 except OSError as e: 175 except OSError as e:
diff --git a/tools/game_gate.py b/tools/game_gate.py
index fee55866b..b88ec9535 100644
--- a/tools/game_gate.py
+++ b/tools/game_gate.py
@@ -8,6 +8,7 @@ script's output: the precompile lines), leonida.log (the runtime's log) and data
8numbers, switch names and verdicts only: no path, no user or machine name, nothing the title printed. 8numbers, switch names and verdicts only: no path, no user or machine name, nothing the title printed.
9Schema and rules: docs/game_gate.md. 9Schema and rules: docs/game_gate.md.
10""" 10"""
11import csv
11import datetime as dt 12import datetime as dt
12import glob 13import glob
13import json 14import json
@@ -31,6 +32,8 @@ END_WINDOW_S = 60.0
31GAP_FAIL_S = 10.0 32GAP_FAIL_S = 10.0
32# The last frame line before the stop request is at most this old for the run to count as alive. 33# The last frame line before the stop request is at most this old for the run to count as alive.
33ALIVE_S = 30.0 34ALIVE_S = 30.0
35# The memory stop: the PC under its commit floor this long (5 s memory lines).
36COMMIT_LOW_S = 20.0
34DEVICE_LOST = 0x887A0005 37DEVICE_LOST = 0x887A0005
35 38
36ANSI = re.compile(r"\x1b\[[0-9;]*m") 39ANSI = re.compile(r"\x1b\[[0-9;]*m")
@@ -49,6 +52,14 @@ MEMORY = re.compile(r"^memory: (\d+) MB private \((\d+) MB of it in memory; the
49 r"left to commit\)") 52 r"left to commit\)")
50VIDEO = re.compile(r"^video memory as the system counts it, [^:]*: the card's own: budget (\d+) MB, in use (\d+) MB, " 53VIDEO = re.compile(r"^video memory as the system counts it, [^:]*: the card's own: budget (\d+) MB, in use (\d+) MB, "
51 r".*?; the PC's shared with the card: budget (\d+) MB, in use (\d+) MB") 54 r".*?; the PC's shared with the card: budget (\d+) MB, in use (\d+) MB")
55# The census line with them: objects let go that wait for their submissions, and those handed to the reaper thread
56# and not let go yet (the reaper's queue, the number a pile-up shows first).
57WAITS = re.compile(r"^memory, what waits to be let go: (\d+) objects let go that wait for the submissions that may use "
58 r"them \(LEONIDA_BURY_LAG\), (\d+) retired objects, landed host lists and lists' fronts handed to the "
59 r"thread that lets them go")
60SERIES = "memory.csv"
61SERIES_COLUMNS = ("t_s", "private_mb", "in_memory_mb", "pc_free_mb", "pc_commit_left_mb", "vram_budget_mb",
62 "vram_in_use_mb", "shared_in_use_mb", "waiting_objects", "reaper_queue")
52 63
53# The runtime's own words this parser reads, and where they are written: tests/test_game_gate.py checks that 64# The runtime's own words this parser reads, and where they are written: tests/test_game_gate.py checks that
54# each is still there, so a reworded line fails the test, not the next gate. 65# each is still there, so a reworded line fails the test, not the next gate.
@@ -76,6 +87,11 @@ SOURCES = {
76 "d3d12/crates/leonida-gpu/src/host.rs", 87 "d3d12/crates/leonida-gpu/src/host.rs",
77 "the PC's shared with the card: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs", 88 "the PC's shared with the card: budget {} MB, in use {} MB": "d3d12/crates/leonida-gpu/src/host.rs",
78 'h.log_video_memory("with the memory line")': "d3d12/crates/leonida-gpu/src/copystat.rs", 89 'h.log_video_memory("with the memory line")': "d3d12/crates/leonida-gpu/src/copystat.rs",
90 # One key over the whole part WAITS reads, the ", " between its two numbers too.
91 "memory, what waits to be let go: {waiting} objects let go that wait for the submissions that may use them "
92 "(LEONIDA_BURY_LAG), {handed} retired objects, landed host lists and lists' fronts handed to the thread that "
93 "lets them go": "d3d12/crates/leonida-gpu/src/census.rs",
94 "crate::census::log();": "d3d12/crates/leonida-gpu/src/copystat.rs",
79} 95}
80 96
81 97
@@ -124,6 +140,7 @@ class Run:
124 self.missed = [] # t of each pipeline not made within its wait 140 self.missed = [] # t of each pipeline not made within its wait
125 self.memory = [] # (t, private MB, in memory MB, PC free MB, PC left to commit MB) 141 self.memory = [] # (t, private MB, in memory MB, PC free MB, PC left to commit MB)
126 self.video = [] # (t, card budget MB, card in use MB, shared budget MB, shared in use MB) 142 self.video = [] # (t, card budget MB, card in use MB, shared budget MB, shared in use MB)
143 self.waits = [] # (t, objects waiting for their submissions, the reaper's queue)
127 self.settings = None # from the runtime's settings line 144 self.settings = None # from the runtime's settings line
128 self.suspend = None 145 self.suspend = None
129 self.ended_at = None 146 self.ended_at = None
@@ -155,6 +172,8 @@ class Run:
155 self.memory.append((t,) + tuple(int(x) for x in MEMORY.match(text).groups())) 172 self.memory.append((t,) + tuple(int(x) for x in MEMORY.match(text).groups()))
156 elif text.startswith("video memory as the system counts it") and VIDEO.match(text): 173 elif text.startswith("video memory as the system counts it") and VIDEO.match(text):
157 self.video.append((t,) + tuple(int(x) for x in VIDEO.match(text).groups())) 174 self.video.append((t,) + tuple(int(x) for x in VIDEO.match(text).groups()))
175 elif text.startswith("memory, what waits to be let go") and WAITS.match(text):
176 self.waits.append((t,) + tuple(int(x) for x in WAITS.match(text).groups()))
158 elif text.startswith("a pipeline not made within its wait"): 177 elif text.startswith("a pipeline not made within its wait"):
159 self.missed.append(t) 178 self.missed.append(t)
160 elif target == "settings": 179 elif target == "settings":
@@ -271,6 +290,37 @@ def read_precompile(lines):
271 return out 290 return out
272 291
273 292
293def since_end(rows, low):
294 """Seconds the last rows have all been `low`, from the first of them to the last row (0.0 if the last is not)."""
295 first = None
296 for row in reversed(rows):
297 if not low(row):
298 break
299 first = row[0]
300 return rows[-1][0] - first if first is not None else 0.0
301
302
303def memory_alarm(run):
304 """Why scripts/game-gate.ps1 must stop the run for memory now, or None, from the latest memory lines and the
305 limits it wrote in run.json (`memory_stop`; 0 or less turns one off)."""
306 limits = run.meta.get("memory_stop") or {}
307 private_max = limits.get("private_max_mb") or 0
308 left_min = limits.get("commit_left_min_mb") or 0
309 over_s = limits.get("over_budget_s") or 0
310 if run.memory:
311 private = run.memory[-1][1]
312 if private_max > 0 and private > private_max:
313 return f"private bytes {private} MB, over {private_max} MB"
314 low = since_end(run.memory, lambda m: m[4] < left_min) if left_min > 0 else 0.0
315 if low >= COMMIT_LOW_S:
316 return f"the PC had under {left_min} MB left to commit for {low:.0f} s"
317 if over_s > 0 and run.video:
318 over = since_end(run.video, lambda v: v[2] > v[1])
319 if over >= over_s:
320 return f"video memory over its budget for {over:.0f} s"
321 return None
322
323
274def state(run): 324def state(run):
275 world = run.world_at() 325 world = run.world_at()
276 last = run.last_at 326 last = run.last_at
@@ -282,6 +332,7 @@ def state(run):
282 "frame_lines": len(run.frames), 332 "frame_lines": len(run.frames),
283 "relaunched": run.relaunched, 333 "relaunched": run.relaunched,
284 "device_lost": any(c["kind"] == "device_lost" for c in run.crashes), 334 "device_lost": any(c["kind"] == "device_lost" for c in run.crashes),
335 "memory_stop": memory_alarm(run),
285 } 336 }
286 337
287 338
@@ -334,13 +385,76 @@ def fps_block(run, world, end):
334 return out 385 return out
335 386
336 387
337def memory_block(run): 388def slope_per_min(points):
338 """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics).""" 389 """Least-squares slope of (t in s, value) points, per minute; None under 3 points or with no time spread."""
390 if len(points) < 3:
391 return None
392 mt = sum(t for t, _ in points) / len(points)
393 mv = sum(v for _, v in points) / len(points)
394 spread = sum((t - mt) ** 2 for t, _ in points)
395 if spread == 0:
396 return None
397 return 60.0 * sum((t - mt) * (v - mv) for t, v in points) / spread
398
399
400def near(rows, t, within=2.0):
401 """The row of `rows` (sorted by time) nearest to t, if within `within` seconds."""
402 best = min(rows, key=lambda r: abs(r[0] - t), default=None)
403 return best if best is not None and abs(best[0] - t) <= within else None
404
405
406def memory_rows(run):
407 """One row per memory line, with the video memory and census lines written with it (`memory.csv`)."""
408 rows = []
409 for t, private, in_memory, free, left in run.memory:
410 v = near(run.video, t)
411 w = near(run.waits, t)
412 rows.append({"t_s": round(t, 3), "private_mb": private, "in_memory_mb": in_memory, "pc_free_mb": free,
413 "pc_commit_left_mb": left, "vram_budget_mb": v[1] if v else None,
414 "vram_in_use_mb": v[2] if v else None, "shared_in_use_mb": v[4] if v else None,
415 "waiting_objects": w[1] if w else None, "reaper_queue": w[2] if w else None})
416 return rows
417
418
419def write_series(run, folder):
420 """Writes memory.csv beside summary.json when the run has memory lines; returns its name or None. Without them
421 it removes a memory.csv already there (a folder summarized again), so no old rows sit beside `series: null`.
422 A file it cannot write or remove (open in another program) is said on stderr: the summary is written anyway."""
423 path = os.path.join(folder, SERIES)
424 rows = memory_rows(run)
425 try:
426 if not rows:
427 if os.path.exists(path):
428 os.remove(path)
429 return None
430 with open(path, "w", encoding="utf-8", newline="") as f:
431 out = csv.DictWriter(f, fieldnames=SERIES_COLUMNS, lineterminator="\n")
432 out.writeheader()
433 out.writerows(rows)
434 except OSError as e:
435 print(f"{SERIES} not written or removed: {e.__class__.__name__}: {e.strerror or e}", file=sys.stderr)
436 return None
437 return SERIES
438
439
440def memory_block(run, world=None, end=None):
441 """Peaks of the runtime's memory lines over the whole run (none from a build without diagnostics), the
442 reaper's queue at its longest, and how fast the private bytes grew in the world up to `end` (a pile-up's
443 slope; the lines written while the title ends after the stop request do not count)."""
339 out = {"source": None, "lines": 0, "private_max_mb": None, "private_max_at_s": None, "in_memory_max_mb": None, 444 out = {"source": None, "lines": 0, "private_max_mb": None, "private_max_at_s": None, "in_memory_max_mb": None,
340 "pc_commit_left_min_mb": None, "pc_commit_left_min_at_s": None, "vram_in_use_max_mb": None, 445 "pc_commit_left_min_mb": None, "pc_commit_left_min_at_s": None, "vram_in_use_max_mb": None,
341 "vram_max_at_s": None, "vram_budget_at_max_mb": None, "vram_over_budget_s": None, 446 "vram_max_at_s": None, "vram_budget_at_max_mb": None, "vram_over_budget_s": None,
342 "shared_in_use_max_mb": None} 447 "shared_in_use_max_mb": None, "reaper_queue_max": None, "reaper_queue_max_at_s": None,
448 "waiting_objects_max": None, "private_mb_per_min_in_world": None, "series": None}
449 if run.waits:
450 t, queue = max(((w[0], w[2]) for w in run.waits), key=lambda x: x[1])
451 out["reaper_queue_max"], out["reaper_queue_max_at_s"] = queue, round(t, 3)
452 out["waiting_objects_max"] = max(w[1] for w in run.waits)
453 if run.memory and world is not None:
454 slope = slope_per_min([(m[0], m[1]) for m in run.memory if world <= m[0] and (end is None or m[0] <= end)])
455 out["private_mb_per_min_in_world"] = round(slope, 1) if slope is not None else None
343 if run.memory: 456 if run.memory:
457 out["series"] = SERIES
344 out["source"], out["lines"] = "memory lines", len(run.memory) 458 out["source"], out["lines"] = "memory lines", len(run.memory)
345 t, private = max(((t, p) for t, p, *_ in run.memory), key=lambda x: x[1]) 459 t, private = max(((t, p) for t, p, *_ in run.memory), key=lambda x: x[1])
346 out["private_max_mb"], out["private_max_at_s"] = private, round(t, 3) 460 out["private_max_mb"], out["private_max_at_s"] = private, round(t, 3)
@@ -394,13 +508,16 @@ def summary(run):
394 fails.append("exited_before_stop") 508 fails.append("exited_before_stop")
395 if fps["longest_present_gap_s"] is not None and fps["longest_present_gap_s"] > GAP_FAIL_S: 509 if fps["longest_present_gap_s"] is not None and fps["longest_present_gap_s"] > GAP_FAIL_S:
396 fails.append("present_gap") 510 fails.append("present_gap")
511 if reason == "memory":
512 # Stopped before memory ran out: the run was on its way to a crash, not short by choice.
513 fails.append("memory_stop")
397 if run.relaunched: 514 if run.relaunched:
398 errors.append("relaunched") 515 errors.append("relaunched")
399 if run.event("game") is None and not run.frames: 516 if run.event("game") is None and not run.frames:
400 errors.append("not_started") 517 errors.append("not_started")
401 elif world is None: 518 elif world is None and reason != "memory":
402 (errors if not exited_before_stop else fails).append("world_not_reached") 519 (errors if not exited_before_stop else fails).append("world_not_reached")
403 elif world_s < min_world: 520 elif world_s < min_world and reason != "memory":
404 (errors if reason == "stop_file" else fails).append("stopped_early" if reason == "stop_file" else "world_time_short") 521 (errors if reason == "stop_file" else fails).append("stopped_early" if reason == "stop_file" else "world_time_short")
405 if stop is not None and not alive and not fails and not errors: 522 if stop is not None and not alive and not fails and not errors:
406 fails.append("not_alive_at_stop") 523 fails.append("not_alive_at_stop")
@@ -436,7 +553,7 @@ def summary(run):
436 }, 553 },
437 "fps": fps, 554 "fps": fps,
438 "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)}, 555 "pipelines": {"missed_waits": len(run.missed), "making_max": max((m for *_, m in run.frames), default=0)},
439 "memory": memory_block(run), 556 "memory": dict(memory_block(run, world, end), stop_limits=run.meta.get("memory_stop")),
440 "crash": { 557 "crash": {
441 "kind": crash_kind, 558 "kind": crash_kind,
442 "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None, 559 "at_s": round(first["at_s"], 3) if first and first["at_s"] is not None else None,
@@ -450,7 +567,7 @@ def summary(run):
450 "kind": ("device_lost" if code is not None and code & 0xFFFFFFFF == DEVICE_LOST else 567 "kind": ("device_lost" if code is not None and code & 0xFFFFFFFF == DEVICE_LOST else
451 "killed" if killed else "clean" if code == 0 else "other" if code is not None else None)}, 568 "killed" if killed else "clean" if code == 0 else "other" if code is not None else None)},
452 "stop": {"reason": reason, "killed": killed, "cache_saved": run.ended_at is not None if stop is not None else None, 569 "stop": {"reason": reason, "killed": killed, "cache_saved": run.ended_at is not None if stop is not None else None,
453 "suspend": run.suspend}, 570 "suspend": run.suspend, "memory_why": (run.event("stop_requested") or {}).get("why")},
454 "relaunched": run.relaunched, 571 "relaunched": run.relaunched,
455 "verdict": {"result": result, "reasons": fails + errors, "warnings": warnings, "min_world_s": min_world}, 572 "verdict": {"result": result, "reasons": fails + errors, "warnings": warnings, "min_world_s": min_world},
456 } 573 }
@@ -465,6 +582,8 @@ def main(argv):
465 print(json.dumps(state(run))) 582 print(json.dumps(state(run)))
466 return 0 583 return 0
467 out = summary(run) 584 out = summary(run)
585 # `series` names the file only when it was written.
586 out["memory"]["series"] = write_series(run, argv[2])
468 with open(os.path.join(argv[2], "summary.json"), "w", encoding="utf-8", newline="\n") as f: 587 with open(os.path.join(argv[2], "summary.json"), "w", encoding="utf-8", newline="\n") as f:
469 json.dump(out, f, indent=2) 588 json.dump(out, f, indent=2)
470 f.write("\n") 589 f.write("\n")
diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py
index 675e1ce58..07d2340a8 100644
--- a/tools/pe_inspect.py
+++ b/tools/pe_inspect.py
@@ -91,6 +91,8 @@ class PeImage:
91 # 0x3c holds e_lfanew. Saying "no MZ header" here would blame a signature that is present. 91 # 0x3c holds e_lfanew. Saying "no MZ header" here would blame a signature that is present.
92 raise PeFormatError(f"file is {len(data)} bytes, shorter than the 64-byte MS-DOS header") 92 raise PeFormatError(f"file is {len(data)} bytes, shorter than the 64-byte MS-DOS header")
93 self.nt = struct.unpack_from("<I", data, 0x3C)[0] 93 self.nt = struct.unpack_from("<I", data, 0x3C)[0]
94 if self.nt < 0x40:
95 raise PeFormatError(f"file is {len(data)} bytes, PE header at 0x{self.nt:x} overlaps the 64-byte MS-DOS header")
94 if self.nt + 24 > len(data): 96 if self.nt + 24 > len(data):
95 raise PeFormatError(f"file is {len(data)} bytes, too short to hold the PE header at 0x{self.nt:x}") 97 raise PeFormatError(f"file is {len(data)} bytes, too short to hold the PE header at 0x{self.nt:x}")
96 if data[self.nt:self.nt + 4] != b"PE\0\0": 98 if data[self.nt:self.nt + 4] != b"PE\0\0":
@@ -114,6 +116,10 @@ class PeImage:
114 self.size_of_headers = struct.unpack_from("<I", data, opt + 60)[0] 116 self.size_of_headers = struct.unpack_from("<I", data, opt + 60)[0]
115 self.subsystem = struct.unpack_from("<H", data, opt + 68)[0] 117 self.subsystem = struct.unpack_from("<H", data, opt + 68)[0]
116 self.dll_characteristics = struct.unpack_from("<H", data, opt + 70)[0] 118 self.dll_characteristics = struct.unpack_from("<H", data, opt + 70)[0]
119 if self.size_of_image == 0:
120 raise PeFormatError("invalid SizeOfImage 0")
121 if self.size_of_headers > self.size_of_image:
122 raise PeFormatError(f"SizeOfHeaders {self.size_of_headers} exceeds SizeOfImage {self.size_of_image}")
117 123
118 # NumberOfRvaAndSizes counts the data directories: a slot past it is not a directory, whatever bytes it 124 # NumberOfRvaAndSizes counts the data directories: a slot past it is not a directory, whatever bytes it
119 # holds (runtime/src/pe_loader.cpp reads them the same way). The count is the dword before the table. 125 # holds (runtime/src/pe_loader.cpp reads them the same way). The count is the dword before the table.
@@ -257,42 +263,151 @@ def _imports(img: PeImage, kind: str, index: int, delay: bool = False) -> list[d
257 return entries 263 return entries
258 264
259 265
260def _exports(img: PeImage) -> list[str]: 266def _inspect_exports(img: PeImage) -> dict:
261 rva, size = img.directory(DIR_EXPORT) 267 rva, size = img.directory(DIR_EXPORT)
262 if not rva or size < 40: 268 if not rva or size < 40:
263 return [] 269 return {
270 "exports": [],
271 "forwarders": {},
272 "invalid_export_count": 0,
273 "invalid_exports": [],
274 }
264 at = img.offset(rva, 40) 275 at = img.offset(rva, 40)
265 if at is None: 276 if at is None:
266 start = img.offset(rva) 277 start = img.offset(rva)
267 if start is not None and start + 40 > len(img.data): 278 if start is not None and start + 40 > len(img.data):
268 raise PeFormatError("truncated export directory") 279 raise PeFormatError("truncated export directory")
269 return [] 280 return {
281 "exports": [],
282 "forwarders": {},
283 "invalid_export_count": 0,
284 "invalid_exports": [],
285 }
270 (_chars, _stamp, _major, _minor, _name, base, functions, name_count, addr_functions, 286 (_chars, _stamp, _major, _minor, _name, base, functions, name_count, addr_functions,
271 addr_names, addr_ordinals) = struct.unpack_from("<IIHHIIIIIII", img.data, at) 287 addr_names, addr_ordinals) = struct.unpack_from("<IIHHIIIIIII", img.data, at)
272 288
273 def has_export_at(index: int) -> bool: 289 dir_begin = rva
290 dir_end = rva + size
291
292 def get_export_rva(index: int) -> int | None:
274 if index >= functions: 293 if index >= functions:
275 return False 294 return None
276 # A zero RVA marks an unused slot. An RVA inside the export directory is a valid forwarder.
277 slot = img.offset(addr_functions + index * 4, 4) 295 slot = img.offset(addr_functions + index * 4, 4)
278 return slot is not None and struct.unpack_from("<I", img.data, slot)[0] != 0 296 if slot is None:
297 return None
298 return struct.unpack_from("<I", img.data, slot)[0]
299
300 names = []
301 forwarders = {}
302 forwarder_info = {}
303 invalid_exports = []
304 invalid_export_count = 0
305
306 def record_invalid(key: str, ord_num: int, exp_rva: int, reason: str) -> None:
307 nonlocal invalid_export_count
308 invalid_export_count += 1
309 if len(invalid_exports) < 5:
310 invalid_exports.append({
311 "symbol": key,
312 "ordinal": ord_num,
313 "rva": hex(exp_rva),
314 "reason": reason,
315 })
279 316
280 named, names = set(), [] 317 def process_export(key: str, index: int, exp_rva: int) -> None:
318 ord_num = base + index
319 if dir_begin <= exp_rva < dir_end:
320 target = img.string_at(exp_rva)
321 if not target:
322 record_invalid(key, ord_num, exp_rva, "unreadable_forwarder")
323 target = "?"
324 else:
325 dot = target.rfind(".")
326 if dot <= 0 or dot + 1 >= len(target) or any(ord(c) < 0x20 or ord(c) >= 0x7F for c in target):
327 record_invalid(key, ord_num, exp_rva, "malformed_forwarder")
328 else:
329 fwd_sym = target[dot + 1:]
330 if fwd_sym.startswith("#"):
331 ord_str = fwd_sym[1:]
332 if not ord_str.isdigit() or int(ord_str) <= 0 or int(ord_str) > 0xFFFF:
333 record_invalid(key, ord_num, exp_rva, "malformed_forwarder")
334 forwarders[key] = target
335 forwarder_info[key] = (ord_num, exp_rva, target)
336 elif exp_rva >= img.size_of_image:
337 record_invalid(key, ord_num, exp_rva, "out_of_bounds")
338
339 named = set()
281 for i in range(min(name_count, MAX_ENTRIES)): 340 for i in range(min(name_count, MAX_ENTRIES)):
282 name_at = img.offset(addr_names + i * 4, 4) 341 name_at = img.offset(addr_names + i * 4, 4)
283 ord_at = img.offset(addr_ordinals + i * 2, 2) 342 ord_at = img.offset(addr_ordinals + i * 2, 2)
284 if name_at is None or ord_at is None: 343 if name_at is None or ord_at is None:
285 break 344 break
345 symbol_rva = struct.unpack_from("<I", img.data, name_at)[0]
346 symbol = img.string_at(symbol_rva)
347 key = symbol if symbol is not None else "?"
286 index = struct.unpack_from("<H", img.data, ord_at)[0] 348 index = struct.unpack_from("<H", img.data, ord_at)[0]
287 if not has_export_at(index): 349 if index >= functions:
350 record_invalid(key, base + index, 0, "out_of_range_ordinal")
351 continue
352 exp_rva = get_export_rva(index)
353 if exp_rva is None or exp_rva == 0:
288 continue 354 continue
289 symbol = img.string_at(struct.unpack_from("<I", img.data, name_at)[0]) 355 names.append(key)
290 names.append(symbol if symbol is not None else "?") 356 process_export(key, index, exp_rva)
291 named.add(index) 357 named.add(index)
358
292 for i in range(min(functions, MAX_ENTRIES)): 359 for i in range(min(functions, MAX_ENTRIES)):
293 if i not in named and has_export_at(i): 360 if i not in named:
294 names.append(f"#{base + i}") 361 exp_rva = get_export_rva(i)
295 return names 362 if exp_rva is not None and exp_rva != 0:
363 key = f"#{base + i}"
364 names.append(key)
365 process_export(key, i, exp_rva)
366
367 own_mod = img.string_at(_name) if _name else ""
368
369 def _stem(m: str) -> str:
370 s = m.lower()
371 return s[:-4] if s.endswith(".dll") else s
372
373 own_stem = _stem(own_mod) if own_mod else ""
374 if own_stem:
375 for fwd_key, (ord_num, exp_rva, target) in forwarder_info.items():
376 if target == "?" or "." not in target:
377 continue
378 dot = target.rfind(".")
379 if dot <= 0 or _stem(target[:dot]) != own_stem:
380 continue
381 visited = [fwd_key]
382 curr_target = target
383 has_loop = False
384 while True:
385 c_dot = curr_target.rfind(".")
386 if c_dot <= 0 or _stem(curr_target[:c_dot]) != own_stem:
387 break
388 next_sym = curr_target[c_dot + 1:]
389 if next_sym in visited or len(visited) >= 8:
390 has_loop = True
391 break
392 if next_sym not in forwarders:
393 break
394 visited.append(next_sym)
395 curr_target = forwarders[next_sym]
396 if curr_target == "?":
397 break
398 if has_loop:
399 record_invalid(fwd_key, ord_num, exp_rva, "forwarder_loop")
400
401 return {
402 "exports": names,
403 "forwarders": forwarders,
404 "invalid_export_count": invalid_export_count,
405 "invalid_exports": invalid_exports,
406 }
407
408
409def _exports(img: PeImage) -> list[str]:
410 return _inspect_exports(img)["exports"]
296 411
297 412
298# The resource directory (data directory 2) and its RT_VERSION block. The version block names the build, and its 413# The resource directory (data directory 2) and its RT_VERSION block. The version block names the build, and its
@@ -569,6 +684,203 @@ def _tls_callbacks(img: PeImage) -> int:
569 return count 684 return count
570 685
571 686
687def _inspect_pdata(img: PeImage) -> dict:
688 """Exception Directory (.pdata / DIR_EXCEPTION = 3) validation and function table parsing.
689
690 Matches runtime/src/pe_loader.cpp (Loader::register_unwind) bounds, sorting, non-overlapping intervals,
691 and zero-length entries (e.g. symcryptk.dll). Non-x64 architectures (e.g. x86, ARM64) do not use x64
692 12-byte RUNTIME_FUNCTION tables and are gracefully rejected with informative format metadata.
693 """
694 rva, size = img.directory(DIR_EXCEPTION)
695 present = bool(rva and size)
696 if not present:
697 return {
698 "present": False,
699 "rva": "0x0",
700 "size": 0,
701 "entry_count": 0,
702 "parsed_count": 0,
703 "trailing_bytes": 0,
704 "mapped": False,
705 "truncated": False,
706 "zero_length_count": 0,
707 "inverted_count": 0,
708 "out_of_bounds_count": 0,
709 "unsorted_count": 0,
710 "overlap_count": 0,
711 "min_begin": None,
712 "max_end": None,
713 "valid": True,
714 "sample_errors": [],
715 }
716
717 is_x64 = img.machine == 0x8664
718 is_arm64 = img.machine == 0xAA64
719 entry_size = 8 if is_arm64 else 12
720 entry_count = size // entry_size
721 trailing_bytes = size % entry_size
722
723 bounds = img._range(rva)
724
725 if not is_x64:
726 if is_arm64:
727 fmt = "arm64"
728 reason = "ARM64 architecture uses 8-byte packed unwind records (not 12-byte RUNTIME_FUNCTION)"
729 elif img.machine == 0x14C:
730 fmt = "non-x64"
731 reason = "x86 architecture uses stack-based SEH (no 12-byte RUNTIME_FUNCTION table)"
732 else:
733 fmt = f"unsupported ({MACHINES.get(img.machine, hex(img.machine))})"
734 reason = f"unsupported machine architecture 0x{img.machine:x} (not x86-64)"
735 if bounds is None:
736 mapped = False
737 truncated = False
738 else:
739 start, end = bounds
740 mapped = True
741 needed_bytes = entry_count * entry_size
742 truncated = max(0, end - start) < needed_bytes
743 return {
744 "present": True,
745 "rva": hex(rva),
746 "size": size,
747 "entry_count": entry_count,
748 "parsed_count": 0,
749 "trailing_bytes": trailing_bytes,
750 "mapped": mapped,
751 "truncated": truncated,
752 "zero_length_count": 0,
753 "inverted_count": 0,
754 "out_of_bounds_count": 0,
755 "unsorted_count": 0,
756 "overlap_count": 0,
757 "min_begin": None,
758 "max_end": None,
759 "valid": True,
760 "sample_errors": [],
761 "format": fmt,
762 "rejection_reason": reason,
763 }
764
765 if bounds is None:
766 return {
767 "present": True,
768 "rva": hex(rva),
769 "size": size,
770 "entry_count": entry_count,
771 "parsed_count": 0,
772 "trailing_bytes": trailing_bytes,
773 "mapped": False,
774 "truncated": False,
775 "zero_length_count": 0,
776 "inverted_count": 0,
777 "out_of_bounds_count": 0,
778 "unsorted_count": 0,
779 "overlap_count": 0,
780 "min_begin": None,
781 "max_end": None,
782 "valid": False,
783 "sample_errors": [{"index": 0, "begin": "0x0", "end": "0x0", "unwind": "0x0", "reason": "unmapped"}],
784 }
785
786 start, end = bounds
787 available = max(0, end - start)
788 needed_bytes = entry_count * 12
789 truncated = available < needed_bytes
790 can_parse = min(needed_bytes, available) // 12
791 parsed_count = can_parse
792 mv = memoryview(img.data)
793 pdata_view = mv[start:start + can_parse * 12]
794
795 previous_begin = 0
796 previous_end = 0
797 min_begin = None
798 max_end = None
799 zero_length_count = 0
800 inverted_count = 0
801 out_of_bounds_count = 0
802 unsorted_count = 0
803 overlap_count = 0
804 sample_errors = []
805
806 def add_error(idx: int, b: int, e: int, u: int, reason: str) -> None:
807 if len(sample_errors) < 5:
808 sample_errors.append({
809 "index": idx,
810 "begin": hex(b),
811 "end": hex(e),
812 "unwind": hex(u),
813 "reason": reason,
814 })
815
816 for i, (b, e, u) in enumerate(struct.iter_unpack("<III", pdata_view)):
817 if min_begin is None or b < min_begin:
818 min_begin = b
819 if max_end is None or e > max_end:
820 max_end = e
821
822 entry_failed = False
823
824 if b == e:
825 zero_length_count += 1
826 elif e < b:
827 inverted_count += 1
828 add_error(i, b, e, u, "inverted")
829 entry_failed = True
830
831 info = u & ~1
832 if (b > img.size_of_image or e > img.size_of_image
833 or info > img.size_of_image or (img.size_of_image - info < 4)):
834 out_of_bounds_count += 1
835 if not entry_failed:
836 add_error(i, b, e, u, "out_of_bounds")
837 entry_failed = True
838
839 if i > 0:
840 if b < previous_begin:
841 unsorted_count += 1
842 if not entry_failed:
843 add_error(i, b, e, u, "unsorted")
844 entry_failed = True
845 elif b < previous_end:
846 overlap_count += 1
847 if not entry_failed:
848 add_error(i, b, e, u, "overlap")
849 entry_failed = True
850
851 previous_begin = b
852 if e >= b:
853 previous_end = max(previous_end, e)
854
855 valid = (
856 not truncated
857 and inverted_count == 0
858 and out_of_bounds_count == 0
859 and unsorted_count == 0
860 and overlap_count == 0
861 )
862
863 return {
864 "present": True,
865 "rva": hex(rva),
866 "size": size,
867 "entry_count": entry_count,
868 "parsed_count": parsed_count,
869 "trailing_bytes": trailing_bytes,
870 "mapped": True,
871 "truncated": truncated,
872 "zero_length_count": zero_length_count,
873 "inverted_count": inverted_count,
874 "out_of_bounds_count": out_of_bounds_count,
875 "unsorted_count": unsorted_count,
876 "overlap_count": overlap_count,
877 "min_begin": hex(min_begin) if min_begin is not None else None,
878 "max_end": hex(max_end) if max_end is not None else None,
879 "valid": valid,
880 "sample_errors": sample_errors,
881 }
882
883
572_apiset_cache: dict[str, bool] = {} 884_apiset_cache: dict[str, bool] = {}
573 885
574 886
@@ -846,12 +1158,13 @@ def _inspect(path: str, game_dir: str | None) -> dict:
846 for entry in imports: 1158 for entry in imports:
847 entry["where"] = classify_dll(entry["dll"], game_dir) 1159 entry["where"] = classify_dll(entry["dll"], game_dir)
848 1160
849 exports = _exports(img) 1161 exp = _inspect_exports(img)
1162 exports = exp["exports"]
850 own_names = (os.path.basename(path), _export_module_name(img)) 1163 own_names = (os.path.basename(path), _export_module_name(img))
851 loads = dll_strings(img.data, {i["dll"].lower() for i in imports}, own_names) 1164 loads = dll_strings(img.data, {i["dll"].lower() for i in imports}, own_names)
852 for entry in loads: 1165 for entry in loads:
853 entry["where"] = classify_dll(entry["name"], game_dir) 1166 entry["where"] = classify_dll(entry["name"], game_dir)
854 pdata_rva, pdata_size = img.directory(DIR_EXCEPTION) 1167 pdata = _inspect_pdata(img)
855 reloc_rva, reloc_size = img.directory(DIR_BASERELOC) 1168 reloc_rva, reloc_size = img.directory(DIR_BASERELOC)
856 checked, system_dir = system_dll_source() 1169 checked, system_dir = system_dll_source()
857 1170
@@ -872,7 +1185,12 @@ def _inspect(path: str, game_dir: str | None) -> dict:
872 "imports": imports, 1185 "imports": imports,
873 "export_count": len(exports), 1186 "export_count": len(exports),
874 "exports": exports, 1187 "exports": exports,
875 "pdata_functions": pdata_size // 12 if pdata_rva and pdata_size >= 12 else 0, 1188 "forwarders": exp["forwarders"],
1189 "forwarder_count": len(exp["forwarders"]),
1190 "invalid_export_count": exp["invalid_export_count"],
1191 "invalid_exports": exp["invalid_exports"],
1192 "pdata_functions": pdata["entry_count"],
1193 "pdata": pdata,
876 "tls_callbacks": _tls_callbacks(img), 1194 "tls_callbacks": _tls_callbacks(img),
877 "runtime_load_candidates": loads, 1195 "runtime_load_candidates": loads,
878 # Where `system` was checked: "windows" (System32 and the OS API-set schema), "wine-prefix" (its system32 1196 # Where `system` was checked: "windows" (System32 and the OS API-set schema), "wine-prefix" (its system32
@@ -893,12 +1211,54 @@ def system_dlls_note(r: dict) -> str | None:
893 1211
894 1212
895def to_markdown(r: dict) -> str: 1213def to_markdown(r: dict) -> str:
1214 pdata_summary = f"{r['pdata_functions']:,}"
1215 p = r.get("pdata")
1216 if p and p.get("present"):
1217 if p.get("format"):
1218 pdata_summary += f" ({p['format']})"
1219 elif p.get("valid"):
1220 notes = []
1221 if p.get("zero_length_count"):
1222 notes.append(f"{p['zero_length_count']} zero-length")
1223 if p.get("trailing_bytes"):
1224 notes.append(f"{p['trailing_bytes']} trailing bytes ignored")
1225 suffix = f", {', '.join(notes)}" if notes else ""
1226 pdata_summary += f" (OK{suffix})"
1227 else:
1228 issues = []
1229 if not p.get("mapped"):
1230 issues.append("unmapped")
1231 if p.get("truncated"):
1232 issues.append("truncated")
1233 if p.get("inverted_count"):
1234 issues.append(f"{p['inverted_count']} inverted")
1235 if p.get("out_of_bounds_count"):
1236 issues.append(f"{p['out_of_bounds_count']} out of bounds")
1237 if p.get("unsorted_count"):
1238 issues.append(f"{p['unsorted_count']} unsorted")
1239 if p.get("overlap_count"):
1240 issues.append(f"{p['overlap_count']} overlapping")
1241 pdata_summary += f" (INVALID: {', '.join(issues)})"
1242
1243 exp_summary = f"{r['export_count']:,}"
1244 fwd_count = r.get("forwarder_count", 0)
1245 inv_count = r.get("invalid_export_count", 0)
1246 exp_parts = []
1247 if fwd_count > 0:
1248 exp_parts.append(f"{fwd_count} forwarded")
1249 if inv_count > 0:
1250 inv_details = [f"{inv['symbol']} ({inv['reason']})" for inv in r.get("invalid_exports", [])]
1251 details_str = f": {', '.join(inv_details)}" if inv_details else ""
1252 exp_parts.append(f"INVALID: {inv_count} invalid{details_str}")
1253 if exp_parts:
1254 exp_summary += f" ({'; '.join(exp_parts)})"
1255
896 out = [f"# {r['file']}", "", 1256 out = [f"# {r['file']}", "",
897 f"- {r['machine']}, {'DLL' if r['is_dll'] else 'EXE'}, subsystem {r['subsystem']}, {r['size']:,} bytes", 1257 f"- {r['machine']}, {'DLL' if r['is_dll'] else 'EXE'}, subsystem {r['subsystem']}, {r['size']:,} bytes",
898 f"- image base {r['image_base']}, size {r['size_of_image']:,}, entry RVA {r['entry_rva']}", 1258 f"- image base {r['image_base']}, size {r['size_of_image']:,}, entry RVA {r['entry_rva']}",
899 f"- relocations: {'yes' if r['has_relocs'] else 'NO (must load at preferred base)'}; " 1259 f"- relocations: {'yes' if r['has_relocs'] else 'NO (must load at preferred base)'}; "
900 f"ASLR flag: {r['dynamic_base']}", 1260 f"ASLR flag: {r['dynamic_base']}",
901 f"- .pdata functions: {r['pdata_functions']:,}; TLS callbacks: {r['tls_callbacks']}; exports: {r['export_count']}", 1261 f"- .pdata functions: {pdata_summary}; TLS callbacks: {r['tls_callbacks']}; exports: {exp_summary}",
902 "", "## Sections", "", "| name | rva | vsize | exec | write | entropy | |", "|---|---|---|---|---|---|---|"] 1262 "", "## Sections", "", "| name | rva | vsize | exec | write | entropy | |", "|---|---|---|---|---|---|---|"]
903 for s in r["sections"]: 1263 for s in r["sections"]:
904 flag = "**encrypted?**" if s["looks_encrypted"] else "" 1264 flag = "**encrypted?**" if s["looks_encrypted"] else ""
@@ -931,6 +1291,16 @@ def to_markdown(r: dict) -> str:
931 out.append(", ".join(f"`{f}`" for f in imp["functions"])) 1291 out.append(", ".join(f"`{f}`" for f in imp["functions"]))
932 out.append("") 1292 out.append("")
933 out += resources_markdown(r.get("resources")) 1293 out += resources_markdown(r.get("resources"))
1294 forwarders = r.get("forwarders", {})
1295 if forwarders:
1296 out += ["", "## Forwarded Exports", "", "| export | target |", "|---|---|"]
1297 items = sorted(forwarders.items())
1298 for exp_name, target in items[:50]:
1299 esc_name = exp_name.replace("|", r"\|")
1300 esc_target = target.replace("|", r"\|")
1301 out.append(f"| `{esc_name}` | `{esc_target}` |")
1302 if len(items) > 50:
1303 out.append(f"| ... and {len(items) - 50} more | |")
934 return "\n".join(out) + "\n" 1304 return "\n".join(out) + "\n"
935 1305
936 1306
@@ -1063,7 +1433,15 @@ def main(argv: list[str] | None = None) -> int:
1063 enc = [s["name"] for s in r["sections"] if s["looks_encrypted"]] 1433 enc = [s["name"] for s in r["sections"] if s["looks_encrypted"]]
1064 shim = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "shim") 1434 shim = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "shim")
1065 unverified = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "unverified") 1435 unverified = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "unverified")
1066 print(f"{r['file']:<40} {r['machine']:<7} subsys={r['subsystem']!s:<7} pdata={r['pdata_functions']:<7} " 1436 pdata_status = ""
1437 p = r.get("pdata")
1438 if p and p.get("present"):
1439 if p.get("format"):
1440 pdata_status = p["format"]
1441 else:
1442 pdata_status = "OK" if p.get("valid") else "INVALID"
1443 pdata_col = f"{r['pdata_functions']} {pdata_status}".strip()
1444 print(f"{r['file']:<40} {r['machine']:<7} subsys={r['subsystem']!s:<7} pdata={pdata_col:<9} "
1067 f"shim-imports={shim:<5} encrypted={','.join(enc) or '-'}" 1445 f"shim-imports={shim:<5} encrypted={','.join(enc) or '-'}"
1068 + (f" unverified-imports={unverified}" if unverified else "")) 1446 + (f" unverified-imports={unverified}" if unverified else ""))
1069 note = system_dlls_note(r) 1447 note = system_dlls_note(r)