2

When compiling C or C++ to web assembly (clang/llvm/binaryen) undefined functions are imported from "env".

For example

extern "C" int afunc();

int main() {
  return afunc();
}

compiles to

(module
  (type $FUNCSIG$i (func (result i32)))
  (import "env" "afunc" (func $afunc (result i32)))
  (table 0 anyfunc)
  (memory $0 1)
  (export "memory" (memory $0))
  (export "main" (func $main))
  (func $main (result i32)
    (call $afunc)
  )
)

I guess the line (import "env" "afunc" (func $afunc (result i32))) means that it tries to request the function afunc from the host environment. However, I found no documentation that the host environment should be named env.

Is it possible to exert some control over these host imports? Specifically,

  • can I rename it to something other than env?
  • is it possible to disable this behavior so that I get a linker error when a function is not defined (maybe unless it is a function known to be available in the host)?
MB-F
  • 22,770
  • 4
  • 61
  • 116

1 Answers1

1

Currently the easiest way to compile C and C++ is with emscripten. The components you mention are all components, but emscripten is a full toolchain that supports building end-to-end, and includes all the parts you need including libc/libc++, and a variety of other useful libraries. It supports targeting both asm.js and wasm.

The "env" bit is the default behavior of s2wasm which is designed to work with emscripten. Emscripten has the standard libraries (e.g. libc) and links them into your code, and it also provides some of its functionality as JavaScript code which is also automatically included in your module. It sets up the env import and automatically instantiates your module with it.

Derek
  • 783
  • 1
  • 4
  • 8
  • 1
    Does *default behavior* imply it can be changed? – MB-F Jul 18 '17 at 07:15
  • There's no flag but you can change the value of `ENV` in https://github.com/WebAssembly/binaryen/blob/master/src/asmjs/shared-constants.cpp and recompile it. – Derek Jul 19 '17 at 06:46