forked from tetratelabs/wazero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace-import.go
56 lines (47 loc) · 1.61 KB
/
replace-import.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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)
}