commit 74bceda813be0ce595880a103245ba0069abcb31
parent a8db094eabb33f8fa57aa075a1e952b82774fd66
Author: anon <anon@example.com>
Date: Mon, 19 Oct 2026 21:35:41 +0000
Reduce Wasm bytecode and remove the socket polling worker
Compile the browser client for size and deliver socket readiness through nonblocking browser callbacks. Preserve pending events during lock contention and stop the watcher on final Winsock cleanup. Add threaded event-delivery and watcher-lifecycle regressions, and record the remaining total-memory gap.
Diffstat:
7 files changed, 189 insertions(+), 28 deletions(-)
diff --git a/src/Makefile.wasm b/src/Makefile.wasm
@@ -1,7 +1,7 @@
CC := ../toolchains/emsdk/upstream/emscripten/emcc
CPPFLAGS := -Iruntime -Igame -Idata -DRECOMP_PORTABLE
# Keep exception landing pads in Wasm so JSPI can yield through guest calls.
-CFLAGS := -O2 -flto=thin -fno-strict-aliasing -pthread -sSUPPORT_LONGJMP=wasm
+CFLAGS := -Oz -flto=thin -fno-strict-aliasing -pthread -sSUPPORT_LONGJMP=wasm
PORT_FLAGS := -sUSE_SDL=2 -sUSE_FREETYPE=1
RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_imports.c runtime/linux_gdi.c runtime/linux_audio.c runtime/linux_music.c runtime/browser_audio.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_snapshot.c runtime/browser_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_exception.c runtime/guest_rtti.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c runtime/linux_path.c runtime/browser_host.c runtime/browser_resolution.c runtime/browser_profile.c
GAME_SOURCES := $(wildcard game/*/*.c) game/dispatch.c
@@ -74,6 +74,10 @@ build/wasm/web/runtime-test.html: tests/browser_runtime.c runtime/browser_host.c
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_network.js -o $@ --js-library runtime/browser_profile.js
+build/wasm/socket-events.js: tests/browser_socket_events.c runtime/browser_network.c runtime/linux_sync.c runtime/guest_memory.c runtime/guest_heap.c runtime/recomp_state.c runtime/browser_network.js Makefile.wasm
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) -Dpthread_mutex_trylock=test_mutex_trylock $(filter %.c,$^) --js-library runtime/browser_network.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sEXIT_RUNTIME -o $@
+
build/wasm/web/files-test.html: tests/files.c runtime/linux_file.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/linux_file.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h runtime/browser_profile.c runtime/browser_profile.js
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -o $@ --js-library runtime/browser_profile.js
diff --git a/src/runtime/browser_network.c b/src/runtime/browser_network.c
@@ -2,6 +2,7 @@
#include "linux_sync.h"
#include "guest_heap.h"
#include <pthread.h>
+#include <errno.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <emscripten.h>
@@ -14,6 +15,7 @@ int ao_socket_available(int handle);
int ao_socket_send(int handle, const void *data, int size);
int ao_socket_receive(int handle, void *data, int size, int peek);
void ao_socket_close(int handle);
+void ao_socket_watch(int enabled);
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static unsigned startup_count;
@@ -34,24 +36,23 @@ static struct browser_socket *find_socket_locked(uint32_t handle)
return NULL;
}
-static void *watch_events(void *argument)
+EMSCRIPTEN_KEEPALIVE void browser_socket_events(void)
{
- for (;;) {
- pthread_mutex_lock(&mutex);
- for (struct browser_socket *socket = sockets; socket; socket = socket->next) {
- if (!socket->armed) continue;
- int status = ao_socket_status(socket->handle);
- uint32_t ready = (status & 2 ? 1 : 0) | (status & 12 ? 32 : 0);
- ready &= socket->armed;
- socket->recorded |= ready;
- socket->armed &= ~ready;
- if (status & 8) socket->error = 10054;
- if (ready && socket->event) linux_sync_event_change(socket->event, 1);
- }
- pthread_mutex_unlock(&mutex);
- usleep(5000);
+ /* The browser thread never waits for game workers holding either lock. */
+ int error = pthread_mutex_trylock(&mutex);
+ if (error == EBUSY) return;
+ if (error) abort();
+ for (struct browser_socket *socket = sockets; socket; socket = socket->next) {
+ if (!socket->armed) continue;
+ int status = ao_socket_status(socket->handle);
+ uint32_t ready = (status & 2 ? 1 : 0) | (status & 12 ? 32 : 0);
+ ready &= socket->armed;
+ if (ready && socket->event && !linux_sync_event_try_change(socket->event, 1)) continue;
+ socket->recorded |= ready;
+ socket->armed &= ~ready;
+ if (status & 8) socket->error = 10054;
}
- return NULL;
+ if (pthread_mutex_unlock(&mutex)) abort();
}
static void create_socket(void)
@@ -212,8 +213,7 @@ static void event_select(void)
socket->recorded = socket->error = 0;
socket->nonblocking = 1;
if (mask && !watching) {
- pthread_t thread;
- if (pthread_create(&thread, NULL, watch_events, NULL) || pthread_detach(thread)) abort();
+ ao_socket_watch(1);
watching = 1;
}
g_eax = 0;
@@ -324,12 +324,18 @@ static void cleanup(void)
pthread_mutex_lock(&mutex);
g_eax = UINT32_MAX;
if (startup_count) {
- if (!--startup_count) while (sockets) {
- struct browser_socket *socket = sockets;
- sockets = socket->next;
- if (socket->event) linux_sync_event_release(socket->event);
- ao_socket_close(socket->handle);
- free(socket);
+ if (!--startup_count) {
+ while (sockets) {
+ struct browser_socket *socket = sockets;
+ sockets = socket->next;
+ if (socket->event) linux_sync_event_release(socket->event);
+ ao_socket_close(socket->handle);
+ free(socket);
+ }
+ if (watching) {
+ ao_socket_watch(0);
+ watching = 0;
+ }
}
g_eax = 0;
} else MEM32(g_fs_base + 0x34) = 10093;
diff --git a/src/runtime/browser_network.js b/src/runtime/browser_network.js
@@ -1,5 +1,14 @@
addToLibrary({
- $AOSockets: {next: 0x09000000, sockets: new Map()},
+ $AOSockets: {next: 0x09000000, sockets: new Map(), watcher: null},
+ ao_socket_watch__deps: ['$AOSockets', 'browser_socket_events'],
+ ao_socket_watch__proxy: 'sync',
+ ao_socket_watch: (enabled) => {
+ if (enabled) AOSockets.watcher ??= setInterval(_browser_socket_events, 5);
+ else {
+ clearInterval(AOSockets.watcher);
+ AOSockets.watcher = null;
+ }
+ },
ao_socket_create__deps: ['$AOSockets'],
ao_socket_create__proxy: 'sync',
ao_socket_create: () => {
diff --git a/src/runtime/linux_sync.c b/src/runtime/linux_sync.c
@@ -320,6 +320,17 @@ void linux_sync_event_change(struct semaphore_handle *event, int signaled)
if (pthread_mutex_unlock(&mutex)) abort();
}
+/* Browser callbacks retry rather than blocking the UI on a worker. */
+int linux_sync_event_try_change(struct semaphore_handle *event, int signaled)
+{
+ int error = pthread_mutex_trylock(&mutex);
+ if (error == EBUSY) return 0;
+ if (error) abort();
+ change_event_object_locked(event, signaled);
+ if (pthread_mutex_unlock(&mutex)) abort();
+ return 1;
+}
+
static void close_handle_locked(void)
{
struct semaphore_handle *handle = find_handle_locked(MEM32(g_esp + 4));
diff --git a/src/runtime/linux_sync.h b/src/runtime/linux_sync.h
@@ -6,4 +6,5 @@ struct semaphore_handle;
struct semaphore_handle *linux_sync_event_acquire(uint32_t handle);
void linux_sync_event_release(struct semaphore_handle *event);
void linux_sync_event_change(struct semaphore_handle *event, int signaled);
+int linux_sync_event_try_change(struct semaphore_handle *event, int signaled);
#endif
diff --git a/src/tests/browser_network.mjs b/src/tests/browser_network.mjs
@@ -4,20 +4,38 @@ import vm from 'node:vm';
import test from 'node:test';
function network(arguments_, protocol = 'https:') {
- const connections = [];
+ const connections = [], timers = [], stopped = [];
const context = vm.createContext({
Module: {arguments: arguments_},
location: {href: `${protocol}//game.example/`, protocol},
URL,
+ _browser_socket_events() {},
+ setInterval(callback, delay) { timers.push({callback, delay}); return timers.length; },
+ clearInterval(timer) { stopped.push(timer); },
WebSocket: class {
constructor(url) { connections.push(url.href); }
},
addToLibrary(library) { Object.assign(context, library, {AOSockets: library.$AOSockets}); }
});
vm.runInContext(fs.readFileSync(new URL('../runtime/browser_network.js', import.meta.url), 'utf8'), context);
- return {context, connections};
+ return {context, connections, timers, stopped};
}
+test('readiness watching starts once and can restart after cleanup', () => {
+ const {context, timers, stopped} = network([]);
+
+ context.ao_socket_watch(1);
+ context.ao_socket_watch(1);
+ context.ao_socket_watch(0);
+ context.ao_socket_watch(1);
+
+ assert.equal(timers.length, 2);
+ assert.equal(timers[0].callback, context._browser_socket_events);
+ assert.equal(timers[0].delay, 5);
+ assert.deepEqual(stopped, [1]);
+ assert.equal(context.AOSockets.watcher, 2);
+});
+
for (const executable of [[], ['Clientr.exe']]) {
test(`world/chat routing with ${executable.length ? 'prepended' : 'no'} executable`, () => {
const {context, connections} = network([...executable, 'localtest', 'localtest', '80', '2130706433', '7511', '0', '0']);
diff --git a/src/tests/browser_socket_events.c b/src/tests/browser_socket_events.c
@@ -0,0 +1,112 @@
+#include "linux_network.h"
+#include "linux_sync.h"
+#include "guest_memory.h"
+#include <assert.h>
+#include <errno.h>
+#undef pthread_mutex_trylock
+#include <pthread.h>
+#include <stdatomic.h>
+#include <emscripten/threading.h>
+
+static atomic_int status, blocked_lock, retries;
+static pthread_mutex_t *socket_mutex;
+
+/* Simulate contention at each public event-delivery boundary on the UI thread. */
+int test_mutex_trylock(pthread_mutex_t *mutex)
+{
+ if (emscripten_is_main_runtime_thread()) {
+ if (!socket_mutex) socket_mutex = mutex;
+ int blocked = atomic_load(&blocked_lock);
+ if ((blocked == 1 && mutex == socket_mutex) ||
+ (blocked == 2 && mutex != socket_mutex)) {
+ atomic_fetch_add(&retries, 1);
+ return EBUSY;
+ }
+ }
+ return pthread_mutex_trylock(mutex);
+}
+
+/* Keep readiness under test control while using the production timer and C adapter. */
+int ao_socket_create(void) { return 0x09000000; }
+void ao_socket_connect(int handle, int port) {}
+int ao_socket_status(int handle) { return atomic_load(&status); }
+int ao_socket_available(int handle) { return 1; }
+int ao_socket_send(int handle, const void *data, int size) { return size; }
+int ao_socket_receive(int handle, void *data, int size, int peek)
+{
+ *(unsigned char *)data = 0x5a;
+ return 1;
+}
+void ao_socket_close(int handle) {}
+uint32_t guest_crt_errno_address(void) { return 0x50001000; }
+
+static uint32_t call(const char *name, unsigned count, const uint32_t *arguments)
+{
+ recomp_func_t function = linux_network_lookup(name, 0);
+ if (!function) function = linux_sync_lookup(name);
+ assert(function);
+ g_esp = 0x5000f000;
+ for (unsigned i = 0; i < count; ++i) MEM32(g_esp + 4 + i * 4) = arguments[i];
+ function();
+ assert(g_esp == 0x5000f000 + (count + 1) * 4);
+ return g_eax;
+}
+
+static void readiness_survives_contention(int lock)
+{
+ atomic_store(&status, 0);
+ atomic_store(&retries, 0);
+ atomic_store(&blocked_lock, lock);
+ uint32_t socket = call("socket", 3, (uint32_t[]){2, 1, 0});
+ uint32_t event = call("CreateEventA", 4, (uint32_t[]){0, 1, 0, 0});
+ assert(socket == 0x09000000 && event);
+ assert(!call("WSAEventSelect", 3, (uint32_t[]){socket, event, 33}));
+ atomic_store(&status, 2);
+
+ uint32_t waiting = call("WaitForSingleObject", 2, (uint32_t[]){event, 100});
+ atomic_store(&blocked_lock, 0);
+ uint32_t delivered = call("WaitForSingleObject", 2, (uint32_t[]){event, 1000});
+ assert(!call("WSAEnumNetworkEvents", 3, (uint32_t[]){socket, event, 0x50002000}));
+
+ assert(waiting == 258 && atomic_load(&retries) > 0);
+ assert(delivered == 0 && MEM32(0x50002000) == 1);
+ assert(MEM32(0x50002018) == 0);
+
+ uint32_t disarmed = call("WaitForSingleObject", 2, (uint32_t[]){event, 25});
+ uint32_t received = call("recv", 4, (uint32_t[]){socket, 0x50003000, 1, 0});
+ uint32_t rearmed = call("WaitForSingleObject", 2, (uint32_t[]){event, 1000});
+ assert(!call("WSAEnumNetworkEvents", 3, (uint32_t[]){socket, event, 0x50002000}));
+
+ assert(disarmed == 258 && received == 1 && MEM8(0x50003000) == 0x5a);
+ assert(rearmed == 0 && MEM32(0x50002000) == 1);
+
+ atomic_store(&status, 4);
+ uint32_t closed = call("WaitForSingleObject", 2, (uint32_t[]){event, 1000});
+ assert(!call("WSAEnumNetworkEvents", 3, (uint32_t[]){socket, event, 0x50002000}));
+
+ assert(closed == 0 && MEM32(0x50002000) == 32 && MEM32(0x50002018) == 0);
+
+ atomic_store(&status, 0);
+ assert(!call("WSAEventSelect", 3, (uint32_t[]){socket, event, 33}));
+
+ atomic_store(&status, 8);
+ uint32_t failed = call("WaitForSingleObject", 2, (uint32_t[]){event, 1000});
+ assert(!call("WSAEnumNetworkEvents", 3, (uint32_t[]){socket, event, 0x50002000}));
+
+ assert(failed == 0 && MEM32(0x50002000) == 32 && MEM32(0x50002018) == 10054);
+ assert(!call("closesocket", 1, &socket));
+ assert(call("CloseHandle", 1, &event));
+}
+
+int main(void)
+{
+ assert(!emscripten_is_main_runtime_thread());
+ assert(guest_map("socket event test", 0x50000000, 0x10000));
+ g_fs_base = 0x50000000;
+ assert(!call("WSAStartup", 2, (uint32_t[]){0x0202, 0x50001000}));
+ readiness_survives_contention(1);
+ readiness_survives_contention(2);
+ assert(!call("WSACleanup", 0, NULL));
+ puts("socket events: nonblocking UI callbacks, contention, rearming, close and error delivery passed");
+ return 0;
+}