From d761bae27be0ef52840963864f6d8484e93ff1e0 Mon Sep 17 00:00:00 2001 From: Mitchell Hashimoto Date: Mon, 26 Dec 2022 22:07:33 -0800 Subject: [PATCH] wasm: log should use stack allocated memory first This allows log messages to come through even when OOM. --- src/os/wasm/log.zig | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/os/wasm/log.zig b/src/os/wasm/log.zig index b1957d05a..6ee1055a1 100644 --- a/src/os/wasm/log.zig +++ b/src/os/wasm/log.zig @@ -9,12 +9,25 @@ pub fn log( comptime format: []const u8, args: anytype, ) void { + // The buffer for putting our log message. We try to use a stack-allocated + // buffer first because we want to avoid allocation. If we are logging + // an error DUE to an OOM, allocating will of course fail and we'd like + // to see the error message so we prefer to use this. + var buf: [2048]u8 = undefined; + // Build the string const level_txt = comptime level.asText(); const prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; const txt = level_txt ++ prefix ++ format; - const str = nosuspend std.fmt.allocPrint(wasm.alloc, txt, args) catch return; - defer wasm.alloc.free(str); + + // Format. We attempt to use a stack-allocated string first and if that + // fails we'll try to allocate. + var allocated: bool = false; + const str = nosuspend std.fmt.bufPrint(&buf, txt, args) catch str: { + allocated = true; + break :str std.fmt.allocPrint(wasm.alloc, txt, args) catch return; + }; + defer if (allocated) wasm.alloc.free(str); // Send it over to the JS side JS.log(str.ptr, str.len);