upleb.uk

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

summaryrefslogtreecommitdiff
path: root/scripts/windows-boot
diff options
context:
space:
mode:
authorMoonEyes <ducoinbenjamin@yahoo.fr>2026-11-28 14:26:09 +0100
committerGitHub <noreply@github.com>2026-11-28 14:26:09 +0100
commit7ce011205869b2e881a663e390d8317be5f562f3 (patch)
tree6efdaed9954921baaf970fdff867214dda75c67f /scripts/windows-boot
parent1a0e77ecb72bd538327fb631009dea5426b7c80a (diff)
parent056e6823217b5f2a1fd9b2556ba71fd41a757877 (diff)
Merge pull request #1772 from sodove/feat/windows-boot-mapped-image-stack
windows-boot: recover private stacks for manually mapped images
Diffstat (limited to 'scripts/windows-boot')
-rw-r--r--scripts/windows-boot/README.md30
-rw-r--r--scripts/windows-boot/mapped_stack.py313
2 files changed, 343 insertions, 0 deletions
diff --git a/scripts/windows-boot/README.md b/scripts/windows-boot/README.md
index ac76ecdaa..1ace54184 100644
--- a/scripts/windows-boot/README.md
+++ b/scripts/windows-boot/README.md
@@ -99,3 +99,33 @@ game processes on one GPU make both runs meaningless and can take the driver dow
99| `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only | 99| `minidump.py PID OUT.dmp` | a minidump through dbghelp's `MiniDumpWriteDump`. Do not use `rundll32 comsvcs.dll MiniDump`: Defender flags it. A dump holds game memory: local only |
100 100
101Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell). 101Each prints its usage with `-h` (Python) or `Get-Help` (PowerShell).
102
103## Recover a stack from a manually mapped image
104
105When the exception stack stops inside the mapped executable, run `mapped_stack.py` on the existing
106private dump. Supply the exact PE from the crashing build and an x64 CDB from Debugging Tools for
107Windows. If CDB is on your PATH, omit `--cdb`. The optional `--symbols` takes one local directory
108containing the matching runtime images and PDBs.
109
110```powershell
111py -3 -I scripts\windows-boot\mapped_stack.py D:\runs\fault\crash.dmp D:\package\title.exe --symbols D:\build\RelWithDebInfo --cdb "C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe"
112```
113
114The command derives the mapping base, including a relocated base, by locating a unique captured
115instruction window in an executable section of the supplied PE. It checks for a file-backed x64
116unwind entry at the exception RIP and compares captured bytes from the first header page and that
117function's unwind metadata when available.
118A small dump can establish a local code match only. Use the original image even if another build
119has the same function. Exit-only snapshots, faults outside the supplied image, leaf functions
120without unwind entries, and missing, patched or ambiguous instruction windows cannot establish
121this stack.
122
123CDB reads the exception context and uses the disk image's unwind data to recover callers. The
124script makes a temporary copy of the PE beside the dump under the debugger alias `leonida_mapped`.
125It disables network symbols and writes private frame rows to a new `mapped-stack.txt` beside the
126dump. Use `--output` for a different new file. A successful walk recovers at least one caller and
127can stop when later stack memory or module information is missing. Keep dumps and reports outside
128the checkout and share only the outcome and frame count.
129
130Run the synthetic regression tests with `py -3 -I tests\test_mapped_stack.py`. To include the
131native CDB walk, put x64 CDB on PATH or set `LEONIDA_TEST_CDB` to its full path.
diff --git a/scripts/windows-boot/mapped_stack.py b/scripts/windows-boot/mapped_stack.py
new file mode 100644
index 000000000..b88a4eb19
--- /dev/null
+++ b/scripts/windows-boot/mapped_stack.py
@@ -0,0 +1,313 @@
1"""Recover a private x64 exception stack with an explicitly supplied, manually mapped PE."""
2import argparse
3from dataclasses import dataclass
4import mmap
5import os
6from pathlib import Path, PureWindowsPath
7import re
8import shutil
9import struct
10import subprocess
11import sys
12import tempfile
13
14ROOT = Path(__file__).resolve().parents[2]
15sys.path.insert(0, str(ROOT / "tools"))
16from pe_inspect import DIR_EXCEPTION, PeFormatError, PeImage
17from report_paths import same_report_path
18
19
20def require(condition, message):
21 if not condition:
22 raise ValueError(message)
23
24
25def bounds(offset, size, end):
26 require(0 <= offset <= end and 0 <= size <= end - offset, "truncated or invalid binary structure")
27
28
29def read(data, fmt, offset):
30 fmt = "<" + fmt
31 bounds(offset, struct.calcsize(fmt), len(data))
32 return struct.unpack_from(fmt, data, offset)
33
34
35def records(start, count, stride, end):
36 bounds(start, count * stride, end)
37 return range(start, start + count * stride, stride)
38
39
40def dump_streams(dump):
41 magic, version, count, directory = read(dump, "4sIII", 0)
42 require(magic == b"MDMP" and version & 0xffff == 0xa793, "expected a Windows minidump")
43 streams = {}
44 for pos in records(directory, count, 12, len(dump)):
45 kind, size, offset = read(dump, "III", pos)
46 if kind in (4, 5, 6, 7, 9):
47 require(kind not in streams, "duplicate minidump stream")
48 bounds(offset, size, len(dump))
49 streams[kind] = (offset, offset + size)
50 return streams
51
52
53def stream(streams, kind, minimum):
54 require(kind in streams, "required minidump stream missing")
55 start, end = streams[kind]
56 bounds(start, minimum, end)
57 return start, end
58
59
60def exception_context(dump, streams):
61 system, _ = stream(streams, 7, 2)
62 require(read(dump, "H", system)[0] == 9, "expected an AMD64 dump")
63 require(6 in streams, "dump has no exception context (exit snapshots are unsupported)")
64 exc, _ = stream(streams, 6, 168)
65 size, offset = read(dump, "II", exc + 160)
66 bounds(offset, size, len(dump))
67 require(size >= 256 and read(dump, "I", offset + 48)[0] & 0x100001 == 0x100001,
68 "missing AMD64 control context")
69 return read(dump, "I", exc)[0], read(dump, "Q", offset + 248)[0], read(dump, "Q", offset + 152)[0]
70
71
72def captured_ranges(dump, streams):
73 if 5 in streams: # MINIDUMP_MEMORY_LIST
74 pos, end = stream(streams, 5, 4)
75 for entry in records(pos + 4, read(dump, "I", pos)[0], 16, end):
76 address, size, offset = read(dump, "QII", entry)
77 bounds(offset, size, len(dump))
78 yield address, size, offset
79 if 9 in streams: # MINIDUMP_MEMORY64_LIST stores all bytes consecutively
80 pos, end = stream(streams, 9, 16)
81 count, offset = read(dump, "QQ", pos)
82 for entry in records(pos + 16, count, 16, end):
83 address, size = read(dump, "QQ", entry)
84 bounds(offset, size, len(dump))
85 yield address, size, offset
86 offset += size
87
88
89def instruction_window(dump, streams, rip):
90 window = None
91 for address, size, offset in captured_ranges(dump, streams):
92 if address <= rip < address + size:
93 start, end = max(rip - 128, address), min(rip + 128, address + size)
94 sample = (start, dump[offset + start - address:offset + end - address])
95 require(window is None or sample == window, "ambiguous instruction capture")
96 window = sample
97 require(window is not None, "exception instructions were not captured")
98 require(len(window[1]) >= 32 and len(set(window[1])) >= 8, "insufficient distinctive instruction bytes")
99 return window
100
101
102@dataclass(frozen=True)
103class Mapping:
104 base: int
105 size: int
106 timestamp: int
107 thread: int
108 rip: int
109 rsp: int
110
111
112def mapping_base(pe, address, sample):
113 # Locate the captured instructions in executable disk bytes. This gives the
114 # actual mapping even after rebasing, without trusting the PE preferred base.
115 base = None
116 previous_end = pe.size_of_headers
117 bounds(0, previous_end, min(pe.size_of_image, len(pe.data)))
118 for section in sorted(pe.sections, key=lambda item: item["rva"]):
119 rva, raw, raw_size = section["rva"], section["rawptr"], section["rawsize"]
120 span = section["vsize"] or raw_size
121 require(rva >= previous_end, "overlapping PE sections")
122 bounds(rva, span, pe.size_of_image)
123 bounds(raw, raw_size, len(pe.data))
124 previous_end = rva + span
125 if not section["exec"]:
126 continue
127 raw_end = raw + min(span, raw_size)
128 pos = pe.data.find(sample, raw, raw_end)
129 if pos >= 0:
130 require(base is None and pe.data.find(sample, pos + 1, raw_end) < 0,
131 "instructions match multiple locations in the image")
132 base = address - (rva + pos - raw)
133 require(base is not None, "exception instructions do not match this PE")
134 require(base > 0 and base % 0x10000 == 0 and base + pe.size_of_image <= 2**64, "invalid inferred mapping base")
135 return base
136
137
138def verify_unwind(dump, streams, pe, base, rip):
139 # A synthetic module label alone does not prove that CDB has unwind data.
140 # Require a file-backed RUNTIME_FUNCTION for the fault, and cross-check its
141 # metadata and the PE headers wherever the dump actually captured them.
142 pdata, pdata_size = pe.directory(DIR_EXCEPTION)
143 pdata_off = pe.offset(pdata, pdata_size)
144 require(pdata >= pe.size_of_headers and pdata_off is not None and pdata_size % 12 == 0,
145 "missing or invalid x64 exception directory")
146 metadata = [(base, min(pe.size_of_headers, 4096), 0)]
147 function_found = False
148 for entry in range(pdata_off, pdata_off + pdata_size, 12):
149 begin, end, unwind = read(pe.data, "III", entry)
150 if begin <= rip - base < end:
151 require(not function_found, "ambiguous x64 function entry")
152 function_found = True
153 unwind_off = pe.offset(unwind, 4)
154 require(unwind >= pe.size_of_headers and unwind_off is not None
155 and pe.data[unwind_off] & 7 in (1, 2), "unsupported x64 unwind information")
156 # The header is followed by an array of 2-byte unwind codes.
157 unwind_size = 4 + pe.data[unwind_off + 2] * 2
158 require(pe.offset(unwind, unwind_size) is not None, "truncated x64 unwind codes")
159 metadata.extend([(base + pdata + entry - pdata_off, 12, entry), (base + unwind, unwind_size, unwind_off)])
160 require(function_found, "no x64 unwind entry covers the exception instructions")
161 for address, length, offset in captured_ranges(dump, streams):
162 for start, count, raw in metadata:
163 lo, hi = max(address, start), min(address + length, start + count)
164 if lo < hi:
165 disk = pe.data[raw + lo - start:raw + hi - start]
166 require(dump[offset + lo - address:offset + hi - address] == disk,
167 "captured image metadata differs from the supplied PE")
168
169
170def check_registered_modules(dump, streams, base, size):
171 modules, end = stream(streams, 4, 4)
172 for entry in records(modules + 4, read(dump, "I", modules)[0], 108, end):
173 loaded, extent = read(dump, "QI", entry)
174 require(base + size <= loaded or base >= loaded + extent, "mapping overlaps a registered module")
175 name_rva = read(dump, "I", entry + 20)[0]
176 length = read(dump, "I", name_rva)[0]
177 require(0 < length <= 65534 and length % 2 == 0, "invalid registered module name")
178 start = name_rva + 4
179 bounds(start, length, len(dump))
180 name = PureWindowsPath(dump[start:start + length].decode("utf-16-le"))
181 require(name.stem.casefold() != "leonida_mapped", "staging name already used by a registered module")
182 require((len(name.parts) == 1 and not name.anchor)
183 or re.fullmatch(r"[A-Za-z]:", name.drive) and name.is_absolute(),
184 "dump contains a nonlocal module path")
185 if os.name == "nt" and name.drive:
186 require(local_drive(name.anchor), "dump references a module on a nonlocal drive")
187
188
189def identify(dump, image):
190 streams = dump_streams(dump)
191 thread, rip, rsp = exception_context(dump, streams)
192 address, sample = instruction_window(dump, streams, rip)
193 pe = PeImage(image)
194 require(pe.machine == 0x8664 and pe.is64, "expected an AMD64 PE32+ image")
195 base = mapping_base(pe, address, sample)
196 check_registered_modules(dump, streams, base, pe.size_of_image)
197 verify_unwind(dump, streams, pe, base, rip)
198 return Mapping(base, pe.size_of_image, pe.timestamp, thread, rip, rsp)
199
200
201ROW = re.compile(r"^\s*([0-9a-f]+)\s+[0-9a-f]{8}\x60[0-9a-f]{8}\s+[0-9a-f]{8}\x60[0-9a-f]{8}\s+(.+)", re.I)
202BEGIN = "LEONIDA_STACK_BEGIN"
203END = "LEONIDA_STACK_END"
204
205
206def stack_rows(output, mapping):
207 lines = output.splitlines()
208 require(lines.count(BEGIN) == 1 and lines.count(END) == 1, "CDB did not finish the stack walk")
209 report = lines[lines.index(BEGIN) + 1:lines.index(END)]
210 require(report and report[0].strip().lower() == f"{mapping.rip:x} {mapping.rsp:x}",
211 "CDB could not select the dump's exception context")
212 rows = []
213 for line in report[1:]:
214 if "following frames may be wrong" in line.lower():
215 break
216 frame = ROW.match(line)
217 if frame:
218 require(int(frame[1], 16) == len(rows), "unexpected CDB frame sequence")
219 if not rows:
220 require(re.match(r"leonida_mapped(?:[+!]|$)", frame[2], re.I), "CDB did not load the mapped image")
221 rows.append(line.strip())
222 require(len(rows) >= 2, "CDB could not recover a caller")
223 return rows
224
225
226def debugger_stack(cdb, dump, symbols, scratch, mapping):
227 # CDB parses its own command language. Only parsed integers enter it. The
228 # PE always has the same safe filename in a new, private working directory.
229 command = (f".reload /f leonida_mapped.exe={mapping.base:x},{mapping.size:x},{mapping.timestamp:x}; "
230 f'~~[{mapping.thread:x}]s; .ecxr; .echo {BEGIN}; '
231 f'.printf "%I64x %I64x\\n", @rip, @rsp; kn 40; .echo {END}; q')
232 require(not any(c in str(scratch) for c in ";*"), "temporary directory cannot form a debugger search path")
233 search = str(scratch) if symbols is None else str(scratch) + ";" + str(symbols)
234 env = {key: value for key, value in os.environ.items() if key.upper() in {"SYSTEMROOT", "WINDIR", "SYSTEMDRIVE"}}
235 env.update(dict.fromkeys(("TEMP", "TMP", "LOCALAPPDATA", "APPDATA", "USERPROFILE"), str(scratch)))
236 run = subprocess.run([str(cdb), "-sins", "-sicv", "-netsyms:no", "-nosqm", "-noshell", "-y", search,
237 "-i", search, "-srcpath", str(scratch), "-z", str(dump), "-c", command],
238 cwd=scratch, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
239 stderr=subprocess.STDOUT, timeout=90)
240 require(run.returncode == 0, "CDB failed to analyze the dump")
241 return stack_rows(run.stdout.decode("utf-8", errors="replace"), mapping)
242
243
244def local_drive(anchor):
245 import ctypes
246 return ctypes.windll.kernel32.GetDriveTypeW(str(anchor)) in (2, 3, 5, 6)
247
248
249def local_path(path):
250 # Reject UNC, device namespace and mapped network drives before opening
251 # inputs or using a directory as a debugger search path.
252 absolute = Path(os.path.abspath(path))
253 require(re.fullmatch(r"[A-Za-z]:", absolute.drive) and local_drive(absolute.anchor),
254 "expected a local filesystem path")
255 resolved = absolute.resolve()
256 require(re.fullmatch(r"[A-Za-z]:", resolved.drive) and local_drive(resolved.anchor),
257 "path resolves outside the local filesystem")
258 return resolved
259
260
261def recover(args):
262 require(os.name == "nt", "the x64 Windows debugger is required")
263 dump, image = local_path(args.dump), local_path(args.image)
264 report = local_path(args.output) if args.output else dump.with_name("mapped-stack.txt")
265 require(not report.is_relative_to(ROOT) and not dump.parent.is_relative_to(ROOT),
266 "keep the dump and the private report outside the checkout")
267 require(not any(same_report_path(report, path) for path in (dump, image)), "report collides with an input")
268 require(not report.exists(), "output already exists; choose a fresh report path")
269 debugger = args.cdb or shutil.which("cdb.exe")
270 require(debugger, "x64 CDB not found; provide --cdb")
271 cdb = local_path(debugger)
272 symbols = local_path(args.symbols) if args.symbols else None
273 require(symbols is None or symbols.is_dir() and not any(c in str(symbols) for c in ";*"),
274 "--symbols requires a single local directory")
275 with tempfile.TemporaryDirectory(dir=dump.parent) as scratch:
276 staged = Path(scratch) / "leonida_mapped.exe"
277 shutil.copyfile(image, staged)
278 with dump.open("rb") as df, staged.open("rb") as ef:
279 with mmap.mmap(df.fileno(), 0, access=mmap.ACCESS_READ) as md, \
280 mmap.mmap(ef.fileno(), 0, access=mmap.ACCESS_READ) as pe:
281 mapping = identify(md, pe)
282 rows = debugger_stack(cdb, dump, symbols, scratch, mapping)
283 # On Windows rename publishes the completed report and refuses an existing
284 # destination, including one created by a concurrent analysis.
285 with tempfile.TemporaryDirectory(dir=report.parent) as pending:
286 finished = Path(pending) / "stack.txt"
287 finished.write_text("\n".join(rows) + "\n", encoding="utf-8", newline="\n")
288 finished.rename(report)
289 print(f"Recovered {len(rows)} frames. Keep the stack report private.")
290
291
292def main():
293 parser = argparse.ArgumentParser(description=__doc__)
294 parser.add_argument("dump", type=Path, help="private Windows exception minidump")
295 parser.add_argument("image", type=Path, help="the exact mapped PE from the crashing build")
296 parser.add_argument("--symbols", type=Path, help="local directory with matching runtime images and PDBs")
297 parser.add_argument("--cdb", type=Path, help="path to the trusted x64 cdb.exe (default: search PATH)")
298 parser.add_argument("--output", type=Path, help="new private output path (default: mapped-stack.txt beside dump)")
299 args = parser.parse_args()
300 try:
301 recover(args)
302 except PeFormatError:
303 parser.exit(1, "invalid PE image\n")
304 except ValueError as error:
305 parser.exit(1, f"{error}\n")
306 except subprocess.TimeoutExpired:
307 parser.exit(1, "CDB timed out\n")
308 except OSError as error:
309 parser.exit(1, f"local file or debugger operation failed ({type(error).__name__})\n")
310
311
312if __name__ == "__main__":
313 main()