feat(verify): unicorn per-function differential harness (x87 ST0 capture, rvadb convention)
This commit is contained in:
1 parent
16f2556b23
commit
39f01099a5
10 files changed
+679
No files matched your search
@@ -0,0 +1,3 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
.pytest_cache/
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Calibrate real FUN_101ab6d0 x87 returns and differential detection.
|
||||
|
||||
Run from the worktree:
|
||||
tools/unicorn_diff/.venv/bin/python tools/unicorn_diff/calibrate.py
|
||||
"""
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
|
||||
from udiff import (
|
||||
Buffer, CallSpec, FloatTolerance, PeImage, RegValue,
|
||||
ReturnKind, RunResult, UnicornRunner, Verdict, detect_fp, diff,
|
||||
)
|
||||
from udiff.abi import f32
|
||||
from udiff.metadata import RVADB_PATH, load_calling_convention
|
||||
|
||||
|
||||
def calibrate(dll: Path) -> None:
|
||||
"""Compare real register-ABI calls with independently computed distances."""
|
||||
image = PeImage(dll)
|
||||
runner = UnicornRunner(image)
|
||||
convention = load_calling_convention(0x1AB6D0)
|
||||
print(f"metadata={RVADB_PATH} RVA=0x1ab6d0 calling_convention={convention.value}")
|
||||
model = detect_fp(image.read(0x1AB6D0, 0xDA), image.va(0x1AB6D0))
|
||||
assert model.name == "x87", model
|
||||
print(f"DLL={dll} base={image.image_base:#x} VA={image.va(0x1AB6D0):#x}")
|
||||
print(f"FP={model.name} flags={' '.join(model.compiler_flags)}")
|
||||
tolerance = FloatTolerance(absolute=1e-6, relative=1e-6)
|
||||
print(f"tolerance: absolute={tolerance.absolute} relative={tolerance.relative}")
|
||||
center = (1.0, 2.0, 3.0)
|
||||
extent = (2.0, 3.0, 4.0)
|
||||
box = Buffer("box", struct.pack("<6f", *center, *extent))
|
||||
for point in ((6.0, 9.0, 7.0), (-4.0, -5.0, 3.0), center):
|
||||
original = runner.run(CallSpec(
|
||||
rva=0x1AB6D0,
|
||||
conv=convention,
|
||||
ret=ReturnKind.FLOAT_ST0,
|
||||
regs=(
|
||||
RegValue("eax", buffer=box),
|
||||
RegValue("edi", buffer=Buffer("point", struct.pack("<3f", *point))),
|
||||
),
|
||||
))
|
||||
# Binary: center +/- extent spill to float; max(lower, point),
|
||||
# min(upper, result); subtract point; sum squares; final float spill.
|
||||
# These integral fixtures keep intermediate products exact in both
|
||||
# Python binary64 and the original x87 extended precision.
|
||||
offsets = tuple(
|
||||
f32(p - min(f32(c + e), max(f32(c - e), p)))
|
||||
for p, c, e in zip(point, center, extent, strict=True)
|
||||
)
|
||||
expected = f32(sum(value * value for value in offsets))
|
||||
reference = RunResult(eax=0, st0=expected)
|
||||
matching = diff(original, reference, tolerance)
|
||||
assert original.st0_raw is not None, "real x87 register capture missing"
|
||||
assert matching.verdict is Verdict.EQUAL, matching
|
||||
print(
|
||||
f"point={point} ST(0)={original.st0} raw={original.st0_raw} "
|
||||
f"steps={original.steps} reference={expected} match={matching.verdict.value}"
|
||||
)
|
||||
# Inject a wrong additive constant into the reference calculation.
|
||||
wrong_reference = replace(reference, st0=f32(expected + 1.0))
|
||||
injected = diff(original, wrong_reference, tolerance)
|
||||
assert injected.verdict is Verdict.DIFF, injected
|
||||
assert len(injected.differences) == 1, injected
|
||||
assert injected.differences[0].startswith("ST(0):"), injected
|
||||
print(f"injected-bug={injected.verdict.value} {injected.differences[0]}")
|
||||
assert original.st0 is not None
|
||||
# All fields, including EAX and raw capture, remain identical except
|
||||
# the decoded ST(0). This isolates the comparator's floating channel.
|
||||
mutated = replace(original, st0=original.st0 + 2.0)
|
||||
mutation = diff(original, mutated, tolerance)
|
||||
assert mutation.verdict is Verdict.DIFF, mutation
|
||||
assert len(mutation.differences) == 1, mutation
|
||||
assert mutation.differences[0].startswith("ST(0):"), mutation
|
||||
print(f"ST(0)-mutation={mutation.verdict.value} {mutation.differences[0]}")
|
||||
print("PASS: real x87 capture, reference match, injected bug, ST(0)-only mutation")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
calibrate(Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/home/athapa/ghidra/gamekdm.dll"))
|
||||
@@ -0,0 +1,4 @@
|
||||
unicorn==2.1.4
|
||||
capstone==5.0.7
|
||||
pefile==2024.8.26
|
||||
pytest==9.2.0
|
||||
@@ -0,0 +1,11 @@
|
||||
from .abi import Buffer, CallConv, CallSpec, RegValue, ReturnKind, StackValue
|
||||
from .image import PeImage
|
||||
from .fp import FpModel, detect_fp
|
||||
from .result import DiffReport, FloatTolerance, GlobalDelta, RunResult, Verdict, diff
|
||||
from .runner import UnicornRunner
|
||||
|
||||
__all__ = [
|
||||
"Buffer", "CallConv", "CallSpec", "DiffReport", "FloatTolerance",
|
||||
"GlobalDelta", "PeImage", "RegValue", "ReturnKind", "RunResult", "FpModel",
|
||||
"StackValue", "UnicornRunner", "Verdict", "diff", "detect_fp",
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import assert_never
|
||||
|
||||
REG_NAMES: tuple[str, ...] = ("eax", "ebx", "ecx", "edx", "esi", "edi", "ebp")
|
||||
|
||||
|
||||
class CallConv(Enum):
|
||||
CDECL = "cdecl"
|
||||
STDCALL = "stdcall"
|
||||
THISCALL = "thiscall"
|
||||
FASTCALL = "fastcall"
|
||||
REGISTER = "register"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class ReturnKind(Enum):
|
||||
INT = "int"
|
||||
FLOAT_ST0 = "float_st0"
|
||||
DOUBLE_ST0 = "double_st0"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Buffer:
|
||||
tag: str
|
||||
data: bytes
|
||||
out_size: int = 0
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.tag or self.out_size < 0:
|
||||
raise AbiError(detail="buffers need a name and a nonnegative output size")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RegValue:
|
||||
reg: str
|
||||
immediate: int | None = None
|
||||
buffer: Buffer | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.reg not in REG_NAMES:
|
||||
raise AbiError(detail=f"unknown register {self.reg!r}")
|
||||
if (self.immediate is None) == (self.buffer is None):
|
||||
raise AbiError(detail=f"register {self.reg}: set exactly one of immediate/buffer")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StackValue:
|
||||
immediate: int | None = None
|
||||
buffer: Buffer | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if (self.immediate is None) == (self.buffer is None):
|
||||
raise AbiError(detail="stack arg: set exactly one of immediate/buffer")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CallSpec:
|
||||
rva: int
|
||||
conv: CallConv
|
||||
ret: ReturnKind
|
||||
regs: tuple[RegValue, ...] = ()
|
||||
stack_args: tuple[StackValue, ...] = ()
|
||||
globals_watched: tuple[tuple[str, int, int], ...] = ()
|
||||
buffers: tuple[Buffer, ...] = field(default=())
|
||||
branch_sites: tuple[int, ...] = ()
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
names = [reg.reg for reg in self.regs]
|
||||
if len(names) != len(set(names)):
|
||||
raise AbiError(detail="register inputs must be unique")
|
||||
if self.conv is CallConv.THISCALL and "ecx" not in names:
|
||||
raise AbiError(detail="thiscall requires this in ECX via RegValue")
|
||||
if self.conv is CallConv.UNKNOWN and self.stack_args:
|
||||
raise AbiError(detail="unknown convention cannot determine stack argument cleanup")
|
||||
if len(self.stack_args) * 4 > 0xFFF00:
|
||||
raise AbiError(detail="arguments exceed the mapped stack")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AbiError(Exception):
|
||||
detail: str
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"ABI error: {self.detail}"
|
||||
|
||||
|
||||
def f32(value: float) -> float:
|
||||
# Round only at observed DWORD spills, not after every x87 operation.
|
||||
return struct.unpack("<f", struct.pack("<f", value))[0]
|
||||
|
||||
|
||||
def pack_vec3_f32(x: float, y: float, z: float) -> bytes:
|
||||
return struct.pack("<fff", x, y, z)
|
||||
|
||||
|
||||
def cleanup_is_callee(conv: CallConv) -> bool:
|
||||
match conv:
|
||||
case CallConv.STDCALL | CallConv.THISCALL | CallConv.FASTCALL:
|
||||
return True
|
||||
case CallConv.CDECL | CallConv.REGISTER | CallConv.UNKNOWN:
|
||||
# UNKNOWN is permitted only without stack arguments by CallSpec.
|
||||
return False
|
||||
case unreachable:
|
||||
assert_never(unreachable)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""x87 return capture and instruction-derived floating point evidence."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
from capstone import CS_ARCH_X86, CS_MODE_32, Cs
|
||||
from capstone.x86_const import X86_GRP_FPU
|
||||
from unicorn import Uc
|
||||
from unicorn.x86_const import UC_X86_REG_FP0, UC_X86_REG_FPSW, UC_X86_REG_FPTAG
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FpError(Exception):
|
||||
detail: str
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"floating point error: {self.detail}"
|
||||
|
||||
|
||||
def capture_st0(cpu: Uc) -> tuple[float, tuple[int, int]]:
|
||||
"""Read physical FP[TOP], including exponent; UC_X86_REG_ST0 omits it."""
|
||||
top = (cpu.reg_read(UC_X86_REG_FPSW) >> 11) & 7
|
||||
if (cpu.reg_read(UC_X86_REG_FPTAG) >> (2 * top)) & 3 == 3:
|
||||
raise FpError(detail="floating return declared but ST(0) is empty")
|
||||
significand, sign_exponent = cpu.reg_read(UC_X86_REG_FP0 + top)
|
||||
exponent = sign_exponent & 0x7FFF
|
||||
sign = -1.0 if sign_exponent & 0x8000 else 1.0
|
||||
if exponent == 0x7FFF:
|
||||
value = math.inf if significand == 1 << 63 else math.nan
|
||||
else:
|
||||
try:
|
||||
value = math.ldexp(significand, max(exponent, 1) - 16383 - 63)
|
||||
except OverflowError:
|
||||
value = math.inf
|
||||
return math.copysign(value, sign), (significand, sign_exponent)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FpModel:
|
||||
x87_sites: tuple[int, ...]
|
||||
sse_sites: tuple[int, ...]
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
if self.x87_sites and self.sse_sites:
|
||||
return "mixed"
|
||||
if self.sse_sites:
|
||||
return "sse"
|
||||
if self.x87_sites:
|
||||
return "x87"
|
||||
return "unobserved"
|
||||
|
||||
@property
|
||||
def compiler_flags(self) -> tuple[str, ...]:
|
||||
if self.x87_sites and self.sse_sites:
|
||||
raise FpError(detail="mixed instructions require a per-function FP decision")
|
||||
math_flags = ("-mfpmath=sse", "-msse2") if self.sse_sites else ("-mfpmath=387",)
|
||||
return math_flags + ("-ffp-contract=off", "-fno-fast-math")
|
||||
|
||||
|
||||
def detect_fp(code: bytes, va: int) -> FpModel:
|
||||
"""Classify a bounded validity-gate disassembly, never the compiler version."""
|
||||
disassembler = Cs(CS_ARCH_X86, CS_MODE_32)
|
||||
disassembler.detail = True
|
||||
x87: list[int] = []
|
||||
sse: list[int] = []
|
||||
instructions = list(disassembler.disasm(code, va))
|
||||
if sum(ins.size for ins in instructions) != len(code):
|
||||
raise FpError(detail=f"incomplete instruction range at {va:#x}")
|
||||
for ins in instructions:
|
||||
if ins.group(X86_GRP_FPU):
|
||||
x87.append(ins.address)
|
||||
# Scalar FP instructions, including loads, comparisons and conversions.
|
||||
# An integer SSE instruction such as PXOR alone is not FP evidence.
|
||||
if "xmm" in ins.op_str and (
|
||||
ins.mnemonic.endswith(("ss", "sd")) or ins.mnemonic.startswith("cvt")
|
||||
):
|
||||
sse.append(ins.address)
|
||||
return FpModel(tuple(x87), tuple(sse))
|
||||
@@ -0,0 +1,87 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pefile
|
||||
from unicorn import Uc, UC_ARCH_X86, UC_MODE_32
|
||||
from unicorn.unicorn_const import UC_PROT_ALL
|
||||
from unicorn.x86_const import (
|
||||
UC_X86_REG_FPCW, UC_X86_REG_FPSW, UC_X86_REG_FPTAG, UC_X86_REG_MXCSR,
|
||||
)
|
||||
|
||||
PAGE = 0x1000
|
||||
STACK_BASE = 0x00200000
|
||||
STACK_SIZE = 0x00100000
|
||||
SCRATCH_BASE = 0x00400000
|
||||
SCRATCH_SIZE = 0x00100000
|
||||
CODE_SCRATCH = 0x00600000
|
||||
CODE_SCRATCH_SIZE = PAGE
|
||||
|
||||
|
||||
def _align_up(value: int, align: int = PAGE) -> int:
|
||||
return (value + align - 1) & ~(align - 1)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ImageError(Exception):
|
||||
detail: str
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"image error: {self.detail}"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class LoadedImage:
|
||||
image_base: int
|
||||
size: int
|
||||
dll_path: Path
|
||||
|
||||
|
||||
class PeImage:
|
||||
def __init__(self, dll_path: str | Path) -> None:
|
||||
self._path = Path(dll_path)
|
||||
if not self._path.is_file():
|
||||
raise ImageError(detail=f"dll not found: {self._path}")
|
||||
self._pe = pefile.PE(str(self._path), fast_load=True)
|
||||
if self._pe.FILE_HEADER.Machine != 0x14C or self._pe.OPTIONAL_HEADER.Magic != 0x10B:
|
||||
raise ImageError(detail="only x86 PE32 images are supported")
|
||||
self.image_base: int = int(self._pe.OPTIONAL_HEADER.ImageBase)
|
||||
self.size: int = _align_up(int(self._pe.OPTIONAL_HEADER.SizeOfImage))
|
||||
self._mapped: bytes = self._pe.get_memory_mapped_image(ImageBase=self.image_base)
|
||||
|
||||
@property
|
||||
def info(self) -> LoadedImage:
|
||||
return LoadedImage(image_base=self.image_base, size=self.size, dll_path=self._path)
|
||||
|
||||
def section_table(self) -> list[tuple[str, int, int]]:
|
||||
rows: list[tuple[str, int, int]] = []
|
||||
for sec in self._pe.sections:
|
||||
name = sec.Name.rstrip(b"\x00").decode("ascii", "replace")
|
||||
rows.append((name, self.image_base + int(sec.VirtualAddress), int(sec.Misc_VirtualSize)))
|
||||
return rows
|
||||
|
||||
def va(self, rva: int) -> int:
|
||||
if not 0 <= rva < self.size:
|
||||
raise ImageError(detail=f"RVA outside image: {rva:#x}")
|
||||
return self.image_base + rva
|
||||
|
||||
def read(self, rva: int, size: int) -> bytes:
|
||||
if size < 0 or rva < 0 or rva + size > self.size:
|
||||
raise ImageError(detail=f"read outside image: {rva:#x}+{size:#x}")
|
||||
return self._mapped[rva:rva + size].ljust(size, b"\x00")
|
||||
|
||||
def new_emulator(self) -> Uc:
|
||||
uc = Uc(UC_ARCH_X86, UC_MODE_32)
|
||||
image = self._mapped.ljust(self.size, b"\x00")[: self.size]
|
||||
uc.mem_map(self.image_base, self.size, UC_PROT_ALL)
|
||||
uc.mem_write(self.image_base, image)
|
||||
uc.mem_map(STACK_BASE, STACK_SIZE, UC_PROT_ALL)
|
||||
uc.mem_map(SCRATCH_BASE, SCRATCH_SIZE, UC_PROT_ALL)
|
||||
uc.mem_map(CODE_SCRATCH, CODE_SCRATCH_SIZE, UC_PROT_ALL)
|
||||
# Empty x87 stack, round-to-nearest, 64-bit significand (80-bit registers).
|
||||
uc.reg_write(UC_X86_REG_FPCW, 0x037F)
|
||||
uc.reg_write(UC_X86_REG_FPSW, 0)
|
||||
uc.reg_write(UC_X86_REG_FPTAG, 0xFFFF)
|
||||
uc.reg_write(UC_X86_REG_MXCSR, 0x1F80)
|
||||
return uc
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Read per-function calling conventions from the recovered RVA database."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Final
|
||||
|
||||
from .abi import AbiError, CallConv
|
||||
|
||||
RVADB_PATH: Final = Path(__file__).resolve().parents[3] / "re" / "rvadb.json"
|
||||
|
||||
|
||||
def load_calling_convention(
|
||||
address: int, metadata_path: Path = RVADB_PATH,
|
||||
) -> CallConv:
|
||||
"""Resolve an RVA or VA; preserve unknown rather than guessing an ABI."""
|
||||
with metadata_path.open(encoding="utf-8") as source:
|
||||
database = json.load(source)
|
||||
image_base = int(database["image_base"], 0)
|
||||
rva = address - image_base if address >= image_base else address
|
||||
for function in database["functions"]:
|
||||
if int(function["rva"], 0) == rva:
|
||||
recorded = function["calling_convention"]
|
||||
try:
|
||||
return CallConv(recorded.removeprefix("__"))
|
||||
except ValueError as error:
|
||||
raise AbiError(
|
||||
detail=f"unsupported convention {recorded!r} at RVA {rva:#x}",
|
||||
) from error
|
||||
raise AbiError(detail=f"function RVA {rva:#x} absent from {metadata_path}")
|
||||
@@ -0,0 +1,101 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Verdict(Enum):
|
||||
EQUAL = "EQUAL"
|
||||
DIFF = "DIFF"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GlobalDelta:
|
||||
tag: str
|
||||
rva: int
|
||||
before: bytes
|
||||
after: bytes
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RunResult:
|
||||
eax: int
|
||||
st0: float | None
|
||||
out_buffers: tuple[tuple[str, bytes], ...] = ()
|
||||
globals_delta: tuple[GlobalDelta, ...] = ()
|
||||
esp_before: int = 0
|
||||
esp_after: int = 0
|
||||
steps: int = 0
|
||||
st0_raw: tuple[int, int] | None = None
|
||||
branch_outcomes: tuple[tuple[int, bool], ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DiffReport:
|
||||
verdict: Verdict
|
||||
differences: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FloatTolerance:
|
||||
absolute: float = 1e-6
|
||||
relative: float = 1e-6
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not all(math.isfinite(v) and v >= 0 for v in (self.absolute, self.relative)):
|
||||
raise ComparisonError(detail="tolerances must be finite and nonnegative")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ComparisonError(Exception):
|
||||
detail: str
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"comparison error: {self.detail}"
|
||||
|
||||
|
||||
def changed_bytes(deltas: tuple[GlobalDelta, ...]) -> tuple[tuple[int, int, int], ...]:
|
||||
"""Compare net changes independent of watch names or machine store widths."""
|
||||
changes: dict[int, tuple[int, int]] = {}
|
||||
for delta in deltas:
|
||||
for offset, (before, after) in enumerate(zip(delta.before, delta.after, strict=True)):
|
||||
if before != after:
|
||||
changes[delta.rva + offset] = (before, after)
|
||||
return tuple((rva, before, after) for rva, (before, after) in sorted(changes.items()))
|
||||
|
||||
|
||||
def diff(
|
||||
original: RunResult,
|
||||
reference: RunResult,
|
||||
tolerance: FloatTolerance = FloatTolerance(),
|
||||
) -> DiffReport:
|
||||
differences: list[str] = []
|
||||
if original.st0 is not None or reference.st0 is not None:
|
||||
if original.st0 is None or reference.st0 is None:
|
||||
differences.append(f"ST(0): orig={original.st0!r}, ref={reference.st0!r}")
|
||||
elif not math.isclose(
|
||||
original.st0,
|
||||
reference.st0,
|
||||
rel_tol=tolerance.relative,
|
||||
abs_tol=tolerance.absolute,
|
||||
):
|
||||
differences.append(f"ST(0): orig={original.st0!r}, ref={reference.st0!r}")
|
||||
elif original.eax != reference.eax:
|
||||
differences.append(f"EAX: orig={original.eax:#010x}, ref={reference.eax:#010x}")
|
||||
if sorted(original.out_buffers) != sorted(reference.out_buffers):
|
||||
differences.append(
|
||||
f"out_buffers: orig={original.out_buffers!r}, ref={reference.out_buffers!r}"
|
||||
)
|
||||
if changed_bytes(original.globals_delta) != changed_bytes(reference.globals_delta):
|
||||
differences.append(
|
||||
f"globals_delta: orig={original.globals_delta!r}, ref={reference.globals_delta!r}"
|
||||
)
|
||||
if original.branch_outcomes != reference.branch_outcomes:
|
||||
differences.append(
|
||||
f"branches: orig={original.branch_outcomes!r}, ref={reference.branch_outcomes!r}"
|
||||
)
|
||||
return DiffReport(
|
||||
Verdict.DIFF if differences else Verdict.EQUAL,
|
||||
tuple(differences),
|
||||
)
|
||||
@@ -0,0 +1,176 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
|
||||
from capstone import CS_ARCH_X86, CS_GRP_JUMP, CS_MODE_32, Cs
|
||||
from unicorn import Uc, UcError, UC_HOOK_CODE, UC_HOOK_MEM_WRITE
|
||||
from unicorn.x86_const import (
|
||||
UC_X86_REG_EAX,
|
||||
UC_X86_REG_EBP,
|
||||
UC_X86_REG_EBX,
|
||||
UC_X86_REG_ECX,
|
||||
UC_X86_REG_EDI,
|
||||
UC_X86_REG_EDX,
|
||||
UC_X86_REG_ESI,
|
||||
UC_X86_REG_ESP,
|
||||
UC_X86_REG_EIP,
|
||||
)
|
||||
|
||||
from .abi import Buffer, CallSpec, ReturnKind, cleanup_is_callee
|
||||
from .fp import capture_st0
|
||||
from .image import CODE_SCRATCH, SCRATCH_BASE, SCRATCH_SIZE, STACK_BASE, STACK_SIZE, PeImage
|
||||
from .result import GlobalDelta, RunResult
|
||||
|
||||
REGS = {
|
||||
"eax": UC_X86_REG_EAX,
|
||||
"ebx": UC_X86_REG_EBX,
|
||||
"ecx": UC_X86_REG_ECX,
|
||||
"edx": UC_X86_REG_EDX,
|
||||
"esi": UC_X86_REG_ESI,
|
||||
"edi": UC_X86_REG_EDI,
|
||||
"ebp": UC_X86_REG_EBP,
|
||||
}
|
||||
RETURN_SENTINEL = CODE_SCRATCH + 0xF00
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RunError(Exception):
|
||||
detail: str
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"emulation error: {self.detail}"
|
||||
|
||||
|
||||
class UnicornRunner:
|
||||
def __init__(self, image: PeImage, max_instructions: int = 1_000_000) -> None:
|
||||
if max_instructions <= 0:
|
||||
raise RunError(detail="instruction budget must be positive")
|
||||
self.image = image
|
||||
self.max_instructions = max_instructions
|
||||
|
||||
def run(self, spec: CallSpec) -> RunResult:
|
||||
uc = self.image.new_emulator()
|
||||
by_tag: dict[str, tuple[int, Buffer]] = {}
|
||||
cursor = SCRATCH_BASE
|
||||
buffers = (
|
||||
list(spec.buffers)
|
||||
+ [r.buffer for r in spec.regs if r.buffer is not None]
|
||||
+ [s.buffer for s in spec.stack_args if s.buffer is not None]
|
||||
)
|
||||
for buf in buffers:
|
||||
if buf.tag in by_tag:
|
||||
if by_tag[buf.tag][1] != buf:
|
||||
raise RunError(detail=f"conflicting buffer tag {buf.tag}")
|
||||
continue
|
||||
size = max(len(buf.data), buf.out_size, 1)
|
||||
if cursor + size > SCRATCH_BASE + SCRATCH_SIZE:
|
||||
raise RunError(detail="scratch buffer capacity exceeded")
|
||||
uc.mem_write(cursor, buf.data.ljust(size, b"\x00"))
|
||||
by_tag[buf.tag] = (cursor, buf)
|
||||
cursor += (size + 15) & ~15
|
||||
for rv in spec.regs:
|
||||
value = by_tag[rv.buffer.tag][0] if rv.buffer is not None else rv.immediate
|
||||
if value is None:
|
||||
raise RunError(detail=f"register {rv.reg} has no value")
|
||||
uc.reg_write(REGS[rv.reg], value)
|
||||
esp = STACK_BASE + STACK_SIZE - 0x100
|
||||
for arg in reversed(spec.stack_args):
|
||||
value = by_tag[arg.buffer.tag][0] if arg.buffer is not None else arg.immediate
|
||||
if value is None:
|
||||
raise RunError(detail="stack argument has no value")
|
||||
esp -= 4
|
||||
uc.mem_write(esp, struct.pack("<I", value & 0xFFFFFFFF))
|
||||
esp -= 4
|
||||
uc.mem_write(esp, struct.pack("<I", RETURN_SENTINEL))
|
||||
uc.reg_write(UC_X86_REG_ESP, esp)
|
||||
globals_before = [
|
||||
(tag, rva, bytes(uc.mem_read(self.image.va(rva), size)))
|
||||
for tag, rva, size in spec.globals_watched
|
||||
]
|
||||
steps = 0
|
||||
written: set[int] = set()
|
||||
branches: list[tuple[int, bool]] = []
|
||||
pending_branch: tuple[int, int] | None = None
|
||||
decoder = Cs(CS_ARCH_X86, CS_MODE_32)
|
||||
decoder.detail = True
|
||||
branch_fallthrough: dict[int, int] = {}
|
||||
for rva in spec.branch_sites:
|
||||
address = self.image.va(rva)
|
||||
ins = next(decoder.disasm(self.image.read(rva, 15), address), None)
|
||||
if ins is None or not ins.group(CS_GRP_JUMP) or ins.mnemonic == "jmp":
|
||||
raise RunError(detail=f"branch probe is not a conditional jump: {address:#x}")
|
||||
branch_fallthrough[address] = address + ins.size
|
||||
|
||||
# Unicorn fixes these callback signatures.
|
||||
def on_code(cpu: Uc, address: int, size: int, user_data: None) -> None:
|
||||
nonlocal steps, pending_branch
|
||||
steps += 1
|
||||
if pending_branch is not None:
|
||||
site, fallthrough = pending_branch
|
||||
branches.append((site - self.image.image_base, address != fallthrough))
|
||||
pending_branch = (
|
||||
(address, branch_fallthrough[address]) if address in branch_fallthrough else None
|
||||
)
|
||||
|
||||
def on_write(
|
||||
cpu: Uc, access: int, address: int, size: int, value: int, user_data: None,
|
||||
) -> None:
|
||||
start = max(address, self.image.image_base)
|
||||
end = min(address + size, self.image.image_base + self.image.size)
|
||||
written.update(range(start, end))
|
||||
|
||||
hook = uc.hook_add(UC_HOOK_CODE, on_code)
|
||||
write_hook = uc.hook_add(
|
||||
UC_HOOK_MEM_WRITE, on_write, begin=self.image.image_base,
|
||||
end=self.image.image_base + self.image.size - 1,
|
||||
)
|
||||
try:
|
||||
# Stop before decoding the sentinel's blank scratch page.
|
||||
uc.emu_start(self.image.va(spec.rva), RETURN_SENTINEL, count=self.max_instructions)
|
||||
except UcError as error:
|
||||
raise RunError(
|
||||
detail=f"{error} at EIP={uc.reg_read(UC_X86_REG_EIP):#x} after {steps} instructions"
|
||||
) from error
|
||||
finally:
|
||||
uc.hook_del(hook)
|
||||
uc.hook_del(write_hook)
|
||||
if uc.reg_read(UC_X86_REG_EIP) != RETURN_SENTINEL:
|
||||
raise RunError(detail=f"did not return after {steps} instructions")
|
||||
esp_after = uc.reg_read(UC_X86_REG_ESP)
|
||||
expected = esp + 4 + (len(spec.stack_args) * 4 if cleanup_is_callee(spec.conv) else 0)
|
||||
if esp_after != expected:
|
||||
raise RunError(detail=f"stack cleanup mismatch: esp={esp_after:#x}, expected={expected:#x}")
|
||||
eax = uc.reg_read(UC_X86_REG_EAX)
|
||||
st0 = None
|
||||
st0_raw = None
|
||||
if spec.ret in (ReturnKind.FLOAT_ST0, ReturnKind.DOUBLE_ST0):
|
||||
st0, st0_raw = capture_st0(uc)
|
||||
outputs = tuple(
|
||||
(tag, bytes(uc.mem_read(address, buf.out_size)))
|
||||
for tag, (address, buf) in by_tag.items()
|
||||
if buf.out_size
|
||||
)
|
||||
deltas = []
|
||||
for tag, rva, before in globals_before:
|
||||
after = bytes(uc.mem_read(self.image.va(rva), len(before)))
|
||||
if before != after:
|
||||
deltas.append(GlobalDelta(tag, rva, before, after))
|
||||
written.difference_update(range(self.image.va(rva), self.image.va(rva) + len(before)))
|
||||
addresses = sorted(written)
|
||||
index = 0
|
||||
while index < len(addresses):
|
||||
start = addresses[index]
|
||||
end = start + 1
|
||||
index += 1
|
||||
while index < len(addresses) and addresses[index] == end:
|
||||
end += 1
|
||||
index += 1
|
||||
rva = start - self.image.image_base
|
||||
before = self.image.read(rva, end - start)
|
||||
after = bytes(uc.mem_read(start, end - start))
|
||||
if before != after:
|
||||
deltas.append(GlobalDelta("image", rva, before, after))
|
||||
return RunResult(
|
||||
eax, st0, outputs, tuple(deltas), esp, esp_after, steps, st0_raw, tuple(branches),
|
||||
)
|
||||
Reference in new issue
Block a user