aorecomp

Anarchy Online classic in the browser

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


commit 3f497fbecfb94d7773d7370840eac3b4703dc90d
parent c20a9b68fa244d7a6bb82cfa7ab1e8e7c705cec3
Author: anon <anon@example.com>
Date:   Thu, 15 Oct 2026 09:39:40 +0000

Implement Linux message loop and worker synchronization

Diffstat:
Mdecompiled/Makefile.linux | 12++++++++++++
Mdecompiled/runtime/guest_crt.c | 13+++++++++++++
Mdecompiled/runtime/linux_sync.c | 188++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mdecompiled/runtime/linux_window.c | 326++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mdecompiled/tests/dynamic_imports.c | 40++++++++++++++++------------------------
Mdecompiled/tests/event.c | 60+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Adecompiled/tests/mutex.c | 329+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adecompiled/tests/strncmp.c | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdecompiled/tests/window.c | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/reconstruction/test_portable_mutex.py | 21+++++++++++++++++++++
Atools/reconstruction/test_portable_strncmp.py | 21+++++++++++++++++++++
11 files changed, 1239 insertions(+), 38 deletions(-)

diff --git a/decompiled/Makefile.linux b/decompiled/Makefile.linux @@ -169,6 +169,7 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric ./build/linux/audio ./build/linux/guest-rand ./build/linux/semaphore + ./build/linux/mutex ./build/linux/guest-scanf ./build/linux/network-startup ./build/linux/files @@ -195,6 +196,7 @@ test: build/linux/window build/linux/graphics build/linux/atoi build/linux/stric ./build/linux/guest-stat ./build/linux/stdio-input ./build/linux/stricmp + ./build/linux/strncmp ./build/linux/atoi ./build/linux/graphics ./build/linux/window @@ -273,3 +275,13 @@ build/linux/audio: tests/audio.c runtime/linux_audio.c runtime/guest_heap.c runt $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lSDL2 -o $@ test: build/linux/audio + +build/linux/strncmp: tests/strncmp.c runtime/guest_crt.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_crt.h runtime/guest_heap.h runtime/guest_memory.h + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -lm -o $@ + +test: build/linux/strncmp + +build/linux/mutex: tests/mutex.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 + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -o $@ + +test: build/linux/mutex diff --git a/decompiled/runtime/guest_crt.c b/decompiled/runtime/guest_crt.c @@ -562,6 +562,18 @@ static void crt_strcmp(void) g_esp += 4; } +static void crt_strncmp(void) +{ + uint32_t left = MEM32(g_esp + 4), right = MEM32(g_esp + 8), count = MEM32(g_esp + 12); + g_eax = 0; + for (uint32_t i = 0; i < count; ++i) { + unsigned a = MEM8(left + i), b = MEM8(right + i); + if (a != b) { g_eax = a - b; break; } + if (!a) break; + } + g_esp += 4; +} + static void crt_memcmp(void) { g_eax = (uint32_t)memcmp((const void *)ADDR(MEM32(g_esp + 4)), @@ -773,6 +785,7 @@ recomp_func_t guest_crt_lookup(const char *name) {"floor", crt_floor}, {"_EH_prolog", crt_eh_prolog}, {"strlen", crt_strlen}, {"strcmp", crt_strcmp}, + {"strncmp", crt_strncmp}, {"_stricmp", crt_stricmp}, {"_strnicmp", crt_strnicmp}, {"tolower", crt_tolower}, diff --git a/decompiled/runtime/linux_sync.c b/decompiled/runtime/linux_sync.c @@ -3,6 +3,7 @@ #include <errno.h> #include <fcntl.h> #include <linux/futex.h> +#include <limits.h> #include <stdatomic.h> #include <pthread.h> #include <sys/file.h> @@ -24,13 +25,16 @@ _Static_assert(sizeof(_Atomic uint32_t) == 4 && ATOMIC_INT_LOCK_FREE == 2, struct semaphore_handle { uint32_t id, access; - int fd, event; + int fd, kind; /* 0: semaphore, 1: auto-reset event, 2: mutex, 3: manual-reset event */ + pthread_mutex_t ownership; + int abandoned; unsigned references; struct semaphore_state *state; struct semaphore_handle *next; }; static struct semaphore_handle *handles; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t changed = PTHREAD_COND_INITIALIZER; static uint32_t next_handle = 0x100; static void system_failure(const char *operation) @@ -130,7 +134,8 @@ static uint32_t open_semaphore_locked(const char *name, int create, int32_t init next_handle += 4; handle->access = access; handle->fd = fd; - handle->event = 0; + handle->kind = 0; + handle->abandoned = 0; handle->references = 1; handle->state = state; handle->next = handles; @@ -167,13 +172,12 @@ static void open_named_semaphore_locked(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"); + if (MEM32(g_esp + 4) || MEM32(g_esp + 16)) { + fprintf(stderr, "Event security attributes and names are not implemented\n"); abort(); } g_eax = open_semaphore_locked(NULL, 1, MEM32(g_esp + 12) != 0, 1, 0x1f0003); - handles->event = 1; + handles->kind = MEM32(g_esp + 8) ? 3 : 1; g_esp += 20; } @@ -181,11 +185,13 @@ static void change_event_locked(int signaled) { struct semaphore_handle *handle = find_handle_locked(MEM32(g_esp + 4)); g_eax = 0; - if (handle && !handle->event) MEM32(g_fs_base + 0x34) = 6; + if (handle && handle->kind != 1 && handle->kind != 3) MEM32(g_fs_base + 0x34) = 6; else if (handle) { - /* Repeated SetEvent calls retain one signal; waits consume it once. */ + /* Auto-reset wakes one waiter; manual-reset stays signaled for all waiters. */ atomic_store(&handle->state->count, signaled); - if (signaled && syscall(SYS_futex, &handle->state->count, FUTEX_WAKE, 1, NULL, NULL, 0) < 0) + if (signaled && pthread_cond_broadcast(&changed)) abort(); + if (signaled && syscall(SYS_futex, &handle->state->count, FUTEX_WAKE, + handle->kind == 3 ? INT_MAX : 1, NULL, NULL, 0) < 0) system_failure("event wake"); g_eax = 1; } @@ -195,9 +201,48 @@ static void change_event_locked(int signaled) static void set_event_locked(void) { change_event_locked(1); } static void reset_event_locked(void) { change_event_locked(0); } +static void create_mutex_locked(void) +{ + if (MEM32(g_esp + 4) || MEM32(g_esp + 12)) { + fprintf(stderr, "Mutex security attributes and names are not implemented\n"); + abort(); + } + g_eax = open_semaphore_locked(NULL, 1, 0, 1, 0x1f0001); + handles->kind = 2; + pthread_mutexattr_t attributes; + if (pthread_mutexattr_init(&attributes) || + pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE) || + pthread_mutexattr_setrobust(&attributes, PTHREAD_MUTEX_ROBUST) || + pthread_mutex_init(&handles->ownership, &attributes) || + pthread_mutexattr_destroy(&attributes)) abort(); + if (MEM32(g_esp + 8) && pthread_mutex_lock(&handles->ownership)) abort(); + g_esp += 16; +} + +static void release_mutex_locked(void) +{ + struct semaphore_handle *handle = find_handle_locked(MEM32(g_esp + 4)); + g_eax = 0; + if (handle && handle->kind != 2) MEM32(g_fs_base + 0x34) = 6; + else if (handle) { + int error = pthread_mutex_unlock(&handle->ownership); + if (error == EPERM) MEM32(g_fs_base + 0x34) = 288; /* ERROR_NOT_OWNER */ + else if (error) abort(); + else { + g_eax = 1; + if (pthread_cond_broadcast(&changed)) abort(); + } + } + g_esp += 8; +} + static void release_handle_locked(struct semaphore_handle *handle) { if (--handle->references) return; + if (handle->kind == 2 && pthread_mutex_destroy(&handle->ownership)) { + fprintf(stderr, "Closing an owned mutex is not implemented\n"); + abort(); + } 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); @@ -222,7 +267,7 @@ static void release_semaphore_locked(void) 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; + if (handle && handle->kind != 0) 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) { @@ -235,6 +280,7 @@ static void release_semaphore_locked(void) if (atomic_compare_exchange_weak(&handle->state->count, &count, count + increment)) { uint32_t previous = MEM32(g_esp + 12); if (previous) MEM32(previous) = count; + if (pthread_cond_broadcast(&changed)) abort(); if (syscall(SYS_futex, &handle->state->count, FUTEX_WAKE, increment, NULL, NULL, 0) < 0) system_failure("semaphore wake"); g_eax = 1; @@ -260,10 +306,25 @@ static void wait_for_single_object_locked(void) deadline.tv_nsec += (milliseconds % 1000) * 1000000; if (deadline.tv_nsec >= 1000000000) { ++deadline.tv_sec; deadline.tv_nsec -= 1000000000; } } - for (;;) { + if (handle->kind == 2) { + /* Native robust mutexes preserve recursion and report owner death. */ + if (pthread_mutex_unlock(&mutex)) abort(); + int error = !milliseconds ? pthread_mutex_trylock(&handle->ownership) : + milliseconds == UINT32_MAX ? pthread_mutex_lock(&handle->ownership) : + pthread_mutex_clocklock(&handle->ownership, CLOCK_MONOTONIC, &deadline); + if (error == EOWNERDEAD && pthread_mutex_consistent(&handle->ownership)) abort(); + if (pthread_mutex_lock(&mutex)) abort(); + if (!error || error == EOWNERDEAD) { + g_eax = error == EOWNERDEAD || handle->abandoned ? 128 : 0; + handle->abandoned = 0; + } + else if (error == ETIMEDOUT || error == EBUSY) g_eax = 258; + else abort(); + } else for (;;) { uint32_t count = atomic_load(&handle->state->count); if (count) { - if (atomic_compare_exchange_weak(&handle->state->count, &count, count - 1)) { + if (handle->kind == 3 || + atomic_compare_exchange_weak(&handle->state->count, &count, count - 1)) { g_eax = 0; /* WAIT_OBJECT_0 */ break; } @@ -285,6 +346,104 @@ static void wait_for_single_object_locked(void) g_esp += 12; } +static uint32_t try_multiple_locked(struct semaphore_handle **objects, unsigned count, int all) +{ + unsigned acquired = 0; + for (; acquired < count; ++acquired) { + struct semaphore_handle *object = objects[acquired]; + int ready; + if (object->kind == 2) { + int error = pthread_mutex_trylock(&object->ownership); + if (error == EOWNERDEAD) { + if (pthread_mutex_consistent(&object->ownership)) abort(); + object->abandoned = 1; + } else if (error && error != EBUSY) abort(); + ready = error != EBUSY; + } else ready = atomic_load(&object->state->count) != 0; + if (!ready) { + if (all) break; + continue; + } + if (!all) { + uint32_t result = acquired + (object->abandoned ? 128 : 0); + object->abandoned = 0; + if (object->kind == 0 || object->kind == 1) atomic_fetch_sub(&object->state->count, 1); + return result; + } + } + + /* Commit all signal consumption together, or undo only tentative mutex locks. */ + if (all && acquired == count) { + uint32_t result = 0; + for (unsigned i = 0; i < count; ++i) { + if (objects[i]->abandoned) result = 128; + objects[i]->abandoned = 0; + if (objects[i]->kind == 0 || objects[i]->kind == 1) + atomic_fetch_sub(&objects[i]->state->count, 1); + } + return result; + } + if (all) for (unsigned i = 0; i < acquired; ++i) + if (objects[i]->kind == 2 && pthread_mutex_unlock(&objects[i]->ownership)) abort(); + return 258; +} + +static void wait_for_multiple_objects_locked(void) +{ + uint32_t count = MEM32(g_esp + 4), array = MEM32(g_esp + 8); + uint32_t all = MEM32(g_esp + 12), milliseconds = MEM32(g_esp + 16); + if (MEM32(g_esp + 20)) { + fprintf(stderr, "Alertable multiple-object waits are not implemented\n"); + abort(); + } + g_esp += 24; + g_eax = UINT32_MAX; + if (!count || count > 64) { MEM32(g_fs_base + 0x34) = 87; return; } + struct semaphore_handle *objects[64]; + for (unsigned i = 0; i < count; ++i) { + objects[i] = find_handle_locked(MEM32(array + 4*i)); + if (!objects[i]) return; + if (!(objects[i]->access & 0x100000)) { MEM32(g_fs_base + 0x34) = 5; return; } + if (objects[i]->fd >= 0) { + fprintf(stderr, "Cross-process multiple-object waits are not implemented\n"); + abort(); + } + if (all) for (unsigned j = 0; j < i; ++j) + if (objects[i] == objects[j]) { MEM32(g_fs_base + 0x34) = 87; return; } + } + + /* Retain handles while sleeping; the registry lock makes local waits atomic. */ + int has_mutex = 0; + for (unsigned i = 0; i < count; ++i) { + ++objects[i]->references; + has_mutex |= objects[i]->kind == 2; + } + struct timespec now, deadline; + if (clock_gettime(CLOCK_MONOTONIC, &now)) abort(); + deadline.tv_sec = now.tv_sec + milliseconds / 1000; + deadline.tv_nsec = now.tv_nsec + (milliseconds % 1000) * 1000000; + if (deadline.tv_nsec >= 1000000000) { ++deadline.tv_sec; deadline.tv_nsec -= 1000000000; } + for (;;) { + g_eax = try_multiple_locked(objects, count, all); + if (g_eax != 258 || !milliseconds) break; + if (clock_gettime(CLOCK_MONOTONIC, &now)) abort(); + if (milliseconds != UINT32_MAX && (now.tv_sec > deadline.tv_sec || + (now.tv_sec == deadline.tv_sec && now.tv_nsec >= deadline.tv_nsec))) break; + struct timespec wake = deadline; + if (has_mutex) { + /* Owner death has no condition notification; recheck robust mutexes. */ + now.tv_nsec += 10000000; + if (now.tv_nsec >= 1000000000) { ++now.tv_sec; now.tv_nsec -= 1000000000; } + if (milliseconds == UINT32_MAX || now.tv_sec < wake.tv_sec || + (now.tv_sec == wake.tv_sec && now.tv_nsec < wake.tv_nsec)) wake = now; + } + int error = !has_mutex && milliseconds == UINT32_MAX ? pthread_cond_wait(&changed, &mutex) : + pthread_cond_clockwait(&changed, &mutex, CLOCK_MONOTONIC, &wake); + if (error && error != ETIMEDOUT) abort(); + } + for (unsigned i = 0; i < count; ++i) release_handle_locked(objects[i]); +} + static void call_serialized(recomp_func_t function) { if (pthread_mutex_lock(&mutex)) abort(); @@ -300,6 +459,9 @@ static void wait_for_single_object(void) { call_serialized(wait_for_single_objec 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); } +static void create_mutex(void) { call_serialized(create_mutex_locked); } +static void release_mutex(void) { call_serialized(release_mutex_locked); } +static void wait_for_multiple_objects(void) { call_serialized(wait_for_multiple_objects_locked); } recomp_func_t linux_sync_lookup(const char *name) { @@ -308,6 +470,8 @@ recomp_func_t linux_sync_lookup(const char *name) {"CloseHandle", close_handle}, {"ReleaseSemaphore", release_semaphore}, {"WaitForSingleObject", wait_for_single_object}, {"CreateEventA", create_event}, {"SetEvent", set_event}, {"ResetEvent", reset_event}, + {"CreateMutexA", create_mutex}, {"ReleaseMutex", release_mutex}, + {"WaitForMultipleObjectsEx", wait_for_multiple_objects}, }; 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_window.c b/decompiled/runtime/linux_window.c @@ -3,6 +3,7 @@ #include "guest_heap.h" #include <SDL2/SDL.h> #include <strings.h> +#include <pthread.h> /* Guest classes and handles contain no native pointers. SDL owns decoration. */ static struct window_class { @@ -26,6 +27,18 @@ static struct window_icon { SDL_Surface *pixels; struct window_icon *next; } *icons; +static struct queued_message { + struct queued_message *next; + uint32_t words[7]; + int keyboard; + SDL_Keymod modifiers; +} *message_head, *message_tail; +static pthread_mutex_t message_mutex = PTHREAD_MUTEX_INITIALIZER; +static int quit_pending; +static uint32_t quit_code; +static uint8_t keyboard_state[256]; +static uint32_t queued_mouse_buttons; +static void destroy_window(void); struct SDL_Window *linux_window_native(uint32_t handle) { @@ -294,14 +307,39 @@ static void default_procedure(void) case 0x01: /* WM_CREATE */ case 0x02: /* WM_DESTROY */ case 0x82: /* WM_NCDESTROY */ + case 0x0f: /* WM_PAINT: the game presents its own rendered surface. */ + case 0x100: case 0x101: case 0x102: /* Unhandled keyboard input. */ + case 0x104: case 0x105: case 0x106: + case 0x200: case 0x201: case 0x202: case 0x203: + case 0x204: case 0x205: case 0x206: case 0x207: case 0x208: case 0x209: case 0x20a: break; - default: unsupported("default message", message); + case 0x10: /* WM_CLOSE */ + PUSH32(g_esp, handle); + PUSH32(g_esp, RECOMP_RETADDR); + destroy_window(); + g_eax = 0; + break; + default: if (message < 0x400) unsupported("default message", message); } g_esp += 20; } static void release_window(void) { + if (pthread_mutex_lock(&message_mutex)) abort(); + struct queued_message **link = &message_head; + message_tail = NULL; + while (*link) { + if ((*link)->words[0] == client.handle) { + struct queued_message *removed = *link; + *link = removed->next; + free(removed); + } else { + message_tail = *link; + link = &(*link)->next; + } + } + if (pthread_mutex_unlock(&message_mutex)) abort(); SDL_HideWindow(linux_graphics_window()); client.handle = 0; client.focus = 0; @@ -728,6 +766,285 @@ static void device_caps(void) g_esp += 12; } +/* Posted messages retain their payload until the owning message loop removes them. */ +static void queue_message(uint32_t handle, uint32_t message, uint32_t wparam, + uint32_t lparam, int keyboard, SDL_Keymod modifiers) +{ + struct queued_message *entry = calloc(1, sizeof(*entry)); + if (!entry) abort(); + entry->words[0] = handle; + entry->words[1] = message; + entry->words[2] = wparam; + entry->words[3] = lparam; + entry->words[4] = SDL_GetTicks(); + int x, y; + SDL_GetGlobalMouseState(&x, &y); + entry->words[5] = x; entry->words[6] = y; + entry->keyboard = keyboard; + entry->modifiers = modifiers; + if (pthread_mutex_lock(&message_mutex)) abort(); + if (message_tail) message_tail->next = entry; + else message_head = entry; + message_tail = entry; + if (pthread_mutex_unlock(&message_mutex)) abort(); +} + +static void wake_message_loop(void) +{ + if (!SDL_WasInit(SDL_INIT_EVENTS)) return; + SDL_Event wake = {.type = SDL_USEREVENT}; + if (SDL_PushEvent(&wake) < 0) abort(); +} + +static void post_message(void) +{ + uint32_t handle = MEM32(g_esp + 4); + g_eax = !handle || handle == client.handle; + if (!g_eax) MEM32(g_fs_base + 0x34) = 1400; + else { + queue_message(handle, MEM32(g_esp + 8), MEM32(g_esp + 12), MEM32(g_esp + 16), 0, 0); + wake_message_loop(); + } + g_esp += 20; +} + +static void post_quit_message(void) +{ + if (pthread_mutex_lock(&message_mutex)) abort(); + quit_pending = 1; + quit_code = MEM32(g_esp + 4); + if (pthread_mutex_unlock(&message_mutex)) abort(); + wake_message_loop(); + g_esp += 8; +} + +/* US virtual keys and x86 Set-1 scan codes used by the game's input handler. */ +static uint32_t virtual_key(SDL_Keycode key, unsigned *scan) +{ + if (key >= SDLK_a && key <= SDLK_z) { + static const uint8_t scans[] = {30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,19,31,20,22,47,17,45,21,44}; + *scan = scans[key - SDLK_a]; + return 'A' + key - SDLK_a; + } + if (key >= SDLK_0 && key <= SDLK_9) { + *scan = key == SDLK_0 ? 11 : key - SDLK_1 + 2; + return key; + } + if (key >= SDLK_F1 && key <= SDLK_F12) { + *scan = key <= SDLK_F10 ? 59 + key - SDLK_F1 : 87 + key - SDLK_F11; + return 0x70 + key - SDLK_F1; + } + static const struct { SDL_Keycode key; uint16_t code, scan; } keys[] = { + {SDLK_ESCAPE,0x1b,1}, {SDLK_BACKSPACE,8,14}, {SDLK_TAB,9,15}, + {SDLK_RETURN,13,28}, {SDLK_SPACE,32,57}, {SDLK_CAPSLOCK,20,58}, + {SDLK_LSHIFT,16,42}, {SDLK_RSHIFT,16,54}, {SDLK_LCTRL,17,29}, + {SDLK_RCTRL,17,0x11d}, {SDLK_LALT,18,56}, {SDLK_RALT,18,0x138}, + {SDLK_HOME,0x24,0x147}, {SDLK_END,0x23,0x14f}, + {SDLK_PAGEUP,0x21,0x149}, {SDLK_PAGEDOWN,0x22,0x151}, + {SDLK_LEFT,0x25,0x14b}, {SDLK_UP,0x26,0x148}, + {SDLK_RIGHT,0x27,0x14d}, {SDLK_DOWN,0x28,0x150}, + {SDLK_INSERT,0x2d,0x152}, {SDLK_DELETE,0x2e,0x153}, + {SDLK_SEMICOLON,0xba,39}, {SDLK_EQUALS,0xbb,13}, {SDLK_COMMA,0xbc,51}, + {SDLK_MINUS,0xbd,12}, {SDLK_PERIOD,0xbe,52}, {SDLK_SLASH,0xbf,53}, + {SDLK_BACKQUOTE,0xc0,41}, {SDLK_LEFTBRACKET,0xdb,26}, + {SDLK_BACKSLASH,0xdc,43}, {SDLK_RIGHTBRACKET,0xdd,27}, {SDLK_QUOTE,0xde,40}, + }; + for (unsigned i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i) + if (keys[i].key == key) { *scan = keys[i].scan; return keys[i].code; } + return 0; +} + +static void process_event(const SDL_Event *event) +{ + if (!client.handle) return; + if (event->type == SDL_QUIT) queue_message(client.handle, 0x10, 0, 0, 0, 0); + else if (event->type == SDL_WINDOWEVENT && + event->window.windowID == SDL_GetWindowID(linux_graphics_window())) { + switch (event->window.event) { + case SDL_WINDOWEVENT_CLOSE: queue_message(client.handle, 0x10, 0, 0, 0, 0); break; + case SDL_WINDOWEVENT_FOCUS_GAINED: + if (!client.active) { + client.active = 1; + send_message(0x1c, 1, 0); + send_message(0x86, 1, 0); + send_message(6, 1, 0); + change_focus(client.handle); + } + break; + case SDL_WINDOWEVENT_FOCUS_LOST: + if (client.active) { + client.active = 0; + change_focus(0); + send_message(0x86, 0, 0); + send_message(6, 0, 0); + send_message(0x1c, 0, 0); + } + break; + case SDL_WINDOWEVENT_SIZE_CHANGED: + send_message(5, 0, (event->window.data1 & 0xffffu) | ((uint32_t)event->window.data2 << 16)); + break; + case SDL_WINDOWEVENT_MOVED: + send_message(3, 0, (event->window.data1 & 0xffffu) | ((uint32_t)event->window.data2 << 16)); + break; + } + } else if (event->type == SDL_KEYDOWN || event->type == SDL_KEYUP) { + unsigned scan = 0; + uint32_t key = virtual_key(event->key.keysym.sym, &scan); + if (!key) return; + int up = event->type == SDL_KEYUP, alt = !!(event->key.keysym.mod & KMOD_ALT) || key == 18; + uint32_t flags = 1 | (scan << 16) | (alt ? 0x20000000u : 0) | + (up || event->key.repeat ? 0x40000000u : 0) | (up ? 0x80000000u : 0); + queue_message(client.handle, (alt ? 0x104 : 0x100) + up, key, flags, 1, event->key.keysym.mod); + } else if (event->type == SDL_MOUSEMOTION) { + uint32_t state = (event->motion.state & SDL_BUTTON_LMASK ? 1 : 0) | + (event->motion.state & SDL_BUTTON_RMASK ? 2 : 0) | + (event->motion.state & SDL_BUTTON_MMASK ? 16 : 0); + queued_mouse_buttons = state; + SDL_Keymod modifiers = SDL_GetModState(); + state |= modifiers & KMOD_SHIFT ? 4 : 0; + state |= modifiers & KMOD_CTRL ? 8 : 0; + queue_message(client.handle, 0x200, state, + (event->motion.x & 0xffffu) | ((uint32_t)event->motion.y << 16), 2, 0); + } else if (event->type == SDL_MOUSEBUTTONDOWN || event->type == SDL_MOUSEBUTTONUP) { + uint32_t button = event->button.button, message, mask; + if (button == SDL_BUTTON_LEFT) { message = 0x201; mask = 1; } + else if (button == SDL_BUTTON_RIGHT) { message = 0x204; mask = 2; } + else if (button == SDL_BUTTON_MIDDLE) { message = 0x207; mask = 16; } + else return; + int up = event->type == SDL_MOUSEBUTTONUP; + queued_mouse_buttons = up ? queued_mouse_buttons & ~mask : queued_mouse_buttons | mask; + uint32_t state = queued_mouse_buttons; + SDL_Keymod modifiers = SDL_GetModState(); + state |= modifiers & KMOD_SHIFT ? 4 : 0; + state |= modifiers & KMOD_CTRL ? 8 : 0; + queue_message(client.handle, message + up, state, + (event->button.x & 0xffffu) | ((uint32_t)event->button.y << 16), 2, 0); + } else if (event->type == SDL_MOUSEWHEEL) { + int x, y; + SDL_GetGlobalMouseState(&x, &y); + int delta = event->wheel.y * 120; + if (event->wheel.direction == SDL_MOUSEWHEEL_FLIPPED) delta = -delta; + uint32_t state = queued_mouse_buttons | (SDL_GetModState() & KMOD_SHIFT ? 4 : 0) | + (SDL_GetModState() & KMOD_CTRL ? 8 : 0); + queue_message(client.handle, 0x20a, ((uint32_t)delta << 16) | state, + (x & 0xffffu) | ((uint32_t)y << 16), 2, 0); + } +} + +static int read_message(uint32_t output, uint32_t window, uint32_t first, uint32_t last, int remove) +{ + if (pthread_mutex_lock(&message_mutex)) abort(); + struct queued_message **link = &message_head, *previous = NULL; + while (*link) { + struct queued_message *entry = *link; + uint32_t handle = entry->words[0], message = entry->words[1]; + if ((!window || (window == UINT32_MAX ? !handle : handle == window)) && + ((!first && !last) || (message >= first && message <= last))) { + memcpy((void *)ADDR(output), entry->words, sizeof(entry->words)); + if (remove) { + if (entry->keyboard == 1) { + keyboard_state[entry->words[2]] = message & 1 ? 0 : 0x80; + SDL_SetModState(entry->modifiers); + } else if (entry->keyboard == 2) { + keyboard_state[1] = entry->words[2] & 1 ? 0x80 : 0; + keyboard_state[2] = entry->words[2] & 2 ? 0x80 : 0; + keyboard_state[4] = entry->words[2] & 16 ? 0x80 : 0; + } + *link = entry->next; + if (message_tail == entry) message_tail = previous; + free(entry); + } + if (pthread_mutex_unlock(&message_mutex)) abort(); + return 1; + } + previous = entry; + link = &entry->next; + } + int found = quit_pending; + if (found) { + uint32_t words[] = {0, 0x12, quit_code, 0, SDL_GetTicks(), 0, 0}; + memcpy((void *)ADDR(output), words, sizeof(words)); + if (remove) quit_pending = 0; + } + if (pthread_mutex_unlock(&message_mutex)) abort(); + return found; +} + +static void retrieve_message(int wait) +{ + uint32_t output = MEM32(g_esp + 4), window = MEM32(g_esp + 8); + uint32_t first = MEM32(g_esp + 12), last = MEM32(g_esp + 16); + uint32_t flags = wait ? 1 : MEM32(g_esp + 20); + g_esp += wait ? 20 : 24; + if (flags & ~3u) unsupported("PeekMessage flags", flags); + if (window && window != UINT32_MAX && window != client.handle) { + MEM32(g_fs_base + 0x34) = 1400; + g_eax = wait ? UINT32_MAX : 0; + return; + } + for (;;) { + SDL_Event event; + while (SDL_PollEvent(&event)) process_event(&event); + if (read_message(output, window, first, last, flags & 1)) { + g_eax = !wait || MEM32(output + 4) != 0x12; + return; + } + if (!wait) { g_eax = 0; return; } + if (!SDL_WaitEvent(&event)) { fprintf(stderr, "%s\n", SDL_GetError()); abort(); } + process_event(&event); + } +} + +static void peek_message(void) { retrieve_message(0); } +static void get_message(void) { retrieve_message(1); } + +static void dispatch_message(void) +{ + uint32_t record = MEM32(g_esp + 4), handle = MEM32(record); + g_esp += 8; + g_eax = 0; + if (handle && handle == client.handle) + g_eax = send_message(MEM32(record + 4), MEM32(record + 8), MEM32(record + 12)); + else if (handle) MEM32(g_fs_base + 0x34) = 1400; +} + +static void translate_message(void) +{ + uint32_t record = MEM32(g_esp + 4), message = MEM32(record + 4), key = MEM32(record + 8); + g_esp += 8; + g_eax = message == 0x100 || message == 0x101 || message == 0x104 || message == 0x105; + if (message != 0x100 && message != 0x104) return; + SDL_Keymod modifiers = SDL_GetModState(); + uint32_t character = 0; + if (key >= 'A' && key <= 'Z') { + character = modifiers & KMOD_CTRL ? key - 'A' + 1 : + key + (!!(modifiers & KMOD_SHIFT) != !!(modifiers & KMOD_CAPS) ? 0 : 32); + } else if (key >= '0' && key <= '9') { + character = modifiers & KMOD_SHIFT ? ")!@#$%^&*("[key - '0'] : key; + } else if (key == 8 || key == 9 || key == 13 || key == 32) character = key; + else { + const char *plain = ";=,-./`[\\]'", *shifted = ":+<_>?~{|}\""; + static const uint8_t codes[] = {0xba,0xbb,0xbc,0xbd,0xbe,0xbf,0xc0,0xdb,0xdc,0xdd,0xde}; + for (unsigned i = 0; i < sizeof(codes); ++i) + if (key == codes[i]) character = (modifiers & KMOD_SHIFT ? shifted : plain)[i]; + } + if (character) queue_message(MEM32(record), message == 0x104 ? 0x106 : 0x102, + character, MEM32(record + 12), 0, 0); +} + +static void get_keyboard_state(void) +{ + uint32_t output = MEM32(g_esp + 4); + SDL_Keymod modifiers = SDL_GetModState(); + keyboard_state[16] = modifiers & KMOD_SHIFT ? 0x80 : 0; + keyboard_state[17] = modifiers & KMOD_CTRL ? 0x80 : 0; + keyboard_state[18] = modifiers & KMOD_ALT ? 0x80 : 0; + keyboard_state[20] = modifiers & KMOD_CAPS ? 1 : 0; + memcpy((void *)ADDR(output), keyboard_state, sizeof(keyboard_state)); + g_eax = 1; + g_esp += 8; +} + static void register_class_a(void) { register_class(0); } static void register_class_w(void) { register_class(1); } static void unregister_class_a(void) { unregister_class(0); } @@ -743,6 +1060,13 @@ recomp_func_t linux_window_lookup(const char *dll, const char *name) return NULL; } if (strcasecmp(dll, "user32.dll")) return NULL; + if (!strcmp(name, "PeekMessageA") || !strcmp(name, "PeekMessageW")) return peek_message; + if (!strcmp(name, "GetMessageA") || !strcmp(name, "GetMessageW")) return get_message; + if (!strcmp(name, "DispatchMessageA") || !strcmp(name, "DispatchMessageW")) return dispatch_message; + if (!strcmp(name, "PostMessageA") || !strcmp(name, "PostMessageW")) return post_message; + if (!strcmp(name, "PostQuitMessage")) return post_quit_message; + if (!strcmp(name, "TranslateMessage")) return translate_message; + if (!strcmp(name, "GetKeyboardState")) return get_keyboard_state; if (!strcmp(name, "LoadIconA")) return load_icon; if (!strcmp(name, "RegisterClassA")) return register_class_a; if (!strcmp(name, "RegisterClassW")) return register_class_w; diff --git a/decompiled/tests/dynamic_imports.c b/decompiled/tests/dynamic_imports.c @@ -1,7 +1,6 @@ #include "linux_imports.h" #include "guest_memory.h" #include <assert.h> -#include <sys/wait.h> #include <unistd.h> static void thread_entry(void) @@ -109,31 +108,24 @@ static void import_names_are_owned_and_calls_are_dispatched(void) assert(linux_import_count() == count); } -static void unresolved_window_call_fails_explicitly(void) +static void resolved_message_loop_consumes_quit(void) { strcpy((char *)ADDR(0x50000100u), "GetMessageW"); uint32_t symbol = call("GetProcAddress", 0xf2000000u, 0x50000100u); - int output[2]; - assert(!pipe(output)); - pid_t child = fork(); - assert(child >= 0); - - if (!child) { - close(output[0]); - assert(dup2(output[1], STDERR_FILENO) == STDERR_FILENO); - close(output[1]); - recomp_lookup_import(symbol)(); - _exit(99); - } - close(output[1]); - char message[256] = {0}; - assert(read(output[0], message, sizeof(message) - 1) > 0); - close(output[0]); - int status; - assert(waitpid(child, &status, 0) == child); - - assert(WIFEXITED(status) && WEXITSTATUS(status) == 3); - assert(strstr(message, "user32.dll!GetMessageW ordinal=0 caller=280028f0")); + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = 73; + recomp_lookup_import(linux_import_bind("user32.dll", "PostQuitMessage", 0))(); + memset((void *)ADDR(0x500001fc), 0xa5, 36); + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = 0x50000200; + MEM32(g_esp + 8) = MEM32(g_esp + 12) = MEM32(g_esp + 16) = 0; + + recomp_lookup_import(symbol)(); + + assert(g_eax == 0 && g_esp == 0x5000ff14); + assert(MEM32(0x50000200) == 0 && MEM32(0x50000204) == 0x12); + assert(MEM32(0x50000208) == 73); + assert(MEM32(0x500001fc) == 0xa5a5a5a5 && MEM32(0x5000021c) == 0xa5a5a5a5); } static void file_and_event_handles_close_through_imports(void) @@ -209,7 +201,7 @@ int main(void) window_symbols_survive_library_release(); failed_lookups_report_errors(); import_names_are_owned_and_calls_are_dispatched(); - unresolved_window_call_fails_explicitly(); + resolved_message_loop_consumes_quit(); file_and_event_handles_close_through_imports(); thread_handles_dispatch_through_imports(); game_exports_return_callable_guest_addresses(); diff --git a/decompiled/tests/event.c b/decompiled/tests/event.c @@ -160,6 +160,63 @@ static void event_and_semaphore_handles_are_distinct(void) assert(close_object(event) && close_object(semaphore)); } +#ifdef _WIN32 +static DWORD WINAPI manual_wait(void *argument) +{ + assert(WaitForSingleObject(argument, 1000) == 0); + return 0; +} +#endif + +static void manual_signal_releases_all_waiters(void) +{ +#ifdef _WIN32 + uint32_t event = (uintptr_t)CreateEventA(NULL, TRUE, TRUE, NULL); + HANDLE workers[4]; +#else + uint32_t args[] = {0, 1, 1, 0}; + uint32_t event = call("CreateEventA", 4, args); + pid_t workers[4]; +#endif + assert(event && wait_object(event, 0) == 0 && wait_object(event, 0) == 0); + assert(change(event, 0) && wait_object(event, 0) == 258); + for (unsigned i = 0; i < 4; ++i) { +#ifdef _WIN32 + workers[i] = CreateThread(NULL, 0, manual_wait, (void *)(uintptr_t)event, 0, NULL); + assert(workers[i]); +#else + workers[i] = fork(); + assert(workers[i] >= 0); + if (!workers[i]) { + assert(wait_object(event, 1000) == 0); + _exit(0); + } +#endif + } + +#ifdef _WIN32 + Sleep(50); +#else + usleep(50000); +#endif + assert(change(event, 1)); + + for (unsigned i = 0; i < 4; ++i) { +#ifdef _WIN32 + assert(WaitForSingleObject(workers[i], 1000) == 0); + assert(CloseHandle(workers[i])); +#else + int status; + assert(waitpid(workers[i], &status, 0) == workers[i]); + assert(WIFEXITED(status) && WEXITSTATUS(status) == 0); +#endif + } + assert(wait_object(event, 0) == 0 && wait_object(event, 0) == 0); + assert(change(event, 0) && wait_object(event, 20) == 258); + assert(change(event, 1) && wait_object(event, 0) == 0); + assert(close_object(event)); +} + int main(void) { #ifndef _WIN32 @@ -172,6 +229,7 @@ int main(void) 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"); + manual_signal_releases_all_waiters(); + puts("events: auto/manual reset, four waiters, coalesced signals, finite/infinite waits and handle types passed"); return 0; } diff --git a/decompiled/tests/mutex.c b/decompiled/tests/mutex.c @@ -0,0 +1,329 @@ +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#ifdef _WIN32 +#include <windows.h> +#else +#include "linux_sync.h" +#include "guest_memory.h" +#include <pthread.h> +#include <unistd.h> +#endif + +static uint32_t call(const char *name, unsigned count, const uint32_t *args) +{ +#ifdef _WIN32 + FARPROC function = GetProcAddress(GetModuleHandleA("kernel32.dll"), name); + assert(function); + if (count == 1) return ((uint32_t (WINAPI *)(uint32_t))function)(args[0]); + if (count == 2) return ((uint32_t (WINAPI *)(uint32_t,uint32_t))function)(args[0], args[1]); + if (count == 3) return ((uint32_t (WINAPI *)(uint32_t,uint32_t,uint32_t))function)(args[0], args[1], args[2]); + if (count == 4) return ((uint32_t (WINAPI *)(uint32_t,uint32_t,uint32_t,uint32_t))function)(args[0], args[1], args[2], args[3]); + return ((uint32_t (WINAPI *)(uint32_t,uint32_t,uint32_t,uint32_t,uint32_t))function)(args[0], args[1], args[2], args[3], args[4]); +#else + g_esp = g_fs_base + 0xf000; + uint32_t stack = g_esp; + for (unsigned i = 0; i < count; ++i) MEM32(g_esp + 4 + 4*i) = args[i]; + g_ebx = 123; g_esi = 234; g_edi = 345; g_ebp = 456; + linux_sync_lookup(name)(); + assert(g_esp == stack + 4*(count + 1)); + assert(g_ebx == 123 && g_esi == 234 && g_edi == 345 && g_ebp == 456); + return g_eax; +#endif +} + +static uint32_t error(void) +{ +#ifdef _WIN32 + return GetLastError(); +#else + return MEM32(g_fs_base + 0x34); +#endif +} + +static uint32_t create(int owned) +{ + uint32_t args[] = {0, owned, 0}; + return call("CreateMutexA", 3, args); +} + +static uint32_t wait_object(uint32_t object, uint32_t timeout) +{ + uint32_t args[] = {object, timeout}; + return call("WaitForSingleObject", 2, args); +} + +static uint32_t release(uint32_t object) { return call("ReleaseMutex", 1, &object); } +static void close_object(uint32_t object) { assert(call("CloseHandle", 1, &object)); } + +static uint32_t wait_many(unsigned count, uint32_t *objects, int all, uint32_t timeout) +{ +#ifdef _WIN32 + uint32_t array = (uintptr_t)objects; +#else + uint32_t array = g_fs_base + 0x4000; + for (unsigned i = 0; i < count; ++i) MEM32(array + i*4) = objects[i]; +#endif + uint32_t args[] = {count, array, all, timeout, 0}; + return call("WaitForMultipleObjectsEx", 5, args); +} + +struct work { uint32_t mutex, ready, mode, index; }; +static unsigned counter; + +#ifdef _WIN32 +static DWORD WINAPI worker(void *argument) +#else +static void *worker(void *argument) +#endif +{ + struct work *work = argument; +#ifndef _WIN32 + g_fs_base = 0x50010000 + 0x10000 * work->index; +#endif + if (work->mode == 0) { + assert(!release(work->mutex) && error() == 288); + assert(wait_object(work->mutex, 0) == 258); + assert(wait_object(work->mutex, 25) == 258); + } else if (work->mode == 1 || work->mode == 2 || work->mode == 5) { + assert(wait_object(work->mutex, UINT32_MAX) == 0); + assert(call("SetEvent", 1, &work->ready)); + if (work->mode == 2 || work->mode == 5) { +#ifdef _WIN32 + Sleep(50); +#else + usleep(50000); +#endif + if (work->mode == 2) assert(release(work->mutex)); + } + } else if (work->mode == 3) { + for (unsigned i = 0; i < 1000; ++i) { + assert(wait_object(work->mutex, UINT32_MAX) == 0); + assert(wait_object(work->mutex, 0) == 0); + ++counter; + assert(release(work->mutex) && release(work->mutex)); + } + } else { + assert(wait_object(work->mutex, 0) == 0); + assert(release(work->mutex)); + } + return 0; +} + +#ifdef _WIN32 +typedef HANDLE worker_thread; +#else +typedef pthread_t worker_thread; +#endif + +static worker_thread start(struct work *work) +{ + worker_thread thread; +#ifdef _WIN32 + thread = CreateThread(NULL, 0, worker, work, 0, NULL); + assert(thread); +#else + assert(!pthread_create(&thread, NULL, worker, work)); +#endif + return thread; +} + +static void join(worker_thread thread) +{ +#ifdef _WIN32 + assert(WaitForSingleObject(thread, 5000) == 0); + assert(CloseHandle(thread)); +#else + assert(!pthread_join(thread, NULL)); +#endif +} + +static void recursive_ownership(void) +{ + struct work work = {.mutex = create(1)}; + assert(work.mutex && wait_object(work.mutex, 0) == 0); + + join(start(&work)); + assert(release(work.mutex)); + join(start(&work)); + assert(release(work.mutex)); + + assert(!release(work.mutex) && error() == 288); + assert(wait_object(work.mutex, 0) == 0 && release(work.mutex)); + close_object(work.mutex); + assert(!release(work.mutex) && error() == 6); +} + +static void waiting_and_abandonment(unsigned mode, uint32_t timeout) +{ + uint32_t event_args[] = {0, 0, 0, 0}; + struct work work = {.mutex = create(0), .ready = call("CreateEventA", 4, event_args), .mode = mode}; + assert(work.mutex && work.ready); + worker_thread thread = start(&work); + assert(wait_object(work.ready, 1000) == 0); + if (mode == 1) join(thread); + + uint32_t result = wait_object(work.mutex, timeout); + + assert(result == (mode == 1 ? 128 : 0)); + assert(wait_object(work.mutex, 0) == 0); + assert(release(work.mutex) && release(work.mutex)); + assert(wait_object(work.mutex, 0) == 0 && release(work.mutex)); + if (mode == 2) join(thread); + close_object(work.ready); + close_object(work.mutex); +} + +static void contended_mutual_exclusion(void) +{ + uint32_t mutex = create(0); + struct work work[4]; + worker_thread threads[4]; + assert(mutex); + + for (unsigned i = 0; i < 4; ++i) { + work[i] = (struct work){.mutex = mutex, .mode = 3, .index = i}; + threads[i] = start(&work[i]); + } + for (unsigned i = 0; i < 4; ++i) join(threads[i]); + + assert(counter == 4000); + assert(!release(mutex) && error() == 288); + assert(!call("SetEvent", 1, &mutex) && error() == 6); + uint32_t args[] = {mutex, 1, 0}; + assert(!call("ReleaseSemaphore", 3, args) && error() == 6); + close_object(mutex); +} + +static void multiple_event_signals(void) +{ + for (unsigned mask = 0; mask < 8; ++mask) { + uint32_t objects[3]; + for (unsigned i = 0; i < 3; ++i) { + uint32_t args[] = {0, i == 1, !!(mask & (1 << i)), 0}; + objects[i] = call("CreateEventA", 4, args); + assert(objects[i]); + } + + uint32_t result = wait_many(3, objects, 1, 0); + + assert(result == (mask == 7 ? 0 : 258)); + for (unsigned i = 0; i < 3; ++i) { + int signaled = (mask & (1 << i)) && (mask != 7 || i == 1); + assert(wait_object(objects[i], 0) == (signaled ? 0 : 258)); + if (signaled) assert(call("SetEvent", 1, &objects[i])); + } + for (unsigned i = 0; i < 3; ++i) { + int signaled = (mask & (1 << i)) && (mask != 7 || i == 1); + if (signaled) { + assert(wait_many(3, objects, 0, 0) == i); + assert(call("ResetEvent", 1, &objects[i])); + } + } + assert(wait_many(3, objects, 0, 0) == 258); + for (unsigned i = 0; i < 3; ++i) close_object(objects[i]); + } +} + +static void multiple_wait_preserves_ownership(void) +{ + struct work work = {.mutex = create(0), .mode = 4}; + uint32_t args[] = {0, 1, 0, 0}; + uint32_t objects[] = {work.mutex, call("CreateEventA", 4, args)}; + assert(objects[0] && objects[1]); + + assert(wait_many(2, objects, 1, 25) == 258); + join(start(&work)); + assert(call("SetEvent", 1, &objects[1])); + assert(wait_many(2, objects, 1, 0) == 0); + + work.mode = 0; + join(start(&work)); + assert(release(objects[0])); + assert(!release(objects[0]) && error() == 288); + uint32_t duplicate[] = {objects[1], objects[1]}; + assert(wait_many(2, duplicate, 1, 0) == UINT32_MAX && error() == 87); + assert(wait_many(2, duplicate, 0, 0) == 0); + assert(wait_many(0, objects, 0, 0) == UINT32_MAX && error() == 87); + close_object(objects[0]); + assert(wait_many(2, objects, 0, 0) == UINT32_MAX && error() == 6); + close_object(objects[1]); +} + +static void multiple_wait_with_owner_exit(int all) +{ + uint32_t args[] = {0, 1, 0, 0}; + uint32_t event = call("CreateEventA", 4, args); + struct work work = {.mutex = create(0), .ready = event, .mode = 1}; + join(start(&work)); + assert(call("ResetEvent", 1, &event)); + uint32_t objects[] = {work.mutex, event}; + + assert(wait_many(2, objects, 1, 0) == 258); + assert(call("SetEvent", 1, &event)); + uint32_t result = all ? wait_many(2, objects, 1, 1000) : wait_object(work.mutex, 0); + + assert(result == 128); + assert(release(work.mutex)); + close_object(event); + close_object(work.mutex); +} + +static void multiple_wait_wakes_on_release(uint32_t timeout, unsigned mode) +{ + uint32_t args[] = {0, 1, 0, 0}; + struct work work = {.mutex = create(0), .ready = call("CreateEventA", 4, args), .mode = mode}; + worker_thread thread = start(&work); + assert(wait_object(work.ready, 1000) == 0); + uint32_t objects[] = {work.ready, work.mutex}; + + uint32_t result = wait_many(2, objects, 1, timeout); + + assert(result == (mode == 5 ? 128 : 0) && release(work.mutex)); + join(thread); + close_object(work.ready); + close_object(work.mutex); +} + +static void multiple_semaphore_consumption(void) +{ + uint32_t args[] = {0, 1, 2, 0}; + uint32_t objects[] = {call("CreateSemaphoreA", 4, args), create(1)}; + assert(objects[0] && objects[1]); + + assert(wait_many(2, objects, 1, 0) == 0); + assert(wait_many(2, objects, 1, 0) == 258); + + assert(wait_object(objects[0], 0) == 258); + assert(release(objects[1]) && release(objects[1])); + assert(!release(objects[1]) && error() == 288); + close_object(objects[0]); + close_object(objects[1]); +} + +int main(void) +{ +#ifndef _WIN32 + assert(guest_map("mutex test", 0x50000000, 0x50000)); + g_fs_base = 0x50000000; + alarm(20); +#endif + recursive_ownership(); + waiting_and_abandonment(1, 0); + waiting_and_abandonment(1, 1000); + waiting_and_abandonment(1, UINT32_MAX); + waiting_and_abandonment(2, 1000); + waiting_and_abandonment(2, UINT32_MAX); + contended_mutual_exclusion(); + multiple_event_signals(); + multiple_wait_preserves_ownership(); + multiple_wait_with_owner_exit(0); + multiple_wait_with_owner_exit(1); + multiple_wait_wakes_on_release(1000, 2); + multiple_wait_wakes_on_release(UINT32_MAX, 2); + multiple_wait_wakes_on_release(1000, 5); + multiple_wait_wakes_on_release(UINT32_MAX, 5); + multiple_semaphore_consumption(); + puts("mutexes: ownership, recursion, finite/infinite waits, abandonment, 4000 contended updates and ABI passed"); + puts("multiple waits: all/any signals, atomic consumption, ownership rollback, abandonment, wakeup and errors passed"); +} diff --git a/decompiled/tests/strncmp.c b/decompiled/tests/strncmp.c @@ -0,0 +1,78 @@ +#include <assert.h> +#include <stdint.h> +#include <stdio.h> +#include <string.h> +#ifdef _WIN32 +#include <windows.h> +static int (__cdecl *compare)(const char *, const char *, size_t); +#else +#include "guest_crt.h" +#include "guest_memory.h" +recomp_func_t recomp_lookup(uint32_t address) { abort(); } +recomp_func_t recomp_lookup_import(uint32_t address) { abort(); } +#endif + +static int call(const char *left, const char *right, unsigned count) +{ +#ifdef _WIN32 + return compare(left, right, count); +#else + memcpy((void *)ADDR(0x50000100), left, 4); + memcpy((void *)ADDR(0x50000200), right, 4); + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = 0x50000100; + MEM32(g_esp + 8) = 0x50000200; + MEM32(g_esp + 12) = count; + g_ebx = 123; g_esi = 234; g_edi = 345; g_ebp = 456; + guest_crt_lookup("strncmp")(); + assert(g_esp == 0x5000ff04 && MEM32(g_esp + 8) == count); + assert(g_ebx == 123 && g_esi == 234 && g_edi == 345 && g_ebp == 456); + return (int32_t)g_eax; +#endif +} + +int main(void) +{ +#ifdef _WIN32 + compare = (void *)GetProcAddress(LoadLibraryA("msvcrt.dll"), "strncmp"); + assert(compare); +#else + assert(guest_map("strncmp test", 0x50000000, 0x10000)); +#endif + uint32_t digest = 2166136261u; + + for (unsigned count = 0; count <= 4; ++count) + for (unsigned a = 0; a < 256; ++a) + for (unsigned b = 0; b < 256; ++b) { + char left[] = {'A', (char)a, 'C', 0}; + char right[] = {'A', (char)b, 'b', 0}; + digest = (digest ^ (uint32_t)call(left, right, count)) * 16777619u; + } + + assert(digest == 0x1e9c0ec5); + assert(call("ABC", "ABD", 2) == 0); + assert(call("ABC", "AbC", 3) == -32); + assert(call("a\0Z", "a\0b", 4) == 0); +#ifndef _WIN32 + MEM8(0x5000ffff) = 'A'; + MEM8(0x50000100) = 'A'; + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = 0x5000ffff; + MEM32(g_esp + 8) = 0x50000100; + MEM32(g_esp + 12) = 1; + guest_crt_lookup("strncmp")(); + assert(g_eax == 0); + assert(guest_map("strncmp second page", 0x50010000, 0x10000)); + MEM8(0x50010000) = 'B'; + MEM8(0x50000101) = 'C'; + g_esp = 0x5000ff00; + MEM32(g_esp + 12) = 2; + guest_crt_lookup("strncmp")(); + assert(g_eax == UINT32_MAX); + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = MEM32(g_esp + 8) = MEM32(g_esp + 12) = 0; + guest_crt_lookup("strncmp")(); + assert(g_eax == 0); +#endif + printf("strncmp: 327680 byte pairs, digest %08x, bounds, case, NUL and ABI passed\n", digest); +} diff --git a/decompiled/tests/window.c b/decompiled/tests/window.c @@ -19,6 +19,7 @@ uint32_t guest_map(const char *name, uint32_t base, uint32_t size) #include "guest_memory.h" #include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> +#include <pthread.h> static void procedure(void); recomp_func_t recomp_lookup(uint32_t address) { assert(address == 0x11110000u); return procedure; } recomp_func_t recomp_lookup_import(uint32_t address) { return recomp_lookup(address); } @@ -30,6 +31,7 @@ static int wide; static int capture_focus, clear_in_callback; static int capture_geometry; static int capture_visibility; +static unsigned queue_dispatches; static uint32_t workspace(void) { @@ -64,6 +66,7 @@ static uint32_t call(const char *name, unsigned count, const uint32_t *arguments if (count == 2) return ((uint32_t (WINAPI *)(uint32_t, uint32_t))function)(arguments[0], arguments[1]); if (count == 3) return ((uint32_t (WINAPI *)(uint32_t, uint32_t, uint32_t))function)(arguments[0], arguments[1], arguments[2]); if (count == 4) return ((uint32_t (WINAPI *)(uint32_t, uint32_t, uint32_t, uint32_t))function)(arguments[0], arguments[1], arguments[2], arguments[3]); + if (count == 5) return ((uint32_t (WINAPI *)(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t))function)(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]); if (count == 6) return ((uint32_t (WINAPI *)(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t))function)(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]); if (count == 7) return ((uint32_t (WINAPI *)(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t))function)(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6]); assert(count == 12); @@ -109,6 +112,10 @@ static uint32_t error(void) static uint32_t receive(uint32_t handle, uint32_t message, uint32_t wparam, uint32_t lparam) { + if (message == 0x8001 || message == 0x8002) { + ++queue_dispatches; + return wparam ^ lparam; + } if (message == 0x24 || message == 0x81 || message == 0x83 || message == 1 || message == 2 || message == 0x82 || (capture_visibility && (message == 0x18 || message == 0x46 || message == 0x47 || message == 3 || message == 5)) || @@ -605,6 +612,180 @@ static void screensaver_inhibition_is_process_scoped(void) } #endif +static void posted_message_filtering_and_dispatch(void) +{ + message_count = 0; + uint32_t window = call("CreateWindowExA", 12, args); + uint32_t output = workspace() + 512; + uint32_t peek[] = {output, window, 0x8001, 0x8002, 0}; + uint32_t post[] = {window, 0x8001, 0x12345678, 0x76543210}; + assert(call("PostMessageA", 4, post)); + post[1] = 0x8002; + assert(call("PostMessageA", 4, post)); + memset(memory(output - 4), 0xa5, 36); + queue_dispatches = 0; + + assert(call("PeekMessageA", 5, peek)); + uint32_t first[7]; + memcpy(first, memory(output), sizeof(first)); + assert(call("PeekMessageA", 5, peek)); + + assert(!memcmp(first, memory(output), sizeof(first))); + assert(first[0] == window && first[1] == 0x8001); + assert(first[2] == 0x12345678 && first[3] == 0x76543210); + assert(memory(output)[-1] == 0xa5a5a5a5 && memory(output)[7] == 0xa5a5a5a5); + assert(queue_dispatches == 0); + assert(call("DispatchMessageA", 1, &output) == 0x64606468); + assert(queue_dispatches == 1); + + /* Remove the second message by filter, retaining the first one's position. */ + peek[2] = peek[3] = 0x8002; peek[4] = 1; + assert(call("PeekMessageA", 5, peek) && memory(output)[1] == 0x8002); + assert(!call("PeekMessageA", 5, peek)); + assert(memory(output)[1] == 0x8002); + peek[2] = peek[3] = 0x8001; + assert(call("GetMessageA", 4, peek) && memory(output)[1] == 0x8001); + assert(!call("TranslateMessage", 1, &output)); + assert(!call("PeekMessageA", 5, peek)); + assert(call("DestroyWindow", 1, &window)); +} + +static void thread_messages_and_quit(void) +{ + uint32_t output = workspace() + 512; + uint32_t post[] = {0, 0x8001, 41, 57}; + uint32_t peek[] = {output, UINT32_MAX, 0x8001, 0x8001, 1}; + assert(call("PostMessageA", 4, post)); + + assert(call("PeekMessageA", 5, peek)); + uint32_t result = call("DispatchMessageA", 1, &output); + + assert(!result && memory(output)[0] == 0 && memory(output)[1] == 0x8001); + assert(memory(output)[2] == 41 && memory(output)[3] == 57); + assert(!call("PeekMessageA", 5, peek)); + uint32_t code = 73; + call("PostQuitMessage", 1, &code); + peek[1] = 0; peek[4] = 0; + assert(call("PeekMessageA", 5, peek)); + assert(memory(output)[1] == 0x12 && memory(output)[2] == 73); + assert(call("PeekMessageA", 5, peek)); + assert(!call("GetMessageA", 4, peek)); + assert(memory(output)[1] == 0x12 && memory(output)[2] == 73); + assert(!call("PeekMessageA", 5, peek)); +} + +static void translation_preserves_the_input_message(void) +{ + message_count = 0; + uint32_t window = call("CreateWindowExA", 12, args); + uint32_t output = workspace() + 512; + uint32_t input[] = {window, 0x100, 32, 0x00390001, 0, 0, 0}; + memcpy(memory(output), input, sizeof(input)); + uint32_t peek[] = {output + 64, window, 0x102, 0x102, 1}; + + uint32_t result = call("TranslateMessage", 1, &output); + + assert(result && !memcmp(memory(output), input, sizeof(input))); + assert(call("PeekMessageA", 5, peek)); + assert(memory(output + 64)[1] == 0x102 && memory(output + 64)[2] == 32); + assert(memory(output + 64)[3] == 0x00390001); + memory(output)[1] = 0x101; + memory(output)[3] = 0xc0390001; + assert(call("TranslateMessage", 1, &output)); + assert(!call("PeekMessageA", 5, peek)); + assert(call("DestroyWindow", 1, &window)); +} + +#ifdef _WIN32 +static DWORD WINAPI post_from_thread(void *argument) +#else +static void *post_from_thread(void *argument) +#endif +{ +#ifdef _WIN32 + Sleep(20); +#else + g_esp = 0x5000d000; + SDL_Delay(20); +#endif + assert(call("PostMessageA", 4, argument)); + return 0; +} + +static void waiting_message_loop_wakes_for_post(void) +{ + message_count = 0; + uint32_t window = call("CreateWindowExA", 12, args); + uint32_t post[] = {window, 0x8001, 123, 456}; + uint32_t output = workspace() + 512; + uint32_t get[] = {output, window, 0x8001, 0x8001}; +#ifdef _WIN32 + HANDLE thread = CreateThread(NULL, 0, post_from_thread, post, 0, NULL); + assert(thread); +#else + pthread_t thread; + assert(!pthread_create(&thread, NULL, post_from_thread, post)); +#endif + + uint32_t result = call("GetMessageA", 4, get); + + assert(result && memory(output)[1] == 0x8001); + assert(memory(output)[2] == 123 && memory(output)[3] == 456); +#ifdef _WIN32 + assert(WaitForSingleObject(thread, 1000) == WAIT_OBJECT_0); + assert(CloseHandle(thread)); +#else + assert(!pthread_join(thread, NULL)); +#endif + assert(call("DestroyWindow", 1, &window)); +} + +#ifndef _WIN32 +static void sdl_keyboard_and_mouse_reach_guest_messages(void) +{ + message_count = 0; + uint32_t window = call("CreateWindowExA", 12, args); + SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT); + SDL_Event event = {.type = SDL_KEYDOWN}; + event.key.windowID = SDL_GetWindowID(linux_graphics_window()); + event.key.keysym.sym = SDLK_w; + event.key.keysym.mod = KMOD_LSHIFT; + assert(SDL_PushEvent(&event) == 1); + event.type = SDL_KEYUP; + event.key.keysym.mod = KMOD_NONE; + assert(SDL_PushEvent(&event) == 1); + uint32_t output = workspace() + 512, keys = workspace() + 640; + uint32_t peek[] = {output, window, 0x100, 0x101, 1}; + + assert(call("PeekMessageA", 5, peek)); + assert(call("GetKeyboardState", 1, &keys)); + + assert(memory(output)[1] == 0x100 && memory(output)[2] == 'W'); + assert(memory(output)[3] == 0x00110001); + assert(((uint8_t *)memory(keys))['W'] == 0x80 && ((uint8_t *)memory(keys))[16] == 0x80); + assert(call("PeekMessageA", 5, peek)); + assert(memory(output)[1] == 0x101 && memory(output)[3] == 0xc0110001); + assert(call("GetKeyboardState", 1, &keys)); + assert(!((uint8_t *)memory(keys))['W'] && !((uint8_t *)memory(keys))[16]); + + memset(&event, 0, sizeof(event)); + event.type = SDL_MOUSEBUTTONDOWN; + event.button.button = SDL_BUTTON_LEFT; + event.button.x = -3; event.button.y = 29; + assert(SDL_PushEvent(&event) == 1); + event.type = SDL_MOUSEBUTTONUP; + assert(SDL_PushEvent(&event) == 1); + peek[2] = 0x201; peek[3] = 0x202; + assert(call("PeekMessageA", 5, peek)); + assert(memory(output)[1] == 0x201 && memory(output)[2] == 1 && memory(output)[3] == 0x001dfffd); + assert(call("GetKeyboardState", 1, &keys) && ((uint8_t *)memory(keys))[1] == 0x80); + assert(call("PeekMessageA", 5, peek)); + assert(memory(output)[1] == 0x202 && memory(output)[2] == 0); + assert(call("GetKeyboardState", 1, &keys) && !((uint8_t *)memory(keys))[1]); + assert(call("DestroyWindow", 1, &window)); +} +#endif + int main(void) { game_data_Clientr_exe(); @@ -632,6 +813,13 @@ int main(void) window_geometry_preserves_requested_client_area(); visibility_dispatches_callbacks_and_preserves_geometry(); reconstructed_icon_matches_native_window_pixels(); + posted_message_filtering_and_dispatch(); + thread_messages_and_quit(); + translation_preserves_the_input_message(); + waiting_message_loop_wakes_for_post(); +#ifndef _WIN32 + sdl_keyboard_and_mouse_reach_guest_messages(); +#endif class_release_invalidates_its_atom(); } wide = 0; @@ -642,5 +830,6 @@ int main(void) screensaver_inhibition_is_process_scoped(); #endif puts("window: ANSI/UTF-16 creation, rejection, focus/activation, reentrancy, client geometry, destruction and desktop format passed"); + puts("messages: posting, filtering, peek/remove, dispatch, thread messages, quit and character translation passed"); return 0; } diff --git a/tools/reconstruction/test_portable_mutex.py b/tools/reconstruction/test_portable_mutex.py @@ -0,0 +1,21 @@ +"""Check the guest mutex ownership and waiting contract on Windows and native Linux.""" +import pathlib +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +decompiled = root / "decompiled" +work = root / "tools/reconstruction/work/portable-mutex" +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/mutex.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/mutex"], check=True) +actual = subprocess.check_output(wsl + ["./build/linux/mutex"], text=True, timeout=30) +assert actual == expected, (expected, actual) +print("Windows == Linux contract: " + actual.strip()) diff --git a/tools/reconstruction/test_portable_strncmp.py b/tools/reconstruction/test_portable_strncmp.py @@ -0,0 +1,21 @@ +"""Check the guest bounded string comparison contract on Windows and native Linux.""" +import pathlib +import subprocess + + +root = pathlib.Path(__file__).resolve().parents[2] +decompiled = root / "decompiled" +work = root / "tools/reconstruction/work/portable-strncmp" +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/strncmp.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/strncmp"], check=True) +actual = subprocess.check_output(wsl + ["./build/linux/strncmp"], text=True, timeout=30) +assert actual == expected, (expected, actual) +print("Windows == Linux contract: " + actual.strip())