aorecomp

Anarchy Online classic in the browser

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


commit 87d9f8a4992a21e39e6140318608de50a5ff7250
parent 56240f54c987d639080b188a733068a837ed75b9
Author: anon <anon@example.com>
Date:   Thu, 15 Oct 2026 10:58:22 +0000

Implement native Linux TCP transport and connection readiness

Diffstat:
Mdecompiled/Makefile.linux | 2+-
Mdecompiled/runtime/linux_network.c | 380+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdecompiled/runtime/linux_sync.c | 19+++++++++++++------
Mdecompiled/tests/mutex.c | 26+++++++++++++++-----------
Mdecompiled/tests/network_startup.c | 337+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/reconstruction/test_portable_network_startup.py | 4++--
6 files changed, 748 insertions(+), 20 deletions(-)

diff --git a/decompiled/Makefile.linux b/decompiled/Makefile.linux @@ -76,7 +76,7 @@ build/linux/guest-scanf: tests/guest_scanf.c runtime/guest_crt.c runtime/guest_h build/linux/network-startup: tests/network_startup.c runtime/linux_network.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/linux_network.h runtime/guest_memory.h mkdir -p $(@D) - $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -lm -o $@ + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lm -o $@ build/linux/os-version: tests/os_version.c runtime/linux_platform.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/linux_platform.h runtime/guest_memory.h mkdir -p $(@D) diff --git a/decompiled/runtime/linux_network.c b/decompiled/runtime/linux_network.c @@ -1,8 +1,145 @@ +#define _GNU_SOURCE #include "linux_network.h" #include <arpa/inet.h> +#include <errno.h> +#include <fcntl.h> +#include <pthread.h> +#include <poll.h> +#include <sys/ioctl.h> +#include <time.h> #include <unistd.h> static unsigned startup_count; +static pthread_mutex_t socket_mutex = PTHREAD_MUTEX_INITIALIZER; +struct guest_socket { + uint32_t handle; + int descriptor, connecting; + unsigned shutdown; /* Local read/write bits 1/2; observed peer TCP EOF bit 4. */ + struct guest_socket *next; +}; +static struct guest_socket *sockets; +static uint32_t next_handle = 0x09000000u; + +static uint32_t socket_error(int error) +{ + switch (error) { + case EBADF: case ENOTSOCK: return 10038; + case EINTR: return 10004; + case EACCES: case EPERM: return 10013; + case EFAULT: return 10014; + case EINVAL: return 10022; + case EMFILE: case ENFILE: return 10024; + case EAGAIN: return 10035; + case EINPROGRESS: return 10035; + case EALREADY: return 10037; + case EPROTONOSUPPORT: return 10043; + case ESOCKTNOSUPPORT: return 10044; + case EOPNOTSUPP: return 10045; + case EAFNOSUPPORT: return 10047; + case EADDRINUSE: return 10048; + case EADDRNOTAVAIL: return 10049; + case ENETDOWN: return 10050; + case ENETUNREACH: return 10051; + case ECONNABORTED: return 10053; + case ECONNRESET: return 10054; + case ENOBUFS: case ENOMEM: return 10055; + case EISCONN: return 10056; + case ENOTCONN: return 10057; + case EPIPE: return 10058; + case ETIMEDOUT: return 10060; + case ECONNREFUSED: return 10061; + case EHOSTUNREACH: return 10065; + default: + fprintf(stderr, "Unmapped socket error: %s\n", strerror(error)); + abort(); + } +} + +static struct guest_socket *find_socket_locked(uint32_t handle) +{ + if (!startup_count) { MEM32(g_fs_base + 0x34) = 10093; return NULL; } + for (struct guest_socket *socket = sockets; socket; socket = socket->next) + if (socket->handle == handle) return socket; + MEM32(g_fs_base + 0x34) = 10038; + return NULL; +} + +static void create_socket(void) +{ + int family = MEM32(g_esp + 4), type = MEM32(g_esp + 8), protocol = MEM32(g_esp + 12); + g_esp += 16; + g_eax = UINT32_MAX; + if (pthread_mutex_lock(&socket_mutex)) abort(); + uint32_t error = 0; + if (!startup_count) error = 10093; + else if (family != 2 || (type != 1 && type != 2) || (protocol && protocol != 6 && protocol != 17)) { + fprintf(stderr, "Unsupported socket family/type/protocol: %d/%d/%d\n", family, type, protocol); + abort(); + } else { + int descriptor = socket(AF_INET, type == 1 ? SOCK_STREAM : SOCK_DGRAM, protocol); + if (descriptor < 0) error = socket_error(errno); + else { + struct guest_socket *socket = malloc(sizeof(*socket)); + if (!socket || next_handle >= 0x0a000000u) abort(); + *socket = (struct guest_socket){next_handle, descriptor, 0, 0, sockets}; + sockets = socket; + next_handle += 4; + g_eax = socket->handle; + } + } + MEM32(g_fs_base + 0x34) = error; + if (pthread_mutex_unlock(&socket_mutex)) abort(); +} + +static void close_socket(void) +{ + uint32_t handle = MEM32(g_esp + 4); + g_esp += 8; + g_eax = UINT32_MAX; + if (pthread_mutex_lock(&socket_mutex)) abort(); + struct guest_socket *socket = find_socket_locked(handle); + if (socket) { + if (close(socket->descriptor)) MEM32(g_fs_base + 0x34) = socket_error(errno); + else { + struct guest_socket **link = &sockets; + while (*link != socket) link = &(*link)->next; + *link = socket->next; + free(socket); + MEM32(g_fs_base + 0x34) = 0; + g_eax = 0; + } + } + if (pthread_mutex_unlock(&socket_mutex)) abort(); +} + +static void control_socket(void) +{ + uint32_t handle = MEM32(g_esp + 4), command = MEM32(g_esp + 8), argument = MEM32(g_esp + 12); + g_esp += 16; + g_eax = UINT32_MAX; + if (pthread_mutex_lock(&socket_mutex)) abort(); + struct guest_socket *socket = find_socket_locked(handle); + if (socket) { + if (!argument) MEM32(g_fs_base + 0x34) = 10014; + else { + unsigned long request; + if (command == 0x8004667eu) request = FIONBIO; + else if (command == 0x4004667fu) request = FIONREAD; + else { + fprintf(stderr, "Unsupported ioctlsocket command: %08x\n", command); + abort(); + } + int value = request == FIONBIO ? MEM32(argument) != 0 : 0; + if (ioctl(socket->descriptor, request, &value)) MEM32(g_fs_base + 0x34) = socket_error(errno); + else { + if (request == FIONREAD) MEM32(argument) = value; + MEM32(g_fs_base + 0x34) = 0; + g_eax = 0; + } + } + } + if (pthread_mutex_unlock(&socket_mutex)) abort(); +} static void network_long(void) { @@ -10,6 +147,218 @@ static void network_long(void) g_esp += 8; } +static int socket_descriptor(uint32_t handle, unsigned direction) +{ + /* Hold a descriptor reference across the potentially blocking native call. */ + if (pthread_mutex_lock(&socket_mutex)) abort(); + struct guest_socket *socket = find_socket_locked(handle); + if (socket && (socket->shutdown & direction)) { + MEM32(g_fs_base + 0x34) = 10058; + socket = NULL; + } + int descriptor = socket ? fcntl(socket->descriptor, F_DUPFD_CLOEXEC, 0) : -1; + if (socket && descriptor < 0) MEM32(g_fs_base + 0x34) = socket_error(errno); + if (pthread_mutex_unlock(&socket_mutex)) abort(); + return descriptor; +} + +static void connect_socket(void) +{ + uint32_t handle = MEM32(g_esp + 4), address = MEM32(g_esp + 8); + int32_t length = MEM32(g_esp + 12); + g_esp += 16; + g_eax = UINT32_MAX; + int descriptor = socket_descriptor(handle, 0); + if (descriptor < 0) return; + + uint32_t error = 0; + if (!address || length < 16) error = 10014; + else if (MEM16(address) != 2) error = 10047; + else { + struct sockaddr_in native = {0}; + native.sin_family = AF_INET; + native.sin_port = MEM16(address + 2); + native.sin_addr.s_addr = MEM32(address + 4); + if (connect(descriptor, (struct sockaddr *)&native, sizeof(native))) error = socket_error(errno); + } + if (close(descriptor)) abort(); + if (pthread_mutex_lock(&socket_mutex)) abort(); + for (struct guest_socket *socket = sockets; socket; socket = socket->next) + if (socket->handle == handle) { socket->connecting = error == 10035; break; } + if (pthread_mutex_unlock(&socket_mutex)) abort(); + MEM32(g_fs_base + 0x34) = error; + g_eax = error ? UINT32_MAX : 0; +} + +static void transfer_socket(int sending) +{ + uint32_t handle = MEM32(g_esp + 4), buffer = MEM32(g_esp + 8), flags = MEM32(g_esp + 16); + int32_t length = MEM32(g_esp + 12); + g_esp += 20; + g_eax = UINT32_MAX; + int descriptor = socket_descriptor(handle, sending ? 2 : 1); + if (descriptor < 0) return; + uint32_t error = 0; + if (!buffer || length < 0) error = 10014; + else { + if (flags && (sending || flags != 2)) { + fprintf(stderr, "Unsupported socket %s flags: %08x\n", sending ? "send" : "recv", flags); + abort(); + } + int result = sending ? send(descriptor, (void *)ADDR(buffer), length, MSG_NOSIGNAL) : + recv(descriptor, (void *)ADDR(buffer), length, flags ? MSG_PEEK : 0); + if (result < 0) error = socket_error(errno); + else { + g_eax = result; + if (!sending && !result && length) { + int type; + socklen_t size = sizeof(type); + if (getsockopt(descriptor, SOL_SOCKET, SO_TYPE, &type, &size)) abort(); + if (type == SOCK_STREAM) { + if (pthread_mutex_lock(&socket_mutex)) abort(); + for (struct guest_socket *socket = sockets; socket; socket = socket->next) + if (socket->handle == handle) { socket->shutdown |= 4; break; } + if (pthread_mutex_unlock(&socket_mutex)) abort(); + } + } + } + } + if (close(descriptor)) abort(); + MEM32(g_fs_base + 0x34) = error; +} + +static void send_socket(void) { transfer_socket(1); } +static void receive_socket(void) { transfer_socket(0); } + +static void shutdown_socket(void) +{ + uint32_t handle = MEM32(g_esp + 4), how = MEM32(g_esp + 8); + g_esp += 12; + g_eax = UINT32_MAX; + if (pthread_mutex_lock(&socket_mutex)) abort(); + struct guest_socket *socket = find_socket_locked(handle); + if (socket) { + if (how > 2) MEM32(g_fs_base + 0x34) = 10022; + else { + int result = shutdown(socket->descriptor, how == 0 ? SHUT_RD : how == 1 ? SHUT_WR : SHUT_RDWR); + /* Linux discards the TCP connection after both FINs; Winsock still accepts shutdown. */ + if (result && !(errno == ENOTCONN && (socket->shutdown & 4))) + MEM32(g_fs_base + 0x34) = socket_error(errno); + else { + socket->shutdown |= how == 0 ? 1 : how == 1 ? 2 : 3; + MEM32(g_fs_base + 0x34) = 0; + g_eax = 0; + } + } + } + if (pthread_mutex_unlock(&socket_mutex)) abort(); +} + +static void select_sockets(void) +{ + uint32_t sets[] = {MEM32(g_esp + 8), MEM32(g_esp + 12), MEM32(g_esp + 16)}; + uint32_t timeout = MEM32(g_esp + 20), counts[3], total = 0, error = 0; + int64_t deadline = 0; + g_esp += 24; + g_eax = UINT32_MAX; + if (pthread_mutex_lock(&socket_mutex)) abort(); + if (!startup_count) error = 10093; + if (pthread_mutex_unlock(&socket_mutex)) abort(); + if (error) { MEM32(g_fs_base + 0x34) = error; return; } + + /* Winsock uses arrays of 32-bit handles and an unchanged 32-bit timeval. */ + if (timeout) { + int32_t seconds = MEM32(timeout), micros = MEM32(timeout + 4); + if (seconds < 0 || micros < 0) { MEM32(g_fs_base + 0x34) = 10022; return; } + struct timespec now; + if (clock_gettime(CLOCK_MONOTONIC, &now)) abort(); + deadline = (int64_t)now.tv_sec * 1000000000 + now.tv_nsec + + (int64_t)seconds * 1000000000 + (int64_t)micros * 1000; + } + for (unsigned set = 0; set < 3; ++set) { + counts[set] = sets[set] ? MEM32(sets[set]) : 0; + if (counts[set] > UINT32_MAX - total) abort(); + total += counts[set]; + } + if (!total) { MEM32(g_fs_base + 0x34) = 10022; return; } + struct pollfd *polls = calloc(total, sizeof(*polls)); + struct select_entry { uint32_t handle; int descriptor, connecting, ready; }; + struct select_entry *entries = calloc(total, sizeof(*entries)); + if (!polls || !entries) abort(); + unsigned acquired = 0; + if (pthread_mutex_lock(&socket_mutex)) abort(); + for (unsigned set = 0; set < 3 && !error; ++set) { + for (unsigned i = 0; i < counts[set]; ++i) { + uint32_t handle = MEM32(sets[set] + 4 + i * 4); + struct guest_socket *socket = find_socket_locked(handle); + if (!socket) { error = MEM32(g_fs_base + 0x34); break; } + int descriptor = fcntl(socket->descriptor, F_DUPFD_CLOEXEC, 0); + if (descriptor < 0) { error = socket_error(errno); break; } + entries[acquired] = (struct select_entry){handle, descriptor, socket->connecting, 0}; + polls[acquired++] = (struct pollfd){descriptor, set == 0 ? POLLIN : set == 1 ? POLLOUT : POLLPRI, 0}; + } + } + if (pthread_mutex_unlock(&socket_mutex)) abort(); + + /* poll reports failed connects as writable; Winsock reports them in exceptfds. */ + unsigned ready = 0; + while (!error) { + struct timespec remaining; + if (timeout) { + struct timespec now; + if (clock_gettime(CLOCK_MONOTONIC, &now)) abort(); + int64_t nanos = deadline - ((int64_t)now.tv_sec * 1000000000 + now.tv_nsec); + if (nanos < 0) nanos = 0; + remaining = (struct timespec){nanos / 1000000000, nanos % 1000000000}; + } + int result = ppoll(polls, total, timeout ? &remaining : NULL, NULL); + if (result < 0) { error = socket_error(errno); break; } + if (!result) break; + unsigned index = 0; + for (unsigned set = 0; set < 3; ++set) { + for (unsigned i = 0; i < counts[set]; ++i, ++index) { + int events = polls[index].revents; + if (!events) continue; + int failed_connect = 0; + if (entries[index].connecting) { + struct sockaddr_in peer; + socklen_t length = sizeof(peer); + failed_connect = getpeername(entries[index].descriptor, (struct sockaddr *)&peer, &length) != 0; + if (!failed_connect) { + entries[index].connecting = 0; + if (pthread_mutex_lock(&socket_mutex)) abort(); + for (struct guest_socket *socket = sockets; socket; socket = socket->next) + if (socket->handle == entries[index].handle) { socket->connecting = 0; break; } + if (pthread_mutex_unlock(&socket_mutex)) abort(); + } + } + entries[index].ready = failed_connect ? set == 2 : + set == 0 ? (events & (POLLIN | POLLHUP | POLLERR)) != 0 : + set == 1 ? (events & POLLOUT) != 0 : (events & POLLPRI) != 0; + ready += entries[index].ready; + /* Ignore an unrequested failed connection until another event/timeout. */ + if (!entries[index].ready && (failed_connect || (events & (POLLHUP | POLLERR)))) polls[index].fd = -1; + } + } + if (ready) break; + } + if (!error) { + unsigned index = 0; + for (unsigned set = 0; set < 3; ++set) { + unsigned count = 0; + for (unsigned i = 0; i < counts[set]; ++i, ++index) + if (entries[index].ready) MEM32(sets[set] + 4 + count++ * 4) = entries[index].handle; + if (sets[set]) MEM32(sets[set]) = count; + } + g_eax = ready; + } + for (unsigned i = 0; i < acquired; ++i) + if (close(entries[i].descriptor)) abort(); + free(entries); + free(polls); + MEM32(g_fs_base + 0x34) = error; +} + static void network_short(void) { g_eax = htons((uint16_t)MEM32(g_esp + 4)); @@ -26,8 +375,19 @@ static void address_string(void) g_esp += 8; } +static void socket_in_set(void) +{ + uint32_t handle = MEM32(g_esp + 4), set = MEM32(g_esp + 8); + g_eax = 0; + for (uint32_t i = 0; i < MEM32(set); ++i) { + if (MEM32(set + 4 + i * 4) == handle) { g_eax = 1; break; } + } + g_esp += 12; +} + static void wsa_startup(void) { + if (pthread_mutex_lock(&socket_mutex)) abort(); uint16_t requested = MEM32(g_esp + 4); uint32_t data = MEM32(g_esp + 8); uint16_t version = 0x0202; @@ -50,17 +410,28 @@ static void wsa_startup(void) } } g_esp += 12; + if (pthread_mutex_unlock(&socket_mutex)) abort(); } static void wsa_cleanup(void) { + if (pthread_mutex_lock(&socket_mutex)) abort(); g_eax = UINT32_MAX; if (startup_count) { --startup_count; + if (!startup_count) { + while (sockets) { + struct guest_socket *socket = sockets; + sockets = socket->next; + if (close(socket->descriptor)) abort(); + free(socket); + } + } MEM32(g_fs_base + 0x34) = 0; g_eax = 0; } else MEM32(g_fs_base + 0x34) = 10093; /* WSANOTINITIALISED */ g_esp += 4; + if (pthread_mutex_unlock(&socket_mutex)) abort(); } static void wsa_get_last_error(void) @@ -77,6 +448,7 @@ static void wsa_set_last_error(void) static void host_name(void) { + if (pthread_mutex_lock(&socket_mutex)) abort(); uint32_t output = MEM32(g_esp + 4); int32_t size = MEM32(g_esp + 8); char name[256]; @@ -90,6 +462,7 @@ static void host_name(void) MEM32(g_fs_base + 0x34) = error; g_eax = error ? UINT32_MAX : 0; g_esp += 12; + if (pthread_mutex_unlock(&socket_mutex)) abort(); } recomp_func_t linux_network_lookup(const char *name, uint32_t ordinal) @@ -101,6 +474,13 @@ recomp_func_t linux_network_lookup(const char *name, uint32_t ordinal) {"htonl", 8, network_long}, {"htons", 9, network_short}, {"ntohl", 14, network_long}, {"ntohs", 15, network_short}, {"inet_ntoa", 12, address_string}, + {"socket", 23, create_socket}, {"closesocket", 3, close_socket}, + {"ioctlsocket", 10, control_socket}, + {"connect", 4, connect_socket}, + {"__WSAFDIsSet", 151, socket_in_set}, + {"select", 18, select_sockets}, + {"send", 19, send_socket}, {"recv", 16, receive_socket}, + {"shutdown", 22, shutdown_socket}, }; for (unsigned i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i) if (name ? !strcmp(name, functions[i].name) : ordinal == functions[i].ordinal) diff --git a/decompiled/runtime/linux_sync.c b/decompiled/runtime/linux_sync.c @@ -392,11 +392,7 @@ 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_esp += 20; g_eax = UINT32_MAX; if (!count || count > 64) { MEM32(g_fs_base + 0x34) = 87; return; } struct semaphore_handle *objects[64]; @@ -463,6 +459,16 @@ 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); } +static void wait_for_multiple_objects_ex(void) +{ + if (MEM32(g_esp + 20)) { + fprintf(stderr, "Alertable multiple-object waits are not implemented\n"); + abort(); + } + wait_for_multiple_objects(); + g_esp += 4; +} + recomp_func_t linux_sync_lookup(const char *name) { static const struct { const char *name; recomp_func_t function; } functions[] = { @@ -471,7 +477,8 @@ recomp_func_t linux_sync_lookup(const char *name) {"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}, + {"WaitForMultipleObjects", wait_for_multiple_objects}, + {"WaitForMultipleObjectsEx", wait_for_multiple_objects_ex}, }; 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/tests/mutex.c b/decompiled/tests/mutex.c @@ -56,6 +56,8 @@ static uint32_t wait_object(uint32_t object, uint32_t timeout) 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 int extended_wait; + static uint32_t wait_many(unsigned count, uint32_t *objects, int all, uint32_t timeout) { #ifdef _WIN32 @@ -65,7 +67,7 @@ static uint32_t wait_many(unsigned count, uint32_t *objects, int all, uint32_t t 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); + return call(extended_wait ? "WaitForMultipleObjectsEx" : "WaitForMultipleObjects", extended_wait ? 5 : 4, args); } struct work { uint32_t mutex, ready, mode, index; }; @@ -315,15 +317,17 @@ int main(void) 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(); + for (extended_wait = 0; extended_wait < 2; ++extended_wait) { + 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"); + puts("multiple waits: ordinary/Ex APIs, all/any signals, atomic consumption, ownership rollback, abandonment, wakeup and errors passed"); } diff --git a/decompiled/tests/network_startup.c b/decompiled/tests/network_startup.c @@ -9,6 +9,9 @@ #include "guest_memory.h" #include <sys/utsname.h> #include <pthread.h> +#include <arpa/inet.h> +#include <unistd.h> +#include <time.h> static uint32_t call(uint32_t ordinal, unsigned count, const uint32_t *arguments) { @@ -134,6 +137,323 @@ static void hostname_queries(int initialized) } } +static uint32_t socket_create(int type) +{ +#ifdef _WIN32 + return socket(AF_INET, type, 0); +#else + uint32_t arguments[] = {2, type, 0}; + return call(23, 3, arguments); +#endif +} + +static void socket_set_membership(void) +{ + const uint32_t handles[] = {0, 17, 23, UINT32_MAX}; + const unsigned counts[] = {0, 1, 2, 64}; + for (unsigned c = 0; c < 4; ++c) { + for (unsigned h = 0; h < 4; ++h) { +#ifdef _WIN32 + fd_set set; + set.fd_count = counts[c]; + for (unsigned i = 0; i < counts[c]; ++i) set.fd_array[i] = i ? 23 : 17; +#else + MEM32(0x50000600) = counts[c]; + for (unsigned i = 0; i < counts[c]; ++i) MEM32(0x50000604 + i * 4) = i ? 23 : 17; + uint32_t arguments[] = {handles[h], 0x50000600}; +#endif + set_error(777); + +#ifdef _WIN32 + int result = __WSAFDIsSet(handles[h], &set); +#else + int result = call(151, 2, arguments); +#endif + + assert(result == ((counts[c] && h == 1) || (counts[c] > 1 && h == 2))); + assert(get_error() == 777); + } + } +} + +static int socket_close(uint32_t handle) +{ +#ifdef _WIN32 + return closesocket(handle); +#else + return call(3, 1, &handle); +#endif +} + +static int socket_shutdown(uint32_t handle, uint32_t how) +{ +#ifdef _WIN32 + return shutdown(handle, how); +#else + uint32_t arguments[] = {handle, how}; + return call(22, 2, arguments); +#endif +} + +static int socket_control(uint32_t handle, uint32_t command, uint32_t *value) +{ +#ifdef _WIN32 + return ioctlsocket(handle, command, (u_long *)value); +#else + MEM32(0x50000400) = 0x12345678; + MEM32(0x50000404) = value ? *value : 0; + MEM32(0x50000408) = 0x87654321; + uint32_t arguments[] = {handle, command, value ? 0x50000404 : 0}; + int result = call(10, 3, arguments); + if (value) *value = MEM32(0x50000404); + assert(MEM32(0x50000400) == 0x12345678 && MEM32(0x50000408) == 0x87654321); + return result; +#endif +} + +static int socket_connect(uint32_t handle, const struct sockaddr_in *address, int length) +{ +#ifdef _WIN32 + return connect(handle, (const struct sockaddr *)address, length); +#else + if (address) memcpy((void *)ADDR(0x50000500), address, 16); + uint32_t arguments[] = {handle, address ? 0x50000500 : 0, length}; + return call(4, 3, arguments); +#endif +} + +struct socket_set { uint32_t count, handles[4]; }; + +static int socket_transfer(int sending, uint32_t handle, unsigned char *bytes, int length, int flags) +{ +#ifdef _WIN32 + return sending ? send(handle, (const char *)bytes, length, flags) : recv(handle, (char *)bytes, length, flags); +#else + MEM32(0x50000a00) = 0x12345678; + MEM32(0x50000a14) = 0x87654321; + if (bytes) memcpy((void *)ADDR(0x50000a04), bytes, 16); + uint32_t arguments[] = {handle, bytes ? 0x50000a04 : 0, length, flags}; + int result = call(sending ? 19 : 16, 4, arguments); + if (bytes) memcpy(bytes, (void *)ADDR(0x50000a04), 16); + assert(MEM32(0x50000a00) == 0x12345678 && MEM32(0x50000a14) == 0x87654321); + return result; +#endif +} + +static double monotonic_seconds(void) +{ +#ifdef _WIN32 + LARGE_INTEGER counter, frequency; + assert(QueryPerformanceCounter(&counter) && QueryPerformanceFrequency(&frequency)); + return (double)counter.QuadPart / frequency.QuadPart; +#else + struct timespec now; + assert(!clock_gettime(CLOCK_MONOTONIC, &now)); + return now.tv_sec + now.tv_nsec / 1000000000.0; +#endif +} + +static int socket_select(struct socket_set *read, struct socket_set *write, + struct socket_set *except, const int32_t *timeout) +{ + struct socket_set *sets[] = {read, write, except}; +#ifdef _WIN32 + fd_set native[3]; + for (unsigned i = 0; i < 3; ++i) + if (sets[i]) memcpy(&native[i], sets[i], sizeof(*sets[i])); + int result = select(-1, read ? &native[0] : NULL, write ? &native[1] : NULL, + except ? &native[2] : NULL, (const struct timeval *)timeout); + for (unsigned i = 0; i < 3; ++i) + if (sets[i]) memcpy(sets[i], &native[i], sizeof(*sets[i])); +#else + uint32_t arguments[] = {UINT32_MAX, 0, 0, 0, timeout ? 0x50000900 : 0}; + for (unsigned i = 0; i < 3; ++i) { + if (!sets[i]) continue; + arguments[i + 1] = 0x50000804 + i * 32; + MEM32(arguments[i + 1] - 4) = 0x12345678; + MEM32(arguments[i + 1] + 20) = 0x87654321; + memcpy((void *)ADDR(arguments[i + 1]), sets[i], 20); + } + if (timeout) memcpy((void *)ADDR(0x50000900), timeout, 8); + int result = call(18, 5, arguments); + for (unsigned i = 0; i < 3; ++i) { + if (!sets[i]) continue; + memcpy(sets[i], (void *)ADDR(arguments[i + 1]), 20); + assert(MEM32(arguments[i + 1] - 4) == 0x12345678); + assert(MEM32(arguments[i + 1] + 20) == 0x87654321); + } + if (timeout) assert(!memcmp((void *)ADDR(0x50000900), timeout, 8)); +#endif + return result; +} + +static void loopback_connect(int nonblocking, int listening) +{ + uint32_t listener = socket(AF_INET, SOCK_STREAM, 0); + assert(listener != UINT32_MAX); + struct sockaddr_in address = {0}; + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(0x7f000001); + assert(!bind(listener, (const struct sockaddr *)&address, sizeof(address))); +#ifdef _WIN32 + int length = sizeof(address); +#else + socklen_t length = sizeof(address); +#endif + assert(!getsockname(listener, (struct sockaddr *)&address, &length)); + if (listening) assert(!listen(listener, 1)); + uint32_t handle = socket_create(1), mode = nonblocking; + assert(handle != UINT32_MAX); + assert(socket_control(handle, 0x8004667e, &mode) == 0); + set_error(777); + + int result = socket_connect(handle, &address, sizeof(address)); + uint32_t error = get_error(); + + if (nonblocking) assert(result == -1 && error == 10035); + else if (listening) assert(result == 0 && error == 0); + else assert(result == -1 && error == 10061); + if (nonblocking) { + struct socket_set write = {1, {handle}}, except = {1, {handle}}; + int32_t timeout[] = {10, 0}; + int selected = socket_select(NULL, &write, &except, timeout); + assert(selected == 1); + assert(write.count == (unsigned)listening && except.count == (unsigned)!listening); + assert((listening ? write.handles[0] : except.handles[0]) == handle); + assert(get_error() == 0 && timeout[0] == 10 && timeout[1] == 0); + if (!listening) { + write.count = 1; + timeout[0] = 0; + timeout[1] = 20000; + double start = monotonic_seconds(); + assert(socket_select(NULL, &write, NULL, timeout) == 0); + assert(monotonic_seconds() - start >= 0.015 && write.count == 0); + } + } + if (listening) { + struct sockaddr_in peer; + length = sizeof(peer); + uint32_t accepted = accept(listener, (struct sockaddr *)&peer, &length); + assert(accepted != UINT32_MAX && peer.sin_addr.s_addr == htonl(0x7f000001)); + struct socket_set read = {1, {handle}}, write = {1, {handle}}, except = {1, {handle}}; + int32_t timeout[] = {0, 10000}; + double start = monotonic_seconds(); + assert(socket_select(&read, NULL, NULL, timeout) == 0 && read.count == 0); + assert(monotonic_seconds() - start >= 0.005); + assert(timeout[0] == 0 && timeout[1] == 10000 && get_error() == 0); + assert(send(accepted, "abc", 3, 0) == 3); + read.count = 1; + assert(socket_select(&read, NULL, NULL, NULL) == 1 && read.count == 1); + timeout[1] = 0; + assert(socket_select(&read, &write, &except, timeout) == 2); + assert(read.count == 1 && write.count == 1 && except.count == 0); + assert(read.handles[0] == handle && write.handles[0] == handle); + uint32_t unread = 0; + assert(!socket_control(handle, 0x4004667f, &unread) && unread == 3); + + unsigned char bytes[16]; + memset(bytes, 0xa5, sizeof(bytes)); + for (int sending = 0; sending < 2; ++sending) { + assert(socket_transfer(sending, handle, bytes, -1, 0) == -1 && get_error() == 10014); + } + assert(socket_transfer(1, handle, NULL, 1, 0) == -1 && get_error() == 10014); + + assert(socket_transfer(0, handle, bytes, 2, 2) == 2); + + assert(!memcmp(bytes, "ab", 2) && get_error() == 0); + for (unsigned i = 2; i < sizeof(bytes); ++i) assert(bytes[i] == 0xa5); + assert(!socket_control(handle, 0x4004667f, &unread) && unread == 3); + assert(socket_transfer(0, handle, bytes, 1, 0) == 1 && bytes[0] == 'a'); + assert(socket_transfer(0, handle, bytes, 16, 0) == 2 && !memcmp(bytes, "bc", 2)); + mode = 1; + assert(!socket_control(handle, 0x8004667e, &mode)); + assert(socket_transfer(0, handle, bytes, 1, 0) == -1 && get_error() == 10035); + assert(!memcmp(bytes, "bc", 2)); + const unsigned char response[] = {0, 1, 0xfe, 0xff}; + memcpy(bytes, response, sizeof(response)); + assert(socket_transfer(1, handle, bytes, 4, 0) == 4 && get_error() == 0); + assert(!memcmp(bytes, response, 4)); + memset(bytes, 0, sizeof(bytes)); + assert(recv(accepted, (char *)bytes, 4, MSG_WAITALL) == 4 && !memcmp(bytes, response, 4)); + assert(socket_shutdown(handle, 3) == -1 && get_error() == 10022); + assert(socket_shutdown(handle, 1) == 0 && get_error() == 0); + assert(recv(accepted, (char *)bytes, 1, 0) == 0); + assert(socket_transfer(1, handle, bytes, 1, 0) == -1 && get_error() == 10058); + assert(!shutdown(accepted, 1)); /* SD_SEND and SHUT_WR are both 1. */ + read.count = 1; + assert(socket_select(&read, NULL, NULL, NULL) == 1); + assert(socket_transfer(0, handle, bytes, 16, 0) == 0 && get_error() == 0); + assert(socket_shutdown(handle, nonblocking ? 2 : 0) == 0 && get_error() == 0); + assert(socket_transfer(0, handle, bytes, 1, 0) == -1 && get_error() == 10058); +#ifdef _WIN32 + assert(!closesocket(accepted)); +#else + assert(!close(accepted)); +#endif + } + assert(!socket_close(handle)); +#ifdef _WIN32 + assert(!closesocket(listener)); +#else + assert(!close(listener)); +#endif +} + +static void socket_lifetime(int initialized) +{ + uint32_t value = 1; + set_error(777); + + int result = socket_control(UINT32_MAX, 0x8004667e, &value); + + assert(result == -1 && get_error() == (initialized ? 10038 : 10093)); + assert(value == 1); + assert(socket_close(UINT32_MAX) == -1); + assert(get_error() == (initialized ? 10038 : 10093)); + assert(socket_connect(UINT32_MAX, NULL, 0) == -1); + assert(get_error() == (initialized ? 10038 : 10093)); + assert(socket_shutdown(UINT32_MAX, 1) == -1); + assert(get_error() == (initialized ? 10038 : 10093)); + struct socket_set read = {1, {UINT32_MAX}}; + int32_t timeout[] = {0, 0}; + assert(socket_select(&read, NULL, NULL, timeout) == -1); + assert(get_error() == (initialized ? 10038 : 10093)); + assert(read.count == 1 && read.handles[0] == UINT32_MAX); + read.count = 0; + assert(socket_select(&read, NULL, NULL, timeout) == -1); + assert(get_error() == (initialized ? 10022 : 10093)); + for (int type = 1; type <= 2; ++type) { + set_error(777); + + uint32_t handle = socket_create(type); + + if (!initialized) { + assert(handle == UINT32_MAX && get_error() == 10093); + continue; + } + assert(handle != UINT32_MAX && get_error() == 0); + assert(socket_connect(handle, NULL, 16) == -1 && get_error() == 10014); + struct sockaddr_in address = {0}; + assert(socket_connect(handle, &address, 15) == -1 && get_error() == 10014); + assert(socket_connect(handle, &address, 16) == -1 && get_error() == 10047); + const uint32_t modes[] = {1, 0xffffffff, 0, 1}; + for (unsigned i = 0; i < 4; ++i) { + value = modes[i]; + set_error(777); + assert(socket_control(handle, 0x8004667e, &value) == 0); + assert(value == modes[i] && get_error() == 0); + } + value = 0xa5a5a5a5; + assert(socket_control(handle, 0x4004667f, &value) == 0); + assert(value == 0 && get_error() == 0); + assert(socket_control(handle, 0x8004667e, NULL) == -1); + assert(get_error() == 10014); + assert(socket_close(handle) == 0 && get_error() == 0); + assert(socket_close(handle) == -1 && get_error() == 10038); + assert(socket_control(handle, 0x4004667f, &value) == -1 && get_error() == 10038); + } +} + static const char *format_address(uint32_t address) { #ifdef _WIN32 @@ -241,6 +561,8 @@ int main(void) #endif byte_order(); address_strings(); + socket_lifetime(0); + socket_set_membership(); hostname_queries(0); cleanup(-1); const struct { uint16_t version; uint32_t error; } versions[] = { @@ -253,9 +575,18 @@ int main(void) hostname_queries(1); byte_order(); address_strings(); + socket_lifetime(1); + socket_set_membership(); + loopback_connect(0, 1); + loopback_connect(1, 1); + loopback_connect(0, 0); + loopback_connect(1, 0); + uint32_t orphan = socket_create(1); + assert(orphan != UINT32_MAX); for (unsigned i = 0; i < initialized; ++i) cleanup(0); cleanup(-1); assert(startup(2, 0) == 0); + assert(socket_close(orphan) == -1 && get_error() == 10038); cleanup(0); cleanup(-1); assert(digest == 0xd6dc7661); @@ -264,5 +595,11 @@ int main(void) puts("hostname: 24 buffer and initialization cases, native host name and guest ABI passed"); puts("byte order: all 16-bit values and six 32-bit cases, before/after startup, errors preserved"); puts("inet_ntoa: five addresses, buffer reuse, per-thread storage and cleared errors before/after startup"); + puts("sockets: TCP/UDP creation, nonblocking control, unread count, close, cleanup, invalid handles and guest ABI passed"); + puts("connect: blocking/nonblocking loopback, refused connection, invalid addresses and guest ABI passed"); + puts("fd_set: empty/single/multiple/full membership, duplicate entries and preserved errors before/after startup passed"); + puts("select: pending connect success/failure, read/write readiness, timeout, infinite wait, invalid sets and unread bytes passed"); + puts("transport: binary send/recv, peek, partial reads, would-block, graceful close, invalid lengths and canaries passed"); + puts("shutdown: send/receive half-close, peer EOF, disabled directions, invalid handles/modes and guest ABI passed"); return 0; } diff --git a/tools/reconstruction/test_portable_network_startup.py b/tools/reconstruction/test_portable_network_startup.py @@ -1,4 +1,4 @@ -"""Compare Winsock startup, cleanup and error state with the native Linux adapters.""" +"""Compare Winsock initialization, address conversion and socket lifetime with Linux.""" import pathlib import subprocess @@ -19,7 +19,7 @@ wsl = ["wsl", "-d", "Ubuntu-26.04", "--cd", linux_path, "--exec"] subprocess.run(wsl + [ "gcc", "-O2", "-DRECOMP_PORTABLE", "-Iruntime", "-fno-strict-aliasing", "tests/network_startup.c", "runtime/linux_network.c", "runtime/guest_memory.c", - "runtime/recomp_state.c", "-lm", "-o", linux_output, + "runtime/recomp_state.c", "-pthread", "-lm", "-o", linux_output, ], check=True) actual = subprocess.check_output(wsl + [linux_output], text=True, timeout=30) assert actual == expected, (expected, actual)