165 lines
5.8 KiB
Python
165 lines
5.8 KiB
Python
"""Per-function differential scaffold from one re/rvadb.json row.
|
|
|
|
Emits a compilable MinGW C++ stub (the reconstruction skeleton, pinned with
|
|
the rva comment docs/conventions.md requires) plus a Python CallSpec harness
|
|
scaffold shaped like prove_box/prove_elev in tools/unicorn_diff/prove_t11.py.
|
|
The row's calling_convention, signature and globals_touched decide the
|
|
boilerplate; a worker fills the TODO body and representative CallSpec inputs,
|
|
not the surrounding structure.
|
|
"""
|
|
# /// script
|
|
# requires-python = ">=3.11"
|
|
# dependencies = []
|
|
# ///
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import sys
|
|
from pathlib import Path
|
|
from typing import Final
|
|
|
|
from rvadb import FunctionRow, load_database
|
|
|
|
CALLCONV_TO_GK: Final[dict[str, str]] = {
|
|
"cdecl": "GK_CDECL",
|
|
"stdcall": "GK_STDCALL",
|
|
"thiscall": "GK_THISCALL",
|
|
}
|
|
|
|
|
|
def gk_macro(calling_convention: str) -> tuple[str, str]:
|
|
normalized = calling_convention.removeprefix("__")
|
|
macro = CALLCONV_TO_GK.get(normalized)
|
|
if macro is not None:
|
|
return macro, ""
|
|
warning = f" // TODO: rvadb calling_convention={calling_convention!r} has no GK_* macro; confirm from disasm."
|
|
return "GK_CDECL", warning
|
|
|
|
|
|
def split_params(params_text: str) -> tuple[str, ...]:
|
|
text = params_text.strip()
|
|
if text in ("", "void"):
|
|
return ()
|
|
depth = 0
|
|
parts: list[str] = []
|
|
current = ""
|
|
for char in text:
|
|
if char == "," and depth == 0:
|
|
parts.append(current)
|
|
current = ""
|
|
continue
|
|
if char in "(<":
|
|
depth += 1
|
|
elif char in ")>":
|
|
depth -= 1
|
|
current += char
|
|
parts.append(current)
|
|
return tuple(part.strip() for part in parts)
|
|
|
|
|
|
def parse_signature(signature: str) -> tuple[str, tuple[str, ...]]:
|
|
open_paren = signature.index("(")
|
|
close_paren = signature.rindex(")")
|
|
return_type = signature[:open_paren].strip()
|
|
params = split_params(signature[open_paren + 1:close_paren])
|
|
return return_type, params
|
|
|
|
|
|
def render_params(ghidra_params: tuple[str, ...]) -> str:
|
|
if not ghidra_params:
|
|
return "void"
|
|
args = [f"std::uint32_t arg{i} /* ghidra: {text} */" for i, text in enumerate(ghidra_params)]
|
|
return ", ".join(args)
|
|
|
|
|
|
def render_cpp_stub(row: FunctionRow) -> str:
|
|
return_type_guess, params = parse_signature(row.signature)
|
|
macro, convention_warning = gk_macro(row.calling_convention)
|
|
cpp_return_type = "void" if return_type_guess == "void" else "std::uint32_t"
|
|
return_stmt = "" if cpp_return_type == "void" else "return {};"
|
|
rva_hex = row.rva[2:]
|
|
globals_list = ", ".join(row.globals_touched) if row.globals_touched else "(none recorded)"
|
|
lines = [
|
|
"// AUTO-GENERATED by tools/wave/callspec_scaffold.py -- fill in, then move into src/",
|
|
f"// rva=0x{rva_hex} (orig {row.name})",
|
|
f"// calling_convention(rvadb)={row.calling_convention!r} -> {macro}",
|
|
f"// signature(rvadb)={row.signature!r}",
|
|
f"// globals_touched: {globals_list}",
|
|
"// TODO: move into the owning namespace per docs/conventions.md, give it its",
|
|
"// real semantic name, and replace the stub body with the reconstruction",
|
|
"// decompiled per docs/reconstruction-loop.md step 1-2.",
|
|
]
|
|
if convention_warning:
|
|
lines.append(convention_warning)
|
|
lines += [
|
|
'#include "gk/types.h"',
|
|
"",
|
|
"namespace gk::todo {",
|
|
"",
|
|
f"{cpp_return_type} {macro} Reconstructed_{rva_hex}({render_params(params)}) {{",
|
|
" // TODO: reconstructed body goes here (see docs/conventions.md).",
|
|
f" {return_stmt}".rstrip(),
|
|
"}",
|
|
"",
|
|
"} // namespace gk::todo",
|
|
"",
|
|
]
|
|
return "\n".join(lines)
|
|
|
|
|
|
def render_python_scaffold(row: FunctionRow) -> str:
|
|
rva_hex = row.rva[2:]
|
|
return "\n".join([
|
|
f"def prove_{rva_hex}(image: PeImage, log: list[str]) -> None: # orig: {row.name}",
|
|
" runner = UnicornRunner(image)",
|
|
f" conv = load_calling_convention(0x{rva_hex})",
|
|
" # TODO: representative cases -- regs/buffers below are placeholders.",
|
|
" spec = CallSpec(",
|
|
f" rva=0x{rva_hex},",
|
|
" conv=conv,",
|
|
" ret=ReturnKind.INT, # TODO: confirm INT/FLOAT_ST0/DOUBLE_ST0 from the disasm",
|
|
" regs=(), # TODO: add RegValue(...) per argument/this-pointer",
|
|
" )",
|
|
" original = runner.run(spec)",
|
|
" # TODO: run the compiled reconstruction under wine with the same inputs and diff()",
|
|
f' log.append(f"FUN_{rva_hex}: TODO - add representative inputs and the diff() assertion")',
|
|
"",
|
|
])
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description="Scaffold a compilable C++ stub + CallSpec harness for one rvadb row.",
|
|
)
|
|
parser.add_argument("db", type=Path)
|
|
parser.add_argument("rva", help="canonical hex RVA, e.g. 0x001ab640")
|
|
parser.add_argument("--out-dir", type=Path, default=None)
|
|
args = parser.parse_args()
|
|
|
|
db = load_database(args.db)
|
|
row = next((r for r in db.functions if r.rva == args.rva), None)
|
|
if row is None:
|
|
print(f"RVA {args.rva} not found in {args.db}", file=sys.stderr)
|
|
return 2
|
|
|
|
cpp_text = render_cpp_stub(row)
|
|
py_text = render_python_scaffold(row)
|
|
if args.out_dir is None:
|
|
print(cpp_text)
|
|
print("// ---- Python CallSpec scaffold ----")
|
|
print(py_text)
|
|
return 0
|
|
|
|
args.out_dir.mkdir(parents=True, exist_ok=True)
|
|
cpp_path = args.out_dir / f"recon_{row.rva[2:]}.stub.cpp"
|
|
py_path = args.out_dir / f"prove_{row.rva[2:]}.stub.py"
|
|
cpp_path.write_text(cpp_text, encoding="utf-8")
|
|
py_path.write_text(py_text, encoding="utf-8")
|
|
print(f"wrote {cpp_path}")
|
|
print(f"wrote {py_path}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|