Is there any way to limit linear memory usage at all costs?

I am compiling Zig to WASM, which is going to be ran on a platform where linear memory is unimaginably slow. Is there any way that I can limit this, preferably through the build system?

There is @wasmMemorySize()

You could wrap std.heap.wasm_allocator into something like this:

pub const limited_wasm_allocator = std.mem.Allocator{
    .ptr = undefined,
    .vtable = &.{
        .alloc = alloc,
        [...]
    };
};

fn alloc(... len: usize ...) ?[*]u8 {
    const required_pages = std.math.divCeil(usize, len, std.wasm.page_size);
    if (@wasmMemorySize(0) + required_pages > max_page_count) {
        return null;
    } else {
        return std.heap.wasm_allocator.rawAlloc(...);
    }
}

[...]

and pass max_page_count as a build option.

I don’t know how expensive calling @wasmMemorySize() (size: Wasm text instruction - WebAssembly | MDN) is on your target platform though.

1 Like

Forget about that, there’s also a global --max-memory=[bytes] link option for WASM.

zig build-obj --help → Global Link Options:

  --initial-memory=[bytes]       (WebAssembly) initial size of the linear memory
  --max-memory=[bytes]           (WebAssembly) maximum size of the linear memory