"""Unit tests for tools/pe_inspect.py: standard-library PE parsing, directory walks and the report it writes. The fixtures are built here, byte by byte, so the test needs no game files and no third-party packages. The 32-bit image exists because a delay-import descriptor without dlattrRva stores virtual addresses in 32-bit fields: that form can only be built for an image whose base fits in 32 bits, and it is what the parser has to convert. python -I tests/test_pe_inspect.py """ import contextlib import io import json import os import re import struct import sys import shutil import tempfile import unittest from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) TOOLS_DIR = os.path.join(ROOT, "tools") if TOOLS_DIR not in sys.path: sys.path.insert(0, TOOLS_DIR) import pe_inspect # noqa: E402 IMAGE_BASE = 0x180000000 BASE32 = 0x10000000 TEXT_RVA = 0x1000 TEXT_RAW = 0x200 TEXT_SIZE = 0x1000 def place(buf: bytearray, rva: int, blob: bytes) -> None: at = TEXT_RAW + (rva - TEXT_RVA) assert at + len(blob) <= len(buf), f"fixture does not fit at {rva:#x}" buf[at:at + len(blob)] = blob def build_image(is64: bool = True, with_directories: bool = True) -> bytes: """A one-section image with imports (by name and by ordinal), a delay import, exports (two named, one ordinal-only), .pdata entries, TLS callbacks and a relocation directory. The 32-bit build also carries a delay-import descriptor whose fields are virtual addresses rather than RVAs.""" base = IMAGE_BASE if is64 else BASE32 opt_size = 240 if is64 else 224 assert 0x58 + opt_size + 40 <= TEXT_RAW buf = bytearray(TEXT_RAW + TEXT_SIZE) buf[0:2] = b"MZ" struct.pack_into(" bytes: """build_image() with its export directory replaced: `slots` is AddressOfFunctions, `names` maps an index into it to the export name that points at it.""" buf = bytearray(build_image(is64=is64)) img = pe_inspect.PeImage(bytes(buf)) dir_entry = (0x58 + (112 if is64 else 96)) + pe_inspect.DIR_EXPORT * 8 struct.pack_into(" dll_rva == 0 -> must be skipped, not "MZ". place(data, 0x1520 + 4, struct.pack(" list[str]: return pe_inspect._exports(pe_inspect.PeImage(data)) def test_unused_ordinal_slot_is_not_an_export(self): for is64 in (True, False): data = with_exports([0x1000, 0, 0x1010], {0: "Alpha"}, is64=is64) self.assertEqual(self.exports_of(data), ["Alpha", "#12"]) path = os.path.join(self.dir, "gap.dll") with open(path, "wb") as f: f.write(data) report = pe_inspect.inspect(path, None) self.assertEqual(report["exports"], ["Alpha", "#12"]) self.assertEqual(report["export_count"], 2) def test_named_exports_require_a_populated_address_table_slot(self) -> None: for is64 in (True, False): with self.subTest(is64=is64): data = bytearray(with_exports([0x1000, 0, FORWARDER, 0x1010], {0: "Alpha", 1: "Empty", 2: "Forwarded", 4: "Outside"}, is64=is64)) # The bytes after AddressOfFunctions are not part of its declared four slots. place(data, EXPORT_FUNCS + 16, struct.pack(" str: err = io.StringIO() with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): self.assertEqual(pe_inspect.main([*images, "--out", out]), 0) return err.getvalue() def read_report(self, out: str, name: str) -> tuple[dict, str]: with open(os.path.join(out, name + ".json"), encoding="utf-8") as f: data = json.load(f) with open(os.path.join(out, name + ".md"), encoding="utf-8") as f: return data, f.read() def test_cli_exe_and_dll_with_the_same_stem_get_separate_reports(self): sub = os.path.join(self.dir, "stem") os.makedirs(sub) exe, dll = os.path.join(sub, "game.exe"), os.path.join(sub, "game.dll") with open(exe, "wb") as f: f.write(build_image(is64=False)) with open(dll, "wb") as f: f.write(build_image()) out = os.path.join(self.dir, "reports_stem") self.run_cli([exe, dll], out) self.assertEqual(sorted(os.listdir(out)), ["game.dll.json", "game.dll.md", "game.exe.json", "game.exe.md"]) exe_r, exe_md = self.read_report(out, "game.exe") dll_r, dll_md = self.read_report(out, "game.dll") self.assertEqual((exe_r["file"], exe_r["machine"]), ("game.exe", self.report32["machine"])) self.assertEqual((dll_r["file"], dll_r["machine"]), ("game.dll", "x86-64")) self.assertNotEqual(exe_r["machine"], dll_r["machine"]) self.assertIn("# game.exe", exe_md) self.assertIn("# game.dll", dll_md) def test_cli_same_file_name_from_two_directories_gets_a_numbered_suffix(self): a, b = os.path.join(self.dir, "a"), os.path.join(self.dir, "b") os.makedirs(a) os.makedirs(b) first, second = os.path.join(a, "x.exe"), os.path.join(b, "x.exe") with open(first, "wb") as f: f.write(build_image()) with open(second, "wb") as f: f.write(build_image(is64=False)) out = os.path.join(self.dir, "reports_dup") err = self.run_cli([first, second, first], out) self.assertEqual(sorted(os.listdir(out)), ["x.exe-2.json", "x.exe-2.md", "x.exe.json", "x.exe.md"]) r1, _ = self.read_report(out, "x.exe") r2, _ = self.read_report(out, "x.exe-2") self.assertEqual(r1["machine"], "x86-64") self.assertEqual(r2["machine"], self.report32["machine"]) self.assertNotEqual(r1["machine"], r2["machine"]) self.assertIn("report written as x.exe-2.json", err) self.assertIn("given more than once", err) def check_same_image_under_another_folder(self, tag: str, link) -> None: a, b = os.path.join(self.dir, tag + "_a"), os.path.join(self.dir, tag + "_b") os.makedirs(a) os.makedirs(b) first, second = os.path.join(a, "x.exe"), os.path.join(b, "x.exe") with open(first, "wb") as f: f.write(build_image()) link(first, second) open(os.path.join(b, "xmem.dll"), "wb").close() out = os.path.join(self.dir, "reports_" + tag) self.run_cli([first, second], out) self.assertEqual(sorted(os.listdir(out)), ["x.exe-2.json", "x.exe-2.md", "x.exe.json", "x.exe.md"]) def resolves(report: dict) -> dict: return {(i["dll"], i["kind"]): i["where"] for i in report["imports"]} for name, img in (("x.exe", first), ("x.exe-2", second)): single = os.path.join(self.dir, "reports_" + tag + "_single_" + name) self.run_cli([img], single) combined, _ = self.read_report(out, name) alone, _ = self.read_report(single, "x.exe") self.assertEqual(resolves(combined), resolves(alone)) self.assertEqual(resolves(self.read_report(out, "x.exe")[0])[("xmem.dll", "normal")], "shim") self.assertEqual(resolves(self.read_report(out, "x.exe-2")[0])[("xmem.dll", "normal")], "bundled") def test_cli_symlinked_image_under_another_folder_gets_its_own_report(self): def link(src, dst): try: os.symlink(src, dst) except (OSError, NotImplementedError) as e: self.skipTest(f"os.symlink unavailable: {e}") self.check_same_image_under_another_folder("symlink", link) def test_cli_copied_image_under_another_folder_gets_its_own_report(self): self.check_same_image_under_another_folder("copy", shutil.copyfile) def test_cli_reports_a_non_pe_file(self): bad = os.path.join(self.dir, "not_pe_cli.bin") with open(bad, "wb") as f: f.write(b"MZ" + bytes(10)) err = io.StringIO() with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): self.assertEqual(pe_inspect.main([bad, "--out", os.path.join(self.dir, "reports2")]), 1) self.assertIn("not a PE image", err.getvalue()) def test_same_output_path_identity(self): a = os.path.join(self.dir, "test.exe") self.assertTrue(pe_inspect.same_output_path(a, a)) b = os.path.join(self.dir, "other.exe") self.assertFalse(pe_inspect.same_output_path(a, b)) def test_cli_refuses_to_overwrite_input_file_with_report(self): out = os.path.join(self.dir, "reports_collision") os.makedirs(out, exist_ok=True) colliding_file = os.path.join(out, "sample.dll.json") with open(colliding_file, "w", encoding="utf-8") as f: f.write("original preserved text") err = io.StringIO() with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): rc = pe_inspect.main([self.image, colliding_file, "--out", out]) self.assertEqual(rc, 1) self.assertIn("would overwrite input file", err.getvalue()) with open(colliding_file, "r", encoding="utf-8") as f: self.assertEqual(f.read(), "original preserved text") def test_cli_refuses_existing_file_as_out_dir(self): file_out = os.path.join(self.dir, "some_file.txt") with open(file_out, "w", encoding="utf-8") as f: f.write("file not dir") err = io.StringIO() with contextlib.redirect_stderr(err): self.assertEqual(pe_inspect.main([self.image, "--out", file_out]), 1) self.assertIn("path is a file, not a directory", err.getvalue()) OPT = 0x58 # where build_image puts the optional header class DirectoryCountTest(unittest.TestCase): """NumberOfRvaAndSizes counts the data directories; a slot past it is not one, whatever it holds.""" def report(self, count, is64=True): image = bytearray(build_image(is64=is64)) struct.pack_into(" bytes: return text.encode("utf-16-le") + b"\0\0" def vs_block(key: str, value: bytes = b"", children: tuple = (), text: bool = False) -> bytes: """One VS_VERSIONINFO-style block: header, key, value and children, each padded to 4 bytes.""" out = bytearray(6) + utf16z(key) out += bytes(-len(out) % 4) + value for child in children: out += bytes(-len(out) % 4) + child struct.pack_into(" bytes: """VS_VERSIONINFO: file version 1.2.3.4, product version 5.6.7.8, PRERELEASE and PRIVATEBUILD set, NT_WINDOWS32, APP; a 040904b0 string table holding VERSION_VALUES; a Translation of 0409/1200.""" fixed = struct.pack("<13I", signature, 0x10000, (1 << 16) | 2, (3 << 16) | 4, (5 << 16) | 6, (7 << 16) | 8, 0x3F, 0x02 | 0x08 | 0x40, 0x40004, 1, 0, 0, 0) strings = tuple(vs_block(k, utf16z(v), text=True) for k, v in VERSION_VALUES.items()) string_info = vs_block("StringFileInfo", children=(vs_block("040904b0", children=strings),)) var_info = vs_block("VarFileInfo", children=(vs_block("Translation", struct.pack(" bytearray: """build_image() without its directories, plus a resource directory at RSRC: a VERSION type (one name, language 0x409) and a MANIFEST type (one name, language 0) whose data is 32 bytes.""" buf = bytearray(build_image(with_directories=False)) struct.pack_into(" None: place(buf, RSRC + at, struct.pack(" dict: path = os.path.join(self.dir, name) with open(path, "wb") as f: f.write(data) return pe_inspect.inspect(path, None) def test_types_fixed_info_languages_and_keys(self): import hashlib res = self.inspect(with_resources())["resources"] self.assertTrue(res["present"]) self.assertEqual(res["problems"], []) self.assertEqual([(t["type"], t["id"], t["entries"]) for t in res["types"]], [("VERSION", 16, 1), ("MANIFEST", 24, 1)]) self.assertEqual(res["types"][1]["bytes"], 32) v = res["version"] self.assertEqual((v["language"], v["codepage"], v["size"]), (0x409, 1200, len(version_block()))) f = v["fixed"] self.assertEqual((f["file_version"], f["product_version"], f["struct_version"]), ("1.2.3.4", "5.6.7.8", "1.0")) self.assertEqual(f["flag_names"], ["PRERELEASE", "PRIVATEBUILD"]) # 0x40 is outside the mask self.assertEqual((f["flags"], f["flags_mask"]), (0x4A, 0x3F)) self.assertEqual((f["os_name"], f["type_name"], f["subtype"], f["date"]), ("NT_WINDOWS32", "APP", 0, 0)) self.assertEqual(v["translations"], ["040904b0"]) self.assertEqual(v["string_count"], 4) self.assertEqual(v["other_blocks"], 0) [table] = v["string_tables"] self.assertEqual(table["lang_codepage"], "040904b0") self.assertEqual([s["key"] for s in table["strings"]], ["CompanyName", "ProductName", "FileVersion", None]) values = list(VERSION_VALUES.values()) self.assertEqual([s["chars"] for s in table["strings"]], [len(x) for x in values]) self.assertEqual([s["sha256"] for s in table["strings"]], [hashlib.sha256(x.encode()).hexdigest() for x in values]) self.assertEqual(table["strings"][3]["key_sha256"], hashlib.sha256(b"MadeUpCustomKey").hexdigest()) def test_values_and_custom_keys_appear_in_no_output(self): path = os.path.join(self.dir, "versioned.exe") with open(path, "wb") as f: f.write(with_resources()) out = os.path.join(self.dir, "reports") stdout = io.StringIO() with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(io.StringIO()): self.assertEqual(pe_inspect.main([path, "--out", out]), 0) with open(os.path.join(out, "versioned.exe.json"), encoding="utf-8") as f: text_json = f.read() with open(os.path.join(out, "versioned.exe.md"), encoding="utf-8") as f: text_md = f.read() self.assertIn("file version 1.2.3.4, product version 5.6.7.8", text_md) self.assertIn("| 040904b0 | CompanyName |", text_md) self.assertIn("versioned.exe: version block file 1.2.3.4, product 5.6.7.8, 4 string keys", stdout.getvalue()) for output, text in (("json", text_json), ("markdown", text_md), ("stdout", stdout.getvalue())): for secret in [*VERSION_VALUES.values(), "MadeUpCustomKey", "fixture-branch-xyz"]: with self.subTest(output=output, secret=secret): self.assertNotIn(secret.lower(), text.lower()) def test_no_resource_directory(self): r = self.inspect(build_image(), "plain.dll") self.assertEqual(r["resources"], {"present": False, "types": [], "named_types": 0, "version": None, "problems": []}) self.assertTrue(pe_inspect.to_markdown(r).endswith("## Resources\n\nnone\n")) self.assertIsNone(pe_inspect.version_summary(r)) def test_directory_rva_outside_every_section(self): buf = with_resources() struct.pack_into(" root res = self.inspect(buf)["resources"] self.assertTrue(any("reached a second time" in p for p in res["problems"]), res["problems"]) self.assertIsNone(res["version"]) self.assertEqual([t["type"] for t in res["types"]], ["MANIFEST"]) buf = with_resources() struct.pack_into(" itself res = self.inspect(buf)["resources"] self.assertTrue(any("only three levels are read" in p for p in res["problems"]), res["problems"]) self.assertIsNone(res["version"]) def test_named_types_are_counted_not_named(self): buf = with_resources() name_at = 0x400 # after the version data place(buf, RSRC + name_at, struct.pack(" named r = self.inspect(buf) self.assertEqual(r["resources"]["named_types"], 1) self.assertEqual([t["type"] for t in r["resources"]["types"]], ["VERSION", "(named)"]) self.assertNotIn("SECRETTYP", json.dumps(r) + pe_inspect.to_markdown(r)) class LongNameTest(unittest.TestCase): def test_a_long_decorated_import_name_is_read_whole(self): # the section is 0x1000 bytes, so the longest name that fits after the fixtures is used: 1,200 characters name = "?Long@" + "V" * 1190 + "@@QE" self.assertEqual(len(name), 1200) image = bytearray(build_image()) place(image, 0x1B00, struct.pack(" str: path = os.path.join(self.dir, name) with open(path, "wb") as f: f.write(data) return path def cut_inside(self, full: bytes, index: int, into: int) -> bytes: """The image cut `into` bytes after the start of data directory `index`.""" rva, _size = pe_inspect.PeImage(full).directory(index) return full[:pe_inspect.PeImage(full).offset(rva) + into] def test_each_table_cut_short_is_a_pe_format_error(self): for is64 in (True, False): full = build_image(is64=is64) cases = { "optional header": full[:0x58 + 2 + 16], # magic present, AddressOfEntryPoint cut off "export directory": self.cut_inside(full, pe_inspect.DIR_EXPORT, 10), "tls directory": self.cut_inside(full, pe_inspect.DIR_TLS, 20 if is64 else 10), } for what, data in cases.items(): with self.subTest(is64=is64, cut=what): path = self.write("cut.dll", data) with self.assertRaises(pe_inspect.PeFormatError): pe_inspect.inspect(path, None) def test_every_cut_length_gives_a_report_or_a_pe_format_error(self): for is64 in (True, False): full = build_image(is64=is64) for n in range(0, len(full), 16): with self.subTest(is64=is64, length=n): path = self.write("sweep.dll", full[:n]) try: pe_inspect.inspect(path, None) except pe_inspect.PeFormatError: pass def test_cli_reports_a_truncated_file_and_keeps_going(self): cut = self.write("cut.dll", build_image()[:0x58 + 2 + 16]) good = self.write("good.dll", build_image()) out = os.path.join(self.dir, "reports") err = io.StringIO() with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): self.assertEqual(pe_inspect.main([cut, good, "--out", out]), 1) self.assertIn("cut.dll: not a PE image (truncated optional header)", err.getvalue()) self.assertEqual(sorted(os.listdir(out)), ["good.dll.json", "good.dll.md"]) def test_export_counts_past_the_table_cap_do_not_run_away(self): full = bytearray(build_image()) img = pe_inspect.PeImage(bytes(full)) at = img.offset(img.directory(pe_inspect.DIR_EXPORT)[0]) struct.pack_into(" str: path = os.path.join(self.dir, name) with open(path, "wb") as f: f.write(data) return path def dos_header(self, size: int, nt: int | None = None) -> bytes: """`size` bytes starting with MZ, optionally with e_lfanew at 0x3c pointing at `nt`.""" data = bytearray(size) data[0:2] = b"MZ" if nt is not None: struct.pack_into(" None: """PeImage raises the message, and the CLI prints it to stderr and exits 1; no traceback on either path.""" with self.assertRaisesRegex(pe_inspect.PeFormatError, expected): pe_inspect.PeImage(data) err = io.StringIO() with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): self.assertEqual(pe_inspect.main([self.write(name, data), "--out", os.path.join(self.dir, "reports")]), 1) self.assertIn(expected, err.getvalue()) if not_expected: self.assertNotIn(not_expected, err.getvalue()) def test_mz_shorter_than_the_msdos_header_reports_the_length(self): # a 4-byte truncated copy: the signature is there, the 64-byte MS-DOS header (e_lfanew lives at 0x3c) is not self.check_rejected("short4.bin", self.dos_header(4), "file is 4 bytes, shorter than the 64-byte MS-DOS header", not_expected="no MZ header") def test_mz_one_byte_short_of_the_msdos_header_reports_the_length(self): self.check_rejected("short63.bin", self.dos_header(63), "file is 63 bytes, shorter than the 64-byte MS-DOS header", not_expected="no MZ header") def test_file_without_the_mz_signature_still_reports_no_mz_header(self): for name, data in (("aaaa.bin", b"AAAA"), ("empty.bin", b""), ("one_byte.bin", b"A"), ("m.bin", b"M")): with self.subTest(name=name): self.check_rejected(name, data, "no MZ header") def test_e_lfanew_past_the_end_reports_a_short_file_not_a_missing_signature(self): # 64 bytes: the MS-DOS header fits, the PE header it points at at 0x40 does not self.check_rejected("nt_past.bin", self.dos_header(64, 0x40), "file is 64 bytes, too short to hold the PE header at 0x40", not_expected="no PE signature") def test_pe_header_cut_after_the_signature_reports_a_short_file(self): # PE\0\0 at 0x40 is there, the 20 bytes of file header after it are cut off data = bytearray(self.dos_header(68, 0x40)) data[0x40:0x44] = b"PE\0\0" self.check_rejected("coff_cut.bin", bytes(data), "file is 68 bytes, too short to hold the PE header at 0x40", not_expected="no PE signature") def test_a_long_enough_file_with_a_wrong_signature_still_reports_no_pe_signature(self): data = bytearray(self.dos_header(88, 0x40)) data[0x40:0x44] = b"XX\0\0" self.check_rejected("bad_sig.bin", bytes(data), "no PE signature") class SectionBoundaryReadTest(unittest.TestCase): """Strings and multi-byte directory entries must not cross section/header boundaries or alias 64-bit thunks.""" @staticmethod def two_section_bytes(is64: bool = True, a_vsize: int = 0x200, a_raw: int = 0x200) -> tuple[bytearray, int]: """Build raw bytes for a two-section image with `.a` at 0x1000 and `.b` immediately after it.""" b_raw = 0x200 + a_raw image = bytearray(build_image(is64=is64, with_directories=False)[:0x200]) + bytearray(a_raw + 0x200) struct.pack_into(" bytes: """A version-6 API-set schema: {contract name without ".dll": host DLL, or "" for a contract with no host}.""" header, entry, value = 28, 24, 20 strings = bytearray() offset = header + len(contracts) * (entry + value) entries, values = bytearray(), bytearray() for i, (name, host) in enumerate(contracts.items()): name_at = offset + len(strings) strings += name.encode("utf-16-le") host_at = offset + len(strings) strings += host.encode("utf-16-le") hashed = name.rindex("-") * 2 value_at = header + len(contracts) * entry + i * value entries += struct.pack("<6I", 0, name_at, len(name) * 2, hashed, value_at, 1) values += struct.pack("<5I", 0, 0, 0, host_at, len(host) * 2) body = entries + values + strings return struct.pack("<7I", 6, header + len(body), 0, len(contracts), header, 0, 31) + body def build_apiset_dll(schema: bytes) -> bytes: """A 64-bit image whose one section is the .apiset section Wine's apisetschema.dll carries.""" raw = 0x200 size = (len(schema) + 0x1FF) & ~0x1FF buf = bytearray(raw + size) buf[0:2] = b"MZ" struct.pack_into(" str: path = os.path.join(self.dir, *parts) os.makedirs(path, exist_ok=True) for name in files: open(os.path.join(path, name), "wb").close() return path def prefix(self, files=(), schema: dict[str, str] | None = None) -> str: """A fake Wine prefix whose system32 holds `files` (and an apisetschema.dll for `schema`); made current.""" root = os.path.join(self.dir, "prefix") system32 = self.folder("prefix", "drive_c", "windows", "system32", files=files) if schema is not None: with open(os.path.join(system32, "apisetschema.dll"), "wb") as f: f.write(build_apiset_dll(build_apiset_schema(schema))) os.environ["WINEPREFIX"] = root return system32 def report(self, game_dir: str | None = None) -> dict: path = os.path.join(self.dir, "image.dll") with open(path, "wb") as f: f.write(build_image()) return pe_inspect.inspect(path, game_dir) def test_bundled_names_compare_without_case(self): game = self.folder("game", files=("msvcp140.dll", "Bink2.DLL")) os.makedirs(os.path.join(game, "folder.dll")) for windows in (False, True): with self.subTest(windows=windows): self.host(windows) self.assertEqual(pe_inspect.classify_dll("MSVCP140.dll", game), "bundled") self.assertEqual(pe_inspect.classify_dll("bink2.dll", game), "bundled") self.assertNotEqual(pe_inspect.classify_dll("folder.dll", game), "bundled", "a folder isn't a DLL") # A file added after the folder was first listed is seen too. self.host(False) open(os.path.join(game, "Late.dll"), "wb").close() os.utime(game, ns=(os.stat(game).st_atime_ns, os.stat(game).st_mtime_ns + 1_000_000)) self.assertEqual(pe_inspect.classify_dll("LATE.dll", game), "bundled") def test_wine_prefix_system32_is_compared_without_case(self): system32 = self.prefix(files=("KERNEL32.dll", "advapi32.dll", "winhttp.dll")) self.assertEqual(pe_inspect.classify_dll("kernel32.dll", None), "system") self.assertEqual(pe_inspect.classify_dll("ADVAPI32.dll", None), "system") self.assertEqual(pe_inspect.classify_dll("WinHttp.dll", None), "system", "as on Windows, where it's in System32") self.assertEqual(pe_inspect.classify_dll("contoso.dll", None), "shim") self.assertEqual(pe_inspect.classify_dll("xmem.dll", None), "shim") self.assertEqual(pe_inspect.system_dll_source(), ("wine-prefix", system32)) r = self.report() self.assertEqual(r["system_dlls"], {"checked": "wine-prefix", "dir": system32}) where = {i["dll"]: i["where"] for i in r["imports"]} self.assertEqual((where["kernel32.dll"], where["xmem.dll"]), ("system", "shim")) self.assertIn(f"System DLLs checked in the Wine prefix's `{system32}`.", pe_inspect.to_markdown(r)) def test_home_wine_prefix_when_wineprefix_is_unset(self): home = self.folder("home") system32 = self.folder("home", ".wine", "drive_c", "windows", "system32", files=("kernel32.dll",)) del os.environ["WINEPREFIX"] with mock.patch.dict(os.environ, {"HOME": home, "USERPROFILE": home}): self.assertEqual(pe_inspect.wine_system32(), system32) self.assertEqual(pe_inspect.classify_dll("Kernel32.dll", None), "system") def test_no_prefix_reports_unverified_except_what_the_shims_own(self): self.assertIsNone(pe_inspect.wine_system32()) self.assertEqual(pe_inspect.classify_dll("contoso.dll", None), "unverified") self.assertEqual(pe_inspect.classify_dll("kernel32.dll", None), "unverified", "a host DLL the shims patch") self.assertEqual(pe_inspect.classify_dll("xmem.dll", None), "shim") self.assertEqual(pe_inspect.classify_dll("XMEM.DLL", None), "shim") self.assertEqual(pe_inspect.classify_dll("D3D12_xs.dll", None), "shim") game = self.folder("game", files=("XMEM.dll",)) self.assertEqual(pe_inspect.classify_dll("xmem.dll", game), "bundled") r = self.report() self.assertEqual(r["system_dlls"], {"checked": "none", "dir": None}) md = pe_inspect.to_markdown(r) self.assertIn("| kernel32.dll | normal | system (unverified) | 1 |", md) self.assertIn("| xmem.dll | normal | shim | 1 |", md) self.assertIn("System DLLs could not be checked: no Wine prefix", md) out = io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): self.assertEqual(pe_inspect.main([os.path.join(self.dir, "image.dll"), "--out", os.path.join(self.dir, "reports")]), 0) self.assertIn("shim-imports=2 ", out.getvalue(), "xmem.dll, imported and delay-imported") self.assertIn("unverified-imports=1", out.getvalue(), "kernel32.dll") self.assertIn("System DLLs could not be checked", out.getvalue()) def test_api_sets_on_a_host_that_is_not_windows(self): self.assertEqual(pe_inspect.classify_dll("api-ms-win-core-synch-l1-2-0.dll", None), "unverified", "no prefix: an API set is never a shim the runtime owns") self.prefix(files=("api-ms-win-crt-runtime-l1-1-0.dll",), schema={"api-ms-win-core-synch-l1-2-0": "kernelbase.dll", "api-ms-win-core-empty-l1-1-0": "", "ext-ms-win-gdi-dc-l1-2-0": "gdi32.dll"}) self.assertEqual(pe_inspect.classify_dll("api-ms-win-core-synch-l1-2-0.dll", None), "system") self.assertEqual(pe_inspect.classify_dll("API-MS-WIN-Core-Synch-L1-2-1.dll", None), "system", "a lookup compares the name up to its last hyphen") self.assertEqual(pe_inspect.classify_dll("ext-ms-win-gdi-dc-l1-2-0.dll", None), "system") self.assertEqual(pe_inspect.classify_dll("api-ms-win-core-empty-l1-1-0.dll", None), "shim", "no host") self.assertEqual(pe_inspect.classify_dll("api-ms-win-core-missing-l1-1-0.dll", None), "shim") self.assertEqual(pe_inspect.classify_dll("API-MS-WIN-CRT-RUNTIME-L1-1-0.DLL", None), "system", "the file") def test_windows_classification_is_unchanged(self): system32 = self.folder("System32", files=("kernel32.dll",)) self.host(True, system32) self.prefix(files=("contoso.dll", "kernel32.dll")) # a Wine prefix is not consulted on Windows self.assertEqual(pe_inspect.system_dll_source(), ("windows", system32)) self.assertEqual(pe_inspect.classify_dll("kernel32.dll", None), "system") self.assertEqual(pe_inspect.classify_dll("contoso.dll", None), "shim", "never unverified on Windows") self.assertEqual(pe_inspect.classify_dll("xmem.dll", None), "shim") for resolves, expected in ((True, "system"), (False, "shim")): with mock.patch.object(pe_inspect, "_apiset_resolves", lambda name, r=resolves: r): self.assertEqual(pe_inspect.classify_dll("api-ms-win-core-synch-l1-2-0.dll", None), expected) game = self.folder("game", files=("xmem.dll",)) self.assertEqual(pe_inspect.classify_dll("xmem.dll", game), "bundled") r = self.report() self.assertEqual(r["system_dlls"], {"checked": "windows", "dir": system32}) md = pe_inspect.to_markdown(r) self.assertNotIn("System DLLs", md, "the Windows report reads as before") self.assertIn("| kernel32.dll | normal | system | 1 |", md) def test_runtime_shim_dlls_follow_the_registry(self): owned = pe_inspect.runtime_shim_dlls() self.assertTrue({"xmem.dll", "d3d12_xs.dll"} <= owned, owned) self.assertFalse({"kernel32.dll", "kernelbase.dll", "msvcrt.dll"} & owned) self.assertFalse([n for n in owned if n.startswith(("api-ms-", "ext-ms-"))]) with open(os.path.join(ROOT, "runtime", "shims", "registry.cpp"), encoding="utf-8") as f: text = f.read() body = text[text.index("bool owns_dll("):] host = body[body.index("host[] = {") + len("host[] = {"):body.index("};")] self.assertEqual(set(re.findall(r'"([^"]+)"', host)), set(pe_inspect._SHIM_HOST_DLLS), "_SHIM_HOST_DLLS is owns_dll's host list") src = self.folder("shims") with open(os.path.join(src, "a.cpp"), "w", encoding="utf-8", newline="\n") as f: f.write('static const char* x = "notatable.dll";\nfind("alsonot.dll", "f");\n' 'SHIM_TABLE(a,\n {"Foo.dll", "F", reinterpret_cast(&f)},\n MACRO("bar.dll"),\n' ' {"kernel32.dll", "K", nullptr},\n MACRO("api-ms-win-core-file-l1-1-0.dll"),\n);\n') self.assertEqual(pe_inspect.runtime_shim_dlls(src), {"foo.dll", "bar.dll"}) self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset()) class TestExportForwarders(unittest.TestCase): def inspect_buf(self, buf: bytes) -> dict: return pe_inspect._inspect_exports(pe_inspect.PeImage(buf)) def test_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarder(self): """The directory is [begin, end): an RVA equal to the end is past it, as in runtime/src/pe_loader.cpp.""" end = 0x1800 # the export directory of with_exports() is [0x1700, 0x1800) data = with_exports([end], {0: "AtTheEnd"}, base=1) exp = self.inspect_buf(data) self.assertEqual(exp["forwarders"], {}) self.assertEqual(exp["exports"], ["AtTheEnd"]) last = with_exports([end - 1], {0: "LastByte"}, base=1) self.assertIn("LastByte", self.inspect_buf(last)["forwarders"]) def test_case1_normal_exports_and_unused_slots(self): """Case 1: Normal code exports + unused zero-RVA slot skipped (forwarders empty, invalid_export_count 0).""" data = with_exports([0x1000, 0, 0x1010], {0: "Alpha", 2: "Beta"}, base=1) exp = self.inspect_buf(data) self.assertEqual(exp["exports"], ["Alpha", "Beta"]) self.assertEqual(exp["forwarders"], {}) self.assertEqual(exp["invalid_export_count"], 0) self.assertEqual(exp["invalid_exports"], []) def test_case2_named_forwarded_export(self): """Case 2: Named forwarded export (RVA inside export directory [0x1700, 0x1800)).""" data = with_exports([0x1000, FORWARDER], {0: "NormalFunc", 1: "Sleep"}, base=10) exp = self.inspect_buf(data) self.assertEqual(exp["exports"], ["NormalFunc", "Sleep"]) self.assertEqual(exp["forwarders"], {"Sleep": "other.Target"}) self.assertEqual(exp["invalid_export_count"], 0) with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: f.write(data) f.flush() tmp_path = f.name try: report = pe_inspect.inspect(tmp_path, None) md = pe_inspect.to_markdown(report) self.assertIn("(1 forwarded)", md) self.assertIn("## Forwarded Exports", md) self.assertIn("| `Sleep` | `other.Target` |", md) finally: os.unlink(tmp_path) def test_case3_ordinal_only_forwarder(self): """Case 3: Ordinal-only forwarded export (index not in named).""" data = with_exports([0x1000, FORWARDER], {0: "Func"}, base=10) exp = self.inspect_buf(data) self.assertEqual(exp["exports"], ["Func", "#11"]) self.assertEqual(exp["forwarders"], {"#11": "other.Target"}) self.assertEqual(exp["invalid_export_count"], 0) def test_case4_aliased_named_forwarders(self): """Case 4: Two export names mapping to the same forwarded EAT index.""" data = with_exports([FORWARDER], {0: "AliasA"}, base=1) buf = bytearray(data) place(buf, 0x1700, struct.pack("= size_of_image).""" data = with_exports([0x3000], {0: "BadFunc"}, base=10) exp = self.inspect_buf(data) self.assertEqual(exp["exports"], ["BadFunc"]) self.assertEqual(exp["invalid_export_count"], 1) self.assertEqual(len(exp["invalid_exports"]), 1) self.assertEqual(exp["invalid_exports"][0]["symbol"], "BadFunc") self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_bounds") with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: f.write(data) f.flush() tmp_path = f.name try: report = pe_inspect.inspect(tmp_path, None) md = pe_inspect.to_markdown(report) self.assertIn("INVALID: 1 invalid: BadFunc (out_of_bounds)", md) finally: os.unlink(tmp_path) def test_case6_unreadable_forwarder_and_error_cap(self): """Case 6: Unreadable forwarder string and invalid error cap at <= 5.""" buf = bytearray(build_image()) dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8 struct.pack_into("= functions recorded as invalid, dir_size < 40 returns empty.""" data = with_exports([0x1000], {0: "NormalFunc"}, base=1) buf = bytearray(data) # Point the ordinal table to index 5 while NumberOfFunctions is 1 place(buf, 0x1C80, struct.pack(" sample.Sleep or sample.dll.Sleep for target in (b"sample.Sleep\0", b"sample.dll.Sleep\0"): with self.subTest(target=target): data = bytearray(with_exports([FORWARDER], {0: "Sleep"}, base=1)) place(data, FORWARDER, target) exp = self.inspect_buf(bytes(data)) self.assertEqual(exp["invalid_export_count"], 1) self.assertEqual(exp["invalid_exports"][0]["symbol"], "Sleep") self.assertEqual(exp["invalid_exports"][0]["reason"], "forwarder_loop") with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: f.write(data) f.flush() tmp_path = f.name try: report = pe_inspect.inspect(tmp_path, None) md = pe_inspect.to_markdown(report) self.assertIn("INVALID: 1 invalid: Sleep (forwarder_loop)", md) finally: os.unlink(tmp_path) def test_case12_intra_module_forwarder_cyclic_loop(self): """Case 12: Mutual/cyclic intra-module forwarders (Alpha -> Beta, Beta -> Alpha).""" fwd_a = 0x1790 fwd_b = 0x17B0 data = bytearray(with_exports([fwd_a, fwd_b], {0: "Alpha", 1: "Beta"}, base=1)) place(data, fwd_a, b"sample.Beta\0") place(data, fwd_b, b"sample.Alpha\0") exp = self.inspect_buf(bytes(data)) self.assertEqual(exp["invalid_export_count"], 2) symbols = {inv["symbol"] for inv in exp["invalid_exports"]} self.assertEqual(symbols, {"Alpha", "Beta"}) for inv in exp["invalid_exports"]: self.assertEqual(inv["reason"], "forwarder_loop") def test_case13_intra_module_forwarder_depth_limit(self): """Case 13: Forwarder chain >= 8 within the same module is detected as a loop.""" # Chain F0 -> F1 -> ... -> F8 slots = [] names = {} base_addr = 0x1790 for k in range(9): addr = base_addr + k * 11 slots.append(addr) names[k] = f"F{k}" data = bytearray(with_exports(slots, names, base=1)) for k in range(8): addr = base_addr + k * 11 place(data, addr, f"sample.F{k+1}\0".encode()) # The 9th points to an external module (valid in isolation) place(data, base_addr + 8 * 11, b"kernel32.Sleep\0") exp = self.inspect_buf(bytes(data)) # F0's chain length reaches 8, so F0 triggers forwarder_loop f0_inv = [inv for inv in exp["invalid_exports"] if inv["symbol"] == "F0"] self.assertEqual(len(f0_inv), 1) self.assertEqual(f0_inv[0]["reason"], "forwarder_loop") def test_case14_pe_header_edge_cases(self): """Case 14: e_lfanew overlapping DOS header, SizeOfImage 0, SizeOfHeaders > SizeOfImage.""" base_data = build_image() # e_lfanew < 0x40 data_short_nt = bytearray(base_data) struct.pack_into(" SizeOfImage data_hdr_overflow = bytearray(base_data) struct.pack_into("