wasmerio / wasmer-go

🐹🕸️ WebAssembly runtime for Go
https://pkg.go.dev/github.com/wasmerio/wasmer-go
MIT License
2.8k stars 161 forks source link

Cannot print statements from the WASM module #373

Closed glethuillier closed 1 year ago

glethuillier commented 1 year ago

Describe the bug

The following error occurs when trying to instantiate a WASM module that contains a call to fmt.Println: Missing import: wasi_snapshot_preview1.fd_write

Steps to reproduce

  1. Use the latest version of tinygo (0.27.0) to compile the Go code to WASM (from this issue)
package main

import "fmt"

func main() {
    fmt.Println("Hello wasmer.io")
}

//export Sum
func Sum(x, y int) int {
    return x + y
}
tinygo build -o test.wasm -target wasi .
  1. User wasmer to load test.wasm (from this issue)
package main

import (
    _ "embed"
    "fmt"

    "github.com/wasmerio/wasmer-go/wasmer"
)

var instance *wasmer.Instance

//go:embed test.wasm
var wasmBytes []byte

func init() {
    store := wasmer.NewStore(wasmer.NewEngine())
    module, e := wasmer.NewModule(store, wasmBytes)
    if e != nil {
        panic(e)
    }
    // fmt.Printf("Load Wasm Size: %.2fMB\n", float64(len(wasmBytes))/1024/1024)
    instance, e = wasmer.NewInstance(module, wasmer.NewImportObject())
    if e != nil {
        panic(e) // panic: Missing import: `go`.`debug`
    }
}

func main() {
    sum, _ := instance.Exports.GetFunction("Sum")
    result, _ := sum(5, 37)
    fmt.Println(result)
}

Expected behavior

Hello wasmer.io
42

Actual behavior

panic: Missing import: `wasi_snapshot_preview1`.`fd_write`

goroutine 1 [running]:
main.init.0()
    /Users/abc/main.go:24 +0x160
exit status 2

Additional context

This issue is related to this problem.

Compiled on macOS. Tinygo 0.27.0 installed via brew.

glethuillier commented 1 year ago

Solved by using this: https://github.com/wasmerio/wasmer-go/blob/master/examples/wasi/main.go#L16-L22

Perhaps would it be possible to clarify the documentation to explain that wasmer.NewWasiStateBuilder("wasi-program") is required?