# Per-function reconstruction loop and wave playbook This is the repeatable procedure a worker (human or agent) runs to turn one original `FUN_` into a verified MinGW C++ reconstruction, and the playbook for running many workers in parallel until coverage reaches 100% across `gamekdm.dll` and its in-scope companions. It is grounded in what the proven slice (T11) and the hybrid detour framework (T12) actually produced. The functions used as worked examples below are real: - `gk::game::BoxDistanceSquared` in `src/game/box_distance.cpp` (rva `0x001ab6d0`), with its two clamp callees `0x001ab640` and `0x001ab5b0`. - `gk::game::UpdateCameraElevation` in `src/game/nui_elevation.cpp` (rva `0x0000f510`). - `gk::game::UpdateValidityCandidates` in `src/game/validity.cpp` (rva `0x000e4140`). - The differential proof that gates all three: `tools/unicorn_diff/prove_t11.py`. - The detour registry: `src/hybrid/detours.h`, `src/hybrid/detours.cpp`, `src/hybrid/README.md`. - The concurrency lock and its validator: `re/rvadb.json`, `tools/ghidra/validate_rvadb.py`, `tools/ghidra/export_rvadb.py`. Read `docs/conventions.md` (the binding cleanup contract) and `docs/pipeline.md` (zero-to-verified build) first. This file is the loop that sits on top of them. ## Prerequisites (once per shell) ```bash cd /path/to/worktree source ~/.nix-profile/etc/profile.d/nix.sh source ./activate.sh command -v i686-w64-mingw32-g++ gendef dlltool wine # sanity check ``` The Ghidra projects already exist under `/home/athapa/ghidra`: `gkproj.rep` holds the analyzed `gamekdm.dll`; each in-scope companion has its own project (`avsproj`, `essproj`, `arkkdmproj`, ...), created by `tools/ghidra/import_companions.sh`. The original `gamekdm.dll` the differential emulates lives at `/home/athapa/ghidra/gamekdm.dll`. ## 1. The mechanical loop Each function goes through the same ordered steps. The status field in the RVA database (`re/rvadb.json`) records where it is and, critically, acts as the claim lock between workers (section 2). The allowed status values, enforced by `tools/ghidra/validate_rvadb.py`, are `orig` (untouched), `stub` (forwarded or placeholder), `reimpl` (reconstructed, not yet proven), and `verified`. ### Step 0: pick and claim an RVA (orig -> reimpl) Find an unclaimed function and flip its status so no other worker takes it. The "in-progress" state is the `reimpl` enum value; `orig` means nobody owns it. ```bash # list claimable (status=orig) functions python3 - <<'PY' import json db = json.load(open("re/rvadb.json")) orig = [f["rva"] for f in db["functions"] if f["status"] == "orig"] print(len(orig), "claimable; first few:", orig[:5]) PY # claim ONE rva: orig -> reimpl (edit in place, then commit the DB alone) python3 - "0x001ab640" <<'PY' import json, sys rva = sys.argv[1] db = json.load(open("re/rvadb.json")) row = next(f for f in db["functions"] if f["rva"] == rva) assert row["status"] == "orig", f"{rva} already {row['status']} (someone owns it)" row["status"] = "reimpl" json.dump(db, open("re/rvadb.json", "w"), indent=1) print("claimed", rva, "-> reimpl") PY ``` Commit the claim (the RVA DB change only) before doing the work, so the lock is visible to every other worker's next `git pull` / rebase. One rva, one owner. ### Step 1: decompile from the Ghidra project Decompile the claimed function headless, from the already-analyzed project, with no re-analysis. Put a tiny decompile post-script on the script path (any dir, e.g. a scratch dir outside the tree; it is tooling, not a tracked source file) that opens the decompiler and prints the C for one rva: ```python # /tmp/decompile.py (@category GameKDM; Jython 2.7 under Ghidra 11.3) from ghidra.app.decompiler import DecompInterface from ghidra.util.task import ConsoleTaskMonitor args = getScriptArgs() rva = int(args[0], 16) fn = currentProgram.getFunctionManager().getFunctionAt( currentProgram.getImageBase().add(rva)) ifc = DecompInterface(); ifc.openProgram(currentProgram) res = ifc.decompileFunction(fn, 60, ConsoleTaskMonitor()) print("DECOMP_BEGIN"); print(res.getDecompiledFunction().getC()); print("DECOMP_END") ``` ```bash export JAVA_HOME=/home/athapa/jdk/jdk-21.0.5+11 /home/athapa/ghidra/ghidra_11.3.1_PUBLIC/support/analyzeHeadless \ /home/athapa/ghidra gkproj -process gamekdm.dll -noanalysis -readOnly \ -scriptPath /tmp -postScript decompile.py 0x001ab640 ``` For a companion function, point at its project instead (`avsproj` for `libavs-win32.dll`, and so on). Also read the raw validity-gate disasm for the same rva: the calling convention, the FP model (x87 vs SSE), and the struct field accesses are read off the disasm, not guessed (see `docs/conventions.md`). **Worker judgement:** Ghidra's output names things like `param_1`, `unaff_ESI`, and `NAN(a) || NAN(b)` guards. Deciding the real signature, which register carries the hidden output pointer, and the semantic name is human/agent work. ### Step 2: clean to MinGW C++ per docs/conventions.md Write the reconstruction into the right module namespace file under `src/`. Apply every rule in `docs/conventions.md`: - Pin the origin so the differ can read it back: `// rva=0x101ab6d0 (orig FUN_101ab6d0)`. - State the calling convention with `GK_CDECL` / `GK_STDCALL` / `GK_THISCALL` (`include/gk/types.h`), read from the disasm (`ret N` = callee cleanup, `this` in `ecx` = thiscall, bare `ret` = cdecl). - Match MSVC struct layout (natural alignment, or `GK_PACK_PUSH(n)` / `GK_PACK_POP`). Structs live in `include/gk/structs` (`math.h`, `validity.h`, `skeleton.h`, `manager.h`) and are shared; see the struct-DB rule in 2.4. - Match the original FP model: `-mfpmath=387` default, `-mfpmath=sse -msse2` when the disasm shows SSE scalar ops; always `-ffp-contract=off -fno-fast-math`. `box_distance.cpp` keeps `volatile` spills to reproduce the original's exact intermediate rounding; this is deliberate, not noise. - Let MinGW regenerate vtables/RTTI under the Itanium ABI; never memcpy MSVC vtable bytes. `src/game/box_distance.cpp` is the reference for a clean leaf reconstruction; `src/game/nui_elevation.cpp` shows a function that dispatches through a reconstructed virtual interface. ### Step 3: verify with the Unicorn differential (and golden where a fixture exists) Build the reconstruction harness into a 32-bit wine executable with the pinned float flags, then run the differential. It emulates the real routine inside the shipping DLL (Unicorn) and runs the compiled C++ under wine on the same inputs, asserting behavioural equality through the T8 differ, and it injects a known bug to prove the comparison can fail (non-vacuity). ```bash i686-w64-mingw32-g++ -std=c++20 -O2 -mfpmath=sse -msse2 -ffp-contract=off -fno-fast-math \ -Iinclude -Isrc -Isrc/game \ tools/unicorn_diff/recon_harness.cpp \ src/game/box_distance.cpp src/game/validity.cpp src/game/nui_elevation.cpp \ -L/nix/store/g72bh3mrbh6gkh59axd2199js9kccxfs-mcfgthread-i686-w64-mingw32-2.5.1/lib \ -o tools/unicorn_diff/recon.exe -static -static-libgcc -static-libstdc++ tools/unicorn_diff/.venv/bin/python tools/unicorn_diff/prove_t11.py # expect: ALL DIFFERENTIALS PASS (exit 0) ``` Where a committed input/output fixture exists, also run the standalone golden harness (no binary, no wine; it proves its own assertions can fail): ```bash tests/golden/run.sh # expect: GOLDEN HARNESS OK: clean run passed and every perturbation failed. ``` **Worker judgement:** a brand-new function has no case in `prove_t11.py` yet. Adding its `CallSpec` (argument registers, `ReturnKind`, memory layout of its pointer arguments, representative input cases) is the real reconstruction work. Copy the shape of `prove_box` / `prove_elev` / `prove_gate`. For companions, their own proof script is the pattern (`re/avs/prove_t14.py`). ### Step 4: register the detour (only if POD/stateless per T12's ownership rule) If the function is a pure, POD-in/POD-out leaf with no shared mutable global state and no foreign-object ABI, it can be hot-patched into the loaded original image via `src/hybrid/detours.*`. Ownership is an immutable allowlist in the registry (`Entry entries_[]` in `detours.h`), never caller-supplied. Only `Ownership::pod_only` entries can be enabled; `set_enabled` returns `ownership_blocked` for anything else. The T12 ownership verdicts, from `src/hybrid/README.md`, are the template: | RVA | Reconstruction | Ownership | | --- | --- | --- | | `0x1ab6d0` | `BoxDistanceSquared` | `pod_only` (allowed): POD inputs, no allocations, EH, globals, or virtual calls. | | `0x0e4140` | `UpdateValidityCandidates` | `shared_mutable_globals` (blocked): reads/writes shared candidate globals; a second copy would drift. | | `0x00f510` | `UpdateCameraElevation` | `foreign_object_abi` (blocked): shared sensor/object state and MSVC virtual ABI. | A blocked function is still reconstructed and differentially verified; it just is not hot-patched. Extending the allowlist requires auditing ownership, the exact register ABI, instruction boundaries, and relocation needs by hand. ### Step 5: mark verified (reimpl -> verified) Once the differential (and golden, where applicable) passes, flip the status and revalidate the whole DB before committing. ```bash python3 - "0x001ab640" <<'PY' import json, sys rva = sys.argv[1] db = json.load(open("re/rvadb.json")) row = next(f for f in db["functions"] if f["rva"] == rva) assert row["status"] == "reimpl", f"{rva} is {row['status']}, expected reimpl" row["status"] = "verified" json.dump(db, open("re/rvadb.json", "w"), indent=1) print("verified", rva) PY # revalidate: counts, unique/sorted rvas, call-graph symmetry, data payloads python3 tools/ghidra/validate_rvadb.py re/rvadb.json "$(python3 -c \ 'import json;print(json.load(open("re/rvadb.json"))["function_count"])')" # expect: RVADB_VALID functions=... ghidra_count=... data_symbols=... ``` `export_rvadb.py` preserves prior statuses on re-export, so re-running Ghidra analysis never silently resets a `verified` row back to `orig`. ## 2. Parallelization playbook ### 2.1 RTTI / namespace clustering Shard by cohesion, not by raw address ranges. Cluster functions that belong to the same recovered C++ class (shared vtable / RTTI) or the same owning module namespace into one worker's assignment. `export_rvadb.py` records `owning_module_guess` per function; a class's methods share layout decisions and touch the same structs, so one worker reconstructing a whole class avoids two workers racing on the same vtable or struct definition. The validity cluster (`box_distance` + `validity` + the clamp leaves `0x1ab640` / `0x1ab5b0`) is one such unit: its leaves are reconstructed in the same pass as their caller. ### 2.2 The RVA DB status field as the concurrency lock `re/rvadb.json` is the single source of truth for who owns what. The protocol: - A function at `orig` is unclaimed. - A worker claims by committing `orig -> reimpl` (section 1, step 0) **before** starting. The commit publishes the claim; the next worker's pull sees it. - `reimpl` means owned and in progress. No other worker touches a non-`orig` row. - `verified` is terminal. Only the owning worker flips `reimpl -> verified`, and only after the differential passes. `validate_rvadb.py` is the referee: it enforces the status enum, unique and sorted rvas, and bidirectional call-graph edges, so a merge that corrupts the lock table fails loudly. Keep claim commits small (the DB alone) so they rebase cleanly against other workers' claims. ### 2.3 Sharding functions across workers Build the work queue from the DB, partition by cluster, and hand each worker a disjoint set of rvas: ```bash python3 - <<'PY' import json, collections db = json.load(open("re/rvadb.json")) orig = [f for f in db["functions"] if f["status"] == "orig"] by_mod = collections.Counter(f["owning_module_guess"] for f in orig) print(len(orig), "claimable functions across", len(by_mod), "module clusters") for mod, n in by_mod.most_common(10): print(f" {n:5d} {mod}") PY ``` Prefer leaf-first ordering inside a shard: a function cannot be marked `verified` until its callees and read globals are (sections 2.4 and 3a), so assign a worker a caller plus its not-yet-done callees together rather than splitting a call chain across workers. ### 2.4 Struct-DB coordination (include/gk/structs ownership) Shared structs are a second lock surface. Struct layouts live in `include/gk/structs` (and, per companion, in a struct DB like `re/avs/avs_structdb.json`). The rule: a struct has one owner. The first worker to need a struct defines it in `include/gk/structs`, with the Ghidra evidence in a comment (`// offsets confirmed via Ghidra struct editor on orig/gamekdm.dll`, and the `FUN_...` accessors that prove each offset, as `math.h` and `validity.h` already do). Other workers include it; they do not redefine it. A worker that discovers a new field extends the shared definition in one commit, the same way the status lock works, so two reconstructions can never disagree on a layout. The companion struct DBs are intentionally partial (only the fields a verified leaf actually touches), which keeps layout claims honest. ## 3. Required gates and budgets ### 3a. Globals-first gate A function may not be marked `verified` until every global it reads, and every callee it depends on, is already reconstructed/verified. Reason: the differential emulates the original's globals, but a reconstruction that silently depends on an un-modelled constant table can pass by luck on the sampled inputs. Each row carries `globals_touched` and `callees`; check them before step 5: ```bash python3 - "0x000e4140" <<'PY' import json, sys rva = sys.argv[1] db = json.load(open("re/rvadb.json")) idx = {f["rva"]: f for f in db["functions"]} row = idx[rva] print("globals_touched:", row["globals_touched"]) unverified = [c for c in row["callees"] if idx[c]["status"] != "verified"] print("callees not yet verified:", unverified) # Gate: every read global must be a reconstructed/verified const table or an # owned struct field, and `unverified` must be empty, before status->verified. PY ``` For `0x000e4140` the gate is visible: it touches fifteen globals (the validity transform, box, tolerances, and candidate array) and calls `0x001ab6d0`. Those globals become the `ValidityState` struct and those callees are verified first; only then does the caller qualify. ### 3b. Per-wave compute / time budget and sharding for the Unicorn harness The differential is the expensive step: each case emulates real DLL code under Unicorn and spawns a `wine` process for the reconstruction. Budget it per wave: - Build `recon.exe` once per wave, not once per function (it statically links all reconstructed TUs). Rebuild only when a source file in the wave changes. - The harness is embarrassingly parallel across functions: shard `prove_t11.py`-style cases by function and run N shards concurrently, one per core. On a 16-core host, cap concurrent `wine` processes (each is a full process) at roughly the core count to avoid thrashing; `WINEDEBUG=-all` keeps per-call overhead down. - Rough cost model: emulation is dominated by `emu_start` instruction count (the gate case runs with `count=2_000_000`; box/elev are far cheaper). Order a wave cheap-functions-first so a shard that blows its time budget is one expensive function, not the whole batch. - Set a per-function wall-clock ceiling; a case that does not return cleanly (`emu did not return cleanly`) is a reconstruction or harness bug, not a slow run, and should fail fast rather than hang the wave. ### 3c. Evidence retention Commit the durable, reviewable evidence; never commit raw binaries or dumps. - Keep: the reconstruction source, the differential/golden proof scripts, the RVA DB status, the per-wave evidence logs under `.omo/evidence/gamekdm-decomp-linux/`, and committed golden I/O tuples. - Never commit: the original `gamekdm.dll` or companion DLLs, Ghidra projects (`*.rep`), built `*.dll` / `*.exe` / `*.a` / `*.o`, decompiled dumps, and the Python venv. `.gitignore` already enforces this (`orig/*`, `*.dll`, `*.exe`, `*.a`, `*.o`, `decompiled/`, `.venv/`, `.omo/`, `*.rep/`). - A reviewer reproduces, rather than trusts, the dumps: `docs/pipeline.md` rebuilds everything from a clean checkout plus the owner's legally-possessed originals. Evidence logs record what ran and the result, not the copyrighted bytes. ## Preserving the Track-B modding seam This project is "A leads to B": A is the faithful reconstruction, B is the modding toolkit (custom songs, mods) built on top of it. The reconstruction must stay moddable, so a cleanup decision that is behaviourally invisible to the differential can still be wrong if it welds shut a seam Track B needs. The rule: reconstruct mod-relevant functions as named, isolated, non-inlined units with stable signatures, so Track B can later hook or replace them. What to protect, concretely: - **Keep mod-relevant boundaries as distinct named functions.** Song registration, content/asset load, and chart/score parsing are the Track-B surface. Reconstruct each as its own named function with a stable signature (the same `// rva=...` pin and `GK_*` convention as any other), never folded into a wrapper. A stable boundary is hookable two ways: hot-patched through the T12 detour registry (`src/hybrid/detours.*`, for a `pod_only` leaf) or swapped at build time in a pure rebuild (`docs/pipeline.md`). - **Do not aggressively inline across module boundaries.** During the step 2 cleanup, resist merging a mod-relevant leaf into its caller even when the compiler would and the differential would still pass. An inlined song-load helper has no address and no symbol, so neither a detour nor a build-time replacement can reach it. Isolation here is a deliberate interface choice, not dead structure. (This is the one place the "no helper for a hypothetical need" instinct is overridden: the hook point is a real, planned need.) - **Flag the seam in the RVA DB.** When a function is on the song/content pipeline, record it as a Track-B seam in its claim entry so later workers and waves keep it isolated instead of optimizing it away. A note that marks the seam looks like: ```bash python3 - "0x000e4140" <<'PY' import json, sys rva = sys.argv[1] db = json.load(open("re/rvadb.json")) row = next(f for f in db["functions"] if f["rva"] == rva) row.setdefault("notes", []) note = "Track-B seam \u2014 keep isolated: song/content pipeline, must stay a" \ " named non-inlined hook point for the modding toolkit" if note not in row["notes"]: row["notes"].append(note) json.dump(db, open("re/rvadb.json", "w"), indent=1) print("flagged", rva, "as Track-B seam") PY ``` (Use the real song/content-pipeline rvas, not the validity example above, which is shown only for the mechanics.) The flag travels with the lock table, so a reviewer can audit that every seam function shipped as a reachable symbol, and a later deslop/refactor pass knows not to inline it. The gate: before marking a seam function `verified`, confirm it is still a distinct exported-or-addressable symbol (an entry the detour registry or a build-time swap can bind), not an inlined fragment. A mod-relevant function that verifies behaviourally but has been inlined out of existence fails this gate and must be re-split. ## 4. Grinding to 100% coverage across gamekdm + companions (IS-6b) Coverage is measured straight off the lock table: `verified / function_count` per program. Successive `ulw-execute` waves drive it to 100% like this: 1. **One program at a time, dependency order.** `gamekdm.dll` is the primary target; the in-scope companions reconstruct in the topological order fixed by `docs/companion-inventory.md` and driven into their own Ghidra projects by `tools/ghidra/import_companions.sh` (AVS2 base first: `libavs-win32`, then `-ea3`, `ess`, `libacio`, `arkkdm`, ...). Each program has its own RVA DB (`re/rvadb.json` for gamekdm, `re/avs/avs_rvadb.json` for libavs, and so on) and its own differential proof (`prove_t11.py`, `re/avs/prove_t14.py`), so a wave on one program never contends with a wave on another. 2. **Each wave is a sharded batch of the loop.** Pick the next tranche of `orig` functions (section 2.3), leaf-first within RTTI/namespace clusters, claim them as a batch, fan them out to workers, and run the loop in section 1 for each. The status lock keeps the fan-out collision-free; the globals-first gate (3a) keeps a wave from marking a caller before its dependencies. 3. **A wave is done when its batch is all `verified` and the DB validates.** Run `validate_rvadb.py`, the full `prove_t11.py`, and the golden harness; append the transcript to the wave's evidence log. Re-export with `export_rvadb.py` (prior statuses preserved) to pull in any functions Ghidra newly split, which re-enter the queue as `orig`. 4. **Repeat until `verified == function_count`** for the program, then advance to the next program in the dependency DAG. Hot-patchable (`pod_only`) leaves are registered as detours along the way (section 1, step 4); blocked functions ship as verified reconstructions for the full static rebuild (`docs/pipeline.md`). Full coverage across gamekdm and every IN-SCOPE companion is the IS-6b end state.