"""Unit tests for tools/import_call_sites.py: thunks and the direct calls to them, on an image built here byte by byte. The image has two executable-code layouts the tool must tell apart: calls (E8) and tail jumps (E9) to the thunk of an import, and an import nothing calls. It needs no game files and no third-party packages. python -I tests/test_import_call_sites.py """ import contextlib import io import json import os import struct import sys import tempfile import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TOOLS_DIR = os.path.join(ROOT, "tools") if TOOLS_DIR not in sys.path: sys.path.insert(0, TOOLS_DIR) import import_call_sites # noqa: E402 import pe_inspect # noqa: E402 IMAGE_BASE = 0x140000000 TEXT_RVA = 0x1000 IDATA_RVA = 0x2000 DIRECTORIES = 0x58 + 112 # .text layout (RVAs): three thunks, then the callers. THUNK_FOO = TEXT_RVA + 0x00 THUNK_BAR = TEXT_RVA + 0x10 THUNK_ORD = TEXT_RVA + 0x20 # .idata layout: descriptor table, lookup table, address table, hint/name entries, module name. IAT_FOO = IDATA_RVA + 0x60 IAT_BAR = IAT_FOO + 8 IAT_ORD = IAT_FOO + 16 OTHER_IAT_RVA = IDATA_RVA + 0xE0 DELAY_DIRECTORY = DIRECTORIES + 13 * 8 DELAY_DESC = IDATA_RVA + 0x100 DELAY_IAT = IDATA_RVA + 0x140 DELAY_INT = IDATA_RVA + 0x160 DELAY_DLL = IDATA_RVA + 0x180 DELAY_NAME = IDATA_RVA + 0x1A0 DELAY_THUNK = TEXT_RVA + 0x30 DELAY_ORD_THUNK = TEXT_RVA + 0x40 DELAY_CALLS = [TEXT_RVA + 0x110, TEXT_RVA + 0x120] DELAY_JMP = TEXT_RVA + 0x130 DELAY_ORD_CALL = TEXT_RVA + 0x140 NORMAL_CALL = TEXT_RVA + 0x100 def rel32(from_end, target): return struct.pack(" len(blob) cut = TEXT_RVA + 0x1000 - 4 data[cut:cut + 2] = b"\xff\x15" out = import_call_sites.call_sites(bytes(data))["imports"] self.assertIn("xmem.dll!XMemFoo", out) def test_cli_output_includes_direct_slot_calls(self): data = bytearray(build_image([])) call_rva = TEXT_RVA + 0x150 data[call_rva:call_rva + 6] = b"\xff\x15" + rel32(call_rva + 6, IAT_BAR) with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "image.exe") with open(path, "wb") as f: f.write(data) out = io.StringIO() with contextlib.redirect_stdout(out): rc = import_call_sites.main([path, "--dll", "xmem.dll", "--json"]) self.assertEqual(rc, 0) parsed = json.loads(out.getvalue()) self.assertEqual(parsed["imports"]["xmem.dll!XMemBar"]["call"], [hex(call_rva)]) if __name__ == "__main__": unittest.main()