Files
wazero/examples/replace-import/replace-import.go
Crypt Keeper 92ba4929e5 Drops support for the WebAssembly text format (#614)
This drops the text format (%.wat) and renames
InstantiateModuleFromCode to InstantiateModuleFromBinary as it is no
longer ambiguous.

We decided to stop supporting the text format as it isn't typically used
in production, yet costs a lot of work to develop. Given the resources
available and the increased work added with WebAssembly 2.0 and soon
WASI 2, we can't afford to spend the time on it.

The old parser is used only internally and will eventually be moved to
its own repository named watzero, possibly towards archival.

See #59

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-06-01 19:01:43 +08:00

66 lines
1.9 KiB
Go

package main
import (
"context"
_ "embed"
"fmt"
"log"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
)
// needsImportWasm was generated by the following:
// cd testdata; wat2wasm --debug-names needs_import.wat
//go:embed testdata/needs_import.wasm
var needsImportWasm []byte
// main shows how to override a module or function name hard-coded in a
// WebAssembly module. This is similar to what some tools call "linking".
func main() {
// Choose the context to use for function calls.
ctx := context.Background()
// Create a new WebAssembly Runtime.
r := wazero.NewRuntime()
defer r.Close(ctx) // This closes everything this Runtime created.
// Instantiate a Go-defined module named "assemblyscript" that exports a
// function to close the module that calls "abort".
host, err := r.NewModuleBuilder("assemblyscript").
ExportFunction("abort", func(ctx context.Context, m api.Module, messageOffset, fileNameOffset, line, col uint32) {
_ = m.CloseWithExitCode(ctx, 255)
}).Instantiate(ctx, r)
if err != nil {
log.Panicln(err)
}
defer host.Close(ctx)
// Compile the WebAssembly module, replacing the import "env.abort" with
// "assemblyscript.abort".
compileConfig := wazero.NewCompileConfig().
WithImportRenamer(func(externType api.ExternType, oldModule, oldName string) (newModule, newName string) {
if oldModule == "env" && oldName == "abort" {
return "assemblyscript", "abort"
}
return oldModule, oldName
})
code, err := r.CompileModule(ctx, needsImportWasm, compileConfig)
if err != nil {
log.Panicln(err)
}
defer code.Close(ctx)
// Instantiate the WebAssembly module.
mod, err := r.InstantiateModule(ctx, code, wazero.NewModuleConfig())
if err != nil {
log.Panicln(err)
}
defer mod.Close(ctx)
// Since the above worked, the exported function closes the module.
_, err = mod.ExportedFunction("abort").Call(ctx, 0, 0, 0, 0)
fmt.Println(err)
}