feat(hybrid): detour carve-out framework (slice-proven)
This commit is contained in:
1 parent
74902f528b
commit
910f33c38f
5 files changed
+381
No files matched your search
@@ -29,3 +29,24 @@ target_link_options(gamekdm PRIVATE
|
||||
set_target_properties(gamekdm PROPERTIES
|
||||
LINK_DEPENDS "${CMAKE_SOURCE_DIR}/export/gamekdm.def"
|
||||
)
|
||||
|
||||
# T12: explicit startup installer, linked by a host before invoking gameMain.
|
||||
# Only the audited POD slice crosses into the separately built MinGW CRT.
|
||||
add_library(gamekdm_detours STATIC
|
||||
src/hybrid/detours.cpp
|
||||
src/game/box_distance.cpp
|
||||
)
|
||||
target_include_directories(gamekdm_detours PUBLIC
|
||||
${CMAKE_SOURCE_DIR}/include
|
||||
${CMAKE_SOURCE_DIR}/src/hybrid
|
||||
)
|
||||
target_compile_features(gamekdm_detours PUBLIC cxx_std_17)
|
||||
target_compile_options(gamekdm_detours PRIVATE
|
||||
-Wall -Wextra -Werror -mfpmath=387 -ffp-contract=off -fno-fast-math
|
||||
-fno-exceptions -fno-rtti
|
||||
)
|
||||
add_executable(gamekdm_detour_test src/hybrid/test_host.cpp)
|
||||
target_link_libraries(gamekdm_detour_test PRIVATE gamekdm_detours)
|
||||
target_compile_options(gamekdm_detour_test PRIVATE
|
||||
-Wall -Wextra -Werror -mfpmath=387 -ffp-contract=off -fno-fast-math
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
# T12 hybrid detours
|
||||
|
||||
Build with the repository's i686 MinGW toolchain:
|
||||
|
||||
```sh
|
||||
source ~/.nix-profile/etc/profile.d/nix.sh
|
||||
source ./activate.sh
|
||||
cp /home/athapa/ghidra/gamekdm.dll orig/gamekdm_orig.dll
|
||||
cmake -S . -B build-t12 -DCMAKE_TOOLCHAIN_FILE=cmake/toolchain-mingw-i686.cmake -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build-t12 -j2
|
||||
WINEDEBUG=-all wine build-t12/gamekdm_detour_test.exe \
|
||||
"$(winepath -w "$PWD/orig/gamekdm_orig.dll")" \
|
||||
"$(winepath -w '/mnt/f/Users/Aaron Thapa/Downloads/KDM-2016021900/contents')"
|
||||
```
|
||||
|
||||
Append `--relocate` to reserve the preferred image base before loading and test
|
||||
the nonzero slide. Production startup calls `load(path)`, which uses normal
|
||||
`LoadLibraryExA`, including dependency resolution and DLL initialization. The
|
||||
focused slice test calls `load(path, false)`: Wine maps the actual PE with
|
||||
`DONT_RESOLVE_DLL_REFERENCES`, avoiding unrelated `gameMain` process bootstrap.
|
||||
The tested box routine and its two callees have no imports, so all executed
|
||||
code and data still come from the mapped original DLL; nothing is emulated or
|
||||
substituted. Full initialized loading requires the real launcher environment
|
||||
and remains the production default rather than silently falling back.
|
||||
|
||||
`gamekdm_detours` is a static library for a startup host. Call `load`, then
|
||||
`set_enabled(rva, true)` for each requested registry row before starting game
|
||||
threads. Entries default to disabled. The original export and every unpatched
|
||||
function remain in the loaded original image. This test host does not launch
|
||||
`gameMain` or claim a full game playback test.
|
||||
|
||||
The handwritten x86 trampoline supports only the audited box-distance entry:
|
||||
RVA `0x1ab6d0` (VA `0x101ab6d0`). Its first six bytes are three whole
|
||||
instructions without relative operands. They are checked before patching,
|
||||
copied to an executable trampoline, and followed by a relative jump back.
|
||||
An ABI adapter maps original EAX/EDI arguments to the existing reconstruction's
|
||||
cdecl POD references and returns ST0. A private atomic diagnostic counter
|
||||
proves which implementation ran. It shares no ownership with original state.
|
||||
|
||||
Ownership is an immutable allowlist in the registry, not caller-supplied
|
||||
trust metadata. Unknown RVAs cannot be hooked. Audited entries:
|
||||
|
||||
| RVA | Reconstruction | Ownership |
|
||||
| --- | --- | --- |
|
||||
| `0x1ab6d0` | `BoxDistanceSquared` | Allowed: POD inputs, no allocations, EH, globals, or virtual calls. Original clamp callees `0x1ab640` and `0x1ab5b0` only use inputs and stack/output buffers. |
|
||||
| `0x0e4140` | `UpdateValidityCandidates` | Blocked: original reads and writes shared globals, including candidates at `0x3e29b0`; reconstructed explicit state must not become a second copy. |
|
||||
| `0x00f510` | `UpdateCameraElevation` | Blocked: shared sensor/object state and original MSVC virtual ABI do not match the reconstructed interface/layout. |
|
||||
|
||||
Original data addresses use `at_rva`, derived from the loaded module base
|
||||
(slide = base - `0x10000000`). No original globals are duplicated. This
|
||||
installer intentionally provides no generic trampoline decoder: extending the
|
||||
allowlist requires auditing ownership, the actual register ABI, instruction
|
||||
boundaries, and relocation requirements.
|
||||
|
||||
Call toggles and `unload` only while game callers are quiescent. Six-byte
|
||||
instruction patches are not atomic; this library does not suspend threads.
|
||||
Observe the result of `unload` before unloading replacement code. A failed
|
||||
restore retains the original module rather than freeing a still-hooked image.
|
||||
The checked timestamp, image dimensions, and prologue identify the expected
|
||||
layout, not a cryptographic authenticity check. The tested input DLL SHA-256 is
|
||||
`0595cb1dd98e4c02e2700f22f29d6504a9a74b401238ba5ec539d666ee8f0804`.
|
||||
@@ -0,0 +1,141 @@
|
||||
#include "detours.h"
|
||||
#include "../game/validity.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
static_assert(sizeof(void*) == 4, "Detours require PE32 x86");
|
||||
|
||||
namespace {
|
||||
volatile LONG calls = 0;
|
||||
// Three complete instructions, with no PC-relative operands:
|
||||
// push ebp; mov ebp,esp; sub esp,0x34.
|
||||
constexpr unsigned char prologue[] = {0x55, 0x8b, 0xec, 0x83, 0xec, 0x34};
|
||||
|
||||
void jump(unsigned char* out, std::uintptr_t from, std::uintptr_t to) {
|
||||
out[0] = 0xe9;
|
||||
const std::uint32_t displacement = static_cast<std::uint32_t>(to - from - 5);
|
||||
std::memcpy(out + 1, &displacement, sizeof(displacement));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" float __cdecl gk_box_impl(const gk::ValidityBox* box,
|
||||
const gk::Vec3* point) {
|
||||
InterlockedIncrement(&calls);
|
||||
return gk::game::BoxDistanceSquared(*box, *point);
|
||||
}
|
||||
|
||||
extern "C" void gk_box_adapter();
|
||||
// Original ABI: EAX=box, EDI=point, return ST0. Preserve nonvolatile
|
||||
// registers and align the MinGW call stack independently of the MSVC caller.
|
||||
asm(".text\n"
|
||||
".globl _gk_box_adapter\n"
|
||||
"_gk_box_adapter:\n"
|
||||
"pushl %ebp\n"
|
||||
"movl %esp,%ebp\n"
|
||||
"andl $-16,%esp\n"
|
||||
"subl $8,%esp\n"
|
||||
"pushl %edi\n"
|
||||
"pushl %eax\n"
|
||||
"call _gk_box_impl\n"
|
||||
"leave\n"
|
||||
"ret\n");
|
||||
|
||||
namespace gk::hybrid {
|
||||
|
||||
unsigned long box_calls() { return static_cast<unsigned long>(calls); }
|
||||
|
||||
void* Detours::at_rva(std::uint32_t rva) const {
|
||||
return module_ && rva < image_size_
|
||||
? reinterpret_cast<void*>(base() + rva) : nullptr;
|
||||
}
|
||||
|
||||
Result Detours::load(const char* path, bool initialize) {
|
||||
if (module_) return Result::win32_error;
|
||||
module_ = LoadLibraryExA(path, nullptr,
|
||||
initialize ? 0 : DONT_RESOLVE_DLL_REFERENCES);
|
||||
if (!module_) return Result::win32_error;
|
||||
const auto* dos = reinterpret_cast<const IMAGE_DOS_HEADER*>(module_);
|
||||
const auto* nt = reinterpret_cast<const IMAGE_NT_HEADERS32*>(base() + dos->e_lfanew);
|
||||
// Pin the audited binary's layout. Also check the exact overwrite bytes.
|
||||
if (nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386 ||
|
||||
nt->FileHeader.TimeDateStamp != 0x56285d99 ||
|
||||
nt->OptionalHeader.SizeOfImage != 0x41c000) {
|
||||
unload();
|
||||
return Result::image_mismatch;
|
||||
}
|
||||
image_size_ = nt->OptionalHeader.SizeOfImage;
|
||||
const auto* target = static_cast<const unsigned char*>(at_rva(entries_[0].rva));
|
||||
if (std::memcmp(target, prologue, sizeof(prologue)) != 0) {
|
||||
unload();
|
||||
return Result::image_mismatch;
|
||||
}
|
||||
trampoline_ = static_cast<unsigned char*>(
|
||||
VirtualAlloc(nullptr, 11, MEM_COMMIT | MEM_RESERVE,
|
||||
PAGE_EXECUTE_READWRITE));
|
||||
if (!trampoline_) {
|
||||
unload();
|
||||
return Result::win32_error;
|
||||
}
|
||||
std::memcpy(trampoline_, prologue, sizeof(prologue));
|
||||
jump(trampoline_ + 6, reinterpret_cast<std::uintptr_t>(trampoline_ + 6),
|
||||
reinterpret_cast<std::uintptr_t>(target + 6));
|
||||
if (!FlushInstructionCache(GetCurrentProcess(), trampoline_, 11)) {
|
||||
unload();
|
||||
return Result::win32_error;
|
||||
}
|
||||
return Result::ok;
|
||||
}
|
||||
|
||||
Result Detours::set_enabled(std::uint32_t rva, bool enabled) {
|
||||
Entry* entry = nullptr;
|
||||
for (auto& candidate : entries_) {
|
||||
if (candidate.rva == rva) entry = &candidate;
|
||||
}
|
||||
if (!entry) return Result::unknown_rva;
|
||||
// Checked even on repeated requests and before touching any original byte.
|
||||
// Only the audited allowlist can be enabled; callers cannot relabel ownership.
|
||||
if (entry->ownership != Ownership::pod_only) return Result::ownership_blocked;
|
||||
if (!module_ || !trampoline_) return Result::not_loaded;
|
||||
if (entry->enabled == enabled) return Result::ok;
|
||||
auto* target = static_cast<unsigned char*>(at_rva(rva));
|
||||
unsigned char patch[6];
|
||||
jump(patch, reinterpret_cast<std::uintptr_t>(target),
|
||||
reinterpret_cast<std::uintptr_t>(&gk_box_adapter));
|
||||
patch[5] = 0x90;
|
||||
if (std::memcmp(target, entry->enabled ? patch : prologue, 6) != 0)
|
||||
return Result::image_mismatch;
|
||||
DWORD old;
|
||||
if (!VirtualProtect(target, 6, PAGE_EXECUTE_READWRITE, &old))
|
||||
return Result::win32_error;
|
||||
std::memcpy(target, enabled ? patch : prologue, 6);
|
||||
entry->enabled = enabled; // Track actual bytes even if protection restore fails.
|
||||
DWORD ignored;
|
||||
const BOOL protected_again = VirtualProtect(target, 6, old, &ignored);
|
||||
const BOOL flushed = FlushInstructionCache(GetCurrentProcess(), target, 6);
|
||||
return protected_again && flushed ? Result::ok : Result::win32_error;
|
||||
}
|
||||
|
||||
Result Detours::unload() {
|
||||
if (entries_[0].enabled) {
|
||||
const Result result = set_enabled(entries_[0].rva, false);
|
||||
if (result != Result::ok) return result;
|
||||
}
|
||||
if (trampoline_) {
|
||||
if (!VirtualFree(trampoline_, 0, MEM_RELEASE)) return Result::win32_error;
|
||||
trampoline_ = nullptr;
|
||||
}
|
||||
if (module_) {
|
||||
if (!FreeLibrary(module_)) return Result::win32_error;
|
||||
module_ = nullptr;
|
||||
}
|
||||
image_size_ = 0;
|
||||
return Result::ok;
|
||||
}
|
||||
|
||||
Detours::~Detours() {
|
||||
// Never unload a still-hooked image on failure. The caller must observe
|
||||
// unload() before unloading the module containing the replacement code.
|
||||
unload();
|
||||
}
|
||||
|
||||
} // namespace gk::hybrid
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace gk::hybrid {
|
||||
|
||||
enum class Ownership { pod_only, shared_mutable_globals, foreign_object_abi };
|
||||
enum class Result {
|
||||
ok, ownership_blocked, unknown_rva, not_loaded, image_mismatch, win32_error
|
||||
};
|
||||
|
||||
struct Entry {
|
||||
std::uint32_t rva;
|
||||
const char* impl_symbol;
|
||||
bool enabled;
|
||||
Ownership ownership;
|
||||
};
|
||||
|
||||
// Single owner; call load/toggle/unload only while game threads are quiescent.
|
||||
// No DllMain work: the host invokes load during startup before gameMain.
|
||||
class Detours {
|
||||
public:
|
||||
Detours() = default;
|
||||
Detours(const Detours&) = delete;
|
||||
Detours& operator=(const Detours&) = delete;
|
||||
~Detours();
|
||||
|
||||
Result load(const char* path, bool initialize = true);
|
||||
Result set_enabled(std::uint32_t rva, bool enabled);
|
||||
Result unload();
|
||||
const Entry* entries() const { return entries_; }
|
||||
static constexpr std::size_t count = 3;
|
||||
std::uintptr_t base() const { return reinterpret_cast<std::uintptr_t>(module_); }
|
||||
std::intptr_t slide() const { return static_cast<std::intptr_t>(base() - 0x10000000u); }
|
||||
// Original data is addressed in its owning image, never copied into a CRT.
|
||||
void* at_rva(std::uint32_t rva) const;
|
||||
void* original_box() const { return trampoline_; }
|
||||
|
||||
private:
|
||||
HMODULE module_ = nullptr;
|
||||
std::uint32_t image_size_ = 0;
|
||||
unsigned char* trampoline_ = nullptr;
|
||||
Entry entries_[count] = {
|
||||
{0x1ab6d0, "gk::game::BoxDistanceSquared", false, Ownership::pod_only},
|
||||
{0x0e4140, "gk::game::UpdateValidityCandidates", false,
|
||||
Ownership::shared_mutable_globals},
|
||||
{0x00f510, "gk::game::UpdateCameraElevation", false,
|
||||
Ownership::foreign_object_abi}};
|
||||
};
|
||||
|
||||
// Diagnostic counter belongs exclusively to this module, not the original CRT.
|
||||
unsigned long box_calls();
|
||||
|
||||
} // namespace gk::hybrid
|
||||
@@ -0,0 +1,102 @@
|
||||
#include "detours.h"
|
||||
#include "../game/validity.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" float __cdecl gk_call_box(void* entry, const gk::ValidityBox* box,
|
||||
const gk::Vec3* point);
|
||||
asm(".text\n"
|
||||
".globl _gk_call_box\n"
|
||||
"_gk_call_box:\n"
|
||||
"pushl %edi\n"
|
||||
"movl 8(%esp),%edx\n"
|
||||
"movl 12(%esp),%eax\n"
|
||||
"movl 16(%esp),%edi\n"
|
||||
"call *%edx\n"
|
||||
"popl %edi\n"
|
||||
"ret\n");
|
||||
|
||||
#define CHECK(condition) do { if (!(condition)) { \
|
||||
std::printf("FAIL line=%d condition=%s win32=%lu\n", \
|
||||
__LINE__, #condition, GetLastError()); return 1; } } while (0)
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
using gk::hybrid::Result;
|
||||
CHECK(argc == 3 || argc == 4);
|
||||
// Resolve genuine companion imports through the supplied game directory.
|
||||
CHECK(SetDllDirectoryA(argv[2]));
|
||||
void* reservation = nullptr;
|
||||
if (argc == 4) {
|
||||
CHECK(std::strcmp(argv[3], "--relocate") == 0);
|
||||
reservation = VirtualAlloc(reinterpret_cast<void*>(0x10000000), 0x41c000,
|
||||
MEM_RESERVE, PAGE_NOACCESS);
|
||||
CHECK(reservation == reinterpret_cast<void*>(0x10000000));
|
||||
}
|
||||
gk::hybrid::Detours hooks;
|
||||
// This focused slice host maps the real PE without invoking gameMain's full
|
||||
// process bootstrap; production startup uses load(path)'s default `true`.
|
||||
const Result loaded = hooks.load(argv[1], false);
|
||||
std::printf("LoadLibrary result=%d win32=%lu\n", static_cast<int>(loaded), GetLastError());
|
||||
CHECK(loaded == Result::ok);
|
||||
std::printf("runtime_base=0x%08lx slide=0x%08lx\n",
|
||||
static_cast<unsigned long>(hooks.base()),
|
||||
static_cast<unsigned long>(hooks.slide()));
|
||||
CHECK(!reservation || hooks.slide() != 0);
|
||||
CHECK(hooks.at_rva(0x3d3230) ==
|
||||
reinterpret_cast<void*>(hooks.base() + 0x3d3230));
|
||||
CHECK(hooks.at_rva(0x41c000) == nullptr);
|
||||
|
||||
constexpr std::uint32_t box_rva = 0x1ab6d0;
|
||||
void* entry = hooks.at_rva(box_rva);
|
||||
unsigned char before[3][16];
|
||||
for (std::size_t i = 0; i < hooks.count; ++i) {
|
||||
std::memcpy(before[i], hooks.at_rva(hooks.entries()[i].rva), 16);
|
||||
std::printf("registry rva=0x%06lx impl_symbol=%s enabled=%d ownership=%d\n",
|
||||
static_cast<unsigned long>(hooks.entries()[i].rva),
|
||||
hooks.entries()[i].impl_symbol, hooks.entries()[i].enabled,
|
||||
static_cast<int>(hooks.entries()[i].ownership));
|
||||
}
|
||||
const gk::ValidityBox box = {{1, 2, 3}, {2, 3, 4}};
|
||||
const gk::Vec3 points[] = {{6, 9, 7}, {-4, -5, 3}, {1, 2, 3},
|
||||
{1.3f, 0, 2.5f}, {3, 5, 7}, {3.25f, 5.5f, 8}};
|
||||
const float expected[] = {25, 25, 0, 0, 0, 1.3125f};
|
||||
for (std::size_t i = 0; i < sizeof(points) / sizeof(points[0]); ++i) {
|
||||
const auto count = gk::hybrid::box_calls();
|
||||
const float original = gk_call_box(entry, &box, &points[i]);
|
||||
CHECK(original == expected[i]);
|
||||
CHECK(gk::hybrid::box_calls() == count);
|
||||
CHECK(hooks.set_enabled(box_rva, true) == Result::ok);
|
||||
CHECK(hooks.set_enabled(box_rva, true) == Result::ok);
|
||||
CHECK(hooks.entries()[0].enabled);
|
||||
CHECK(*static_cast<unsigned char*>(entry) == 0xe9);
|
||||
const float detoured = gk_call_box(entry, &box, &points[i]);
|
||||
CHECK(gk::hybrid::box_calls() == count + 1);
|
||||
CHECK(std::memcmp(&original, &detoured, sizeof(float)) == 0);
|
||||
const float trampoline = gk_call_box(hooks.original_box(), &box, &points[i]);
|
||||
CHECK(std::memcmp(&original, &trampoline, sizeof(float)) == 0);
|
||||
CHECK(gk::hybrid::box_calls() == count + 1);
|
||||
CHECK(hooks.set_enabled(box_rva, false) == Result::ok);
|
||||
CHECK(!hooks.entries()[0].enabled);
|
||||
CHECK(std::memcmp(before[0], entry, 16) == 0);
|
||||
const float restored = gk_call_box(entry, &box, &points[i]);
|
||||
CHECK(restored == original && gk::hybrid::box_calls() == count + 1);
|
||||
std::printf("case=%u OFF=%g ON=%g trampoline=%g restored=%g calls=%lu EQUAL\n",
|
||||
static_cast<unsigned>(i), original, detoured, trampoline, restored,
|
||||
gk::hybrid::box_calls());
|
||||
}
|
||||
CHECK(hooks.set_enabled(box_rva, true) == Result::ok);
|
||||
for (std::size_t i = 1; i < hooks.count; ++i) {
|
||||
CHECK(hooks.set_enabled(hooks.entries()[i].rva, true) == Result::ownership_blocked);
|
||||
CHECK(!hooks.entries()[i].enabled && hooks.entries()[0].enabled);
|
||||
CHECK(std::memcmp(before[i], hooks.at_rva(hooks.entries()[i].rva), 16) == 0);
|
||||
std::printf("rva=0x%06lx ownership BLOCKED; bytes unchanged; box still ON\n",
|
||||
static_cast<unsigned long>(hooks.entries()[i].rva));
|
||||
}
|
||||
CHECK(hooks.set_enabled(0x123456, true) == Result::unknown_rva);
|
||||
CHECK(hooks.unload() == Result::ok);
|
||||
CHECK(hooks.base() == 0 && !hooks.entries()[0].enabled);
|
||||
if (reservation) CHECK(VirtualFree(reservation, 0, MEM_RELEASE));
|
||||
std::puts("PASS detours OFF==original; ON=slice+equivalence; stateful-detour BLOCKED");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user