d3d12_guid_sites, d3d12_iid_scan: report an unreadable header or import table (D3D12-TOOLS-ERROR-REPORTING)

d3d12_guid_sites ignored an explicit --header that does not exist and exited 0 with no known GUIDs.
Both tools now exit 2 with an ERROR line for a missing header and for a header with a malformed GUID.
d3d12_iid_scan keeps the d3d12_xs.dll names read before a parse error and warns on stderr instead of
returning None, so the 'imports may be IID data' warning is not lost.
New tests use hand-made files: missing header, malformed GUID, unreadable import table, and a good header.
This commit is contained in:
Romain PINSOLLE
2026-11-24 16:15:03 +01:00
parent a28927849a
commit 255156c2c8
4 changed files with 143 additions and 10 deletions

View File

@ -176,7 +176,7 @@ class GuidSites(unittest.TestCase):
image, _ = pe32plus(text, rdata)
path = self.write("t6.dll", image)
out = os.path.join(self.tmp.name, "out.json")
header = os.path.join(self.tmp.name, "none.h")
header = self.write("none.h", b"// a header that lists no interfaces\n")
result = subprocess.run(
[sys.executable, "-I", os.path.join(ROOT, "tools", "d3d12_guid_sites.py"), path,
"--header", header, "--known", f"ID3D12CommandQueue={QUEUE}", "--json", out],

View File

@ -0,0 +1,106 @@
"""tools/d3d12_guid_sites.py and tools/d3d12_iid_scan.py report a bad header or an unreadable import table.
Hand-made inputs only: a few bytes stand in for a PE image, and the header is written by the test (no SDK, no game files).
"""
import os
import struct
import subprocess
import sys
import tempfile
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS = os.path.join(ROOT, "tools")
GOOD_HEADER = b'MIDL_INTERFACE("6102dee4-af59-4c3d-9c5b-7a1e4cb0d5b6")\nID3D12Fence\n'
BAD_HEADER = b'MIDL_INTERFACE("000000000000000000000000000000000000")\nID3D12Fence\n'
def pe_stub(bad):
"""A 0x300-byte PE32+ image with one d3d12_xs.dll import (ordinal 50), or, when bad, a second descriptor whose
name is an unterminated string at the end of the file."""
b = bytearray(0x300)
b[0:2] = b"MZ"
struct.pack_into("<I", b, 0x3C, 0x40)
b[0x40:0x44] = b"PE\0\0"
struct.pack_into("<HHIIIHH", b, 0x44, 0x8664, 1, 0, 0, 0, 240, 0x22)
struct.pack_into("<H", b, 0x58, 0x20B)
struct.pack_into("<II", b, 0x58 + 112 + 8, 0x1000, 0x40) # import directory: RVA, size
b[0x148:0x148 + 8] = b".text\0\0\0"
struct.pack_into("<IIII", b, 0x148 + 8, 0x200, 0x1000, 0x200, 0x200) # VirtualSize, VA, SizeOfRawData, raw
struct.pack_into("<IIIII", b, 0x200, 0x1040, 0, 0, 0x1030, 0x1040) # descriptor 1: name RVA 0x1030
b[0x230:0x23D] = b"d3d12_xs.dll\0"
struct.pack_into("<Q", b, 0x240, (1 << 63) | 50)
if bad:
struct.pack_into("<IIIII", b, 0x214, 0x1040, 0, 0, 0x10F8, 0x1040) # descriptor 2: name RVA 0x10F8
b[0x2F8:0x300] = b"AAAAAAAA" # no NUL before the file ends
return bytes(b)
class ToolErrorReporting(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
def tearDown(self):
self.tmp.cleanup()
def write(self, name, data):
path = os.path.join(self.tmp.name, name)
with open(path, "wb") as f:
f.write(data)
return path
def run_tool(self, tool, *args):
return subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool + ".py"), *args],
capture_output=True, text=True, timeout=120, errors="replace")
def test_missing_explicit_header_is_an_error_in_both_tools(self):
image = self.write("tiny.exe", b"MZ")
missing = os.path.join(self.tmp.name, "no_such_d3d12.h")
for tool in ("d3d12_guid_sites", "d3d12_iid_scan"):
with self.subTest(tool=tool):
p = self.run_tool(tool, image, "--header", missing)
self.assertEqual(p.returncode, 2, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertIn("ERROR: d3d12.h not found", p.stderr)
self.assertEqual(p.stdout, "", "no GUID table may be printed for a missing header")
def test_malformed_guid_in_header_is_an_error_in_both_tools(self):
image = self.write("tiny.exe", b"MZ")
header = self.write("bad.h", BAD_HEADER)
for tool in ("d3d12_guid_sites", "d3d12_iid_scan"):
with self.subTest(tool=tool):
p = self.run_tool(tool, image, "--header", header)
self.assertEqual(p.returncode, 2, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertTrue(p.stderr.startswith("ERROR: cannot read "), p.stderr)
self.assertIn(header, p.stderr)
self.assertIn("malformed", p.stderr)
def test_unreadable_import_table_keeps_names_and_warns(self):
header = self.write("ok.h", GOOD_HEADER)
image = self.write("bad.exe", pe_stub(bad=True))
p = self.run_tool("d3d12_iid_scan", image, "--header", header)
self.assertEqual(p.returncode, 0, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertIn("imports from d3d12_xs.dll: #50", p.stdout)
self.assertIn("WARNING: bad.exe: the d3d12_xs.dll import table could not be read to the end", p.stderr)
self.assertIn("no terminating NUL", p.stderr)
def test_good_header_and_stub_behave_as_before(self):
header = self.write("ok.h", GOOD_HEADER)
image = self.write("good.exe", pe_stub(bad=False))
p = self.run_tool("d3d12_iid_scan", image, "--header", header)
self.assertEqual(p.returncode, 0, p.stderr)
self.assertEqual(p.stderr, "")
self.assertIn("imports from d3d12_xs.dll: #50", p.stdout)
self.assertIn("WARNING: these d3d12_xs.dll imports may be IID data", p.stdout)
p = self.run_tool("d3d12_guid_sites", image, "--header", header)
self.assertEqual(p.returncode, 0, p.stderr)
self.assertIn("1 known GUIDs from", p.stdout)
self.assertNotIn("Traceback", p.stderr)
if __name__ == "__main__":
unittest.main()

View File

@ -387,9 +387,19 @@ def main(argv: list[str] | None = None) -> int:
if source and same_report_path(args.json, source):
ap.error(f"--json {args.json} would overwrite the input {source}")
if args.header is not None and not os.path.isfile(args.header):
print(f"ERROR: d3d12.h not found: {args.header}", file=sys.stderr)
return 2
known: dict[str, uuid.UUID] = {}
if header and os.path.isfile(header):
known.update(read_iids(header))
try:
known.update(read_iids(header))
except OSError as e:
print(f"ERROR: cannot read {header}: {e.strerror or e}", file=sys.stderr)
return 2
except ValueError as e:
print(f"ERROR: cannot read {header}: a MIDL_INTERFACE GUID is malformed ({e})", file=sys.stderr)
return 2
for pair in args.known:
name, _, value = pair.partition("=")
try:

View File

@ -61,12 +61,20 @@ def read_iids(header: str) -> dict[str, uuid.UUID]:
def d3d12_xs_imports(data: bytes) -> list[str] | None:
"""What the PE image imports from d3d12_xs.dll: names, or "#N" for an import by ordinal (ordinals 23-115 are
GUID data, docs/d3d12_xs_surface.md section 2). None when the image does not import d3d12_xs.dll at all."""
return read_d3d12_xs_imports(data)[0]
def read_d3d12_xs_imports(data: bytes) -> tuple[list[str] | None, str | None]:
"""d3d12_xs_imports, and why the import table could not be read to its end (None when it could).
A parse error keeps the names read before it, so the caller can say the list may be incomplete."""
names: list[str] | None = None
try:
if data[:2] != b"MZ":
return None
return None, None
pe = struct.unpack_from("<I", data, 0x3C)[0]
if data[pe:pe + 4] != b"PE\0\0":
return None
return None, None
sections, opt_size = struct.unpack_from("<H", data, pe + 6)[0], struct.unpack_from("<H", data, pe + 20)[0]
opt = pe + 24
pe32plus = struct.unpack_from("<H", data, opt)[0] == 0x20B
@ -85,9 +93,11 @@ def d3d12_xs_imports(data: bytes) -> list[str] | None:
return None
def cstr(at: int) -> bytes:
return data[at:data.index(b"\0", at)]
end = data.find(b"\0", at)
if end < 0:
raise ValueError("an import name has no terminating NUL")
return data[at:end]
names: list[str] | None = None
pos = offset(imp_rva) if imp_rva else None
while pos is not None and pos + 20 <= len(data):
lookup_rva, _, _, name_rva, iat_rva = struct.unpack_from("<IIIII", data, pos)
@ -110,9 +120,9 @@ def d3d12_xs_imports(data: bytes) -> list[str] | None:
names.append(cstr(hint + 2).decode("ascii", "replace") if hint is not None else "?")
thunk += width
pos += 20
return names
except (struct.error, ValueError):
return None
except (struct.error, ValueError) as e:
return names, str(e)
return names, None
def possible_iid_imports(names: list[str] | None) -> list[str]:
@ -128,12 +138,13 @@ def scan(path: str, iids: dict[str, uuid.UUID]) -> dict:
with open(path, "rb") as f:
data = f.read()
found = sorted(name for name, guid in iids.items() if guid.bytes_le in data)
imports = d3d12_xs_imports(data)
imports, import_error = read_d3d12_xs_imports(data)
return {
"image": os.path.basename(path),
"found": found,
"focus": {name: name in found for name in FOCUS if name in iids},
"d3d12_xs_imports": imports,
"d3d12_xs_import_error": import_error,
"possible_iid_imports": possible_iid_imports(imports),
}
@ -160,6 +171,9 @@ def main(argv: list[str] | None = None) -> int:
except OSError as e:
print(f"ERROR: cannot read {header}: {e.strerror or e}", file=sys.stderr)
return 2
except ValueError as e:
print(f"ERROR: cannot read {header}: a MIDL_INTERFACE GUID is malformed ({e})", file=sys.stderr)
return 2
if not iids:
print(f"ERROR: no ID3D12 MIDL_INTERFACE declarations in {header}", file=sys.stderr)
return 2
@ -181,6 +195,9 @@ def main(argv: list[str] | None = None) -> int:
if r["possible_iid_imports"]:
print(" WARNING: these d3d12_xs.dll imports may be IID data, so an absent IID proves nothing for "
"this image: " + ", ".join(r["possible_iid_imports"]))
if r["d3d12_xs_import_error"]:
print(f"WARNING: {r['image']}: the d3d12_xs.dll import table could not be read to the end "
f"({r['d3d12_xs_import_error']}); imports after that point are not listed", file=sys.stderr)
if args.json:
try:
with open(args.json, "w", encoding="utf-8", newline="\n") as f: