How to set max memory limit in wasm

I don't know of a way to tell the Rust compiler to generate a .wasm file with the memory limit set.

However, I would suggest you to enforce this on the runtime level. If you are using wasmtime, you can embed their runtime into a wrapper app and control memory & CPU usage precisely. This way you don't even need to trust the value in the .wasm file you are running.

If you don't feel like providing your runtime, lunatic even allows you to write rust code that compiles to wasm and then loads other .wasm files dynamically with specific memory/cpu/syscalls constraints. You can even run just a closure from the currently executing .wasm file in a separate "process" (wasm instance), with specific memory and CPU constraints.

Btw. When compiling to wasm, Rust uses a shadow-stack on the wasm heap that will eat part of your heap memory. You can configure how big this stack is with a flag (I think it's actually a LLVM flag and I can't remember it now). You need to account for this too if you are setting a small wasm page size (like ~20).

2 Likes