Using Zig with WebAssembly

Hello, I’m quite new to Zig, recently I’ve been playing with using it for WASM and had some (mis)adventures, so I wrote up all the things I learned:

If anyone knows

  1. What is __stack_pointer? (I also asked this on SO)
  2. What’s happening to pages 15 and 16 in section Memory?

it would be a help. Thanks!


Hello @mjg, welcome to the forum :slight_smile:
Thank you for sharing your web assembly journey. :heart:

I found a reference in Thread.zig source in standard library.
It is used for thread bookkeeping in wasi threads.
A source code comment in Thread.zig is:

// restore the original stack pointer so we can free the memory
// without having to worry about freeing the stack
1 Like

This is part of Wasm’s tool conventions. You can’t just have a bunch of WASM libraries interact with each other, share memory, and so on without any way to coordinate things like where the stack and heap are. This is separate from the stack of the Wasm runtime itself, and is instead part of Wasm’s linear memory.

Looking in the convention on dynamic linking:

  • env.__stack_pointer - A mutable i32 global representing the explicit stack pointer as an offset into the above memory.

This should (?) make it safer (?) for two separate Wasm modules to share memory.

AFAIK, C/++, Rust, and others follow these conventions to some extent, tho I assume most of it comes from having LLVM as a backend.


Thank you @dimdin and @TUSF

re “2. What’s happening to pages 15 and 16 in section Memory?” I just figured that nothing is necessarily happening to page 16, it’s just that the end of page 15 is written to so I print that as one “block”.

Still surprises me somewhat, the way I was modeling it mentally is that 16 pages (0-15) is the default initial memory, so it writes to page 16 “after the userspace”.

1 Like