| 51 | } |
| 52 | |
| 53 | func (prog *program) run(ctx context.Context) error { |
| 54 | wasmName := filepath.Base(prog.filePath) |
| 55 | wasmCode, err := os.ReadFile(prog.filePath) |
| 56 | if err != nil { |
| 57 | return fmt.Errorf("reading wasm module: %w", err) |
| 58 | } |
| 59 | |
| 60 | p := wzprof.ProfilingFor(wasmCode) |
| 61 | |
| 62 | cpu := p.CPUProfiler(wzprof.HostTime(prog.hostTime)) |
| 63 | mem := p.MemoryProfiler(wzprof.InuseMemory(prog.inuseMemory)) |
| 64 | |
| 65 | var listeners []experimental.FunctionListenerFactory |
| 66 | if prog.cpuProfile != "" || prog.pprofAddr != "" { |
| 67 | stdout.Printf("enabling cpu profiler") |
| 68 | listeners = append(listeners, cpu) |
| 69 | } |
| 70 | if prog.memProfile != "" || prog.pprofAddr != "" { |
| 71 | stdout.Printf("enabling memory profiler") |
| 72 | listeners = append(listeners, mem) |
| 73 | } |
| 74 | if prog.sampleRate < 1 { |
| 75 | stdout.Printf("configuring sampling rate to %.2g%%", prog.sampleRate) |
| 76 | for i, lstn := range listeners { |
| 77 | listeners[i] = wzprof.Sample(prog.sampleRate, lstn) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | ctx = context.WithValue(ctx, |
| 82 | experimental.FunctionListenerFactoryKey{}, |
| 83 | experimental.MultiFunctionListenerFactory(listeners...), |
| 84 | ) |
| 85 | |
| 86 | runtime := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig(). |
| 87 | WithDebugInfoEnabled(true). |
| 88 | WithCustomSections(true)) |
| 89 | |
| 90 | stdout.Printf("compiling wasm module %s", prog.filePath) |
| 91 | compiledModule, err := runtime.CompileModule(ctx, wasmCode) |
| 92 | if err != nil { |
| 93 | return fmt.Errorf("compiling wasm module: %w", err) |
| 94 | } |
| 95 | err = p.Prepare(compiledModule) |
| 96 | if err != nil { |
| 97 | return fmt.Errorf("preparing wasm module: %w", err) |
| 98 | } |
| 99 | |
| 100 | if prog.pprofAddr != "" { |
| 101 | u := &url.URL{Scheme: "http", Host: prog.pprofAddr, Path: "/debug/pprof"} |
| 102 | stdout.Printf("starting prrof http sever at %s", u) |
| 103 | |
| 104 | server := http.NewServeMux() |
| 105 | server.Handle("/debug/pprof/", wzprof.Handler(prog.sampleRate, cpu, mem)) |
| 106 | |
| 107 | go func() { |
| 108 | if err := http.ListenAndServe(prog.pprofAddr, server); err != nil { |
| 109 | stderr.Println(err) |
| 110 | } |