feat(libavs-win32): reconstruct+verify wave 1 5 functions

Wave 1 on the laggard libavs-win32.dll: five self-contained AVS runtime
leaves (string/memory comparison and length helpers), each reconstructed as
MinGW C++ and verified against the shipping binary via the T1 Unicorn
differential (exact EAX channel) plus a per-body injected-bug non-vacuity
check. All are pure POD-in/scalar-out leaves: no module globals, callees, or
foreign-ABI dispatch, so the globals-first gate is trivially satisfied.
fp_model=none, portability=port.

  0x10011550 node_strlen   NUL-terminated byte-string length
  0x10005020 node_wcslen   UTF-16 code-unit length before NUL
  0x100118d0 node_strcmp   ordered byte compare, null-operand 3-way sign
  0x100114a0 node_strncmp  length-bounded node_strcmp
  0x100111c0 node_memcmp   fixed-length byte compare, 3-way sign

0x10011550 and 0x100114a0 end in a bare RET (caller cleanup), so they are
__cdecl despite Ghidra's __stdcall guess; the convention is read from the
disassembly. Proof: re/avs/prove_libavs-win32_wave1.py (32 cases, exit 0).
This commit is contained in:
ulw-execute committed 2026-11-29 10:42:05 -05:00
1 parent dbec57f800
commit 65670927cd
5 files changed
+510 -5

No files matched your search

