feat(libavs-ea3): reconstruct+verify wave 11 2

This commit is contained in:
ulw-execute committed 2026-11-29 10:38:36 -05:00
1 parent c74abaf043
commit 295da1f3af
5 files changed
+523 -2

No files matched your search

@@ -185966,7 +185966,7 @@
"owning_module_guess": "unknown",
"rva": "0x00025460",
"signature": "undefined __stdcall FUN_10025460(void)",
"status": "orig"
"status": "verified"
},
{
"callees": [
@@ -197722,7 +197722,7 @@
"owning_module_guess": "unknown",
"rva": "0x000405c0",
"signature": "undefined __cdecl ___mtold12(char * param_1, int param_2, uint * param_3)",
"status": "orig"
"status": "verified"
},
{
"callees": [
@@ -0,0 +1,227 @@
"""libavs-win32-ea3.dll wave-11 differential proof.
Self-contained CRT/runtime leaves that survived waves 1-10, each proved with the
compiled-recon differential: the original is emulated inside the shipping
libavs-win32-ea3.dll under Unicorn and the MinGW C++ reconstruction
(src/libavs-win32-ea3/leaf_ops_w11.cpp) runs under wine on identical inputs,
compared bit-for-bit through the T8 differ.
Channels compared: an owned 12-byte output block (___mtold12, the VS2010 CRT
decimal-mantissa to _LDBL12 converter, whose observable is the three mantissa
dwords plus the 16-bit exponent) and an owned destination buffer (the register
-convention forward block copy at 0x53fc, whose observable is the copied bytes).
Both reconstructions are base-agnostic: every byte compared is a value the
function wrote into a caller-supplied buffer, never a raw pointer.
A final pass rebuilds the reconstruction with a per-body injected bug and asserts
every differential flags it.
tools/unicorn_diff/.venv/bin/python re/libavs-win32-ea3/prove_libavs-win32-ea3_wave11.py
"""
# /// script
# requires-python = ">=3.11"
# dependencies = ["unicorn", "pefile", "capstone"]
# ///
from __future__ import annotations
import dataclasses
import os
import struct
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tools" / "unicorn_diff"))
from udiff import ( # noqa: E402
Buffer, CallConv, CallSpec, PeImage, RegValue, ReturnKind,
RunResult, StackValue, UnicornRunner, Verdict, diff,
)
from udiff.image import SCRATCH_BASE # noqa: E402
from udiff.scaffold import resolve_oracle # noqa: E402
CDECL = CallConv.CDECL
REGISTER = CallConv.REGISTER
VOID = ReturnKind.VOID
MODULE = ROOT / "re" / "libavs-win32-ea3"
HARNESS = MODULE / "recon_libavs-win32-ea3_wave11_harness.cpp"
SRC = ROOT / "src" / "libavs-win32-ea3" / "leaf_ops_w11.cpp"
RECON = MODULE / "recon_libavs-win32-ea3_wave11.exe"
_MCF = sorted(Path("/nix/store").glob("*mcfgthread-i686-w64-mingw32-2.5.1/lib/libmcfgthread.a"))
MCFGTHREAD_LIB = str(_MCF[0].parent) if _MCF else (
"/nix/store/g72bh3mrbh6gkh59axd2199js9kccxfs-mcfgthread-i686-w64-mingw32-2.5.1/lib"
)
def build(src: Path, exe: Path) -> None:
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",
str(HARNESS), str(src),
f"-L{MCFGTHREAD_LIB}", "-o", str(exe),
"-static", "-static-libgcc", "-static-libstdc++"],
check=True, timeout=60,
)
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, timeout=60)
return bytes.fromhex(out.stdout.decode().replace("\n", "").strip())
def u32(value: int) -> bytes:
return struct.pack("<I", value & 0xFFFFFFFF)
SUB_SIZE = 0x2C
SUB_TAGS = ("s80", "s84", "s88", "s8c", "s90", "s94")
SUB_FIELD_OFF = (0x80, 0x84, 0x88, 0x8C, 0x90, 0x94)
@dataclasses.dataclass(frozen=True, slots=True)
class Case:
mode: str
spec: CallSpec
payload: bytes
buf_tag: str
def mtold12_case(digit_values: list[int]) -> Case:
count = len(digit_values)
spec = CallSpec(
rva=0x405C0, conv=CDECL, ret=VOID,
stack_args=(StackValue(buffer=Buffer("dig", bytes(digit_values))),
StackValue(immediate=count),
StackValue(buffer=Buffer("out", b"\x00" * 12, out_size=12))))
payload = u32(count) + bytes(digit_values)
return Case("mtold12", spec, payload, "out")
def clear_case(gate_true: bool, subs: list[tuple[bool, int, int]]) -> Case:
addrs = []
cursor = SCRATCH_BASE
for _ in range(6):
addrs.append(cursor)
cursor += (SUB_SIZE + 15) & ~15
obj_addr = cursor
obj = bytearray(0x98)
obj[4:8] = u32(obj_addr if gate_true else 0)
sub_buffers = []
for i, (present, v24, v28) in enumerate(subs):
obj[SUB_FIELD_OFF[i]:SUB_FIELD_OFF[i] + 4] = u32(addrs[i] if present else 0)
body = bytearray(SUB_SIZE)
body[0x24:0x28] = u32(v24)
body[0x28:0x2C] = u32(v28)
sub_buffers.append(Buffer(SUB_TAGS[i], bytes(body), out_size=SUB_SIZE))
spec = CallSpec(
rva=0x25460, conv=REGISTER, ret=VOID,
regs=(RegValue("eax", buffer=Buffer("obj", bytes(obj))),),
buffers=tuple(sub_buffers))
payload = bytes([1 if gate_true else 0]) + b"".join(
bytes([1 if present else 0]) + u32(v24) + u32(v28) for present, v24, v28 in subs)
return Case("clear", spec, payload, "")
def to_results(case: Case, original: RunResult, recon: bytes) -> tuple[RunResult, RunResult]:
if case.mode == "clear":
chunks = tuple(
(SUB_TAGS[i], recon[i * SUB_SIZE:(i + 1) * SUB_SIZE]) for i in range(6))
return original, RunResult(out_buffers=chunks)
return original, RunResult(out_buffers=((case.buf_tag, recon),))
def build_entries() -> dict[str, tuple[str, list[Case]]]:
return {
"mtold12": ("___mtold12 MtoLd12",
[mtold12_case([1, 2, 3]),
mtold12_case([9, 9, 9, 9, 9, 9, 9, 9, 9, 9]),
mtold12_case([5]),
mtold12_case([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9]),
mtold12_case([1, 0, 0, 0, 0, 0, 0, 0])]),
"clear": ("FUN_10025460 ClearPairFields",
[clear_case(True, [(True, 1, 0x11111111), (True, 1, 0x22222222),
(True, 1, 0x33333333), (True, 1, 0x44444444),
(True, 1, 0x55555555), (True, 1, 0x66666666)]),
clear_case(False, [(True, 1, 0xAAAA0001), (True, 1, 0xAAAA0002),
(True, 1, 0xAAAA0003), (True, 1, 0xAAAA0004),
(True, 1, 0xAAAA0005), (True, 1, 0xAAAA0006)]),
clear_case(True, [(True, 2, 0xBBBB0001), (False, 1, 0xBBBB0002),
(True, 0, 0xBBBB0003), (True, 1, 0xBBBB0004),
(False, 1, 0xBBBB0005), (True, 1, 0xBBBB0006)]),
clear_case(True, [(True, 1, 0xC0000001), (True, 7, 0xC0000002),
(True, 1, 0xC0000003), (True, 0, 0xC0000004),
(True, 1, 0xC0000005), (True, 9, 0xC0000006)])]),
}
MUTATIONS: list[tuple[str, str, str]] = [
("// rva=0x100405c0", "std::int16_t exponent = 0x404e;", "std::int16_t exponent = 0x404f;"),
("// rva=0x10025460", "== obj[1]", "!= obj[1]"),
]
def mutate(src: str, anchor: str, old: str, new: str) -> str:
start = src.index(anchor)
hit = src.index(old, start)
return src[:hit] + new + src[hit + len(old):]
def main() -> int:
oracle = resolve_oracle("libavs-win32-ea3.dll")
image = PeImage(oracle.path)
runner = UnicornRunner(image)
entries = build_entries()
log = [f"DLL={oracle.path} sha256={oracle.sha256} base={image.image_base:#x} "
"comparison=faithful (exact owned-buffer channels)"]
build(SRC, RECON)
total_cases = 0
for _, (title, cases) in entries.items():
print(f"PROVING {title}", flush=True)
for case in cases:
original = runner.run(case.spec)
recon = run_recon(RECON, case.mode, case.payload)
left, right = to_results(case, original, recon)
report = diff(left, right)
assert report.verdict is Verdict.EQUAL, (title, case.mode, case.payload.hex(), report)
log.append(f" {title}: PASS ({len(cases)} cases, original==reconstructed)")
total_cases += len(cases)
bug_src = SRC.read_text()
for anchor, old, new in MUTATIONS:
bug_src = mutate(bug_src, anchor, old, new)
assert bug_src != SRC.read_text(), "no mutation applied"
bug_cpp = RECON.parent / "leaf_ops_w11_bug.cpp"
bug_exe = RECON.parent / "recon_libavs-win32-ea3_wave11_bug.exe"
bug_cpp.write_text(bug_src)
try:
build(bug_cpp, bug_exe)
for _, (title, cases) in entries.items():
case = cases[0]
original = runner.run(case.spec)
recon = run_recon(bug_exe, case.mode, case.payload)
left, right = to_results(case, original, recon)
report = diff(left, right)
assert report.verdict is Verdict.DIFF, (title, "injected bug not caught")
log.append(f" BUG {title} (injected bug rejected: {report.differences[0].split(':')[0]})")
finally:
bug_cpp.unlink(missing_ok=True)
bug_exe.unlink(missing_ok=True)
log.append(f"NON-VACUITY: PASS (per-body injected bug caught for all {len(entries)} bodies)")
log.append(f"ALL DIFFERENTIALS PASS ({total_cases} cases across {len(entries)} bodies, "
f"{len(entries)} verified functions)")
log.append("GLOBALS-FIRST: PASS (self-contained leaves: the CRT mantissa converter writes only "
"its caller-supplied output block; the sub-object clearer reads and writes only the "
"caller-supplied object and sub-object blocks; no module global is touched)")
print("\n".join(log))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,100 @@
// Differential harness for the libavs-win32-ea3.dll wave-11 leaves. Reads a hex
// payload on stdin, runs the reconstruction named by argv[1] on the same inputs
// the Unicorn side feeds the original, and writes the hex result the T8 differ
// compares.
// mtold12 -> the 12-byte _LDBL12 output block (mantissa + exponent);
// clear -> the six 0x2c-byte sub-objects after the +0x24/+0x28 clears.
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "libavs-win32-ea3/leaf_ops_w11.h"
using namespace gk::avsea3;
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");
}
std::uint32_t U32(const std::uint8_t* p) {
std::uint32_t v = 0;
std::memcpy(&v, p, 4);
return v;
}
int RunMtoLd12(const std::vector<std::uint8_t>& in) {
std::int32_t count = static_cast<std::int32_t>(U32(in.data()));
const char* digits = reinterpret_cast<const char*>(in.data() + 4);
std::uint8_t out[12];
std::memset(out, 0, sizeof(out));
MtoLd12(digits, count, out);
PutHex(out, sizeof(out));
return 0;
}
int RunClear(const std::vector<std::uint8_t>& in) {
constexpr std::size_t kSub = 0x2c;
std::uint8_t gate = in[0];
std::vector<std::uint32_t> obj(0x26, 0);
std::vector<std::vector<std::uint8_t>> subs(6, std::vector<std::uint8_t>(kSub, 0));
const int field_dword[6] = {0x20, 0x21, 0x22, 0x23, 0x24, 0x25};
const std::uint8_t* p = in.data() + 1;
for (int i = 0; i < 6; ++i) {
std::uint8_t present = p[0];
std::uint32_t v24 = U32(p + 1);
std::uint32_t v28 = U32(p + 5);
p += 9;
std::memcpy(subs[i].data() + 0x24, &v24, 4);
std::memcpy(subs[i].data() + 0x28, &v28, 4);
obj[field_dword[i]] =
present ? static_cast<std::uint32_t>(reinterpret_cast<std::uintptr_t>(subs[i].data())) : 0u;
}
obj[1] = gate ? static_cast<std::uint32_t>(reinterpret_cast<std::uintptr_t>(obj.data())) : 0u;
ClearPairFields(obj.data());
std::vector<std::uint8_t> out;
for (int i = 0; i < 6; ++i) {
out.insert(out.end(), subs[i].begin(), subs[i].end());
}
PutHex(out.data(), out.size());
return 0;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::fprintf(stderr, "usage: recon_avsea3_w11 <mode>\n");
return 2;
}
const std::vector<std::uint8_t> in = ReadHex();
const std::string mode = argv[1];
if (mode == "mtold12") return RunMtoLd12(in);
if (mode == "clear") return RunClear(in);
std::fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
+158
View File
@@ -0,0 +1,158 @@
#include "libavs-win32-ea3/leaf_ops_w11.h"
#include <cstdint>
#include <cstring>
namespace gk {
namespace avsea3 {
// rva=0x100405c0 (orig ___mtold12)
// Literal transcription of the VS2010 CRT multi-precision digit accumulator:
// a 96-bit accumulator (out[0..2]) is grown by *10 + next_digit per step, then
// normalised left until bit 95 is set, and a 16-bit exponent (seeded 0x404e) is
// written at byte offset 10. Every operation is unsigned 32-bit integer, so the
// transcription reproduces the original bit-for-bit.
void GK_CDECL MtoLd12(const char* digits, std::int32_t count, void* out) {
std::uint32_t* acc = static_cast<std::uint32_t*>(out);
const char* p = digits;
std::uint32_t high = 0;
std::int16_t exponent = 0x404e;
acc[0] = 0;
acc[1] = 0;
acc[2] = 0;
if (count != 0) {
std::uint32_t top = 0;
do {
std::uint32_t a0 = acc[0];
std::uint32_t a0_copy = acc[0];
std::uint32_t a1 = acc[1];
std::uint32_t a2 = acc[2];
bool carry = false;
std::uint32_t v5 = (high * 2 | a0 >> 0x1f) * 2 | a0 * 2 >> 0x1f;
a0 = a0 * 4;
high = (top * 2 | high >> 0x1f) * 2 | high * 2 >> 0x1f;
std::uint32_t v6 = a0_copy + a0;
acc[0] = a0;
acc[1] = v5;
acc[2] = high;
if ((v6 < a0) || (v6 < a0_copy)) {
carry = true;
}
acc[0] = v6;
std::uint32_t v9 = v5;
if (carry) {
carry = false;
v9 = v5 + 1;
if ((v9 < v5) || (v9 == 0)) {
carry = true;
}
acc[1] = v9;
if (carry) {
high = high + 1;
acc[2] = high;
}
}
carry = false;
std::uint32_t v2 = v9 + a1;
if ((v2 < v9) || (v2 < a1)) {
carry = true;
}
acc[1] = v2;
if (carry) {
high = high + 1;
acc[2] = high;
}
carry = false;
top = (high + a2) * 2 | v2 >> 0x1f;
v9 = v6 * 2;
std::uint32_t v8 = v2 * 2 | v6 >> 0x1f;
acc[2] = top;
acc[0] = v9;
acc[1] = v8;
high = v9 + static_cast<std::uint32_t>(static_cast<std::int32_t>(*p));
if ((high < v9) || (high < static_cast<std::uint32_t>(static_cast<std::int32_t>(*p)))) {
carry = true;
}
acc[0] = high;
high = v8;
if (carry) {
high = v8 + 1;
carry = false;
if ((high < v8) || (high == 0)) {
carry = true;
}
acc[1] = high;
if (carry) {
top = top + 1;
acc[2] = top;
}
}
count = count + -1;
p = p + 1;
acc[1] = high;
acc[2] = top;
} while (count != 0);
}
if (acc[2] == 0) {
std::uint32_t lo = acc[1];
std::uint32_t hi;
do {
exponent = static_cast<std::int16_t>(exponent - 0x10);
hi = lo >> 0x10;
lo = lo << 0x10 | acc[0] >> 0x10;
acc[1] = lo;
acc[0] = acc[0] << 0x10;
} while (hi == 0);
acc[2] = hi;
}
std::uint32_t t = acc[2];
if ((t & 0x8000) == 0) {
std::uint32_t mid = acc[1];
std::uint32_t shifted;
do {
exponent = static_cast<std::int16_t>(exponent - 1);
shifted = t * 2;
t = shifted | mid >> 0x1f;
mid = mid * 2 | acc[0] >> 0x1f;
acc[0] = acc[0] * 2;
acc[1] = mid;
acc[2] = t;
} while ((shifted & 0x8000) == 0);
}
std::memcpy(static_cast<std::uint8_t*>(out) + 10, &exponent, 2);
}
// rva=0x10025460 (orig FUN_10025460)
// Clears the +0x24/+0x28 dword pair of every eligible sub-object. The object's
// +0x80/+0x8c/+0x90 sub-objects are visited only when object==*(object+4); the
// +0x84/+0x88/+0x94 sub-objects are always visited. A sub-object is cleared only
// when non-null and its +0x24 dword equals 1.
namespace {
void ClearIfMarked(std::uint32_t slot) {
if (slot == 0) {
return;
}
std::uint32_t* sub = reinterpret_cast<std::uint32_t*>(slot);
if (sub[9] == 1) {
sub[9] = 0;
sub[10] = 0;
}
}
} // namespace
void GK_CDECL ClearPairFields(void* object) {
std::uint32_t* obj = static_cast<std::uint32_t*>(object);
if (reinterpret_cast<std::uintptr_t>(object) == obj[1]) {
ClearIfMarked(obj[0x20]);
ClearIfMarked(obj[0x23]);
ClearIfMarked(obj[0x24]);
}
ClearIfMarked(obj[0x21]);
ClearIfMarked(obj[0x22]);
ClearIfMarked(obj[0x25]);
}
} // namespace avsea3
} // namespace gk
+36
View File
@@ -0,0 +1,36 @@
#pragma once
// Reconstructed libavs-win32-ea3.dll wave-11 leaves. Each declaration pins its
// origin rva and states the calling convention read from the disassembly, per
// docs/conventions.md. Wave 11 drains self-contained CRT/runtime leaves the
// earlier waves left in orig.
//
// The observable channel for each is an owned caller-supplied buffer or a
// register-passed buffer, compared bit-for-bit through the T8 differ, so every
// reconstruction is base-agnostic.
#include <cstdint>
#include "gk/types.h"
namespace gk {
namespace avsea3 {
// rva=0x100405c0 (orig ___mtold12, VS2010 CRT) __cdecl: convert the first
// `count` raw decimal-digit values (each byte already a 0..9 value) at
// `digits` into a 12-byte _LDBL12 intermediate at `out` (three mantissa dwords
// at +0/+4/+8 and a 16-bit biased exponent at +10). The 96-bit accumulator is
// multiplied by ten (<<1 and <<2 added) and the next digit added per step, then
// the result is normalised left until bit 95 is set, decrementing the exponent
// (seeded 0x404e). Pure integer; modelled as a write of the caller-supplied
// 12-byte output block.
void GK_CDECL MtoLd12(const char* digits, std::int32_t count, void* out);
// rva=0x10025460 (orig FUN_10025460) register convention (EAX=object): for each
// of six sub-object pointers held at object+0x80/+0x84/+0x88/+0x8c/+0x90/+0x94,
// when the sub-object is non-null and its +0x24 dword equals 1, clear its +0x24
// and +0x28 dwords. The +0x80/+0x8c/+0x90 trio is gated on object==*(object+4);
// the +0x84/+0x88/+0x94 trio is always processed. Modelled as reads/writes of
// caller-supplied sub-object blocks reached through the caller-supplied object.
void GK_CDECL ClearPairFields(void* object);
} // namespace avsea3
} // namespace gk