Search code examples
v8webassemblyemscriptenemccwasi

How to run in wee8 wasm code that was compiled from c++ with emcc? (WASI in wee8?)


I am trying to compile C++ code to wasm and then embed it in other C++ code with wee8 (v8's wasm-api). Currently I'm getting a Segfault on instantiating the module:

    auto instance = wasm::Instance::make(store, module.get(), imports);

Note that I have no problem embedding code that I write as .wat and convert to .wasm, so the problem is specifically with embedding code compiled with emcc. I am guessing that what I'm missing is WASI support in wee8? Does it exist? How can I enable it? Alternatively: can I ask emcc not to generate any WASI calls?

Here is a minimal example which results in:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

In cpp42.cpp:

int main() {
    return 42;
}

Compiling this to wasm with:

emcc -O3 cpp42.cpp -o cpp42.wasm

Inspecting the compiled wasm module with wabt's wasm2wat shows that it contains the following import

  (import "wasi_snapshot_preview1" "proc_exit" (func (;0;) (type 0)))

Which I suspect to be the cause of the problem.

Then embedding with wee8 like in the examples in the repo and like I do with other wasm files causes the segfault mentioned above.

Just as another check: running

wasmer cpp42.wasm 
echo $?
> 42

Works without a problem.


Solution

  • I can answer part of your question:

    I'm missing is WASI support in wee8? Does it exist?

    No, wee8 does not implement WASI. Adding such support is theoretically possible, but not currently scheduled to get done.

    You can implement it yourself in your wee8 embedder, and make it available to loaded modules via imports. Most (or all?) of it could probably be a reusable (among many engine implementations) library, potentially offered and maintained by the WASI project itself. (I don't know whether such a library exists already.)

    You didn't say what imports object you're currently passing; it needs to be an array of wasm::Extern* pointers that's at least as long as the imports of the module, and ordered equivalently (i.e. imports[i] will be the module's ith import).

    (I agree that the Wasm C/C++ API is very barebones currently. Unless/until that is changed, you'll have to build any convenience mechanisms yourself. It's all possible with the information that's available, it's just clearly less convenient than instantiating Wasm modules from JavaScript.)