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

188 lines
7.5 KiB
Python

from __future__ import annotations
import math
import struct
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .t2 import IoEvent
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 | None = None
st0: float | None = 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], ...] = ()
globals_snapshot: tuple[GlobalDelta, ...] = ()
import_calls: tuple[IoEvent, ...] = ()
edx: int | None = None
ret_offset: int | None = None
@dataclass(frozen=True, slots=True)
class DiffReport:
verdict: Verdict
differences: tuple[str, ...]
@dataclass(frozen=True, slots=True)
class FloatTolerance:
"""Rounding window for PORTABLE-mode golden comparison only.
This belongs exclusively to cross-architecture golden replay of X87-class
functions, where the reference is produced on a different host FPU and an
exact bit match is not expected. It is never applied to the faithful
differential against the original binary: pass it to ``diff`` to opt into
portable mode, and leave ``tolerance`` unset for the exact faithful compare.
"""
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 snapshot_bytes(snapshots: tuple[GlobalDelta, ...]) -> tuple[tuple[int, int, int], ...]:
"""Keep unchanged input bytes too: equal deltas alone cannot prove equal state."""
values: dict[int, tuple[int, int]] = {}
for snapshot in snapshots:
for offset, pair in enumerate(zip(snapshot.before, snapshot.after, strict=True)):
address = snapshot.rva + offset
if address in values and values[address] != pair:
raise ComparisonError(detail=f"conflicting snapshots at {address:#x}")
values[address] = pair
return tuple((rva, before, after) for rva, (before, after) in sorted(values.items()))
def diff(
original: RunResult,
reference: RunResult,
tolerance: FloatTolerance | None = None,
) -> DiffReport:
"""Compare two runs; float handling depends on the mode.
Faithful mode (``tolerance is None``, the default, used for the real-binary
differential): a float returned in ST(0) must match BIT-EXACTLY, and when
both runs captured the raw 80-bit x87 register those encodings must be
identical too. No rounding window is applied, so a reconstruction that
drifts by any nonzero amount - including less than 1e-6 - is rejected.
Portable golden mode (``tolerance`` supplied): ST(0) is compared with
``math.isclose``. Reserved for cross-architecture golden replay of
X87-class functions; never use it for the faithful differential.
"""
differences: list[str] = []
if original.eax is None and original.st0 is None and original.ret_offset is None:
if not (changed_bytes(original.globals_delta) or original.import_calls
or any(data for _, data in original.out_buffers)):
raise ComparisonError(detail="void original has no deterministic observable")
if (original.eax is None) != (reference.eax is None):
differences.append("return kind: void/value mismatch")
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 tolerance is None:
# Faithful: identical IEEE-754 double bits, including NaN payloads,
# plus the exact raw x87 register whenever both runs captured it.
if struct.pack("<d", original.st0) != struct.pack(
"<d", reference.st0
):
differences.append(f"ST(0): orig={original.st0!r}, ref={reference.st0!r}")
if (
original.st0_raw is not None
and reference.st0_raw is not None
and original.st0_raw != reference.st0_raw
):
differences.append(
f"ST(0) raw: orig={original.st0_raw!r}, ref={reference.st0_raw!r}"
)
elif not (
math.isnan(original.st0)
and math.isnan(reference.st0)
) and 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!r}, ref={reference.eax!r}")
# Multi-register (EDX:EAX / undefined8) high word: compared as its own channel
# so a 64-bit return whose low word matches but high word drifts is rejected.
if original.edx != reference.edx:
differences.append(f"EDX: orig={original.edx!r}, ref={reference.edx!r}")
# Same-image pointer return: compared as an image-relative offset, never as a
# cross-image absolute, so a reconstruction linked at a different base still
# matches when - and only when - it points at the same place in its own image.
if original.ret_offset != reference.ret_offset:
differences.append(
f"ret_offset: orig={original.ret_offset!r}, ref={reference.ret_offset!r}"
)
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 snapshot_bytes(original.globals_snapshot) != snapshot_bytes(reference.globals_snapshot):
differences.append(
f"globals_snapshot: orig={original.globals_snapshot!r}, "
f"ref={reference.globals_snapshot!r}"
)
if original.import_calls != reference.import_calls:
differences.append(
f"import_calls: orig={original.import_calls!r}, ref={reference.import_calls!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),
)