aorecomp

Anarchy Online classic in the browser

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


commit daacf8598a2ae410596952bb68276d7096288a40
parent e49ca4216072330b84dc21a82c47c0de52d3be51
Author: anon <anon@example.com>
Date:   Wed, 14 Oct 2026 23:38:07 +0000

Advance Linux ACE startup with formatting, events and TLS

Diffstat:
Mdecompiled/Makefile.linux | 24++++++++++++++++++++++--
Adecompiled/runtime/guest_format.c | 168+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adecompiled/runtime/guest_format.h | 5+++++
Mdecompiled/runtime/linux_host.c | 4++++
Mdecompiled/runtime/linux_platform.c | 32++++++++++++++++++++++++++++++++
Mdecompiled/runtime/linux_sync.c | 37+++++++++++++++++++++++++++++++++++--
Adecompiled/runtime/linux_tls.c | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adecompiled/runtime/linux_tls.h | 5+++++
Adecompiled/tests/event.c | 177+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adecompiled/tests/guest_format.c | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdecompiled/tests/linux_platform.c | 14++++++++++++++
Adecompiled/tests/os_version.c | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adecompiled/tests/tls.c | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/reconstruction/test_portable_event.py | 26++++++++++++++++++++++++++
Atools/reconstruction/test_portable_format.py | 26++++++++++++++++++++++++++
Atools/reconstruction/test_portable_os_version.py | 26++++++++++++++++++++++++++
Atools/reconstruction/test_portable_tls.py | 26++++++++++++++++++++++++++
17 files changed, 994 insertions(+), 4 deletions(-)

