What is `__stack_pointer` in zig wasm?

106 views Asked by At

Using this in add.zig

export fn add(a: i32, b: i32) i32 {
    return a + b;
}

and compiling with zig 0.11

zig build-lib add.zig -target wasm32-freestanding -dynamic --export=add -O ReleaseFast

then inspecting the output with wasm2wat add.wasm, I get the following output:

(module
  (type (;0;) (func (param i32 i32) (result i32)))
  (func $add (type 0) (param i32 i32) (result i32)
    local.get 1
    local.get 0
    i32.add)
  (memory (;0;) 16)
  (global $__stack_pointer (mut i32) (i32.const 1048576))
  (export "memory" (memory 0))
  (export "add" (func $add)))

Where is this line (global $__stack_pointer (mut i32) (i32.const 1048576)) coming from? I thought wasm stack was kind of implicit and separate from the memory. The number 1048576 is 2^16 * 16 so it seems to be pointing at the end of the memory.

I was trying to test with clang, and I couldn't get it to generate this.

1

There are 1 answers

0
mjg On

From WebAssembly tool conventions GitHub

A WebAssembly dynamic library must obey certain conventions. In addition to the dylink section described above a module may import the following globals that will be provided by the dynamic loader:

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