Files
rtaranu f820d2f3d1 disasm: measure a jump table indexed from slot 1
MSVC's memcpy/memmove dispatch their lead bytes through
`jmp [eax*4 + LeadUpVec - 4]` with eax 1..3, so slot 0 at the
displacement is padding or the previous jmp's tail, not a pointer.
resync_jump_tables measured nothing there and dropped the table, so the
function ended at its own dispatch: every arm after the table became an
indirect call no function covered. MechAssault's memmove (0x001D0580)
ended at 0x001D05E4 instead of 0x001D08BD, the boot stack was corrupted by
the first unaligned copy, and the tail was split into false starts. The
lifter already reads such a table one slot on; measure it there too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:12:11 -05:00

1297 lines
59 KiB
Python

"""
Disassembly engine using Capstone.
Provides linear sweep and recursive descent disassembly of x86-32 code,
with instruction classification and operand analysis.
"""
import bisect
import struct
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set, Tuple
from capstone import Cs, CS_ARCH_X86, CS_MODE_32, CsInsn
from capstone import (CS_OP_IMM, CS_OP_MEM, CS_OP_REG,
CS_GRP_INT, CS_GRP_IRET, CS_GRP_PRIVILEGE)
from capstone.x86_const import (
X86_REG_EFLAGS,
)
from capstone import x86_const
from . import config
from .loader import BinaryImage, SectionInfo
@dataclass
class Instruction:
"""A decoded instruction with metadata."""
address: int
size: int
mnemonic: str
op_str: str
bytes_hex: str
# Classification
is_call: bool = False
is_ret: bool = False
is_jump: bool = False
is_cond_jump: bool = False
is_nop: bool = False
# Resolved targets
call_target: Optional[int] = None # For direct calls
jump_target: Optional[int] = None # For direct jumps
memory_ref: Optional[int] = None # For [addr] references
jump_table: Optional[int] = None # For `jmp [reg*4 + table]`
imm_ref: Optional[int] = None # For `push offset x` / `mov reg, offset x`
@property
def is_branch(self) -> bool:
return self.is_jump or self.is_cond_jump
@property
def is_terminator(self) -> bool:
return self.is_ret or self.is_jump # Unconditional terminator
@property
def end_address(self) -> int:
return self.address + self.size
def to_dict(self) -> dict:
d = {
"address": f"0x{self.address:08X}",
"size": self.size,
"mnemonic": self.mnemonic,
"op_str": self.op_str,
"bytes": self.bytes_hex,
}
if self.call_target is not None:
d["call_target"] = f"0x{self.call_target:08X}"
if self.jump_target is not None:
d["jump_target"] = f"0x{self.jump_target:08X}"
if self.memory_ref is not None:
d["memory_ref"] = f"0x{self.memory_ref:08X}"
if self.imm_ref is not None:
d["imm_ref"] = f"0x{self.imm_ref:08X}"
return d
def _file_end(section, data) -> int:
"""VA where a section's file bytes end.
get_section_data appends a little of the loader's zero fill so that an
instruction starting in the file bytes can finish (BinaryImage
.get_section_data says why). No instruction may start in that fill:
decoding it would hand every title zeros dressed up as code.
linear_sweep and decode_at are the only places that insert into
`instructions`, so they are the only ones that need this bound. The
other readers of get_section_data only test bytes: the prologue-shape
and terminator helpers here decode zeros as `add [eax], al`, which is
neither; the prologue and CC-padding passes in functions.py match
nothing in zeros and only add candidates at addresses already decoded.
labels.py's string scan reads .rdata, which XBEs flag executable, so it
gets the fill too: a string running up to .rdata's raw end now finds
its terminator in the fill and gets a label, as the loaded image would
have it. The gap-alias clamp in functions.py ends an alias past raw_size
only at the end of the instruction that crosses it, or at raw_size.
"""
raw = getattr(section, "raw_size", None)
if raw is None:
raw = len(data)
return section.virtual_addr + min(raw, len(data))
class DisasmEngine:
"""
x86-32 disassembly engine backed by Capstone.
Supports both linear sweep (complete coverage) and recursive descent
(reachability validation) modes.
"""
def __init__(self, image: BinaryImage):
self.image = image
self._cs = Cs(CS_ARCH_X86, CS_MODE_32)
self._cs.detail = True
# Instruction cache: address -> Instruction
self.instructions: Dict[int, Instruction] = {}
# Sorted address list (built lazily for range queries)
self._sorted_addrs: Optional[List[int]] = None
# Embedded jump tables: table VA -> end VA (exclusive).
# Populated by resync_jump_tables() from the indexed indirect jumps
# recorded during the sweep.
self.jump_tables: Dict[int, int] = {}
self._jt_candidates: Set[int] = set()
# Indexed-jump displacement -> the (start, end) of each instruction
# that dispatches through it, and -> the table start it resolves to
# when the displacement is not the table's first slot.
self._jt_sites: Dict[int, List[Tuple[int, int]]] = {}
self._jt_base: Dict[int, int] = {}
# Byte-sized tables read through an index, `movzx eax, byte ptr
# [eax + disp]`. MSVC's two-level switch maps a sparse case value to a
# dense arm number this way and parks the byte table straight after
# the dword table it feeds. disp -> addresses of the reads, so that
# index_table_length() can find the bound check in front of one.
self.byte_tables: Dict[int, List[int]] = {}
def _classify_instruction(self, cs_insn: CsInsn) -> Instruction:
"""Convert a Capstone instruction to our Instruction type."""
mnemonic = cs_insn.mnemonic
insn = Instruction(
address=cs_insn.address,
size=cs_insn.size,
mnemonic=mnemonic,
op_str=cs_insn.op_str,
bytes_hex=cs_insn.bytes.hex(),
)
# Classify by mnemonic
insn.is_call = mnemonic in config.CALL_MNEMONICS
insn.is_ret = mnemonic in config.RET_MNEMONICS
insn.is_jump = mnemonic in config.JMP_MNEMONICS
insn.is_cond_jump = mnemonic in config.COND_JMP_MNEMONICS
insn.is_nop = mnemonic in config.NOP_MNEMONICS
# Resolve operand targets using Capstone detail
try:
operands = cs_insn.operands
except Exception:
operands = []
if operands:
op = operands[0]
if insn.is_call:
if op.type == CS_OP_IMM:
insn.call_target = op.imm & 0xFFFFFFFF
elif op.type == CS_OP_MEM and op.mem.base == 0 and op.mem.index == 0:
insn.memory_ref = op.mem.disp & 0xFFFFFFFF
elif insn.is_jump or insn.is_cond_jump:
if op.type == CS_OP_IMM:
insn.jump_target = op.imm & 0xFFFFFFFF
elif op.type == CS_OP_MEM and op.mem.base == 0 and op.mem.index == 0:
insn.memory_ref = op.mem.disp & 0xFFFFFFFF
elif op.type == CS_OP_MEM and op.mem.index != 0:
# `jmp dword ptr [reg*4 + disp]` -- a switch dispatch. disp
# is the address of a table of code pointers, and MSVC
# parks that table inside the function body, right after
# this instruction. See resync_jump_tables().
disp = op.mem.disp & 0xFFFFFFFF
if self.image.base_address <= disp < (
self.image.base_address + self.image.image_size):
insn.jump_table = disp
self._jt_candidates.add(disp)
self._jt_sites.setdefault(disp, []).append(
(insn.address, insn.end_address))
# Only the widening loads. `cmp byte ptr [esi + disp], 0` reads a
# byte field of a static struct, not an index table.
if mnemonic in ("movzx", "movsx") and len(operands) == 2:
src = operands[1]
if (src.type == CS_OP_MEM and src.size == 1
and (src.mem.index != 0 or src.mem.base != 0)):
disp = src.mem.disp & 0xFFFFFFFF
if self.image.base_address <= disp < (
self.image.base_address
+ self.image.image_size):
self.byte_tables.setdefault(disp, []).append(
insn.address)
# Check for memory references in non-branch instructions
if not (insn.is_call or insn.is_branch) and insn.memory_ref is None:
for operand in operands:
if (operand.type == CS_OP_MEM and
operand.mem.base == 0 and operand.mem.index == 0):
addr = operand.mem.disp & 0xFFFFFFFF
if self.image.base_address <= addr < (
self.image.base_address + self.image.image_size):
insn.memory_ref = addr
break
# Immediate operands that are addresses, e.g. `push offset str` or
# `mov reg, offset table`. These are how string literals and static
# data are almost always referenced, and they are NOT memory
# operands, so the memory_ref scan above never sees them. On calls
# and branches the immediate is the target, handled above.
if not (insn.is_call or insn.is_branch):
for operand in operands:
if operand.type != CS_OP_IMM:
continue
addr = operand.imm & 0xFFFFFFFF
if self.image.base_address <= addr < (
self.image.base_address + self.image.image_size):
insn.imm_ref = addr
break
return insn
def linear_sweep(self, section: SectionInfo,
progress_callback=None) -> int:
"""
Linear sweep disassembly of a section.
Decodes all bytes sequentially. On invalid byte sequences,
skips forward and resumes decoding.
Returns number of instructions decoded.
"""
data = self.image.get_section_data(section)
if not data:
return 0
va_start = section.virtual_addr
file_end = _file_end(section, data)
total = file_end - va_start
count = 0
offset = 0
while offset < total:
# Decode from current offset to end of section
chunk = data[offset:]
chunk_va = va_start + offset
last_end_offset = offset
for cs_insn in self._cs.disasm(chunk, chunk_va):
if cs_insn.address >= file_end:
break # the loader's zero fill finishes, never starts, code
insn = self._classify_instruction(cs_insn)
self.instructions[insn.address] = insn
count += 1
last_end_offset = (cs_insn.address + cs_insn.size) - va_start
# Progress reporting
if progress_callback and last_end_offset > offset:
progress_callback(min(last_end_offset, total), total)
if last_end_offset > offset:
offset = last_end_offset
else:
# Capstone couldn't decode anything - skip one byte
offset += 1
# If we've decoded to near the end, we're done
if offset >= total:
break
# Invalidate sorted address cache
self._sorted_addrs = None
if progress_callback:
progress_callback(total, total)
return count
def resync_jump_tables(self, min_entries: int = 3,
max_entries: int = 512) -> int:
"""
Treat MSVC's embedded switch tables as data and realign after them.
`jmp dword ptr [reg*4 + disp]` dispatches through a table of code
pointers, and MSVC emits that table inline -- inside the function, on
the fall-through path, immediately after the jump. linear_sweep has no
way to know, so it decodes the pointers as instructions and comes out
the far side out of phase. Every byte after it belongs to an
instruction that does not exist, up to wherever the stream happens to
resync.
That is not a cosmetic loss. It routinely eats the function's own
epilogue, so the `pop esi / pop edi` balancing the prologue is never
lifted and **every caller silently loses those registers**. Half-Life 2
hits it in the CRT: memcpy and memmove both carry a tail-copy table, so
the C++ static-initialiser loop -- which walks its constructor array
with esi as the cursor and edi as the limit -- had both clobbered by
its own callees and stopped after 8% of the list, leaving Source with
no registered interfaces to hand CreateInterface.
Fix it where it starts: measure each table, drop the instructions the
sweep hallucinated over it, and decode_at() past the end to pick the
real code back up. A table entry must point into an executable section
for the table to keep growing, which is what bounds it.
Returns the number of tables resynced.
"""
resynced = 0
for tbl in sorted(self._jt_candidates):
# XBEs mark .rdata and .data executable, so "points at an
# executable section" alone would let an array of data pointers
# pass as a jump table -- and resyncing over real instructions is
# far worse than missing a table. A switch never jumps out of its
# own section, so require that.
home = self.image.get_section_at_va(tbl)
if home is None:
continue
lo = home.virtual_addr
hi = lo + home.virtual_size
entries = 0
while entries < max_entries:
# MSVC's two-level switch parks the byte index table straight
# after the dword table. Its first bytes, small arm numbers
# such as `00 02 02 00`, read as a dword are an address low
# in the section, so the walk would take them as one more
# arm. A `movzx` names that byte table; stop in front of it.
if tbl + entries * 4 in self.byte_tables:
break
target = self.image.read_u32_at_va(tbl + entries * 4)
if target is None or not (lo <= target < hi):
break
entries += 1
ARM_WINDOW = 0x400
# MSVC's memcpy/memmove dispatch their lead bytes through
# `jmp [eax*4 + LeadUpVec - 4]` with eax 1..3: slot 0 is whatever
# sits in front of the table (the tail of the previous jmp, a nop)
# and is never read. The lifter already looks one slot on
# (_analyze_switch_table); measure the table from there too, or the
# function ends at its own dispatch and every arm after the table
# becomes an indirect call nothing resolves (MechAssault's memmove
# at 0x001D0580 ended at 0x001D05E4).
if entries == 0:
first = self.image.read_u32_at_va(tbl + 4)
ahead = 0
while (first is not None and lo <= first < hi
and ahead < max_entries):
slot = tbl + 4 + ahead * 4
if slot in self.byte_tables:
break
target = self.image.read_u32_at_va(slot)
if (target is None or not (lo <= target < hi)
or abs(target - first) > ARM_WINDOW):
break
ahead += 1
if ahead >= min_entries:
self._jt_base[tbl] = tbl + 4
tbl += 4
entries = ahead
# The displacement need not be the first slot. MSVC's memmove
# dispatches its backward tail through `jmp [ecx*4 + LAST]`, the
# table's last entry, with the index counting down from there --
# measured forward that is a one-entry table, dropped as too short,
# so the function ended at it and lost every arm and its epilogue.
# Walk down as well, stopping before the bytes of any instruction
# that dispatches through this table: a table parked right after
# its jmp would otherwise read the jmp's own displacement, which is
# an in-section address, as a slot.
#
# "Points into the section" is far too weak going down: the bytes
# before a table are usually the function's last instruction, and
# `ret N` (c2 NN 00) plus the byte before it reads as a small
# in-section address -- Wreckless lost three epilogues that way.
# A real slot points at the same arms, so the walk only accepts
# targets within ARM_WINDOW of the slot the displacement names --
# the one entry known to be real. Not of the whole forward run:
# that can over-read into a following byte-index table, whose
# `00 01 02 00` is itself an in-section address, and a window that
# wide let HL2's `leave; ret 4` in as a slot. A table measured one
# slot on has nothing below it: slot 0 is not a pointer.
sites = self._jt_sites.get(tbl, ())
anchor = (self.image.read_u32_at_va(tbl)
if entries and tbl not in self._jt_base.values() else None)
back = 0
while anchor is not None and entries + back < max_entries:
slot = tbl - (back + 1) * 4
if any(a < slot + 4 and slot < e for a, e in sites):
break
target = self.image.read_u32_at_va(slot)
if (target is None or not (lo <= target < hi)
or abs(target - anchor) > ARM_WINDOW):
break
back += 1
entries += back
if back:
self._jt_base[tbl] = tbl - back * 4
tbl -= back * 4
if entries < min_entries:
# Too short to distinguish from code that merely looks like
# pointers. Leaving it alone costs nothing; a wrong skip here
# would delete real instructions.
continue
end = tbl + entries * 4
for insn in self.get_instructions_in_range(
tbl - 16, end):
if insn.end_address > tbl and insn.address < end:
del self.instructions[insn.address]
self._sorted_addrs = None
self.jump_tables[tbl] = end
self.decode_at(end)
resynced += 1
return resynced
def index_table_length(self, table: int) -> Optional[int]:
"""Entries in the byte index table at `table`, read from the bound
check in front of a load from it, or None when there is none.
MSVC guards the load with the switch range:
cmp eax, N
ja default
movzx eax, byte ptr [eax + table]
jmp dword ptr [eax*4 + arms]
so the index is 0..N and the table holds N + 1 bytes.
"""
for site in self.byte_tables.get(table, ()):
ja = self._instruction_ending_at(site)
if ja is None or ja.mnemonic.lower() not in ("ja", "jae"):
continue
cmp = self._instruction_ending_at(ja.address)
if cmp is None or cmp.mnemonic.lower() != "cmp":
continue
_, _, imm = cmp.op_str.replace(" ", "").partition(",")
try:
bound = int(imm, 0)
except ValueError:
continue
if bound < 0:
continue
return bound + 1 if ja.mnemonic.lower() == "ja" else bound
return None
def _instruction_ending_at(self, addr: int) -> Optional[Instruction]:
for back in range(1, 16):
insn = self.instructions.get(addr - back)
if insn is not None and insn.end_address == addr:
return insn
return None
def is_jump_table_ref(self, addr: int) -> bool:
"""Does some `jmp [reg*4 + disp]` name `addr` as its table, measured
or not? resync_jump_tables skips tables shorter than min_entries, but
they are still tables."""
return addr in self._jt_candidates
def jump_table_entries(self, tbl: int) -> List[int]:
"""Code pointers held by a resynced jump table, or [] if unknown."""
tbl = self._jt_base.get(tbl, tbl)
end = self.jump_tables.get(tbl)
if end is None:
return []
return [self.image.read_u32_at_va(a) or 0
for a in range(tbl, end, 4)]
def decode_at(self, addr: int, max_insns: int = 4096,
replace_overlaps: bool = False) -> int:
"""
Decode a stream starting exactly at `addr`, realigning the sweep.
linear_sweep decodes each section as one stream and resyncs only by
skipping a byte when capstone fails. Where it enters a run of data --
a jump table, alignment padding, an embedded constant -- it comes out
the far side misaligned and stays that way until it happens to fall
back into step. Everything downstream keys off self.instructions, so an
address the sweep stepped over simply does not exist: recursive_descent
stops dead there (it only reads this dict, it never decodes), and
_pass_call_targets drops the candidate.
That is how Halo 2276 ended up with 46 direct call targets that never
became functions. 0x00017AB0 is named in a caller's own call list, is
16-aligned, and sits in a 5.7 KB hole between two detected functions --
the strongest evidence a function start can have, discarded because a
byte-skip upstream put the stream out of phase.
Decoding stops as soon as it lands on an address already decoded: at
that point the streams have converged and the rest is already correct.
So this rewrites only the out-of-phase run, not the section.
Overlapping decodes are left in place rather than evicted. On x86 two
valid instruction streams really can share bytes, and the callers that
matter walk forward by end_address from a known start, so each follows
its own chain. Evicting the old one would corrupt whichever function
was already using it. With replace_overlaps, the caller has verified
that the old stream is unclaimed, so its overlapping instructions go.
Returns the number of instructions newly decoded.
"""
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return 0
data = self.image.get_section_data(section)
if not data:
return 0
offset = addr - section.virtual_addr
file_end = _file_end(section, data)
if offset < 0 or addr >= file_end:
return 0
added = 0
overlaps = set()
for cs_insn in self._cs.disasm(data[offset:], addr):
if cs_insn.address >= file_end:
break
if cs_insn.address != addr and cs_insn.address in self.instructions:
break # resynced with the existing stream
if replace_overlaps:
overlaps.update(old.address for old in
self.get_instructions_in_range(
cs_insn.address - 15,
cs_insn.address + cs_insn.size)
if old.address != cs_insn.address
and old.end_address > cs_insn.address)
if cs_insn.address not in self.instructions:
self.instructions[cs_insn.address] = \
self._classify_instruction(cs_insn)
added += 1
insn = self.instructions[cs_insn.address]
if insn.is_terminator:
break
if added >= max_insns:
break
for old_addr in overlaps:
del self.instructions[old_addr]
if added or overlaps:
self._sorted_addrs = None
return added
def block_tail_jump(self, addr: int, max_insns: int = 256):
"""
Where the straight-line block at `addr` jumps, if it ends in an
unconditional jmp rather than a ret.
probes_as_returning_body deliberately stops at such a jump, because for
a weak candidate -- an address that merely appeared as an immediate --
a tail jump is not evidence of a function. But for a branch target that
is already known to be reached from inside a function, the jump is the
block's terminator and its destination is the rest of the same
function. Half-Life 2's _lock helper reaches its loop tail this way:
"cmp [ebp-0x1c],-1 / jne / inc edi / jmp back into the body".
Returns the jump target, or None if the block rets, runs long, or ends
in something that is not a direct jmp.
"""
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return None
# Stay inside the section's file bytes: a long bound past the end of
# the image would otherwise read nothing at all.
data = self.image.get_section_data(section)
data = data[addr - section.virtual_addr:][:max_insns * 8]
if not data:
return None
count = 0
for decoded in self._cs.disasm(data, addr):
count += 1
if count > max_insns:
return None
mnemonic = decoded.mnemonic.lower()
if mnemonic in config.RET_MNEMONICS:
return None # a ret block: not this shape
if mnemonic in config.JMP_MNEMONICS:
try:
ops = decoded.operands
except Exception:
return None
if not ops or ops[0].type != CS_OP_IMM:
return None # indirect: nothing to name
return ops[0].imm & 0xFFFFFFFF
return None
def probes_as_returning_body(self, addr: int,
max_insns: int = 64) -> bool:
"""
Stricter sibling of probes_as_function_body: does the stream at `addr`
reach a `ret` without first hitting an unconditional `jmp`?
Used where the evidence that something is a function is weak -- an
address that merely appears as an immediate -- so the bar has to be
higher than "decodes to some terminator". Requiring a ret rejects data
that happens to disassemble, and stopping at an unconditional jmp keeps
this out of tail-call territory, which _pass_tail_jump_targets already
covers with better evidence. Conditional branches are fine: a real
function has them. So is a switch dispatch through a table that
resync_jump_tables has measured: the probe continues in its arms.
"""
return self._probe_straight_line(addr, max_insns) == ("ret", None)
def probe_tail_call(self, addr: int,
max_insns: int = 64) -> Optional[int]:
"""
Where the body at `addr` tail-jumps, when the walk
probes_as_returning_body makes ends in a direct `jmp` out of the window
rather than a ret. None otherwise.
The tail jump on its own is not evidence -- data disassembles into a
stray `jmp` readily -- so this only reports the destination. A caller
that finds it is the exact start of a known function has a body that
ends in "return f(...)", which is how MSVC emits frameless wrappers and
the `mov eax, <FuncInfo>; jmp __CxxFrameHandler` handler thunks.
"""
kind, target = self._probe_straight_line(addr, max_insns)
return target if kind == "tail" else None
def _probe_straight_line(self, addr: int, max_insns: int):
"""Shared walk for the two probes above.
Returns ("ret", None), ("tail", target) for a direct jmp that leaves
the window or goes backwards, or (None, None) for anything else.
A walk that crossed int3 never counts as a tail call: it started in
alignment padding and ran into the function after it. One title has
an immediate naming the last int3 before a function that tail-jumps.
"""
crossed_padding = False
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return None, None
count = 0
resume = addr
# One pass per straight-line segment. A segment ends at a ret (yes),
# at anything tail-call shaped (no), or at a switch dispatch through
# a table this engine has already measured -- which is neither: the
# function continues in its arms, so the probe resumes at the first
# arm past the jump and keeps its instruction budget. A function
# reached only as an immediate, with no prologue, that opens with
# exactly that dispatch was otherwise refused, and the switch tables
# it owns were translated nowhere.
while resume is not None and count < max_insns:
data = self.image.read_bytes_at_va(resume, (max_insns - count) * 8)
if not data:
return None, None
limit = resume + len(data)
start = resume
resume = None
for decoded in self._cs.disasm(data, start):
count += 1
mnemonic = decoded.mnemonic.lower()
if mnemonic == "int3":
crossed_padding = True
if mnemonic in config.RET_MNEMONICS:
return "ret", None
if mnemonic in config.JMP_MNEMONICS:
# An unconditional jump forward, still inside the window
# being probed, is ordinary control flow -- MSVC emits it
# constantly to skip an else-branch. Only a jump that
# leaves the window, or goes backwards, is tail-call
# shaped and ends the probe.
#
# Rejecting every jmp cost Half-Life 2 its
# CreateInterface list walk (0x00427F80): a clean 90-byte
# function that happens to contain one `jmp` over four
# instructions.
try:
ops = decoded.operands
except Exception:
return None, None
if not ops:
return None, None
if ops[0].type == CS_OP_MEM and ops[0].mem.index != 0:
arm = self._first_arm_after(
ops[0].mem.disp & 0xFFFFFFFF, decoded.address)
if arm is None:
return None, None
resume = arm
break
if ops[0].type != CS_OP_IMM:
return None, None
target = ops[0].imm & 0xFFFFFFFF
if not (decoded.address < target < limit):
if crossed_padding:
return None, None
return "tail", target
if count >= max_insns:
return None, None
return None, None
def probes_as_callback_body(self, addr: int, upper: int,
lower: Optional[int] = None,
tail_targets=(), *, require_entry_frame=False,
allow_indirect_tails=False,
escapes: Optional[Set[int]] = None) -> bool:
"""Read-only proof of a closed callback CFG inside an unclaimed gap.
Calls may return from other functions; branches and fallthrough must
stay on decoded instruction boundaries. Reuse the translator's CFG
decoder and the sweep's measured switch tables, without a size cap.
allow_indirect_tails: an indirect jmp that is not a measured table is
an exit. True takes any form; "mem" takes a memory operand
(`jmp [reg + N]`, a vtable slot or a function-pointer field), or a
register the body itself wrote, never a bare `jmp reg`.
escapes: when given, a direct jmp or jcc out of [lower, upper) to an
address nobody has proven is not a refusal: the destination is added
to the set and the edge counts as an exit. The body is closed only
once the caller proves every destination itself, in its own gap.
A switch arm outside the gap counts as an exit when it is in
tail_targets, whether or not escapes is given.
"""
from ..recomp.disasm import Disassembler
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return False
data = self.image.get_section_data(section)
lower = addr if lower is None else max(lower, section.virtual_addr)
upper = min(upper, section.virtual_addr + len(data))
raw = data[lower - section.virtual_addr:upper - section.virtual_addr]
if require_entry_frame:
# A weak table word may name a suffix after its owner's cmp.
# Reject an entry prefix that reads arithmetic flags before
# producing them. String operations may read the ABI's DF. A
# writer defines only its own flags: inc and dec leave CF.
pending = {"AF", "CF", "OF", "PF", "SF", "ZF"}
flag = lambda kind, name: getattr(x86_const, f"X86_EFLAGS_{kind}_{name}")
for insn in self._cs.disasm(raw[addr - lower:], addr):
if (X86_REG_EFLAGS in insn.regs_read
and (not insn.eflags or any(
insn.eflags & flag("TEST", f) for f in pending))):
return False
if X86_REG_EFLAGS in insn.regs_write:
pending = {f for f in pending if insn.eflags and not any(
insn.eflags & flag(kind, f)
for kind in ("MODIFY", "SET", "RESET", "UNDEFINED"))}
if not pending or insn.mnemonic in ("call", "jmp", "ret", "retn"):
break
# One decoder for every probe: the sweep probes tens of thousands of
# gaps, often the same bytes again, and each probe re-decodes its gap
# whenever a switch adds arms. The probe only reads the instructions.
decoder = self.__dict__.get("_probe_decoder")
if decoder is None:
decoder = self._probe_decoder = Disassembler(cache_cfg_decodes=True)
entries = {addr}
tables = {}
indirect_tails = set()
while True:
decoded = decoder.disassemble_cfg(
raw, lower, upper, entries,
stop_mnemonics=("int3", "int", "ud2", "hlt", "iret", "iretd"))
arms = set()
for insn in decoded:
if not insn.is_jump or insn.jump_target is not None:
continue
if not insn.operands:
return False
op = insn.operands[0]
if (allow_indirect_tails
and (op.type != "mem" or not op.mem_index
or not self.jump_table_entries(op.mem_disp))):
# "mem": `jmp reg` only when the body loaded that
# register itself, a handler fetched from a table
# (`mov eax, [eax*4+T] ; ... ; jmp eax`). A lone `ff e0`
# decoded from a stray word has no such load.
if (allow_indirect_tails == "mem" and op.type != "mem"
and not (op.type == "reg" and any(
op.reg in other.regs_written
for other in decoded if other is not insn))):
return False
indirect_tails.add(insn.address)
continue
if (op.type != "mem" or not op.mem_index or op.mem_base
or op.mem_scale != 4 or op.mem_seg):
return False
targets = self.jump_table_entries(op.mem_disp)
# An arm outside the gap is fine when it is a proven entry: a
# dispatcher whose arms are other functions (a two-instruction
# `mov eax, [ecx+N]; jmp [eax*4+table]` method) exits into
# them as a tail call does.
if not targets or any(not lower <= t < upper
and t not in tail_targets for t in targets):
return False
tables[insn.address] = targets
arms.update(t for t in targets if lower <= t < upper)
if arms <= entries:
break
entries.update(arms)
starts = {insn.address for insn in decoded}
call_ends = {insn.end_address for insn in decoded if insn.is_call}
branch_targets = {insn.jump_target for insn in decoded if insn.is_branch}
branch_targets.update(arms)
end = lower
exits = backward = False
for insn in decoded:
if insn.address < end or insn.end_address > upper:
return False # two reachable streams overlap
end = insn.end_address
# Same no-return shape as static callback recovery. A branch into
# the padding is a trap, not evidence that the call never returns.
if (insn.mnemonic == "int3" and insn.address in call_ends
and insn.address not in branch_targets):
exits = True
continue
if (set(insn.groups) & {CS_GRP_INT, CS_GRP_IRET, CS_GRP_PRIVILEGE}
or insn.mnemonic.split()[-1] in (
"ud2", "ud0", "ud1", "retf", "in", "out",
"insb", "insw", "insd", "outsb", "outsw", "outsd")):
return False
if insn.is_ret or insn.address in indirect_tails:
exits = True
continue
edges = []
if insn.is_branch:
edges = ([insn.jump_target] if insn.jump_target is not None
else tables.get(insn.address, []))
if not edges:
return False
if not insn.is_jump:
edges = [*edges, insn.end_address]
for edge in edges:
if edge in starts:
continue
if edge in tail_targets and (edge == insn.jump_target
or insn.address in tables):
exits = True # preserve proven tails to existing bodies
continue
# A direct jump or branch out of the gap to code nobody has
# proven yet. The caller may prove that destination on its
# own (escapes); until it does, this body is not closed.
if (escapes is not None and edge == insn.jump_target
and not lower <= edge < upper):
escapes.add(edge)
exits = True
continue
return False
backward |= any(edge in starts and edge <= insn.address for edge in edges)
if require_entry_frame:
saved = {insn.op_str for insn in decoded if insn.mnemonic == "push"}
restored = {insn.op_str for insn in decoded if insn.mnemonic == "pop"}
restored &= {"ebx", "esi", "edi", "ebp"}
# A callable shared body must supply its own saved registers. An
# epilogue suffix that consumes its owner's saves is not an entry.
if restored - saved:
return False
# Nor may it free a frame or stack it never built.
# shortcut: checks which instructions appear, not stack depth;
# walk the depth per path if a suffix ever frees more than it built.
esp = lambda insn, m: insn.mnemonic == m and insn.op_str.startswith("esp,")
if any(insn.mnemonic == "leave" for insn in decoded) and "ebp" not in saved:
return False
if (any(esp(insn, "add") for insn in decoded)
and not any(insn.mnemonic in ("push", "enter") or esp(insn, "sub")
for insn in decoded)):
return False
if not (backward or restored or any(insn.is_ret for insn in decoded)
or any(insn.mnemonic == "int3" and insn.address in call_ends
for insn in decoded)
or all("esp" not in insn.regs_written for insn in decoded)):
return False
return bool(decoded) and (exits or backward)
def _first_arm_after(self, table: int, site: int) -> Optional[int]:
"""The lowest entry of a measured jump table that lies past `site`,
or None when `table` is not one this engine has measured."""
entries = self.jump_table_entries(table)
later = [a for a in entries if a > site]
return min(later) if later else None
def probes_as_vcall_thunk(self, addr: int) -> bool:
"""Is this MSVC's virtual-call thunk?
mov eax, [ecx] ; load the vtable from `this`
jmp dword ptr [eax + N] ; dispatch to slot N
A real function, and one that only ever exists as a value in a table --
the compiler emits them for pointers-to-virtual-member-functions and
for interface forwarding. They end in an indirect tail jump and never
reach a `ret`, so probes_as_returning_body rejects them, and they are
packed back to back with no int3 between them, so the padding boundary
pass does not see them either.
Half-Life 2 has 568 of these and only 41 were being found. Each missed
one is an indirect call the runtime cannot resolve, so the call is
skipped rather than made: two of them, at 0x00583BE2 and 0x00583BFA,
were being reached 22 million times in a boot that then sat spinning.
Matched shape-exactly rather than by relaxing the general prober,
because "ends in an indirect jump" on its own is weak evidence that
data happens to disassemble into.
"""
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return False
data = self.image.read_bytes_at_va(addr, 16)
if not data:
return False
insns = list(self._cs.disasm(data, addr, count=3))
# A thunk into a member subobject adjusts `this` first:
#
# mov ecx, [ecx + 8] ; or add/sub ecx, imm
# mov eax, [ecx]
# jmp dword ptr [eax + 0x80]
#
# Half-Life 2's 0x00452AC0 is one, named only by a vtable without
# RTTI. Missing it skipped the call and the boot crashed a few
# million calls later.
if len(insns) == 3 and self._is_this_adjust(insns[0]):
insns = insns[1:]
if len(insns) < 2:
return False
load, dispatch = insns[:2]
if load.mnemonic.lower() != "mov":
return False
try:
load_ops = load.operands
jmp_ops = dispatch.operands
except Exception:
return False
# mov <reg>, [<reg>] -- the vtable load, no index, no displacement
if len(load_ops) != 2:
return False
dst, src = load_ops
if dst.type != CS_OP_REG or src.type != CS_OP_MEM:
return False
if src.mem.base == 0 or src.mem.index != 0 or src.mem.disp != 0:
return False
if dispatch.mnemonic.lower() not in config.JMP_MNEMONICS:
return False
if len(jmp_ops) != 1 or jmp_ops[0].type != CS_OP_MEM:
return False
# ...through the register the load just filled.
return jmp_ops[0].mem.base == dst.reg and jmp_ops[0].mem.index == 0
@staticmethod
def _is_this_adjust(insn) -> bool:
"""mov ecx, [ecx + N] / mov ecx, [N] / add ecx, imm / sub ecx, imm."""
m = insn.mnemonic.lower()
try:
ops = insn.operands
except Exception:
return False
if len(ops) != 2 or ops[0].type != CS_OP_REG or ops[0].reg != x86_const.X86_REG_ECX:
return False
if m == "mov":
# [ecx + N] for a member subobject, or [N] for a global object
# (Half-Life 2's 0x00457420: mov ecx, [0x0080C1F0]).
src = ops[1]
return (src.type == CS_OP_MEM and src.mem.index == 0
and src.mem.disp != 0
and src.mem.base in (x86_const.X86_REG_ECX, 0))
return m in ("add", "sub") and ops[1].type == CS_OP_IMM
def probes_as_prologue(self, addr: int) -> bool:
"""
Read-only: do the bytes at `addr` start with a recognisable MSVC
function prologue?
Weaker evidence than probes_as_function_body, and deliberately so:
this is asked about an address the linear sweep has already claimed as
the middle of an instruction, where a full-body probe would have to
decide which of two overlapping decodings is real. A prologue is the
one shape that does not occur by accident in the middle of another
instruction, so it is enough to say the sweep drifted rather than that
the address is wrong.
Recognises what MSVC actually emits at -O2 for the Xbox XDK: the
frame-pointer form, the register saves that start a frameless
function, the stack adjustment, and the two-byte hot-patch nop.
"""
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return False
data = self.image.get_section_data(section)
if not data:
return False
offset = addr - section.virtual_addr
if offset < 0 or offset >= len(data):
return False
insns = list(self._cs.disasm(data[offset:offset + 16], addr, count=2))
if not insns:
return False
first = insns[0]
m, ops = first.mnemonic, first.op_str
if m == "push" and ops == "ebp":
# push ebp; mov ebp, esp -- or lea ebp, [esp-N] for a frame the
# callee shifts, which is what default.xbe's XPP code uses.
if len(insns) > 1:
nxt = insns[1]
if nxt.mnemonic == "mov" and nxt.op_str.replace(" ", "") == "ebp,esp":
return True
if nxt.mnemonic == "lea" and nxt.op_str.startswith("ebp,"):
return True
return False
if m == "push" and ops in ("esi", "edi", "ebx"):
return True
if m == "sub" and ops.startswith("esp,"):
return True
if m == "mov" and ops.replace(" ", "") == "edi,edi":
return True # hot-patch pad
# A function whose frame __SEH_prolog builds:
#
# push <frame size> immediate
# push <scope table> immediate
# call __SEH_prolog
#
# There is no "push ebp; mov ebp, esp" to find, because the helper does
# that on the caller's behalf, so none of the shapes above match and
# such a function is invisible to every pass that asks this question.
# Half-Life 2 has one at 0x001F572B, reached only through a vtable: the
# call could not be resolved, so it was skipped rather than made, and
# the arguments already pushed for it stayed on the stack. That shifted
# the caller's frame, and its "pop ebx" then restored the wrong slot.
#
# Two immediate pushes followed by a call is specific enough not to
# occur by accident -- and this is only ever asked about an address
# that already looks like a boundary.
if m == "push" and ops.startswith("0x") and len(insns) > 1:
nxt = insns[1]
if nxt.mnemonic == "push" and nxt.op_str.startswith("0x"):
third = list(self._cs.disasm(
data[offset:offset + 24], addr, count=3))
if len(third) > 2 and third[2].mnemonic == "call":
return True
# A frame larger than a page, which MSVC opens with a stack probe:
#
# mov eax, <frame size>
# call __chkstk (_alloca_probe)
#
# Same reason as __SEH_prolog: the helper moves esp, so there is no
# push/sub to find. Half-Life 2's 0x00426370 (mov eax, 0x8028) is
# reached only through a vtable without RTTI; once code after int3
# padding had to probe as code, it and every function like it
# vanished, and the vtable call went to nothing.
if (m == "mov" and ops.startswith("eax, 0x") and len(insns) > 1
and insns[1].mnemonic == "call"):
return True
return False
def probes_as_constant_stub(self, addr: int) -> bool:
"""Is this the whole of a constant-returning accessor?
mov <reg>, <imm32>
ret [imm16]
MSVC emits runs of these for members that return a fixed address, packs
them back to back with no padding, and reaches them only through
vtables -- so no pass that looks for a prologue, padding or a call site
finds them. Half-Life 2 has 3,147.
Matched exactly, and not by asking a general "does a ret come soon"
probe. That was tried: allowing any short run ending in ret added 825
function starts instead of the 19 this shape accounts for, because data
and mid-function fragments satisfy it too, and the title stopped
loading. The narrow rule is the honest one -- it is what was measured.
"""
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return False
data = self.image.get_section_data(section)
if not data:
return False
offset = addr - section.virtual_addr
if offset < 0 or offset >= len(data):
return False
insns = list(self._cs.disasm(data[offset:offset + 12], addr, count=2))
if len(insns) != 2:
return False
first, second = insns
if first.mnemonic != "mov":
return False
try:
ops = first.operands
except Exception:
return False
if len(ops) != 2 or ops[0].type != CS_OP_REG or ops[1].type != CS_OP_IMM:
return False
return second.mnemonic in config.RET_MNEMONICS
def probes_as_function_body(self, addr: int,
max_insns: int = 8192) -> bool:
"""
Read-only: does the instruction stream starting at `addr` look like a
function body -- i.e. does it reach a ret or a tail jump without
running into bytes that will not decode?
Corroboration for a direct call target the linear sweep stepped over.
Alignment used to serve that role, but a real MSVC function start is
only aligned when the linker had a reason to pad it; the CRT's
_mtinitlocks sits at Wreckless 0x000F211A, immediately after a jump
table, at no alignment at all. Decoding is the stronger evidence and
the one that actually distinguishes code from a plausible-looking
address read out of data.
Follows instructions the sweep already decoded where they exist, and
decodes the rest here without recording them, so calling this never
changes what the sweep produced.
max_insns only bounds the walk's cost -- leaving the section already
terminates it. Keep it well clear of the largest real function: Blood
Wake 0x0005E670 runs 537 instructions before its first ret, and a cap
of 512 rejected it.
"""
section = self.image.get_section_at_va(addr)
if section is None or not section.executable:
return False
data = self.image.get_section_data(section)
if not data:
return False
for _ in range(max_insns):
insn = self.instructions.get(addr)
if insn is not None:
if insn.is_ret or insn.is_jump:
return True
addr = insn.end_address
else:
offset = addr - section.virtual_addr
if offset < 0 or offset >= len(data):
return False
decoded = next(self._cs.disasm(data[offset:], addr, count=1),
None)
if decoded is None:
return False # undecodable: not code
mnemonic = decoded.mnemonic.lower()
if (mnemonic in config.RET_MNEMONICS
or mnemonic in config.JMP_MNEMONICS):
return True
addr += decoded.size
if not (section.virtual_addr <= addr
< section.virtual_addr + section.virtual_size):
return False # ran off the section without terminating
return False
def recursive_descent(self, start_addresses: List[int],
section_bounds: List[Tuple[int, int]]) -> Set[int]:
"""
Recursive descent from given start addresses.
Follows control flow to determine reachable instructions.
Returns set of reachable instruction addresses.
"""
reachable: Set[int] = set()
worklist = list(start_addresses)
visited_starts: Set[int] = set()
def in_bounds(addr: int) -> bool:
return any(s <= addr < e for s, e in section_bounds)
while worklist:
addr = worklist.pop()
if addr in visited_starts:
continue
visited_starts.add(addr)
# Walk the instruction stream linearly from this start point
while True:
if addr in reachable:
break # Already explored from here
if not in_bounds(addr):
break
insn = self.instructions.get(addr)
if insn is None:
# Tried calling decode_at here to realign, on the theory
# that descent was being truncated by the same out-of-phase
# runs decode_at fixes for call targets. Measured on Halo
# 2276: +138 reachable instructions out of 640k (0.02%),
# zero new functions, and one tail_jump_target lost. Not
# worth the risk of following a bad decode deeper.
#
# It is small because descent starts from function heads the
# sweep already decoded and stops at ret/jmp, so it seldom
# walks into a hole in the first place -- the call-target
# path in _pass_call_targets already catches the cases that
# matter. See docs/technical/ms-fusion-adoption-plan.md.
break
reachable.add(addr)
# Follow call targets (but continue past the call)
if insn.is_call and insn.call_target is not None:
if in_bounds(insn.call_target) and insn.call_target not in visited_starts:
worklist.append(insn.call_target)
# Follow conditional jump targets (and continue fall-through)
if insn.is_cond_jump and insn.jump_target is not None:
if in_bounds(insn.jump_target) and insn.jump_target not in visited_starts:
worklist.append(insn.jump_target)
# Unconditional jump: follow target, stop linear walk
if insn.is_jump:
if insn.jump_target is not None and in_bounds(insn.jump_target):
if insn.jump_target not in visited_starts:
worklist.append(insn.jump_target)
break
if insn.is_ret:
break
addr = insn.end_address
return reachable
def get_instruction(self, address: int) -> Optional[Instruction]:
"""Get a decoded instruction by address."""
return self.instructions.get(address)
def _ensure_sorted_addrs(self):
"""Build sorted address list if not cached."""
if self._sorted_addrs is None:
self._sorted_addrs = sorted(self.instructions.keys())
def instruction_covering(self, addr: int) -> Optional[Instruction]:
"""The decoded instruction whose bytes contain `addr` but do not start
at it, or None.
A hit means the sweep already has a coherent decode across this
address, so anything claiming a function starts here is claiming an
instruction boundary in the middle of an instruction. That is worth
distrusting: realigning there splits whatever the address sits in.
"""
self._ensure_sorted_addrs()
# Scan back over the longest an x86 instruction can be, rather than
# looking only at the nearest preceding start. Overlapping decodes are
# allowed here -- decode_at leaves the stream it realigned over in
# place -- so `addr` can be a recorded boundary *and* sit inside an
# instruction the sweep decoded. Checking one neighbour misses exactly
# that case, which is the one worth catching.
i = bisect.bisect_left(self._sorted_addrs, addr)
j = bisect.bisect_left(self._sorted_addrs, addr - 15)
for k in range(i - 1, j - 1, -1):
if k < 0:
break
insn = self.instructions[self._sorted_addrs[k]]
if insn.address < addr < insn.address + insn.size:
return insn
return None
def get_instructions_in_range(self, start: int, end: int) -> List[Instruction]:
"""Get all instructions in address range [start, end), sorted."""
self._ensure_sorted_addrs()
import bisect
lo = bisect.bisect_left(self._sorted_addrs, start)
hi = bisect.bisect_left(self._sorted_addrs, end)
return [self.instructions[self._sorted_addrs[i]]
for i in range(lo, hi)]
def instruction_count(self) -> int:
return len(self.instructions)
def get_call_targets(self) -> Set[int]:
"""Return all direct call target addresses."""
targets = set()
for insn in self.instructions.values():
if insn.call_target is not None:
targets.add(insn.call_target)
return targets
def get_indirect_call_refs(self) -> Dict[int, List[int]]:
"""
Return memory addresses referenced by indirect calls.
Maps: memory_address -> [calling_instruction_addresses]
"""
refs: Dict[int, List[int]] = {}
for insn in self.instructions.values():
if insn.is_call and insn.memory_ref is not None:
refs.setdefault(insn.memory_ref, []).append(insn.address)
return refs