+20 -5
View File
@@ -194573,7 +194573,10 @@
"owning_module_guess": "unknown",
"rva": "0x00005020",
"signature": "size_t __cdecl _wcslen(wchar_t * _Str)",
"status": "orig"
"status": "verified",
"fp_model": "none",
"portability": "port",
"evidence": "T1 Unicorn differential re/avs/prove_libavs-win32_wave1.py (node_wcslen): 4 cases original==recon exact EAX, plus injected-bug non-vacuity (NUL test 0->1 caught as EAX DIFF). __cdecl (bare RET); no callees/globals, globals-first gate trivial. Reconstruction src/avs/leaf_ops_w1.cpp node_wcslen. Semantic name node_wcslen (UTF-16 code-unit length before NUL)."
},
{
"callees": [
@@ -199112,7 +199115,10 @@
"owning_module_guess": "unknown",
"rva": "0x000111c0",
"signature": "int __cdecl XCd229cc000154(uint param_1, uint param_2, int param_3)",
"status": "orig"
"status": "verified",
"fp_model": "none",
"portability": "port",
"evidence": "T1 Unicorn differential re/avs/prove_libavs-win32_wave1.py (node_memcmp): 8 cases (equal, first/second-byte diff, bounded, n=0, null operands) original==recon exact EAX, plus injected-bug non-vacuity (byte-diff +1 caught as EAX DIFF). __cdecl (bare RET); no callees/globals, globals-first gate trivial. Reconstruction src/avs/leaf_ops_w1.cpp node_memcmp. Semantic name node_memcmp (fixed-length byte compare, null-operand 3-way sign)."
},
{
"callees": [
@@ -199166,7 +199172,10 @@
"owning_module_guess": "unknown",
"rva": "0x000114a0",
"signature": "uint __stdcall XCd229cc00007a(uint param_1, uint param_2, int param_3)",
"status": "orig"
"status": "verified",
"fp_model": "none",
"portability": "port",
"evidence": "T1 Unicorn differential re/avs/prove_libavs-win32_wave1.py (node_strncmp): 8 cases (length-bounded equal/less, truncated, b-NUL stop, n=0, null operands) original==recon exact EAX, plus injected-bug non-vacuity (NUL compare 0->1 caught as EAX DIFF). Bare RET => __cdecl (overrides Ghidra __stdcall guess); no callees/globals, globals-first gate trivial. Reconstruction src/avs/leaf_ops_w1.cpp node_strncmp. Semantic name node_strncmp (length-bounded node_strcmp)."
},
{
"callees": [],
@@ -199209,7 +199218,10 @@
"owning_module_guess": "unknown",
"rva": "0x00011550",
"signature": "int __stdcall XCd229cc000056(char * param_1)",
"status": "orig"
"status": "verified",
"fp_model": "none",
"portability": "port",
"evidence": "T1 Unicorn differential re/avs/prove_libavs-win32_wave1.py (node_strlen): 4 cases original==recon exact EAX, plus injected-bug non-vacuity (NUL test '\\0'->'\\x01' caught as EAX DIFF). Bare RET => __cdecl (overrides Ghidra __stdcall guess); no callees/globals, globals-first gate trivial. Reconstruction src/avs/leaf_ops_w1.cpp node_strlen. Semantic name node_strlen (NUL-terminated byte-string length)."
},
{
"callees": [],
@@ -199450,7 +199462,10 @@
"owning_module_guess": "unknown",
"rva": "0x000118d0",
"signature": "uint __cdecl XCd229cc0000a0(uint param_1, uint param_2)",
"status": "orig"
"status": "verified",
"fp_model": "none",
"portability": "port",
"evidence": "T1 Unicorn differential re/avs/prove_libavs-win32_wave1.py (node_strcmp): 8 cases (equal, less, greater, prefix, empty, both/either-null) original==recon exact EAX, plus injected-bug non-vacuity (NUL compare 0->1 caught as EAX DIFF). __cdecl (bare RET); no callees/globals, globals-first gate trivial. Reconstruction src/avs/leaf_ops_w1.cpp node_strcmp. Semantic name node_strcmp (ordered byte compare stopping at operand-b NUL, null-operand 3-way sign)."
},
{
"callees": [],
+237
View File
@@ -0,0 +1,237 @@
"""libavs-win32.dll wave-1 differential proof.
Five self-contained AVS runtime leaves (string/memory comparison and length
helpers) proved with the compiled-recon differential: each original is emulated
inside the shipping libavs-win32.dll under Unicorn and the MinGW C++
reconstruction (src/avs/leaf_ops_w1.cpp) runs under wine on identical inputs,
compared bit-for-bit through the T8 differ (exact EAX channel). A final pass
rebuilds the reconstruction with a per-body injected bug and asserts every
differential flags it.
Globals-first: every leaf is self-contained. node_strlen / node_wcslen read one
caller-supplied string; node_strcmp / node_strncmp / node_memcmp read two
caller-supplied buffers. None reads or writes a module global or calls another
routine, so the ownership gate is trivially satisfied.
tools/unicorn_diff/.venv/bin/python re/avs/prove_libavs-win32_wave1.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, ReturnKind,
RunResult, StackValue, UnicornRunner, Verdict, diff,
)
from udiff.scaffold import resolve_oracle # noqa: E402
CDECL = CallConv.CDECL
INT = ReturnKind.INT
MODULE = ROOT / "re" / "avs"
HARNESS = MODULE / "recon_avs_w1_harness.cpp"
SRC = ROOT / "src" / "avs" / "leaf_ops_w1.cpp"
RECON = MODULE / "recon_avs_w1.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",
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=120,
)
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)
@dataclasses.dataclass(frozen=True, slots=True)
class Case:
mode: str
spec: CallSpec
payload: bytes
def strlen_case(text: bytes) -> Case:
data = text + b"\x00"
spec = CallSpec(rva=0x11550, conv=CDECL, ret=INT,
stack_args=(StackValue(buffer=Buffer("s", data)),))
return Case("strlen", spec, data)
def wcslen_case(units: list[int]) -> Case:
data = b"".join(struct.pack("<H", u) for u in units) + b"\x00\x00"
spec = CallSpec(rva=0x5020, conv=CDECL, ret=INT,
stack_args=(StackValue(buffer=Buffer("ws", data)),))
return Case("wcslen", spec, data)
def _arg(tag: str, data: bytes, is_null: bool) -> StackValue:
return StackValue(immediate=0) if is_null else StackValue(buffer=Buffer(tag, data))
def strcmp_case(a: bytes | None, b: bytes | None) -> Case:
adata = (a if a is not None else b"") + b"\x00"
bdata = (b if b is not None else b"") + b"\x00"
spec = CallSpec(rva=0x118D0, conv=CDECL, ret=INT,
stack_args=(_arg("a", adata, a is None), _arg("b", bdata, b is None)))
payload = (bytes([1 if a is None else 0, 1 if b is None else 0])
+ u32(len(adata)) + adata + u32(len(bdata)) + bdata)
return Case("strcmp", spec, payload)
def strncmp_case(a: bytes | None, b: bytes | None, n: int) -> Case:
adata = (a if a is not None else b"") + b"\x00"
bdata = (b if b is not None else b"") + b"\x00"
spec = CallSpec(rva=0x114A0, conv=CDECL, ret=INT,
stack_args=(_arg("a", adata, a is None), _arg("b", bdata, b is None),
StackValue(immediate=n)))
payload = (bytes([1 if a is None else 0, 1 if b is None else 0]) + u32(n)
+ u32(len(adata)) + adata + u32(len(bdata)) + bdata)
return Case("strncmp", spec, payload)
def memcmp_case(a: bytes | None, b: bytes | None, n: int) -> Case:
adata = a if a is not None else b""
bdata = b if b is not None else b""
spec = CallSpec(rva=0x111C0, conv=CDECL, ret=INT,
stack_args=(_arg("a", adata, a is None), _arg("b", bdata, b is None),
StackValue(immediate=n)))
payload = (bytes([1 if a is None else 0, 1 if b is None else 0]) + u32(n)
+ u32(len(adata)) + adata + u32(len(bdata)) + bdata)
return Case("memcmp", spec, payload)
def build_entries() -> dict[str, tuple[str, list[Case]]]:
return {
"strlen": ("FUN_10011550 node_strlen",
[strlen_case(b""), strlen_case(b"a"), strlen_case(b"avs2 property"),
strlen_case(b"\xff\xfe\x01")]),
"wcslen": ("FUN_10005020 node_wcslen",
[wcslen_case([]), wcslen_case([0x41]),
wcslen_case([0x61, 0x76, 0x73, 0x32]), wcslen_case([0xFFFF, 0x0001])]),
"strcmp": ("FUN_100118d0 node_strcmp",
[strcmp_case(b"abc", b"abc"), strcmp_case(b"abc", b"abd"),
strcmp_case(b"abcd", b"abc"), strcmp_case(b"abc", b"abcd"),
strcmp_case(b"", b""), strcmp_case(None, b"x"),
strcmp_case(b"x", None), strcmp_case(None, None)]),
"strncmp": ("FUN_100114a0 node_strncmp",
[strncmp_case(b"abc", b"abc", 3), strncmp_case(b"abc", b"abd", 3),
strncmp_case(b"abcd", b"abXd", 2), strncmp_case(b"abc", b"abc", 10),
strncmp_case(b"abcZ", b"abc", 10), strncmp_case(b"abc", b"abc", 0),
strncmp_case(None, b"x", 3), strncmp_case(b"x", None, 3)]),
"memcmp": ("FUN_100111c0 node_memcmp",
[memcmp_case(b"abc", b"abc", 3), memcmp_case(b"abc", b"abd", 3),
memcmp_case(b"\x01\x02\x03", b"\x01\x05\x03", 3),
memcmp_case(b"abcd", b"abXd", 2), memcmp_case(b"abc", b"abc", 0),
memcmp_case(None, b"xyz", 3), memcmp_case(b"xyz", None, 3),
memcmp_case(None, None, 3)]),
}
MUTATIONS: list[tuple[str, str, str]] = [
("// rva=0x10011550", "while (s[n] != '\\0') {", "while (s[n] != '\\x01') {"),
("// rva=0x10005020", "while (s[n] != 0) {", "while (s[n] != 1) {"),
("// rva=0x100118d0", "if (b[i] == 0 || (d = d - static_cast<std::uint32_t>(b[i])) != 0) {",
"if (b[i] == 1 || (d = d - static_cast<std::uint32_t>(b[i])) != 0) {"),
("// rva=0x100114a0", "if (b[i] == 0 || (d = d - static_cast<std::uint32_t>(b[i])) != 0) {",
"if (b[i] == 1 || (d = d - static_cast<std::uint32_t>(b[i])) != 0) {"),
("// rva=0x100111c0",
"const int d = static_cast<int>(static_cast<std::uint32_t>(a[i]) -\n"
" static_cast<std::uint32_t>(b[i]));",
"const int d = static_cast<int>(static_cast<std::uint32_t>(a[i]) -\n"
" static_cast<std::uint32_t>(b[i]) + 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.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 EAX channel)"]
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)
report = diff(original, RunResult(eax=int.from_bytes(recon, "little")))
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_w1_bug.cpp"
bug_exe = RECON.parent / "recon_avs_w1_bug.exe"
bug_cpp.write_text(bug_src)
try:
build(bug_cpp, bug_exe)
for _, (title, cases) in entries.items():
flagged = False
for case in cases:
original = runner.run(case.spec)
recon = run_recon(bug_exe, case.mode, case.payload)
report = diff(original, RunResult(eax=int.from_bytes(recon, "little")))
if report.verdict is Verdict.DIFF:
flagged = True
log.append(f" BUG {title} (injected bug rejected: "
f"{report.differences[0].split(':')[0]})")
break
assert flagged, (title, "injected bug not caught by any case")
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: each reads only its "
"caller-supplied string/buffer operands; no module global, callee, or "
"foreign-ABI dispatch)")
print("\n".join(log))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+136
View File
@@ -0,0 +1,136 @@
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include "avs/leaf_ops_w1.h"
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 Rd32(const std::vector<std::uint8_t> &in, std::size_t pos) {
return static_cast<std::uint32_t>(in[pos]) |
(static_cast<std::uint32_t>(in[pos + 1]) << 8) |
(static_cast<std::uint32_t>(in[pos + 2]) << 16) |
(static_cast<std::uint32_t>(in[pos + 3]) << 24);
}
int RunStrlen(const std::vector<std::uint8_t> &in) {
const std::uint32_t r =
static_cast<std::uint32_t>(avs::node_strlen(reinterpret_cast<const char *>(in.data())));
PutHex(&r, sizeof(r));
return 0;
}
int RunWcslen(const std::vector<std::uint8_t> &in) {
const std::uint32_t r =
avs::node_wcslen(reinterpret_cast<const std::uint16_t *>(in.data()));
PutHex(&r, sizeof(r));
return 0;
}
int RunStrcmp(const std::vector<std::uint8_t> &in) {
std::size_t c = 0;
const std::uint8_t a_null = in[c++];
const std::uint8_t b_null = in[c++];
const std::uint32_t la = Rd32(in, c);
c += 4;
const unsigned char *a = in.data() + c;
c += la;
const std::uint32_t lb = Rd32(in, c);
c += 4;
const unsigned char *b = in.data() + c;
const std::uint32_t r = avs::node_strcmp(a_null ? nullptr : a, b_null ? nullptr : b);
PutHex(&r, sizeof(r));
return 0;
}
int RunStrncmp(const std::vector<std::uint8_t> &in) {
std::size_t c = 0;
const std::uint8_t a_null = in[c++];
const std::uint8_t b_null = in[c++];
const int n = static_cast<int>(Rd32(in, c));
c += 4;
const std::uint32_t la = Rd32(in, c);
c += 4;
const unsigned char *a = in.data() + c;
c += la;
const std::uint32_t lb = Rd32(in, c);
c += 4;
const unsigned char *b = in.data() + c;
const std::uint32_t r = avs::node_strncmp(a_null ? nullptr : a, b_null ? nullptr : b, n);
PutHex(&r, sizeof(r));
return 0;
}
int RunMemcmp(const std::vector<std::uint8_t> &in) {
std::size_t c = 0;
const std::uint8_t a_null = in[c++];
const std::uint8_t b_null = in[c++];
const int n = static_cast<int>(Rd32(in, c));
c += 4;
const std::uint32_t la = Rd32(in, c);
c += 4;
const unsigned char *a = in.data() + c;
c += la;
const std::uint32_t lb = Rd32(in, c);
c += 4;
const unsigned char *b = in.data() + c;
const std::uint32_t r =
static_cast<std::uint32_t>(avs::node_memcmp(a_null ? nullptr : a, b_null ? nullptr : b, n));
PutHex(&r, sizeof(r));
return 0;
}
} // namespace
int main(int argc, char **argv) {
if (argc < 2) {
std::fprintf(stderr, "usage: recon_avs_w1 <mode>\n");
return 2;
}
const std::vector<std::uint8_t> in = ReadHex();
const std::string mode = argv[1];
if (mode == "strlen") {
return RunStrlen(in);
}
if (mode == "wcslen") {
return RunWcslen(in);
}
if (mode == "strcmp") {
return RunStrcmp(in);
}
if (mode == "strncmp") {
return RunStrncmp(in);
}
if (mode == "memcmp") {
return RunMemcmp(in);
}
std::fprintf(stderr, "unknown mode %s\n", argv[1]);
return 2;
}
+93
View File
@@ -0,0 +1,93 @@
#include "avs/leaf_ops_w1.h"
namespace avs {
// rva=0x10011550 (orig XCd229cc000056)
int GK_CDECL node_strlen(const char *s) {
if (s == nullptr) {
return 0;
}
int n = 0;
while (s[n] != '\0') {
n = n + 1;
}
return n;
}
// rva=0x10005020 (orig _wcslen)
std::uint32_t GK_CDECL node_wcslen(const std::uint16_t *s) {
std::uint32_t n = 0;
while (s[n] != 0) {
n = n + 1;
}
return n;
}
// rva=0x100118d0 (orig XCd229cc0000a0)
std::uint32_t GK_CDECL node_strcmp(const unsigned char *a, const unsigned char *b) {
const std::uint32_t fa = (a != nullptr) ? 1u : 0u;
const std::uint32_t fb = (b != nullptr) ? 1u : 0u;
if ((fa & fb) != 0) {
std::uint32_t d = 0;
int i = 0;
while (true) {
d = static_cast<std::uint32_t>(a[i]);
if (b[i] == 0 || (d = d - static_cast<std::uint32_t>(b[i])) != 0) {
break;
}
i = i + 1;
}
return d;
}
if (fb != 0 || fa != 0) {
return (fa == 0) ? 0xFFFFFFFFu : 1u;
}
return 0u;
}
// rva=0x100114a0 (orig XCd229cc00007a)
std::uint32_t GK_CDECL node_strncmp(const unsigned char *a, const unsigned char *b, int n) {
const std::uint32_t fa = (a != nullptr) ? 1u : 0u;
const std::uint32_t fb = (b != nullptr) ? 1u : 0u;
if ((fb & fa) == 0) {
if (fb == 0 && fa == 0) {
return 0u;
}
return (fa == 0) ? 0xFFFFFFFFu : 1u;
}
if (n > 0) {
int i = 0;
do {
std::uint32_t d = static_cast<std::uint32_t>(a[i]);
if (b[i] == 0 || (d = d - static_cast<std::uint32_t>(b[i])) != 0) {
return d;
}
i = i + 1;
} while (i < n);
}
return 0u;
}
// rva=0x100111c0 (orig XCd229cc000154)
int GK_CDECL node_memcmp(const unsigned char *a, const unsigned char *b, int n) {
const std::uint32_t fa = (a != nullptr) ? 1u : 0u;
const std::uint32_t fb = (b != nullptr) ? 1u : 0u;
if ((fb & fa) != 0) {
if (n > 0) {
int i = 0;
do {
const int d = static_cast<int>(static_cast<std::uint32_t>(a[i]) -
static_cast<std::uint32_t>(b[i]));
if (d != 0) {
return d;
}
i = i + 1;
} while (i < n);
}
} else if (fb != 0 || fa != 0) {
return (fa == 0) ? -1 : 1;
}
return 0;
}
} // namespace avs
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <cstdint>
#include "gk/types.h"
namespace avs {
// rva=0x10011550 (orig XCd229cc000056) node_strlen
int GK_CDECL node_strlen(const char *s);
// rva=0x10005020 (orig _wcslen) node_wcslen
std::uint32_t GK_CDECL node_wcslen(const std::uint16_t *s);
// rva=0x100118d0 (orig XCd229cc0000a0) node_strcmp
std::uint32_t GK_CDECL node_strcmp(const unsigned char *a, const unsigned char *b);
// rva=0x100114a0 (orig XCd229cc00007a) node_strncmp
std::uint32_t GK_CDECL node_strncmp(const unsigned char *a, const unsigned char *b, int n);
// rva=0x100111c0 (orig XCd229cc000154) node_memcmp
int GK_CDECL node_memcmp(const unsigned char *a, const unsigned char *b, int n);
} // namespace avs