Search code examples
javascriptnode.jswebassembly

Why arguments are zeroed at WebAssembly imported function call?


I manually generated a WASM module that decompiles by wasm2wat into the following code.

(module
  (type (;0;) (func))
  (type (;1;) (func (param i32 i32)))
  (import "std" "print" (func (;0;) (type 1)))
  (func (;1;) (type 0)
    i32.const 0
    i32.const 13
    call 0)
  (memory (;0;) 13)
  (export "main" (func 0))
  (export "data" (memory 0))
  (data (;0;) (i32.const 0) "Hello, world!"))

At Node site I instantiate the module, supplying the following imports.

const imports = {
  std: {
    print: (utf8Offset, utf8Length) => {
      console.log([utf8Offset, utf8Length]);
      ...
    },
  },
};

When main function runs, console.log reports two zeros instead of 0 and 13. Why?


Solution

  • The problem was solved. I didn't take into account that functions are numbered starting from imports, not from in-module definitions.

    main export should look like this:

    (export "main" (func 1))