RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9b5e2765b7
commit
a24ed6df7c
322 changed files with 83009 additions and 7504 deletions
36
native/Loader/Build-Loader.ps1
Normal file
36
native/Loader/Build-Loader.ps1
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# Build-Loader.ps1
|
||||
# Compiles the native RynthCore.Loader.dll (x86 MSVC) into native\Loader\bin.
|
||||
# Does not deploy: copy it to Runtime\ yourself (a running client keeps the old loader
|
||||
# until it restarts; the loader is injected once per process).
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" `
|
||||
-latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 `
|
||||
-property installationPath 2>$null
|
||||
if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 }
|
||||
|
||||
$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name
|
||||
$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer"
|
||||
$cl = "$vcBase\bin\Hostx86\x86\cl.exe"
|
||||
$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name
|
||||
$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer"
|
||||
$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer"
|
||||
$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared"
|
||||
$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86"
|
||||
|
||||
$src = $PSScriptRoot
|
||||
$out = Join-Path $src "bin"
|
||||
$obj = Join-Path $out "obj"
|
||||
New-Item -ItemType Directory -Path $out, $obj -Force | Out-Null
|
||||
|
||||
Write-Host "Compiling RynthCore.Loader.dll (MSVC $vcVer, x86)..."
|
||||
Push-Location $obj
|
||||
try {
|
||||
& $cl /nologo /O2 /MT /GS /W4 /wd4100 /LD /Zi "$src\Loader.c" "$src\Hooks.c" "$src\Clr.c" "$src\Services.c" user32.lib `
|
||||
/link /MACHINE:X86 /DEF:"$src\Loader.def" /DEBUG /OPT:REF /OUT:"$out\RynthCore.Loader.dll" /PDB:"$out\RynthCore.Loader.pdb"
|
||||
if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE }
|
||||
} finally { Pop-Location }
|
||||
|
||||
$size = (Get-Item "$out\RynthCore.Loader.dll").Length
|
||||
Write-Host "Built: $out\RynthCore.Loader.dll ($size bytes)"
|
||||
175
native/Loader/Clr.c
Normal file
175
native/Loader/Clr.c
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
// ============================================================================
|
||||
// Clr.c - hosts CoreCLR once, from the app-local runtime in Runtime\dotnet\, and
|
||||
// talks to RynthCore.Shim.dll (default ALC), which owns the collectible
|
||||
// AssemblyLoadContext each engine generation lives in.
|
||||
//
|
||||
// The raw coreclr_* API is used (no hostfxr, runtimeconfig.json or deps.json): the
|
||||
// TPA list is every managed DLL in Runtime\dotnet\ plus the Shim. The engine and its
|
||||
// own dependencies (Avalonia, ImGui.NET, ...) are NOT on the TPA list: the Shim loads
|
||||
// them into the engine's collectible ALC, so they go away with it.
|
||||
// ============================================================================
|
||||
|
||||
#include "Loader.h"
|
||||
#include <stdio.h>
|
||||
|
||||
typedef int (__stdcall *coreclr_initialize_fn)(const char* exePath, const char* appDomainFriendlyName,
|
||||
int propertyCount, const char** propertyKeys, const char** propertyValues,
|
||||
void** hostHandle, unsigned int* domainId);
|
||||
typedef int (__stdcall *coreclr_create_delegate_fn)(void* hostHandle, unsigned int domainId,
|
||||
const char* assemblyName, const char* typeName, const char* methodName, void** fn);
|
||||
|
||||
// Shared with RynthCore.Shim (ShimHost.cs): keep the layouts in step.
|
||||
typedef struct LoaderApi {
|
||||
int size;
|
||||
void (__stdcall *log)(const char* level, const char* utf8);
|
||||
int (__stdcall *freeMb)(int* largestMb);
|
||||
const char* loaderDir;
|
||||
int (__stdcall *hookCount)(void);
|
||||
} LoaderApi;
|
||||
|
||||
typedef struct ShimApi {
|
||||
int size;
|
||||
int (__stdcall *loadEngine)(int generation, const char* stagedPathUtf8);
|
||||
int (__stdcall *unloadEngine)(void); // 1 = the ALC was freed
|
||||
void* (__stdcall *engineExport)(const char* nameUtf8);
|
||||
} ShimApi;
|
||||
|
||||
typedef int (__stdcall *shim_init_fn)(LoaderApi* api, ShimApi* out);
|
||||
|
||||
static LoaderApi g_loaderApi;
|
||||
static ShimApi g_shim;
|
||||
static int g_started;
|
||||
|
||||
int __stdcall RcHooks_Count(void);
|
||||
|
||||
static void __stdcall ShimLog(const char* level, const char* utf8) { LoaderLog(level ? level : "INF", "[shim] %s", utf8); }
|
||||
static int __stdcall ShimFreeMb(int* largestMb)
|
||||
{
|
||||
long largest;
|
||||
long free = LoaderFreeAddressSpaceMb(&largest);
|
||||
if (largestMb) *largestMb = (int)largest;
|
||||
return (int)free;
|
||||
}
|
||||
|
||||
static int IsNativeRuntimeFile(const char* n)
|
||||
{
|
||||
static const char* natives[] = {
|
||||
"coreclr.dll", "clrjit.dll", "clrgc.dll", "clrgcexp.dll", "hostfxr.dll", "hostpolicy.dll",
|
||||
"mscordaccore.dll", "mscordbi.dll", "mscorrc.dll", "clretwrc.dll", "msquic.dll",
|
||||
"System.IO.Compression.Native.dll", "Microsoft.DiaSymReader.Native.x86.dll",
|
||||
};
|
||||
for (int i = 0; i < (int)(sizeof natives / sizeof natives[0]); i++)
|
||||
if (!_stricmp(n, natives[i])) return 1;
|
||||
return !_strnicmp(n, "mscordaccore_", 13);
|
||||
}
|
||||
|
||||
static int AppendDlls(char* tpa, size_t cap, const char* dir)
|
||||
{
|
||||
char pattern[MAX_PATH];
|
||||
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\*.dll", dir);
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE h = FindFirstFileA(pattern, &fd);
|
||||
if (h == INVALID_HANDLE_VALUE) return 0;
|
||||
int n = 0;
|
||||
do {
|
||||
if (IsNativeRuntimeFile(fd.cFileName)) continue;
|
||||
strcat_s(tpa, cap, dir);
|
||||
strcat_s(tpa, cap, "\\");
|
||||
strcat_s(tpa, cap, fd.cFileName);
|
||||
strcat_s(tpa, cap, ";");
|
||||
n++;
|
||||
} while (FindNextFileA(h, &fd));
|
||||
FindClose(h);
|
||||
return n;
|
||||
}
|
||||
|
||||
int ClrStart(const char* loaderDir)
|
||||
{
|
||||
if (g_started) return 0;
|
||||
char runtimeDir[MAX_PATH], coreclrPath[MAX_PATH], shimPath[MAX_PATH];
|
||||
_snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", loaderDir);
|
||||
_snprintf_s(coreclrPath, sizeof coreclrPath, _TRUNCATE, "%s\\coreclr.dll", runtimeDir);
|
||||
_snprintf_s(shimPath, sizeof shimPath, _TRUNCATE, "%s\\RynthCore.Shim.dll", loaderDir);
|
||||
if (GetFileAttributesA(shimPath) == INVALID_FILE_ATTRIBUTES) {
|
||||
LoaderLog("ERR", "CLR: %s is missing", shimPath);
|
||||
return 1;
|
||||
}
|
||||
|
||||
long free0 = LoaderFreeAddressSpaceMb(NULL);
|
||||
DWORD t0 = GetTickCount();
|
||||
HMODULE clr = LoadLibraryExA(coreclrPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
|
||||
if (!clr) {
|
||||
LoaderLog("ERR", "CLR: LoadLibrary %s failed (error %lu)", coreclrPath, GetLastError());
|
||||
return 2;
|
||||
}
|
||||
coreclr_initialize_fn init = (coreclr_initialize_fn)GetProcAddress(clr, "coreclr_initialize");
|
||||
coreclr_create_delegate_fn create = (coreclr_create_delegate_fn)GetProcAddress(clr, "coreclr_create_delegate");
|
||||
if (!init || !create) return 3;
|
||||
|
||||
static char tpa[128 * 1024];
|
||||
tpa[0] = 0;
|
||||
int count = AppendDlls(tpa, sizeof tpa, runtimeDir);
|
||||
strcat_s(tpa, sizeof tpa, shimPath);
|
||||
strcat_s(tpa, sizeof tpa, ";");
|
||||
|
||||
char nativeDirs[2 * MAX_PATH + 4], baseDir[MAX_PATH + 2];
|
||||
_snprintf_s(nativeDirs, sizeof nativeDirs, _TRUNCATE, "%s;%s;", loaderDir, runtimeDir);
|
||||
_snprintf_s(baseDir, sizeof baseDir, _TRUNCATE, "%s\\", loaderDir);
|
||||
const char* keys[] = {
|
||||
"TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "APP_CONTEXT_BASE_DIRECTORY",
|
||||
"System.GC.Server", "System.GC.Concurrent", "System.Globalization.Invariant", "System.GC.RetainVM",
|
||||
};
|
||||
// Concurrent (background) GC on: the engine and the managed plugins share this one GC,
|
||||
// and with it off every gen2 (~every 10 s, driven by large allocations) was a fully
|
||||
// blocking 55-66 ms pause that AC's main thread hit whenever it was in managed code.
|
||||
const char* values[] = {
|
||||
tpa, "", nativeDirs, baseDir,
|
||||
"false", "true", "true", "false",
|
||||
};
|
||||
char exePath[MAX_PATH];
|
||||
GetModuleFileNameA(NULL, exePath, MAX_PATH);
|
||||
void* hostHandle = NULL;
|
||||
unsigned int domainId = 0;
|
||||
int hr = init(exePath, "RynthCore", (int)(sizeof keys / sizeof keys[0]), keys, values, &hostHandle, &domainId);
|
||||
if (hr < 0) {
|
||||
LoaderLog("ERR", "CLR: coreclr_initialize failed 0x%08x", hr);
|
||||
return 4;
|
||||
}
|
||||
|
||||
shim_init_fn shimInit = NULL;
|
||||
hr = create(hostHandle, domainId, "RynthCore.Shim", "RynthCore.Shim.ShimHost", "Init", (void**)&shimInit);
|
||||
if (hr < 0 || !shimInit) {
|
||||
LoaderLog("ERR", "CLR: RynthCore.Shim.ShimHost.Init not found (0x%08x)", hr);
|
||||
return 5;
|
||||
}
|
||||
g_loaderApi.size = sizeof g_loaderApi;
|
||||
g_loaderApi.log = ShimLog;
|
||||
g_loaderApi.freeMb = ShimFreeMb;
|
||||
g_loaderApi.loaderDir = LoaderDirectory();
|
||||
g_loaderApi.hookCount = RcHooks_Count;
|
||||
g_shim.size = sizeof g_shim;
|
||||
int rc = shimInit(&g_loaderApi, &g_shim);
|
||||
if (rc != 0 || !g_shim.loadEngine || !g_shim.unloadEngine || !g_shim.engineExport) {
|
||||
LoaderLog("ERR", "CLR: Shim init failed (rc=%d)", rc);
|
||||
return 6;
|
||||
}
|
||||
g_started = 1;
|
||||
LoaderLog("INF", "CLR: CoreCLR up in %lu ms from %s (%d framework assemblies), %ld MB of address space used.",
|
||||
GetTickCount() - t0, runtimeDir, count, free0 - LoaderFreeAddressSpaceMb(NULL));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ClrLoadEngine(int generation, const char* stagedPath)
|
||||
{
|
||||
return g_started ? g_shim.loadEngine(generation, stagedPath) : -1;
|
||||
}
|
||||
|
||||
void ClrUnloadEngine(void)
|
||||
{
|
||||
if (g_started) g_shim.unloadEngine();
|
||||
}
|
||||
|
||||
void* ClrEngineExport(const char* name)
|
||||
{
|
||||
return g_started ? g_shim.engineExport(name) : NULL;
|
||||
}
|
||||
332
native/Loader/Hooks.c
Normal file
332
native/Loader/Hooks.c
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
// ============================================================================
|
||||
// Hooks.c - MinHook facade with permanent stubs
|
||||
//
|
||||
// Exports MinHook's API (MH_Initialize, MH_CreateHook, MH_EnableHook, ...) with the
|
||||
// same signatures and status codes, so the engine's Hooking/MinHook.cs can call either
|
||||
// this facade or minhook.x86.dll.
|
||||
//
|
||||
// The difference: nothing native ever points at engine code directly. For every target
|
||||
// the facade allocates a permanent 6-byte stub, `jmp dword ptr [slot]`, and installs the
|
||||
// real MinHook hook once, with the stub as the detour. The slot holds either the
|
||||
// engine's detour (hook enabled) or MinHook's trampoline (hook disabled: a transparent
|
||||
// pass-through to the original, whatever the calling convention). A reload only
|
||||
// re-points slots, so an engine generation can be unloaded as soon as no thread is
|
||||
// inside its code, and the next generation's MH_CreateHook for the same target reuses
|
||||
// the same stub and gets the same trampoline back.
|
||||
//
|
||||
// Hooks are "owned" by the generation that created them: MH_CreateHook on a target
|
||||
// created by an earlier generation succeeds (no MH_ERROR_ALREADY_CREATED), and
|
||||
// HooksPassThroughAll() (every reload) turns every slot back into a pass-through and
|
||||
// takes the patch out of the target (MinHook disable: original bytes back), so the next
|
||||
// generation's pattern scans see AC's real prologues; its MH_CreateHook puts it back.
|
||||
// The stub and trampoline are never freed, so a thread still returning through them is
|
||||
// safe.
|
||||
//
|
||||
// Patching is batched. Every MinHook enable/disable freezes all the process's threads
|
||||
// (a system-wide thread snapshot, ~100 ms here), and an engine installs ~60 hooks: one
|
||||
// freeze each made up ~7 s of every reload. The facade records which targets should be
|
||||
// patched and applies them in one queued MinHook freeze: straight after the engine's
|
||||
// init export returns (HooksFlush; on a first launch AC's main thread is still suspended
|
||||
// then), on every reload, and ~20 ms after the last change otherwise (a background
|
||||
// flusher). A hook's slot is set at once; its patch follows within that window.
|
||||
// ============================================================================
|
||||
|
||||
#include "Loader.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#define MH_OK 0
|
||||
#define MH_ERROR_ALREADY_INITIALIZED 1
|
||||
#define MH_ERROR_NOT_INITIALIZED 2
|
||||
#define MH_ERROR_ALREADY_CREATED 3
|
||||
#define MH_ERROR_NOT_CREATED 4
|
||||
#define MH_ERROR_ENABLED 5
|
||||
#define MH_ERROR_DISABLED 6
|
||||
#define MH_ERROR_MEMORY_ALLOC 9
|
||||
#define MH_UNKNOWN -1
|
||||
|
||||
#define MAX_HOOKS 1024
|
||||
#define STUB_SIZE 8
|
||||
|
||||
typedef int (__stdcall *mh_init_fn)(void);
|
||||
typedef int (__stdcall *mh_create_fn)(void* target, void* detour, void** original);
|
||||
typedef int (__stdcall *mh_target_fn)(void* target);
|
||||
typedef const char* (__stdcall *mh_status_fn)(int status);
|
||||
|
||||
typedef struct HookEntry {
|
||||
void* target;
|
||||
void* trampoline; // MinHook's call-the-original trampoline (never freed)
|
||||
void* detour; // the owning generation's detour, or NULL once removed
|
||||
int generation; // generation that last created it
|
||||
int created; // created (and not removed) by `generation`
|
||||
int enabled; // slot == detour
|
||||
int patched; // MinHook's jump is in the target
|
||||
int want; // it should be (applied by the next flush)
|
||||
} HookEntry;
|
||||
|
||||
static CRITICAL_SECTION g_lock;
|
||||
static int g_ready;
|
||||
static int g_generation;
|
||||
static HMODULE g_minhook;
|
||||
static mh_init_fn p_init;
|
||||
static mh_create_fn p_create;
|
||||
static mh_target_fn p_enable;
|
||||
static mh_target_fn p_disable;
|
||||
static mh_target_fn p_queueDisable;
|
||||
static mh_target_fn p_queueEnable;
|
||||
static mh_init_fn p_applyQueued;
|
||||
static mh_status_fn p_status;
|
||||
|
||||
static HookEntry g_hooks[MAX_HOOKS];
|
||||
static void* volatile g_slots[MAX_HOOKS];
|
||||
static unsigned char* g_stubs;
|
||||
static int g_count;
|
||||
static HANDLE g_dirtyEvent;
|
||||
static volatile DWORD g_lastChange;
|
||||
|
||||
static void FlushLocked(const char* why);
|
||||
|
||||
static DWORD WINAPI Flusher(LPVOID unused)
|
||||
{
|
||||
(void)unused;
|
||||
for (;;) {
|
||||
WaitForSingleObject(g_dirtyEvent, INFINITE);
|
||||
do Sleep(20); while (GetTickCount() - g_lastChange < 20); // settle: one freeze per burst
|
||||
EnterCriticalSection(&g_lock);
|
||||
FlushLocked("batched");
|
||||
LeaveCriticalSection(&g_lock);
|
||||
}
|
||||
}
|
||||
|
||||
int HooksInit(const char* loaderDir)
|
||||
{
|
||||
InitializeCriticalSection(&g_lock);
|
||||
char path[MAX_PATH];
|
||||
_snprintf_s(path, sizeof path, _TRUNCATE, "%s\\minhook.x86.dll", loaderDir);
|
||||
g_minhook = LoadLibraryA(path);
|
||||
if (!g_minhook) g_minhook = LoadLibraryA("minhook.x86.dll");
|
||||
if (!g_minhook) return 0;
|
||||
p_init = (mh_init_fn)GetProcAddress(g_minhook, "MH_Initialize");
|
||||
p_create = (mh_create_fn)GetProcAddress(g_minhook, "MH_CreateHook");
|
||||
p_enable = (mh_target_fn)GetProcAddress(g_minhook, "MH_EnableHook");
|
||||
p_disable = (mh_target_fn)GetProcAddress(g_minhook, "MH_DisableHook");
|
||||
p_queueDisable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueDisableHook");
|
||||
p_queueEnable = (mh_target_fn)GetProcAddress(g_minhook, "MH_QueueEnableHook");
|
||||
p_applyQueued = (mh_init_fn)GetProcAddress(g_minhook, "MH_ApplyQueued");
|
||||
p_status = (mh_status_fn)GetProcAddress(g_minhook, "MH_StatusToString");
|
||||
if (!p_init || !p_create || !p_enable || !p_disable) return 0;
|
||||
int st = p_init();
|
||||
if (st != MH_OK && st != MH_ERROR_ALREADY_INITIALIZED) {
|
||||
LoaderLog("ERR", "Hooks: MH_Initialize = %d", st);
|
||||
return 0;
|
||||
}
|
||||
g_stubs = (unsigned char*)VirtualAlloc(NULL, MAX_HOOKS * STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
|
||||
if (!g_stubs) return 0;
|
||||
g_dirtyEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
|
||||
if (p_queueEnable && p_queueDisable && p_applyQueued && g_dirtyEvent) {
|
||||
HANDLE t = CreateThread(NULL, 0, Flusher, NULL, 0, NULL);
|
||||
if (t) CloseHandle(t);
|
||||
}
|
||||
g_ready = 1;
|
||||
LoaderLog("INF", "Hooks: MinHook facade ready (%s, %d stub slots, %s patching).", path, MAX_HOOKS,
|
||||
p_queueEnable ? "batched" : "per-hook");
|
||||
return 1;
|
||||
}
|
||||
|
||||
void HooksBeginGeneration(int generation)
|
||||
{
|
||||
EnterCriticalSection(&g_lock);
|
||||
g_generation = generation;
|
||||
LeaveCriticalSection(&g_lock);
|
||||
}
|
||||
|
||||
static void SetPatched(int i, int patched)
|
||||
{
|
||||
HookEntry* e = &g_hooks[i];
|
||||
if (e->patched == patched) return;
|
||||
int st = patched ? p_enable(e->target) : p_disable(e->target);
|
||||
if (st == MH_OK) e->patched = patched;
|
||||
else LoaderLog("ERR", "Hooks: MinHook %s %p failed: %d", patched ? "enable" : "disable", e->target, st);
|
||||
}
|
||||
|
||||
// Records whether target i should be patched; the next flush applies it. (Caller holds g_lock.)
|
||||
static void Want(int i, int patched)
|
||||
{
|
||||
HookEntry* e = &g_hooks[i];
|
||||
e->want = patched;
|
||||
if (e->want == e->patched) return;
|
||||
if (!p_queueEnable || !p_queueDisable || !p_applyQueued || !g_dirtyEvent) {
|
||||
SetPatched(i, patched); // no queue in this MinHook: one at a time
|
||||
return;
|
||||
}
|
||||
g_lastChange = GetTickCount();
|
||||
SetEvent(g_dirtyEvent);
|
||||
}
|
||||
|
||||
// Applies every pending patch/unpatch in one MinHook freeze. (Caller holds g_lock.)
|
||||
static void FlushLocked(const char* why)
|
||||
{
|
||||
static int queued[MAX_HOOKS];
|
||||
int n = 0;
|
||||
for (int i = 0; i < g_count; i++) {
|
||||
HookEntry* e = &g_hooks[i];
|
||||
if (e->want == e->patched) continue;
|
||||
int st = e->want ? p_queueEnable(e->target) : p_queueDisable(e->target);
|
||||
if (st == MH_OK) queued[n++] = i;
|
||||
else SetPatched(i, e->want);
|
||||
}
|
||||
if (n == 0) return;
|
||||
DWORD t0 = GetTickCount();
|
||||
int st = p_applyQueued();
|
||||
if (st == MH_OK) {
|
||||
for (int k = 0; k < n; k++) g_hooks[queued[k]].patched = g_hooks[queued[k]].want;
|
||||
LoaderLog("INF", "Hooks: %d patch(es) applied in one freeze (%lu ms, %s).", n, GetTickCount() - t0, why);
|
||||
} else {
|
||||
LoaderLog("ERR", "Hooks: MH_ApplyQueued (%d, %s) = %d; applying one at a time.", n, why, st);
|
||||
for (int k = 0; k < n; k++) SetPatched(queued[k], g_hooks[queued[k]].want);
|
||||
}
|
||||
}
|
||||
|
||||
void HooksFlush(void)
|
||||
{
|
||||
if (!g_ready) return;
|
||||
EnterCriticalSection(&g_lock);
|
||||
FlushLocked("engine init");
|
||||
LeaveCriticalSection(&g_lock);
|
||||
}
|
||||
|
||||
static void SetSlot(int i, int enabled)
|
||||
{
|
||||
HookEntry* e = &g_hooks[i];
|
||||
e->enabled = enabled;
|
||||
InterlockedExchangePointer((PVOID volatile*)&g_slots[i], enabled ? e->detour : e->trampoline);
|
||||
}
|
||||
|
||||
void HooksPassThroughAll(void)
|
||||
{
|
||||
if (!g_ready) return;
|
||||
EnterCriticalSection(&g_lock);
|
||||
int live = 0;
|
||||
for (int i = 0; i < g_count; i++) {
|
||||
if (g_hooks[i].enabled) live++;
|
||||
SetSlot(i, 0);
|
||||
Want(i, 0);
|
||||
g_hooks[i].created = 0;
|
||||
g_hooks[i].detour = NULL;
|
||||
}
|
||||
FlushLocked("reload"); // AC's own prologues back, now
|
||||
LeaveCriticalSection(&g_lock);
|
||||
LoaderLog("INF", "Hooks: %d hook(s) now pass straight through (%d were still enabled).", g_count, live);
|
||||
}
|
||||
|
||||
static int Find(void* target)
|
||||
{
|
||||
for (int i = 0; i < g_count; i++)
|
||||
if (g_hooks[i].target == target) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
// --- MinHook API ------------------------------------------------------------
|
||||
|
||||
int __stdcall MH_Initialize(void) { return g_ready ? MH_ERROR_ALREADY_INITIALIZED : MH_ERROR_NOT_INITIALIZED; }
|
||||
|
||||
// Hooks outlive every engine generation; "uninitialize" only turns them into pass-throughs.
|
||||
int __stdcall MH_Uninitialize(void) { HooksPassThroughAll(); return MH_OK; }
|
||||
|
||||
int __stdcall MH_CreateHook(void* target, void* detour, void** original)
|
||||
{
|
||||
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
|
||||
int st = MH_OK;
|
||||
EnterCriticalSection(&g_lock);
|
||||
int i = Find(target);
|
||||
if (i >= 0) {
|
||||
HookEntry* e = &g_hooks[i];
|
||||
if (e->created && e->generation == g_generation) {
|
||||
st = MH_ERROR_ALREADY_CREATED;
|
||||
} else {
|
||||
e->detour = detour;
|
||||
e->generation = g_generation;
|
||||
e->created = 1;
|
||||
SetSlot(i, 0);
|
||||
Want(i, 1);
|
||||
if (original) *original = e->trampoline;
|
||||
}
|
||||
} else if (g_count >= MAX_HOOKS) {
|
||||
st = MH_ERROR_MEMORY_ALLOC;
|
||||
} else {
|
||||
i = g_count;
|
||||
unsigned char* stub = g_stubs + i * STUB_SIZE;
|
||||
void* volatile* slot = &g_slots[i];
|
||||
stub[0] = 0xFF; stub[1] = 0x25; // jmp dword ptr [slot]
|
||||
*(void* volatile**)(stub + 2) = slot;
|
||||
stub[6] = 0xCC; stub[7] = 0xCC;
|
||||
FlushInstructionCache(GetCurrentProcess(), stub, STUB_SIZE);
|
||||
|
||||
void* tramp = NULL;
|
||||
st = p_create(target, stub, &tramp);
|
||||
if (st == MH_OK) {
|
||||
HookEntry* e = &g_hooks[i];
|
||||
e->target = target;
|
||||
e->trampoline = tramp;
|
||||
e->detour = detour;
|
||||
e->generation = g_generation;
|
||||
e->created = 1;
|
||||
e->enabled = 0;
|
||||
*slot = tramp; // pass-through until the engine enables it
|
||||
g_count++;
|
||||
e->patched = 0;
|
||||
Want(i, 1); // the patch goes in (slot passes through)
|
||||
st = MH_OK;
|
||||
if (original) *original = tramp;
|
||||
}
|
||||
}
|
||||
LeaveCriticalSection(&g_lock);
|
||||
return st;
|
||||
}
|
||||
|
||||
int __stdcall MH_RemoveHook(void* target)
|
||||
{
|
||||
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
|
||||
int st = MH_OK;
|
||||
EnterCriticalSection(&g_lock);
|
||||
int i = Find(target);
|
||||
if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED;
|
||||
else {
|
||||
SetSlot(i, 0);
|
||||
Want(i, 0); // original bytes back, like MinHook's remove
|
||||
g_hooks[i].created = 0;
|
||||
g_hooks[i].detour = NULL;
|
||||
}
|
||||
LeaveCriticalSection(&g_lock);
|
||||
return st;
|
||||
}
|
||||
|
||||
static int SetEnabled(void* target, int enable)
|
||||
{
|
||||
if (!g_ready) return MH_ERROR_NOT_INITIALIZED;
|
||||
int st = MH_OK;
|
||||
EnterCriticalSection(&g_lock);
|
||||
if (target == NULL) { // MH_ALL_HOOKS
|
||||
for (int i = 0; i < g_count; i++)
|
||||
if (g_hooks[i].created && g_hooks[i].enabled != enable) SetSlot(i, enable);
|
||||
} else {
|
||||
int i = Find(target);
|
||||
if (i < 0 || !g_hooks[i].created) st = MH_ERROR_NOT_CREATED;
|
||||
else if (g_hooks[i].enabled == enable) st = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED;
|
||||
else SetSlot(i, enable);
|
||||
}
|
||||
LeaveCriticalSection(&g_lock);
|
||||
return st;
|
||||
}
|
||||
|
||||
int __stdcall MH_EnableHook(void* target) { return SetEnabled(target, 1); }
|
||||
int __stdcall MH_DisableHook(void* target) { return SetEnabled(target, 0); }
|
||||
|
||||
const char* __stdcall MH_StatusToString(int status)
|
||||
{
|
||||
if (p_status) return p_status(status);
|
||||
return status == MH_OK ? "MH_OK" : "MH_UNKNOWN";
|
||||
}
|
||||
|
||||
// Lets the engine tell this facade from minhook.x86.dll (and an old NativeAOT loader).
|
||||
int __stdcall RcHooks_Version(void) { return 1; }
|
||||
int __stdcall RcHooks_Count(void) { return g_count; }
|
||||
407
native/Loader/Loader.c
Normal file
407
native/Loader/Loader.c
Normal file
|
|
@ -0,0 +1,407 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Loader.dll - native loader (docs/UNLOADABLE_ENGINE_PLAN.md, Phase 1)
|
||||
//
|
||||
// Injected into acclient.exe by RynthCore.Injector / the launcher, which call the
|
||||
// RynthCoreInit export on a remote thread (same contract as the old NativeAOT loader).
|
||||
//
|
||||
// Two engine hosts, chosen by looking at Runtime\RynthCore.Engine.dll:
|
||||
// - NativeAOT engine (a native DLL exporting RynthCoreEngineInit): staged to
|
||||
// .engine_loads\, LoadLibrary'd, never freed. Today's behaviour.
|
||||
// - Managed engine (a PE with a CLR header): the loader starts CoreCLR once from
|
||||
// Runtime\dotnet\ and hands the engine to RynthCore.Shim.dll (default ALC), which
|
||||
// loads each generation into a collectible AssemblyLoadContext and unloads it on
|
||||
// reload, so a reload gives its memory back.
|
||||
//
|
||||
// Either way the loader owns the reload event, the file watcher, the address-space
|
||||
// guard and a MinHook facade (Hooks.c): every hook is installed once, through a
|
||||
// permanent stub, and a reload only re-points the stub.
|
||||
// ============================================================================
|
||||
|
||||
#include "Loader.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
#define ENGINE_DLL_NAME "RynthCore.Engine.dll"
|
||||
#define ENGINE_INIT_EXPORT "RynthCoreEngineInit"
|
||||
#define ENGINE_SHUTDOWN_EXPORT "RynthCoreShutdown"
|
||||
#define ENGINE_REFUSED_EXPORT "RynthCoreReloadRefused"
|
||||
#define LOG_DIR "C:\\Games\\RynthCore\\Logs"
|
||||
#define STAGING_SUBDIR ".engine_loads"
|
||||
#define MIN_RELOAD_INTERVAL_MS 1500
|
||||
// A managed engine gives its memory back on reload, so the guard only has to keep
|
||||
// room for one more generation; the NativeAOT engine leaks every generation.
|
||||
#define MIN_FREE_MB_AOT 1200
|
||||
#define MIN_FREE_MB_CLR 500
|
||||
|
||||
typedef unsigned int (__stdcall *engine_u32_fn)(void* param);
|
||||
typedef unsigned int (__stdcall *engine_refused_fn)(int freeMb);
|
||||
|
||||
static volatile LONG g_initialized;
|
||||
static char g_loaderDir[MAX_PATH];
|
||||
static char g_enginePath[MAX_PATH];
|
||||
static int g_engineIsManaged;
|
||||
static HMODULE g_engineModule; // NativeAOT host only
|
||||
static int g_initCount;
|
||||
static HANDLE g_reloadEvent;
|
||||
static FILETIME g_canonicalWrite;
|
||||
static volatile LONG g_reloadInFlight;
|
||||
static volatile ULONGLONG g_lastReloadDone;
|
||||
static CRITICAL_SECTION g_logLock;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Logging: same per-client file and line format as the engine (LogPaths.cs).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
void LoaderLog(const char* level, const char* fmt, ...)
|
||||
{
|
||||
char msg[3072];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
_vsnprintf_s(msg, sizeof msg, _TRUNCATE, fmt, ap);
|
||||
va_end(ap);
|
||||
|
||||
SYSTEMTIME t;
|
||||
GetLocalTime(&t);
|
||||
char line[3300];
|
||||
int n = _snprintf_s(line, sizeof line, _TRUNCATE, "[%02d:%02d:%02d.%03d] [pid:%lu] [%s] [loader] %s\r\n",
|
||||
t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, GetCurrentProcessId(), level, msg);
|
||||
if (n < 0) n = (int)strlen(line);
|
||||
|
||||
char path[MAX_PATH];
|
||||
_snprintf_s(path, sizeof path, _TRUNCATE, LOG_DIR "\\RynthCore.%lu.log", GetCurrentProcessId());
|
||||
EnterCriticalSection(&g_logLock);
|
||||
CreateDirectoryA("C:\\Games\\RynthCore", NULL);
|
||||
CreateDirectoryA(LOG_DIR, NULL);
|
||||
for (int attempt = 0; attempt < 4; attempt++) {
|
||||
HANDLE h = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
if (h != INVALID_HANDLE_VALUE) {
|
||||
DWORD written;
|
||||
WriteFile(h, line, (DWORD)n, &written, NULL);
|
||||
CloseHandle(h);
|
||||
break;
|
||||
}
|
||||
Sleep(5);
|
||||
}
|
||||
LeaveCriticalSection(&g_logLock);
|
||||
OutputDebugStringA(line);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Address space
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
long LoaderFreeAddressSpaceMb(long* largestMb)
|
||||
{
|
||||
SYSTEM_INFO si;
|
||||
GetSystemInfo(&si);
|
||||
unsigned char* p = (unsigned char*)si.lpMinimumApplicationAddress;
|
||||
unsigned char* end = (unsigned char*)si.lpMaximumApplicationAddress;
|
||||
unsigned long long total = 0, largest = 0;
|
||||
MEMORY_BASIC_INFORMATION mbi;
|
||||
while (p < end && VirtualQuery(p, &mbi, sizeof mbi) == sizeof mbi) {
|
||||
if (mbi.RegionSize == 0) break;
|
||||
if (mbi.State == MEM_FREE) {
|
||||
total += mbi.RegionSize;
|
||||
if (mbi.RegionSize > largest) largest = mbi.RegionSize;
|
||||
}
|
||||
p = (unsigned char*)mbi.BaseAddress + mbi.RegionSize;
|
||||
}
|
||||
if (largestMb) *largestMb = (long)(largest / (1024 * 1024));
|
||||
return (long)(total / (1024 * 1024));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Engine file: staging and kind
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static int FileLastWrite(const char* path, FILETIME* out)
|
||||
{
|
||||
WIN32_FILE_ATTRIBUTE_DATA d;
|
||||
if (!GetFileAttributesExA(path, GetFileExInfoStandard, &d)) return 0;
|
||||
*out = d.ftLastWriteTime;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// 1 = the file is a .NET assembly (PE with a CLR header), 0 = native, -1 = unreadable.
|
||||
static int IsManagedPe(const char* path)
|
||||
{
|
||||
HANDLE h = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
if (h == INVALID_HANDLE_VALUE) return -1;
|
||||
unsigned char buf[4096];
|
||||
DWORD read = 0;
|
||||
BOOL ok = ReadFile(h, buf, sizeof buf, &read, NULL);
|
||||
CloseHandle(h);
|
||||
if (!ok || read < sizeof(IMAGE_DOS_HEADER)) return -1;
|
||||
IMAGE_DOS_HEADER* dos = (IMAGE_DOS_HEADER*)buf;
|
||||
if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 ||
|
||||
(DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS32) > read) return -1;
|
||||
IMAGE_NT_HEADERS32* nt = (IMAGE_NT_HEADERS32*)(buf + dos->e_lfanew);
|
||||
if (nt->Signature != IMAGE_NT_SIGNATURE) return -1;
|
||||
if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return 0;
|
||||
if (nt->OptionalHeader.NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR) return 0;
|
||||
return nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress != 0;
|
||||
}
|
||||
|
||||
static void CleanStaleStagingFiles(const char* stagingDir)
|
||||
{
|
||||
char pattern[MAX_PATH];
|
||||
_snprintf_s(pattern, sizeof pattern, _TRUNCATE, "%s\\RynthCore.Engine.p*.gen*.*", stagingDir); // .dll + .pdb
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE f = FindFirstFileA(pattern, &fd);
|
||||
if (f == INVALID_HANDLE_VALUE) return;
|
||||
do {
|
||||
char p[MAX_PATH];
|
||||
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", stagingDir, fd.cFileName);
|
||||
DeleteFileA(p); // fails for files a live process still maps: fine
|
||||
} while (FindNextFileA(f, &fd));
|
||||
FindClose(f);
|
||||
}
|
||||
|
||||
// Copies the canonical engine to .engine_loads\RynthCore.Engine.p<pid>.gen<N>.dll so the
|
||||
// canonical file is never locked (a developer can copy over it) and every generation is
|
||||
// a distinct module/assembly path.
|
||||
static int StageEngine(int generation, char* stagedPath, size_t cap)
|
||||
{
|
||||
char stagingDir[MAX_PATH];
|
||||
_snprintf_s(stagingDir, sizeof stagingDir, _TRUNCATE, "%s\\" STAGING_SUBDIR, g_loaderDir);
|
||||
CreateDirectoryA(stagingDir, NULL);
|
||||
CleanStaleStagingFiles(stagingDir);
|
||||
_snprintf_s(stagedPath, cap, _TRUNCATE, "%s\\RynthCore.Engine.p%lu.gen%d.dll",
|
||||
stagingDir, GetCurrentProcessId(), generation);
|
||||
if (!CopyFileA(g_enginePath, stagedPath, FALSE)) {
|
||||
LoaderLog("ERR", "StageEngine: copy to %s failed (error %lu)", stagedPath, GetLastError());
|
||||
return 0;
|
||||
}
|
||||
if (g_engineIsManaged) {
|
||||
// The debug symbols travel with the assembly so stack traces keep line numbers.
|
||||
char srcPdb[MAX_PATH], dstPdb[MAX_PATH];
|
||||
_snprintf_s(srcPdb, sizeof srcPdb, _TRUNCATE, "%s\\RynthCore.Engine.pdb", g_loaderDir);
|
||||
_snprintf_s(dstPdb, sizeof dstPdb, _TRUNCATE, "%.*s.pdb", (int)(strlen(stagedPath) - 4), stagedPath);
|
||||
CopyFileA(srcPdb, dstPdb, FALSE);
|
||||
}
|
||||
LoaderLog("INF", "Staged engine for gen %d at %s", generation, stagedPath);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Engine calls, whichever host
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static void* EngineExport(const char* name)
|
||||
{
|
||||
if (g_engineIsManaged) return ClrEngineExport(name);
|
||||
return g_engineModule ? (void*)GetProcAddress(g_engineModule, name) : NULL;
|
||||
}
|
||||
|
||||
static unsigned int LoadAndInitEngine(void)
|
||||
{
|
||||
g_initCount++;
|
||||
HooksBeginGeneration(g_initCount);
|
||||
|
||||
char staged[MAX_PATH];
|
||||
if (!StageEngine(g_initCount, staged, sizeof staged)) return 11;
|
||||
if (!FileLastWrite(g_enginePath, &g_canonicalWrite)) GetSystemTimeAsFileTime(&g_canonicalWrite);
|
||||
|
||||
if (g_engineIsManaged) {
|
||||
int rc = ClrLoadEngine(g_initCount, staged);
|
||||
if (rc != 0) {
|
||||
LoaderLog("ERR", "Managed engine gen %d failed to load (rc=%d)", g_initCount, rc);
|
||||
return 4;
|
||||
}
|
||||
} else {
|
||||
HMODULE m = LoadLibraryA(staged);
|
||||
if (!m) {
|
||||
LoaderLog("ERR", "LoadLibrary failed for engine (path=%s, error %lu)", staged, GetLastError());
|
||||
return 4;
|
||||
}
|
||||
g_engineModule = m;
|
||||
LoaderLog("INF", "Engine module loaded at 0x%08p from %s", (void*)m, staged);
|
||||
}
|
||||
|
||||
engine_u32_fn init = (engine_u32_fn)EngineExport(ENGINE_INIT_EXPORT);
|
||||
if (!init) {
|
||||
LoaderLog("ERR", "Engine missing export '%s'", ENGINE_INIT_EXPORT);
|
||||
return 5;
|
||||
}
|
||||
unsigned int rc = init((void*)(INT_PTR)g_initCount);
|
||||
// The hooks the engine installed during init go in now, in one freeze, before the
|
||||
// injector resumes AC's main thread (first launch) or the new generation runs.
|
||||
HooksFlush();
|
||||
LoaderLog("INF", ENGINE_INIT_EXPORT "(initCount=%d) returned %u.", g_initCount, rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void Reload(void)
|
||||
{
|
||||
long largest;
|
||||
long freeBefore = LoaderFreeAddressSpaceMb(&largest);
|
||||
LoaderLog("INF", "Reload requested (gen %d, %ld MB free, largest %ld MB).", g_initCount, freeBefore, largest);
|
||||
|
||||
engine_u32_fn shutdown = (engine_u32_fn)EngineExport(ENGINE_SHUTDOWN_EXPORT);
|
||||
if (shutdown) {
|
||||
unsigned int rc = shutdown(NULL);
|
||||
LoaderLog("INF", ENGINE_SHUTDOWN_EXPORT " returned %u.", rc);
|
||||
} else {
|
||||
LoaderLog("WRN", "Engine has no '%s' export; skipping graceful shutdown.", ENGINE_SHUTDOWN_EXPORT);
|
||||
}
|
||||
|
||||
// Whatever the engine left enabled now passes straight through to AC.
|
||||
HooksPassThroughAll();
|
||||
ServicesReleaseAll();
|
||||
Sleep(150);
|
||||
|
||||
if (g_engineIsManaged) {
|
||||
ClrUnloadEngine();
|
||||
} else if (g_engineModule) {
|
||||
// A NativeAOT module can't be freed (its runtime keeps threads with frames in it).
|
||||
LoaderLog("INF", "Reload: NativeAOT engine 0x%08p left mapped (can't unload).", (void*)g_engineModule);
|
||||
g_engineModule = NULL;
|
||||
}
|
||||
|
||||
unsigned int rc = LoadAndInitEngine();
|
||||
long freeAfter = LoaderFreeAddressSpaceMb(&largest);
|
||||
LoaderLog(rc == 0 ? "INF" : "ERR", "Reload: %s (gen %d, %ld MB free, %+ld MB vs before the reload).",
|
||||
rc == 0 ? "complete" : "re-init FAILED", g_initCount, freeAfter, freeAfter - freeBefore);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reload triggers: the engine's named event, and the canonical DLL changing on disk
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static DWORD WINAPI ReloadWatcher(LPVOID unused)
|
||||
{
|
||||
(void)unused;
|
||||
for (;;) {
|
||||
if (WaitForSingleObject(g_reloadEvent, INFINITE) != WAIT_OBJECT_0) { Sleep(100); continue; }
|
||||
|
||||
ULONGLONG last = g_lastReloadDone;
|
||||
if (last != 0 && GetTickCount64() - last < MIN_RELOAD_INTERVAL_MS) {
|
||||
LoaderLog("INF", "ReloadWatcher: signal %llu ms after the last reload; coalesced.", GetTickCount64() - last);
|
||||
continue;
|
||||
}
|
||||
|
||||
long minFree = g_engineIsManaged ? MIN_FREE_MB_CLR : MIN_FREE_MB_AOT;
|
||||
long freeMb = LoaderFreeAddressSpaceMb(NULL);
|
||||
if (freeMb < minFree) {
|
||||
LoaderLog("WRN", "ReloadWatcher: reload REFUSED - only %ld MB of address space free (need %ld MB). "
|
||||
"Restart the client to load the new engine.", freeMb, minFree);
|
||||
engine_refused_fn refused = (engine_refused_fn)EngineExport(ENGINE_REFUSED_EXPORT);
|
||||
if (refused) refused((int)freeMb);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (InterlockedCompareExchange(&g_reloadInFlight, 1, 0) != 0) {
|
||||
LoaderLog("INF", "ReloadWatcher: reload already in flight; coalesced.");
|
||||
continue;
|
||||
}
|
||||
Reload();
|
||||
g_lastReloadDone = GetTickCount64();
|
||||
InterlockedExchange(&g_reloadInFlight, 0);
|
||||
|
||||
int drained = 0;
|
||||
while (WaitForSingleObject(g_reloadEvent, 0) == WAIT_OBJECT_0) drained++;
|
||||
if (drained) LoaderLog("INF", "ReloadWatcher: drained %d signal(s) received during the reload.", drained);
|
||||
}
|
||||
}
|
||||
|
||||
static DWORD WINAPI FileWatcher(LPVOID unused)
|
||||
{
|
||||
(void)unused;
|
||||
for (;;) {
|
||||
Sleep(1000);
|
||||
FILETIME now;
|
||||
if (!FileLastWrite(g_enginePath, &now) || CompareFileTime(&now, &g_canonicalWrite) <= 0) continue;
|
||||
// Let the writer (cp, dotnet publish) finish before staging from it.
|
||||
Sleep(500);
|
||||
FILETIME stable;
|
||||
if (!FileLastWrite(g_enginePath, &stable) || CompareFileTime(&stable, &now) != 0) continue;
|
||||
LoaderLog("INF", "FileWatcher: %s changed; signaling reload.", g_enginePath);
|
||||
g_canonicalWrite = stable;
|
||||
SetEvent(g_reloadEvent);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exports
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const char* LoaderDirectory(void) { return g_loaderDir; }
|
||||
int LoaderGeneration(void) { return g_initCount; }
|
||||
|
||||
unsigned int __stdcall RynthCoreInit(void* param)
|
||||
{
|
||||
(void)param;
|
||||
if (InterlockedCompareExchange(&g_initialized, 1, 0) != 0) {
|
||||
LoaderLog("WRN", "RynthCoreInit called twice; ignoring the second call.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
HMODULE self = NULL;
|
||||
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
(LPCSTR)&RynthCoreInit, &self);
|
||||
GetModuleFileNameA(self, g_loaderDir, MAX_PATH);
|
||||
char* slash = strrchr(g_loaderDir, '\\');
|
||||
if (slash) *slash = 0;
|
||||
|
||||
LoaderLog("INF", "RynthCoreInit (native loader %s) starting in %s.", LOADER_VERSION, g_loaderDir);
|
||||
{
|
||||
// Test clients (tools\TestClient, scripts\Test-Clr*.ps1) say so first, so monitors can skip them.
|
||||
char tag[128];
|
||||
if (GetEnvironmentVariableA("RYNTHCORE_TEST_CLIENT", tag, sizeof tag) > 0)
|
||||
LoaderLog("INF", "TestClient: %s", tag);
|
||||
}
|
||||
|
||||
_snprintf_s(g_enginePath, sizeof g_enginePath, _TRUNCATE, "%s\\" ENGINE_DLL_NAME, g_loaderDir);
|
||||
int managed = IsManagedPe(g_enginePath);
|
||||
if (managed < 0) {
|
||||
LoaderLog("ERR", "FATAL: engine DLL not found or unreadable at %s", g_enginePath);
|
||||
return 3;
|
||||
}
|
||||
g_engineIsManaged = managed;
|
||||
long largest;
|
||||
long freeMb = LoaderFreeAddressSpaceMb(&largest);
|
||||
LoaderLog("INF", "Engine is %s; %ld MB of address space free (largest %ld MB).",
|
||||
managed ? "a managed assembly: hosting CoreCLR" : "NativeAOT", freeMb, largest);
|
||||
|
||||
if (!HooksInit(g_loaderDir)) {
|
||||
LoaderLog("ERR", "FATAL: MinHook could not be loaded from %s", g_loaderDir);
|
||||
return 6;
|
||||
}
|
||||
if (managed) {
|
||||
int rc = ClrStart(g_loaderDir);
|
||||
if (rc != 0) {
|
||||
LoaderLog("ERR", "FATAL: CoreCLR did not start (rc=%d)", rc);
|
||||
return 7;
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int rc = LoadAndInitEngine();
|
||||
if (rc != 0) return rc;
|
||||
|
||||
char eventName[128];
|
||||
_snprintf_s(eventName, sizeof eventName, _TRUNCATE, "Local\\RynthCore.Engine.RequestReload.p%lu", GetCurrentProcessId());
|
||||
g_reloadEvent = CreateEventA(NULL, FALSE, FALSE, eventName);
|
||||
if (!g_reloadEvent) {
|
||||
LoaderLog("WRN", "CreateEvent failed (error %lu); reload disabled.", GetLastError());
|
||||
return 0;
|
||||
}
|
||||
HANDLE t = CreateThread(NULL, 0, ReloadWatcher, NULL, 0, NULL);
|
||||
if (t) CloseHandle(t);
|
||||
t = CreateThread(NULL, 0, FileWatcher, NULL, 0, NULL);
|
||||
if (t) CloseHandle(t);
|
||||
LoaderLog("INF", "Reload watcher armed on '%s'; file watcher on '%s' (poll 1 s).", eventName, g_enginePath);
|
||||
return 0;
|
||||
}
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID reserved)
|
||||
{
|
||||
(void)h; (void)reserved;
|
||||
if (reason == DLL_PROCESS_ATTACH) {
|
||||
InitializeCriticalSection(&g_logLock);
|
||||
DisableThreadLibraryCalls(h);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
16
native/Loader/Loader.def
Normal file
16
native/Loader/Loader.def
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
LIBRARY "RynthCore.Loader.dll"
|
||||
EXPORTS
|
||||
RynthCoreInit
|
||||
MH_Initialize
|
||||
MH_Uninitialize
|
||||
MH_CreateHook
|
||||
MH_RemoveHook
|
||||
MH_EnableHook
|
||||
MH_DisableHook
|
||||
MH_StatusToString
|
||||
RcHooks_Version
|
||||
RcHooks_Count
|
||||
RcSubclass_Install
|
||||
RcSubclass_Release
|
||||
RcApiStub
|
||||
RcServices_Version
|
||||
26
native/Loader/Loader.h
Normal file
26
native/Loader/Loader.h
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
#pragma once
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
|
||||
#define LOADER_VERSION "2.0"
|
||||
|
||||
// Loader.c
|
||||
void LoaderLog(const char* level, const char* fmt, ...);
|
||||
long LoaderFreeAddressSpaceMb(long* largestMb);
|
||||
const char* LoaderDirectory(void);
|
||||
int LoaderGeneration(void);
|
||||
|
||||
// Hooks.c: MinHook facade (see the header comment there)
|
||||
int HooksInit(const char* loaderDir);
|
||||
void HooksBeginGeneration(int generation);
|
||||
void HooksPassThroughAll(void);
|
||||
void HooksFlush(void);
|
||||
|
||||
// Services.c: permanent window subclass + plugin API stubs
|
||||
void ServicesReleaseAll(void);
|
||||
|
||||
// Clr.c: CoreCLR host for a managed engine
|
||||
int ClrStart(const char* loaderDir);
|
||||
int ClrLoadEngine(int generation, const char* stagedPath);
|
||||
void ClrUnloadEngine(void);
|
||||
void* ClrEngineExport(const char* name);
|
||||
176
native/Loader/Services.c
Normal file
176
native/Loader/Services.c
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
// ============================================================================
|
||||
// Services.c - the other native entry points the engine hands out, made permanent
|
||||
// (docs/UNLOADABLE_ENGINE_PLAN.md: "nothing native points into collectible code").
|
||||
//
|
||||
// 1. Window subclass: RcSubclass_Install puts the loader's own WndProc on a window,
|
||||
// once for the life of the process, and forwards to the current engine's handler.
|
||||
// RcSubclass_Release (and every reload) makes it a pure pass-through to the window's
|
||||
// previous proc. The engine never has to unhook, so a foreign subclasser stacked on
|
||||
// top of us (Decal, DirectInput) can never be ripped out of the chain, and nothing
|
||||
// in the chain ever points at an unloaded engine.
|
||||
//
|
||||
// 2. Plugin API stubs: RcApiStub(index, fn) returns a permanent stub for table slot
|
||||
// `index` that jumps to `fn`. Plugins copy the table and can't give it back; after a
|
||||
// reload the slots are empty until the next engine fills them, and a plugin thread
|
||||
// that calls one in between waits (any calling convention: registers and stack are
|
||||
// untouched) and then runs the new engine's function.
|
||||
// ============================================================================
|
||||
|
||||
#include "Loader.h"
|
||||
|
||||
// --- 1. window subclass --------------------------------------------------------
|
||||
|
||||
#define MAX_SUBCLASSED 16
|
||||
|
||||
typedef LRESULT (CALLBACK *wndproc_fn)(HWND, UINT, WPARAM, LPARAM);
|
||||
|
||||
typedef struct Subclass {
|
||||
HWND hwnd;
|
||||
WNDPROC previous; // the proc we replaced (AC's, or whoever was there)
|
||||
wndproc_fn volatile handler; // current engine's handler, or NULL = pass-through
|
||||
} Subclass;
|
||||
|
||||
static Subclass g_subclassed[MAX_SUBCLASSED];
|
||||
static volatile LONG g_subclassCount;
|
||||
static CRITICAL_SECTION g_servicesLock;
|
||||
static int g_servicesReady;
|
||||
|
||||
static void EnsureServices(void)
|
||||
{
|
||||
if (!g_servicesReady) {
|
||||
InitializeCriticalSection(&g_servicesLock);
|
||||
g_servicesReady = 1;
|
||||
}
|
||||
}
|
||||
|
||||
static Subclass* FindSubclass(HWND hwnd)
|
||||
{
|
||||
LONG n = g_subclassCount;
|
||||
for (LONG i = 0; i < n; i++)
|
||||
if (g_subclassed[i].hwnd == hwnd) return &g_subclassed[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK LoaderWndProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l)
|
||||
{
|
||||
Subclass* s = FindSubclass(hwnd);
|
||||
if (!s) return DefWindowProcA(hwnd, msg, w, l);
|
||||
wndproc_fn h = s->handler;
|
||||
if (h) return h(hwnd, msg, w, l);
|
||||
return CallWindowProcA(s->previous, hwnd, msg, w, l);
|
||||
}
|
||||
|
||||
// Returns 1 and the window's previous proc (what the engine's handler must forward to).
|
||||
int __stdcall RcSubclass_Install(HWND hwnd, void* handler, void** previousOut)
|
||||
{
|
||||
EnsureServices();
|
||||
int ok = 1;
|
||||
EnterCriticalSection(&g_servicesLock);
|
||||
Subclass* s = FindSubclass(hwnd);
|
||||
if (!s) {
|
||||
if (g_subclassCount >= MAX_SUBCLASSED) ok = 0;
|
||||
else {
|
||||
s = &g_subclassed[g_subclassCount];
|
||||
s->hwnd = hwnd;
|
||||
s->handler = NULL;
|
||||
SetLastError(0);
|
||||
s->previous = (WNDPROC)SetWindowLongA(hwnd, GWL_WNDPROC, (LONG)(LONG_PTR)LoaderWndProc);
|
||||
if (!s->previous) {
|
||||
LoaderLog("ERR", "Subclass: SetWindowLong on 0x%p failed (error %lu)", (void*)hwnd, GetLastError());
|
||||
ok = 0;
|
||||
} else {
|
||||
InterlockedIncrement(&g_subclassCount);
|
||||
LoaderLog("INF", "Subclass: 0x%p subclassed for good (previous proc 0x%p).", (void*)hwnd, (void*)s->previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ok) {
|
||||
s->handler = (wndproc_fn)handler;
|
||||
if (previousOut) *previousOut = (void*)s->previous;
|
||||
}
|
||||
LeaveCriticalSection(&g_servicesLock);
|
||||
return ok;
|
||||
}
|
||||
|
||||
int __stdcall RcSubclass_Release(HWND hwnd)
|
||||
{
|
||||
Subclass* s = FindSubclass(hwnd);
|
||||
if (!s) return 0;
|
||||
s->handler = NULL;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// --- 2. plugin API stubs --------------------------------------------------------
|
||||
|
||||
#define MAX_API_STUBS 512
|
||||
#define API_STUB_SIZE 32
|
||||
|
||||
static void* volatile g_apiSlots[MAX_API_STUBS];
|
||||
static unsigned char* g_apiStubs;
|
||||
static volatile LONG g_apiWaitLogged;
|
||||
|
||||
// Called from a stub whose slot is empty (between engine generations). Blocks until the
|
||||
// next engine fills the table. stdcall, one argument; the stub saves every register.
|
||||
static void __stdcall ApiWait(int index)
|
||||
{
|
||||
DWORD start = GetTickCount();
|
||||
int logged = 0;
|
||||
while (g_apiSlots[index] == NULL) {
|
||||
Sleep(10);
|
||||
if (!logged && GetTickCount() - start > 10000) {
|
||||
logged = 1;
|
||||
LoaderLog("WRN", "ApiStub: a plugin thread has waited 10 s for API slot %d (no engine loaded?).", index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void BuildApiStub(int i)
|
||||
{
|
||||
unsigned char* p = g_apiStubs + i * API_STUB_SIZE;
|
||||
unsigned char* start = p;
|
||||
void* volatile* slot = &g_apiSlots[i];
|
||||
*p++ = 0xA1; *(void* volatile**)p = slot; p += 4; // mov eax, [slot]
|
||||
*p++ = 0x85; *p++ = 0xC0; // test eax, eax
|
||||
*p++ = 0x74; *p++ = 0x02; // jz +2 (wait)
|
||||
*p++ = 0xFF; *p++ = 0xE0; // jmp eax
|
||||
*p++ = 0x60; // pushad
|
||||
*p++ = 0x68; *(int*)p = i; p += 4; // push i
|
||||
*p++ = 0xE8; *(int*)p = (int)((unsigned char*)ApiWait - (p + 4)); p += 4; // call ApiWait
|
||||
*p++ = 0x61; // popad
|
||||
*p++ = 0xE9; *(int*)p = (int)(start - (p + 4)); p += 4; // jmp start
|
||||
while (p < start + API_STUB_SIZE) *p++ = 0xCC;
|
||||
}
|
||||
|
||||
void* __stdcall RcApiStub(int index, void* fn)
|
||||
{
|
||||
EnsureServices();
|
||||
if (index < 0 || index >= MAX_API_STUBS) return fn;
|
||||
EnterCriticalSection(&g_servicesLock);
|
||||
if (!g_apiStubs) {
|
||||
g_apiStubs = (unsigned char*)VirtualAlloc(NULL, MAX_API_STUBS * API_STUB_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
|
||||
if (g_apiStubs) {
|
||||
for (int i = 0; i < MAX_API_STUBS; i++) BuildApiStub(i);
|
||||
FlushInstructionCache(GetCurrentProcess(), g_apiStubs, MAX_API_STUBS * API_STUB_SIZE);
|
||||
}
|
||||
}
|
||||
LeaveCriticalSection(&g_servicesLock);
|
||||
if (!g_apiStubs) return fn;
|
||||
// Already one of ours (a table wrapped twice): never point a slot at a stub.
|
||||
if ((unsigned char*)fn >= g_apiStubs && (unsigned char*)fn < g_apiStubs + MAX_API_STUBS * API_STUB_SIZE)
|
||||
return fn;
|
||||
InterlockedExchangePointer((PVOID volatile*)&g_apiSlots[index], fn);
|
||||
return g_apiStubs + index * API_STUB_SIZE;
|
||||
}
|
||||
|
||||
// Every reload: nothing we hand out may keep pointing into the old engine.
|
||||
void ServicesReleaseAll(void)
|
||||
{
|
||||
EnsureServices();
|
||||
EnterCriticalSection(&g_servicesLock);
|
||||
for (LONG i = 0; i < g_subclassCount; i++) g_subclassed[i].handler = NULL;
|
||||
for (int i = 0; i < MAX_API_STUBS; i++) g_apiSlots[i] = NULL;
|
||||
LeaveCriticalSection(&g_servicesLock);
|
||||
LoaderLog("INF", "Services: %ld window subclass(es) pass through, plugin API slots emptied until the next engine.", g_subclassCount);
|
||||
}
|
||||
|
||||
int __stdcall RcServices_Version(void) { return 1; }
|
||||
Loading…
Reference in a new issue