upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNolan Cotter <186326284+NolanCotter@users.noreply.github.com>2026-11-22 16:54:55 -0700
committerNolan Cotter <186326284+NolanCotter@users.noreply.github.com>2026-11-22 17:02:10 -0700
commitd122c4f75c52516dbfbcdd357c2ee8a11ebca28a (patch)
treebba3636cdde8aa82684024bf9f78233b617834ef
parent2be25cee2c87c369bb2e5446746f9650c01d7ba7 (diff)
tools: import_inventory normalises DLL names and reports shared tables per DLL
Review findings on #2490: descriptors sharing one lookup table lost the later DLL's association (the walk was deduplicated before the DLL was attached), and names like "GameInput" or "gameinput.dll." reported as a "gameinput" host module while the loader keys them gameinput.dll. Lookup tables now parse once per RVA into a name cache and emit per descriptor, matching the loader's per-IAT binding; the emitted pair count stays under MAX_TOTAL_ENTRIES. DLL names go through a port of pe_loader.cpp's dll_key (basename, lower, one trailing dot dropped, .dll added when there is no extension) at both input boundaries and in summarize(), so the report groups and routes on the loader's key. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
-rw-r--r--tests/test_import_inventory.py49
-rw-r--r--tools/import_inventory.py60
2 files changed, 89 insertions, 20 deletions
diff --git a/tests/test_import_inventory.py b/tests/test_import_inventory.py
index 96b26c48a..bd7bf35fa 100644
--- a/tests/test_import_inventory.py
+++ b/tests/test_import_inventory.py
@@ -157,6 +157,28 @@ class ImportListTest(unittest.TestCase):
157 self.assertEqual(imports, [("ok.dll", "Fine")]) 157 self.assertEqual(imports, [("ok.dll", "Fine")])
158 self.assertEqual(bad, 3) 158 self.assertEqual(bad, 3)
159 159
160 def test_dll_names_normalise_like_the_loader(self):
161 # pe_loader.cpp's dll_key: ".dll" is added when there is no extension, one trailing '.' is
162 # dropped, a directory part is stripped — "GameInput" and "gameinput.dll." key gameinput.dll.
163 imports, bad = inv.parse_import_lines([
164 "GameInput!GameInputCreate",
165 "gameinput.dll.!GameInputCreate",
166 "dir\\XMem.DLL!XMemAlloc",
167 ])
168 self.assertEqual(imports, [("gameinput.dll", "GameInputCreate"),
169 ("gameinput.dll", "GameInputCreate"),
170 ("xmem.dll", "XMemAlloc")])
171 self.assertEqual(bad, 0)
172
173 def test_dll_key_edge_cases(self):
174 # The same rules the C++ applies, including the odd corners: only one trailing dot is
175 # dropped, and a name that is all extension keeps it.
176 self.assertEqual(inv.dll_key("GameInput"), "gameinput.dll")
177 self.assertEqual(inv.dll_key("gameinput.dll."), "gameinput.dll")
178 self.assertEqual(inv.dll_key("gameinput.."), "gameinput.")
179 self.assertEqual(inv.dll_key("api-ms-win-core-file-l2-1-0.dll"),
180 "api-ms-win-core-file-l2-1-0.dll")
181
160 182
161class PeParseTest(unittest.TestCase): 183class PeParseTest(unittest.TestCase):
162 @classmethod 184 @classmethod
@@ -239,8 +261,9 @@ class PeParseTest(unittest.TestCase):
239 with self.assertRaisesRegex(inv.PeFormatError, "unreadable name"): 261 with self.assertRaisesRegex(inv.PeFormatError, "unreadable name"):
240 inv.pe_imports(path) 262 inv.pe_imports(path)
241 263
242 def test_shared_thunk_table_is_walked_once(self): 264 def test_shared_thunk_table_reports_each_dll(self):
243 # Two descriptors pointing at one lookup table report one set of imports, not two. 265 # Two descriptors pointing at one lookup table parse it once, but the loader binds each
266 # descriptor's IAT separately, so both DLLs get the association.
244 buf, place, directory = make_pe32plus() 267 buf, place, directory = make_pe32plus()
245 directory(1, 0x1100, 60) 268 directory(1, 0x1100, 60)
246 place(0x1100, struct.pack("<IIIII", 0x1200, 0, 0, 0x1300, 0x1240)) 269 place(0x1100, struct.pack("<IIIII", 0x1200, 0, 0, 0x1300, 0x1240))
@@ -250,7 +273,20 @@ class PeParseTest(unittest.TestCase):
250 place(0x1320, b"xtest2.dll\0") 273 place(0x1320, b"xtest2.dll\0")
251 place(0x1400, b"\x00\x00" + b"XTestFunc\0") 274 place(0x1400, b"\x00\x00" + b"XTestFunc\0")
252 path = write_image(self.tmp.name, "shared.exe", bytes(buf)) 275 path = write_image(self.tmp.name, "shared.exe", bytes(buf))
253 self.assertEqual(inv.pe_imports(path), [("xtest.dll", "XTestFunc")]) 276 self.assertEqual(inv.pe_imports(path),
277 [("xtest.dll", "XTestFunc"), ("xtest2.dll", "XTestFunc")])
278
279 def test_descriptor_dll_name_normalises_like_the_loader(self):
280 # A descriptor naming "GameInput" binds the module the shims register — pe_loader.cpp's
281 # dll_key adds the extension; a bare name must not report a "gameinput" host import.
282 buf, place, directory = make_pe32plus()
283 directory(1, 0x1100, 40)
284 place(0x1100, struct.pack("<IIIII", 0x1200, 0, 0, 0x1300, 0x1240))
285 place(0x1200, struct.pack("<QQ", 0x1400, 0))
286 place(0x1300, b"GameInput\0")
287 place(0x1400, b"\x00\x00" + b"GameInputCreate\0")
288 path = write_image(self.tmp.name, "bare.exe", bytes(buf))
289 self.assertEqual(inv.pe_imports(path), [("gameinput.dll", "GameInputCreate")])
254 290
255 291
256class ShimTableTest(unittest.TestCase): 292class ShimTableTest(unittest.TestCase):
@@ -322,6 +358,13 @@ class ReportTest(unittest.TestCase):
322 self.assertEqual(len(rows), len(self.rows)) 358 self.assertEqual(len(rows), len(self.rows))
323 self.assertEqual(per_dll, self.per_dll) 359 self.assertEqual(per_dll, self.per_dll)
324 360
361 def test_unnormalised_names_route_as_their_key(self):
362 # summarize() must route on the loader's dll_key too: "GameInput" is the registered
363 # gameinput.dll, not a "gameinput" host module.
364 rows, per_dll = inv.summarize([("GameInput", "GameInputCreate")], self.implemented)
365 self.assertEqual(rows, [("gameinput.dll", "GameInputCreate", inv.HRESULT, inv.IMPLEMENTED)])
366 self.assertEqual(per_dll["gameinput.dll"], [1, 1, 0, 1, 0, 0])
367
325 def test_report_text(self): 368 def test_report_text(self):
326 text = inv.format_report(self.IMPORTS, self.implemented) 369 text = inv.format_report(self.IMPORTS, self.implemented)
327 self.assertIn("d3d12_xs.dll!D3D12XboxCreateDevice", text) 370 self.assertIn("d3d12_xs.dll!D3D12XboxCreateDevice", text)
diff --git a/tools/import_inventory.py b/tools/import_inventory.py
index 3bdcc104b..f700fdb19 100644
--- a/tools/import_inventory.py
+++ b/tools/import_inventory.py
@@ -14,6 +14,9 @@ what an unimplemented thunk returns under LEONIDA_UNIMPLEMENTED=fail — and is
14registrations in runtime/shims/*.cpp, mirroring the loader's routing: a registered ``dll!name`` binds to the 14registrations in runtime/shims/*.cpp, mirroring the loader's routing: a registered ``dll!name`` binds to the
15shim; an unregistered import on a module the shims own binds to the unimplemented-import thunk; anything else 15shim; an unregistered import on a module the shims own binds to the unimplemented-import thunk; anything else
16binds to the host Windows DLL (when the host has it — the tool reports the route, not the host's exports). 16binds to the host Windows DLL (when the host has it — the tool reports the route, not the host's exports).
17
18DLL names are reported under the loader's key — pe_loader.cpp's dll_key(), the LoadLibrary file-name rule —
19so an import naming ``GameInput`` or ``gameinput.dll.`` groups and routes as ``gameinput.dll``.
17""" 20"""
18from __future__ import annotations 21from __future__ import annotations
19 22
@@ -84,8 +87,19 @@ def classify(dll: str, name: str) -> str:
84 return OTHER 87 return OTHER
85 88
86 89
90def dll_key(name: str) -> str:
91 """Port of pe_loader.cpp's dll_key(): the LoadLibrary file-name rule on a module name — basename only,
92 lower-case, one trailing '.' dropped, '.dll' added when the name has no extension. An import naming
93 "GameInput" or "gameinput.dll." resolves to gameinput.dll, the module the shims register."""
94 name = name[max(name.rfind("\\"), name.rfind("/")) + 1:].lower()
95 if name.endswith("."):
96 return name[:-1]
97 return name if "." in name else name + ".dll"
98
99
87def parse_import_lines(lines) -> tuple[list[tuple[str, str]], int]: 100def parse_import_lines(lines) -> tuple[list[tuple[str, str]], int]:
88 """(dll, name) pairs from `dll!function` lines, and the count of lines skipped as malformed.""" 101 """(dll, name) pairs from `dll!function` lines, and the count of lines skipped as malformed. The DLL part
102 comes back under the loader's dll_key."""
89 imports, bad = [], 0 103 imports, bad = [], 0
90 for line in lines: 104 for line in lines:
91 line = line.strip() 105 line = line.strip()
@@ -95,7 +109,7 @@ def parse_import_lines(lines) -> tuple[list[tuple[str, str]], int]:
95 if not bang or not dll.strip() or not name.strip(): 109 if not bang or not dll.strip() or not name.strip():
96 bad += 1 110 bad += 1
97 continue 111 continue
98 imports.append((dll.strip().lower(), name.strip())) 112 imports.append((dll_key(dll.strip()), name.strip()))
99 return imports, bad 113 return imports, bad
100 114
101 115
@@ -104,7 +118,7 @@ class PeFormatError(ValueError):
104 118
105 119
106MAX_ENTRIES = 65536 # a table this long is not a table; stops a malformed image from looping forever 120MAX_ENTRIES = 65536 # a table this long is not a table; stops a malformed image from looping forever
107MAX_TOTAL_ENTRIES = 262144 # a bound over every table together, so many tables cannot loop forever either 121MAX_TOTAL_ENTRIES = 262144 # bounds the table entries parsed and the (dll, name) pairs emitted
108 122
109 123
110def _cstring(data: bytes, offset: int, limit: int = 4097) -> str | None: 124def _cstring(data: bytes, offset: int, limit: int = 4097) -> str | None:
@@ -162,14 +176,17 @@ def pe_imports(path: str) -> list[tuple[str, str]]:
162 return None if at is None else _cstring(data, at) 176 return None if at is None else _cstring(data, at)
163 177
164 out = [] 178 out = []
165 seen_tables = set() # thunk tables already walked: descriptors may share one, and the entries are the same 179 tables = {} # lookup-table RVA -> symbol names, parsed once per table
166 total = 0 180 total = 0
167 181
168 def walk_thunks(dll: str, lookup: int) -> None: 182 def walk_table(lookup: int) -> list[str]:
183 """The symbol names one lookup table lists. Descriptors may share a table; the loader still binds
184 each descriptor's IAT separately, so the names emit per DLL, but the table parses only once."""
169 nonlocal total 185 nonlocal total
170 if not lookup or lookup in seen_tables: 186 names = tables.get(lookup)
171 return 187 if names is not None:
172 seen_tables.add(lookup) 188 return names
189 names = []
173 for j in range(MAX_ENTRIES): 190 for j in range(MAX_ENTRIES):
174 entry = offset(lookup + j * 8) 191 entry = offset(lookup + j * 8)
175 if entry is None or entry + 8 > len(data): 192 if entry is None or entry + 8 > len(data):
@@ -181,12 +198,22 @@ def pe_imports(path: str) -> list[tuple[str, str]]:
181 if total > MAX_TOTAL_ENTRIES: 198 if total > MAX_TOTAL_ENTRIES:
182 raise PeFormatError(f"more than {MAX_TOTAL_ENTRIES} import entries") 199 raise PeFormatError(f"more than {MAX_TOTAL_ENTRIES} import entries")
183 if value & (1 << 63): 200 if value & (1 << 63):
184 out.append((dll, f"#{value & 0xFFFF}")) 201 names.append(f"#{value & 0xFFFF}")
185 continue 202 continue
186 name = string_at((value & 0x7FFFFFFF) + 2) # skip the 2-byte hint 203 name = string_at((value & 0x7FFFFFFF) + 2) # skip the 2-byte hint
187 if name is None: 204 if name is None:
188 raise PeFormatError("an import thunk points at an unreadable name") 205 raise PeFormatError("an import thunk points at an unreadable name")
189 out.append((dll, name)) 206 names.append(name)
207 tables[lookup] = names
208 return names
209
210 def walk_thunks(dll: str, lookup: int) -> None:
211 if not lookup:
212 return
213 names = walk_table(lookup)
214 if len(out) + len(names) > MAX_TOTAL_ENTRIES:
215 raise PeFormatError(f"more than {MAX_TOTAL_ENTRIES} import entries")
216 out.extend((dll, name) for name in names)
190 217
191 # Data directory entry 1. The loader stops the table at the first descriptor with Name == 0 and fails on an 218 # Data directory entry 1. The loader stops the table at the first descriptor with Name == 0 and fails on an
192 # unreadable name; read_string throws there. 219 # unreadable name; read_string throws there.
@@ -204,7 +231,7 @@ def pe_imports(path: str) -> list[tuple[str, str]]:
204 dll = string_at(name_rva) 231 dll = string_at(name_rva)
205 if dll is None: 232 if dll is None:
206 raise PeFormatError("an import descriptor points at an unreadable DLL name") 233 raise PeFormatError("an import descriptor points at an unreadable DLL name")
207 walk_thunks(dll.lower(), oft if oft else iat_rva) 234 walk_thunks(dll_key(dll), oft if oft else iat_rva)
208 235
209 # Data directory entry 13: delay imports, which the loader binds eagerly — the same checks it makes on an 236 # Data directory entry 13: delay imports, which the loader binds eagerly — the same checks it makes on an
210 # IMAGE_DELAYLOAD_DESCRIPTOR (32 bytes; version-2 fields are RVAs). 237 # IMAGE_DELAYLOAD_DESCRIPTOR (32 bytes; version-2 fields are RVAs).
@@ -227,7 +254,7 @@ def pe_imports(path: str) -> list[tuple[str, str]]:
227 dll = string_at(name_rva) 254 dll = string_at(name_rva)
228 if dll is None: 255 if dll is None:
229 raise PeFormatError("a delay-import descriptor points at an unreadable DLL name") 256 raise PeFormatError("a delay-import descriptor points at an unreadable DLL name")
230 walk_thunks(dll.lower(), int_rva) 257 walk_thunks(dll_key(dll), int_rva)
231 return out 258 return out
232 259
233 260
@@ -377,13 +404,12 @@ def owned_dlls(implemented: set[str]) -> frozenset[str]:
377 404
378 405
379def summarize(imports: list[tuple[str, str]], implemented: set[str]): 406def summarize(imports: list[tuple[str, str]], implemented: set[str]):
380 """(rows, per_dll): rows are (dll, name, class, binding) sorted and deduplicated, where binding is 407 """(rows, per_dll): rows are (dll, name, class, binding) sorted and deduplicated on the loader's
381 IMPLEMENTED, HOST or THUNK, mirroring the loader's routing order; per_dll maps a dll to 408 dll_key, where binding is IMPLEMENTED, HOST or THUNK, mirroring the loader's routing order; per_dll
382 [imports, hresult, other, implemented, host, unimplemented thunk].""" 409 maps a dll to [imports, hresult, other, implemented, host, unimplemented thunk]."""
383 owned = owned_dlls(implemented) 410 owned = owned_dlls(implemented)
384 rows = [] 411 rows = []
385 for dll, name in sorted(set(imports)): 412 for dll, name in sorted({(dll_key(d), n) for d, n in imports}):
386 dll = dll.lower()
387 cls = classify(dll, name) 413 cls = classify(dll, name)
388 if f"{dll}!{name}" in implemented: 414 if f"{dll}!{name}" in implemented:
389 binding = IMPLEMENTED 415 binding = IMPLEMENTED