diff --git a/CMakeLists.txt b/CMakeLists.txt index 0e9087c..d337923 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,15 +1,80 @@ cmake_minimum_required(VERSION 3.16) project(gamekdm LANGUAGES C CXX) +option(BUILD_PURE "Build without linking or loading the original binary" OFF) +option(PURE_SLICE "Build the verified T11 slice with explicit remainder stubs" OFF) +set(PURE_REQUIRE_RVA "" CACHE STRING + "Additional semicolon-separated RVAs that the PURE coverage gate must verify") + # 32-bit Windows DLL, built with the pinned i686-w64-mingw32 cross toolchain # (see cmake/toolchain-mingw-i686.cmake, toolchain.lock). The real shipping # gamekdm.dll's reconstructed source lands in src/* over subsequent tasks; # today's target is a minimal stub so the layered tree + build + export # table shape is proven before any real logic is reconstructed. -add_library(gamekdm SHARED - src/entry/gamemain.cpp -) +if(BUILD_PURE) + find_package(Python3 REQUIRED COMPONENTS Interpreter) + set(_pure_gate_args + "${CMAKE_SOURCE_DIR}/cmake/check_pure_coverage.py" + "${CMAKE_SOURCE_DIR}/re/rvadb.json" + ) + if(PURE_SLICE) + list(APPEND _pure_gate_args + --mode slice + --slice-status "${CMAKE_SOURCE_DIR}/re/pure-slice-status.json" + ) + else() + list(APPEND _pure_gate_args --mode full) + endif() + foreach(_pure_rva IN LISTS PURE_REQUIRE_RVA) + list(APPEND _pure_gate_args --require-rva "${_pure_rva}") + endforeach() + execute_process( + COMMAND "${Python3_EXECUTABLE}" ${_pure_gate_args} + RESULT_VARIABLE _pure_gate_result + ) + if(NOT _pure_gate_result EQUAL 0) + message(FATAL_ERROR "PURE coverage/reachability gate failed") + endif() + add_custom_target(pure_coverage_gate ALL + COMMAND "${Python3_EXECUTABLE}" ${_pure_gate_args} + VERBATIM + ) + + if(NOT PURE_SLICE) + message(FATAL_ERROR + "PURE coverage passed, but the complete reconstructed source graph " + "and entry point are not integrated yet") + endif() + + add_library(gamekdm_pure_slice SHARED + src/pure/slice.cpp + src/game/box_distance.cpp + src/game/validity.cpp + src/game/nui_elevation.cpp + ) + add_dependencies(gamekdm_pure_slice pure_coverage_gate) + target_include_directories(gamekdm_pure_slice PRIVATE + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/src + ) + target_compile_features(gamekdm_pure_slice PRIVATE cxx_std_17) + target_compile_options(gamekdm_pure_slice PRIVATE + -Wall -Wextra -Werror -mfpmath=387 -ffp-contract=off -fno-fast-math + ) + set_target_properties(gamekdm_pure_slice PROPERTIES + OUTPUT_NAME "gamekdm_pure_slice" + PREFIX "" + SUFFIX ".dll" + ) + + add_executable(gamekdm_pure_host src/pure/mock_host.cpp) + add_dependencies(gamekdm_pure_host gamekdm_pure_slice) + target_compile_options(gamekdm_pure_host PRIVATE -Wall -Wextra -Werror) + return() +endif() + +add_library(gamekdm SHARED src/entry/gamemain.cpp) target_include_directories(gamekdm PRIVATE ${CMAKE_SOURCE_DIR}/include diff --git a/cmake/check_pure_coverage.py b/cmake/check_pure_coverage.py new file mode 100644 index 0000000..a9d5977 --- /dev/null +++ b/cmake/check_pure_coverage.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Fail a PURE build unless every selected reachable RVA is verified.""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Final, TypedDict + + +class FunctionRecord(TypedDict): + rva: str + name: str + status: str + callees: list[str] + + +SLICE_ROOTS: Final = ("0x0000f510", "0x000e4140", "0x001ab6d0") +SLICE_SUBSTITUTIONS: Final = { + "0x001ab5b0", # clamp helper reconstructed inline + "0x001ab640", # clamp helper reconstructed inline + "0x001db674", # MSVC security cookie supplied by the new toolchain +} + + +def fail(detail: str) -> None: + """Report a closed coverage gate with a stable diagnostic.""" + print(f"PURE gate: not yet at coverage: {detail}", file=sys.stderr) + raise SystemExit(1) + + +def main() -> None: + """Parse the RVA graph and enforce the selected PURE-build policy.""" + parser = argparse.ArgumentParser() + parser.add_argument("database", type=Path) + parser.add_argument("--mode", choices=("full", "slice"), required=True) + parser.add_argument("--slice-status", type=Path) + parser.add_argument("--require-rva", action="append", default=[]) + args = parser.parse_args() + + try: + raw = json.loads(args.database.read_text(encoding="utf-8")) + records: list[FunctionRecord] = raw["functions"] + except (OSError, json.JSONDecodeError, KeyError, TypeError) as error: + fail(f"cannot parse {args.database}: {error}") + + by_rva: dict[str, FunctionRecord] = {} + for record in records: + rva = record["rva"].lower() + if rva in by_rva: + fail(f"duplicate function RVA {rva}") + by_rva[rva] = record + + slice_verified: set[str] = set() + if args.mode == "slice": + if args.slice_status is None: + fail("slice verification status file was not supplied") + try: + claims = json.loads( + args.slice_status.read_text(encoding="utf-8") + )["functions"] + slice_verified = { + claim["rva"].lower() + for claim in claims + if claim["status"] == "verified" + } + except (OSError, json.JSONDecodeError, KeyError, TypeError) as error: + fail(f"cannot parse {args.slice_status}: {error}") + + roots = list(by_rva) if args.mode == "full" else list(SLICE_ROOTS) + roots.extend(rva.lower() for rva in args.require_rva) + pending = roots + visited: set[str] = set() + while pending: + rva = pending.pop() + if rva in visited: + continue + visited.add(rva) + record = by_rva.get(rva) + if record is None: + fail(f"reachable RVA {rva} is missing from the database") + verified_here = record["status"] == "verified" or rva in slice_verified + if not verified_here: + fail(f"{rva} {record['name']} has status={record['status']}") + for callee in record["callees"]: + callee_rva = callee.lower() + if args.mode == "slice" and callee_rva in SLICE_SUBSTITUTIONS: + continue + pending.append(callee_rva) + + verified = sum(record["status"] == "verified" for record in records) + if args.mode == "full" and verified != len(records): + fail(f"verified coverage is {verified}/{len(records)}, expected 100%") + print( + f"PURE gate: PASS mode={args.mode} " + f"verified={verified}/{len(records)} reachable={len(visited)}" + ) + + +if __name__ == "__main__": + main() diff --git a/docs/cutover.md b/docs/cutover.md new file mode 100644 index 0000000..22c31ef --- /dev/null +++ b/docs/cutover.md @@ -0,0 +1,120 @@ +# PURE build cutover procedure + +T17 establishes a build mechanism, not a completed game cutover. The three +T11 routines have differential evidence in `task-11.log`; the rest of +`re/rvadb.json` is not at 100% verified coverage. Windows full-game QA is +still required. A slice smoke test cannot authorize deployment. + +## Build modes + +The default build remains the hybrid proxy plus detour installer. +`BUILD_PURE=ON` excludes both targets and their source files. It never links +an original game DLL or its import libraries. + +The full mode requires every function in the target DLL's RVA database to +have `status=verified` (verified / function_count = 100%, no rounding). +Missing, duplicate, unknown, `orig`, `stub`, or `reimpl` records fail closed. +The gate also traverses callees and rejects missing or unverified reachable +functions. Full mode conservatively treats **every recorded function as a +root**, covering exports, callbacks, constructors, TLS and DLL entry points, +and possible indirect targets already present in the database. + +Ghidra's graph contains only resolved edges. Before full cutover, audit +indirect calls, vtables, callbacks, dynamic lookups, imports, entry points, +and assembly against the final source/link map. Add missing targets to the +database and repeat the gate; 100% of an incomplete inventory is insufficient. +Companion DLLs require their own complete inventories and equivalent checks. +System APIs may remain imports; no original game or companion implementation +may be linked or dynamically loaded, including through transitive imports. + +```sh +source ~/.nix-profile/etc/profile.d/nix.sh +source ./activate.sh +cmake -S . -B build-pure-full \ + -DCMAKE_TOOLCHAIN_FILE=cmake/toolchain-mingw-i686.cmake \ + -DBUILD_PURE=ON +``` + +This must currently fail with `not yet at coverage`. Even after metadata +reaches 100%, the scaffold refuses a full artifact until the reconstructed +entry point and complete source graph are integrated. Do not replace that +refusal with the proxy or with slice stubs. + +## Slice mechanism validation + +```sh +cmake -S . -B build-pure \ + -DCMAKE_TOOLCHAIN_FILE=cmake/toolchain-mingw-i686.cmake \ + -DBUILD_PURE=ON -DPURE_SLICE=ON +cmake --build build-pure +(cd build-pure && WINEDEBUG=-all wine gamekdm_pure_host.exe) +``` + +`gamekdm_pure_slice.dll` is deliberately named differently from the shipping +DLL. Its small C interface exposes the three reconstructed routines to a +mock host compiled with the same toolchain. `gameMain` is an explicit +unsupported stub returning -17; camera get/set are supplied by the host's +mock sensor. All remaining game subsystems are outside this mini-build. +No generic fake implementations of thousands of unknown signatures are +generated, and no stub is counted as verified. + +The slice gate requires the three `status=verified` claims in +`re/pure-slice-status.json`, reconciles their RVAs against `re/rvadb.json`, +and traverses the canonical database's reconstructed dependency graph. +This temporary evidence overlay is accepted only by slice mode; full mode +uses only canonical `re/rvadb.json` statuses. The only original edges omitted in slice +mode are the two clamp helpers now implemented inline in `box_distance.cpp`, +and MSVC's security-cookie helper replaced by the compiler runtime. These +edge substitutions never apply to the full gate. Camera virtual dispatch +ends at the explicit host mock, not a Kinect/original binary. + +To prove that a new internal dependency cannot silently enter the slice: + +```sh +cmake -S . -B build-pure-reject \ + -DCMAKE_TOOLCHAIN_FILE=cmake/toolchain-mingw-i686.cmake \ + -DBUILD_PURE=ON -DPURE_SLICE=ON -DPURE_REQUIRE_RVA=0x00009e20 +``` + +Expect a nonzero configure exit and `not yet at coverage` naming gameMain. +The gate runs at configuration and before each build, so a subsequent +status downgrade also blocks rebuilding. `PURE_REQUIRE_RVA` adds roots; +it cannot replace the mandatory roots or relax coverage. + +Inspect the final PE imports and linker inputs, then run the mock host in +a directory without original DLLs. T17 evidence lives in +`/home/athapa/kdm-re/.omo/evidence/gamekdm-decomp-linux/task-17.log`. + +## Final Windows / spice2x full-game QA + +Only begin this checklist with a complete, stub-free build and the full +coverage/reachability and dependency audits passed. Preserve a separate +known-good hybrid installation for rollback. Record build/source hashes, +rvadb hash, Windows version, spice2x version/configuration, Kinect driver, +GPU/driver, input mappings, logs, and screenshots with each result. + +- [ ] Stage the complete pure build in an isolated game directory; remove + original game/companion DLLs from its loader search paths. Confirm + PE32 ABI, gameMain name/ordinal/calling convention and required exports. +- [ ] Launch with the user's normal spice2x configuration. Inspect loaded + modules and dynamic-load traces: no original binary or proxy/detour. + Boot, asset loading, attract mode and title/menu navigation succeed. +- [ ] Check service/test menu, calibration, coin/start, cabinet buttons, + card/profile/save behavior and supported offline/network modes. +- [ ] Exercise Kinect startup, tracking acquisition/loss/reacquisition, + both players, validity boundaries, cursor selection, camera elevation, + reconnect and device-error recovery on the real hardware. +- [ ] Play complete songs in each supported mode/difficulty and multiplayer; + compare timing, scoring, combo, animations, audio/video sync and results + with the recorded hybrid baseline. Check pause/exit/retry transitions. +- [ ] Verify configuration/profile persistence after shutdown and restart; + exercise missing assets, cancelled loads and supported error paths. +- [ ] Run repeated sessions and a sustained play/attract soak; inspect frame + pacing, memory/handles, crash logs, shutdown and restart behavior. +- [ ] Confirm all differential/golden checks still pass. Attach QA evidence + and owner acceptance. Keep cutover incomplete for any failing item, + unresolved indirect target, stub, or original-binary dependency. + +Promote the isolated installation only after all gates and checklist items +pass. Roll back by restoring the separate known-good installation; never +silently load an original DLL as a fallback inside the pure build. diff --git a/re/pure-slice-status.json b/re/pure-slice-status.json new file mode 100644 index 0000000..e89d7a4 --- /dev/null +++ b/re/pure-slice-status.json @@ -0,0 +1,8 @@ +{ + "evidence": "/home/athapa/kdm-re/.omo/evidence/gamekdm-decomp-linux/task-11.log", + "functions": [ + {"rva": "0x0000f510", "status": "verified"}, + {"rva": "0x000e4140", "status": "verified"}, + {"rva": "0x001ab6d0", "status": "verified"} + ] +} diff --git a/src/pure/mock_host.cpp b/src/pure/mock_host.cpp new file mode 100644 index 0000000..b5318f2 --- /dev/null +++ b/src/pure/mock_host.cpp @@ -0,0 +1,37 @@ +#include + +#include +#include + +int main() { + HMODULE module = LoadLibraryA("gamekdm_pure_slice.dll"); + if (module == nullptr) { + std::fprintf(stderr, "PURE_LOAD_FAIL error=%lu\n", + static_cast(GetLastError())); + return 1; + } + using SelfTest = int (*)(); + using GameMain = int (*)(void*); + const FARPROC self_address = GetProcAddress(module, "pure_slice_self_test"); + const FARPROC main_address = GetProcAddress(module, "gameMain"); + if (self_address == nullptr || main_address == nullptr) { + std::fprintf(stderr, "PURE_EXPORT_FAIL\n"); + return 2; + } + SelfTest self_test; + GameMain game_main; + static_assert(sizeof(self_test) == sizeof(self_address)); + static_assert(sizeof(game_main) == sizeof(main_address)); + std::memcpy(&self_test, &self_address, sizeof(self_test)); + std::memcpy(&game_main, &main_address, sizeof(game_main)); + const int self_result = self_test(); + const int stub_result = game_main(nullptr); + FreeLibrary(module); + if (self_result != 0 || stub_result != -17) { + std::fprintf(stderr, "PURE_SELF_TEST_FAIL self=%d stub=%d\n", + self_result, stub_result); + return 3; + } + std::puts("PURE_SLICE_LOAD_PASS"); + return 0; +} diff --git a/src/pure/slice.cpp b/src/pure/slice.cpp new file mode 100644 index 0000000..f6a0e4e --- /dev/null +++ b/src/pure/slice.cpp @@ -0,0 +1,60 @@ +#include +#include + +#include "game/nui_elevation.h" +#include "game/validity.h" + +namespace { + +class MockSensor final : public gk::game::ICameraElevation { + public: + std::int32_t GK_STDCALL GetAngle(std::int32_t* out_degrees) override { + *out_degrees = 7; + return 0; + } + + std::int32_t GK_STDCALL SetAngle(std::int32_t degrees) override { + applied = degrees; + return 0; + } + + std::int32_t applied = 0; +}; + +} // namespace + +extern "C" __declspec(dllexport) int gameMain(void*) { + // Explicit slice-only stub. A full PURE build must replace this entry point. + return -17; +} + +extern "C" __declspec(dllexport) int pure_slice_self_test() { + const gk::ValidityBox box{{1.0F, 2.0F, 3.0F}, {2.0F, 3.0F, 4.0F}}; + if (gk::game::BoxDistanceSquared(box, {6.0F, 9.0F, 7.0F}) != 25.0F) { + return 1; + } + + gk::LiveManager manager{}; + manager.synthetic_tracking_mode = 1; + gk::game::ValidityState state{}; + state.transform = {1, 0, 0, 0, 0, 1, 0, 0, + 0, 0, 1, 0, 0, 0, 0, 1}; + state.box = box; + state.missing_position = {-999.0F, -999.0F, -999.0F}; + state.entry_tolerance = 0.0F; + state.retained_tolerance = 0.0F; + gk::game::UpdateValidityCandidates(manager, state); + if (state.candidates[0].valid != 0) { + return 2; + } + + MockSensor sensor; + gk::game::ElevationThread thread{10, -5, 0, + gk::game::kAccumulatorSentinel, &sensor}; + gk::game::UpdateCameraElevation(thread); + if (thread.smoothed_angle != 7 || thread.applied_angle != 10 || + sensor.applied != 10) { + return 3; + } + return 0; +}