From b68dae451d1321e282a87d4c835a97f3d99138d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=9A=93?= Date: Sun, 2 Mar 2025 14:05:49 -0500 Subject: [PATCH] Zero out memory allocated by wasm-rt In release 1.0 of the WebAssembly Specification, it says that all the bytes in WebAssembly memory need to be initialized to 0 on creation of the memory, and when memory is grown, the new bytes also need to be initialized to 0. It seems this zeroing behaviour is indeed required for the sandbox to operate correctly. Not zeroing leads to undefined behaviour. This manifested as a crash that occurred when restarting the libretro core, but for some reason, only on Emscripten. Not sure why this didn't happen on other platforms. Even sanitizers weren't able to detect the bug! (cherry picked from commit edf061e323b8f0ab0c6a72c76ae7ccc07a1649c0) --- binding-sandbox/wasm-rt.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/binding-sandbox/wasm-rt.cpp b/binding-sandbox/wasm-rt.cpp index 8e992a4b..cc65bb21 100644 --- a/binding-sandbox/wasm-rt.cpp +++ b/binding-sandbox/wasm-rt.cpp @@ -80,6 +80,7 @@ extern "C" void wasm_rt_allocate_memory(wasm_rt_memory_t *memory, uint32_t initi memory->data = memory->private_data; #endif memory->pages = initial_pages; + std::memset(memory->data, 0, memory->size); } extern "C" uint32_t wasm_rt_grow_memory(wasm_rt_memory_t *memory, uint32_t pages) { @@ -106,8 +107,10 @@ extern "C" uint32_t wasm_rt_grow_memory(wasm_rt_memory_t *memory, uint32_t pages #ifdef MKXPZ_BIG_ENDIAN memory->data = memory->private_data + std::max((size_t)new_size, (size_t)WASM_MIN_PAGES * (size_t)WASM_PAGE_SIZE) - (size_t)new_size; + std::memset(memory->data, 0, new_size - memory->size); #else memory->data = memory->private_data; + std::memset(memory->data + memory->size, 0, new_size - memory->size); #endif // MKXPZ_BIG_ENDIAN uint32_t old_pages = memory->pages;