Files
kdm-re/tools/unicorn_diff/udiff/fp.py
T

81 lines
2.9 KiB
Python

"""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))