"""Unit tests for tools/import_fail_fast.py: which result of an import a call site stops the program on. The image is tests/test_import_call_sites.py's (xmem.dll: XMemFoo, XMemBar, #7 behind thunks), with call sites written into `.text` here, one per case: the test of the result, the branch, and the side that reaches `int3`, `ud2`, `int 29h` or a call that does not return. It needs no game files and no third-party packages. python -I tests/test_import_fail_fast.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__))) for d in (os.path.join(ROOT, "tools"), os.path.join(ROOT, "tests")): if d not in sys.path: sys.path.insert(0, d) import import_fail_fast # noqa: E402 from test_import_call_sites import (IAT_BAR, TEXT_RVA, THUNK_FOO, THUNK_ORD, # noqa: E402 build_image, rel32) FOO, BAR, ORD = "xmem.dll!XMemFoo", "xmem.dll!XMemBar", "xmem.dll!#7" FAR_INT3 = TEXT_RVA + 0xF00 # int3 FUNC = TEXT_RVA + 0xF10 # ret NORETURN = TEXT_RVA + 0xF20 # call FUNC; int3 SITES = TEXT_RVA + 0x100 # one site every 0x40 bytes from here INT3, RET, UD2, INT29 = b"\xcc", b"\xc3", b"\x0f\x0b", b"\xcd\x29" TEST_EAX, TEST_RAX = b"\x85\xc0", b"\x48\x85\xc0" def jcc8(cc, disp): return bytes((0x70 | cc, disp)) # (case, how the import is called, code after the call (bytes, or a function of the RVA it starts at), condition). CASES = [ ("test eax / jne over int3", FOO, TEST_EAX + jcc8(0x5, 1) + INT3 + RET, "eax == 0"), ("test rax / je rel32 to a far int3", FOO, lambda pc: TEST_RAX + b"\x0f\x84" + rel32(pc + 9, FAR_INT3) + RET, "rax == 0"), ("test eax / jns over int3", FOO, TEST_EAX + jcc8(0x9, 1) + INT3 + RET, "eax < 0"), ("cmp eax, 1 / jne to a call that does not return", FOO, lambda pc: b"\x83\xf8\x01\x0f\x85" + rel32(pc + 9, NORETURN) + RET, "eax != 1"), ("cmp rax, -1 / je to int3", FOO, b"\x48\x83\xf8\xff" + jcc8(0x4, 1) + RET + INT3, "rax == -1"), ("cmp eax, 2 / jb to int3", FOO, b"\x83\xf8\x02" + jcc8(0x2, 1) + RET + INT3, "eax