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