upleb.uk

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

summaryrefslogtreecommitdiff
path: root/tools
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 /tools
parent7c245a359b8bdb6d9985c6d3ffd2bee0609de911 (diff)
parent895c472faa1c3d44a1358640f09c1f10e6a6a876 (diff)
Merge origin/main into carry/1346
Diffstat (limited to 'tools')
-rw-r--r--tools/awc_shorts.py12
-rw-r--r--tools/game_gate.py133
-rw-r--r--tools/pe_inspect.py416
3 files changed, 534 insertions, 27 deletions
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)