Debian Codegraph @

experimental/importresolver_test.go

raw symbols SCIP
1 package experimental_test
2
3 import (
4 "context"
5 "fmt"
6 "testing"
7
8 "github.com/tetratelabs/wazero"
9 "github.com/tetratelabs/wazero/api"
10 "github.com/tetratelabs/wazero/experimental"
11 "github.com/tetratelabs/wazero/internal/testing/binaryencoding"
12 "github.com/tetratelabs/wazero/internal/testing/require"
13 "github.com/tetratelabs/wazero/internal/wasm"
14 )
15
16 func TestImportResolver(t *testing.T) {
17 ctx := context.Background()
18
19 r := wazero.NewRuntime(ctx)
20 defer r.Close(ctx)
21
22 for i := 0; i < 5; i++ {
23 var callCount int
24 start := func(ctx context.Context) {
25 callCount++
26 }
27 modImport, err := r.NewHostModuleBuilder(fmt.Sprintf("env%d", i)).
28 NewFunctionBuilder().WithFunc(start).Export("start").
29 Compile(ctx)
30 require.NoError(t, err)
31 // Anonymous module, it will be resolved by the import resolver.
32 instanceImport, err := r.InstantiateModule(ctx, modImport, wazero.NewModuleConfig().WithName(""))
33 require.NoError(t, err)
34
35 resolveImport := func(name string) api.Module {
36 if name == "env" {
37 return instanceImport
38 }
39 return nil
40 }
41
42 // Set the import resolver in the context.
43 ctx = experimental.WithImportResolver(context.Background(), resolveImport)
44
45 one := uint32(1)
46 binary := binaryencoding.EncodeModule(&wasm.Module{
47 TypeSection: []wasm.FunctionType{{}},
48 ImportSection: []wasm.Import{{Module: "env", Name: "start", Type: wasm.ExternTypeFunc, DescFunc: 0}},
49 FunctionSection: []wasm.Index{0},
50 CodeSection: []wasm.Code{
51 {Body: []byte{wasm.OpcodeCall, 0, wasm.OpcodeEnd}}, // Call the imported env.start.
52 },
53 StartSection: &one,
54 })
55
56 modMain, err := r.CompileModule(ctx, binary)
57 require.NoError(t, err)
58
59 _, err = r.InstantiateModule(ctx, modMain, wazero.NewModuleConfig())
60 require.NoError(t, err)
61 require.Equal(t, 1, callCount)
62 }
63 }