0

I'm working on an issue to clean up all the memory from a webassembly app built with Emscripten. Some related questions without a suitable answer are here and here.

From my understanding, Webassembly memory can only be freed if all JS references to Wasm instance are set to undefined or fall out of scope. In some cases this is proving difficult due to reasons outside my control.

So, I'm wondering if it's possible to set, clear or reset the entire heap on a WebAssembly instance. In this case I no longer need it, it's litereally app cleanup and want to return memory to the browser.

I'm looking for something like this:

wasmInstance.buffer = undefined;

or

wasmInstance.buffer = new WebAssembly.Memory({ initial: 1});

I have tried

wasmInstance.HEAPF64 = undefined; 
wasmInstance.HEAPF32 = undefined; 
// ... etc 

However this only clears the TypedArray views on the webassembly buffer (heap) not the buffer itself.

Dr. Andrew Burnett-Thompson
  • 20,980
  • 8
  • 88
  • 178
  • 1
    I'm not really sure if we can access the entirety of cleaning the heap option via JS/TS. Since you've mentioned the app memory cleanup, you can explore `wasm-gc` option. – Jishan Shaikh Jun 06 '23 at 13:01
  • Thanks for the suggestion, a quick google search only turned up this repository for wasm-gc. Is this what you meant? https://github.com/alexcrichton/wasm-gc – Dr. Andrew Burnett-Thompson Jun 06 '23 at 13:13
  • 1
    Yes, we used to use it from its CLI crate ([`wasm-gc`](https://docs.rs/crate/wasm-gc/0.1.6)) – Jishan Shaikh Jun 07 '23 at 06:46

1 Answers1

0

I figured out the answer to this, and posted it here which is a related question.

TLDR: allow JS to Garbage Collect the wasmInstance and it will also GC the wasm heap. That's the only way to free wasm memory

Dr. Andrew Burnett-Thompson
  • 20,980
  • 8
  • 88
  • 178