commit a9eecc58f9847224f4f668f9a4e2aa815c005fb1
parent 6e25001c5c8ddbf479744880d54b335caf46618c
Author: anon <anon@example.com>
Date: Thu, 15 Oct 2026 00:12:01 +0000
Implement guest CRT output streams for native Linux startup
Diffstat:
11 files changed, 753 insertions(+), 24 deletions(-)
diff --git a/decompiled/Makefile.linux b/decompiled/Makefile.linux
@@ -3,7 +3,7 @@ CPPFLAGS := -Iruntime -Isrc -Idata -DRECOMP_PORTABLE
CFLAGS := -O2 -fno-strict-aliasing
GAME_SOURCES := $(wildcard src/*/*.c) src/dispatch.c
DATA_SOURCES := $(wildcard data/*.c)
-RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_platform.c runtime/linux_sync.c runtime/linux_tls.c runtime/linux_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c
+RUNTIME_SOURCES := runtime/linux_host.c runtime/linux_platform.c runtime/linux_sync.c runtime/linux_tls.c runtime/linux_network.c runtime/guest_memory.c runtime/guest_heap.c runtime/guest_crt.c runtime/guest_stdio.c runtime/guest_format.c runtime/guest_msvcp.c runtime/recomp_state.c runtime/eh32.c
VENDOR_SOURCES := $(wildcard vendor/msvcp60/source/*.c) $(wildcard vendor/ace/source/*.c)
OBJECTS := $(patsubst %.c,build/linux/%.o,$(GAME_SOURCES) $(DATA_SOURCES) $(RUNTIME_SOURCES) $(VENDOR_SOURCES))
@@ -92,7 +92,11 @@ build/linux/delete-file: tests/delete_file.c runtime/linux_platform.c runtime/gu
mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lm -o $@
-test: build/linux/linecrypt build/linux/guest-heap build/linux/guest-crt build/linux/linux-platform build/linux/msvcp-strings build/linux/ace-token build/linux/msvcp-stdio-data build/linux/guest-eh build/linux/guest-rand build/linux/semaphore build/linux/guest-scanf build/linux/network-startup build/linux/os-version build/linux/guest-format build/linux/event build/linux/tls build/linux/module-filename build/linux/delete-file
+build/linux/guest-stdio: tests/guest_stdio.c runtime/guest_stdio.c runtime/guest_crt.c runtime/guest_format.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_stdio.h runtime/guest_crt.h runtime/guest_format.h runtime/guest_heap.h runtime/guest_memory.h
+ mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -lm -o $@
+
+test: build/linux/linecrypt build/linux/guest-heap build/linux/guest-crt build/linux/linux-platform build/linux/msvcp-strings build/linux/ace-token build/linux/msvcp-stdio-data build/linux/guest-eh build/linux/guest-rand build/linux/semaphore build/linux/guest-scanf build/linux/network-startup build/linux/os-version build/linux/guest-format build/linux/event build/linux/tls build/linux/module-filename build/linux/delete-file build/linux/guest-stdio
./build/linux/linecrypt
./build/linux/guest-heap
./build/linux/guest-crt
@@ -111,5 +115,6 @@ test: build/linux/linecrypt build/linux/guest-heap build/linux/guest-crt build/l
./build/linux/tls
./build/linux/module-filename
./build/linux/delete-file
+ ./build/linux/guest-stdio
-include $(OBJECTS:.o=.d)
diff --git a/decompiled/runtime/guest_crt.c b/decompiled/runtime/guest_crt.c
@@ -10,7 +10,7 @@ static size_t exit_callback_count;
static int error_mode;
static uint32_t abort_handler;
-static uint32_t errno_address(void)
+uint32_t guest_crt_errno_address(void)
{
/* Private CRT storage inside the host-owned 64 KiB guest thread block. */
return g_fs_base + 0x2000;
@@ -18,7 +18,7 @@ static uint32_t errno_address(void)
static void crt_errno(void)
{
- g_eax = errno_address();
+ g_eax = guest_crt_errno_address();
g_esp += 4;
}
@@ -28,7 +28,7 @@ static void crt_set_error_mode(void)
g_eax = error_mode;
if (mode >= 0 && mode <= 2) error_mode = mode;
else if (mode != 3) {
- MEM32(errno_address()) = 22; /* MSVCRT EINVAL */
+ MEM32(guest_crt_errno_address()) = 22; /* MSVCRT EINVAL */
g_eax = UINT32_MAX;
}
g_esp += 4;
diff --git a/decompiled/runtime/guest_crt.h b/decompiled/runtime/guest_crt.h
@@ -3,5 +3,6 @@
#include "recomp_types.h"
recomp_func_t guest_crt_lookup(const char *name);
uint32_t guest_crt_data(const char *name);
+uint32_t guest_crt_errno_address(void);
void guest_crt_startup(int argc, char **argv, char **environment);
#endif
diff --git a/decompiled/runtime/guest_format.c b/decompiled/runtime/guest_format.c
@@ -3,19 +3,18 @@
#include <stdarg.h>
struct output_buffer {
- uint32_t address, capacity;
+ char *bytes;
size_t length;
};
static void append(struct output_buffer *output, const char *bytes, size_t length)
{
- if (output->length < output->capacity) {
- size_t count = output->capacity - output->length;
- if (count > length) count = length;
- memcpy((void *)ADDR(output->address + (uint32_t)output->length), bytes, count);
- }
+ if (length > INT_MAX - output->length) abort();
+ char *grown = realloc(output->bytes, output->length + length + 1);
+ if (!grown) abort();
+ output->bytes = grown;
+ memcpy(output->bytes + output->length, bytes, length);
output->length += length;
- if (output->length > INT_MAX) abort();
}
/* Host varargs contain real typed values, never the guest's 32-bit va_list. */
@@ -138,18 +137,31 @@ static void format_output(struct output_buffer *output, const char *format, uint
free(native);
}
+char *guest_format_string(uint32_t format, uint32_t arguments, uint32_t *length)
+{
+ struct output_buffer output = {malloc(1), 0};
+ if (!output.bytes) abort();
+ format_output(&output, (const char *)ADDR(format), arguments);
+ output.bytes[output.length] = 0;
+ *length = output.length;
+ return output.bytes;
+}
+
static void buffer_format(int bounded, int list)
{
uint32_t destination = MEM32(g_esp + 4);
uint32_t capacity = bounded ? MEM32(g_esp + 8) : UINT32_MAX;
uint32_t format_slot = g_esp + (bounded ? 12 : 8);
uint32_t arguments = list ? MEM32(format_slot + 4) : format_slot + 4;
- struct output_buffer output = {destination, capacity, 0};
- format_output(&output, (const char *)ADDR(MEM32(format_slot)), arguments);
+ uint32_t length;
+ char *output = guest_format_string(MEM32(format_slot), arguments, &length);
+ uint32_t copied = length < capacity ? length : capacity;
+ if (copied) memcpy((void *)ADDR(destination), output, copied);
+ free(output);
/* Legacy _snprintf writes no terminator when the result fills the buffer. */
- if (output.length < capacity) MEM8(destination + (uint32_t)output.length) = 0;
- g_eax = destination && output.length > capacity ? UINT32_MAX : (uint32_t)output.length;
+ if (length < capacity) MEM8(destination + length) = 0;
+ g_eax = destination && length > capacity ? UINT32_MAX : length;
g_esp += 4;
}
diff --git a/decompiled/runtime/guest_format.h b/decompiled/runtime/guest_format.h
@@ -2,4 +2,6 @@
#define GUEST_FORMAT_H
#include "recomp_types.h"
recomp_func_t guest_format_lookup(const char *name);
+/* Returns malloc-owned host bytes, including embedded NULs in the reported length. */
+char *guest_format_string(uint32_t format, uint32_t arguments, uint32_t *length);
#endif
diff --git a/decompiled/runtime/guest_stdio.c b/decompiled/runtime/guest_stdio.c
@@ -0,0 +1,329 @@
+#define _GNU_SOURCE
+#include "guest_stdio.h"
+#include "guest_crt.h"
+#include "guest_heap.h"
+#include "guest_format.h"
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+/* FILE pointers and buffers are guest addresses. Native descriptors stay here. */
+struct stream { uint32_t file; int descriptor, text; };
+static struct stream streams[512];
+static unsigned stream_count;
+
+static int file_error(int error)
+{
+ if (error == ENOTDIR) error = ENOENT;
+ if (error == EISDIR || error == EROFS) error = EACCES;
+ if (error == ENAMETOOLONG) error = 38; /* MSVCRT ENAMETOOLONG */
+ MEM32(guest_crt_errno_address()) = error;
+ return -1;
+}
+
+static void initialize_streams(void)
+{
+ if (stream_count) return;
+ uint32_t iob = guest_crt_data("_iob");
+ for (unsigned i = 0; i < 20; ++i) {
+ streams[i].file = iob + i * 32;
+ streams[i].descriptor = i < 3 ? fcntl(i, F_DUPFD_CLOEXEC, 3) : -1;
+ streams[i].text = 1;
+ if (i < 3 && streams[i].descriptor < 0) { perror("standard stream duplication"); abort(); }
+ }
+ stream_count = 20;
+}
+
+static struct stream *find_stream(uint32_t file)
+{
+ initialize_streams();
+ for (unsigned i = 0; i < stream_count; ++i)
+ if (streams[i].file == file) return &streams[i];
+ fprintf(stderr, "Unknown guest FILE address %08x\n", file);
+ abort();
+}
+
+static int write_bytes(struct stream *stream, const char *data, size_t size)
+{
+ while (size) {
+ ssize_t written = write(stream->descriptor, data, size);
+ if (written < 0 && errno == EINTR) continue;
+ if (written <= 0) {
+ MEM32(stream->file + 12) |= 0x20; /* _IOERR */
+ return file_error(written < 0 ? errno : ENOSPC);
+ }
+ data += written;
+ size -= written;
+ }
+ return 0;
+}
+
+static int write_text(struct stream *stream, const char *data, size_t size)
+{
+ if (!stream->text) return write_bytes(stream, data, size);
+ const char *end = data + size;
+ while (data < end) {
+ const char *newline = memchr(data, '\n', end - data);
+ const char *stop = newline ? newline : end;
+ if (write_bytes(stream, data, stop - data)) return -1;
+ if (newline && write_bytes(stream, "\r\n", 2)) return -1;
+ data = newline ? newline + 1 : end;
+ }
+ return 0;
+}
+
+static int flush_stream(struct stream *stream)
+{
+ uint32_t file = stream->file, flags = MEM32(file + 12);
+ if (stream->descriptor < 0) return file_error(EBADF);
+ if (!(flags & 2)) {
+ if (MEM32(file + 4)) {
+ fprintf(stderr, "Flushing buffered guest input is not implemented\n");
+ abort();
+ }
+ return 0;
+ }
+ uint32_t base = MEM32(file + 8), pointer = MEM32(file);
+ int result = 0;
+ if (base && pointer != base && !(flags & 4)) {
+ if (pointer < base || pointer - base > MEM32(file + 24)) abort();
+ result = write_text(stream, (const char *)ADDR(base), pointer - base);
+ }
+ MEM32(file) = base;
+ MEM32(file + 4) = 0;
+ if (flags & 0x80) MEM32(file + 12) &= ~2u;
+ return result;
+}
+
+static int flush_all(void)
+{
+ int result = 0;
+ for (unsigned i = 0; i < stream_count; ++i)
+ if (streams[i].descriptor >= 0 && (MEM32(streams[i].file + 12) & 2))
+ if (flush_stream(&streams[i])) result = -1;
+ return result;
+}
+
+static int close_stream(struct stream *stream)
+{
+ if (stream->descriptor < 0) return file_error(EBADF);
+ int result = flush_stream(stream);
+ if (close(stream->descriptor)) result = file_error(errno);
+ uint32_t file = stream->file;
+ if (MEM32(file + 12) & 8) guest_free(MEM32(file + 8));
+ MEM32(file) = MEM32(file + 4) = MEM32(file + 8) = MEM32(file + 12) = 0;
+ stream->descriptor = -1;
+ return result;
+}
+
+static uint32_t open_stream(struct stream *stream, const char *name, const char *mode)
+{
+ int options, flags, text = MEM32(guest_crt_data("_fmode")) != 0x8000;
+ if (*mode == 'r') { options = O_RDONLY; flags = 1; }
+ else if (*mode == 'w') { options = O_WRONLY | O_CREAT | O_TRUNC; flags = 2; }
+ else if (*mode == 'a') { options = O_WRONLY | O_CREAT | O_APPEND; flags = 2; }
+ else { file_error(EINVAL); return 0; }
+ for (const char *p = mode + 1; *p; ++p) {
+ if (*p == '+') { options = (options & ~O_ACCMODE) | O_RDWR; flags = 0x80; }
+ else if (*p == 'b') text = 0;
+ else if (*p == 't') text = 1;
+ else { fprintf(stderr, "Unsupported guest stream mode: %s\n", mode); abort(); }
+ }
+ if ((name[0] && name[1] == ':') || (name[0] == '\\' && name[1] == '\\')) {
+ fprintf(stderr, "Windows drive/UNC stream paths are not implemented: %s\n", name);
+ abort();
+ }
+ char *path = strdup(name);
+ if (!path) abort();
+ for (char *p = path; *p; ++p) if (*p == '\\') *p = '/';
+ struct stat info;
+ if (!stat(path, &info) && (S_ISDIR(info.st_mode) ||
+ ((options & O_ACCMODE) != O_RDONLY && !(info.st_mode & 0222)))) {
+ free(path);
+ file_error(EACCES);
+ return 0;
+ }
+ int descriptor = open(path, options | O_CLOEXEC, 0666);
+ int error = errno;
+ free(path);
+ if (descriptor < 0) { file_error(error); return 0; }
+
+ /* Guest descriptor numbers are independent of the host descriptor table. */
+ unsigned number;
+ for (number = 0; number < 512; ++number) {
+ unsigned i;
+ for (i = 0; i < stream_count; ++i)
+ if (streams[i].descriptor >= 0 && MEM32(streams[i].file + 16) == number) break;
+ if (i == stream_count) break;
+ }
+ stream->descriptor = descriptor;
+ stream->text = text;
+ MEM32(stream->file) = MEM32(stream->file + 4) = MEM32(stream->file + 8) = 0;
+ MEM32(stream->file + 12) = flags;
+ MEM32(stream->file + 16) = number;
+ MEM32(stream->file + 28) = 0;
+ return stream->file;
+}
+
+static void crt_fopen(void)
+{
+ initialize_streams();
+ unsigned i;
+ for (i = 0; i < stream_count; ++i) if (streams[i].descriptor < 0) break;
+ if (i == 512) { file_error(EMFILE); g_eax = 0; }
+ else {
+ if (i == stream_count) {
+ streams[i].file = guest_malloc(32);
+ if (!streams[i].file) { file_error(ENOMEM); g_eax = 0; g_esp += 4; return; }
+ memset((void *)ADDR(streams[i].file), 0, 32);
+ streams[i].descriptor = -1;
+ ++stream_count;
+ }
+ g_eax = open_stream(&streams[i], (const char *)ADDR(MEM32(g_esp + 4)),
+ (const char *)ADDR(MEM32(g_esp + 8)));
+ }
+ g_esp += 4;
+}
+
+static void crt_freopen(void)
+{
+ struct stream *stream = find_stream(MEM32(g_esp + 12));
+ if (stream->descriptor >= 0) close_stream(stream);
+ g_eax = open_stream(stream, (const char *)ADDR(MEM32(g_esp + 4)),
+ (const char *)ADDR(MEM32(g_esp + 8)));
+ g_esp += 4;
+}
+
+static int put_character(struct stream *stream, unsigned char character)
+{
+ uint32_t file = stream->file, flags = MEM32(file + 12);
+ if (stream->descriptor < 0 || !(flags & (2 | 0x80))) {
+ MEM32(file + 12) |= 0x20;
+ return file_error(EBADF);
+ }
+ if (flags & 1) {
+ fprintf(stderr, "Switching buffered input to output requires guest input support\n");
+ abort();
+ }
+ MEM32(file + 12) |= 2;
+ if (flags & 4) return write_text(stream, (const char *)&character, 1) ? -1 : character;
+ if (!MEM32(file + 8)) {
+ uint32_t buffer = guest_malloc(4096);
+ if (!buffer) return file_error(ENOMEM);
+ MEM32(file) = MEM32(file + 8) = buffer;
+ MEM32(file + 24) = 4096;
+ MEM32(file + 12) |= 8;
+ }
+ if ((int32_t)MEM32(file + 4) <= 0) {
+ if (flush_stream(stream)) return -1;
+ MEM32(file + 12) |= 2;
+ MEM32(file + 4) = MEM32(file + 24);
+ }
+ MEM8(MEM32(file)) = character;
+ ++MEM32(file);
+ --MEM32(file + 4);
+ return character;
+}
+
+static void crt_fputc(void)
+{
+ g_eax = put_character(find_stream(MEM32(g_esp + 8)), MEM32(g_esp + 4));
+ g_esp += 4;
+}
+
+static void crt_fwrite(void)
+{
+ uint32_t bytes = MEM32(g_esp + 4), size = MEM32(g_esp + 8), count = MEM32(g_esp + 12);
+ if (!size || !count) { g_eax = 0; g_esp += 4; return; }
+ uint64_t total = (uint64_t)size * count, written = 0;
+ if (total > UINT32_MAX) { file_error(EINVAL); g_eax = 0; g_esp += 4; return; }
+ struct stream *stream = find_stream(MEM32(g_esp + 16));
+ while (written < total && put_character(stream, MEM8(bytes + (uint32_t)written)) >= 0) ++written;
+ g_eax = size ? written / size : 0;
+ g_esp += 4;
+}
+
+static void crt_fputs(void)
+{
+ const unsigned char *text = (const unsigned char *)ADDR(MEM32(g_esp + 4));
+ struct stream *stream = find_stream(MEM32(g_esp + 8));
+ g_eax = 0;
+ while (*text) if (put_character(stream, *text++) < 0) { g_eax = UINT32_MAX; break; }
+ g_esp += 4;
+}
+
+static void crt_fflush(void)
+{
+ uint32_t file = MEM32(g_esp + 4);
+ g_eax = file ? flush_stream(find_stream(file)) : flush_all();
+ g_esp += 4;
+}
+
+static void crt_fclose(void)
+{
+ g_eax = close_stream(find_stream(MEM32(g_esp + 4)));
+ g_esp += 4;
+}
+
+static void crt_setvbuf(void)
+{
+ struct stream *stream = find_stream(MEM32(g_esp + 4));
+ uint32_t file = stream->file, buffer = MEM32(g_esp + 8), mode = MEM32(g_esp + 12), size = MEM32(g_esp + 16);
+ g_eax = UINT32_MAX;
+ if (mode != 0 && mode != 0x40 && mode != 4) file_error(EINVAL);
+ else if (mode != 4 && (size < 2 || size > INT_MAX)) file_error(EINVAL);
+ else if (!flush_stream(stream)) {
+ size &= ~1u; /* MSVCRT buffers use an even byte count. */
+ if (MEM32(file + 12) & 8) guest_free(MEM32(file + 8));
+ MEM32(file + 12) &= ~(8u | 0x100u | 0x400u | 4u);
+ if (mode == 4) { buffer = file + 20; size = 2; MEM32(file + 12) |= 4; }
+ else if (buffer) MEM32(file + 12) |= 0x500;
+ else {
+ buffer = guest_malloc(size);
+ if (!buffer) { fprintf(stderr, "Guest stream buffer allocation failed\n"); abort(); }
+ MEM32(file + 12) |= 0x408;
+ }
+ MEM32(file) = MEM32(file + 8) = buffer;
+ MEM32(file + 4) = 0;
+ MEM32(file + 24) = size;
+ g_eax = 0;
+ }
+ g_esp += 4;
+}
+
+static void crt_fileno(void)
+{
+ struct stream *stream = find_stream(MEM32(g_esp + 4));
+ g_eax = stream->descriptor >= 0 ? MEM32(stream->file + 16) : file_error(EBADF);
+ g_esp += 4;
+}
+
+static void print_file(int list)
+{
+ struct stream *stream = find_stream(MEM32(g_esp + 4));
+ uint32_t length;
+ char *text = guest_format_string(MEM32(g_esp + 8), list ? MEM32(g_esp + 12) : g_esp + 12, &length);
+ g_eax = length;
+ for (uint32_t i = 0; i < length; ++i)
+ if (put_character(stream, (unsigned char)text[i]) < 0) { g_eax = UINT32_MAX; break; }
+ free(text);
+ g_esp += 4;
+}
+
+static void crt_fprintf(void) { print_file(0); }
+static void crt_vfprintf(void) { print_file(1); }
+
+recomp_func_t guest_stdio_lookup(const char *name)
+{
+ static const struct { const char *name; recomp_func_t function; } functions[] = {
+ {"fopen", crt_fopen}, {"freopen", crt_freopen}, {"fclose", crt_fclose},
+ {"fflush", crt_fflush}, {"fputc", crt_fputc}, {"fwrite", crt_fwrite},
+ {"fputs", crt_fputs}, {"setvbuf", crt_setvbuf}, {"_fileno", crt_fileno},
+ {"fprintf", crt_fprintf}, {"vfprintf", crt_vfprintf},
+ };
+ for (unsigned i = 0; i < sizeof(functions) / sizeof(functions[0]); ++i)
+ if (!strcmp(name, functions[i].name)) return functions[i].function;
+ return NULL;
+}
diff --git a/decompiled/runtime/guest_stdio.h b/decompiled/runtime/guest_stdio.h
@@ -0,0 +1,5 @@
+#ifndef GUEST_STDIO_H
+#define GUEST_STDIO_H
+#include "recomp_types.h"
+recomp_func_t guest_stdio_lookup(const char *name);
+#endif
diff --git a/decompiled/runtime/linux_host.c b/decompiled/runtime/linux_host.c
@@ -3,6 +3,7 @@
#include "game-modules.h"
#include "guest_crt.h"
#include "guest_format.h"
+#include "guest_stdio.h"
#include "linux_platform.h"
#include "linux_sync.h"
#include "linux_tls.h"
@@ -185,7 +186,8 @@ recomp_func_t recomp_lookup_import(uint32_t va)
extern void native32_shim_CxxThrowException(void);
return native32_shim_CxxThrowException;
}
- recomp_func_t function = guest_crt_lookup(imports[current_import].name);
+ recomp_func_t function = guest_stdio_lookup(imports[current_import].name);
+ if (!function) function = guest_crt_lookup(imports[current_import].name);
if (!function) function = guest_format_lookup(imports[current_import].name);
if (function) return function;
}
diff --git a/decompiled/tests/guest_stdio.c b/decompiled/tests/guest_stdio.c
@@ -0,0 +1,307 @@
+#include <assert.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _WIN32
+#include <windows.h>
+static HMODULE crt;
+#else
+#include "guest_stdio.h"
+#include "guest_crt.h"
+#include "guest_memory.h"
+#include <unistd.h>
+recomp_func_t recomp_lookup(uint32_t address) { fprintf(stderr, "Unexpected stdio guest callback %08x\n", address); abort(); }
+recomp_func_t recomp_lookup_import(uint32_t address) { return recomp_lookup(address); }
+#endif
+
+static void *memory(uint32_t address)
+{
+#ifdef _WIN32
+ return (void *)(uintptr_t)address;
+#else
+ return (void *)ADDR(address);
+#endif
+}
+
+static uint32_t address(const void *bytes, unsigned size)
+{
+#ifdef _WIN32
+ return (uintptr_t)bytes;
+#else
+ static uint32_t next = 0x50004000u;
+ uint32_t result = next;
+ memcpy(memory(result), bytes, size);
+ next += (size + 3) & ~3u;
+ assert(next < 0x5000e000u);
+ return result;
+#endif
+}
+
+static uint32_t string(const char *text) { return address(text, strlen(text) + 1); }
+
+static uint32_t call(const char *name, unsigned count, const uint32_t *arguments)
+{
+#ifdef _WIN32
+ uint32_t args[4] = {0};
+ if (count) memcpy(args, arguments, count * 4);
+ uint32_t (__cdecl *function)(uint32_t, uint32_t, uint32_t, uint32_t) = (void *)GetProcAddress(crt, name);
+ assert(function);
+ return function(args[0], args[1], args[2], args[3]);
+#else
+ g_esp = 0x5000ff00u;
+ if (count) memcpy(memory(g_esp + 4), arguments, count * 4);
+ g_ebx = 0x12345678;
+ g_esi = 0x23456789;
+ g_edi = 0x3456789a;
+ g_ebp = 0x456789ab;
+ recomp_func_t function = guest_stdio_lookup(name);
+ if (!function) function = guest_crt_lookup(name);
+ assert(function);
+ function();
+ assert(g_esp == 0x5000ff04u);
+ assert(g_ebx == 0x12345678 && g_esi == 0x23456789);
+ assert(g_edi == 0x3456789a && g_ebp == 0x456789ab);
+ return g_eax;
+#endif
+}
+
+static uint32_t open_file(const char *name, const char *mode)
+{
+ uint32_t args[] = {string(name), string(mode)};
+ return call("fopen", 2, args);
+}
+
+static void check_contents(const char *path, const void *expected, unsigned size)
+{
+ unsigned char bytes[256];
+ FILE *file = fopen(path, "rb");
+ assert(file);
+ size_t count = fread(bytes, 1, sizeof(bytes), file);
+ assert(!fclose(file));
+ if (count != size || memcmp(bytes, expected, size)) {
+ printf("File %s: %u bytes, expected %u\n", path, (unsigned)count, size);
+ fflush(stdout);
+ }
+ assert(count == size && !memcmp(bytes, expected, size));
+}
+
+static void text_output_honors_direct_buffer_writes(uint32_t stderr_file)
+{
+ uint32_t reopen[] = {string("text.txt"), string("w"), stderr_file};
+ assert(call("freopen", 3, reopen) == stderr_file);
+ uint32_t *fields = memory(stderr_file);
+ assert(fields[0] == 0 && fields[1] == 0 && fields[2] == 0 && fields[3] == 2 && fields[4] == 2);
+ uint32_t put[] = {'a', stderr_file};
+
+ assert(call("fputc", 2, put) == 'a');
+ assert(fields[0] - fields[2] == 1 && fields[1] == 4095 && fields[3] == 0xa && fields[6] == 4096);
+ *(unsigned char *)memory(fields[0]++) = '\n';
+ --fields[1]; /* Same field aliases used by translated MSVCP60 streambuf. */
+ assert(call("fflush", 1, &stderr_file) == 0);
+
+ check_contents("text.txt", "a\r\n", 3);
+ assert(fields[0] == fields[2] && fields[1] == 0 && fields[3] == 0xa);
+ uint32_t write[] = {string("b\r\n"), 1, 3, stderr_file};
+ assert(call("fwrite", 4, write) == 3);
+ uint32_t puts[] = {string("tail\n"), stderr_file};
+ assert((int32_t)call("fputs", 2, puts) >= 0);
+ assert(call("fclose", 1, &stderr_file) == 0);
+ check_contents("text.txt", "a\r\nb\r\r\ntail\r\n", 13);
+ assert(fields[0] == 0 && fields[1] == 0 && fields[2] == 0 && fields[3] == 0);
+}
+
+static void binary_output_preserves_bytes_and_user_buffer(void)
+{
+ uint32_t file = open_file("binary.bin", "wb");
+ assert(file);
+ unsigned char canaries[66];
+ memset(canaries, 0xa5, sizeof(canaries));
+ uint32_t buffer = address(canaries, sizeof(canaries));
+ uint32_t setbuf[] = {file, buffer + 1, 0, 63};
+ assert(call("setvbuf", 4, setbuf) == 0);
+ uint32_t *fields = memory(file);
+ assert(fields[0] == buffer + 1 && fields[2] == buffer + 1 && fields[3] == 0x502 && fields[6] == 62);
+ const unsigned char bytes[] = {'x', 0, '\r', '\n', 0xff};
+ uint32_t write[] = {address(bytes, sizeof(bytes)), 1, sizeof(bytes), file};
+
+ for (unsigned i = 0; i < 20; ++i) assert(call("fwrite", 4, write) == sizeof(bytes));
+ uint32_t all = 0;
+ assert(call("fflush", 1, &all) == 0);
+
+ unsigned char expected[101];
+ for (unsigned i = 0; i < 20; ++i) memcpy(expected + i * 5, bytes, 5);
+ check_contents("binary.bin", expected, 100);
+ assert(*(unsigned char *)memory(buffer) == 0xa5 && *(unsigned char *)memory(buffer + 65) == 0xa5);
+ assert(*(unsigned char *)memory(buffer + 63) == 0xa5 && *(unsigned char *)memory(buffer + 64) == 0xa5);
+ assert(fields[0] == buffer + 1 && fields[1] == 0);
+ assert(call("fclose", 1, &file) == 0);
+ file = open_file("binary.bin", "ab");
+ assert(file);
+ uint32_t put[] = {'z', file};
+ assert(call("fputc", 2, put) == 'z' && call("fclose", 1, &file) == 0);
+ expected[100] = 'z';
+ check_contents("binary.bin", expected, 101);
+}
+
+static void unbuffered_output_is_visible_immediately(void)
+{
+ uint32_t file = open_file("unbuffered.txt", "w");
+ assert(file);
+ uint32_t setbuf[] = {file, 0, 4, 0};
+ assert(call("setvbuf", 4, setbuf) == 0);
+ uint32_t put[] = {'\n', file};
+
+ assert(call("fputc", 2, put) == '\n');
+
+ check_contents("unbuffered.txt", "\r\n", 2);
+ uint32_t *fields = memory(file);
+ assert(fields[0] == file + 20 && fields[2] == file + 20 && fields[1] == 0 && fields[3] == 6 && fields[6] == 2);
+ assert(call("fclose", 1, &file) == 0);
+}
+
+static void reopen_failure_closes_the_old_stream(void)
+{
+ uint32_t file = open_file("closed.txt", "wb");
+ assert(file);
+ uint32_t put[] = {'c', file};
+ assert(call("fputc", 2, put) == 'c');
+ uint32_t *error = memory(call("_errno", 0, NULL));
+ *error = 777;
+ uint32_t reopen[] = {string("missing/file.txt"), string("r"), file};
+
+ assert(call("freopen", 3, reopen) == 0);
+
+ assert(*error == 2);
+ assert(((uint32_t *)memory(file))[3] == 0);
+ check_contents("closed.txt", "c", 1);
+}
+
+static void readonly_stream_reports_write_error(void)
+{
+ uint32_t file = open_file("closed.txt", "rb");
+ assert(file);
+ uint32_t *error = memory(call("_errno", 0, NULL));
+ *error = 777;
+ uint32_t put[] = {'x', file};
+
+ uint32_t result = call("fputc", 2, put);
+ if (result != UINT32_MAX || *error != 9 || !(((uint32_t *)memory(file))[3] & 0x20)) {
+ printf("readonly put=%08x errno=%u flags=%x\n", result, *error, ((uint32_t *)memory(file))[3]);
+ fflush(stdout);
+ }
+ assert(result == UINT32_MAX);
+
+ assert(*error == 9 && (((uint32_t *)memory(file))[3] & 0x20));
+ assert(call("fclose", 1, &file) == 0);
+ check_contents("closed.txt", "c", 1);
+ uint32_t directory = open_file(".", "rb");
+ if (directory || *error != 13) { printf("directory=%08x errno=%u\n", directory, *error); fflush(stdout); }
+ assert(!directory && *error == 13);
+}
+
+static void cexit_preserves_pending_stream_state(void)
+{
+ uint32_t file = open_file("exit.txt", "wb");
+ assert(file);
+ uint32_t put[] = {'e', file};
+ assert(call("fputc", 2, put) == 'e');
+
+ call("_cexit", 0, NULL);
+
+ check_contents("exit.txt", "", 0);
+ uint32_t *fields = memory(file);
+ assert(fields[0] - fields[2] == 1);
+ assert(call("fclose", 1, &file) == 0);
+ check_contents("exit.txt", "e", 1);
+}
+
+static void formatted_output_uses_guest_arguments_and_text_stream(void)
+{
+ uint32_t file = open_file("formatted.txt", "w");
+ assert(file);
+ assert(call("_fileno", 1, &file) == ((uint32_t *)memory(file))[4]);
+ uint32_t direct[] = {file, string("id=%08x\n"), 0xabcd};
+ uint32_t values[] = {string("value"), (uint32_t)-42, 0};
+ uint32_t list[] = {file, string("[%s] %ld%c\n"), address(values, sizeof(values))};
+
+ assert(call("fprintf", 3, direct) == 12);
+ assert(call("vfprintf", 3, list) == 13);
+ assert(call("fclose", 1, &file) == 0);
+
+ const char expected[] = "id=0000abcd\r\n[value] -42\0\r\n";
+ check_contents("formatted.txt", expected, sizeof(expected) - 1);
+}
+
+static void additional_streams_have_independent_buffers_and_descriptors(void)
+{
+ uint32_t files[24];
+ for (unsigned i = 0; i < 24; ++i) {
+ files[i] = open_file("many.bin", "ab");
+ assert(files[i] && call("_fileno", 1, &files[i]) == i + 2);
+ for (unsigned j = 0; j < i; ++j) assert(files[i] != files[j]);
+ }
+
+ for (unsigned i = 0; i < 24; ++i) {
+ uint32_t put[] = {i, files[i]};
+ assert(call("fputc", 2, put) == i);
+ }
+ for (unsigned i = 24; i; --i) assert(call("fclose", 1, &files[i - 1]) == 0);
+
+ const unsigned char expected[] = {23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12,
+ 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
+ check_contents("many.bin", expected, sizeof(expected));
+}
+
+static void fwrite_returns_element_counts(void)
+{
+ uint32_t file = open_file("elements.bin", "wb");
+ assert(file);
+ uint32_t write[] = {string("abcdef"), 2, 3, file};
+
+ assert(call("fwrite", 4, write) == 3);
+ write[1] = 0;
+ assert(call("fwrite", 4, write) == 0);
+ write[1] = 2;
+ write[2] = 0;
+ assert(call("fwrite", 4, write) == 0);
+ assert(call("fclose", 1, &file) == 0);
+
+ check_contents("elements.bin", "abcdef", 6);
+}
+
+int main(void)
+{
+#ifdef _WIN32
+ crt = LoadLibraryA("msvcrt.dll");
+ assert(crt);
+ uint32_t stderr_file = (uintptr_t)GetProcAddress(crt, "_iob") + 64;
+ char temporary[MAX_PATH], directory[MAX_PATH];
+ assert(GetTempPathA(sizeof(temporary), temporary));
+ assert(GetTempFileNameA(temporary, "aos", 0, directory));
+ assert(DeleteFileA(directory) && CreateDirectoryA(directory, NULL) && SetCurrentDirectoryA(directory));
+#else
+ assert(guest_map("stdio test memory", 0x50000000u, 0x10000u));
+ g_fs_base = 0x50001000u;
+ uint32_t stderr_file = guest_crt_data("_iob") + 64;
+ char directory[] = "/tmp/ao-stdio-test-XXXXXX";
+ assert(mkdtemp(directory) && !chdir(directory));
+#endif
+ text_output_honors_direct_buffer_writes(stderr_file);
+ binary_output_preserves_bytes_and_user_buffer();
+ unbuffered_output_is_visible_immediately();
+ reopen_failure_closes_the_old_stream();
+ readonly_stream_reports_write_error();
+ formatted_output_uses_guest_arguments_and_text_stream();
+ additional_streams_have_independent_buffers_and_descriptors();
+ fwrite_returns_element_counts();
+ cexit_preserves_pending_stream_state();
+ assert(!remove("text.txt") && !remove("binary.bin") && !remove("unbuffered.txt") && !remove("closed.txt") && !remove("exit.txt") && !remove("formatted.txt") && !remove("many.bin") && !remove("elements.bin"));
+#ifdef _WIN32
+ assert(SetCurrentDirectoryA(temporary) && RemoveDirectoryA(directory));
+#else
+ assert(!chdir("/tmp") && !rmdir(directory));
+#endif
+ puts("stdio output: text/binary bytes, direct FILE writes, user buffers, flush, append and reopen failures passed");
+ return 0;
+}
diff --git a/docs/linux-crt-stdio.md b/docs/linux-crt-stdio.md
@@ -1,15 +1,15 @@
# Linux guest CRT stdio boundary
-The next stdio layer needs real 32-bit guest `_iobuf` objects and guest buffers.
+The stdio layer uses real 32-bit guest `_iobuf` objects and guest buffers.
A table containing only native `FILE *` values is insufficient: translated
MSVCP60 streambuf methods read and modify the guest buffer pointer and count
without calling a CRT adapter. Host descriptors and host pointers must remain
in host-only bookkeeping keyed by the guest FILE address.
-This document records static inspection and a small Windows initialization
-probe. It does not claim that Linux file or stream operations work. Providing
-the `_iob` data export is a useful separate step; unsupported operations should
-continue to fail explicitly until implemented.
+The output implementation in `runtime/guest_stdio.c` now supports opening,
+reopening, writing, flushing and closing local files. Input, seeking, wide stdio
+and descriptor interoperation remain unimplemented. The initial analysis and
+the implemented/verified output subset are recorded below.
## Observed ABI and initialization
@@ -181,8 +181,47 @@ expected values for small cases.
7. Translated cout/cerr flushing, tie ordering and error propagation, including
stdout redirected to a file. Successful constructors alone are insufficient.
-These are proposed tests. Only the initial Windows `_iob` snapshot was executed
-in this investigation. No Linux stdio equivalence has been established here.
+The list above includes outstanding input, seeking and translated-iostream
+checks. The output checks actually executed are described below.
+
+## Implemented output and verification
+
+`guest_stdio.c` owns native descriptors in a host-only table keyed by guest FILE
+addresses. Standard descriptors are duplicated, so redirecting the game's stderr
+does not redirect the host's diagnostic stream. The first twenty FILE records
+use `_iob`; additional records use the guest heap, up to the CRT's 512-stream
+limit. Guest descriptor numbers and native descriptor numbers are separate.
+
+Implemented calls are fopen, freopen, fclose, fflush, fputc, fwrite, fputs,
+fprintf, vfprintf, setvbuf and _fileno. Output buffers remain in guest memory;
+flush uses the current guest pointer/base, including direct translated writes.
+Text output expands LF to CRLF without dropping an existing CR. Binary output
+preserves all bytes. Append uses the native append flag. Caller-owned buffers
+are not freed; odd sizes round down to an even byte count as observed in MSVCRT.
+
+`test_portable_stdio.py` compares Windows x86 MSVCRT with the Linux adapters in
+fresh temporary directories. It checks physical file contents, representative
+FILE fields, stack/register preservation, direct FILE-buffer writes, text and
+binary output, embedded NUL/0xff, formatted guest arguments, buffer exhaustion,
+caller-buffer canaries, unbuffered visibility, fflush(NULL), append, element
+counts, failed reopen, directory/open errors and write attempts on read-only
+streams. Twenty-four simultaneous streams exercise allocation past `_iob` and
+independent buffers/descriptors. All cases pass. The shared string-format engine
+also still passes its separate 288-case Windows comparison.
+
+The tested system MSVCRT `_cexit` leaves an explicitly opened stream's pending
+bytes buffered; fclose subsequently writes them. This was also observed after
+calling __getmainargs. The fixture checks this behavior, and no extra implicit
+flush was added to the guest `_cexit` adapter. It differs from the general
+[current CRT documentation](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/cexit-c-exit),
+so complete application/DLL shutdown remains an outstanding validation step.
+
+Input and seeking APIs still fail at unresolved imports. Flushing nonempty
+input buffers and switching buffered input to output fail explicitly. Unicode
+stdio, multibyte locales, Windows drive/UNC paths, sharing/locking semantics,
+descriptor APIs and nonstandard mode suffixes are unsupported. Formatted output
+inherits the existing formatter's explicit rejection of floats, wide strings
+and percent-n. This is working file output, not complete CRT equivalence.
## REA evidence ledger
diff --git a/tools/reconstruction/test_portable_stdio.py b/tools/reconstruction/test_portable_stdio.py
@@ -0,0 +1,27 @@
+"""Compare guest FILE output and physical bytes with Windows x86 MSVCRT."""
+import pathlib
+import subprocess
+
+
+root = pathlib.Path(__file__).resolve().parents[2]
+decompiled = root / "decompiled"
+work = root / "tools/reconstruction/work/portable-stdio"
+work.mkdir(parents=True, exist_ok=True)
+reference = work / "reference.exe"
+subprocess.run([
+ str(root / "tools/rust/llvm-mingw-20261006-ucrt-x86_64/bin/i686-w64-mingw32-clang.exe"),
+ "-O2", "tests/guest_stdio.c", "-o", str(reference),
+], cwd=decompiled, check=True)
+expected = subprocess.check_output([str(reference)], text=True, timeout=30)
+linux_path = "/mnt/" + decompiled.drive[0].lower() + decompiled.as_posix()[2:]
+linux_output = "/mnt/" + work.drive[0].lower() + work.as_posix()[2:] + "/translated"
+wsl = ["wsl", "-d", "Ubuntu-26.04", "--cd", linux_path, "--exec"]
+subprocess.run(wsl + [
+ "gcc", "-O2", "-DRECOMP_PORTABLE", "-Iruntime", "-fno-strict-aliasing",
+ "tests/guest_stdio.c", "runtime/guest_stdio.c", "runtime/guest_crt.c", "runtime/guest_format.c",
+ "runtime/guest_heap.c", "runtime/guest_memory.c", "runtime/recomp_state.c",
+ "-lm", "-o", linux_output,
+], check=True)
+actual = subprocess.check_output(wsl + [linux_output], text=True, timeout=30)
+assert actual == expected, (expected, actual)
+print("Windows == Linux: " + actual.strip())