"""List the call sites where an x86-64 PE image stops itself when an import returns a failure, from the file alone. Usage: python -I tools/import_fail_fast.py [--import DLL!NAME ...] [--dll DLL ...] [--all] [--json] A title treats some results as impossible: it tests the returned value and branches to `int3` (MSVC's `__debugbreak` and the marker it places after a call that does not return) when the value is the failing one. A shim that returns that value at such a site stops the boot there, with no error message. This lists, per import, how many of its call sites do that and on which value, so the results each shim must get right are known before a run reaches them. How, with nothing run: 1. Call sites. A `call rel32` to the import's thunk (tools/import_call_sites.py finds the thunks) and a `call qword [rip+disp32]` through the import's address-table slot, the form an image uses for the `api-ms-win-*` imports. A site's RVA is that of its `E8` or `FF` byte. Tail jumps are skipped: their result is tested by a caller, not here. 2. The test. The instructions after the call are decoded (tools/gdk_runtime_calls.py's decoder) up to the first `test` or `cmp` of the result: rax at any width, or a register it was copied to with `mov`. A `test` of the register with itself or with a constant, or a `cmp` with a constant. When a branch, a call, a return or another write to every copy of the result comes first, the site is not one this tool can judge. 3. The branch. The next instruction must be a conditional jump. Each side is followed for a few instructions, and through up to two unconditional jumps. A side is fatal when it reaches `int3`, `ud2` or `int 29h` (`__fastfail`), or a `call` whose next instruction is `int3` (a call that does not return). 4. The condition is the value that takes the fatal side, written with the result register at the width the test read: `eax == 0`, `rax == -1`, `eax < 0` (a failed HRESULT), `eax != 1`, `(al & 0x1) == 0`. `u` are unsigned comparisons. A site where both sides are fatal is not counted. What a count means: a site found here is code that can stop the title, not proof that the boot reaches it. Only straight-line code after the call is read, so a result stored and tested later, or a failure path that logs before it stops, is not seen. The counts are heuristic: they can miss sites that way, and a stray `E8` or `FF 15` byte pair inside another instruction could add a false one, which is rare. Output is import names, counts, conditions and RVAs only, no instruction bytes. `--json` prints every import the image names (or every one `--import`/`--dll` selects), including those with no call site (`"calls": 0`), with `"fatal"` empty when none of its sites is fatal. The table's last line, "N of M import(s) called directly", gives both numbers: M imports named (or selected), N of them with at least one direct call site. The rest are reached only through a stored pointer or a tail jump, or not at all. """ import argparse import json import os import re import struct import sys ROOT = os.path.dirname(os.path.abspath(__file__)) if ROOT not in sys.path: sys.path.insert(0, ROOT) import pe_inspect # noqa: E402 from gdk_runtime_calls import RAX, decode, writes # noqa: E402 from import_call_sites import (call_sites, dll_selector, import_selector, import_slots, # noqa: E402 unmatched_selectors) CALL_SLOT = re.compile(b"\xff\x15") PREFIXES = frozenset((0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3)) COPY_OPS = frozenset((0x8B, 0x63, 0x1B6, 0x1B7, 0x1BE, 0x1BF)) # mov, movsxd, movzx, movsx: r <- r/m TEST_WINDOW = 8 # instructions read after a call to find the test of its result SIDE_WINDOW = 4 # instructions read on each side of the branch, per jump followed SIDE_JUMPS = 2 # unconditional jumps followed on a side # Condition codes of jcc (low nibble of 70-7F / 0F 80-8F), as the comparison that takes the jump. CMP_CONDITION = {0x2: "=u", 0x4: "==", 0x5: "!=", 0x6: "<=u", 0x7: ">u", 0xC: "<", 0xD: ">=", 0xE: "<=", 0xF: ">"} # After `test r, r`: CF = OF = 0, so the condition is one on the sign and zero of r. SELF_TEST_CONDITION = {0x4: "== 0", 0x5: "!= 0", 0x6: "== 0", 0x7: "!= 0", 0x8: "< 0", 0x9: ">= 0", 0xC: "< 0", 0xD: ">= 0", 0xE: "<= 0", 0xF: "> 0"} RESULT_NAME = {8: "al", 16: "ax", 32: "eax", 64: "rax"} def instruction_bytes(img, insn): at = img.offset(insn.rva, insn.size) return img.data[at:at + insn.size] if at is not None else b"" def decode_at(img, rva): at = img.offset(rva) if at is None: return None return decode(img.data, at, rva - at) def width(raw, insn): """Operand width of an ALU instruction: 8 for the byte forms, else 64 with REX.W, 16 with a 0x66 prefix, 32.""" if insn.op in (0x84, 0x80, 0x3C, 0xA8, 0xF6): return 8 if insn.wide: return 64 for b in raw: if b == 0x66: return 16 if b not in PREFIXES: break return 32 def immediate(raw, insn, size): """The instruction's trailing immediate (sign-extended).""" fmt = {1: " len(blob): continue key = slots.get(s["rva"] + at + 6 + struct.unpack_from("5s} {'fatal':>5s} stops the program when") for key, e in sorted(rows, key=lambda kv: (-len(kv[1]["fatal"]), kv[0])): print(f"{key:{w}s} {e['calls']:5d} {len(e['fatal']):5d} {summary(e)}") called = sum(1 for e in imports.values() if e["calls"]) with_fatal = sum(1 for e in imports.values() if e["fatal"]) sites = sum(len(e["fatal"]) for e in imports.values()) print(f"{called} of {len(imports)} import(s) called directly, {with_fatal} with a fatal result check, " f"{sites} fatal site(s)") return 0 if __name__ == "__main__": try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode sys.stdout.reconfigure(errors="replace") except (AttributeError, ValueError, OSError): pass sys.exit(main())