Skip to content

Instantly share code, notes, and snippets.

@maxsei
Created February 12, 2024 22:56
Show Gist options
  • Select an option

  • Save maxsei/c3803c6d917e803b2cae7be047c39a16 to your computer and use it in GitHub Desktop.

Select an option

Save maxsei/c3803c6d917e803b2cae7be047c39a16 to your computer and use it in GitHub Desktop.
memory experiment with wasm gpa
const std = @import("std");
const wasm_api = @import("node_modules/@thi.ng/wasm-api/zig/lib.zig");

var gpa = std.heap.GeneralPurposeAllocator(.{}){};
pub const WASM_ALLOCATOR = gpa.allocator();

pub export fn start() i32 {
    const allocator = wasm_api.allocator().?;
    const page_size = 65_536;
    const n_pages = 1024 * 64;
    for (0..n_pages) |i| {
        _ = allocator.alloc(u8, page_size) catch {
            wasm_api.printStr("page_size");
            wasm_api.printU32(page_size);
            wasm_api.printStr("i");
            wasm_api.printU32(i);
            wasm_api.printStr("n_pages");
            wasm_api.printU32(n_pages);
            wasm_api.panic("out of memory - 6351a5fe", null, 0);
        };
    }
    return 0;
}
[DEBUG] wasm: page_size console.js:6:12
[DEBUG] wasm: 65536 console.js:6:12
[DEBUG] wasm: i console.js:6:12
[DEBUG] wasm: 65491 console.js:6:12
[DEBUG] wasm: n_pages console.js:6:12
[DEBUG] wasm: 65536 console.js:6:12
Sourcegraph browser extension is running contentPage.main.bundle.js:78945:11
Uncaught (in promise) Error: Panic: out of memory - 6351a5fe
    <anonymous> deferror.js:3
    _panic bridge.js:68
    <anonymous> todo.ts:12
    async* todo.ts:13

Wasm is allowed to allocate have up to 4GiB in the browser. We allocated 65491 pages (3.997253417969 GiB), meaning that the leftover memory is used for other stack operations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment