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)
This commit is contained in:
刘皓 2025-03-02 14:05:49 -05:00
parent db0758f634
commit b68dae451d
No known key found for this signature in database
GPG key ID: 7901753DB465B711

View file

@ -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;