Files
wazero/examples/replace-import/replace-import.go
Crypt Keeper 45ff2fe12f Propagates context to all api interface methods that aren't constant (#502)
This prepares for exposing operations like Memory.Grow while keeping the
ability to trace what did that, by adding a `context.Context` initial
parameter. This adds this to all API methods that mutate or return
mutated data.

Before, we made a change to trace functions and general lifecycle
commands, but we missed this part. Ex. We track functions, but can't
track what closed the module, changed memory or a mutable constant.
Changing to do this now is not only more consistent, but helps us
optimize at least the interpreter to help users identify otherwise
opaque code that can cause harm. This is critical before we add more
functions that can cause harm, such as Memory.Grow.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
2022-04-25 08:13:18 +08:00

57 lines
1.6 KiB
Go

package replace_import
import (
"context"
_ "embed"
"fmt"
"log"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
)
// 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()
// 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)
if err != nil {
log.Fatal(err)
}
defer host.Close(ctx)
// Compile WebAssembly code that needs the function "env.abort".
code, err := r.CompileModule(ctx, []byte(`(module $needs-import
(import "env" "abort" (func $~lib/builtins/abort (param i32 i32 i32 i32)))
(export "abort" (func 0)) ;; exports the import for testing
)`))
if err != nil {
log.Fatal(err)
}
defer code.Close(ctx)
// Instantiate the WebAssembly module, replacing the import "env.abort"
// with "assemblyscript.abort".
mod, err := r.InstantiateModuleWithConfig(ctx, code, wazero.NewModuleConfig().
WithImport("env", "abort", "assemblyscript", "abort"))
if err != nil {
log.Fatal(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)
}