Files
kdm-re/docs/spec/08-abi-conventions.md
ulw-execute 3910630c25 docs: mark release-difference facts verified; fix doc inconsistencies
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.
2026-11-28 21:01:37 -05:00

247 lines
12 KiB
Markdown

# 08 - ABI, Calling Conventions, and Struct Layouts
This section pins the binary-level contract the reconstruction has to honor: the
compiler and ABI the original `gamekdm.dll` was built with, the calling
convention at every module boundary, and the struct layouts recovered from the
image. Everything here is grounded in the reconstruction's own convention docs
(`docs/conventions.md`, `docs/companion-conventions.md`) and the reconstructed
headers under `include/gk/`, with offsets pinned by the `static_assert` set in
`include/gk/offsets_assert.h`.
Related sections: [06 - gamekdm subsystems](./06-gamekdm-subsystems.md),
[07 - companion DLLs](./07-companion-dlls.md).
## Compiler and image facts
The original binary is a 32-bit (x86) Windows DLL built with MSVC (`cl.exe`),
the VS2010 SP1 x86 toolchain, linked against the static CRT (`/MT`). The default
free-function convention is `__cdecl`, while many internal entry points and
vtables use `__stdcall` or `__thiscall`
(`include/gk/types.h:4-8`). The image base is `0x10000000`, which is why Ghidra
RVAs read like `0x10023af0` and the RVA database (`re/rvadb.json`, 9728
functions) stores each function's address relative to that base
(`docs/conventions.md`, "Function naming").
The official module topology is the nine shipped modules in
`contents/modules/`; `Kinect10.dll` is an external Microsoft NUI runtime
dependency of `gamekdm.dll`, not a companion module.
The floating-point model is x87 with 80-bit intermediates, matching VS2010 SP1
x86's default. It is detected, not assumed: x87 opcodes (`fld`, `fmul`, `fstp`,
`fadd`, ...) in the validity-gate disasm mean x87 and a `-mfpmath=387` build;
SSE scalar opcodes (`movss`, `mulss`, `addss`, `cvtsi2ss`, ...) mean SSE and a
`-mfpmath=sse -msse2` build. The default is `-mfpmath=387` unless the disasm
shows SSE, and every FP build adds `-ffp-contract=off -fno-fast-math` so the
compiler never fuses or reorders FP ops away from the original's rounding
(`docs/conventions.md`, "Floating point model").
MinGW/GCC on i686 is ABI-compatible with these MSVC calling conventions, so the
reconstruction names the convention explicitly at each declaration rather than
copying bytes (`include/gk/types.h:5-11`).
## Calling-convention macros
`include/gk/types.h` defines three convention macros. Under GCC they expand to
the matching `__attribute__`, under MSVC to the keyword, and any other compiler
is a hard `#error` (`include/gk/types.h:15-25`):
| Macro | GCC expansion | MSVC expansion | Cleanup / `this` |
|---|---|---|---|
| `GK_CDECL` | `__attribute__((cdecl))` | `__cdecl` | caller-cleaned |
| `GK_STDCALL` | `__attribute__((stdcall))` | `__stdcall` | callee-cleaned |
| `GK_THISCALL` | `__attribute__((thiscall))` | `__thiscall` | `this` in `ecx`, callee-cleaned |
Apply them by origin (`docs/conventions.md`, "Calling convention macros"):
- `GK_CDECL`: caller-cleaned C convention. Used for avs and afp interop (the
game's `avs2` / `avfs` imports and callbacks) and anything the original
declared `__cdecl`, which is MSVC's default for free functions.
- `GK_STDCALL`: callee-cleaned stdcall. Used for the Win32-style boundaries:
Kinect10 (`Kinect10.dll`) and Direct3D 9 (`d3d9.dll`) entry points and any
`WINAPI`/`CALLBACK` path.
- `GK_THISCALL`: MSVC thiscall. Used for internal non-virtual member functions
reconstructed as free functions, and any method whose disasm passes `this` in
`ecx` and cleans its own stack.
When the convention can't be read off the import table, it's read from the
disasm: `ret N` (nonzero) is callee cleanup (stdcall/thiscall); a bare `ret`
with the caller fixing `esp` is cdecl; `this` arriving in `ecx` marks thiscall
(`docs/conventions.md`, "Calling convention macros").
## Calling convention per companion module
Each companion's convention and binding mode were derived by disassembling
`gamekdm.dll`'s own call sites against its Import Address Table: a
`call DWORD PTR ds:0x<iat>` followed by the caller popping arguments (`add
esp,N`) is cdecl; a callee returning `ret N` with no caller fixup is stdcall
(`docs/companion-conventions.md`, intro).
| DLL | Convention | Evidence (from `docs/companion-conventions.md`) | `--kill-at` |
|---|---|---|---|
| libavs-win32.dll | cdecl | caller-cleanup call-site evidence | no |
| libavs-win32-ea3.dll | cdecl | same vendor build / export-naming scheme as libavs-win32 | no |
| libafp-win32.dll | cdecl | caller-cleanup call-site evidence | no |
| libafputils-win32.dll | cdecl (logger entry points cdecl-varargs) | caller-cleanup call-site evidence | no |
| ess.dll | cdecl | not called via gamekdm's IAT; plain undecorated C exports, no `@N` | no |
| arkkdm.dll | stdcall | `arkAFPBoot` call-site evidence | yes |
| libacio.dll | cdecl | not called via gamekdm's IAT; undecorated plain-C exports | no |
| Kinect10.dll (external Microsoft NUI runtime) | stdcall | external-import call-site evidence | yes |
The shipped-module imports listed above bind by name. The external Kinect10
runtime is imported by ordinal in
gamekdm's import table but exported by name in the DLL (`NuiInitialize`, ...)
plus one `NONAME` ordinal-1 export. `--kill-at` strips dlltool's guessed `@N`
stdcall decoration so the import binds to the DLL's real undecorated export
name; it's needed for `arkkdm.dll` and `Kinect10.dll` (whose export tables hold
undecorated names) and is a no-op for the six cdecl companions, whose `.def`
files carry no `@N` for dlltool to strip
(`docs/companion-conventions.md`, "`--kill-at` scope"). The generated import
libraries are link-proven by `tests/importlibs/companion_link_test.c`, with a
negative control that removes one `.def` entry and confirms the link then fails
(`docs/companion-conventions.md`, "Link proof").
## Struct packing rules
MSVC built the original with its default packing (natural alignment, equivalent
to `#pragma pack(8)` on x86) unless a translation unit set a tighter pack. A
reconstructed struct either relies on natural alignment (already correct for
int/float/pointer-only structs on x86) or brackets itself with the pack macros
to reproduce the exact MSVC pack state (`docs/conventions.md`, "Struct
packing"). The macros are in `include/gk/types.h:54-56`:
- `GK_PRAGMA(x)` stringizes `x` and emits it as a `_Pragma`.
- `GK_PACK_PUSH(n)` emits `#pragma pack(push, n)`.
- `GK_PACK_POP` emits `#pragma pack(pop)`.
GCC/MinGW honor `#pragma pack` identically to MSVC, so no byte copying is needed.
Every reconstructed struct header brackets its layout with `GK_PACK_PUSH(8)` /
`GK_PACK_POP` (for example `include/gk/structs/math.h`,
`include/gk/structs/manager.h`), matching MSVC's default pack(8).
## Reconstructed struct layouts
The layouts below are the recovered binary structures under
`include/gk/structs/`, with every offset pinned by a `static_assert` in
`include/gk/offsets_assert.h`. Unrecovered regions are kept as byte-storage
arrays (`storage_XXXX`) rather than invented fields
(`include/gk/structs/manager.h`).
### Math types (`include/gk/structs/math.h`)
Natural x86 layout confirmed by float-indexed accesses in `FUN_101799b0`,
`FUN_101ab5b0`, `FUN_101ab640`.
- `gk::Vec3`: `float x,y,z` at `+0x00/+0x04/+0x08`, size `0x0c`.
- `gk::Vec4`: `float x,y,z,w` at `+0x00/+0x04/+0x08/+0x0c`, size `0x10`.
- `gk::Matrix4x4`: 16 row-major floats `m00..m33` at `+0x00` through `+0x3c`,
size `0x40`. `FUN_101799b0` reads all sixteen contiguous floats;
`FUN_100e4140` applies rows 0..2 to candidate positions.
(All asserts: `include/gk/offsets_assert.h:11-40`.)
### Skeleton types (`include/gk/structs/skeleton.h`)
Kinect NUI v1 wire layout. `kSkeletonCount = 6`, `kSkeletonJointCount = 20`.
`SkeletonTrackingState` / `JointTrackingState` are `uint32_t` enums
(`not_tracked=0`, `inferred/position_only=1`, `tracked=2`).
`gk::SkeletonData` (size `0x1b4`, the stride `FUN_100e4140` advances through
candidates by):
| Field | Offset |
|---|---|
| `tracking_state` | `0x000` |
| `tracking_id` | `0x004` |
| `enrollment_index` | `0x008` |
| `user_index` | `0x00c` |
| `position` (`Vec4`) | `0x010` |
| `joint_positions[20]` (`Vec4`) | `0x020` |
| `joint_tracking_states[20]` | `0x160` |
| `quality_flags` | `0x1b0` |
`gk::SkeletonFrame` (size `0xa68`), the `NUI_SKELETON_FRAME` copied into the live
manager at `+0x1a0`: `timestamp` (`int64`) `0x000`, `frame_number` `0x008`,
`flags` `0x00c`, `floor_clip_plane` (`Vec4`) `0x010`, `normal_to_gravity`
(`Vec4`) `0x020`, `skeletons[6]` `0x030`
(`include/gk/offsets_assert.h:42-57`).
### Live manager (`include/gk/structs/manager.h`)
`gk::LiveManager` is the live object addressed by `*(gamekdm.dll+0x3cf1b4)`.
Selected pinned offsets (`include/gk/offsets_assert.h:75-87`):
| Field | Offset |
|---|---|
| `nui_thread_address` | `0x0000` |
| `committed_subsystems` | `0x000c` |
| `subsystem_mask` | `0x0010` |
| `flags` | `0x0014` |
| `reference_direction` (`Vec3`) | `0x0020` |
| `gravity` (`Vec4`) | `0x002c` |
| `skeleton_frame` | `0x01a0` |
| `requested_tracking_ids[2]` | `0x15f0` |
| `skeleton_tracking_enabled` | `0x15f8` |
| `nui_sensor_address` | `0x15fc` |
| `selected_tracking_ids[2]` | `0x1684` |
| `synthetic_tracking_mode` | `0x17f4` |
`gk::CursorControllerState` is reached through `DAT_103d2bb8`. The pointer at
`+0x000` (`inner_address`) is an opaque target address; no MSVC vtable/RTTI bytes
are reproduced. Cursor fields: `player1_x` `+0x108`, `player1_y` `+0x10c`,
`player2_x` `+0x110`, `player2_y` `+0x114`
(`include/gk/offsets_assert.h:89-93`).
### Validity types (`include/gk/structs/validity.h`)
- `gk::ValidityBox` (`DAT_103d3230`, size `0x18`): `minimum` (`Vec3`) `+0x00`,
`maximum` (`Vec3`) `+0x0c`. Consumed as six consecutive floats by
`FUN_101ab6d0`'s clamp-and-distance check.
- `gk::ValidityCandidate` (`DAT_103e29b0`..., stride `0x20` for six candidates,
size `0x20`): `source_position` (`Vec3`) `+0x00`, `transformed_position`
(`Vec3`) `+0x0c`, `tracking_id` (`float`) `+0x18`, `valid` (`uint8`) `+0x1c`,
`reserved[3]` `+0x1d`. `FUN_100e4140` writes these fields
(`include/gk/offsets_assert.h:59-73`).
## vtable and RTTI reconstruction
C++ classes are declared and MinGW regenerates the vtable and RTTI under the
Itanium ABI. MSVC vtable or RTTI bytes are never memcpy'd, because MSVC and
Itanium disagree on layout: MSVC stores the Complete Object Locator at
`vtable[-1]`, Itanium stores the `type_info` pointer at `vtable[-1]`, so copied
bytes are wrong under MinGW (`docs/conventions.md`, "vtable and RTTI
reconstruction"). The procedure:
1. Reconstruct the class hierarchy and virtual-function signatures from the
Ghidra-recovered vtables.
2. Verify slot order with `g++ -fdump-lang-class` and compare the emitted vtable
slot order against Ghidra's; they must agree slot for slot.
3. Let the toolchain emit RTTI; never hand-build `type_info`.
## Function naming and forwarding
Each undecompiled routine is named `FUN_<rva>` by Ghidra (lowercase hex RVA,
image base excluded). Reconstruction renames it to a semantic name in the
module namespace (e.g. `gk::audio::MixSample`) and pins the origin in a comment
the differ reads back: `// rva=0x10023af0 (orig FUN_10023af0)`. One RVA maps to
exactly one semantic name, recorded in the function's claim entry so the mapping
stays reversible; an existing import/export symbol is kept as the semantic name
(`docs/conventions.md`, "Function naming").
A function may be forwarded (left as a call into the original image) only if
neither it nor any callee writes a global that non-forwarded code reads. If a
forwarded routine and a reconstructed routine both touch the same global, state
drifts, so the function must be reconstructed instead (`docs/conventions.md`,
"Global ownership").
## Macro cross-check
The `GK_` macro names in `docs/conventions.md` and `include/gk/types.h` must
match exactly. The macros in scope are `GK_CDECL`, `GK_STDCALL`, `GK_THISCALL`,
`GK_PRAGMA`, `GK_PACK_PUSH`, and `GK_PACK_POP`, cross-checked with:
```
grep -o 'GK[_][A-Z_]*' docs/conventions.md include/gk/types.h | sort -u
```
(`docs/conventions.md`, "Macro cross-check").