Owner confirmed the differing sizes/export counts/RVAs are just a different release of the same official game. Remove the "pending re-check against clean-release binary" / "contaminated install" caveats throughout and state those numbers (module sizes, export counts, gameMain RVA 0x9e20) as verified facts. Drop the stale 3,369,104-byte gamekdm figure in favor of the consistent 3.19 MB. Genuine format/behavior UNVERIFIED markers (undecoded .arc/.ifs/.ttc/etc. formats, Kinect dispatch/sync) are preserved.
294 lines
17 KiB
Markdown
294 lines
17 KiB
Markdown
# 09 - The kdm-re reconstruction codebase
|
|
|
|
This section documents the `kdm-re` repository itself: the layout, the no-sudo
|
|
cross-build, the verification harnesses, the three cutover build modes, and the
|
|
per-function loop that turns one shipping `FUN_<rva>` into a proven MinGW C++
|
|
reconstruction. It is the engineering counterpart to the subsystem analysis in
|
|
[./06-gamekdm-subsystems.md](./06-gamekdm-subsystems.md); the companion-DLL and
|
|
AVS detail it leans on lives in [./07-companion-dlls.md](./07-companion-dlls.md)
|
|
and [./08-libavs.md](./08-libavs.md).
|
|
|
|
Everything below is grounded in the tree at `/home/athapa/kdm-re` as it stands.
|
|
Scope note: the reconstruction is early. The canonical RVA database carries
|
|
`9728` function records and, at this writing, exactly one is `verified` and
|
|
`9727` are still `orig` (unclaimed), confirmed by reading `re/rvadb.json`
|
|
(`function_count` = 9728; status histogram `Counter({'orig': 9727,
|
|
'verified': 1})`). The three-function proven slice is tracked through a separate
|
|
evidence overlay (`re/pure-slice-status.json`), not the canonical statuses.
|
|
|
|
Release scope follows [the official inventory](../companion-inventory.md):
|
|
exactly nine Konami modules in `contents/modules/`.
|
|
|
|
## 1. Repository layout
|
|
|
|
Top level of the checkout (`ls` of `/home/athapa/kdm-re`):
|
|
|
|
| Path | Purpose |
|
|
| --- | --- |
|
|
| `CMakeLists.txt` | Build driver for all three modes (hybrid proxy, PURE full, PURE slice). |
|
|
| `activate.sh` | Sources Nix and puts the pinned i686 cross toolchain + wine on `PATH`. |
|
|
| `toolchain.lock` | Pins nixpkgs rev, GCC/mingw/wine versions, mcfgthread store path. |
|
|
| `cmake/` | `toolchain-mingw-i686.cmake` (cross toolchain file) and `check_pure_coverage.py` (the coverage gate). |
|
|
| `include/gk/` | Reconstructed-source headers: `types.h` (ABI macros), `manager.h`, `offsets_assert.h`, and `structs/` (`math.h`, `validity.h`, `skeleton.h`, `manager.h`). |
|
|
| `src/` | Reconstruction source, sharded by module: `entry/`, `game/`, `hybrid/`, `pure/`, plus still-empty module dirs (`gs/`, `mm/`, `movie/`, `particle/`, `platform/`, `render/`, `ui/`, `util/`). |
|
|
| `re/` | The RE data lock: `rvadb.json` (canonical function DB), `importlibs/` (companion `.def` + generated `.dll.a`), `avs/` (companion proofs), `pure-slice-status.json`. |
|
|
| `tools/` | `ghidra/` (DB export/validate), `unicorn_diff/` (differential harness), `gen_importlibs.sh`. |
|
|
| `tests/golden/` | Standalone golden-I/O replay harness and fixtures. |
|
|
| `docs/` | `pipeline.md`, `cutover.md`, `reconstruction-loop.md`, `conventions.md`, and this `spec/`. |
|
|
| `orig/`, `export/`, `bin/` | Gitignored originals drop zone, the hand-authored `gamekdm.def`, and the `activate.sh`-generated tool aliases. |
|
|
|
|
Source modules carry one reconstructed function per concern. The three that
|
|
actually compile today are `src/game/box_distance.cpp`
|
|
(`gk::game::BoxDistanceSquared`, rva `0x001ab6d0`), `src/game/validity.cpp`
|
|
(`UpdateValidityCandidates`, rva `0x000e4140`), and `src/game/nui_elevation.cpp`
|
|
(`UpdateCameraElevation`, rva `0x0000f510`), as named in
|
|
`docs/reconstruction-loop.md` and wired into `CMakeLists.txt:46-50`.
|
|
|
|
## 2. Build system
|
|
|
|
### No-sudo cross toolchain
|
|
|
|
The build targets a 32-bit Windows DLL and never touches system packages. Every
|
|
tool comes from a user-space Nix profile pinned in `toolchain.lock` (nixpkgs rev
|
|
`619c39f6eac5d1ed6b8f073a9414baf7034b2356`, GCC 16.2.0 / mingw-w64 14.0.0, wine
|
|
11.0, per `docs/pipeline.md` section 0). `activate.sh` sources
|
|
`~/.nix-profile/etc/profile.d/nix.sh`, prepends `~/.nix-profile/bin` plus a
|
|
worktree-local `bin/`, and symlinks the bare `dlltool`, `gendef`, and `objdump`
|
|
names onto their `i686-w64-mingw32-` prefixed binaries (`activate.sh:17-33`). It
|
|
must be sourced, not executed, and returns non-zero with recovery guidance when
|
|
a tool is missing (`activate.sh:5-8`) so a broken toolchain never looks clean.
|
|
|
|
### CMake toolchain file
|
|
|
|
`cmake/toolchain-mingw-i686.cmake` sets `CMAKE_SYSTEM_NAME Windows`,
|
|
`CMAKE_SYSTEM_PROCESSOR x86`, and the `i686-w64-mingw32-` compiler/windres/
|
|
dlltool prefix (lines 15-24). The decisive choice is static linking: the
|
|
original `gamekdm.dll` was built by MSVC with a statically linked CRT and
|
|
imports zero C/C++ runtime DLLs, so the rebuild must match that import shape or
|
|
it is not a drop-in replacement. The file seeds
|
|
`CMAKE_{EXE,SHARED,MODULE}_LINKER_FLAGS_INIT` with
|
|
`-static-libgcc -static-libstdc++ -static` and a `-L` onto the pinned
|
|
`mcfgthread` lib dir (toolchain file final three `set()` lines). Plain `-static`
|
|
forces even `-lmcfgthread`, pulled in by GCC 16.2.0's default link spec, to
|
|
resolve against its `.a` instead of its import library, so no
|
|
`libgcc_s_dw2-1.dll` / `libstdc++-6.dll` / `libmcfgthread-*.dll` import leaks in.
|
|
|
|
### The default hybrid build
|
|
|
|
With no options, `CMakeLists.txt` builds `gamekdm` as a SHARED library from the
|
|
single TU `src/entry/gamemain.cpp` (`CMakeLists.txt:88`), links the hand-written
|
|
`export/gamekdm.def` so only `gameMain` is exported at ordinal 1
|
|
(`CMakeLists.txt:100-106`), and also builds the T12 detour static library
|
|
`gamekdm_detours` (from `src/hybrid/detours.cpp` + `src/game/box_distance.cpp`)
|
|
and its `gamekdm_detour_test` host. The detour TU compiles with
|
|
`-mfpmath=387 -ffp-contract=off -fno-fast-math -fno-exceptions -fno-rtti`
|
|
(`CMakeLists.txt:120-121`) to match the original's float model. Build and
|
|
confirm the export table with:
|
|
|
|
```bash
|
|
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=cmake/toolchain-mingw-i686.cmake
|
|
cmake --build build
|
|
i686-w64-mingw32-objdump -p build/gamekdm.dll | grep -A6 'Export Address Table'
|
|
```
|
|
|
|
Output is `build/gamekdm.dll`, a PE32 (i386) DLL (`docs/pipeline.md` section 4).
|
|
|
|
### Companion import libraries
|
|
|
|
The reconstruction links against MinGW import libs derived from the game's own
|
|
shipped modules, plus the external Kinect10.dll NUI runtime gamekdm imports.
|
|
`tools/gen_importlibs.sh` runs `gendef` then `i686-w64-mingw32-dlltool` for the
|
|
seven shipped modules in its current map (`libavs-win32`, `libavs-win32-ea3`,
|
|
`libafp-win32`, `libafputils-win32`, `ess`, `arkkdm`, `libacio`) plus the
|
|
external `Kinect10` dependency, and writes `re/importlibs/lib<name>.dll.a`.
|
|
The two stdcall entries, `arkkdm` and the external `Kinect10`, get `--kill-at`;
|
|
the cdecl shipped modules do not, because their names have no `@N` decoration
|
|
to strip (`tools/gen_importlibs.sh` header comment
|
|
and `CONV` table). The `.def` files are committed; the `.dll.a` archives are
|
|
gitignored and regenerated.
|
|
|
|
The current script expects all inputs in one directory. That assumption does
|
|
not match the clean release: Konami modules reside in `contents/modules/`,
|
|
while Microsoft supplies the external NUI runtime separately.
|
|
|
|
### PURE build modes and the coverage gate
|
|
|
|
Two options switch the build away from the hybrid proxy
|
|
(`CMakeLists.txt:4-5`):
|
|
|
|
- `BUILD_PURE=ON` excludes the proxy and detour targets entirely and never links
|
|
an original DLL or its import libs.
|
|
- `PURE_SLICE=ON` (only meaningful with `BUILD_PURE`) builds the three-function
|
|
verified slice plus explicit remainder stubs.
|
|
|
|
Both run `cmake/check_pure_coverage.py` against `re/rvadb.json` at configure time
|
|
and as an `ALL` custom target before each build (`CMakeLists.txt:17-42`). The
|
|
gate is fail-closed:
|
|
|
|
- **Full mode** treats every recorded function as a root, traverses the `callees`
|
|
graph, and fails unless the whole DB is `status=verified` (`verified ==
|
|
len(records)`, no rounding). Today that is `1/9728`, so full mode fails with
|
|
`not yet at coverage` by design (`check_pure_coverage.py`, `main()` final
|
|
check). Even once metadata hits 100%, `CMakeLists.txt:45-48` still aborts full
|
|
mode with a `FATAL_ERROR`, because the complete reconstructed source graph and
|
|
entry point are not integrated. That refusal is deliberate and must not be
|
|
swapped for the proxy.
|
|
- **Slice mode** roots only `0x0000f510`, `0x000e4140`, `0x001ab6d0`
|
|
(`SLICE_ROOTS` in `check_pure_coverage.py`), accepts the three
|
|
`status=verified` claims from the evidence overlay `re/pure-slice-status.json`,
|
|
and skips three substitution RVAs during traversal: the two clamp helpers
|
|
`0x001ab5b0` / `0x001ab640` (reconstructed inline) and `0x001db674` (the MSVC
|
|
security cookie supplied by the new toolchain), per `SLICE_SUBSTITUTIONS`.
|
|
These substitutions never apply to the full gate.
|
|
|
|
`PURE_REQUIRE_RVA` adds extra mandatory roots but cannot relax coverage; passing
|
|
`-DPURE_REQUIRE_RVA=0x00009e20` forces a `not yet at coverage` failure naming
|
|
`gameMain`, which is how `docs/cutover.md` proves a new internal dependency can't
|
|
silently enter the slice.
|
|
|
|
## 3. The proxy, the detour carve-out, and the pure slice
|
|
|
|
**Proxy (`src/entry/gamemain.cpp`).** The Phase-0 export is a forwarding proxy.
|
|
`gameMain` only `LoadLibraryA("gamekdm_orig.dll")` at call time, resolves the
|
|
original `gameMain` by name then ordinal 1, forwards `hInstance`, and returns the
|
|
original's result (`src/entry/gamemain.cpp:37-73`). It is declared `GK_CDECL`
|
|
with a single pointer arg, matched from the original's bare `ret`
|
|
(`gamemain.cpp:17-19`). Only KERNEL32 and msvcrt symbols are touched, giving
|
|
the rebuilt proxy/slice DLL a clean KERNEL32+msvcrt import table — this is the
|
|
reconstruction's own minimal-proxy shape, not a match to the original's import
|
|
table. The original `gamekdm.dll` imports its shipped Konami middleware
|
|
(`libavs-win32.dll`, `libafp-win32.dll`, `libafputils-win32.dll`), the
|
|
external Microsoft NUI runtime (`Kinect10.dll`), Direct3D
|
|
(`d3d9.dll`, `d3dx9_43.dll`), and a conventional Win32 OS set (`KERNEL32.dll`,
|
|
`USER32.dll`, `GDI32.dll`, `ADVAPI32.dll`, `SHELL32.dll`, `ole32.dll`,
|
|
`WS2_32.dll`, `WINMM.dll`, `IMM32.dll`, `DINPUT8.dll`) — not msvcrt, since its
|
|
statically linked CRT imports zero C/C++ runtime DLLs. Because the original is
|
|
resolved lazily, the rebuilt DLL loads on its own as a valid smoke test with no
|
|
original present (`docs/pipeline.md` section 5c).
|
|
|
|
**Detour carve-out (`src/hybrid/`).** The T12 installer hot-patches a
|
|
reconstruction into the loaded original image, but only for an immutable
|
|
allowlist. `src/hybrid/detours.h` hardcodes three `Entry` rows with an
|
|
`Ownership` verdict each: `BoxDistanceSquared` (`0x1ab6d0`) is `pod_only`
|
|
(allowed), `UpdateValidityCandidates` (`0x0e4140`) is `shared_mutable_globals`
|
|
(blocked), and `UpdateCameraElevation` (`0x00f510`) is `foreign_object_abi`
|
|
(blocked). `set_enabled` returns `ownership_blocked` for anything but
|
|
`pod_only`, and unknown RVAs can't be hooked at all. The handwritten x86
|
|
trampoline supports only `0x1ab6d0`: its first six bytes are three whole
|
|
instructions with no relative operands, checked before patching, copied to an
|
|
executable trampoline, then followed by a jump back; an ABI adapter maps the
|
|
original EAX/EDI args to the cdecl POD reconstruction and returns ST0
|
|
(`src/hybrid/README.md`). Original data is addressed in its owning image via
|
|
`at_rva` (`slide = base - 0x10000000`), never copied into the CRT. The tested
|
|
input DLL SHA-256 is pinned in the README as
|
|
`0595cb1dd98e4c02e2700f22f29d6504a9a74b401238ba5ec539d666ee8f0804`.
|
|
|
|
**Pure slice (`src/pure/`).** `src/pure/slice.cpp` exports a slice-only
|
|
`gameMain` that is an explicit unsupported stub returning `-17`, plus a
|
|
`pure_slice_self_test` that drives all three reconstructed routines against known
|
|
inputs and returns 0 on success. The camera interface terminates at a `MockSensor`
|
|
implementing `ICameraElevation` (`GetAngle` returns 7, `SetAngle` records the
|
|
applied value), never a Kinect or original binary. `src/pure/mock_host.cpp`
|
|
`LoadLibraryA`s the slice DLL, asserts `pure_slice_self_test() == 0` and
|
|
`gameMain(nullptr) == -17`, and prints `PURE_SLICE_LOAD_PASS`. The slice DLL is
|
|
named `gamekdm_pure_slice.dll`, deliberately different from the shipping name.
|
|
|
|
## 4. Verification system
|
|
|
|
Three independent gates, all reproducible on Linux with no network and no game
|
|
binary beyond the owner's legally-possessed originals.
|
|
|
|
### Unicorn per-function differential (`tools/unicorn_diff/`)
|
|
|
|
This is the universal gate. For each reconstructed function it emulates the real
|
|
routine inside the shipping `gamekdm.dll` under Unicorn (original-as-oracle) and
|
|
runs the compiled C++ reconstruction under wine on the same inputs, then asserts
|
|
behavioural equality; it also injects a known bug to prove the comparison can
|
|
fail (non-vacuity). The oracle binary path is pinned in
|
|
`tools/unicorn_diff/prove_t11.py` (`DLL = Path("/home/athapa/ghidra/gamekdm.dll")`).
|
|
The `udiff` package carries the pieces: `runner.py` (Unicorn register/stack
|
|
setup, `CallSpec`/`ReturnKind` from `abi.py`), `image.py` (PE mapping and scratch
|
|
layout), `result.py` (global deltas), and `metadata.py` (calling convention from
|
|
the DB).
|
|
|
|
Float fidelity is where this harness earns its keep. `udiff/fp.py`'s
|
|
`capture_st0` reads the physical x87 register `FP[TOP]` including the exponent,
|
|
because `UC_X86_REG_ST0` omits it, and raises if a float return is declared but
|
|
`ST(0)` is empty. `detect_fp` classifies a bounded disassembly into x87 vs SSE
|
|
scalar sites and derives the exact compiler flags (`-mfpmath=387` for x87,
|
|
`-mfpmath=sse -msse2` for SSE, always `-ffp-contract=off -fno-fast-math`), and
|
|
refuses to guess on a mixed function. Those are the same flags the harness build
|
|
command uses (`docs/pipeline.md` section 5a). Expect `ALL DIFFERENTIALS PASS`,
|
|
exit 0.
|
|
|
|
### Golden I/O harness (`tests/golden/`)
|
|
|
|
A stdlib-only supplement (T9) that replays committed `(input -> expected-output)`
|
|
tuples recorded from existing introspection dumps against an independent
|
|
reconstruction, within a float tolerance, with no binary, wine, or network
|
|
(`tests/golden/README.md`). It covers three subsystems with committed fixtures
|
|
(`depth_projection.json`, `validity_gate.json`, `pose_ref.json` + `ref.txt`).
|
|
Non-vacuity is built in: `--perturb FIELD` nudges one constant so the assertions
|
|
fail on purpose, and `run.sh` reports `VACUITY VIOLATION` if any perturbed run
|
|
still passes. Expect `GOLDEN HARNESS OK: clean run passed and every perturbation
|
|
failed.`, exit 0.
|
|
|
|
### Wine load-smoke
|
|
|
|
A tiny `LoadLibraryA` loader built under the cross toolchain confirms the rebuilt
|
|
`gamekdm.dll` loads under wine and still exports `gameMain`
|
|
(`docs/pipeline.md` section 5c). Because the proxy resolves the original lazily,
|
|
this needs no original present.
|
|
|
|
## 5. The per-function reconstruction loop
|
|
|
|
`docs/reconstruction-loop.md` is the repeatable procedure for turning one
|
|
`FUN_<rva>` into a verified reconstruction. The status field in `re/rvadb.json`
|
|
is both the progress marker and the inter-worker lock, with four values enforced
|
|
by `tools/ghidra/validate_rvadb.py`: `orig` (unclaimed), `reimpl` (owned, in
|
|
progress), `stub`, and `verified` (terminal).
|
|
|
|
1. **Claim (`orig -> reimpl`).** Flip the status and commit the DB alone before
|
|
working, so the lock is visible on the next pull. One RVA, one owner.
|
|
2. **Decompile** the claimed function headless from the already-analyzed Ghidra
|
|
project (`gkproj` for `gamekdm.dll`, per-companion projects otherwise) with
|
|
`-noanalysis -readOnly`, and read the raw disasm for calling convention, FP
|
|
model, and struct field accesses.
|
|
3. **Clean to MinGW C++** in the right `src/` module per `docs/conventions.md`:
|
|
pin the origin (`// rva=...`), state the convention with `GK_CDECL` /
|
|
`GK_STDCALL` / `GK_THISCALL` from `include/gk/types.h`, match MSVC struct
|
|
layout (natural alignment or `GK_PACK_PUSH/POP`), and match the FP model.
|
|
4. **Verify** with the Unicorn differential (and the golden harness where a
|
|
fixture exists), adding the function's `CallSpec` to the proof.
|
|
5. **Register the detour** only if the function is a POD-in/POD-out stateless
|
|
leaf (the `pod_only` ownership rule); blocked functions are still
|
|
reconstructed and verified, just not hot-patched.
|
|
6. **Mark verified (`reimpl -> verified`)** once the differential passes, then
|
|
re-run `validate_rvadb.py` before committing.
|
|
|
|
Two standing gates sit over the loop. The **globals-first gate** forbids marking
|
|
a function `verified` until every global it reads and every callee it depends on
|
|
is already verified (each row carries `globals_touched` and `callees`). The
|
|
**Track-B modding seam** rule keeps song/content/chart boundaries as named,
|
|
non-inlined functions with stable signatures so the later modding toolkit can
|
|
hook or replace them, overriding the usual "no helper for a hypothetical need"
|
|
instinct for those planned hook points. Parallel workers shard by RTTI/namespace
|
|
cluster and coordinate shared struct layouts through single-owner headers in
|
|
`include/gk/structs`.
|
|
|
|
## 6. Cutover status
|
|
|
|
`docs/cutover.md` is explicit that the build mechanism exists but the game
|
|
cutover does not. The three T11 routines have differential evidence; the rest of
|
|
`re/rvadb.json` is nowhere near 100% verified coverage, and a slice smoke test
|
|
cannot authorize deployment. Full cabinet/original-binary runtime QA, on an isolated install with
|
|
a known-good hybrid kept for rollback, is the gated final milestone, and any
|
|
failing item, unresolved indirect target, stub, or original-binary dependency
|
|
keeps cutover incomplete. The pure build must never silently load an original DLL
|
|
as a fallback.
|
|
|
|
See also [./06-gamekdm-subsystems.md](./06-gamekdm-subsystems.md) for what these
|
|
reconstructed functions actually do inside the game, and
|
|
[./07-companion-dlls.md](./07-companion-dlls.md) for the companion DLLs whose
|
|
import libraries `gen_importlibs.sh` produces.
|