feat(slice): reconstruct+verify validity/cursor slice incl vtable fn via differential
This commit is contained in:
1 parent
39f01099a5
commit
9c4e9bc507
7 files changed
+630
No files matched your search
@@ -0,0 +1,28 @@
|
|||||||
|
#include "validity.h"
|
||||||
|
|
||||||
|
namespace gk::game {
|
||||||
|
|
||||||
|
// rva=0x101ab6d0 (orig FUN_101ab6d0)
|
||||||
|
float GK_CDECL BoxDistanceSquared(const ValidityBox& box, const Vec3& point) {
|
||||||
|
// T7's field names are misleading: the instructions use center +/- extent,
|
||||||
|
// not minimum/maximum corners. Preserve its verified binary layout.
|
||||||
|
const float center[] = {box.minimum.x, box.minimum.y, box.minimum.z};
|
||||||
|
const float extent[] = {box.maximum.x, box.maximum.y, box.maximum.z};
|
||||||
|
const float position[] = {point.x, point.y, point.z};
|
||||||
|
float delta[3];
|
||||||
|
for (unsigned axis = 0; axis < 3; ++axis) {
|
||||||
|
// Match the DWORD spills before the two original clamp helpers.
|
||||||
|
volatile float lower = center[axis] - extent[axis];
|
||||||
|
volatile float upper = center[axis] + extent[axis];
|
||||||
|
const float above_lower =
|
||||||
|
lower >= position[axis] ? lower : position[axis];
|
||||||
|
const float clamped = above_lower < upper ? above_lower : upper;
|
||||||
|
volatile float difference = position[axis] - clamped;
|
||||||
|
delta[axis] = difference;
|
||||||
|
}
|
||||||
|
const long double x = delta[0], y = delta[1], z = delta[2];
|
||||||
|
volatile float distance = (x * x + y * y) + z * z;
|
||||||
|
return distance;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace gk::game
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#include "nui_elevation.h"
|
||||||
|
|
||||||
|
namespace gk::game {
|
||||||
|
|
||||||
|
// rva=0x1000f510 (orig FUN_1000f510)
|
||||||
|
void GK_CDECL UpdateCameraElevation(ElevationThread& thread) {
|
||||||
|
std::int32_t current = 0;
|
||||||
|
const std::int32_t status = thread.sensor->GetAngle(¤t);
|
||||||
|
if (status >= 0) {
|
||||||
|
if (thread.accumulator == kAccumulatorSentinel) {
|
||||||
|
thread.accumulator = current;
|
||||||
|
}
|
||||||
|
// (current + 2*prev)/3: the imul 0x55555556 + shr 31 at 0x1000f53c is a
|
||||||
|
// signed divide-by-three truncating toward zero, which C++ int / 3 matches.
|
||||||
|
const std::int32_t averaged = (current + thread.accumulator * 2) / 3;
|
||||||
|
thread.smoothed_angle = averaged;
|
||||||
|
thread.accumulator = averaged;
|
||||||
|
}
|
||||||
|
if (thread.applied_angle != thread.desired_angle) {
|
||||||
|
thread.sensor->SetAngle(thread.desired_angle);
|
||||||
|
thread.applied_angle = thread.desired_angle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace gk::game
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "gk/types.h"
|
||||||
|
|
||||||
|
namespace gk::game {
|
||||||
|
|
||||||
|
// Camera-elevation control surface the NuiThread drives through the live
|
||||||
|
// INuiSensor. Declared as a C++ interface so MinGW emits the Itanium vtable
|
||||||
|
// (never copy MSVC vtable bytes, per docs/conventions.md). The two slots used
|
||||||
|
// here mirror INuiSensor::NuiCameraElevationGetAngle and
|
||||||
|
// ::NuiCameraElevationSetAngle (kinect/fallback/windows-nui/nui_interfaces.h),
|
||||||
|
// the methods the original dispatches at vtable offsets 0x3c and 0x38.
|
||||||
|
class ICameraElevation {
|
||||||
|
public:
|
||||||
|
virtual std::int32_t GK_STDCALL GetAngle(std::int32_t* out_degrees) = 0;
|
||||||
|
virtual std::int32_t GK_STDCALL SetAngle(std::int32_t degrees) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// NuiThread elevation-smoothing state. Offsets pinned to the original
|
||||||
|
// FUN_1000f510 frame: the object arrives in ESI and the function touches
|
||||||
|
// +0x38/+0x3c/+0x40/+0x44 and the sensor pointer at +0x15fc.
|
||||||
|
struct ElevationThread {
|
||||||
|
std::int32_t desired_angle; // +0x38, caller-requested elevation
|
||||||
|
std::int32_t applied_angle; // +0x3c, last angle pushed to the sensor
|
||||||
|
std::int32_t smoothed_angle; // +0x40, published smoothed estimate
|
||||||
|
std::int32_t accumulator; // +0x44, IIR state, sentinel -0x168
|
||||||
|
ICameraElevation* sensor; // +0x15fc, live INuiSensor
|
||||||
|
};
|
||||||
|
|
||||||
|
// cmp DWORD PTR [esi+0x44],0xfffffe98 at 0x1000f527.
|
||||||
|
constexpr std::int32_t kAccumulatorSentinel = -0x168;
|
||||||
|
|
||||||
|
// rva=0x1000f510 (orig FUN_1000f510)
|
||||||
|
void GK_CDECL UpdateCameraElevation(ElevationThread& thread);
|
||||||
|
|
||||||
|
} // namespace gk::game
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
#include "validity.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
namespace gk::game {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Vec3 GK_CDECL TransformPosition(const Matrix4x4& m, const Vec3& p) {
|
||||||
|
// The original uses SSE2 binary64 products/sums, then binary32 stores.
|
||||||
|
// Positions multiply columns in the T7 row-major storage layout.
|
||||||
|
return {
|
||||||
|
static_cast<float>(((double(m.m10) * p.y + double(m.m00) * p.x) +
|
||||||
|
double(m.m20) * p.z) + m.m30),
|
||||||
|
static_cast<float>(((double(m.m11) * p.y + double(m.m01) * p.x) +
|
||||||
|
double(m.m21) * p.z) + m.m31),
|
||||||
|
static_cast<float>(((double(m.m12) * p.y + double(m.m02) * p.x) +
|
||||||
|
double(m.m22) * p.z) + m.m32)};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// rva=0x100e4140 (orig FUN_100e4140)
|
||||||
|
void GK_CDECL UpdateValidityCandidates(const LiveManager& manager,
|
||||||
|
ValidityState& state) {
|
||||||
|
const Matrix4x4 transform = state.transform;
|
||||||
|
for (std::size_t index = 0; index < kSkeletonCount; ++index) {
|
||||||
|
const SkeletonData& skeleton = manager.skeleton_frame.skeletons[index];
|
||||||
|
ValidityCandidate& candidate = state.candidates[index];
|
||||||
|
const std::uint32_t tracking_id = manager.synthetic_tracking_mode
|
||||||
|
? (index < 2 ? static_cast<std::uint32_t>(index + 1) : 0)
|
||||||
|
: skeleton.tracking_id;
|
||||||
|
// The ID is integer bits, despite T7's float field declaration.
|
||||||
|
std::uint32_t previous_id;
|
||||||
|
std::memcpy(&previous_id, &candidate.tracking_id, sizeof(previous_id));
|
||||||
|
if (previous_id != tracking_id) {
|
||||||
|
std::memcpy(&candidate.tracking_id, &tracking_id, sizeof(tracking_id));
|
||||||
|
candidate.valid = 0;
|
||||||
|
}
|
||||||
|
Vec3 source = state.missing_position;
|
||||||
|
if (!manager.synthetic_tracking_mode &&
|
||||||
|
skeleton.tracking_state != SkeletonTrackingState::not_tracked) {
|
||||||
|
source = {skeleton.position.x, skeleton.position.y, skeleton.position.z};
|
||||||
|
}
|
||||||
|
const Vec3 transformed = TransformPosition(transform, source);
|
||||||
|
if (source.x != state.missing_position.x ||
|
||||||
|
source.y != state.missing_position.y ||
|
||||||
|
source.z != state.missing_position.z) {
|
||||||
|
const float tolerance = candidate.valid
|
||||||
|
? state.retained_tolerance : state.entry_tolerance;
|
||||||
|
const float squared_tolerance =
|
||||||
|
static_cast<float>(double(tolerance) * tolerance);
|
||||||
|
candidate.valid = BoxDistanceSquared(state.box, transformed) <=
|
||||||
|
squared_tolerance;
|
||||||
|
if (candidate.valid) {
|
||||||
|
candidate.source_position = source;
|
||||||
|
// The original deliberately applies the matrix a second time.
|
||||||
|
candidate.transformed_position = TransformPosition(transform, transformed);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
candidate.valid = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace gk::game
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "gk/offsets_assert.h"
|
||||||
|
|
||||||
|
namespace gk::game {
|
||||||
|
|
||||||
|
// The original globals are explicit state here; no calls back into the DLL.
|
||||||
|
struct ValidityState {
|
||||||
|
Matrix4x4 transform; // DAT_103d4a80
|
||||||
|
ValidityBox box; // DAT_103d3230
|
||||||
|
Vec3 missing_position; // DAT_103d32c4
|
||||||
|
float entry_tolerance; // DAT_10299294
|
||||||
|
float retained_tolerance; // DAT_10299298
|
||||||
|
ValidityCandidate candidates[kSkeletonCount]; // DAT_103e29b0
|
||||||
|
};
|
||||||
|
|
||||||
|
// rva=0x101ab6d0 (orig FUN_101ab6d0); original inputs EAX=box, EDI=point.
|
||||||
|
float GK_CDECL BoxDistanceSquared(const ValidityBox& box, const Vec3& point);
|
||||||
|
|
||||||
|
// rva=0x100e4140 (orig FUN_100e4140); original inputs were globals.
|
||||||
|
void GK_CDECL UpdateValidityCandidates(const LiveManager& manager,
|
||||||
|
ValidityState& state);
|
||||||
|
|
||||||
|
} // namespace gk::game
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
"""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())
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
#include <cctype>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "gk/structs/manager.h"
|
||||||
|
#include "gk/structs/validity.h"
|
||||||
|
#include "game/validity.h"
|
||||||
|
#include "game/nui_elevation.h"
|
||||||
|
|
||||||
|
using gk::LiveManager;
|
||||||
|
using gk::SkeletonData;
|
||||||
|
using gk::SkeletonTrackingState;
|
||||||
|
using gk::Vec3;
|
||||||
|
using gk::game::BoxDistanceSquared;
|
||||||
|
using gk::game::ElevationThread;
|
||||||
|
using gk::game::ICameraElevation;
|
||||||
|
using gk::game::UpdateCameraElevation;
|
||||||
|
using gk::game::UpdateValidityCandidates;
|
||||||
|
using gk::game::ValidityState;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
std::vector<std::uint8_t> ReadHex() {
|
||||||
|
std::vector<std::uint8_t> out;
|
||||||
|
std::string digits;
|
||||||
|
int c = 0;
|
||||||
|
while ((c = std::getchar()) != EOF) {
|
||||||
|
if (std::isxdigit(c) != 0) {
|
||||||
|
digits.push_back(static_cast<char>(c));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (std::size_t i = 0; i + 1 < digits.size(); i += 2) {
|
||||||
|
out.push_back(static_cast<std::uint8_t>(
|
||||||
|
std::strtol(digits.substr(i, 2).c_str(), nullptr, 16)));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void PutHex(const void* data, std::size_t size) {
|
||||||
|
const auto* bytes = static_cast<const std::uint8_t*>(data);
|
||||||
|
for (std::size_t i = 0; i < size; ++i) {
|
||||||
|
std::printf("%02x", bytes[i]);
|
||||||
|
}
|
||||||
|
std::printf("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
class ScriptedSensor final : public ICameraElevation {
|
||||||
|
public:
|
||||||
|
ScriptedSensor(std::int32_t angle, std::int32_t status)
|
||||||
|
: angle_(angle), status_(status) {}
|
||||||
|
|
||||||
|
std::int32_t GK_STDCALL GetAngle(std::int32_t* out_degrees) override {
|
||||||
|
++get_calls_;
|
||||||
|
*out_degrees = angle_;
|
||||||
|
return status_;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t GK_STDCALL SetAngle(std::int32_t degrees) override {
|
||||||
|
++set_calls_;
|
||||||
|
set_arg_ = degrees;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::int32_t get_calls_ = 0;
|
||||||
|
std::int32_t set_calls_ = 0;
|
||||||
|
std::int32_t set_arg_ = 0;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::int32_t angle_;
|
||||||
|
std::int32_t status_;
|
||||||
|
};
|
||||||
|
|
||||||
|
float ReadFloat(const std::uint8_t* p) {
|
||||||
|
float v = 0.0F;
|
||||||
|
std::memcpy(&v, p, 4);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint32_t ReadU32(const std::uint8_t* p) {
|
||||||
|
std::uint32_t v = 0;
|
||||||
|
std::memcpy(&v, p, 4);
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
int RunBox(const std::vector<std::uint8_t>& in) {
|
||||||
|
gk::ValidityBox box{};
|
||||||
|
Vec3 point{};
|
||||||
|
std::memcpy(&box, in.data(), sizeof(box));
|
||||||
|
std::memcpy(&point, in.data() + sizeof(box), sizeof(point));
|
||||||
|
const float result = BoxDistanceSquared(box, point);
|
||||||
|
PutHex(&result, sizeof(result));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int RunElev(const std::vector<std::uint8_t>& in) {
|
||||||
|
const auto* p = in.data();
|
||||||
|
ElevationThread thread{};
|
||||||
|
thread.desired_angle = static_cast<std::int32_t>(ReadU32(p + 0));
|
||||||
|
thread.applied_angle = static_cast<std::int32_t>(ReadU32(p + 4));
|
||||||
|
thread.smoothed_angle = static_cast<std::int32_t>(ReadU32(p + 8));
|
||||||
|
thread.accumulator = static_cast<std::int32_t>(ReadU32(p + 12));
|
||||||
|
const auto angle = static_cast<std::int32_t>(ReadU32(p + 16));
|
||||||
|
const auto status = static_cast<std::int32_t>(ReadU32(p + 20));
|
||||||
|
ScriptedSensor sensor(angle, status);
|
||||||
|
thread.sensor = &sensor;
|
||||||
|
UpdateCameraElevation(thread);
|
||||||
|
std::uint8_t out[28];
|
||||||
|
std::memcpy(out + 0, &thread.desired_angle, 4);
|
||||||
|
std::memcpy(out + 4, &thread.applied_angle, 4);
|
||||||
|
std::memcpy(out + 8, &thread.smoothed_angle, 4);
|
||||||
|
std::memcpy(out + 12, &thread.accumulator, 4);
|
||||||
|
std::memcpy(out + 16, &sensor.set_calls_, 4);
|
||||||
|
std::memcpy(out + 20, &sensor.set_arg_, 4);
|
||||||
|
std::memcpy(out + 24, &sensor.get_calls_, 4);
|
||||||
|
PutHex(out, sizeof(out));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int RunGate(const std::vector<std::uint8_t>& in) {
|
||||||
|
const auto* p = in.data();
|
||||||
|
std::size_t off = 0;
|
||||||
|
ValidityState state{};
|
||||||
|
std::memcpy(&state.transform, p + off, sizeof(state.transform));
|
||||||
|
off += sizeof(state.transform);
|
||||||
|
std::memcpy(&state.box, p + off, sizeof(state.box));
|
||||||
|
off += sizeof(state.box);
|
||||||
|
std::memcpy(&state.missing_position, p + off, sizeof(state.missing_position));
|
||||||
|
off += sizeof(state.missing_position);
|
||||||
|
state.entry_tolerance = ReadFloat(p + off);
|
||||||
|
off += 4;
|
||||||
|
state.retained_tolerance = ReadFloat(p + off);
|
||||||
|
off += 4;
|
||||||
|
const std::uint8_t synthetic = p[off];
|
||||||
|
off += 1;
|
||||||
|
|
||||||
|
LiveManager manager{};
|
||||||
|
std::memset(&manager, 0, sizeof(LiveManager));
|
||||||
|
manager.synthetic_tracking_mode = synthetic;
|
||||||
|
for (std::size_t i = 0; i < gk::kSkeletonCount; ++i) {
|
||||||
|
SkeletonData& skel = manager.skeleton_frame.skeletons[i];
|
||||||
|
skel.tracking_state = static_cast<SkeletonTrackingState>(ReadU32(p + off));
|
||||||
|
off += 4;
|
||||||
|
skel.tracking_id = ReadU32(p + off);
|
||||||
|
off += 4;
|
||||||
|
skel.position.x = ReadFloat(p + off);
|
||||||
|
off += 4;
|
||||||
|
skel.position.y = ReadFloat(p + off);
|
||||||
|
off += 4;
|
||||||
|
skel.position.z = ReadFloat(p + off);
|
||||||
|
off += 4;
|
||||||
|
}
|
||||||
|
for (std::size_t i = 0; i < gk::kSkeletonCount; ++i) {
|
||||||
|
std::uint32_t id = ReadU32(p + off);
|
||||||
|
off += 4;
|
||||||
|
std::memcpy(&state.candidates[i].tracking_id, &id, 4);
|
||||||
|
state.candidates[i].valid = p[off];
|
||||||
|
off += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdateValidityCandidates(manager, state);
|
||||||
|
PutHex(state.candidates, sizeof(state.candidates));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
if (argc < 2) {
|
||||||
|
std::fprintf(stderr, "usage: recon <box|elev|gate>\n");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
const std::vector<std::uint8_t> in = ReadHex();
|
||||||
|
const std::string mode = argv[1];
|
||||||
|
if (mode == "box") {
|
||||||
|
return RunBox(in);
|
||||||
|
}
|
||||||
|
if (mode == "elev") {
|
||||||
|
return RunElev(in);
|
||||||
|
}
|
||||||
|
if (mode == "gate") {
|
||||||
|
return RunGate(in);
|
||||||
|
}
|
||||||
|
std::fprintf(stderr, "unknown mode %s\n", argv[1]);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user