client/runtime/game_host.c (20978B)
1 #define WIN32_LEAN_AND_MEAN 2 #include <windows.h> 3 #include <shellapi.h> 4 #include <tlhelp32.h> 5 #include <stdint.h> 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <string.h> 9 #include "native32.h" 10 #include "game-modules.h" 11 #include "game-data.h" 12 13 static unsigned char module_state[sizeof(game_modules) / sizeof(game_modules[0])]; 14 static uint32_t module_span[sizeof(game_modules) / sizeof(game_modules[0])]; 15 static CRITICAL_SECTION loader_lock; 16 static int client_index, guest_argc; 17 static char **guest_argv; 18 static char guest_directory[MAX_PATH], guest_filename[MAX_PATH]; 19 static char *guest_command_line; 20 static void attach_module_locked(int index, int startup); 21 static void patch_native_modules(void); 22 static uintptr_t native_hook(const char *name); 23 24 static void fail(const char *message, const char *name) 25 { 26 fprintf(stderr, "[game-host] %s: %s (error %lu)\n", message, name, GetLastError()); 27 fflush(stderr); 28 ExitProcess(3); 29 } 30 31 /* Registered after native32's handler, so its successful NX callback traps 32 * never reach this observer. Leave exception dispatch and termination intact. */ 33 static LONG CALLBACK host_fault(EXCEPTION_POINTERS *exception) 34 { 35 EXCEPTION_RECORD *record = exception->ExceptionRecord; 36 if (record->ExceptionCode == DBG_PRINTEXCEPTION_C) return EXCEPTION_CONTINUE_SEARCH; 37 fprintf(stderr, "[game-host] exception code=%08lx address=%p eip=%08lx thread=%lu\n", 38 record->ExceptionCode, record->ExceptionAddress, exception->ContextRecord->Eip, 39 GetCurrentThreadId()); 40 HMODULE module; 41 if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, 42 (LPCSTR)record->ExceptionAddress, &module)) { 43 char path[MAX_PATH] = {0}; 44 GetModuleFileNameA(module, path, sizeof(path)); 45 fprintf(stderr, "[game-host] module=%s base=%08x rva=%08x\n", path, 46 (uint32_t)(uintptr_t)module, (uint32_t)((uintptr_t)record->ExceptionAddress - (uintptr_t)module)); 47 } 48 fprintf(stderr, "[game-host] native eax=%08lx ecx=%08lx edx=%08lx esp=%08lx ebp=%08lx\n", 49 exception->ContextRecord->Eax, exception->ContextRecord->Ecx, exception->ContextRecord->Edx, 50 exception->ContextRecord->Esp, exception->ContextRecord->Ebp); 51 if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) { 52 ULONG_PTR operation = record->ExceptionInformation[0]; 53 fprintf(stderr, "[game-host] access=%s address=%08lx\n", 54 operation == 0 ? "read" : operation == 1 ? "write" : operation == 8 ? "execute" : "unknown", 55 (unsigned long)record->ExceptionInformation[1]); 56 } 57 /* These are the shared machine globals, which may belong to another guest 58 * thread while the faulting thread is inside a native call. */ 59 fprintf(stderr, "[game-host] machine func=%08x eax=%08x ecx=%08x edx=%08x esp=%08x " 60 "ebx=%08x esi=%08x edi=%08x ebp=%08x\n", 61 g_cur_func, g_eax, g_ecx, g_edx, g_esp, g_ebx, g_esi, g_edi, g_ebp); 62 native32_dump_icalls(16); 63 fflush(stderr); 64 return EXCEPTION_CONTINUE_SEARCH; 65 } 66 67 static IMAGE_NT_HEADERS32 *headers(uint32_t base) 68 { 69 return (void *)(uintptr_t)(base + ((IMAGE_DOS_HEADER *)(uintptr_t)base)->e_lfanew); 70 } 71 72 static int module_named(const char *name) 73 { 74 const char *file = name; 75 for (const char *p = name; *p; p++) if (*p == '\\' || *p == '/') file = p + 1; 76 for (int i = 0; i < game_module_count; i++) 77 if (!_stricmp(file, game_modules[i].name)) return i; 78 return -1; 79 } 80 81 static int module_handle(HMODULE handle) 82 { 83 for (int i = 0; i < game_module_count; i++) 84 if (game_modules[i].base == (uint32_t)(uintptr_t)handle) return i; 85 return -1; 86 } 87 88 static void module_entry_locked(int index, MODULEENTRY32 *entry) 89 { 90 DWORD size = entry->dwSize; 91 memset(entry, 0, sizeof(*entry)); 92 entry->dwSize = size; 93 entry->th32ProcessID = GetCurrentProcessId(); 94 entry->GlblcntUsage = entry->ProccntUsage = 1; 95 entry->modBaseAddr = (BYTE *)(uintptr_t)game_modules[index].base; 96 entry->modBaseSize = module_span[index]; 97 entry->hModule = (HMODULE)(uintptr_t)game_modules[index].base; 98 snprintf(entry->szModule, sizeof(entry->szModule), "%s", game_modules[index].name); 99 snprintf(entry->szExePath, sizeof(entry->szExePath), "%s\\%s", guest_directory, game_modules[index].name); 100 } 101 102 /* The caller's previous hModule is the guest cursor, so independent snapshots 103 * need no extra handle state. The guest prefix reflects current attach state; 104 * the native entries retain the OS snapshot's contents and ordering. */ 105 static BOOL WINAPI host_Module32First(HANDLE snapshot, MODULEENTRY32 *entry) 106 { 107 if (!Module32First(snapshot, entry)) return FALSE; 108 if (entry->th32ProcessID != GetCurrentProcessId()) return TRUE; 109 EnterCriticalSection(&loader_lock); 110 for (int i = 0; i < game_module_count; i++) if (module_state[i]) { 111 module_entry_locked(i, entry); 112 break; 113 } 114 LeaveCriticalSection(&loader_lock); 115 return TRUE; 116 } 117 118 static BOOL WINAPI host_Module32Next(HANDLE snapshot, MODULEENTRY32 *entry) 119 { 120 int index = entry->th32ProcessID == GetCurrentProcessId() ? module_handle(entry->hModule) : -1; 121 if (index < 0) return Module32Next(snapshot, entry); 122 EnterCriticalSection(&loader_lock); 123 for (int i = index + 1; i < game_module_count; i++) if (module_state[i]) { 124 module_entry_locked(i, entry); 125 LeaveCriticalSection(&loader_lock); 126 return TRUE; 127 } 128 LeaveCriticalSection(&loader_lock); 129 return Module32First(snapshot, entry); 130 } 131 132 /* These native wrappers also serve vendor DLL imports, keeping their dynamic 133 * loads inside the same guest module graph as translated game calls. */ 134 static HMODULE WINAPI host_LoadLibraryA(LPCSTR name) 135 { 136 int index = module_named(name); 137 if (index >= 0) { 138 EnterCriticalSection(&loader_lock); 139 attach_module_locked(index, 0); 140 LeaveCriticalSection(&loader_lock); 141 return (HMODULE)(uintptr_t)game_modules[index].base; 142 } 143 HMODULE result = LoadLibraryA(name); 144 if (result) patch_native_modules(); 145 return result; 146 } 147 148 static HMODULE WINAPI host_GetModuleHandleA(LPCSTR name) 149 { 150 if (!name) return (HMODULE)(uintptr_t)game_modules[client_index].base; 151 int index = module_named(name); 152 if (index < 0) return GetModuleHandleA(name); 153 EnterCriticalSection(&loader_lock); 154 HMODULE result = module_state[index] ? (HMODULE)(uintptr_t)game_modules[index].base : NULL; 155 LeaveCriticalSection(&loader_lock); 156 if (!result) SetLastError(ERROR_MOD_NOT_FOUND); 157 return result; 158 } 159 160 static FARPROC WINAPI host_GetProcAddress(HMODULE module, LPCSTR name) 161 { 162 if (module_handle(module) < 0) { 163 if ((uintptr_t)name > 0xffff && (module == GetModuleHandleA("kernel32.dll") || 164 module == GetModuleHandleA("shell32.dll") || module == GetModuleHandleA("msvcrt.dll"))) { 165 uintptr_t hook = native_hook(name); 166 if (hook) return (FARPROC)hook; 167 } 168 return GetProcAddress(module, name); 169 } 170 FARPROC result = (FARPROC)(uintptr_t)native32_export((uint32_t)(uintptr_t)module, name); 171 if (!result) SetLastError(ERROR_PROC_NOT_FOUND); 172 return result; 173 } 174 175 static BOOL WINAPI host_FreeLibrary(HMODULE module) 176 { 177 if (module_handle(module) >= 0) 178 fail("guest DLL unloading is not implemented", game_modules[module_handle(module)].name); 179 return FreeLibrary(module); 180 } 181 182 static BOOL WINAPI host_DisableThreadLibraryCalls(HMODULE module) 183 { 184 if (module_handle(module) >= 0) return TRUE; 185 return DisableThreadLibraryCalls(module); 186 } 187 188 static DWORD WINAPI host_GetModuleFileNameA(HMODULE module, LPSTR output, DWORD capacity) 189 { 190 int index = module ? module_handle(module) : client_index; 191 if (index < 0) return GetModuleFileNameA(module, output, capacity); 192 char path[MAX_PATH]; 193 snprintf(path, sizeof(path), "%s\\%s", guest_directory, game_modules[index].name); 194 DWORD length = (DWORD)strlen(path); 195 if (capacity <= length) { 196 if (capacity) { memcpy(output, path, capacity - 1); output[capacity - 1] = 0; } 197 SetLastError(ERROR_INSUFFICIENT_BUFFER); 198 return capacity; 199 } 200 memcpy(output, path, length + 1); 201 return length; 202 } 203 204 static LPSTR WINAPI host_GetCommandLineA(void) { return guest_command_line; } 205 206 static void WINAPI host_OutputDebugStringA(LPCSTR message) 207 { 208 DWORD error = GetLastError(); 209 fprintf(stderr, "[game-debug] %s\n", message); 210 fflush(stderr); 211 SetLastError(error); 212 OutputDebugStringA(message); 213 } 214 215 static int __cdecl host___getmainargs(int *argc, char ***argv, char ***environment, 216 int wildcard, void *startup) 217 { 218 (void)wildcard; 219 (void)startup; 220 *argc = guest_argc; 221 *argv = guest_argv; 222 *environment = _environ; 223 return 0; 224 } 225 226 static BOOL WINAPI host_VirtualProtect(LPVOID address, SIZE_T size, DWORD protection, PDWORD old) 227 { 228 if (protection & (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)) { 229 uint64_t start = (uintptr_t)address, end = start + size; 230 for (int i = 0; i < game_module_count; i++) 231 if (start < (uint64_t)game_modules[i].base + module_span[i] && end > game_modules[i].base) 232 fail("refusing executable guest image protection", game_modules[i].name); 233 } 234 return VirtualProtect(address, size, protection, old); 235 } 236 237 /* Child process routing must be implemented before game code can start an 238 * original executable from the client directory. Refuse these calls explicitly. */ 239 static BOOL WINAPI host_CreateProcessA(LPCSTR application, LPSTR command, LPSECURITY_ATTRIBUTES process, 240 LPSECURITY_ATTRIBUTES thread, BOOL inherit, DWORD flags, 241 LPVOID environment, LPCSTR directory, LPSTARTUPINFOA startup, 242 LPPROCESS_INFORMATION information) 243 { 244 (void)process; (void)thread; (void)inherit; (void)flags; (void)environment; 245 (void)directory; (void)startup; (void)information; 246 fail("child process routing is not implemented", application ? application : command); 247 return FALSE; 248 } 249 250 static BOOL WINAPI host_CreateProcessW(LPCWSTR application, LPWSTR command, LPSECURITY_ATTRIBUTES process, 251 LPSECURITY_ATTRIBUTES thread, BOOL inherit, DWORD flags, 252 LPVOID environment, LPCWSTR directory, LPSTARTUPINFOW startup, 253 LPPROCESS_INFORMATION information) 254 { 255 (void)application; (void)command; (void)process; (void)thread; (void)inherit; 256 (void)flags; (void)environment; (void)directory; (void)startup; (void)information; 257 fail("child process routing is not implemented", "CreateProcessW"); 258 return FALSE; 259 } 260 261 static void vendor_child_path(const char *file, const char *directory, char *path) 262 { 263 char candidate[MAX_PATH], expected[MAX_PATH]; 264 if (file[0] == '\\' || file[0] == '/' || file[1] == ':') 265 snprintf(candidate, sizeof(candidate), "%s", file); 266 else 267 snprintf(candidate, sizeof(candidate), "%s\\%s", directory ? directory : guest_directory, file); 268 DWORD length = GetFullPathNameA(candidate, MAX_PATH, path, NULL); 269 snprintf(expected, sizeof(expected), "%s\\dxdiag.exe", guest_directory); 270 if (!length || length >= MAX_PATH || _stricmp(path, expected)) 271 fail("child executable is outside the permitted vendor path", file); 272 273 } 274 275 static HINSTANCE WINAPI host_ShellExecuteA(HWND window, LPCSTR operation, LPCSTR file, 276 LPCSTR parameters, LPCSTR directory, INT show) 277 { 278 char path[MAX_PATH]; 279 vendor_child_path(file, directory, path); 280 return ShellExecuteA(window, operation, path, parameters, directory, show); 281 } 282 283 static BOOL WINAPI host_ShellExecuteExA(SHELLEXECUTEINFOA *information) 284 { 285 char path[MAX_PATH]; 286 vendor_child_path(information->lpFile, information->lpDirectory, path); 287 const char *file = information->lpFile; 288 information->lpFile = path; 289 BOOL result = ShellExecuteExA(information); 290 information->lpFile = file; 291 return result; 292 } 293 294 static intptr_t __cdecl host__spawnv(int mode, const char *file, const char *const *arguments) 295 { 296 (void)mode; (void)arguments; 297 fail("CRT child routing is not implemented", file); 298 return -1; 299 } 300 301 static intptr_t __cdecl host__execv(const char *file, const char *const *arguments) 302 { 303 (void)arguments; 304 fail("CRT child routing is not implemented", file); 305 return -1; 306 } 307 #define host__execvp host__execv 308 309 static intptr_t __cdecl host__execve(const char *file, const char *const *arguments, 310 const char *const *environment) 311 { 312 (void)environment; 313 return host__execv(file, arguments); 314 } 315 316 static int __cdecl host_system(const char *command) 317 { 318 fail("command shell routing is not implemented", command); 319 return -1; 320 } 321 322 /* Use the existing native ABI bridge for both stdcall and CRT cdecl wrappers. */ 323 #define HOST_APIS(X) \ 324 X(LoadLibraryA) X(GetModuleHandleA) X(GetProcAddress) X(FreeLibrary) X(Module32First) X(Module32Next) \ 325 X(DisableThreadLibraryCalls) X(GetModuleFileNameA) X(GetCommandLineA) X(OutputDebugStringA) \ 326 X(__getmainargs) X(VirtualProtect) X(CreateProcessA) X(CreateProcessW) \ 327 X(ShellExecuteA) X(ShellExecuteExA) X(_spawnv) X(_execv) X(_execvp) X(_execve) X(system) 328 #define MAKE_SHIM(name) static void shim_##name(void) { \ 329 recomp_lookup_import((uint32_t)(uintptr_t)host_##name)(); } 330 HOST_APIS(MAKE_SHIM) 331 #define SHIM_ENTRY(name) {#name, shim_##name, 0}, 332 static native32_shim_t shims[] = { HOST_APIS(SHIM_ENTRY) }; 333 #define NATIVE_ENTRY(name) {#name, (uintptr_t)host_##name}, 334 static const struct { const char *name; uintptr_t address; } native_hooks[] = { 335 HOST_APIS(NATIVE_ENTRY) 336 }; 337 338 static uintptr_t native_hook(const char *name) 339 { 340 for (unsigned i = 0; i < sizeof(native_hooks) / sizeof(native_hooks[0]); i++) 341 if (!strcmp(name, native_hooks[i].name)) return native_hooks[i].address; 342 return 0; 343 } 344 345 static void patch_imports(uint32_t base, int native) 346 { 347 DWORD rva = headers(base)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; 348 if (!rva) return; 349 IMAGE_IMPORT_DESCRIPTOR *descriptor = (void *)(uintptr_t)(base + rva); 350 for (; descriptor->Name; descriptor++) { 351 if (!descriptor->OriginalFirstThunk) continue; 352 uint32_t *names = (void *)(uintptr_t)(base + descriptor->OriginalFirstThunk); 353 uint32_t *slots = (void *)(uintptr_t)(base + descriptor->FirstThunk); 354 for (; *names; names++, slots++) { 355 if (*names & IMAGE_ORDINAL_FLAG32) continue; 356 const char *name = (char *)(uintptr_t)(base + *names + 2); 357 uint32_t replacement = 0; 358 if (!strcmp(name, "_acmdln")) replacement = (uint32_t)(uintptr_t)&guest_command_line; 359 if (native && native_hook(name)) replacement = (uint32_t)native_hook(name); 360 if (replacement) { 361 DWORD old; 362 if (!VirtualProtect(slots, sizeof(*slots), PAGE_READWRITE, &old)) fail("IAT protection", name); 363 *slots = replacement; 364 if (!VirtualProtect(slots, sizeof(*slots), old, &old)) fail("IAT restore", name); 365 } 366 } 367 } 368 } 369 370 static void patch_native_modules(void) 371 { 372 HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); 373 if (snapshot == INVALID_HANDLE_VALUE) fail("module snapshot", "vendors"); 374 MODULEENTRY32 entry = {0}; 375 entry.dwSize = sizeof(entry); 376 size_t length = strlen(guest_directory); 377 if (Module32First(snapshot, &entry)) do { 378 if (module_named(entry.szModule) >= 0) 379 fail("original game module entered native loader", entry.szExePath); 380 if (!_strnicmp(entry.szExePath, guest_directory, length) && entry.szExePath[length] == '\\') 381 patch_imports((uint32_t)(uintptr_t)entry.modBaseAddr, 1); 382 } while (Module32Next(snapshot, &entry)); 383 CloseHandle(snapshot); 384 } 385 386 static void attach_module_locked(int index, int startup) 387 { 388 if (module_state[index]) return; 389 module_state[index] = 1; 390 uint32_t base = game_modules[index].base; 391 IMAGE_NT_HEADERS32 *nt = headers(base); 392 DWORD rva = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; 393 if (rva) { 394 IMAGE_IMPORT_DESCRIPTOR *dependency = (void *)(uintptr_t)(base + rva); 395 for (; dependency->Name; dependency++) { 396 int child = module_named((char *)(uintptr_t)(base + dependency->Name)); 397 if (child >= 0) attach_module_locked(child, startup); 398 } 399 } 400 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && game_modules[index].entry) { 401 fprintf(stderr, "[game-host] attach %s at %08x\n", game_modules[index].name, game_modules[index].entry); 402 if (!recomp_lookup(game_modules[index].entry)) 403 fail("missing lifted DllMain", game_modules[index].name); 404 /* The NX callback bridge saves the suspended caller's full register 405 * state. Original image pages stay non-executable throughout. */ 406 BOOL (WINAPI *entry)(HINSTANCE, DWORD, LPVOID) = (void *)(uintptr_t)game_modules[index].entry; 407 BOOL result = entry((HINSTANCE)(uintptr_t)base, DLL_PROCESS_ATTACH, (void *)(uintptr_t)startup); 408 if (!result) fail("DllMain rejected process attach", game_modules[index].name); 409 } 410 module_state[index] = 2; 411 } 412 413 recomp_func_t recomp_lookup_manual(uint32_t va) { (void)va; return NULL; } 414 415 static DWORD WINAPI run_client(void *unused) 416 { 417 (void)unused; 418 EnterCriticalSection(&loader_lock); 419 attach_module_locked(client_index, 1); 420 LeaveCriticalSection(&loader_lock); 421 fprintf(stderr, "[game-host] entering Clientr at %08x\n", game_modules[client_index].entry); 422 native32_call_guest(game_modules[client_index].entry, 0, NULL); 423 return 0; 424 } 425 426 int main(int argc, char **argv) 427 { 428 /* Preserve the existing local launch arguments, with Clientr as argv[0]. */ 429 setvbuf(stderr, NULL, _IONBF, 0); 430 GetCurrentDirectoryA(sizeof(guest_directory), guest_directory); 431 snprintf(guest_filename, sizeof(guest_filename), "%s\\Clientr.exe", guest_directory); 432 guest_argc = argc; 433 guest_argv = argv; 434 guest_argv[0] = guest_filename; 435 const char *tail = GetCommandLineA(); 436 if (*tail == '"') { tail++; while (*tail && *tail != '"') tail++; if (*tail) tail++; } 437 else while (*tail && *tail != ' ' && *tail != '\t') tail++; 438 guest_command_line = malloc(strlen(guest_filename) + strlen(tail) + 3); 439 sprintf(guest_command_line, "\"%s\"%s", guest_filename, tail); 440 SetEnvironmentVariableA("ANARCHY_CD", "cd_image"); 441 SetEnvironmentVariableA("ANARCHY_SETUP", "Setupf"); 442 443 /* Reserve all guest images before native vendor imports can occupy them. */ 444 HANDLE job = CreateJobObjectA(NULL, NULL); 445 JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = {0}; 446 limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; 447 if (!job || !SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof(limits)) || 448 !AssignProcessToJobObject(job, GetCurrentProcess())) 449 fail("cannot contain native helper processes", "job object"); 450 /* The process owns this non-inheritable handle until exit; closing it then 451 * terminates any native helpers still running in its job. */ 452 InitializeCriticalSection(&loader_lock); 453 native32_init(); 454 if (!AddVectoredExceptionHandler(0, host_fault)) fail("exception diagnostic registration", "Clientr"); 455 client_index = module_named("Clientr.exe"); 456 game_data_init(); 457 for (int i = 0; i < game_module_count; i++) { 458 module_span[i] = headers(game_modules[i].base)->OptionalHeader.SizeOfImage; 459 IMAGE_DATA_DIRECTORY tls = headers(game_modules[i].base)->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; 460 if (tls.VirtualAddress || tls.Size) fail("PE TLS initialization is not implemented", game_modules[i].name); 461 } 462 for (int i = 0; i < game_module_count; i++) { 463 if (native32_bind(game_modules[i].base, shims, sizeof(shims) / sizeof(shims[0]))) 464 fail("unresolved imports", game_modules[i].name); 465 patch_imports(game_modules[i].base, 0); 466 } 467 patch_native_modules(); 468 fprintf(stderr, "[game-host] initialized and bound %d modules from compiled data; no game PE inputs\n", game_module_count); 469 470 /* Generated C call depth needs a larger native stack than the host main. */ 471 HANDLE thread = CreateThread(NULL, 16 * 1024 * 1024, run_client, NULL, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); 472 if (!thread) fail("CreateThread", "Clientr"); 473 WaitForSingleObject(thread, INFINITE); 474 DWORD result; 475 GetExitCodeThread(thread, &result); 476 CloseHandle(thread); 477 return (int)result; 478 }