264 lines
12 KiB
Python
264 lines
12 KiB
Python
"""T11 keystone proof: original gamekdm.dll vs compiled MinGW reconstruction.
|
|
|
|
For each reconstructed function this emulates the real routine in the shipping
|
|
binary (Unicorn) and runs the compiled C++ reconstruction under wine on the
|
|
same inputs, then asserts behavioural equality through the T8 differ. Run:
|
|
|
|
tools/unicorn_diff/.venv/bin/python tools/unicorn_diff/prove_t11.py
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
from unicorn.x86_const import UC_X86_REG_EIP, UC_X86_REG_ESI, UC_X86_REG_ESP
|
|
|
|
from udiff import (
|
|
Buffer, CallSpec, FloatTolerance, PeImage, RegValue,
|
|
ReturnKind, RunResult, UnicornRunner, Verdict, diff,
|
|
)
|
|
from udiff.image import CODE_SCRATCH, SCRATCH_BASE, STACK_BASE, STACK_SIZE
|
|
from udiff.metadata import load_calling_convention
|
|
from udiff.runner import RETURN_SENTINEL
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
DLL = Path("/home/athapa/ghidra/gamekdm.dll")
|
|
RECON = ROOT / "tools" / "unicorn_diff" / "recon.exe"
|
|
TOL = FloatTolerance(absolute=1e-6, relative=1e-6)
|
|
|
|
|
|
def run_recon(exe: Path, mode: str, payload: bytes) -> bytes:
|
|
env = dict(os.environ)
|
|
env["WINEDEBUG"] = "-all"
|
|
out = subprocess.run(
|
|
["wine", str(exe), mode],
|
|
input=payload.hex().encode(),
|
|
capture_output=True,
|
|
env=env,
|
|
check=True,
|
|
)
|
|
return bytes.fromhex(out.stdout.decode().strip())
|
|
|
|
|
|
def prove_box(image: PeImage, log: list[str]) -> None:
|
|
runner = UnicornRunner(image)
|
|
conv = load_calling_convention(0x1AB6D0)
|
|
cases = ((6.0, 9.0, 7.0), (-4.0, -5.0, 3.0), (1.0, 2.0, 3.0), (1.3, 0.0, 2.5))
|
|
center, extent = (1.0, 2.0, 3.0), (2.0, 3.0, 4.0)
|
|
box = struct.pack("<6f", *center, *extent)
|
|
for point in cases:
|
|
spec = CallSpec(
|
|
rva=0x1AB6D0, conv=conv, ret=ReturnKind.FLOAT_ST0,
|
|
regs=(RegValue("eax", buffer=Buffer("box", box)),
|
|
RegValue("edi", buffer=Buffer("pt", struct.pack("<3f", *point)))),
|
|
)
|
|
original = runner.run(spec)
|
|
recon_bits = run_recon(RECON, "box", box + struct.pack("<3f", *point))
|
|
recon = struct.unpack("<f", recon_bits)[0]
|
|
report = diff(original, RunResult(eax=0, st0=recon), TOL)
|
|
assert report.verdict is Verdict.EQUAL, (point, original.st0, recon, report)
|
|
log.append(f" box point={point} orig_ST0={original.st0!r} recon={recon!r} "
|
|
f"-> {report.verdict.value}")
|
|
log.append(f"FUN_101ab6d0: PASS ({len(cases)} cases, differential original==reconstructed)")
|
|
|
|
|
|
def emulate_elev(image: PeImage, thread: dict[str, int]) -> dict[str, int]:
|
|
uc = image.new_emulator()
|
|
manager = SCRATCH_BASE + 0x1000
|
|
sensor = SCRATCH_BASE + 0x2000
|
|
vtable = SCRATCH_BASE + 0x3000
|
|
rec = SCRATCH_BASE + 0x4000
|
|
stub_get = CODE_SCRATCH + 0x100
|
|
stub_set = CODE_SCRATCH + 0x200
|
|
uc.mem_write(manager + 0x38, struct.pack("<iiii", thread["desired"], thread["applied"],
|
|
thread["smoothed"], thread["accum"]))
|
|
uc.mem_write(manager + 0x15FC, struct.pack("<I", sensor))
|
|
uc.mem_write(sensor, struct.pack("<I", vtable))
|
|
uc.mem_write(vtable + 0x3C, struct.pack("<I", stub_get))
|
|
uc.mem_write(vtable + 0x38, struct.pack("<I", stub_set))
|
|
uc.mem_write(rec, struct.pack("<ii", 0, 0))
|
|
get = (b"\x8b\x44\x24\x08" + b"\xc7\x00" + struct.pack("<i", thread["angle"])
|
|
+ b"\xb8" + struct.pack("<i", thread["status"]) + b"\xc2\x08\x00")
|
|
put = (b"\x8b\x44\x24\x08" + b"\xa3" + struct.pack("<I", rec)
|
|
+ b"\xb8\x01\x00\x00\x00" + b"\xa3" + struct.pack("<I", rec + 4)
|
|
+ b"\x31\xc0" + b"\xc2\x08\x00")
|
|
uc.mem_write(stub_get, get)
|
|
uc.mem_write(stub_set, put)
|
|
esp = STACK_BASE + STACK_SIZE - 0x100
|
|
esp -= 4
|
|
uc.mem_write(esp, struct.pack("<I", RETURN_SENTINEL))
|
|
uc.reg_write(UC_X86_REG_ESP, esp)
|
|
uc.reg_write(UC_X86_REG_ESI, manager)
|
|
uc.emu_start(image.va(0xF510), RETURN_SENTINEL, count=100000)
|
|
if uc.reg_read(UC_X86_REG_EIP) != RETURN_SENTINEL:
|
|
raise RuntimeError("elev did not return cleanly")
|
|
desired, applied, smoothed, accum = struct.unpack("<iiii", uc.mem_read(manager + 0x38, 16))
|
|
set_arg, set_called = struct.unpack("<ii", uc.mem_read(rec, 8))
|
|
return {"desired": desired, "applied": applied, "smoothed": smoothed,
|
|
"accum": accum, "set_arg": set_arg, "set_called": set_called}
|
|
|
|
|
|
def prove_elev(image: PeImage, log: list[str]) -> None:
|
|
cases = (
|
|
{"desired": 10, "applied": -5, "smoothed": 0, "accum": -0x168, "angle": 7, "status": 0},
|
|
{"desired": -5, "applied": -5, "smoothed": 0, "accum": 4, "angle": 19, "status": 0},
|
|
{"desired": 27, "applied": 27, "smoothed": 0, "accum": 0, "angle": -40, "status": -1},
|
|
{"desired": 3, "applied": 1, "smoothed": 9, "accum": -0x168, "angle": -12, "status": 0},
|
|
)
|
|
for case in cases:
|
|
original = emulate_elev(image, case)
|
|
payload = struct.pack("<IIIIII", case["desired"] & 0xFFFFFFFF, case["applied"] & 0xFFFFFFFF,
|
|
case["smoothed"] & 0xFFFFFFFF, case["accum"] & 0xFFFFFFFF,
|
|
case["angle"] & 0xFFFFFFFF, case["status"] & 0xFFFFFFFF)
|
|
out = run_recon(RECON, "elev", payload)
|
|
desired, applied, smoothed, accum, set_called, set_arg, get_called = struct.unpack("<iiiiiii", out)
|
|
recon = {"desired": desired, "applied": applied, "smoothed": smoothed,
|
|
"accum": accum, "set_arg": set_arg if set_called else 0, "set_called": set_called}
|
|
assert get_called >= 1, ("GetAngle never dispatched", case)
|
|
assert recon == original, (case, original, recon)
|
|
log.append(f" elev in={case} orig={original} recon(set_called={set_called},"
|
|
f"get_called={get_called}) -> EQUAL")
|
|
log.append(f"FUN_1000f510: PASS ({len(cases)} cases, vtable GetAngle/SetAngle dispatch "
|
|
"+ object state original==reconstructed)")
|
|
|
|
|
|
def emulate_gate(image: PeImage, case: dict) -> bytes:
|
|
uc = image.new_emulator()
|
|
manager = SCRATCH_BASE + 0x8000
|
|
base = image.image_base
|
|
uc.mem_write(image.va(0x102E54B8 - base), struct.pack("<I", 0))
|
|
uc.mem_write(image.va(0x103D4A80 - base), struct.pack("<16f", *case["matrix"]))
|
|
uc.mem_write(image.va(0x103D32C4 - base), struct.pack("<3f", *case["missing"]))
|
|
uc.mem_write(image.va(0x10299294 - base), struct.pack("<f", case["entry"]))
|
|
uc.mem_write(image.va(0x10299298 - base), struct.pack("<f", case["retained"]))
|
|
uc.mem_write(image.va(0x103D3230 - base), struct.pack("<6f", *case["box"]))
|
|
uc.mem_write(image.va(0x103CF1B4 - base), struct.pack("<I", manager))
|
|
uc.mem_write(manager + 0x17F4, bytes([case["synthetic"]]))
|
|
for i, skel in enumerate(case["skeletons"]):
|
|
skel_base = manager + 0x1D0 + i * 0x1B4
|
|
uc.mem_write(skel_base, struct.pack("<II", skel["state"], skel["id"]))
|
|
uc.mem_write(skel_base + 0x10, struct.pack("<3f", *skel["pos"]))
|
|
for i, seed in enumerate(case["candidates"]):
|
|
cand = image.va(0x103E29B0 - base) + i * 0x20
|
|
uc.mem_write(cand, b"\x00" * 0x20)
|
|
uc.mem_write(cand + 0x18, struct.pack("<I", seed["id"]))
|
|
uc.mem_write(cand + 0x1C, bytes([seed["valid"]]))
|
|
esp = STACK_BASE + STACK_SIZE - 0x100
|
|
esp -= 4
|
|
uc.mem_write(esp, struct.pack("<I", RETURN_SENTINEL))
|
|
uc.reg_write(UC_X86_REG_ESP, esp)
|
|
uc.emu_start(image.va(0xE4140), RETURN_SENTINEL, count=2_000_000)
|
|
if uc.reg_read(UC_X86_REG_EIP) != RETURN_SENTINEL:
|
|
raise RuntimeError("gate did not return cleanly")
|
|
return bytes(uc.mem_read(image.va(0x103E29B0 - base), 0x20 * 6))
|
|
|
|
|
|
def gate_payload(case: dict) -> bytes:
|
|
buf = struct.pack("<16f", *case["matrix"]) + struct.pack("<6f", *case["box"])
|
|
buf += struct.pack("<3f", *case["missing"])
|
|
buf += struct.pack("<ff", case["entry"], case["retained"]) + bytes([case["synthetic"]])
|
|
for skel in case["skeletons"]:
|
|
buf += struct.pack("<II", skel["state"], skel["id"]) + struct.pack("<3f", *skel["pos"])
|
|
for seed in case["candidates"]:
|
|
buf += struct.pack("<I", seed["id"]) + bytes([seed["valid"]])
|
|
return buf
|
|
|
|
|
|
def gate_case(synthetic: int, states: list, ids: list, positions: list, seeds: list) -> dict:
|
|
identity = (1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0)
|
|
return {
|
|
"matrix": identity,
|
|
"box": (0.0, 1.0, 0.0, 1.22, 1.0, 0.675),
|
|
"missing": (-3131.0, -3131.0, -3131.0),
|
|
"entry": 0.05, "retained": 0.08, "synthetic": synthetic,
|
|
"skeletons": [{"state": states[i], "id": ids[i], "pos": positions[i]} for i in range(6)],
|
|
"candidates": seeds,
|
|
}
|
|
|
|
|
|
def prove_gate(image: PeImage, log: list[str]) -> None:
|
|
far = (99.0, 99.0, 99.0)
|
|
seeds = [{"id": 0, "valid": 0} for _ in range(6)]
|
|
cases = [
|
|
gate_case(0, [2, 2, 0, 0, 0, 0], [11, 22, 0, 0, 0, 0],
|
|
[(0.0, 1.0, 0.0), (2.0, 1.0, 0.0), far, far, far, far], seeds),
|
|
gate_case(0, [2, 0, 0, 0, 0, 0], [7, 0, 0, 0, 0, 0],
|
|
[(1.2, 1.0, 0.0), far, far, far, far, far], seeds),
|
|
gate_case(1, [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],
|
|
[far, far, far, far, far, far], seeds),
|
|
]
|
|
for idx, case in enumerate(cases):
|
|
original = emulate_gate(image, case)
|
|
recon = run_recon(RECON, "gate", gate_payload(case))
|
|
assert len(recon) == len(original) == 0x20 * 6, (len(recon), len(original))
|
|
valid_bytes = [recon[i * 0x20 + 0x1C] for i in range(6)]
|
|
assert recon == original, (idx, original.hex(), recon.hex())
|
|
log.append(f" gate case{idx} synthetic={case['synthetic']} valid={valid_bytes} "
|
|
f"candidates[192B] original==reconstructed")
|
|
log.append(f"FUN_100e4140: PASS ({len(cases)} cases, 6-candidate validity array "
|
|
"original==reconstructed)")
|
|
|
|
|
|
def prove_injected_bug(image: PeImage, log: list[str]) -> None:
|
|
src = (ROOT / "src" / "game" / "box_distance.cpp").read_text()
|
|
bug = src.replace("volatile float difference = position[axis] - clamped;",
|
|
"volatile float difference = position[axis] - clamped + 0.01f;")
|
|
assert bug != src, "injection anchor not found"
|
|
with tempfile.TemporaryDirectory() as td:
|
|
bug_cpp = Path(td) / "box_distance_bug.cpp"
|
|
bug_cpp.write_text(bug)
|
|
bug_exe = Path(td) / "recon_bug.exe"
|
|
subprocess.run(
|
|
["i686-w64-mingw32-g++", "-std=c++20", "-O2", "-mfpmath=sse", "-msse2",
|
|
"-ffp-contract=off", "-fno-fast-math", f"-I{ROOT}/include", f"-I{ROOT}/src",
|
|
f"-I{ROOT}/src/game",
|
|
"-L/nix/store/g72bh3mrbh6gkh59axd2199js9kccxfs-mcfgthread-i686-w64-mingw32-2.5.1/lib",
|
|
str(ROOT / "tools/unicorn_diff/recon_harness.cpp"), str(bug_cpp),
|
|
str(ROOT / "src/game/validity.cpp"), str(ROOT / "src/game/nui_elevation.cpp"),
|
|
"-o", str(bug_exe), "-static", "-static-libgcc", "-static-libstdc++"],
|
|
check=True,
|
|
)
|
|
runner = UnicornRunner(image)
|
|
conv = load_calling_convention(0x1AB6D0)
|
|
box = struct.pack("<6f", 1.0, 2.0, 3.0, 2.0, 3.0, 4.0)
|
|
point = (1.3, 0.0, 2.5)
|
|
original = runner.run(CallSpec(
|
|
rva=0x1AB6D0, conv=conv, ret=ReturnKind.FLOAT_ST0,
|
|
regs=(RegValue("eax", buffer=Buffer("box", box)),
|
|
RegValue("edi", buffer=Buffer("pt", struct.pack("<3f", *point)))),
|
|
))
|
|
recon = struct.unpack("<f", run_recon(bug_exe, "box", box + struct.pack("<3f", *point)))[0]
|
|
report = diff(original, RunResult(eax=0, st0=recon), TOL)
|
|
assert report.verdict is Verdict.DIFF, ("bug not caught", original.st0, recon)
|
|
assert report.differences and report.differences[0].startswith("ST(0):"), report
|
|
log.append(f" injected bug (+0.01 on clamp delta) orig_ST0={original.st0!r} "
|
|
f"buggy_recon={recon!r} -> {report.verdict.value} {report.differences[0]}")
|
|
log.append("NON-VACUITY: PASS (injected reconstruction bug caught by the differential)")
|
|
|
|
|
|
def main() -> int:
|
|
if not RECON.is_file():
|
|
print(f"missing {RECON}", file=sys.stderr)
|
|
return 2
|
|
if shutil.which("wine") is None:
|
|
print("wine not on PATH", file=sys.stderr)
|
|
return 2
|
|
image = PeImage(DLL)
|
|
log: list[str] = [f"DLL={DLL} base={image.image_base:#x} tol abs={TOL.absolute} rel={TOL.relative}"]
|
|
prove_box(image, log)
|
|
prove_elev(image, log)
|
|
prove_gate(image, log)
|
|
prove_injected_bug(image, log)
|
|
log.append("ALL DIFFERENTIALS PASS")
|
|
print("\n".join(log))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|