Skip to the content ForoHackers
Log inJoin

WebAssembly memory is just one big ArrayBuffer (y por qué se te rompe al hacer grow)

FrontendJavaScript and TypeScriptWebAssembly
#1167 · spanglish_stacktrace · · Report

A mental model that unblocked me when I started with WebAssembly: a module does not have a heap in the C sense, it has linear memory, one contiguous array of bytes that JS can see as an ArrayBuffer. Pointers inside the module are just indexes into that array.

const mem = new WebAssembly.Memory({ initial: 1, maximum: 4 });   // 1 page = 64 KiB
let view = new Uint8Array(mem.buffer);

view[0] = 42;            // JS writes, wasm sees it at address 0

La parte que me rompió el día: memory can grow, and when it does, the old ArrayBuffer is detached.

mem.grow(1);
console.log(view.length);              // 0, the old buffer is detached
view = new Uint8Array(mem.buffer);     // hay que crear la vista otra vez
console.log(view.length);              // 131072

If you keep a view in a global variable and the module calls memory.grow (say, because its allocator asked for more pages), your old view now has length 0 and reads give you undefined. No error is thrown, because why would there be one? Ya ves.

My rule: never cache mem.buffer or a typed array over it across any call into the module that can allocate. Re-create the view after each call, or wrap it in a tiny function getView() that checks view.buffer !== mem.buffer.

And no, maximum does not protect you from this: it only caps how big memory can get, not whether the buffer is replaced.

#1976 · hexdump_hermit · · Report

Worth adding: "detached" is the right word. The bytes still exist in the new buffer. The old object is a husk with length zero. Reading from it does not fault, which is what makes it so confusing to debug.

#1977 · spanglish_stacktrace · · Report

Exacto, hexdump. Y por eso el bug aparece "a veces": solo cuando el allocator del módulo decide crecer. En desarrollo con pocos datos nunca pasa, y en producción con un fichero grande, boom, silencio.

#1978 · it_works_on_my_vm · · Report

Dumb question: is there any way to be told when memory grows, instead of checking view.buffer !== mem.buffer every time? A callback would be nice.

#1979 · spanglish_stacktrace · · Report

No callback that I know of from the JS side. The check is cheap (one pointer comparison), so a getView() helper is the idiom. If you control the module, you can also export a function that returns the current size and compare that instead.

Log in or join to reply.