github.com/tetratelabs/wazero@v1.7.3-0.20240513003603-48f702e154b5/internal/integration_test/engine/memleak_test.go (about) 1 package adhoc 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "runtime" 8 "strconv" 9 "testing" 10 "time" 11 12 "github.com/tetratelabs/wazero" 13 "github.com/tetratelabs/wazero/internal/platform" 14 ) 15 16 func TestMemoryLeak(t *testing.T) { 17 if testing.Short() { 18 t.Skip("skipping memory leak test in short mode.") 19 } 20 21 if !platform.CompilerSupported() { 22 t.Skip() 23 } 24 25 duration := 5 * time.Second 26 t.Logf("running memory leak test for %s", duration) 27 28 ctx, cancel := context.WithTimeout(context.Background(), duration) 29 defer cancel() 30 31 for ctx.Err() == nil { 32 if err := testMemoryLeakInstantiateRuntimeAndModule(); err != nil { 33 log.Panicln(err) 34 } 35 } 36 37 var stats runtime.MemStats 38 runtime.GC() 39 runtime.ReadMemStats(&stats) 40 41 if stats.Alloc > (100 * 1024 * 1024) { 42 t.Errorf("wazero used more than 100 MiB after running the test for %s (alloc=%d)", duration, stats.Alloc) 43 } 44 fmt.Println(stats.Alloc) 45 } 46 47 func testMemoryLeakInstantiateRuntimeAndModule() error { 48 ctx := context.Background() 49 50 r := wazero.NewRuntime(ctx) 51 defer r.Close(ctx) 52 53 hostBuilder := r.NewHostModuleBuilder("test") 54 55 for i := 0; i < 100; i++ { 56 hostBuilder.NewFunctionBuilder().WithFunc(func() uint32 { return uint32(i) }).Export(strconv.Itoa(i)) 57 } 58 59 hostMod, err := hostBuilder.Instantiate(ctx) 60 if err != nil { 61 return err 62 } 63 if err = hostMod.Close(ctx); err != nil { 64 return err 65 } 66 67 mod, err := r.InstantiateWithConfig(ctx, memoryWasm, 68 wazero.NewModuleConfig().WithStartFunctions()) 69 if err != nil { 70 return err 71 } 72 return mod.Close(ctx) 73 }