commit c839e285ee071d531cd11e5b368a8c227ed3921b
parent 46a6bea9e7b0698be70f4770b8a006535dd42d8e
Author: anon <anon@example.com>
Date: Thu, 15 Oct 2026 07:34:03 +0000
Run native Linux guest threads with isolated CPU state and atomic resource counters
Diffstat:
25 files changed, 1242 insertions(+), 142 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_imports.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c
+RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_diagnostics.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.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))
@@ -128,7 +128,7 @@ build/linux/guest-stat: tests/guest_stat.c runtime/guest_stdio.c runtime/guest_c
mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -lm -o $@
-build/linux/dynamic-imports: tests/dynamic_imports.c runtime/linux_imports.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_network.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_format.c runtime/guest_exception.c runtime/guest_msvcp.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c $(wildcard runtime/*.h)
+build/linux/dynamic-imports: tests/dynamic_imports.c runtime/linux_imports.c runtime/linux_window.c runtime/linux_graphics.c runtime/gl_renderer.c runtime/linux_platform.c runtime/linux_sync.c runtime/linux_file.c runtime/linux_tls.c runtime/linux_thread.c runtime/linux_network.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_format.c runtime/guest_exception.c runtime/guest_msvcp.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c $(wildcard runtime/*.h)
mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lm -lSDL2 -lGL -o $@
@@ -163,6 +163,8 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric
./build/linux/guest-format
./build/linux/event
./build/linux/tls
+ ./build/linux/threads
+ ./build/linux/resource-atomics
./build/linux/module-filename
./build/linux/delete-file
./build/linux/guest-stdio
@@ -206,3 +208,15 @@ build/linux/getenv: tests/getenv.c runtime/guest_crt.c runtime/guest_heap.c runt
$(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -lm -o $@
test: build/linux/getenv
+
+build/linux/threads: tests/threads.c tests/guest_eh_lifted.c runtime/eh32.c runtime/guest_exception.c runtime/linux_thread.c runtime/linux_tls.c runtime/linux_sync.c runtime/linux_platform.c runtime/guest_crt.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c $(wildcard runtime/*.h)
+ mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lm -o $@
+
+test: build/linux/threads
+
+build/linux/resource-atomics: tests/resource_atomics.c src/hhr.dll/lifted-0000.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h
+ mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -pthread -lm -o $@
+
+test: build/linux/resource-atomics
diff --git a/decompiled/runtime/eh32.c b/decompiled/runtime/eh32.c
@@ -60,6 +60,15 @@ static EH_THREAD_LOCAL recomp_ehframe_t* t_frames; /* newest first */
/* The exception a running catch funclet holds, for a bare `throw;`. */
static EH_THREAD_LOCAL uint32_t t_cur_obj, t_cur_info;
+#ifdef RECOMP_PORTABLE
+/* _endthreadex abandons guest frames without running C++ stack destructors. */
+void recomp_eh_thread_exit(void)
+{
+ t_frames = NULL;
+ t_cur_obj = t_cur_info = 0;
+}
+#endif
+
void recomp_eh_push(recomp_ehframe_t* f) { f->prev = t_frames; t_frames = f; }
void recomp_eh_pop(recomp_ehframe_t* f) {
diff --git a/decompiled/runtime/guest_exception.c b/decompiled/runtime/guest_exception.c
@@ -1,19 +1,24 @@
#include "guest_exception.h"
#include "guest_heap.h"
+#include <pthread.h>
static uint32_t exception_data;
+static pthread_once_t exception_once = PTHREAD_ONCE_INIT;
+
+static void initialize_exception_data(void)
+{
+ exception_data = guest_malloc(32);
+ if (!exception_data) abort();
+ /* RTTI is not implemented; these two slots dispatch to native C adapters. */
+ MEM32(exception_data) = 0;
+ MEM32(exception_data + 4) = 0xf1000000u;
+ MEM32(exception_data + 8) = 0xf1000004u;
+ memcpy((void *)ADDR(exception_data + 12), "Unknown exception", 18);
+}
static uint32_t exception_vtable(void)
{
- if (!exception_data) {
- exception_data = guest_malloc(32);
- if (!exception_data) abort();
- /* RTTI is not implemented; these two slots dispatch to native C adapters. */
- MEM32(exception_data) = 0;
- MEM32(exception_data + 4) = 0xf1000000u;
- MEM32(exception_data + 8) = 0xf1000004u;
- memcpy((void *)ADDR(exception_data + 12), "Unknown exception", 18);
- }
+ if (pthread_once(&exception_once, initialize_exception_data)) abort();
return exception_data + 4;
}
diff --git a/decompiled/runtime/guest_heap.c b/decompiled/runtime/guest_heap.c
@@ -3,6 +3,12 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#else
+#include <pthread.h>
+#endif
/* Host-only bookkeeping: guest objects contain only 32-bit guest addresses. */
struct block {
@@ -14,10 +20,15 @@ struct arena {
struct block *blocks;
struct arena *next;
};
+#ifdef _WIN32
+static SRWLOCK mutex = SRWLOCK_INIT;
+#else
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+#endif
static struct arena *arenas;
static uint32_t next_address = 0x60000000u;
-uint32_t guest_malloc(uint32_t size)
+static uint32_t guest_malloc_locked(uint32_t size)
{
uint64_t aligned = ((uint64_t)(size ? size : 1) + 15) & ~15ull;
if (aligned > 0x8fff0000u) return 0;
@@ -51,10 +62,10 @@ uint32_t guest_malloc(uint32_t size)
*arena = (struct arena){block, arenas};
arenas = arena;
next_address += span;
- return guest_malloc(size);
+ return guest_malloc_locked(size);
}
-void guest_free(uint32_t address)
+static void guest_free_locked(uint32_t address)
{
if (!address) return;
for (struct arena *arena = arenas; arena; arena = arena->next) {
@@ -76,21 +87,63 @@ void guest_free(uint32_t address)
abort();
}
-uint32_t guest_realloc(uint32_t address, uint32_t size)
+static uint32_t guest_realloc_locked(uint32_t address, uint32_t size)
{
- if (!address) return guest_malloc(size);
- if (!size) { guest_free(address); return 0; }
+ if (!address) return guest_malloc_locked(size);
+ if (!size) { guest_free_locked(address); return 0; }
for (struct arena *arena = arenas; arena; arena = arena->next) {
for (struct block *block = arena->blocks; block; block = block->next) {
if (block->address != address || block->free) continue;
if (size <= block->size) return address;
- uint32_t replacement = guest_malloc(size);
+ uint32_t replacement = guest_malloc_locked(size);
if (!replacement) return 0;
memcpy((void *)guest_address(replacement), (void *)guest_address(address), block->size);
- guest_free(address);
+ guest_free_locked(address);
return replacement;
}
}
fprintf(stderr, "Invalid guest realloc: %08x\n", address);
abort();
}
+
+/* Allocation metadata is shared by every guest thread. */
+static void lock_heap(void)
+{
+#ifdef _WIN32
+ AcquireSRWLockExclusive(&mutex);
+#else
+ if (pthread_mutex_lock(&mutex)) abort();
+#endif
+}
+
+static void unlock_heap(void)
+{
+#ifdef _WIN32
+ ReleaseSRWLockExclusive(&mutex);
+#else
+ if (pthread_mutex_unlock(&mutex)) abort();
+#endif
+}
+
+uint32_t guest_malloc(uint32_t size)
+{
+ lock_heap();
+ uint32_t address = guest_malloc_locked(size);
+ unlock_heap();
+ return address;
+}
+
+void guest_free(uint32_t address)
+{
+ lock_heap();
+ guest_free_locked(address);
+ unlock_heap();
+}
+
+uint32_t guest_realloc(uint32_t address, uint32_t size)
+{
+ lock_heap();
+ uint32_t replacement = guest_realloc_locked(address, size);
+ unlock_heap();
+ return replacement;
+}
diff --git a/decompiled/runtime/guest_stdio.c b/decompiled/runtime/guest_stdio.c
@@ -1,4 +1,5 @@
#define _GNU_SOURCE
+#include <pthread.h>
#include "guest_stdio.h"
#include "guest_crt.h"
#include "guest_heap.h"
@@ -167,7 +168,7 @@ static uint32_t open_stream(struct stream *stream, const char *name, const char
return stream->file;
}
-static void crt_fopen(void)
+static void crt_fopen_locked(void)
{
initialize_streams();
unsigned i;
@@ -187,7 +188,7 @@ static void crt_fopen(void)
g_esp += 4;
}
-static void crt_freopen(void)
+static void crt_freopen_locked(void)
{
struct stream *stream = find_stream(MEM32(g_esp + 12));
if (stream->descriptor >= 0) close_stream(stream);
@@ -227,13 +228,13 @@ static int put_character(struct stream *stream, unsigned char character)
return character;
}
-static void crt_fputc(void)
+static void crt_fputc_locked(void)
{
g_eax = put_character(find_stream(MEM32(g_esp + 8)), MEM32(g_esp + 4));
g_esp += 4;
}
-static void crt_fwrite(void)
+static void crt_fwrite_locked(void)
{
uint32_t bytes = MEM32(g_esp + 4), size = MEM32(g_esp + 8), count = MEM32(g_esp + 12);
if (!size || !count) { g_eax = 0; g_esp += 4; return; }
@@ -245,7 +246,7 @@ static void crt_fwrite(void)
g_esp += 4;
}
-static void crt_fputs(void)
+static void crt_fputs_locked(void)
{
const unsigned char *text = (const unsigned char *)ADDR(MEM32(g_esp + 4));
struct stream *stream = find_stream(MEM32(g_esp + 8));
@@ -254,20 +255,20 @@ static void crt_fputs(void)
g_esp += 4;
}
-static void crt_fflush(void)
+static void crt_fflush_locked(void)
{
uint32_t file = MEM32(g_esp + 4);
g_eax = file ? flush_stream(find_stream(file)) : flush_all();
g_esp += 4;
}
-static void crt_fclose(void)
+static void crt_fclose_locked(void)
{
g_eax = close_stream(find_stream(MEM32(g_esp + 4)));
g_esp += 4;
}
-static void crt_setvbuf(void)
+static void crt_setvbuf_locked(void)
{
struct stream *stream = find_stream(MEM32(g_esp + 4));
uint32_t file = stream->file, buffer = MEM32(g_esp + 8), mode = MEM32(g_esp + 12), size = MEM32(g_esp + 16);
@@ -293,7 +294,7 @@ static void crt_setvbuf(void)
g_esp += 4;
}
-static void crt_fileno(void)
+static void crt_fileno_locked(void)
{
struct stream *stream = find_stream(MEM32(g_esp + 4));
g_eax = stream->descriptor >= 0 ? MEM32(stream->file + 16) : file_error(EBADF);
@@ -333,14 +334,14 @@ static int64_t stream_position(struct stream *stream)
return position;
}
-static void crt_ftell(void)
+static void crt_ftell_locked(void)
{
int64_t position = stream_position(find_stream(MEM32(g_esp + 4)));
g_eax = position > INT32_MAX ? file_error(EINVAL) : (uint32_t)position;
g_esp += 4;
}
-static void crt_fseek(void)
+static void crt_fseek_locked(void)
{
struct stream *stream = find_stream(MEM32(g_esp + 4));
int64_t offset = (int32_t)MEM32(g_esp + 8);
@@ -398,13 +399,13 @@ static int fill_input(struct stream *stream)
return character;
}
-static void crt_filbuf(void)
+static void crt_filbuf_locked(void)
{
g_eax = fill_input(find_stream(MEM32(g_esp + 4)));
g_esp += 4;
}
-static void crt_fgetc(void)
+static void crt_fgetc_locked(void)
{
uint32_t file = MEM32(g_esp + 4);
struct stream *stream = find_stream(file);
@@ -416,7 +417,7 @@ static void crt_fgetc(void)
g_esp += 4;
}
-static void crt_fread(void)
+static void crt_fread_locked(void)
{
uint32_t output = MEM32(g_esp + 4), size = MEM32(g_esp + 8), count = MEM32(g_esp + 12);
if (!size || !count) { g_eax = 0; g_esp += 4; return; }
@@ -448,7 +449,7 @@ static void crt_fread(void)
g_esp += 4;
}
-static void crt_chmod(void)
+static void crt_chmod_locked(void)
{
const char *name = (const char *)ADDR(MEM32(g_esp + 4));
uint32_t mode = MEM32(g_esp + 8);
@@ -475,7 +476,7 @@ static void crt_chmod(void)
g_esp += 4;
}
-static void crt_stat(void)
+static void crt_stat_locked(void)
{
const char *name = (const char *)ADDR(MEM32(g_esp + 4));
uint32_t output = MEM32(g_esp + 8);
@@ -534,9 +535,38 @@ static void crt_stat(void)
g_esp += 4;
}
-static void crt_fprintf(void) { print_file(MEM32(g_esp + 4), MEM32(g_esp + 8), g_esp + 12); }
-static void crt_vfprintf(void) { print_file(MEM32(g_esp + 4), MEM32(g_esp + 8), MEM32(g_esp + 12)); }
-static void crt_printf(void) { print_file(guest_crt_data("_iob") + 32, MEM32(g_esp + 4), g_esp + 8); }
+static void crt_fprintf_locked(void) { print_file(MEM32(g_esp + 4), MEM32(g_esp + 8), g_esp + 12); }
+static void crt_vfprintf_locked(void) { print_file(MEM32(g_esp + 4), MEM32(g_esp + 8), MEM32(g_esp + 12)); }
+static void crt_printf_locked(void) { print_file(guest_crt_data("_iob") + 32, MEM32(g_esp + 4), g_esp + 8); }
+
+/* API calls serialize shared stream/handle state and synchronous file positions. */
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+static void call_serialized(recomp_func_t function)
+{
+ if (pthread_mutex_lock(&mutex)) abort();
+ function();
+ if (pthread_mutex_unlock(&mutex)) abort();
+}
+
+static void crt_fopen(void) { call_serialized(crt_fopen_locked); }
+static void crt_freopen(void) { call_serialized(crt_freopen_locked); }
+static void crt_fclose(void) { call_serialized(crt_fclose_locked); }
+static void crt_fflush(void) { call_serialized(crt_fflush_locked); }
+static void crt_fputc(void) { call_serialized(crt_fputc_locked); }
+static void crt_fwrite(void) { call_serialized(crt_fwrite_locked); }
+static void crt_fputs(void) { call_serialized(crt_fputs_locked); }
+static void crt_setvbuf(void) { call_serialized(crt_setvbuf_locked); }
+static void crt_fileno(void) { call_serialized(crt_fileno_locked); }
+static void crt_fprintf(void) { call_serialized(crt_fprintf_locked); }
+static void crt_vfprintf(void) { call_serialized(crt_vfprintf_locked); }
+static void crt_printf(void) { call_serialized(crt_printf_locked); }
+static void crt_chmod(void) { call_serialized(crt_chmod_locked); }
+static void crt_stat(void) { call_serialized(crt_stat_locked); }
+static void crt_ftell(void) { call_serialized(crt_ftell_locked); }
+static void crt_fseek(void) { call_serialized(crt_fseek_locked); }
+static void crt_fread(void) { call_serialized(crt_fread_locked); }
+static void crt_fgetc(void) { call_serialized(crt_fgetc_locked); }
+static void crt_filbuf(void) { call_serialized(crt_filbuf_locked); }
recomp_func_t guest_stdio_lookup(const char *name)
{
diff --git a/decompiled/runtime/linux_file.c b/decompiled/runtime/linux_file.c
@@ -1,4 +1,5 @@
#define _GNU_SOURCE
+#include <pthread.h>
#include "linux_file.h"
#include <errno.h>
#include <fcntl.h>
@@ -42,7 +43,7 @@ static uint32_t file_error(int error)
}
}
-static void create_file(void)
+static void create_file_locked(void)
{
const char *name = (const char *)ADDR(MEM32(g_esp + 4));
int buffered = MEM32(g_esp + 12) == 1 && MEM32(g_esp + 20) == 3 && MEM32(g_esp + 24) == 0x80;
@@ -101,7 +102,7 @@ static void create_file(void)
g_esp += 32;
}
-static void read_file(void)
+static void read_file_locked(void)
{
uint32_t output = MEM32(g_esp + 8), size = MEM32(g_esp + 12);
uint32_t count = MEM32(g_esp + 16);
@@ -136,7 +137,7 @@ static void read_file(void)
if (result >= 0) { MEM32(count) = result; g_eax = 1; }
}
-static void set_file_pointer(void)
+static void set_file_pointer_locked(void)
{
struct guest_file *handle = find_handle(MEM32(g_esp + 4));
uint32_t low = MEM32(g_esp + 8), high = MEM32(g_esp + 12);
@@ -175,7 +176,7 @@ static void set_file_pointer(void)
g_esp += 20;
}
-static void close_file(void)
+static void close_file_locked(void)
{
struct guest_file *handle = find_handle(MEM32(g_esp + 4));
g_eax = 0;
@@ -190,6 +191,20 @@ static void close_file(void)
g_esp += 8;
}
+/* API calls serialize shared stream/handle state and synchronous file positions. */
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+static void call_serialized(recomp_func_t function)
+{
+ if (pthread_mutex_lock(&mutex)) abort();
+ function();
+ if (pthread_mutex_unlock(&mutex)) abort();
+}
+
+static void create_file(void) { call_serialized(create_file_locked); }
+static void read_file(void) { call_serialized(read_file_locked); }
+static void set_file_pointer(void) { call_serialized(set_file_pointer_locked); }
+static void close_file(void) { call_serialized(close_file_locked); }
+
recomp_func_t linux_file_lookup(const char *name)
{
if (!strcmp(name, "CreateFileA")) return create_file;
diff --git a/decompiled/runtime/linux_host.c b/decompiled/runtime/linux_host.c
@@ -9,8 +9,12 @@
#include "../vendor/msvcp60/source/module.h"
#include "../vendor/ace/source/module.h"
#include <strings.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <sys/syscall.h>
+#include "linux_thread.h"
-static struct { const char *name; uint32_t base, entry; }
+static struct { const char *name; uint32_t base, entry; int disable_thread_calls; }
modules[sizeof(game_modules) / sizeof(game_modules[0]) + 2];
static const int module_count = sizeof(modules) / sizeof(modules[0]);
@@ -107,11 +111,10 @@ uint32_t recomp_funcinfo(uint32_t handler)
static void disable_thread_library_calls(void)
{
- /* The single-threaded host sends process notifications only. */
uint32_t module = MEM32(g_esp + 4);
g_eax = 0;
for (int i = 0; i < module_count; ++i)
- if (modules[i].base == module) g_eax = 1;
+ if (modules[i].base == module) { modules[i].disable_thread_calls = 1; g_eax = 1; }
if (!g_eax) MEM32(g_fs_base + 0x34) = 126; /* ERROR_MOD_NOT_FOUND */
g_esp += 8;
}
@@ -150,6 +153,23 @@ static void call_guest(uint32_t entry, const uint32_t *args, unsigned count)
}
static unsigned char attached[sizeof(modules) / sizeof(modules[0])];
+static int initialization_order[sizeof(modules) / sizeof(modules[0])];
+static int initialized_count;
+static pthread_mutex_t loader_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+void linux_thread_notify(uint32_t reason)
+{
+ /* DLL callbacks follow dependency initialization order, reversed on detach. */
+ if (pthread_mutex_lock(&loader_mutex)) abort();
+ for (int i = 0; i < initialized_count; ++i) {
+ int module = initialization_order[reason == 2 ? i : initialized_count - i - 1];
+ if (modules[module].disable_thread_calls) continue;
+ uint32_t args[] = {modules[module].base, reason, 0};
+ call_guest(modules[module].entry, args, 3);
+ }
+ if (pthread_mutex_unlock(&loader_mutex)) abort();
+}
+
static void attach_module(int module)
{
@@ -167,6 +187,7 @@ static void attach_module(int module)
fprintf(stderr, "[linux-host] attach %s\n", modules[module].name);
uint32_t args[] = {base, 1, 1};
call_guest(modules[module].entry, args, 3);
+ initialization_order[initialized_count++] = module;
if (!g_eax) {
fprintf(stderr, "Guest DLL rejected initialization: %s\n", modules[module].name);
exit(3);
@@ -206,8 +227,12 @@ int main(int argc, char **argv)
MEM32(g_fs_base + 4) = 0x08400000u;
MEM32(g_fs_base + 8) = 0x08000000u;
MEM32(g_fs_base + 0x18) = g_fs_base;
+ MEM32(g_fs_base + 0x20) = getpid();
+ MEM32(g_fs_base + 0x24) = syscall(SYS_gettid);
int client = module_named("Clientr.exe");
+ if (pthread_mutex_lock(&loader_mutex)) abort();
attach_module(client);
+ if (pthread_mutex_unlock(&loader_mutex)) abort();
call_guest(modules[client].entry, NULL, 0);
return 0;
}
diff --git a/decompiled/runtime/linux_imports.c b/decompiled/runtime/linux_imports.c
@@ -8,6 +8,9 @@
#include "linux_sync.h"
#include "linux_file.h"
#include "linux_tls.h"
+#include "linux_thread.h"
+#include <pthread.h>
+#include <stdatomic.h>
#include "linux_network.h"
#include "linux_graphics.h"
#include "linux_window.h"
@@ -15,9 +18,11 @@
/* External calls receive stable guest identifiers rather than host code addresses. */
static struct { const char *dll, *name; uint32_t ordinal; } imports[4096];
-static unsigned import_count, current_import;
+static _Atomic unsigned import_count;
+static _Thread_local unsigned current_import;
+static pthread_mutex_t import_mutex = PTHREAD_MUTEX_INITIALIZER;
-uint32_t linux_import_bind(const char *dll, const char *name, uint32_t ordinal)
+static uint32_t import_bind_locked(const char *dll, const char *name, uint32_t ordinal)
{
if (!strcasecmp(dll, "msvcrt.dll") && name) {
uint32_t data = guest_crt_data(name);
@@ -36,6 +41,14 @@ uint32_t linux_import_bind(const char *dll, const char *name, uint32_t ordinal)
return 0xf0000000u + 4 * import_count++;
}
+uint32_t linux_import_bind(const char *dll, const char *name, uint32_t ordinal)
+{
+ if (pthread_mutex_lock(&import_mutex)) abort();
+ uint32_t address = import_bind_locked(dll, name, ordinal);
+ if (pthread_mutex_unlock(&import_mutex)) abort();
+ return address;
+}
+
unsigned linux_import_count(void) { return import_count; }
static void external_call(void)
@@ -98,15 +111,25 @@ static void close_handle(void)
{
if ((MEM32(g_esp + 4) & 0xff000000u) == 0x05000000u)
linux_file_lookup("CloseHandle")();
+ else if ((MEM32(g_esp + 4) & 0xff000000u) == 0x06000000u)
+ linux_thread_lookup("CloseHandle")();
else linux_sync_lookup("CloseHandle")();
}
+static void wait_for_single_object(void)
+{
+ if ((MEM32(g_esp + 4) & 0xff000000u) == 0x06000000u)
+ linux_thread_lookup("WaitForSingleObject")();
+ else linux_sync_lookup("WaitForSingleObject")();
+}
+
static recomp_func_t library_lookup(const char *name)
{
if (!strcmp(name, "LoadLibraryA")) return load_library;
if (!strcmp(name, "FreeLibrary")) return free_library;
if (!strcmp(name, "GetProcAddress")) return get_proc_address;
if (!strcmp(name, "CloseHandle")) return close_handle;
+ if (!strcmp(name, "WaitForSingleObject")) return wait_for_single_object;
return NULL;
}
@@ -138,6 +161,7 @@ recomp_func_t recomp_lookup_import(uint32_t va)
if (!function) function = linux_module_lookup(imports[current_import].name);
if (!function) function = linux_sync_lookup(imports[current_import].name);
if (!function) function = linux_tls_lookup(imports[current_import].name);
+ if (!function) function = linux_thread_lookup(imports[current_import].name);
if (function) return function;
}
}
@@ -146,7 +170,8 @@ recomp_func_t recomp_lookup_import(uint32_t va)
extern void native32_shim_CxxThrowException(void);
return native32_shim_CxxThrowException;
}
- recomp_func_t function = guest_stdio_lookup(imports[current_import].name);
+ recomp_func_t function = linux_thread_lookup(imports[current_import].name);
+ if (!function) function = guest_stdio_lookup(imports[current_import].name);
if (!function) function = guest_crt_lookup(imports[current_import].name);
if (!function) function = guest_format_lookup(imports[current_import].name);
if (!function) function = guest_exception_lookup(imports[current_import].name);
diff --git a/decompiled/runtime/linux_platform.c b/decompiled/runtime/linux_platform.c
@@ -16,6 +16,7 @@ struct critical_section {
struct critical_section *next;
};
static struct critical_section *critical_sections;
+static pthread_mutex_t sections_mutex = PTHREAD_MUTEX_INITIALIZER;
static uint32_t unhandled_exception_filter;
static void check_pthread(int error)
@@ -23,7 +24,7 @@ static void check_pthread(int error)
if (error) { fprintf(stderr, "pthread: %s\n", strerror(error)); abort(); }
}
-static struct critical_section *find_critical_section(uint32_t address)
+static struct critical_section *find_critical_section_locked(uint32_t address)
{
for (struct critical_section *section = critical_sections; section; section = section->next)
if (section->address == address) return section;
@@ -31,6 +32,14 @@ static struct critical_section *find_critical_section(uint32_t address)
abort();
}
+static struct critical_section *find_critical_section(uint32_t address)
+{
+ check_pthread(pthread_mutex_lock(§ions_mutex));
+ struct critical_section *section = find_critical_section_locked(address);
+ check_pthread(pthread_mutex_unlock(§ions_mutex));
+ return section;
+}
+
static void initialize_critical_section(void)
{
struct critical_section *section = malloc(sizeof(*section));
@@ -41,10 +50,12 @@ static void initialize_critical_section(void)
check_pthread(pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE));
check_pthread(pthread_mutex_init(§ion->mutex, &attributes));
check_pthread(pthread_mutexattr_destroy(&attributes));
+ check_pthread(pthread_mutex_lock(§ions_mutex));
section->next = critical_sections;
critical_sections = section;
memset((void *)ADDR(section->address), 0, 24);
MEM32(section->address + 4) = UINT32_MAX;
+ check_pthread(pthread_mutex_unlock(§ions_mutex));
g_esp += 8;
}
@@ -69,12 +80,14 @@ static void leave_critical_section(void)
static void delete_critical_section(void)
{
- struct critical_section *section = find_critical_section(MEM32(g_esp + 4));
+ check_pthread(pthread_mutex_lock(§ions_mutex));
+ struct critical_section *section = find_critical_section_locked(MEM32(g_esp + 4));
check_pthread(pthread_mutex_destroy(§ion->mutex));
struct critical_section **link = &critical_sections;
while (*link != section) link = &(*link)->next;
*link = section->next;
free(section);
+ check_pthread(pthread_mutex_unlock(§ions_mutex));
g_esp += 8;
}
diff --git a/decompiled/runtime/linux_sync.c b/decompiled/runtime/linux_sync.c
@@ -4,6 +4,7 @@
#include <fcntl.h>
#include <linux/futex.h>
#include <stdatomic.h>
+#include <pthread.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/stat.h>
@@ -24,10 +25,12 @@ _Static_assert(sizeof(_Atomic uint32_t) == 4 && ATOMIC_INT_LOCK_FREE == 2,
struct semaphore_handle {
uint32_t id, access;
int fd, event;
+ unsigned references;
struct semaphore_state *state;
struct semaphore_handle *next;
};
static struct semaphore_handle *handles;
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static uint32_t next_handle = 0x100;
static void system_failure(const char *operation)
@@ -36,7 +39,7 @@ static void system_failure(const char *operation)
abort();
}
-static struct semaphore_handle *find_handle(uint32_t id)
+static struct semaphore_handle *find_handle_locked(uint32_t id)
{
for (struct semaphore_handle *handle = handles; handle; handle = handle->next)
if (handle->id == id) return handle;
@@ -44,7 +47,7 @@ static struct semaphore_handle *find_handle(uint32_t id)
return NULL;
}
-static uint32_t open_semaphore(const char *name, int create, int32_t initial,
+static uint32_t open_semaphore_locked(const char *name, int create, int32_t initial,
int32_t maximum, uint32_t access)
{
int directory = -1, fd = -1, existing = 0;
@@ -128,6 +131,7 @@ static uint32_t open_semaphore(const char *name, int create, int32_t initial,
handle->access = access;
handle->fd = fd;
handle->event = 0;
+ handle->references = 1;
handle->state = state;
handle->next = handles;
handles = handle;
@@ -135,19 +139,19 @@ static uint32_t open_semaphore(const char *name, int create, int32_t initial,
return handle->id;
}
-static void create_semaphore(void)
+static void create_semaphore_locked(void)
{
if (MEM32(g_esp + 4)) {
fprintf(stderr, "Semaphore security attributes/inheritance are not implemented\n");
abort();
}
uint32_t name = MEM32(g_esp + 16);
- g_eax = open_semaphore(name ? (const char *)ADDR(name) : NULL, 1,
+ g_eax = open_semaphore_locked(name ? (const char *)ADDR(name) : NULL, 1,
MEM32(g_esp + 8), MEM32(g_esp + 12), 0x1f0003);
g_esp += 20;
}
-static void open_named_semaphore(void)
+static void open_named_semaphore_locked(void)
{
uint32_t access = MEM32(g_esp + 4);
if (MEM32(g_esp + 8) || (access & ~0x1f0003u)) {
@@ -156,26 +160,26 @@ static void open_named_semaphore(void)
}
uint32_t name = MEM32(g_esp + 12);
g_eax = 0;
- if (name) g_eax = open_semaphore((const char *)ADDR(name), 0, 0, 0, access);
+ if (name) g_eax = open_semaphore_locked((const char *)ADDR(name), 0, 0, 0, access);
else MEM32(g_fs_base + 0x34) = 87;
g_esp += 16;
}
-static void create_event(void)
+static void create_event_locked(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);
+ g_eax = open_semaphore_locked(NULL, 1, MEM32(g_esp + 12) != 0, 1, 0x1f0003);
handles->event = 1;
g_esp += 20;
}
-static void change_event(int signaled)
+static void change_event_locked(int signaled)
{
- struct semaphore_handle *handle = find_handle(MEM32(g_esp + 4));
+ struct semaphore_handle *handle = find_handle_locked(MEM32(g_esp + 4));
g_eax = 0;
if (handle && !handle->event) MEM32(g_fs_base + 0x34) = 6;
else if (handle) {
@@ -188,28 +192,34 @@ static void change_event(int signaled)
g_esp += 8;
}
-static void set_event(void) { change_event(1); }
-static void reset_event(void) { change_event(0); }
+static void set_event_locked(void) { change_event_locked(1); }
+static void reset_event_locked(void) { change_event_locked(0); }
-static void close_handle(void)
+static void release_handle_locked(struct semaphore_handle *handle)
{
- struct semaphore_handle *handle = find_handle(MEM32(g_esp + 4));
+ if (--handle->references) return;
+ if (munmap(handle->state, sizeof(*handle->state))) system_failure("semaphore unmap");
+ if (handle->fd >= 0 && close(handle->fd)) system_failure("semaphore handle close");
+ free(handle);
+}
+
+static void close_handle_locked(void)
+{
+ struct semaphore_handle *handle = find_handle_locked(MEM32(g_esp + 4));
g_eax = 0;
if (handle) {
struct semaphore_handle **link = &handles;
while (*link != handle) link = &(*link)->next;
*link = handle->next;
- if (munmap(handle->state, sizeof(*handle->state))) system_failure("semaphore unmap");
- if (handle->fd >= 0 && close(handle->fd)) system_failure("semaphore handle close");
- free(handle);
+ release_handle_locked(handle);
g_eax = 1;
}
g_esp += 8;
}
-static void release_semaphore(void)
+static void release_semaphore_locked(void)
{
- struct semaphore_handle *handle = find_handle(MEM32(g_esp + 4));
+ struct semaphore_handle *handle = find_handle_locked(MEM32(g_esp + 4));
int32_t increment = MEM32(g_esp + 8);
g_eax = 0;
if (handle && handle->event) MEM32(g_fs_base + 0x34) = 6;
@@ -235,13 +245,14 @@ static void release_semaphore(void)
g_esp += 16;
}
-static void wait_for_single_object(void)
+static void wait_for_single_object_locked(void)
{
- struct semaphore_handle *handle = find_handle(MEM32(g_esp + 4));
+ struct semaphore_handle *handle = find_handle_locked(MEM32(g_esp + 4));
uint32_t milliseconds = MEM32(g_esp + 8);
g_eax = UINT32_MAX; /* WAIT_FAILED */
if (handle && !(handle->access & 0x100000)) MEM32(g_fs_base + 0x34) = 5;
else if (handle) {
+ ++handle->references;
struct timespec deadline;
if (milliseconds != UINT32_MAX) {
if (clock_gettime(CLOCK_MONOTONIC, &deadline)) system_failure("semaphore clock");
@@ -259,16 +270,37 @@ static void wait_for_single_object(void)
continue;
}
if (!milliseconds) { g_eax = 258; break; }
- if (!syscall(SYS_futex, &handle->state->count, FUTEX_WAIT_BITSET, 0,
- milliseconds == UINT32_MAX ? NULL : &deadline, NULL, FUTEX_BITSET_MATCH_ANY)) continue;
- if (errno == EAGAIN || errno == EINTR) continue;
- if (errno == ETIMEDOUT) { g_eax = 258; break; }
+ if (pthread_mutex_unlock(&mutex)) abort();
+ int result = syscall(SYS_futex, &handle->state->count, FUTEX_WAIT_BITSET, 0,
+ milliseconds == UINT32_MAX ? NULL : &deadline, NULL, FUTEX_BITSET_MATCH_ANY);
+ int error = errno;
+ if (pthread_mutex_lock(&mutex)) abort();
+ if (!result || error == EAGAIN || error == EINTR) continue;
+ if (error == ETIMEDOUT) { g_eax = 258; break; }
+ errno = error;
system_failure("semaphore wait");
}
+ release_handle_locked(handle);
}
g_esp += 12;
}
+static void call_serialized(recomp_func_t function)
+{
+ if (pthread_mutex_lock(&mutex)) abort();
+ function();
+ if (pthread_mutex_unlock(&mutex)) abort();
+}
+
+static void create_semaphore(void) { call_serialized(create_semaphore_locked); }
+static void open_named_semaphore(void) { call_serialized(open_named_semaphore_locked); }
+static void close_handle(void) { call_serialized(close_handle_locked); }
+static void release_semaphore(void) { call_serialized(release_semaphore_locked); }
+static void wait_for_single_object(void) { call_serialized(wait_for_single_object_locked); }
+static void create_event(void) { call_serialized(create_event_locked); }
+static void set_event(void) { call_serialized(set_event_locked); }
+static void reset_event(void) { call_serialized(reset_event_locked); }
+
recomp_func_t linux_sync_lookup(const char *name)
{
static const struct { const char *name; recomp_func_t function; } functions[] = {
diff --git a/decompiled/runtime/linux_thread.c b/decompiled/runtime/linux_thread.c
@@ -0,0 +1,242 @@
+#define _GNU_SOURCE
+#include "linux_thread.h"
+#include "guest_heap.h"
+#include "guest_crt.h"
+#include <errno.h>
+#include <pthread.h>
+#include <time.h>
+#include <unistd.h>
+
+void recomp_eh_thread_exit(void);
+
+/* A live thread and its open handle each own a reference. Closing a handle
+ * never terminates the thread; waits keep their own reference while blocked. */
+struct guest_thread {
+ uint32_t handle, id, entry, argument, allocation, stack_size, exit_code;
+ unsigned references;
+ int complete, suspended;
+ pthread_cond_t changed;
+ struct guest_thread *next;
+};
+static struct guest_thread *threads;
+static uint32_t next_handle = 0x06000000u;
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+static _Thread_local struct guest_thread *current_thread;
+
+static void check_pthread(int error)
+{
+ if (error) { fprintf(stderr, "Thread pthread: %s\n", strerror(error)); abort(); }
+}
+
+static struct guest_thread *find_thread_locked(uint32_t handle)
+{
+ for (struct guest_thread *thread = threads; thread; thread = thread->next)
+ if (thread->handle == handle) return thread;
+ MEM32(g_fs_base + 0x34) = 6;
+ return NULL;
+}
+
+static void release_thread_locked(struct guest_thread *thread)
+{
+ if (--thread->references) return;
+ check_pthread(pthread_cond_destroy(&thread->changed));
+ free(thread);
+}
+
+static void finish_thread(void *argument)
+{
+ struct guest_thread *thread = argument;
+ recomp_eh_thread_exit();
+ MEM32(g_fs_base) = UINT32_MAX;
+ g_esp = g_fs_base - 0x100;
+ linux_thread_notify(3); /* DLL_THREAD_DETACH */
+ guest_free(thread->allocation);
+ check_pthread(pthread_mutex_lock(&mutex));
+ thread->complete = 1;
+ check_pthread(pthread_cond_broadcast(&thread->changed));
+ release_thread_locked(thread);
+ check_pthread(pthread_mutex_unlock(&mutex));
+}
+
+static void *run_thread(void *argument)
+{
+ struct guest_thread *thread = argument;
+ current_thread = thread;
+ g_fs_base = thread->allocation + thread->stack_size;
+ g_esp = g_fs_base - 0x100;
+ memset((void *)ADDR(thread->allocation), 0, thread->stack_size + 0x10000);
+ MEM32(g_fs_base) = UINT32_MAX;
+ MEM32(g_fs_base + 4) = g_fs_base;
+ MEM32(g_fs_base + 8) = thread->allocation;
+ MEM32(g_fs_base + 0x18) = g_fs_base;
+ MEM32(g_fs_base + 0x20) = getpid();
+ MEM32(g_fs_base + 0x24) = gettid();
+
+ /* Publish the real host thread ID before _beginthreadex returns. */
+ check_pthread(pthread_mutex_lock(&mutex));
+ thread->id = gettid();
+ check_pthread(pthread_cond_broadcast(&thread->changed));
+ while (thread->suspended) check_pthread(pthread_cond_wait(&thread->changed, &mutex));
+ check_pthread(pthread_mutex_unlock(&mutex));
+
+ pthread_cleanup_push(finish_thread, thread);
+ linux_thread_notify(2); /* DLL_THREAD_ATTACH */
+ uint32_t stack = g_esp;
+ PUSH32(g_esp, thread->argument);
+ PUSH32(g_esp, RECOMP_RETADDR);
+ recomp_func_t entry = recomp_lookup(thread->entry);
+ if (!entry) {
+ fprintf(stderr, "Missing guest thread entry %08x\n", thread->entry);
+ abort();
+ }
+ entry();
+ if (g_esp != stack) {
+ fprintf(stderr, "Guest thread %08x returned with unbalanced stdcall stack\n", thread->entry);
+ abort();
+ }
+ thread->exit_code = g_eax;
+ pthread_cleanup_pop(1);
+ return NULL;
+}
+
+static void begin_thread(void)
+{
+ uint32_t stack_size = MEM32(g_esp + 8), entry = MEM32(g_esp + 12);
+ uint32_t argument = MEM32(g_esp + 16), flags = MEM32(g_esp + 20);
+ uint32_t id = MEM32(g_esp + 24);
+ if (MEM32(g_esp + 4) || (flags & ~4u)) {
+ fprintf(stderr, "Thread security attributes/creation flags %08x are not implemented\n", flags);
+ abort();
+ }
+ g_esp += 4; /* _beginthreadex is cdecl; its entry function is stdcall. */
+ g_eax = 0;
+ if (!entry) { MEM32(guest_crt_errno_address()) = 22; return; }
+ if (!stack_size) stack_size = 0x400000;
+ uint64_t rounded = ((uint64_t)stack_size + 0xffffu) & ~0xffffull;
+ if (rounded > UINT32_MAX - 0x10000u) { MEM32(guest_crt_errno_address()) = 12; return; }
+
+ struct guest_thread *thread = calloc(1, sizeof(*thread));
+ if (!thread) { MEM32(guest_crt_errno_address()) = 12; return; }
+ thread->allocation = guest_malloc(rounded + 0x10000);
+ if (!thread->allocation) { free(thread); MEM32(guest_crt_errno_address()) = 12; return; }
+ thread->entry = entry;
+ thread->argument = argument;
+ thread->stack_size = rounded;
+ thread->references = 2;
+ thread->suspended = flags == 4;
+ pthread_condattr_t attributes;
+ check_pthread(pthread_condattr_init(&attributes));
+ check_pthread(pthread_condattr_setclock(&attributes, CLOCK_MONOTONIC));
+ check_pthread(pthread_cond_init(&thread->changed, &attributes));
+ check_pthread(pthread_condattr_destroy(&attributes));
+
+ check_pthread(pthread_mutex_lock(&mutex));
+ if (next_handle >= 0x07000000u) abort();
+ thread->handle = next_handle;
+ next_handle += 4;
+ pthread_attr_t host_attributes;
+ check_pthread(pthread_attr_init(&host_attributes));
+ check_pthread(pthread_attr_setdetachstate(&host_attributes, PTHREAD_CREATE_DETACHED));
+ pthread_t host;
+ int error = pthread_create(&host, &host_attributes, run_thread, thread);
+ check_pthread(pthread_attr_destroy(&host_attributes));
+ if (error) {
+ check_pthread(pthread_cond_destroy(&thread->changed));
+ guest_free(thread->allocation);
+ free(thread);
+ MEM32(guest_crt_errno_address()) = error == EAGAIN ? 11 : 12;
+ } else {
+ thread->next = threads;
+ threads = thread;
+ while (!thread->id) check_pthread(pthread_cond_wait(&thread->changed, &mutex));
+ if (id) MEM32(id) = thread->id;
+ g_eax = thread->handle;
+ }
+ check_pthread(pthread_mutex_unlock(&mutex));
+}
+
+static void end_thread(void)
+{
+ if (!current_thread) {
+ fprintf(stderr, "_endthreadex outside a created guest thread\n");
+ abort();
+ }
+ current_thread->exit_code = MEM32(g_esp + 4);
+ pthread_exit(NULL);
+}
+
+static void close_thread(void)
+{
+ check_pthread(pthread_mutex_lock(&mutex));
+ struct guest_thread *thread = find_thread_locked(MEM32(g_esp + 4));
+ g_eax = thread != NULL;
+ if (thread) {
+ struct guest_thread **link = &threads;
+ while (*link != thread) link = &(*link)->next;
+ *link = thread->next;
+ release_thread_locked(thread);
+ }
+ check_pthread(pthread_mutex_unlock(&mutex));
+ g_esp += 8;
+}
+
+static void wait_thread(void)
+{
+ uint32_t milliseconds = MEM32(g_esp + 8);
+ check_pthread(pthread_mutex_lock(&mutex));
+ struct guest_thread *thread = find_thread_locked(MEM32(g_esp + 4));
+ g_eax = UINT32_MAX;
+ if (thread) {
+ ++thread->references;
+ struct timespec deadline;
+ if (clock_gettime(CLOCK_MONOTONIC, &deadline)) abort();
+ deadline.tv_sec += milliseconds / 1000;
+ deadline.tv_nsec += (milliseconds % 1000) * 1000000;
+ if (deadline.tv_nsec >= 1000000000) { ++deadline.tv_sec; deadline.tv_nsec -= 1000000000; }
+ int error = 0;
+ while (!thread->complete && !error) {
+ error = milliseconds == UINT32_MAX ? pthread_cond_wait(&thread->changed, &mutex) :
+ pthread_cond_timedwait(&thread->changed, &mutex, &deadline);
+ if (error != ETIMEDOUT) check_pthread(error);
+ }
+ g_eax = thread->complete ? 0 : 258;
+ release_thread_locked(thread);
+ }
+ check_pthread(pthread_mutex_unlock(&mutex));
+ g_esp += 12;
+}
+
+static void get_exit_code(void)
+{
+ check_pthread(pthread_mutex_lock(&mutex));
+ struct guest_thread *thread = find_thread_locked(MEM32(g_esp + 4));
+ g_eax = thread != NULL;
+ if (thread) MEM32(MEM32(g_esp + 8)) = thread->complete ? thread->exit_code : 259;
+ check_pthread(pthread_mutex_unlock(&mutex));
+ g_esp += 12;
+}
+
+static void resume_thread(void)
+{
+ check_pthread(pthread_mutex_lock(&mutex));
+ struct guest_thread *thread = find_thread_locked(MEM32(g_esp + 4));
+ g_eax = UINT32_MAX;
+ if (thread) {
+ g_eax = thread->suspended;
+ thread->suspended = 0;
+ check_pthread(pthread_cond_broadcast(&thread->changed));
+ }
+ check_pthread(pthread_mutex_unlock(&mutex));
+ g_esp += 8;
+}
+
+recomp_func_t linux_thread_lookup(const char *name)
+{
+ if (!strcmp(name, "_beginthreadex")) return begin_thread;
+ if (!strcmp(name, "_endthreadex")) return end_thread;
+ if (!strcmp(name, "CloseHandle")) return close_thread;
+ if (!strcmp(name, "WaitForSingleObject")) return wait_thread;
+ if (!strcmp(name, "GetExitCodeThread")) return get_exit_code;
+ if (!strcmp(name, "ResumeThread")) return resume_thread;
+ return NULL;
+}
diff --git a/decompiled/runtime/linux_thread.h b/decompiled/runtime/linux_thread.h
@@ -0,0 +1,8 @@
+#ifndef LINUX_THREAD_H
+#define LINUX_THREAD_H
+#include "recomp_types.h"
+
+recomp_func_t linux_thread_lookup(const char *name);
+void linux_thread_notify(uint32_t reason);
+
+#endif
diff --git a/decompiled/runtime/recomp_state.c b/decompiled/runtime/recomp_state.c
@@ -1,15 +1,15 @@
#include "recomp_types.h"
-uint32_t g_eax, g_ecx, g_edx, g_esp, g_ebx, g_esi, g_edi, g_ebp;
-double g_st[8];
-int g_fp_top;
-uint16_t g_fpu_cw = 0x027F;
-uint16_t g_seg_cs, g_seg_ds, g_seg_es, g_seg_fs, g_seg_gs, g_seg_ss;
-uint64_t g_mm[8];
-xmm_t g_xmm[8];
-uint32_t g_mxcsr = 0x1F80;
-uint32_t g_fs_base, g_gs_base;
+RECOMP_THREAD_LOCAL uint32_t g_eax, g_ecx, g_edx, g_esp, g_ebx, g_esi, g_edi, g_ebp;
+RECOMP_THREAD_LOCAL double g_st[8];
+RECOMP_THREAD_LOCAL int g_fp_top;
+RECOMP_THREAD_LOCAL uint16_t g_fpu_cw = 0x027F;
+RECOMP_THREAD_LOCAL uint16_t g_seg_cs, g_seg_ds, g_seg_es, g_seg_fs, g_seg_gs, g_seg_ss;
+RECOMP_THREAD_LOCAL uint64_t g_mm[8];
+RECOMP_THREAD_LOCAL xmm_t g_xmm[8];
+RECOMP_THREAD_LOCAL uint32_t g_mxcsr = 0x1F80;
+RECOMP_THREAD_LOCAL uint32_t g_fs_base, g_gs_base;
ptrdiff_t g_mem_base = 0;
-uint32_t g_cur_func;
-uint32_t g_icall_trace[ICALL_TRACE_SIZE], g_icall_from[ICALL_TRACE_SIZE];
-uint32_t g_icall_trace_idx, g_icall_count;
+RECOMP_THREAD_LOCAL uint32_t g_cur_func;
+RECOMP_THREAD_LOCAL uint32_t g_icall_trace[ICALL_TRACE_SIZE], g_icall_from[ICALL_TRACE_SIZE];
+RECOMP_THREAD_LOCAL uint32_t g_icall_trace_idx, g_icall_count;
diff --git a/decompiled/runtime/recomp_types.h b/decompiled/runtime/recomp_types.h
@@ -30,8 +30,15 @@
* since most VC6 code uses FPO (Frame Pointer Omission).
* ============================================================ */
+/* Each portable host thread executes an independent guest CPU. */
+#ifdef RECOMP_PORTABLE
+#define RECOMP_THREAD_LOCAL _Thread_local
+#else
+#define RECOMP_THREAD_LOCAL
+#endif
+
/* Volatile (caller-saved) registers */
-extern uint32_t g_eax, g_ecx, g_edx, g_esp;
+extern RECOMP_THREAD_LOCAL uint32_t g_eax, g_ecx, g_edx, g_esp;
/* Callee-saved registers (also global for implicit parameter passing).
* ebp is global too, not a per-function local: MSVC's __EH_prolog sets its
@@ -39,15 +46,15 @@ extern uint32_t g_eax, g_ecx, g_edx, g_esp;
* would discard it and every C++ EH function would then address off zero.
* Real x86 has one ebp; FPO functions that never touch it simply pass the
* caller's through, which is exactly the behaviour we want. */
-extern uint32_t g_ebx, g_esi, g_edi, g_ebp;
+extern RECOMP_THREAD_LOCAL uint32_t g_ebx, g_esi, g_edi, g_ebp;
/* The x87 FPU stack is GLOBAL (8 shared registers), not per-function: helpers
* like __ftol receive their argument on the FPU stack from the caller, and the
* control word persists across calls. A per-function local stack would make every
* cross-call FPU value read as 0. */
-extern double g_st[8];
-extern int g_fp_top;
-extern uint16_t g_fpu_cw;
+extern RECOMP_THREAD_LOCAL double g_st[8];
+extern RECOMP_THREAD_LOCAL int g_fp_top;
+extern RECOMP_THREAD_LOCAL uint16_t g_fpu_cw;
/* The arithmetic flags a function RETURNS with. The lazy flag state is local
* to each lifted function, but assembly and the CRT return results in flags:
@@ -62,12 +69,12 @@ extern uint16_t g_fpu_cw;
#else
#define RECOMP_WEAK __attribute__((weak))
#endif
-RECOMP_WEAK uint32_t g_flag_k, g_flag_a, g_flag_b, g_flag_cf;
+RECOMP_WEAK RECOMP_THREAD_LOCAL uint32_t g_flag_k, g_flag_a, g_flag_b, g_flag_cf;
#define RECOMP_FLAGS_OUT() (g_flag_k = _flag_k, g_flag_a = _flag_a, g_flag_b = _flag_b, g_flag_cf = _cf)
#define RECOMP_FLAGS_IN() (_flag_k = g_flag_k, _flag_a = g_flag_a, _flag_b = g_flag_b, _cf = g_flag_cf)
/* Segment registers (flat mode Win32 - effectively unused) */
-extern uint16_t g_seg_cs, g_seg_ds, g_seg_es, g_seg_fs, g_seg_gs, g_seg_ss;
+extern RECOMP_THREAD_LOCAL uint16_t g_seg_cs, g_seg_ds, g_seg_es, g_seg_fs, g_seg_gs, g_seg_ss;
/* Function pointer type for recompiled functions */
typedef void (*recomp_func_t)(void);
@@ -179,8 +186,8 @@ extern ptrdiff_t g_mem_base;
/* Thread-relative segment bases. In Win32, fs: points at the TIB/TEB; gs is
* unused on x86. The lifter emits fs:/gs: accesses as FS_BASE/GS_BASE + addr,
* so the runtime points g_fs_base at a simulated TIB (VA). cs/ds/es/ss are flat. */
-extern uint32_t g_fs_base;
-extern uint32_t g_gs_base;
+extern RECOMP_THREAD_LOCAL uint32_t g_fs_base;
+extern RECOMP_THREAD_LOCAL uint32_t g_gs_base;
#define FS_BASE g_fs_base
#define GS_BASE g_gs_base
@@ -188,7 +195,7 @@ extern uint32_t g_gs_base;
* hlt and segment loads (tools/lift/lift32.py _lift_dos). A DOS host such as
* runtime/dos32 defines them; nothing else references them. Under DOS/4GW es
* is a real selector (the PSP, the environment), so es: overrides get a base. */
-extern uint32_t g_es_base;
+extern RECOMP_THREAD_LOCAL uint32_t g_es_base;
#define ES_BASE g_es_base
void recomp_int(int n);
uint8_t recomp_in8(uint32_t port);
@@ -675,7 +682,7 @@ static inline uint32_t recomp_eflags_setcf(uint32_t kind, uint32_t a, uint32_t b
* wants them thread-local instead.
* ============================================================ */
-extern uint64_t g_mm[8];
+extern RECOMP_THREAD_LOCAL uint64_t g_mm[8];
#define MM_W(v, i) ((int16_t)((uint64_t)(v) >> ((i) * 16)))
#define MM_D(v, i) ((int32_t)((uint64_t)(v) >> ((i) * 32)))
@@ -881,8 +888,8 @@ typedef union {
uint8_t u8[16];
} xmm_t;
-extern xmm_t g_xmm[8];
-extern uint32_t g_mxcsr;
+extern RECOMP_THREAD_LOCAL xmm_t g_xmm[8];
+extern RECOMP_THREAD_LOCAL uint32_t g_mxcsr;
static inline xmm_t xmm_ld(uint32_t a) { xmm_t v; memcpy(&v, (const void*)ADDR(a), 16); return v; }
static inline void xmm_st(uint32_t a, xmm_t v) { memcpy((void*)ADDR(a), &v, 16); }
@@ -953,7 +960,7 @@ static inline uint32_t sse_cmp_pred(double a, double b, int p) {
#else
#define RECOMP_SHARED_DATA __attribute__((weak))
#endif
-RECOMP_SHARED_DATA int64_t g_st_i64[8] = {0};
+RECOMP_SHARED_DATA RECOMP_THREAD_LOCAL int64_t g_st_i64[8] = {0};
static inline void fp_push_impl(double* st, int* top, double val) {
/* Shift stack down, push new value */
@@ -1064,7 +1071,7 @@ static inline void CPUID_impl(uint32_t eax_val, uint32_t ebx_val, uint32_t ecx_v
/* The VA of the function currently executing (see RECOMP_ENTER below); an
* unresolved dispatch is far more useful with its caller named. */
-extern uint32_t g_cur_func;
+extern RECOMP_THREAD_LOCAL uint32_t g_cur_func;
/* ICALL trace ring buffer for crash diagnostics.
*
@@ -1079,10 +1086,10 @@ extern uint32_t g_cur_func;
* report showed it as a caller and never as a target, and the function that
* handed it a null argument was already gone. 128 costs a kilobyte. */
#define ICALL_TRACE_SIZE 128
-extern uint32_t g_icall_trace[ICALL_TRACE_SIZE];
-extern uint32_t g_icall_from[ICALL_TRACE_SIZE];
-extern uint32_t g_icall_trace_idx;
-extern uint32_t g_icall_count;
+extern RECOMP_THREAD_LOCAL uint32_t g_icall_trace[ICALL_TRACE_SIZE];
+extern RECOMP_THREAD_LOCAL uint32_t g_icall_from[ICALL_TRACE_SIZE];
+extern RECOMP_THREAD_LOCAL uint32_t g_icall_trace_idx;
+extern RECOMP_THREAD_LOCAL uint32_t g_icall_count;
/* Lookup functions */
recomp_func_t recomp_lookup(uint32_t va); /* binary search in dispatch table */
@@ -1176,12 +1183,12 @@ recomp_func_t recomp_lookup_import(uint32_t va); /* import bridges */
/* Always-on: the VA of the function currently executing. A plain global store
* (no call), so unlike the ring tracer below it doesn't force register reloads --
* useful for pinning a crash to a function without perturbing codegen. */
-extern uint32_t g_cur_func;
+extern RECOMP_THREAD_LOCAL uint32_t g_cur_func;
#ifdef RECOMP_TRACE
#define RECOMP_ENTER_SIZE 1024
-extern uint32_t g_enter_trace[RECOMP_ENTER_SIZE];
-extern uint32_t g_enter_idx;
+extern RECOMP_THREAD_LOCAL uint32_t g_enter_trace[RECOMP_ENTER_SIZE];
+extern RECOMP_THREAD_LOCAL uint32_t g_enter_idx;
void recomp_trace_enter(uint32_t va);
#define RECOMP_ENTER(va) do { g_cur_func = (va); RECOMP_FLAGS_IN(); recomp_trace_enter(va); } while (0)
#else
@@ -1216,10 +1223,10 @@ void recomp_eh_pop(recomp_ehframe_t* f);
* another guest thread's flag never let that thread run: Yuri's Revenge's
* exit spins until its sound thread acknowledges a stop (0x0040A047) and hung
* there. The registers go back to the globals around the hand-over, which is
- * all a native call does. The counter is global and unsynchronised on purpose:
- * only the thread holding the machine runs lifted code. */
+ * all a native call does. Portable threads own independent loop counters;
+ * the Windows host serializes its shared machine state. */
RECOMP_WEAK void (*recomp_yield_hook)(void);
-RECOMP_WEAK uint32_t g_backedges;
+RECOMP_WEAK RECOMP_THREAD_LOCAL uint32_t g_backedges;
#ifndef RECOMP_YIELD_EVERY
#define RECOMP_YIELD_EVERY 0x10000u
#endif
diff --git a/decompiled/src/hhr.dll/lifted-0000.c b/decompiled/src/hhr.dll/lifted-0000.c
@@ -5533,8 +5533,7 @@ L_310033BB:
eax = MEM32(ebp + (-0x14)); /* 0x310033BB: mov eax, dword ptr [ebp - 0x14] */
MEM32(ebp + 0x10) = eax; /* 0x310033BE: mov dword ptr [ebp + 0x10], eax */
ebx = MEM32(ebp + 0x10); /* 0x310033C1: mov ebx, dword ptr [ebp + 0x10] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x310033C4: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x310033C4: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
esi = MEM32(ebp + 0x8); /* 0x310033C7: mov esi, dword ptr [ebp + 8] */
ecx = MEM32(ebp + (-0x14)); /* 0x310033CA: mov ecx, dword ptr [ebp - 0x14] */
@@ -8589,8 +8588,7 @@ L_31004558:
PUSH32(esp, ebx); /* 0x3100455A: push ebx */
MEM32(ebp + 0x8) = ecx; /* 0x3100455B: mov dword ptr [ebp + 8], ecx */
ebx = MEM32(ebp + 0x8); /* 0x3100455E: mov ebx, dword ptr [ebp + 8] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) - 1; /* 0x31004561: lock dec dword ptr [ebx] */
+ _flag_a = __atomic_fetch_sub((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x31004561: lock dec dword ptr [ebx] */
_flag_k = FK_DEC;
ebx = POP32_VAL(esp); /* 0x31004564: pop ebx */
L_31004565:
@@ -8632,12 +8630,13 @@ L_31004590:
PUSH32(esp, esi); /* 0x31004594: push esi */
PUSH32(esp, edi); /* 0x31004595: push edi */
ebx = MEM32(ebp + 0x8); /* 0x31004596: mov ebx, dword ptr [ebp + 8] */
- eax = MEM32(ebx); /* 0x31004599: mov eax, dword ptr [ebx] */
+ eax = __atomic_load_n((uint32_t *)ADDR(ebx), __ATOMIC_SEQ_CST); /* 0x31004599: mov eax, dword ptr [ebx] */
L_3100459B:
edx = eax + 0x1; /* 0x3100459B: lea edx, [eax + 1] */
- _flag_a = (uint32_t)(eax); _flag_b = (uint32_t)(MEM32(ebx));
- _cf = (uint32_t)((uint32_t)_flag_a < (uint32_t)_flag_b);
- { uint32_t _d = MEM32(ebx); if (eax == _d) { MEM32(ebx) = edx; } else { eax = _d; } } /* 0x3100459E: lock cmpxchg dword ptr [ebx], edx */
+ _flag_a = eax; _flag_b = eax;
+ __atomic_compare_exchange_n((uint32_t *)ADDR(ebx), &_flag_b, edx, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); /* 0x3100459E: lock cmpxchg dword ptr [ebx], edx */
+ _cf = _flag_a < _flag_b;
+ eax = _flag_b;
_flag_k = FK_CMP;
RECOMP_BACKEDGE();
if (CMP_NE(_flag_a, _flag_b)) goto L_3100459B; /* 0x310045A2: jne 0x3100459b */
@@ -8669,8 +8668,7 @@ L_310045B0:
MEM32(eax) = 0x31051118u; /* 0x310045B7: mov dword ptr [eax], 0x31051118 */
MEM32(ebp + (-0x4)) = 0x31051118u; /* 0x310045BD: mov dword ptr [ebp - 4], 0x31051118 */
ebx = MEM32(ebp + (-0x4)); /* 0x310045C4: mov ebx, dword ptr [ebp - 4] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x310045C7: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x310045C7: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
ebx = POP32_VAL(esp); /* 0x310045CA: pop ebx */
esp = ebp; /* 0x310045CB: mov esp, ebp */
@@ -8872,8 +8870,7 @@ L_310046E0:
PUSH32(esp, edi); /* 0x310046EC: push edi */
MEM32(ebp + 0x8) = ecx; /* 0x310046ED: mov dword ptr [ebp + 8], ecx */
ebx = MEM32(ebp + 0x8); /* 0x310046F0: mov ebx, dword ptr [ebp + 8] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x310046F3: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x310046F3: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
edi = MEM32(esi); /* 0x310046F6: mov edi, dword ptr [esi] */
edx = MEM32(eax); /* 0x310046F8: mov edx, dword ptr [eax] */
@@ -8944,12 +8941,13 @@ L_31004740:
PUSH32(esp, esi); /* 0x31004744: push esi */
PUSH32(esp, edi); /* 0x31004745: push edi */
ebx = MEM32(ebp + 0x8); /* 0x31004746: mov ebx, dword ptr [ebp + 8] */
- eax = MEM32(ebx); /* 0x31004749: mov eax, dword ptr [ebx] */
+ eax = __atomic_load_n((uint32_t *)ADDR(ebx), __ATOMIC_SEQ_CST); /* 0x31004749: mov eax, dword ptr [ebx] */
L_3100474B:
edx = eax + (-0x1); /* 0x3100474B: lea edx, [eax - 1] */
- _flag_a = (uint32_t)(eax); _flag_b = (uint32_t)(MEM32(ebx));
- _cf = (uint32_t)((uint32_t)_flag_a < (uint32_t)_flag_b);
- { uint32_t _d = MEM32(ebx); if (eax == _d) { MEM32(ebx) = edx; } else { eax = _d; } } /* 0x3100474E: lock cmpxchg dword ptr [ebx], edx */
+ _flag_a = eax; _flag_b = eax;
+ __atomic_compare_exchange_n((uint32_t *)ADDR(ebx), &_flag_b, edx, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); /* 0x3100474E: lock cmpxchg dword ptr [ebx], edx */
+ _cf = _flag_a < _flag_b;
+ eax = _flag_b;
_flag_k = FK_CMP;
RECOMP_BACKEDGE();
if (CMP_NE(_flag_a, _flag_b)) goto L_3100474B; /* 0x31004752: jne 0x3100474b */
diff --git a/decompiled/src/hhr.dll/lifted-0003.c b/decompiled/src/hhr.dll/lifted-0003.c
@@ -4289,8 +4289,7 @@ L_310086F3:
ecx = MEM32(ebp + (-0x10)); /* 0x310086F3: mov ecx, dword ptr [ebp - 0x10] */
MEM32(ebp + 0xC) = ecx; /* 0x310086F6: mov dword ptr [ebp + 0xc], ecx */
ebx = MEM32(ebp + 0xC); /* 0x310086F9: mov ebx, dword ptr [ebp + 0xc] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x310086FC: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x310086FC: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
esi = MEM32(ebp + 0x8); /* 0x310086FF: mov esi, dword ptr [ebp + 8] */
edx = MEM32(ebp + (-0x10)); /* 0x31008702: mov edx, dword ptr [ebp - 0x10] */
@@ -6143,8 +6142,7 @@ L_31008F90:
PUSH32(esp, ebx); /* 0x31008F97: push ebx */
MEM32(ebp + (-0x4)) = ecx; /* 0x31008F98: mov dword ptr [ebp - 4], ecx */
ebx = MEM32(ebp + (-0x4)); /* 0x31008F9B: mov ebx, dword ptr [ebp - 4] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x31008F9E: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x31008F9E: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
ebx = POP32_VAL(esp); /* 0x31008FA1: pop ebx */
esp = ebp; /* 0x31008FA2: mov esp, ebp */
diff --git a/decompiled/src/hhr.dll/lifted-0004.c b/decompiled/src/hhr.dll/lifted-0004.c
@@ -7415,8 +7415,7 @@ L_3100A720:
ecx = MEM32(ebp + (-0x10)); /* 0x3100A776: mov ecx, dword ptr [ebp - 0x10] */
MEM32(ebp + 0xC) = ecx; /* 0x3100A779: mov dword ptr [ebp + 0xc], ecx */
ebx = MEM32(ebp + 0xC); /* 0x3100A77C: mov ebx, dword ptr [ebp + 0xc] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x3100A77F: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x3100A77F: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
esi = MEM32(ebp + 0x8); /* 0x3100A782: mov esi, dword ptr [ebp + 8] */
edx = MEM32(ebp + (-0x10)); /* 0x3100A785: mov edx, dword ptr [ebp - 0x10] */
@@ -13001,8 +13000,7 @@ L_3100B98A:
eax = MEM32(ebp + (-0x10)); /* 0x3100B98A: mov eax, dword ptr [ebp - 0x10] */
MEM32(ebp + 0xC) = eax; /* 0x3100B98D: mov dword ptr [ebp + 0xc], eax */
ebx = MEM32(ebp + 0xC); /* 0x3100B990: mov ebx, dword ptr [ebp + 0xc] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x3100B993: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x3100B993: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
ecx = MEM32(ebp + (-0x10)); /* 0x3100B996: mov ecx, dword ptr [ebp - 0x10] */
edx = MEM32(ebp + 0x8); /* 0x3100B999: mov edx, dword ptr [ebp + 8] */
diff --git a/decompiled/src/hhr.dll/lifted-0005.c b/decompiled/src/hhr.dll/lifted-0005.c
@@ -11858,8 +11858,7 @@ L_3100F700:
ecx = MEM32(ebp + 0xC); /* 0x3100F75A: mov ecx, dword ptr [ebp + 0xc] */
MEM32(ebp + (-0x10)) = ecx; /* 0x3100F75D: mov dword ptr [ebp - 0x10], ecx */
ebx = MEM32(ebp + (-0x10)); /* 0x3100F760: mov ebx, dword ptr [ebp - 0x10] */
- _flag_a = (uint32_t)(MEM32(ebx)); _flag_b = (uint32_t)(1);
- MEM32(ebx) = MEM32(ebx) + 1; /* 0x3100F763: lock inc dword ptr [ebx] */
+ _flag_a = __atomic_fetch_add((uint32_t *)ADDR(ebx), 1, __ATOMIC_SEQ_CST); _flag_b = 1; /* 0x3100F763: lock inc dword ptr [ebx] */
_flag_k = FK_INC;
esi = MEM32(ebp + 0x8); /* 0x3100F766: mov esi, dword ptr [ebp + 8] */
edx = MEM32(ebp + 0xC); /* 0x3100F769: mov edx, dword ptr [ebp + 0xc] */
diff --git a/decompiled/tests/dynamic_imports.c b/decompiled/tests/dynamic_imports.c
@@ -4,8 +4,15 @@
#include <sys/wait.h>
#include <unistd.h>
-recomp_func_t recomp_lookup(uint32_t address) { (void)address; return NULL; }
+static void thread_entry(void)
+{
+ g_eax = MEM32(g_esp + 4) + 1;
+ g_esp += 8;
+}
+recomp_func_t recomp_lookup(uint32_t address) { return address == 0x11001000 ? thread_entry : NULL; }
recomp_func_t linux_module_lookup(const char *name) { (void)name; return NULL; }
+void linux_thread_notify(uint32_t reason) { (void)reason; }
+void recomp_eh_thread_exit(void) {}
void native32_shim_CxxThrowException(void) { abort(); }
static uint32_t call(const char *name, uint32_t first, uint32_t second)
@@ -20,7 +27,9 @@ static uint32_t call(const char *name, uint32_t first, uint32_t second)
MEM32(g_esp + 4) = first;
MEM32(g_esp + 8) = second;
recomp_lookup_import(linux_import_bind("kernel32.dll", name, 0))();
- assert(g_esp == 0x5000ff00u + (!strcmp(name, "GetProcAddress") ? 12 : 8));
+ assert(g_esp == 0x5000ff00u +
+ (!strcmp(name, "GetProcAddress") || !strcmp(name, "WaitForSingleObject") ||
+ !strcmp(name, "GetExitCodeThread") ? 12 : 8));
assert(g_ebx == 0x12345678u && g_esi == 0x23456789u);
assert(g_edi == 0x3456789au && g_ebp == 0x456789abu);
assert(g_cur_func == 0x280028f0u);
@@ -149,6 +158,24 @@ static void file_and_event_handles_close_through_imports(void)
assert(!unlink(path));
}
+static void thread_handles_dispatch_through_imports(void)
+{
+ uint32_t begin = linux_import_bind("msvcrt.dll", "_beginthreadex", 0);
+ g_esp = 0x5000ff00;
+ uint32_t args[] = {0, 0, 0x11001000, 41, 0, 0x50003000};
+ for (unsigned i = 0; i < 6; ++i) MEM32(g_esp + 4 + i * 4) = args[i];
+
+ recomp_lookup_import(begin)();
+ uint32_t thread = g_eax;
+ assert(thread && g_esp == 0x5000ff04 && MEM32(0x50003000));
+ uint32_t result = call("WaitForSingleObject", thread, 10000);
+ uint32_t queried = call("GetExitCodeThread", thread, 0x50003004);
+ uint32_t closed = call("CloseHandle", thread, 0);
+
+ assert(result == 0 && queried == 1 && MEM32(0x50003004) == 42 && closed == 1);
+ assert(call("WaitForSingleObject", thread, 0) == UINT32_MAX && MEM32(g_fs_base + 0x34) == 6);
+}
+
int main(void)
{
assert(guest_map("dynamic imports test", 0x50000000u, 0x10000u));
@@ -158,6 +185,7 @@ int main(void)
import_names_are_owned_and_calls_are_dispatched();
unresolved_window_call_fails_explicitly();
file_and_event_handles_close_through_imports();
+ thread_handles_dispatch_through_imports();
puts("dynamic imports: 14 window symbols, stable guest IDs, lifetime, errors, dispatch and ABI passed");
return 0;
}
diff --git a/decompiled/tests/guest_rand.c b/decompiled/tests/guest_rand.c
@@ -119,7 +119,7 @@ static void threads_have_independent_seeds(void)
call(1, 1);
assert(next_random() == 41);
- /* Threads run sequentially: the guest register file is not concurrent yet. */
+ /* Join before updating the shared sequence digest from the parent. */
for (unsigned i = 0; i < 2; ++i) {
#ifdef _WIN32
HANDLE thread = CreateThread(NULL, 0, thread_sequence, NULL, 0, NULL);
diff --git a/decompiled/tests/resource_atomics.c b/decompiled/tests/resource_atomics.c
@@ -0,0 +1,156 @@
+#include <assert.h>
+#include <stdint.h>
+#include <stdio.h>
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+static volatile uint32_t counter;
+#else
+#include "recomp_types.h"
+#include <pthread.h>
+void sub_31004590(void);
+void sub_31004740(void);
+void sub_310045B0(void);
+recomp_func_t recomp_lookup(uint32_t address) { (void)address; return NULL; }
+recomp_func_t recomp_lookup_manual(uint32_t address) { (void)address; return NULL; }
+recomp_func_t recomp_lookup_import(uint32_t address) { (void)address; abort(); }
+static _Thread_local uint32_t stack_base = 0x50000000;
+#endif
+
+static void set_counter(uint32_t value)
+{
+#ifdef _WIN32
+ counter = value;
+#else
+ MEM32(0x31051118) = value;
+#endif
+}
+
+static uint32_t get_counter(void)
+{
+#ifdef _WIN32
+ return counter;
+#else
+ return MEM32(0x31051118);
+#endif
+}
+
+static uint32_t change(int operation, uint32_t carry, uint32_t *flags)
+{
+#ifdef _WIN32
+ uint32_t previous = counter;
+ if (operation == 0) {
+ __asm__ volatile("1: leal 1(%0),%%edx; lock cmpxchgl %%edx,%1; jne 1b; pushfl; popl %2"
+ : "+&a"(previous), "+m"(counter), "=r"(*flags) : : "edx", "cc", "memory");
+ } else if (operation == 1) {
+ __asm__ volatile("1: leal -1(%0),%%edx; lock cmpxchgl %%edx,%1; jne 1b; pushfl; popl %2"
+ : "+&a"(previous), "+m"(counter), "=r"(*flags) : : "edx", "cc", "memory");
+ } else {
+ __asm__ volatile("btl $0,%2; lock incl %1; pushfl; popl %0"
+ : "=r"(*flags), "+m"(counter) : "r"(carry) : "cc", "memory");
+ }
+ *flags &= 0x8d5;
+ return previous;
+#else
+ g_esp = stack_base + 0xff00;
+ MEM32(g_esp) = RECOMP_RETADDR;
+ MEM32(g_esp + 4) = 0x31051118;
+ g_ecx = stack_base + 0x100;
+ g_ebx = 0x12345678; g_esi = 0x23456789; g_edi = 0x3456789a; g_ebp = 0x456789ab;
+ g_flag_k = FK_EFLAGS; g_flag_a = carry; g_flag_b = 0; g_flag_cf = carry;
+ if (operation == 0) sub_31004590();
+ else if (operation == 1) sub_31004740();
+ else sub_310045B0();
+ assert(g_esp == stack_base + 0xff04);
+ assert(g_ebx == 0x12345678 && g_esi == 0x23456789 && g_edi == 0x3456789a && g_ebp == 0x456789ab);
+ if (operation == 2) assert(MEM32(stack_base + 0x100) == 0x31051118 && g_eax == stack_base + 0x100);
+ *flags = recomp_eflags(g_flag_k, g_flag_a, g_flag_b, g_flag_cf, 1) & 0x8d5;
+ return operation == 2 ? g_flag_a : g_eax;
+#endif
+}
+
+static void boundaries_preserve_results_and_flags(void)
+{
+ const uint32_t inputs[] = {0, 1, 0x7fffffff, 0x80000000, 0xffffffff};
+ const uint32_t increment_flags[] = {0, 1, 0x894, 0x81, 0x54};
+ for (unsigned i = 0; i < 5; ++i) {
+ for (unsigned operation = 0; operation < 3; ++operation) {
+ uint32_t flags;
+ set_counter(inputs[i]);
+
+ uint32_t previous = change(operation, i & 1, &flags);
+
+ assert(previous == inputs[i]);
+ assert(get_counter() == inputs[i] + (operation == 1 ? UINT32_MAX : 1));
+ assert(flags == (operation == 2 ? increment_flags[i] : 0x44));
+ }
+ }
+}
+
+struct worker { unsigned index, operation; uint64_t sum; };
+#ifdef _WIN32
+static DWORD WINAPI contend(void *argument)
+#else
+static void *contend(void *argument)
+#endif
+{
+ struct worker *worker = argument;
+#ifndef _WIN32
+ stack_base = 0x50000000 + worker->index * 0x10000;
+#endif
+ for (unsigned i = 0; i < 50000; ++i) {
+ uint32_t flags;
+ worker->sum += change(worker->operation, 0, &flags);
+ if (worker->operation != 2) assert(flags == 0x44);
+ }
+ return 0;
+}
+
+static void concurrent_updates_are_not_lost(void)
+{
+ for (unsigned operation = 0; operation < 3; ++operation) {
+ struct worker workers[8];
+#ifdef _WIN32
+ HANDLE threads[8];
+#else
+ pthread_t threads[8];
+#endif
+ set_counter(operation == 1 ? 400000 : 0);
+
+ for (unsigned i = 0; i < 8; ++i) {
+ workers[i] = (struct worker){i, operation, 0};
+#ifdef _WIN32
+ threads[i] = CreateThread(NULL, 0, contend, &workers[i], 0, NULL);
+ assert(threads[i]);
+#else
+ assert(!pthread_create(&threads[i], NULL, contend, &workers[i]));
+#endif
+ }
+ uint64_t sum = 0;
+ for (unsigned i = 0; i < 8; ++i) {
+#ifdef _WIN32
+ assert(WaitForSingleObject(threads[i], 10000) == WAIT_OBJECT_0);
+ assert(CloseHandle(threads[i]));
+#else
+ assert(!pthread_join(threads[i], NULL));
+#endif
+ sum += workers[i].sum;
+ }
+
+ assert(get_counter() == (operation == 1 ? 0 : 400000));
+ /* INC does not return its previous value in the native instruction. */
+ if (operation != 2) assert(sum == (operation == 1 ? 80000200000ull : 79999800000ull));
+ }
+}
+
+int main(void)
+{
+#ifndef _WIN32
+ assert(guest_map("resource atomic counter", 0x31050000, 0x10000));
+ assert(guest_map("resource atomic stacks", 0x50000000, 0x80000));
+#endif
+ boundaries_preserve_results_and_flags();
+ concurrent_updates_are_not_lost();
+ puts("AO resource atomics: 15 boundary/flag cases and 1200000 contended updates across 8 threads passed");
+ return 0;
+}
diff --git a/decompiled/tests/threads.c b/decompiled/tests/threads.c
@@ -0,0 +1,401 @@
+#include <assert.h>
+#include <stdint.h>
+#include <stdio.h>
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+static uintptr_t (__cdecl *native_begin)(void *, unsigned, unsigned (__stdcall *)(void *), void *, unsigned, unsigned *);
+static void (__cdecl *native_end)(unsigned);
+static int *(__cdecl *native_errno)(void);
+static CRITICAL_SECTION counter_lock;
+static unsigned counter;
+#else
+#include "linux_thread.h"
+#include "linux_tls.h"
+#include "linux_sync.h"
+#include "linux_platform.h"
+#include "guest_heap.h"
+#include "guest_crt.h"
+#include "guest_exception.h"
+#include <pthread.h>
+#include <stdatomic.h>
+static pthread_barrier_t cpu_barrier;
+static _Atomic unsigned attached, detached;
+static _Thread_local int notified;
+void sub_42001000(void);
+void sub_42001100(void);
+void native32_shim_CxxThrowException(void);
+uint32_t recomp_funcinfo(uint32_t handler) { assert(handler == 0x42002000); return 0x42003000; }
+recomp_func_t recomp_lookup_manual(uint32_t address) { (void)address; return NULL; }
+
+static void throw_and_catch(void)
+{
+ uint32_t stack = g_esp, frame = g_ebp, fs = MEM32(g_fs_base);
+ PUSH32(g_esp, RECOMP_RETADDR);
+ sub_42001000();
+ assert(g_eax == 42 && g_esp == stack && g_ebp == frame && MEM32(g_fs_base) == fs);
+}
+
+static uint32_t call(recomp_func_t function, unsigned count, const uint32_t *args, int cdecl)
+{
+ uint32_t stack = g_esp;
+ g_esp -= 0x100;
+ MEM32(g_esp) = RECOMP_RETADDR;
+ for (unsigned i = 0; i < count; ++i) MEM32(g_esp + 4 + i * 4) = args[i];
+ function();
+ assert(g_esp == stack - 0x100 + (cdecl ? 4 : (count + 1) * 4));
+ g_esp = stack;
+ return g_eax;
+}
+
+void linux_thread_notify(uint32_t reason)
+{
+ assert(MEM32(g_fs_base + 0x18) == g_fs_base);
+ assert(MEM32(g_fs_base) == UINT32_MAX);
+ assert(g_esp > MEM32(g_fs_base + 8) && g_esp < MEM32(g_fs_base + 4));
+ if (reason == 2) {
+ assert(!notified && MEM32(MEM32(g_fs_base + 8)) == 0);
+ MEM32(MEM32(g_fs_base + 8)) = 0xfeedcafe;
+ notified = 1;
+ ++attached;
+ }
+ else { assert(reason == 3 && notified); notified = 0; ++detached; }
+ throw_and_catch();
+ g_eax = 0xdeadbeef; /* Notifications must not replace a thread's exit code. */
+}
+
+recomp_func_t recomp_lookup_import(uint32_t address)
+{
+ fprintf(stderr, "Unexpected thread-test import %08x\n", address);
+ abort();
+}
+#endif
+
+static uint32_t tls_index, ready, gate, done;
+static uint32_t observed_ids[4];
+
+static void increment_counter(void)
+{
+#ifdef _WIN32
+ EnterCriticalSection(&counter_lock);
+ ++counter;
+ LeaveCriticalSection(&counter_lock);
+#else
+ uint32_t section = 0x50002000;
+ call(linux_platform_lookup("kernel32.dll", "EnterCriticalSection"), 1, §ion, 0);
+ ++MEM32(0x50002100);
+ call(linux_platform_lookup("kernel32.dll", "LeaveCriticalSection"), 1, §ion, 0);
+#endif
+}
+
+static uint32_t tls_get(void)
+{
+#ifdef _WIN32
+ return (uintptr_t)TlsGetValue(tls_index);
+#else
+ return call(linux_tls_lookup("TlsGetValue"), 1, &tls_index, 0);
+#endif
+}
+
+static void tls_set(uint32_t value)
+{
+#ifdef _WIN32
+ assert(TlsSetValue(tls_index, (void *)(uintptr_t)value));
+#else
+ uint32_t args[] = {tls_index, value};
+ assert(call(linux_tls_lookup("TlsSetValue"), 2, args, 0));
+#endif
+}
+
+static uint32_t semaphore(void)
+{
+#ifdef _WIN32
+ return (uintptr_t)CreateSemaphoreA(NULL, 0, 4, NULL);
+#else
+ uint32_t args[] = {0, 0, 4, 0};
+ return call(linux_sync_lookup("CreateSemaphoreA"), 4, args, 0);
+#endif
+}
+
+static void signal_semaphore(uint32_t handle, uint32_t count)
+{
+#ifdef _WIN32
+ assert(ReleaseSemaphore((HANDLE)(uintptr_t)handle, count, NULL));
+#else
+ uint32_t args[] = {handle, count, 0};
+ assert(call(linux_sync_lookup("ReleaseSemaphore"), 3, args, 0));
+#endif
+}
+
+static uint32_t wait(uint32_t handle, uint32_t timeout, int thread)
+{
+#ifdef _WIN32
+ return WaitForSingleObject((HANDLE)(uintptr_t)handle, timeout);
+#else
+ uint32_t args[] = {handle, timeout};
+ return call(thread ? linux_thread_lookup("WaitForSingleObject") : linux_sync_lookup("WaitForSingleObject"), 2, args, 0);
+#endif
+}
+
+static uint32_t close_handle(uint32_t handle, int thread)
+{
+#ifdef _WIN32
+ return CloseHandle((HANDLE)(uintptr_t)handle);
+#else
+ return call(thread ? linux_thread_lookup("CloseHandle") : linux_sync_lookup("CloseHandle"), 1, &handle, 0);
+#endif
+}
+
+static uint32_t exit_code(uint32_t handle)
+{
+#ifdef _WIN32
+ DWORD code;
+ assert(GetExitCodeThread((HANDLE)(uintptr_t)handle, &code));
+ return code;
+#else
+ uint32_t args[] = {handle, g_esp - 0x200};
+ assert(call(linux_thread_lookup("GetExitCodeThread"), 2, args, 0));
+ return MEM32(args[1]);
+#endif
+}
+
+static uint32_t resume(uint32_t handle)
+{
+#ifdef _WIN32
+ return ResumeThread((HANDLE)(uintptr_t)handle);
+#else
+ return call(linux_thread_lookup("ResumeThread"), 1, &handle, 0);
+#endif
+}
+
+static unsigned worker(uint32_t tag)
+{
+ assert(tls_get() == 0);
+ tls_set(0x12340000 + tag);
+#ifdef _WIN32
+ observed_ids[tag] = GetCurrentThreadId();
+ assert(*native_errno() == 0);
+ *native_errno() = 100 + tag;
+#else
+ assert(notified);
+ observed_ids[tag] = call(linux_platform_lookup("kernel32.dll", "GetCurrentThreadId"), 0, NULL, 0);
+ assert(observed_ids[tag] == MEM32(g_fs_base + 0x24));
+ assert(MEM32(guest_crt_errno_address()) == 0);
+ MEM32(guest_crt_errno_address()) = 100 + tag;
+#endif
+ if (tag) {
+ signal_semaphore(ready, 1);
+ assert(wait(gate, 10000, 0) == 0);
+ }
+
+#ifndef _WIN32
+ if (tag == 1 || tag == 2) {
+ /* Both guest CPUs must retain every register while the other executes.
+ * Allocation, reallocation and freeing also contend on the shared heap. */
+ for (unsigned i = 0; i < 128; ++i) {
+ g_eax = tag; g_ecx = tag + 1; g_edx = tag + 2; g_ebx = tag + 3;
+ g_esi = tag + 4; g_edi = tag + 5; g_ebp = tag + 6;
+ g_flag_k = tag; g_flag_a = tag + 7; g_flag_b = tag + 8; g_flag_cf = tag & 1;
+ g_fp_top = tag; g_st[tag] = tag + 0.5; g_fpu_cw = 0x27f + tag * 0x400;
+ g_mm[0] = 0x1234567800000000ull + tag;
+ memset(g_xmm, tag, sizeof(g_xmm));
+ g_mxcsr = 0x1f80 + tag * 0x2000;
+ g_seg_fs = tag; g_gs_base = tag + 9; g_cur_func = tag + 10;
+ g_icall_trace[0] = tag + 11; g_icall_from[0] = tag + 12;
+ g_icall_trace_idx = tag + 13; g_icall_count = tag + 14;
+ g_st_i64[0] = 0x123456789abcdef0ll + tag;
+ g_backedges = tag + 15;
+ uint32_t stack = g_esp, teb = g_fs_base;
+ MEM32(stack - 4) = tag;
+ int barrier = pthread_barrier_wait(&cpu_barrier);
+ assert(!barrier || barrier == PTHREAD_BARRIER_SERIAL_THREAD);
+
+ uint32_t memory = guest_malloc(31 + i);
+ assert(memory);
+ memset((void *)ADDR(memory), tag, 31 + i);
+ memory = guest_realloc(memory, 4096 + i);
+ assert(memory && MEM8(memory) == tag && MEM8(memory + 30 + i) == tag);
+ guest_free(memory);
+ assert(g_eax == tag && g_ecx == tag + 1 && g_edx == tag + 2 && g_ebx == tag + 3);
+ assert(g_esi == tag + 4 && g_edi == tag + 5 && g_ebp == tag + 6);
+ assert(g_flag_k == tag && g_flag_a == tag + 7 && g_flag_b == tag + 8 && g_flag_cf == (tag & 1));
+ assert(g_fp_top == tag && g_st[tag] == tag + 0.5 && g_fpu_cw == 0x27f + tag * 0x400);
+ assert(g_mm[0] == 0x1234567800000000ull + tag && ((unsigned char *)g_xmm)[127] == tag);
+ assert(g_mxcsr == 0x1f80 + tag * 0x2000 && g_seg_fs == tag && g_gs_base == tag + 9);
+ assert(g_cur_func == tag + 10 && g_icall_trace[0] == tag + 11 && g_icall_from[0] == tag + 12);
+ assert(g_icall_trace_idx == tag + 13 && g_icall_count == tag + 14);
+ assert(g_st_i64[0] == 0x123456789abcdef0ll + tag && g_backedges == tag + 15);
+ assert(g_esp == stack && g_fs_base == teb && MEM32(stack - 4) == tag);
+ increment_counter();
+ throw_and_catch();
+ uint32_t object = guest_malloc(12);
+ assert(object);
+ g_ecx = object;
+ call(guest_exception_lookup("??0exception@@QAE@XZ"), 0, NULL, 0);
+ uint32_t message = call(guest_exception_lookup("?what@exception@@UBEPBDXZ"), 0, NULL, 0);
+ assert(!strcmp((const char *)ADDR(message), "Unknown exception"));
+ call(guest_exception_lookup("??1exception@@UAE@XZ"), 0, NULL, 0);
+ guest_free(object);
+ barrier = pthread_barrier_wait(&cpu_barrier);
+ assert(!barrier || barrier == PTHREAD_BARRIER_SERIAL_THREAD);
+ }
+ }
+ assert(MEM32(guest_crt_errno_address()) == 100 + tag);
+#else
+ if (tag == 1 || tag == 2)
+ for (unsigned i = 0; i < 128; ++i) increment_counter();
+ assert(*native_errno() == 100 + (int)tag);
+#endif
+ assert(tls_get() == 0x12340000 + tag);
+ if (tag == 3) signal_semaphore(done, 1);
+ return 0x12345600 + tag;
+}
+
+#ifdef _WIN32
+static unsigned __stdcall returning_entry(void *argument) { return worker((uintptr_t)argument); }
+static unsigned __stdcall exiting_entry(void *argument) { native_end(worker((uintptr_t)argument)); abort(); }
+#else
+static void returning_entry(void) { g_eax = worker(MEM32(g_esp + 4)); g_esp += 8; }
+static void exiting_entry(void)
+{
+ uint32_t code = worker(MEM32(g_esp + 4));
+ /* Model _endthreadex abandoning a generated C++ frame and its FS record. */
+ recomp_ehframe_t abandoned;
+ recomp_eh_push(&abandoned);
+ MEM32(g_fs_base) = g_esp - 0x1000;
+ call(linux_thread_lookup("_endthreadex"), 1, &code, 1);
+ abort();
+}
+recomp_func_t recomp_lookup(uint32_t address)
+{
+ if (address == 0x11001000) return returning_entry;
+ if (address == 0x11002000) return exiting_entry;
+ if (address == 0x42001000) return sub_42001000;
+ if (address == 0x42001100) return sub_42001100;
+ if (address == 0x42002000) return native32_shim_CxxThrowException;
+ return NULL;
+}
+#endif
+
+static uint32_t begin(uint32_t tag, int suspended, int exits, uint32_t *id)
+{
+#ifdef _WIN32
+ return native_begin(NULL, 0, exits ? exiting_entry : returning_entry, (void *)(uintptr_t)tag, suspended ? 4 : 0, id);
+#else
+ uint32_t args[] = {0, 0, exits ? 0x11002000 : 0x11001000, tag, suspended ? 4 : 0, g_esp - 0x200};
+ uint32_t handle = call(linux_thread_lookup("_beginthreadex"), 6, args, 1);
+ *id = MEM32(args[5]);
+ return handle;
+#endif
+}
+
+static void suspended_thread_returns_and_remains_signaled(void)
+{
+ uint32_t id = 0;
+ uint32_t thread = begin(0, 1, 0, &id);
+ assert(thread && id && exit_code(thread) == 259);
+
+ assert(wait(thread, 0, 1) == 258);
+ assert(wait(thread, 10, 1) == 258);
+ assert(resume(thread) == 1);
+ assert(resume(thread) == 0);
+ assert(wait(thread, 10000, 1) == 0);
+
+ assert(id == observed_ids[0]);
+ assert(exit_code(thread) == 0x12345600);
+ assert(wait(thread, 0, 1) == 0 && wait(thread, 0, 1) == 0);
+ assert(close_handle(thread, 1));
+ assert(!close_handle(thread, 1));
+ assert(wait(thread, 0, 1) == UINT32_MAX);
+}
+
+static void concurrent_threads_keep_private_state(void)
+{
+ uint32_t ids[2];
+ uint32_t first = begin(1, 0, 0, &ids[0]);
+ uint32_t second = begin(2, 0, 1, &ids[1]);
+ assert(first && second && first != second && ids[0] != ids[1]);
+ assert(wait(ready, 10000, 0) == 0 && wait(ready, 10000, 0) == 0);
+
+ signal_semaphore(gate, 2);
+ assert(wait(first, 10000, 1) == 0);
+ assert(wait(second, 10000, 1) == 0);
+
+ assert(exit_code(first) == 0x12345601 && exit_code(second) == 0x12345602);
+ assert(ids[0] == observed_ids[1] && ids[1] == observed_ids[2]);
+#ifdef _WIN32
+ assert(counter == 256);
+#else
+ assert(MEM32(0x50002100) == 256);
+#endif
+ assert(tls_get() == 0xabcdef01);
+ assert(close_handle(first, 1) && close_handle(second, 1));
+}
+
+static void closing_a_running_thread_does_not_terminate_it(void)
+{
+ uint32_t id;
+ uint32_t thread = begin(3, 0, 0, &id);
+ assert(thread && wait(ready, 10000, 0) == 0);
+
+ assert(close_handle(thread, 1));
+ signal_semaphore(gate, 1);
+
+ assert(wait(done, 10000, 0) == 0);
+ assert(id == observed_ids[3]);
+}
+
+int main(void)
+{
+#ifdef _WIN32
+ HMODULE crt = LoadLibraryA("msvcrt.dll");
+ assert(crt);
+ native_begin = (void *)GetProcAddress(crt, "_beginthreadex");
+ native_end = (void *)GetProcAddress(crt, "_endthreadex");
+ native_errno = (void *)GetProcAddress(crt, "_errno");
+ assert(native_begin && native_end && native_errno);
+ tls_index = TlsAlloc();
+ InitializeCriticalSection(&counter_lock);
+#else
+ assert(guest_map("thread test main stack and TEB", 0x50000000, 0x20000));
+ g_esp = 0x5000ff00;
+ g_fs_base = 0x50010000;
+ /* The generated throw/catch fixture uses VC6 metadata, with no x86 code. */
+ assert(guest_map("thread test EH metadata", 0x42000000, 0x10000));
+ MEM32(0x42003000) = 0x19930520;
+ MEM32(0x42003004) = 1; MEM32(0x42003008) = 0x42003100;
+ MEM32(0x4200300c) = 1; MEM32(0x42003010) = 0x42003200;
+ MEM32(0x42003100) = UINT32_MAX;
+ MEM32(0x42003208) = 1; MEM32(0x4200320c) = 1;
+ MEM32(0x42003210) = 0x42003300;
+ MEM32(0x4200330c) = 0x42001100;
+ assert(!pthread_barrier_init(&cpu_barrier, NULL, 2));
+ tls_index = call(linux_tls_lookup("TlsAlloc"), 0, NULL, 0);
+ uint32_t section = 0x50002000;
+ call(linux_platform_lookup("kernel32.dll", "InitializeCriticalSection"), 1, §ion, 0);
+#endif
+ assert(tls_index != UINT32_MAX);
+ tls_set(0xabcdef01);
+ ready = semaphore(); gate = semaphore(); done = semaphore();
+ assert(ready && gate && done);
+ suspended_thread_returns_and_remains_signaled();
+ concurrent_threads_keep_private_state();
+ closing_a_running_thread_does_not_terminate_it();
+#ifndef _WIN32
+ /* The closed thread signals done before its detach callback completes. */
+ for (unsigned i = 0; atomic_load(&detached) < 4 && i < 1000; ++i) {
+ uint32_t delay = 1;
+ call(linux_platform_lookup("kernel32.dll", "Sleep"), 1, &delay, 0);
+ }
+ assert(attached == 4 && detached == 4);
+ assert(!pthread_barrier_destroy(&cpu_barrier));
+ assert(call(linux_tls_lookup("TlsFree"), 1, &tls_index, 0));
+ call(linux_platform_lookup("kernel32.dll", "DeleteCriticalSection"), 1, §ion, 0);
+#else
+ assert(TlsFree(tls_index));
+ DeleteCriticalSection(&counter_lock);
+#endif
+ assert(close_handle(ready, 0) && close_handle(gate, 0) && close_handle(done, 0));
+ puts("Threads: concurrent execution, private TLS/errno, IDs, suspended start, waits, exit codes and handle lifetime passed");
+ return 0;
+}
diff --git a/decompiled/tests/tls.c b/decompiled/tests/tls.c
@@ -100,6 +100,9 @@ static DWORD WINAPI thread_values(void *argument)
static void *thread_values(void *argument)
#endif
{
+#ifndef _WIN32
+ g_fs_base = 0x50002000u;
+#endif
uint32_t index = (uintptr_t)argument;
assert(get(index) == 0);
assert(set(index, 0x87654321) && get(index) == 0x87654321);
@@ -111,7 +114,6 @@ 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);
diff --git a/tools/reconstruction/test_portable_threads.py b/tools/reconstruction/test_portable_threads.py
@@ -0,0 +1,21 @@
+"""Compare native Linux guest threads with the Windows MSVCRT thread lifecycle."""
+import pathlib
+import subprocess
+
+
+root = pathlib.Path(__file__).resolve().parents[2]
+decompiled = root / "decompiled"
+work = root / "tools/reconstruction/work/portable-threads"
+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/threads.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:]
+wsl = ["wsl", "-d", "Ubuntu-26.04", "--cd", linux_path, "--exec"]
+subprocess.run(wsl + ["make", "-s", "-f", "Makefile.linux", "build/linux/threads"], check=True)
+actual = subprocess.check_output(wsl + ["./build/linux/threads"], text=True, timeout=30)
+assert actual == expected, (expected, actual)
+print("Windows == Linux: " + actual.strip())
diff --git a/tools/reconstruction/test_resource_atomics.py b/tools/reconstruction/test_resource_atomics.py
@@ -0,0 +1,21 @@
+"""Compare AO's compiled atomic helpers with equivalent native x86 instructions."""
+import pathlib
+import subprocess
+
+
+root = pathlib.Path(__file__).resolve().parents[2]
+decompiled = root / "decompiled"
+work = root / "tools/reconstruction/work/resource-atomics"
+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/resource_atomics.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:]
+wsl = ["wsl", "-d", "Ubuntu-26.04", "--cd", linux_path, "--exec"]
+subprocess.run(wsl + ["make", "-s", "-f", "Makefile.linux", "build/linux/resource-atomics"], check=True)
+actual = subprocess.check_output(wsl + ["./build/linux/resource-atomics"], text=True, timeout=30)
+assert actual == expected, (expected, actual)
+print("Native x86 == generated Linux C: " + actual.strip())