diff --git a/decompiled/Makefile.linux b/decompiled/Makefile.linux @@ -3,7 +3,7 @@ CPPFLAGS := -Iruntime -Isrc -Idata -DRECOMP_PORTABLE CFLAGS := -O2 -fno-strict-aliasing GAME_SOURCES := $(wildcard src/*/*.c) src/dispatch.c DATA_SOURCES := $(wildcard data/*.c) -RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_platform.c runtime/linux_sync.c runtime/linux_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c +RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_platform.c runtime/linux_sync.c runtime/linux_tls.c runtime/linux_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c VENDOR_SOURCES := $(wildcard vendor/msvcp60/source/*.c) $(wildcard vendor/ace/source/*.c) OBJECTS := $(patsubst %.c,build/linux/%.o,$(GAME_SOURCES) $(DATA_SOURCES) $(RUNTIME_SOURCES) $(VENDOR_SOURCES)) @@ -68,7 +68,23 @@ build/linux/network-startup: tests/network_startup.c runtime/linux_network.c run mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -lm -o $@ -test: build/linux/linecrypt build/linux/guest-heap build/linux/guest-crt build/linux/linux-platform build/linux/msvcp-strings build/linux/ace-token build/linux/msvcp-stdio-data build/linux/guest-eh build/linux/guest-rand build/linux/semaphore build/linux/guest-scanf build/linux/network-startup +build/linux/os-version: tests/os_version.c runtime/linux_platform.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/linux_platform.h runtime/guest_memory.h + mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lm -o $@ + +build/linux/guest-format: tests/guest_format.c runtime/guest_format.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_format.h runtime/guest_memory.h + mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -o $@ + +build/linux/event: tests/event.c runtime/linux_sync.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/linux_sync.h runtime/guest_memory.h + mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -o $@ + +build/linux/tls: tests/tls.c runtime/linux_tls.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/linux_tls.h runtime/guest_memory.h + mkdir -p $(@D) + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -o $@ + +test: build/linux/linecrypt build/linux/guest-heap build/linux/guest-crt build/linux/linux-platform build/linux/msvcp-strings build/linux/ace-token build/linux/msvcp-stdio-data build/linux/guest-eh build/linux/guest-rand build/linux/semaphore build/linux/guest-scanf build/linux/network-startup build/linux/os-version build/linux/guest-format build/linux/event build/linux/tls ./build/linux/linecrypt ./build/linux/guest-heap ./build/linux/guest-crt @@ -81,5 +97,9 @@ test: build/linux/linecrypt build/linux/guest-heap build/linux/guest-crt build/l ./build/linux/semaphore ./build/linux/guest-scanf ./build/linux/network-startup + ./build/linux/os-version + ./build/linux/guest-format + ./build/linux/event + ./build/linux/tls -include $(OBJECTS:.o=.d) diff --git a/decompiled/runtime/guest_format.c b/decompiled/runtime/guest_format.c @@ -0,0 +1,168 @@ +#include "guest_format.h" +#include <limits.h> +#include <stdarg.h> + +struct output_buffer { + uint32_t address, capacity; + size_t length; +}; + +static void append(struct output_buffer *output, const char *bytes, size_t length) +{ + if (output->length < output->capacity) { + size_t count = output->capacity - output->length; + if (count > length) count = length; + memcpy((void *)ADDR(output->address + (uint32_t)output->length), bytes, count); + } + output->length += length; + if (output->length > INT_MAX) abort(); +} + +/* Host varargs contain real typed values, never the guest's 32-bit va_list. */ +static void append_value(struct output_buffer *output, const char *format, ...) +{ + va_list arguments, copy; + va_start(arguments, format); + va_copy(copy, arguments); + int length = vsnprintf(NULL, 0, format, copy); + va_end(copy); + if (length < 0) abort(); + char *text = malloc((size_t)length + 1); + if (!text) abort(); + vsnprintf(text, (size_t)length + 1, format, arguments); + va_end(arguments); + append(output, text, length); + free(text); +} + +static void unsupported(const char *format) +{ + fprintf(stderr, "Unsupported guest printf conversion: %s\n", format); + abort(); +} + +static int field_width(const char **cursor, uint32_t *arguments) +{ + if (**cursor == '*') { + ++*cursor; + int value = (int32_t)MEM32(*arguments); + *arguments += 4; + if (value == INT_MIN) unsupported(*cursor); + return value; + } + char *end; + long value = strtol(*cursor, &end, 10); + if (value < 0 || value > INT_MAX) unsupported(*cursor); + *cursor = end; + return (int)value; +} + +static void format_output(struct output_buffer *output, const char *format, uint32_t arguments) +{ + char *native = malloc(strlen(format) + 16); + if (!native) abort(); + while (*format) { + const char *start = format; + while (*format && *format != '%') ++format; + append(output, start, format - start); + if (!*format) break; + start = format++; + if (*format == '%') { + append(output, format++, 1); + continue; + } + + /* Preserve flags; normalize both field arguments for typed host calls. */ + char *end = native; + *end++ = '%'; + while (*format && strchr("-+ #0", *format)) *end++ = *format++; + int width = field_width(&format, &arguments), precision = -1; + if (*format == '.') { + ++format; + precision = field_width(&format, &arguments); + } + *end++ = '*'; + *end++ = '.'; + *end++ = '*'; + + /* Windows long and pointers are 32 bits; I64/ll consume two stack words. */ + int bits = 32, wide = 0; + if (*format == 'h') { + bits = 16; + /* Legacy MSVCRT treats repeated h as short, not C99 signed char. */ + if (*++format == 'h') ++format; + } else if (*format == 'l') { + wide = 1; + if (*++format == 'l') { bits = 64; ++format; } + } else if (!strncmp(format, "I64", 3)) { bits = 64; format += 3; } + else if (!strncmp(format, "I32", 3)) format += 3; + else if (*format == 'I') ++format; + char type = *format; + if (!type) unsupported(start); + ++format; + if (strchr("diuoxX", type)) { + uint64_t value = MEM32(arguments); + arguments += 4; + if (bits == 64) { + value |= (uint64_t)MEM32(arguments) << 32; + arguments += 4; + } + *end++ = 'l'; + *end++ = 'l'; + *end++ = type; + *end = 0; + if (type == 'd' || type == 'i') { + int64_t signed_value = bits == 16 ? (int16_t)value : + bits == 32 ? (int32_t)value : (int64_t)value; + append_value(output, native, width, precision, (long long)signed_value); + } else { + if (bits == 16) value = (uint16_t)value; + append_value(output, native, width, precision, (unsigned long long)value); + } + } else if ((type == 's' || type == 'c') && !wide && bits != 64) { + uint32_t value = MEM32(arguments); + arguments += 4; + *end++ = type; + *end = 0; + if (type == 's') append_value(output, native, width, precision, + value ? (const char *)ADDR(value) : "(null)"); + else append_value(output, native, width, precision, (int)(unsigned char)value); + } else if (type == 'p') { + /* MSVCRT prints eight uppercase digits and ignores explicit precision. */ + *end++ = 'X'; + *end = 0; + append_value(output, native, width, 8, (unsigned int)MEM32(arguments)); + arguments += 4; + } else unsupported(start); + } + free(native); +} + +static void buffer_format(int bounded, int list) +{ + uint32_t destination = MEM32(g_esp + 4); + uint32_t capacity = bounded ? MEM32(g_esp + 8) : UINT32_MAX; + uint32_t format_slot = g_esp + (bounded ? 12 : 8); + uint32_t arguments = list ? MEM32(format_slot + 4) : format_slot + 4; + struct output_buffer output = {destination, capacity, 0}; + format_output(&output, (const char *)ADDR(MEM32(format_slot)), arguments); + + /* Legacy _snprintf writes no terminator when the result fills the buffer. */ + if (output.length < capacity) MEM8(destination + (uint32_t)output.length) = 0; + g_eax = destination && output.length > capacity ? UINT32_MAX : (uint32_t)output.length; + g_esp += 4; +} + +static void format_sprintf(void) { buffer_format(0, 0); } +static void format_vsprintf(void) { buffer_format(0, 1); } +static void format_snprintf(void) { buffer_format(1, 0); } +static void format_vsnprintf(void) { buffer_format(1, 1); } + +recomp_func_t guest_format_lookup(const char *name) +{ + if (!strcmp(name, "sprintf")) return format_sprintf; + if (!strcmp(name, "vsprintf")) return format_vsprintf; + if (!strcmp(name, "_snprintf")) return format_snprintf; + if (!strcmp(name, "_vsnprintf")) return format_vsnprintf; + return NULL; +} diff --git a/decompiled/runtime/guest_format.h b/decompiled/runtime/guest_format.h @@ -0,0 +1,5 @@ +#ifndef GUEST_FORMAT_H +#define GUEST_FORMAT_H +#include "recomp_types.h" +recomp_func_t guest_format_lookup(const char *name); +#endif diff --git a/decompiled/runtime/linux_host.c b/decompiled/runtime/linux_host.c @@ -2,8 +2,10 @@ #include "game-data.h" #include "game-modules.h" #include "guest_crt.h" +#include "guest_format.h" #include "linux_platform.h" #include "linux_sync.h" +#include "linux_tls.h" #include "linux_network.h" #include "guest_msvcp.h" #include "../vendor/msvcp60/source/module.h" @@ -170,6 +172,7 @@ recomp_func_t recomp_lookup_import(uint32_t va) if (function) return function; if (!strcasecmp(imports[current_import].dll, "kernel32.dll")) { function = linux_sync_lookup(imports[current_import].name); + if (!function) function = linux_tls_lookup(imports[current_import].name); if (function) return function; } } @@ -183,6 +186,7 @@ recomp_func_t recomp_lookup_import(uint32_t va) return native32_shim_CxxThrowException; } recomp_func_t function = guest_crt_lookup(imports[current_import].name); + if (!function) function = guest_format_lookup(imports[current_import].name); if (function) return function; } if (!strcasecmp(imports[current_import].dll, "msvcp60.dll") && imports[current_import].name) { diff --git a/decompiled/runtime/linux_platform.c b/decompiled/runtime/linux_platform.c @@ -145,6 +145,12 @@ static void current_thread_id(void) g_esp += 4; } +static void current_process_id(void) +{ + g_eax = (uint32_t)getpid(); + g_esp += 4; +} + static void set_last_error(void) { MEM32(g_fs_base + 0x34) = MEM32(g_esp + 4); @@ -160,6 +166,30 @@ static void get_startup_info(void) g_esp += 8; } +static void get_version(void) +{ + uint32_t info = MEM32(g_esp + 4), size = MEM32(info); + g_eax = 0; + if (size == 148 || size == 156) { + /* Match the unmanifested Windows reference's NT compatibility profile. + * This selects the guest's NT/Unicode paths, not a Linux kernel version. */ + MEM32(info + 4) = 6; + MEM32(info + 8) = 2; + MEM32(info + 12) = 9200; + MEM32(info + 16) = 2; + MEM8(info + 20) = 0; + if (size == 156) { + MEM16(info + 148) = 0; + MEM16(info + 150) = 0; + MEM16(info + 152) = 0x100; + MEM8(info + 154) = 1; + MEM8(info + 155) = 0; + } + g_eax = 1; + } else MEM32(g_fs_base + 0x34) = 122; /* ERROR_INSUFFICIENT_BUFFER */ + 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; @@ -170,7 +200,9 @@ 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}, + {"GetCurrentProcessId", current_process_id}, {"GetStartupInfoA", get_startup_info}, + {"GetVersionExA", get_version}, {"InterlockedExchange", interlocked_exchange}, {"InterlockedIncrement", interlocked_increment}, {"InterlockedDecrement", interlocked_decrement}, diff --git a/decompiled/runtime/linux_sync.c b/decompiled/runtime/linux_sync.c @@ -23,7 +23,7 @@ _Static_assert(sizeof(_Atomic uint32_t) == 4 && ATOMIC_INT_LOCK_FREE == 2, struct semaphore_handle { uint32_t id, access; - int fd; + int fd, event; struct semaphore_state *state; struct semaphore_handle *next; }; @@ -127,6 +127,7 @@ static uint32_t open_semaphore(const char *name, int create, int32_t initial, next_handle += 4; handle->access = access; handle->fd = fd; + handle->event = 0; handle->state = state; handle->next = handles; handles = handle; @@ -160,6 +161,36 @@ static void open_named_semaphore(void) g_esp += 16; } +static void create_event(void) +{ + /* ACE's condition variable uses an unnamed auto-reset event. */ + if (MEM32(g_esp + 4) || MEM32(g_esp + 8) || MEM32(g_esp + 16)) { + fprintf(stderr, "Event security attributes, manual reset and names are not implemented\n"); + abort(); + } + g_eax = open_semaphore(NULL, 1, MEM32(g_esp + 12) != 0, 1, 0x1f0003); + handles->event = 1; + g_esp += 20; +} + +static void change_event(int signaled) +{ + struct semaphore_handle *handle = find_handle(MEM32(g_esp + 4)); + g_eax = 0; + if (handle && !handle->event) MEM32(g_fs_base + 0x34) = 6; + else if (handle) { + /* Repeated SetEvent calls retain one signal; waits consume it once. */ + atomic_store(&handle->state->count, signaled); + if (signaled && syscall(SYS_futex, &handle->state->count, FUTEX_WAKE, 1, NULL, NULL, 0) < 0) + system_failure("event wake"); + g_eax = 1; + } + g_esp += 8; +} + +static void set_event(void) { change_event(1); } +static void reset_event(void) { change_event(0); } + static void close_handle(void) { struct semaphore_handle *handle = find_handle(MEM32(g_esp + 4)); @@ -181,7 +212,8 @@ static void release_semaphore(void) struct semaphore_handle *handle = find_handle(MEM32(g_esp + 4)); int32_t increment = MEM32(g_esp + 8); g_eax = 0; - if (handle && !(handle->access & 2)) MEM32(g_fs_base + 0x34) = 5; + if (handle && handle->event) MEM32(g_fs_base + 0x34) = 6; + else if (handle && !(handle->access & 2)) MEM32(g_fs_base + 0x34) = 5; else if (handle && increment <= 0) MEM32(g_fs_base + 0x34) = 87; else if (handle) { uint32_t count = atomic_load(&handle->state->count); @@ -243,6 +275,7 @@ recomp_func_t linux_sync_lookup(const char *name) {"CreateSemaphoreA", create_semaphore}, {"OpenSemaphoreA", open_named_semaphore}, {"CloseHandle", close_handle}, {"ReleaseSemaphore", release_semaphore}, {"WaitForSingleObject", wait_for_single_object}, + {"CreateEventA", create_event}, {"SetEvent", set_event}, {"ResetEvent", reset_event}, }; for (unsigned i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i) if (!strcmp(name, functions[i].name)) return functions[i].function; diff --git a/decompiled/runtime/linux_tls.c b/decompiled/runtime/linux_tls.c @@ -0,0 +1,81 @@ +#include "linux_tls.h" +#include <pthread.h> + +/* Index allocation is process-wide; values are 32-bit guest words per host thread. + * Generations invalidate every thread's value when a slot is freed or reused. */ +static struct { uint64_t generation; int allocated; } slots[1088]; +static _Thread_local struct { uint64_t generation; uint32_t value; } values[1088]; +static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +static void check_pthread(int error) +{ + if (error) { fprintf(stderr, "TLS pthread: %s\n", strerror(error)); abort(); } +} + +static void allocate_slot(void) +{ + g_eax = UINT32_MAX; /* TLS_OUT_OF_INDEXES */ + check_pthread(pthread_mutex_lock(&mutex)); + for (unsigned index = 0; index < 1088; ++index) { + if (!slots[index].allocated) { + slots[index].allocated = 1; + ++slots[index].generation; + g_eax = index; + break; + } + } + check_pthread(pthread_mutex_unlock(&mutex)); + if (g_eax == UINT32_MAX) MEM32(g_fs_base + 0x34) = 8; /* ERROR_NOT_ENOUGH_MEMORY */ + g_esp += 4; +} + +static void free_slot(void) +{ + uint32_t index = MEM32(g_esp + 4); + g_eax = 0; + check_pthread(pthread_mutex_lock(&mutex)); + if (index < 1088 && slots[index].allocated) { + slots[index].allocated = 0; + ++slots[index].generation; + g_eax = 1; + } + check_pthread(pthread_mutex_unlock(&mutex)); + if (!g_eax) MEM32(g_fs_base + 0x34) = 87; + g_esp += 8; +} + +static void access_slot(int write) +{ + uint32_t index = MEM32(g_esp + 4); + g_eax = 0; + if (index >= 1088) MEM32(g_fs_base + 0x34) = 87; + else { + check_pthread(pthread_mutex_lock(&mutex)); + if (values[index].generation != slots[index].generation) { + values[index].generation = slots[index].generation; + values[index].value = 0; + } + /* Windows Get/Set accept in-range slots even when not allocated. */ + if (write) { + values[index].value = MEM32(g_esp + 8); + g_eax = 1; + } else { + g_eax = values[index].value; + MEM32(g_fs_base + 0x34) = 0; + } + check_pthread(pthread_mutex_unlock(&mutex)); + } + g_esp += write ? 12 : 8; +} + +static void get_value(void) { access_slot(0); } +static void set_value(void) { access_slot(1); } + +recomp_func_t linux_tls_lookup(const char *name) +{ + if (!strcmp(name, "TlsAlloc")) return allocate_slot; + if (!strcmp(name, "TlsFree")) return free_slot; + if (!strcmp(name, "TlsGetValue")) return get_value; + if (!strcmp(name, "TlsSetValue")) return set_value; + return NULL; +} diff --git a/decompiled/runtime/linux_tls.h b/decompiled/runtime/linux_tls.h @@ -0,0 +1,5 @@ +#ifndef LINUX_TLS_H +#define LINUX_TLS_H +#include "recomp_types.h" +recomp_func_t linux_tls_lookup(const char *name); +#endif diff --git a/decompiled/tests/event.c b/decompiled/tests/event.c @@ -0,0 +1,177 @@ +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#ifdef _WIN32 +#include <windows.h> +#else +#include "linux_sync.h" +#include "guest_memory.h" +#include <sys/wait.h> +#include <unistd.h> + +static uint32_t call(const char *name, unsigned count, const uint32_t *arguments) +{ + g_esp = 0x5000ff00u; + for (unsigned i = 0; i < count; ++i) MEM32(g_esp + 4 + i * 4) = arguments[i]; + linux_sync_lookup(name)(); + assert(g_esp == 0x5000ff00u + (count + 1) * 4); + return g_eax; +} +#endif + +static uint32_t create(int signaled) +{ +#ifdef _WIN32 + return (uintptr_t)CreateEventA(NULL, FALSE, signaled, NULL); +#else + uint32_t args[] = {0, 0, signaled, 0}; + return call("CreateEventA", 4, args); +#endif +} + +static uint32_t change(uint32_t handle, int signaled) +{ +#ifdef _WIN32 + return signaled ? SetEvent((HANDLE)(uintptr_t)handle) : ResetEvent((HANDLE)(uintptr_t)handle); +#else + return call(signaled ? "SetEvent" : "ResetEvent", 1, &handle); +#endif +} + +static uint32_t close_object(uint32_t handle) +{ +#ifdef _WIN32 + return CloseHandle((HANDLE)(uintptr_t)handle); +#else + return call("CloseHandle", 1, &handle); +#endif +} + +static uint32_t wait_object(uint32_t handle, uint32_t timeout) +{ +#ifdef _WIN32 + return WaitForSingleObject((HANDLE)(uintptr_t)handle, timeout); +#else + uint32_t args[] = {handle, timeout}; + return call("WaitForSingleObject", 2, args); +#endif +} + +static uint32_t error(void) +{ +#ifdef _WIN32 + return GetLastError(); +#else + return MEM32(g_fs_base + 0x34); +#endif +} + +static void signal_is_consumed_once(void) +{ + uint32_t event = create(1); + assert(event); + + assert(wait_object(event, 0) == 0); + assert(wait_object(event, 0) == 258); + assert(change(event, 1) && change(event, 1)); + assert(wait_object(event, 0) == 0); + + assert(wait_object(event, 0) == 258); + assert(close_object(event)); +} + +static void reset_removes_pending_signal(void) +{ + uint32_t event = create(0); + assert(event && wait_object(event, 0) == 258); + assert(change(event, 1)); + + assert(change(event, 0)); + + assert(wait_object(event, 20) == 258); + assert(close_object(event)); + assert(!change(event, 1) && error() == 6); + assert(!change(event, 0) && error() == 6); + assert(wait_object(event, 0) == UINT32_MAX && error() == 6); +} + +#ifdef _WIN32 +static DWORD WINAPI delayed_signal(void *argument) +{ + Sleep(50); + assert(SetEvent(argument)); + return 0; +} +#endif + +static void blocked_wait_receives_signal(uint32_t timeout) +{ + uint32_t event = create(0); + assert(event); +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 0, delayed_signal, (void *)(uintptr_t)event, 0, NULL); + assert(thread); +#else + /* A host child shares the mapping without sharing guest register globals. */ + pid_t child = fork(); + assert(child >= 0); + if (!child) { + usleep(50000); + assert(change(event, 1)); + _exit(0); + } +#endif + + uint32_t result = wait_object(event, timeout); + + assert(result == 0 && wait_object(event, 0) == 258); +#ifdef _WIN32 + assert(WaitForSingleObject(thread, 1000) == WAIT_OBJECT_0); + assert(CloseHandle(thread)); +#else + int status; + assert(waitpid(child, &status, 0) == child && WIFEXITED(status) && WEXITSTATUS(status) == 0); +#endif + assert(close_object(event)); +} + +static void event_and_semaphore_handles_are_distinct(void) +{ + uint32_t event = create(1); +#ifdef _WIN32 + uint32_t semaphore = (uintptr_t)CreateSemaphoreA(NULL, 0, 1, NULL); +#else + uint32_t args[] = {0, 0, 1, 0}; + uint32_t semaphore = call("CreateSemaphoreA", 4, args); +#endif + assert(event && semaphore && event != semaphore); + +#ifdef _WIN32 + uint32_t result = ReleaseSemaphore((HANDLE)(uintptr_t)event, 1, NULL); +#else + uint32_t release[] = {event, 1, 0}; + uint32_t result = call("ReleaseSemaphore", 3, release); +#endif + + assert(!result && error() == 6); + assert(!change(semaphore, 1) && error() == 6); + assert(!change(semaphore, 0) && error() == 6); + assert(wait_object(event, 0) == 0 && wait_object(semaphore, 0) == 258); + assert(close_object(event) && close_object(semaphore)); +} + +int main(void) +{ +#ifndef _WIN32 + assert(guest_map("event test memory", 0x50000000u, 0x10000u)); + g_fs_base = 0x50001000u; + alarm(20); +#endif + signal_is_consumed_once(); + reset_removes_pending_signal(); + blocked_wait_receives_signal(1000); + blocked_wait_receives_signal(UINT32_MAX); + event_and_semaphore_handles_are_distinct(); + puts("events: auto-reset, coalesced signals, reset, finite/infinite waits and handle types passed"); + return 0; +} diff --git a/decompiled/tests/guest_format.c b/decompiled/tests/guest_format.c @@ -0,0 +1,124 @@ +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <stdarg.h> +#ifdef _WIN32 +#include <windows.h> +static HMODULE crt; +#else +#include "guest_format.h" +#include "guest_memory.h" +#endif + +static uint32_t digest = 2166136261u; +static unsigned cases; + +static void compare_case(const char *format, const uint32_t words[16], const char *expected) +{ + const char *names[] = {"sprintf", "vsprintf", "_snprintf", "_vsnprintf"}; + unsigned length = strlen(expected); + unsigned capacities[] = {0, 1, length ? length - 1 : 0, length, length + 1, 128, 0}; + for (unsigned api = 0; api < 4; ++api) { + for (unsigned size = 0; size < (api < 2 ? 1 : 7); ++size) { + unsigned capacity = api < 2 ? 128 : capacities[size]; + int sizing = api >= 2 && size == 6; + unsigned char output[144], wanted[144]; + memset(output, 0xa5, sizeof(output)); + memset(wanted, 0xa5, sizeof(wanted)); + if (!sizing) { + memcpy(wanted + 4, expected, length < capacity ? length : capacity); + if (length < capacity) wanted[4 + length] = 0; + } + uint32_t arguments[16]; + memcpy(arguments, words, sizeof(arguments)); +#ifdef _WIN32 + for (unsigned i = 0; i < 16; ++i) + if (arguments[i] == 0x50004000u) arguments[i] = (uint32_t)(uintptr_t)"Anarchy Online"; + char *destination = sizing ? NULL : (char *)output + 4; + void *function = (void *)GetProcAddress(crt, names[api]); + assert(function); +#else + strcpy((char *)ADDR(0x50001000u), format); + memcpy((void *)ADDR(0x50002000u), arguments, sizeof(arguments)); + memcpy((void *)ADDR(0x50003000u), output, sizeof(output)); + strcpy((char *)ADDR(0x50004000u), "Anarchy Online"); + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = sizing ? 0 : 0x50003004u; + unsigned slot = g_esp + 8; + if (api >= 2) { MEM32(slot) = capacity; slot += 4; } + MEM32(slot) = 0x50001000u; + if (api & 1) MEM32(slot + 4) = 0x50002000u; + else memcpy((void *)ADDR(slot + 4), arguments, sizeof(arguments)); + g_ebx = 0x12345678; + g_esi = 0x23456789; + g_edi = 0x3456789a; + g_ebp = 0x456789ab; +#endif + +#ifdef _WIN32 + int result; + if (api == 1) result = ((int (__cdecl *)(char *, const char *, va_list))function)(destination, format, (va_list)arguments); + else if (api == 3) result = ((int (__cdecl *)(char *, size_t, const char *, va_list))function)(destination, capacity, format, (va_list)arguments); + else if (api == 0) result = ((int (__cdecl *)(char *, const char *, ...))function)(destination, format, + arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], + arguments[8], arguments[9], arguments[10], arguments[11], arguments[12], arguments[13], arguments[14], arguments[15]); + else result = ((int (__cdecl *)(char *, size_t, const char *, ...))function)(destination, capacity, format, + arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], + arguments[8], arguments[9], arguments[10], arguments[11], arguments[12], arguments[13], arguments[14], arguments[15]); +#else + guest_format_lookup(names[api])(); + int result = (int32_t)g_eax; + memcpy(output, (void *)ADDR(0x50003000u), sizeof(output)); + assert(g_esp == 0x5000ff04u); + assert(g_ebx == 0x12345678 && g_esi == 0x23456789); + assert(g_edi == 0x3456789a && g_ebp == 0x456789ab); +#endif + + int expected_result = !sizing && length > capacity ? -1 : (int)length; + if (result != expected_result || memcmp(output, wanted, sizeof(output))) { + fprintf(stderr, "%s format '%s' capacity %u: result %d expected %d\n", + names[api], format, capacity, result, expected_result); + for (unsigned i = 4; i < 4 + length; ++i) fprintf(stderr, "%02x ", output[i]); + fputc('\n', stderr); + } + assert(result == expected_result); + assert(!memcmp(output, wanted, sizeof(output))); + digest = (digest ^ (uint32_t)result) * 16777619u; + for (unsigned i = 0; i < sizeof(output); ++i) digest = (digest ^ output[i]) * 16777619u; + ++cases; + } + } +} + +int main(void) +{ +#ifdef _WIN32 + crt = LoadLibraryA("msvcrt.dll"); + assert(crt); +#else + assert(guest_map("printf test memory", 0x50000000u, 0x10000u)); +#endif + compare_case("%lx%d", (uint32_t[16]){0x4710e910, 1234}, "4710e9101234"); + compare_case("", (uint32_t[16]){0}, ""); + compare_case("literal %% text", (uint32_t[16]){0}, "literal % text"); + compare_case("%ld %lu %lx", (uint32_t[16]){0x80000000, 0xffffffff, 0xabcdef12}, "-2147483648 4294967295 abcdef12"); + compare_case("%hd %hu", (uint32_t[16]){0xffff8000, 0x1234ffff}, "-32768 65535"); + compare_case("%hhd %hhu %I32d %Id", (uint32_t[16]){0x80, 0x1234ff, 0xffffffff, 42}, "128 13567 -1 42"); + compare_case("%lld %llu", (uint32_t[16]){0, 0x80000000, 0xffffffff, 0xffffffff}, "-9223372036854775808 18446744073709551615"); + compare_case("%I64d %I64u %d", (uint32_t[16]){0, 0x80000000, 0xffffffff, 0xffffffff, 42}, "-9223372036854775808 18446744073709551615 42"); + compare_case("[%s][%.7s][%c]", (uint32_t[16]){0x50004000, 0x50004000, 'X'}, "[Anarchy Online][Anarchy][X]"); + compare_case("[%s]", (uint32_t[16]){0}, "[(null)]"); + compare_case("[%*.*s]", (uint32_t[16]){(uint32_t)-10, (uint32_t)-1, 0x50004000}, "[Anarchy Online]"); + compare_case("[%*.*s]", (uint32_t[16]){(uint32_t)-10, 3, 0x50004000}, "[Ana ]"); + compare_case("[%#x][%#o][%.0d][%08.4d]", (uint32_t[16]){0, 0, 0, 12}, "[0][0][][ 0012]"); + compare_case("[%+08d][% d][%-6u]", (uint32_t[16]){(uint32_t)-42, 42, 9}, "[-0000042][ 42][9 ]"); + compare_case("[%#x][%#X][%#o]", (uint32_t[16]){0xabcd, 0xabcd, 8}, "[0xabcd][0XABCD][010]"); + compare_case("[%p][%#p][%.12p][%012p]", (uint32_t[16]){0xabcd, 0xabcd, 0xabcd, 0xabcd}, "[0000ABCD][0X0000ABCD][0000ABCD][ 0000ABCD]"); + compare_case("[%p][%-12p]", (uint32_t[16]){0, 0xabcd}, "[00000000][0000ABCD ]"); + compare_case("[%#p][%+#012p]", (uint32_t[16]){0, 0}, "[00000000][ 00000000]"); + assert(cases == 288 && digest == 0x3896b505); + printf("printf: %u cases, digest %08x, guest arguments, truncation and canaries passed\n", cases, digest); + return 0; +} diff --git a/decompiled/tests/linux_platform.c b/decompiled/tests/linux_platform.c @@ -2,6 +2,7 @@ #include "guest_crt.h" #include "guest_memory.h" #include <assert.h> +#include <unistd.h> void game_data_hr_dll(void); void sub_32001000(void); @@ -153,6 +154,18 @@ static void startup_info_uses_32_bit_layout(void) assert(g_esp == 0x5000ff08u); } +static void process_id_is_the_native_process(void) +{ + g_esp = 0x5000ff00u; + MEM32(g_fs_base + 0x34) = 777; + + linux_platform_lookup("KERNEL32.dll", "GetCurrentProcessId")(); + + assert(g_eax == (uint32_t)getpid()); + assert(g_esp == 0x5000ff04u); + assert(MEM32(g_fs_base + 0x34) == 777); +} + int main(void) { assert(guest_map("test memory and stack", 0x50000000u, 0x10000u)); @@ -162,6 +175,7 @@ int main(void) critical_sections_allow_recursive_entry(); interlocked_operations_preserve_32_bit_results(); startup_info_uses_32_bit_layout(); + process_id_is_the_native_process(); puts("Linux platform: clocks, AO delta timer, last error, recursive locks and atomics passed"); return 0; } diff --git a/decompiled/tests/os_version.c b/decompiled/tests/os_version.c @@ -0,0 +1,54 @@ +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#ifdef _WIN32 +#include <windows.h> +#else +#include "linux_platform.h" +#include "guest_memory.h" +#endif + +int main(void) +{ +#ifndef _WIN32 + assert(guest_map("OS version test memory", 0x50000000u, 0x10000u)); + g_fs_base = 0x50001000u; +#endif + uint32_t digest = 2166136261u; + const uint32_t sizes[] = {0, 147, 148, 149, 155, 156, 157}; + for (unsigned i = 0; i < 7; ++i) { + unsigned char bytes[208]; + memset(bytes, 0xa5, sizeof(bytes)); + memcpy(bytes + 4, &sizes[i], 4); +#ifdef _WIN32 + SetLastError(777); +#else + memcpy((void *)ADDR(0x50003000u), bytes, sizeof(bytes)); + MEM32(g_fs_base + 0x34) = 777; + g_esp = 0x5000ff00u; + MEM32(g_esp + 4) = 0x50003004u; +#endif + +#ifdef _WIN32 + int result = GetVersionExA((OSVERSIONINFOA *)(bytes + 4)); + uint32_t error = GetLastError(); +#else + linux_platform_lookup("KERNEL32.dll", "GetVersionExA")(); + int result = g_eax; + uint32_t error = MEM32(g_fs_base + 0x34); + memcpy(bytes, (void *)ADDR(0x50003000u), sizeof(bytes)); + assert(g_esp == 0x5000ff08u); +#endif + + assert(result == (sizes[i] == 148 || sizes[i] == 156)); + assert(error == (result ? 777 : 122)); + assert(bytes[0] == 0xa5 && bytes[3] == 0xa5 && bytes[160] == 0xa5); + digest = (digest ^ result) * 16777619u; + digest = (digest ^ error) * 16777619u; + for (unsigned j = 0; j < sizeof(bytes); ++j) digest = (digest ^ bytes[j]) * 16777619u; + } + assert(digest == 0x4002a101); + printf("OS version: 7 size/layout/error cases, NT compatibility profile, digest %08x\n", digest); + return 0; +} diff --git a/decompiled/tests/tls.c b/decompiled/tests/tls.c @@ -0,0 +1,169 @@ +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#ifdef _WIN32 +#include <windows.h> +#else +#include "linux_tls.h" +#include "guest_memory.h" +#include <pthread.h> + +static uint32_t call(const char *name, unsigned count, const uint32_t *arguments) +{ + g_esp = 0x5000ff00u; + for (unsigned i = 0; i < count; ++i) MEM32(g_esp + 4 + i * 4) = arguments[i]; + linux_tls_lookup(name)(); + assert(g_esp == 0x5000ff00u + (count + 1) * 4); + return g_eax; +} +#endif + +static void clear_error(void) +{ +#ifdef _WIN32 + SetLastError(777); +#else + MEM32(g_fs_base + 0x34) = 777; +#endif +} + +static uint32_t error(void) +{ +#ifdef _WIN32 + return GetLastError(); +#else + return MEM32(g_fs_base + 0x34); +#endif +} + +static uint32_t allocate(void) +{ +#ifdef _WIN32 + return TlsAlloc(); +#else + return call("TlsAlloc", 0, NULL); +#endif +} + +static uint32_t release(uint32_t index) +{ +#ifdef _WIN32 + return TlsFree(index); +#else + return call("TlsFree", 1, &index); +#endif +} + +static uint32_t get(uint32_t index) +{ +#ifdef _WIN32 + return (uintptr_t)TlsGetValue(index); +#else + return call("TlsGetValue", 1, &index); +#endif +} + +static uint32_t set(uint32_t index, uint32_t value) +{ +#ifdef _WIN32 + return TlsSetValue(index, (void *)(uintptr_t)value); +#else + uint32_t args[] = {index, value}; + return call("TlsSetValue", 2, args); +#endif +} + +static void values_and_reuse(void) +{ + clear_error(); + uint32_t index = allocate(); + assert(index != UINT32_MAX && error() == 777); + assert(get(index) == 0 && error() == 0); + + clear_error(); + assert(set(index, 0xfedcba98) && error() == 777); + assert(get(index) == 0xfedcba98 && error() == 0); + clear_error(); + assert(release(index) && error() == 777); + + assert(get(index) == 0 && error() == 0); + assert(set(index, 123) && get(index) == 123); + assert(!release(index) && error() == 87); + uint32_t reused = allocate(); + assert(reused != UINT32_MAX && get(reused) == 0); + assert(release(reused)); +} + +#ifdef _WIN32 +static DWORD WINAPI thread_values(void *argument) +#else +static void *thread_values(void *argument) +#endif +{ + uint32_t index = (uintptr_t)argument; + assert(get(index) == 0); + assert(set(index, 0x87654321) && get(index) == 0x87654321); + return 0; +} + +static void values_are_local_to_each_thread(void) +{ + uint32_t index = allocate(); + assert(index != UINT32_MAX && set(index, 0x12345678)); + + /* Guest API calls are serialized while register state remains global. */ +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 0, thread_values, (void *)(uintptr_t)index, 0, NULL); + assert(thread && WaitForSingleObject(thread, 1000) == WAIT_OBJECT_0); + assert(CloseHandle(thread)); +#else + pthread_t thread; + assert(!pthread_create(&thread, NULL, thread_values, (void *)(uintptr_t)index)); + assert(!pthread_join(thread, NULL)); +#endif + + assert(get(index) == 0x12345678); + assert(release(index)); +} + +static void capacity_and_invalid_indices(void) +{ + uint32_t indices[1088]; + unsigned count = 0; + for (;;) { + uint32_t index = allocate(); + if (index == UINT32_MAX) break; + assert(count < 1088); + indices[count++] = index; + } + assert(count >= 1024 && error() == 8); + + for (unsigned i = 0; i < count; ++i) { + assert(get(indices[i]) == 0); + assert(set(indices[i], 0x80000000u + i)); + } + + for (unsigned i = 0; i < count; ++i) { + assert(get(indices[i]) == 0x80000000u + i); + assert(release(indices[i])); + } + assert(get(1088) == 0 && error() == 87); + assert(!set(1088, 42) && error() == 87); + assert(!release(1088) && error() == 87); + assert(get(UINT32_MAX) == 0 && error() == 87); + assert(!set(UINT32_MAX, 42) && error() == 87); + assert(!release(UINT32_MAX) && error() == 87); +} + +int main(void) +{ +#ifndef _WIN32 + assert(guest_map("TLS test memory", 0x50000000u, 0x10000u)); + g_fs_base = 0x50001000u; +#endif + values_and_reuse(); + values_are_local_to_each_thread(); + capacity_and_invalid_indices(); + puts("TLS: guest values, thread isolation, reuse, exhaustion and last-error behavior passed"); + return 0; +} diff --git a/tools/reconstruction/test_portable_event.py b/tools/reconstruction/test_portable_event.py @@ -0,0 +1,26 @@ +"""Compare Linux auto-reset events with the Windows synchronization APIs.""" +import pathlib +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +decompiled = root / "decompiled" +work = root / "tools/reconstruction/work/portable-event" +work.mkdir(parents=True, exist_ok=True) +reference = work / "reference.exe" +subprocess.run([ + str(root / "tools/rust/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"), + "-O2", "tests/event.c", "-o", str(reference), +], cwd=decompiled, check=True) +expected = subprocess.check_output([str(reference)], text=True, timeout=30) +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/event.c", "runtime/linux_sync.c", "runtime/guest_memory.c", + "runtime/recomp_state.c", "-o", linux_output, +], check=True) +actual = subprocess.check_output(wsl + [linux_output], text=True, timeout=30) +assert actual == expected, (expected, actual) +print("Windows == Linux: " + actual.strip()) diff --git a/tools/reconstruction/test_portable_format.py b/tools/reconstruction/test_portable_format.py @@ -0,0 +1,26 @@ +"""Compare guest buffer formatting with the Windows x86 MSVCRT exports.""" +import pathlib +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +decompiled = root / "decompiled" +work = root / "tools/reconstruction/work/portable-format" +work.mkdir(parents=True, exist_ok=True) +reference = work / "reference.exe" +subprocess.run([ + str(root / "tools/rust/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"), + "-O2", "tests/guest_format.c", "-o", str(reference), +], cwd=decompiled, check=True) +expected = subprocess.check_output([str(reference)], text=True, timeout=30) +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_format.c", "runtime/guest_format.c", "runtime/guest_memory.c", + "runtime/recomp_state.c", "-o", linux_output, +], check=True) +actual = subprocess.check_output(wsl + [linux_output], text=True, timeout=30) +assert actual == expected, (expected, actual) +print("Windows == Linux: " + actual.strip()) diff --git a/tools/reconstruction/test_portable_os_version.py b/tools/reconstruction/test_portable_os_version.py @@ -0,0 +1,26 @@ +"""Compare the Linux guest OS profile with the unmanifested Windows reference.""" +import pathlib +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +decompiled = root / "decompiled" +work = root / "tools/reconstruction/work/portable-os-version" +work.mkdir(parents=True, exist_ok=True) +reference = work / "reference.exe" +subprocess.run([ + str(root / "tools/rust/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"), + "-O2", "tests/os_version.c", "-o", str(reference), +], cwd=decompiled, check=True) +expected = subprocess.check_output([str(reference)], text=True, timeout=30) +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/os_version.c", "runtime/linux_platform.c", "runtime/guest_memory.c", + "runtime/recomp_state.c", "-pthread", "-lm", "-o", linux_output, +], check=True) +actual = subprocess.check_output(wsl + [linux_output], text=True, timeout=30) +assert actual == expected, (expected, actual) +print("Windows == Linux: " + actual.strip()) diff --git a/tools/reconstruction/test_portable_tls.py b/tools/reconstruction/test_portable_tls.py @@ -0,0 +1,26 @@ +"""Compare Linux guest TLS with the Windows thread-local storage APIs.""" +import pathlib +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +decompiled = root / "decompiled" +work = root / "tools/reconstruction/work/portable-tls" +work.mkdir(parents=True, exist_ok=True) +reference = work / "reference.exe" +subprocess.run([ + str(root / "tools/rust/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"), + "-O2", "tests/tls.c", "-o", str(reference), +], cwd=decompiled, check=True) +expected = subprocess.check_output([str(reference)], text=True, timeout=30) +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/tls.c", "runtime/linux_tls.c", "runtime/guest_memory.c", + "runtime/recomp_state.c", "-pthread", "-o", linux_output, +], check=True) +actual = subprocess.check_output(wsl + [linux_output], text=True, timeout=30) +assert actual == expected, (expected, actual) +print("Windows == Linux: " + actual.strip())