From 3021e16bbf138ef48d840604e330049def61329a Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Fri, 16 Feb 2024 16:33:07 +0100 Subject: [PATCH] wasm: call __stdio_exit on exit This flushes stdio, so that functions like puts and printf write out all buffered data even if the output isn't connected to a terminal. For discussion, see: https://github.com/bytecodealliance/wasmtime/issues/7833 --- src/runtime/runtime_tinygowasm.go | 8 ++++++++ src/runtime/runtime_wasip1.go | 1 + src/runtime/runtime_wasm_js.go | 1 + 3 files changed, 10 insertions(+) diff --git a/src/runtime/runtime_tinygowasm.go b/src/runtime/runtime_tinygowasm.go index b69a91539..744e138af 100644 --- a/src/runtime/runtime_tinygowasm.go +++ b/src/runtime/runtime_tinygowasm.go @@ -21,6 +21,11 @@ func fd_write(id uint32, iovs *__wasi_iovec_t, iovs_len uint, nwritten *uint) (e //go:wasmimport wasi_snapshot_preview1 proc_exit func proc_exit(exitcode uint32) +// Flush stdio on exit. +// +//export __stdio_exit +func __stdio_exit() + const ( putcharBufferSize = 120 stdout = 1 @@ -72,6 +77,9 @@ func abort() { //go:linkname syscall_Exit syscall.Exit func syscall_Exit(code int) { + // TODO: should we call __stdio_exit here? + // It's a low-level exit (syscall.Exit) so doing any libc stuff seems + // unexpected, but then where else should stdio buffers be flushed? proc_exit(uint32(code)) } diff --git a/src/runtime/runtime_wasip1.go b/src/runtime/runtime_wasip1.go index 595cab9bf..4a1afb2ab 100644 --- a/src/runtime/runtime_wasip1.go +++ b/src/runtime/runtime_wasip1.go @@ -19,6 +19,7 @@ func _start() { heapStart = uintptr(unsafe.Pointer(&heapStartSymbol)) heapEnd = uintptr(wasm_memory_size(0) * wasmPageSize) run() + __stdio_exit() } // Read the command line arguments from WASI. diff --git a/src/runtime/runtime_wasm_js.go b/src/runtime/runtime_wasm_js.go index 96e923c89..0b1aa5bc4 100644 --- a/src/runtime/runtime_wasm_js.go +++ b/src/runtime/runtime_wasm_js.go @@ -18,6 +18,7 @@ func _start() { wasmNested = true run() + __stdio_exit() wasmNested = false }