aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 14392a621187c160e1d1c0fe3f64da0b1298af8c
parent f23dc34c395233d81322398c1efd7a3a67eb429e
Author: anon <anon@example.com>
Date:   Wed, 14 Oct 2026 23:02:07 +0000

Run native Linux CRT startup through game WinMain

Diffstat:
Mdecompiled/runtime/guest_crt.c | 163++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mdecompiled/runtime/guest_crt.h | 1+
Mdecompiled/runtime/linux_host.c | 17++++++++++++++++-
Mdecompiled/runtime/linux_platform.c | 10++++++++++
Mdecompiled/tests/guest_crt.c | 90++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Adecompiled/tests/guest_startup.c | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdecompiled/tests/linux_platform.c | 16++++++++++++++++
Atools/reconstruction/test_portable_startup.py | 37+++++++++++++++++++++++++++++++++++++
8 files changed, 410 insertions(+), 3 deletions(-)

diff --git a/decompiled/runtime/guest_crt.c b/decompiled/runtime/guest_crt.c @@ -3,6 +3,9 @@ #include "guest_memory.h" static _Thread_local uint32_t random_state = 1; +static uint32_t user_matherr; +static uint32_t *exit_callbacks; +static size_t exit_callback_count; uint32_t guest_crt_data(const char *name) { @@ -10,7 +13,10 @@ uint32_t guest_crt_data(const char *name) static const struct { const char *name; uint32_t offset; } symbols[] = { {"_adjust_fdiv", 0}, {"__unguarded_readlc_active", 4}, {"__setlc_active", 8}, {"__lc_handle", 16}, {"__lc_codepage", 40}, {"__lc_collate_cp", 44}, - {"__mb_cur_max", 48}, + {"__mb_cur_max", 48}, {"_fmode", 52}, {"_commode", 56}, + {"_acmdln", 60}, {"__argc", 64}, {"__argv", 68}, + {"_environ", 72}, {"__initenv", 76}, {"_pgmptr", 80}, + {"__app_type", 84}, {"_iob", 0x1000}, }; unsigned index; @@ -35,6 +41,124 @@ uint32_t guest_crt_data(const char *name) return 0x08500000u + symbols[index].offset; } +static uint32_t copy_string_vector(int count, char **strings) +{ + uint64_t size = ((uint64_t)count + 1) * 4; + for (int i = 0; i < count; ++i) size += strlen(strings[i]) + 1; + uint32_t result = size <= UINT32_MAX ? guest_malloc((uint32_t)size) : 0; + if (!result) { fprintf(stderr, "Guest startup allocation failed\n"); abort(); } + uint32_t text = result + (count + 1) * 4; + for (int i = 0; i < count; ++i) { + size_t length = strlen(strings[i]) + 1; + MEM32(result + i * 4) = text; + memcpy((void *)ADDR(text), strings[i], length); + text += (uint32_t)length; + } + MEM32(result + count * 4) = 0; + return result; +} + +void guest_crt_startup(int argc, char **argv, char **environment) +{ + /* Keep both the pointer arrays and their strings in guest-owned memory. */ + int count = 0; + while (environment[count]) ++count; + MEM32(guest_crt_data("__argc")) = argc; + MEM32(guest_crt_data("__argv")) = copy_string_vector(argc, argv); + MEM32(guest_crt_data("_environ")) = copy_string_vector(count, environment); + MEM32(guest_crt_data("__initenv")) = MEM32(guest_crt_data("_environ")); + MEM32(guest_crt_data("_pgmptr")) = MEM32(MEM32(guest_crt_data("__argv"))); + + /* Preserve simple login tokens; quote only arguments that need escaping. */ + uint64_t capacity = 1; + for (int i = 0; i < argc; ++i) capacity += strlen(argv[i]) * 2 + 3; + uint32_t command = capacity <= UINT32_MAX ? guest_malloc((uint32_t)capacity) : 0; + if (!command) { fprintf(stderr, "Guest command line allocation failed\n"); abort(); } + char *output = (char *)ADDR(command); + for (int i = 0; i < argc; ++i) { + if (i) *output++ = ' '; + if (*argv[i] && !strpbrk(argv[i], " \t\"")) { + size_t length = strlen(argv[i]); + memcpy(output, argv[i], length); + output += length; + continue; + } + *output++ = '"'; + const char *input = argv[i]; + while (*input) { + unsigned slashes = 0; + while (*input == '\\') { ++slashes; ++input; } + unsigned escaped = (*input == '"' || !*input) ? slashes * 2 : slashes; + while (escaped--) *output++ = '\\'; + if (*input == '"') *output++ = '\\'; + if (*input) *output++ = *input++; + } + *output++ = '"'; + } + *output = 0; + MEM32(guest_crt_data("_acmdln")) = command; +} + +static void crt_set_app_type(void) +{ + MEM32(guest_crt_data("__app_type")) = MEM32(g_esp + 4); + g_esp += 4; +} + +static void crt_p_fmode(void) +{ + g_eax = guest_crt_data("_fmode"); + g_esp += 4; +} + +static void crt_p_commode(void) +{ + g_eax = guest_crt_data("_commode"); + g_esp += 4; +} + +static void crt_setusermatherr(void) +{ + user_matherr = MEM32(g_esp + 4); + g_esp += 4; +} + +static void crt_getmainargs(void) +{ + /* AO disables wildcard expansion and the malloc new-handler mode. */ + if (MEM32(g_esp + 16) || MEM32(MEM32(g_esp + 20))) { + fprintf(stderr, "Guest CRT wildcard expansion/new-handler mode is not implemented\n"); + abort(); + } + MEM32(MEM32(g_esp + 4)) = MEM32(guest_crt_data("__argc")); + MEM32(MEM32(g_esp + 8)) = MEM32(guest_crt_data("__argv")); + MEM32(MEM32(g_esp + 12)) = MEM32(guest_crt_data("_environ")); + g_eax = 0; + g_esp += 4; +} + +static void crt_controlfp(void) +{ + /* MSVCRT's public mask differs from the x87 word used by generated C. */ + uint32_t state = ((g_fpu_cw & 1) << 4) | ((g_fpu_cw & 2) << 18) | + ((g_fpu_cw & 4) << 1) | ((g_fpu_cw & 8) >> 1) | + ((g_fpu_cw & 16) >> 3) | ((g_fpu_cw & 32) >> 5) | + ((g_fpu_cw & 0x0c00) >> 2) | ((g_fpu_cw & 0x1000) << 6); + if ((g_fpu_cw & 0x0300) == 0x0200) state |= 0x10000; /* 53 bits */ + if (!(g_fpu_cw & 0x0300)) state |= 0x20000; /* 24 bits */ + uint32_t mask = MEM32(g_esp + 8) & 0x7031f; /* _controlfp preserves denormal masking. */ + uint32_t requested = (state & ~mask) | (MEM32(g_esp + 4) & mask); + /* AO's CRT selects the existing 53-bit, nearest, masked-exception mode. + * Other arithmetic modes need support in generated operations first. */ + if (requested != state || g_fpu_cw != 0x027f) { + fprintf(stderr, "Unsupported guest floating-point mode %08x (x87=%04x)\n", + requested, g_fpu_cw); + abort(); + } + g_eax = state; + g_esp += 4; +} + static void crt_initterm(void) { uint32_t begin = MEM32(g_esp + 4), end = MEM32(g_esp + 8); @@ -108,6 +232,38 @@ static void crt_dllonexit(void) g_esp += 4; } +static void crt_onexit(void) +{ + uint32_t callback = MEM32(g_esp + 4); + uint32_t *replacement = callback ? realloc(exit_callbacks, + (exit_callback_count + 1) * sizeof(*exit_callbacks)) : NULL; + g_eax = 0; + if (replacement) { + exit_callbacks = replacement; + exit_callbacks[exit_callback_count++] = callback; + g_eax = callback; + } + g_esp += 4; +} + +static void crt_cexit(void) +{ + uint32_t caller = g_cur_func; + while (exit_callback_count) { + uint32_t entry = exit_callbacks[--exit_callback_count]; + recomp_func_t function = recomp_lookup(entry); + if (!function) function = recomp_lookup_import(entry); + if (!function) { fprintf(stderr, "Missing CRT exit callback %08x\n", entry); abort(); } + PUSH32(g_esp, RECOMP_RETADDR); + function(); + } + free(exit_callbacks); + exit_callbacks = NULL; + fflush(NULL); + g_cur_func = caller; + g_esp += 4; +} + static void crt_new(void) { g_eax = guest_malloc(MEM32(g_esp + 4)); @@ -218,12 +374,17 @@ static void crt_memset(void) recomp_func_t guest_crt_lookup(const char *name) { static const struct { const char *name; recomp_func_t function; } functions[] = { + {"__set_app_type", crt_set_app_type}, {"__p__fmode", crt_p_fmode}, + {"__p__commode", crt_p_commode}, {"__setusermatherr", crt_setusermatherr}, + {"__getmainargs", crt_getmainargs}, + {"_controlfp", crt_controlfp}, {"malloc", crt_malloc}, {"free", crt_free}, {"realloc", crt_realloc}, {"srand", crt_srand}, {"rand", crt_rand}, {"calloc", crt_calloc}, {"strncpy", crt_strncpy}, {"strchr", crt_strchr}, {"memcpy", crt_memcpy}, {"memmove", crt_memmove}, {"memset", crt_memset}, {"_initterm", crt_initterm}, {"__dllonexit", crt_dllonexit}, + {"_onexit", crt_onexit}, {"_cexit", crt_cexit}, {"??2@YAPAXI@Z", crt_new}, {"??3@YAXPAX@Z", crt_free}, {"_ftol", crt_ftol}, {"floor", crt_floor}, diff --git a/decompiled/runtime/guest_crt.h b/decompiled/runtime/guest_crt.h @@ -3,4 +3,5 @@ #include "recomp_types.h" recomp_func_t guest_crt_lookup(const char *name); uint32_t guest_crt_data(const char *name); +void guest_crt_startup(int argc, char **argv, char **environment); #endif diff --git a/decompiled/runtime/linux_host.c b/decompiled/runtime/linux_host.c @@ -137,6 +137,15 @@ static void disable_thread_library_calls(void) g_esp += 8; } +static void get_module_handle(void) +{ + uint32_t name = MEM32(g_esp + 4); + int module = module_named(name ? (const char *)ADDR(name) : "Clientr.exe"); + g_eax = module >= 0 ? modules[module].base : 0; + if (!g_eax) MEM32(g_fs_base + 0x34) = 126; /* ERROR_MOD_NOT_FOUND */ + g_esp += 8; +} + recomp_func_t recomp_lookup_import(uint32_t va) { if (va < 0xf0000000u || ((va - 0xf0000000u) & 3) || @@ -145,6 +154,10 @@ recomp_func_t recomp_lookup_import(uint32_t va) exit(3); } current_import = (va - 0xf0000000u) / 4; + if (!strcasecmp(imports[current_import].dll, "kernel32.dll") && + imports[current_import].name && + !strcmp(imports[current_import].name, "GetModuleHandleA")) + return get_module_handle; if (imports[current_import].name) { recomp_func_t function = linux_platform_lookup(imports[current_import].dll, imports[current_import].name); if (function) return function; @@ -210,8 +223,9 @@ static void attach_module(int module) } } -int main(void) +int main(int argc, char **argv) { + extern char **environ; setvbuf(stderr, NULL, _IONBF, 0); for (int i = 0; i < game_module_count; ++i) { modules[i].name = game_modules[i].name; @@ -227,6 +241,7 @@ int main(void) game_data_init(); msvcp_data_init(); ace_data_init(); + guest_crt_startup(argc, argv, environ); bind_modules(); fprintf(stderr, "[linux-host] initialized %d modules; bound %u external imports\n", module_count, import_count); diff --git a/decompiled/runtime/linux_platform.c b/decompiled/runtime/linux_platform.c @@ -151,6 +151,15 @@ static void set_last_error(void) g_esp += 8; } +static void get_startup_info(void) +{ + /* Direct Linux launches have no requested window placement or inherited handles. */ + uint32_t info = MEM32(g_esp + 4); + memset((void *)ADDR(info), 0, 68); + MEM32(info) = 68; /* sizeof(STARTUPINFOA) in the guest's 32-bit ABI */ + g_esp += 8; +} + recomp_func_t linux_platform_lookup(const char *dll, const char *name) { if (!strcasecmp(dll, "winmm.dll") && !strcmp(name, "timeGetTime")) return tick_count; @@ -161,6 +170,7 @@ recomp_func_t linux_platform_lookup(const char *dll, const char *name) {"GetTickCount", tick_count}, {"Sleep", sleep_milliseconds}, {"GetLastError", get_last_error}, {"SetLastError", set_last_error}, {"GetCurrentThreadId", current_thread_id}, + {"GetStartupInfoA", get_startup_info}, {"InterlockedExchange", interlocked_exchange}, {"InterlockedIncrement", interlocked_increment}, {"InterlockedDecrement", interlocked_decrement}, diff --git a/decompiled/tests/guest_crt.c b/decompiled/tests/guest_crt.c @@ -160,6 +160,90 @@ static void standard_stream_data_preserves_32_bit_layout(void) MEM8(input_buffer + 4095) = 0; } +static void startup_copies_arguments_and_environment(void) +{ + char executable[] = "./game"; + char login[] = "localtest"; + char *argv[] = {executable, login, "73", "", "with space", "say\"hi", "a b\\", "c\\d", NULL}; + char setting[] = "ANARCHY_SETUP=Setupf"; + char *environment[] = {setting, "EMPTY=", NULL}; + + guest_crt_startup(8, argv, environment); + login[0] = 'X'; + setting[0] = 'X'; + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = 0x50005000u; + MEM32(g_esp + 8) = 0x50005004u; + MEM32(g_esp + 12) = 0x50005008u; + MEM32(g_esp + 16) = 0; + MEM32(g_esp + 20) = 0x5000500cu; + MEM32(0x5000500cu) = 0; + guest_crt_lookup("__getmainargs")(); + + uint32_t arguments = MEM32(0x50005004u), variables = MEM32(0x50005008u); + assert(g_eax == 0 && g_esp == 0x5000ff04u); + assert(MEM32(0x50005000u) == 8 && MEM32(arguments + 32) == 0); + assert(!strcmp((char *)ADDR(MEM32(arguments + 4)), "localtest")); + assert(!strcmp((char *)ADDR(MEM32(arguments + 12)), "")); + assert(!strcmp((char *)ADDR(MEM32(arguments + 20)), "say\"hi")); + assert(!strcmp((char *)ADDR(MEM32(variables)), "ANARCHY_SETUP=Setupf")); + assert(!strcmp((char *)ADDR(MEM32(variables + 4)), "EMPTY=")); + assert(MEM32(variables + 8) == 0); + assert(MEM32(guest_crt_data("__initenv")) == variables); + assert(MEM32(guest_crt_data("_pgmptr")) == MEM32(arguments)); + assert(!strcmp((char *)ADDR(MEM32(guest_crt_data("_acmdln"))), + "./game localtest 73 \"\" \"with space\" \"say\\\"hi\" \"a b\\\\\" c\\d")); +} + +static void startup_exposes_writable_crt_modes(void) +{ + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = 2; + + guest_crt_lookup("__set_app_type")(); + guest_crt_lookup("__p__fmode")(); + MEM32(g_eax) = 0x8000; + guest_crt_lookup("__p__commode")(); + MEM32(g_eax) = 0x4000; + + assert(MEM32(guest_crt_data("__app_type")) == 2); + assert(MEM32(guest_crt_data("_fmode")) == 0x8000); + assert(MEM32(guest_crt_data("_commode")) == 0x4000); + assert(g_esp == 0x5000ff0cu); +} + +static void startup_selects_53_bit_floating_point(void) +{ + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = 0x10000; + MEM32(g_esp + 8) = 0x30000; + g_fpu_cw = 0x027f; + + guest_crt_lookup("_controlfp")(); + + assert(g_eax == 0x9001f && g_fpu_cw == 0x027f); + assert(g_esp == 0x5000ff04u); +} + +static void exit_callbacks_run_once_in_reverse_order(void) +{ + MEM32(0x50002000u) = 0; + for (uint32_t callback = 0x11110000u; callback <= 0x22220000u; callback += 0x11110000u) { + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = callback; + guest_crt_lookup("_onexit")(); + assert(g_eax == callback && g_esp == 0x5000ff04u); + } + g_esp = 0x5000ff00u; + g_cur_func = 0x33330000u; + + guest_crt_lookup("_cexit")(); + guest_crt_lookup("_cexit")(); + + assert(MEM32(0x50002000u) == 21); + assert(g_esp == 0x5000ff08u && g_cur_func == 0x33330000u); +} + int main(void) { assert(guest_map("test memory and stack", 0x50000000u, 0x10000u)); @@ -170,7 +254,11 @@ int main(void) eh_prolog_installs_guest_frame(); standard_stream_data_preserves_32_bit_layout(); floor_returns_on_guest_fpu_stack(); + startup_copies_arguments_and_environment(); + startup_exposes_writable_crt_modes(); + startup_selects_53_bit_floating_point(); + exit_callbacks_run_once_in_reverse_order(); assert(MEM32(guest_crt_data("_adjust_fdiv")) == 0); - puts("guest CRT: constructors, stack balance, calloc, DLL exit callbacks and EH frame passed"); + puts("guest CRT: constructors, heap, EH frame, FILE data, floor and startup state passed"); return 0; } diff --git a/decompiled/tests/guest_startup.c b/decompiled/tests/guest_startup.c @@ -0,0 +1,79 @@ +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include <windows.h> +#else +#include "guest_crt.h" +#include "guest_memory.h" + +recomp_func_t recomp_lookup(uint32_t address) +{ + fprintf(stderr, "Unexpected startup-test guest call %08x\n", address); + abort(); +} +recomp_func_t recomp_lookup_import(uint32_t address) { return recomp_lookup(address); } +#endif + +int main(int argc, char **argv) +{ +#ifdef _WIN32 + HMODULE crt = LoadLibraryA("msvcrt.dll"); + assert(crt); + int (__cdecl *getmainargs)(int *, char ***, char ***, int, int *) = + (void *)GetProcAddress(crt, "__getmainargs"); + unsigned (__cdecl *controlfp)(unsigned, unsigned) = (void *)GetProcAddress(crt, "_controlfp"); + assert(getmainargs && controlfp); + int count, startup = 0; + char **arguments, **environment; +#else + assert(argc >= 2); + assert(guest_map("startup test stack", 0x50000000u, 0x10000u)); + char *environment[] = {"ANARCHY_SETUP=Setupf", NULL}; + guest_crt_startup(argc - 1, argv + 1, environment); + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = 0x50001000u; + MEM32(g_esp + 8) = 0x50001004u; + MEM32(g_esp + 12) = 0x50001008u; + MEM32(g_esp + 16) = 0; + MEM32(g_esp + 20) = 0x5000100cu; +#endif + +#ifdef _WIN32 + int result = getmainargs(&count, &arguments, &environment, 0, &startup); + unsigned mode = controlfp(0x10000, 0x30000); +#else + guest_crt_lookup("__getmainargs")(); + assert(g_esp == 0x5000ff04u); + int result = (int)g_eax, count = MEM32(0x50001000u); + uint32_t arguments = MEM32(0x50001004u); + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = 0x10000; + MEM32(g_esp + 8) = 0x30000; + guest_crt_lookup("_controlfp")(); + unsigned mode = g_eax; + assert(g_esp == 0x5000ff04u); + puts((char *)ADDR(MEM32(guest_crt_data("_acmdln")))); +#endif + + assert(result == 0 && mode == 0x9001f); + printf("argc=%d mode=%08x\n", count, mode); + for (int i = 0; i < count; ++i) { +#ifdef _WIN32 + const unsigned char *text = (const unsigned char *)arguments[i]; +#else + const unsigned char *text = (const unsigned char *)ADDR(MEM32(arguments + i * 4)); + assert(!strcmp((char *)text, argv[i + 1])); +#endif + for (; *text; ++text) printf("%02x", *text); + putchar('\n'); + } +#ifdef _WIN32 + assert(arguments[count] == NULL); +#else + assert(MEM32(arguments + count * 4) == 0); +#endif + return 0; +} diff --git a/decompiled/tests/linux_platform.c b/decompiled/tests/linux_platform.c @@ -138,6 +138,21 @@ static void interlocked_operations_preserve_32_bit_results(void) assert(g_esp == 0x5000ff08u); } +static void startup_info_uses_32_bit_layout(void) +{ + uint32_t info = 0x50005004u; + memset((void *)ADDR(info - 4), 0xa5, 76); + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = info; + + linux_platform_lookup("KERNEL32.dll", "GetStartupInfoA")(); + + assert(MEM32(info) == 68); + for (unsigned offset = 4; offset < 68; ++offset) assert(MEM8(info + offset) == 0); + assert(MEM32(info - 4) == 0xa5a5a5a5u && MEM32(info + 68) == 0xa5a5a5a5u); + assert(g_esp == 0x5000ff08u); +} + int main(void) { assert(guest_map("test memory and stack", 0x50000000u, 0x10000u)); @@ -146,6 +161,7 @@ int main(void) last_error_uses_guest_thread_state(); critical_sections_allow_recursive_entry(); interlocked_operations_preserve_32_bit_results(); + startup_info_uses_32_bit_layout(); puts("Linux platform: clocks, AO delta timer, last error, recursive locks and atomics passed"); return 0; } diff --git a/tools/reconstruction/test_portable_startup.py b/tools/reconstruction/test_portable_startup.py @@ -0,0 +1,37 @@ +"""Check guest command-line serialization against the actual Windows MSVCRT parser.""" +import pathlib +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +decompiled = root / "decompiled" +work = root / "tools/reconstruction/work/portable-startup" +work.mkdir(parents=True, exist_ok=True) + +# A space in the executable path also exercises CRT's special argv[0] parsing. +reference = work / "startup reference.exe" +subprocess.run([ + str(root / "tools/rust/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"), + "-O2", "tests/guest_startup.c", "-o", str(reference), +], cwd=decompiled, check=True) +linux_path = "/mnt/" + decompiled.drive[0].lower() + decompiled.as_posix()[2:] +linux_output = "/mnt/" + work.drive[0].lower() + work.as_posix()[2:] + "/translated" +wsl = ["wsl", "-d", "Ubuntu-26.04", "--cd", linux_path, "--exec"] +subprocess.run(wsl + [ + "gcc", "-O2", "-DRECOMP_PORTABLE", "-Iruntime", "-fno-strict-aliasing", + "tests/guest_startup.c", "runtime/guest_crt.c", "runtime/guest_memory.c", + "runtime/guest_heap.c", "runtime/recomp_state.c", "-lm", "-o", linux_output, +], check=True) + +# Feed the exact command line built by production Linux code to Windows. +cases = [[], ["localtest", "localtest", "73", "2130706433", "7511", "0", "0"], + ["", "with space", "with\ttab", 'say"hi', "a b\\", "c\\d"], ["*", "?"]] +for slashes in range(9): + cases.append(["\\" * slashes, "space " + "\\" * slashes, + "x" + "\\" * slashes + '"y', '"' + "\\" * slashes + '"']) +for arguments in cases: + actual = subprocess.check_output(wsl + [linux_output, str(reference), *arguments], text=True, timeout=30) + command, actual = actual.split("\n", 1) + expected = subprocess.check_output(command, text=True, timeout=30) + assert actual == expected, (arguments, expected, actual) +print(f"CRT startup: {len(cases)} command lines match Windows MSVCRT, including quotes/backslashes and FP mode")