Debian Codegraph @

cmd/wazero/wazero.go

raw symbols SCIP
1 package main
2
3 import (
4 "context"
5 "crypto/rand"
6 "errors"
7 "flag"
8 "fmt"
9 "io"
10 "os"
11 "path/filepath"
12 "runtime"
13 "runtime/pprof"
14 "strconv"
15 "strings"
16 "time"
17
18 "github.com/tetratelabs/wazero"
19 "github.com/tetratelabs/wazero/api"
20 "github.com/tetratelabs/wazero/experimental"
21 "github.com/tetratelabs/wazero/experimental/logging"
22 "github.com/tetratelabs/wazero/experimental/sock"
23 "github.com/tetratelabs/wazero/experimental/sysfs"
24 "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
25 internalsys "github.com/tetratelabs/wazero/internal/sys"
26 "github.com/tetratelabs/wazero/internal/version"
27 "github.com/tetratelabs/wazero/sys"
28 )
29
30 func main() {
31 os.Exit(doMain(os.Stdout, os.Stderr))
32 }
33
34 // doMain is separated out for the purpose of unit testing.
35 func doMain(stdOut io.Writer, stdErr logging.Writer) int {
36 flag.CommandLine.SetOutput(stdErr)
37
38 var help bool
39 flag.BoolVar(&help, "h", false, "Prints usage.")
40
41 flag.Parse()
42
43 if help || flag.NArg() == 0 {
44 printUsage(stdErr)
45 return 0
46 }
47
48 if flag.NArg() < 1 {
49 fmt.Fprintln(stdErr, "missing path to wasm file")
50 printUsage(stdErr)
51 return 1
52 }
53
54 subCmd := flag.Arg(0)
55 switch subCmd {
56 case "compile":
57 return doCompile(flag.Args()[1:], stdErr)
58 case "run":
59 return doRun(flag.Args()[1:], stdOut, stdErr)
60 case "version":
61 fmt.Fprintln(stdOut, version.GetWazeroVersion())
62 return 0
63 default:
64 fmt.Fprintln(stdErr, "invalid command")
65 printUsage(stdErr)
66 return 1
67 }
68 }
69
70 func doCompile(args []string, stdErr io.Writer) int {
71 flags := flag.NewFlagSet("compile", flag.ExitOnError)
72 flags.SetOutput(stdErr)
73
74 var help bool
75 flags.BoolVar(&help, "h", false, "Prints usage.")
76
77 var count int
78 var cpuProfile string
79 var memProfile string
80 if version.GetWazeroVersion() != version.Default {
81 count = 1
82 } else {
83 flags.IntVar(&count, "count", 1,
84 "Number of times to perform the compilation. This is useful to benchmark performance of the wazero compiler.")
85
86 flags.StringVar(&cpuProfile, "cpuprofile", "",
87 "Enables cpu profiling and writes the profile at the given path.")
88
89 flags.StringVar(&memProfile, "memprofile", "",
90 "Enables memory profiling and writes the profile at the given path.")
91 }
92
93 cacheDir := cacheDirFlag(flags)
94 workers := workersFlag(flags)
95
96 _ = flags.Parse(args)
97
98 if help {
99 printCompileUsage(stdErr, flags)
100 return 0
101 }
102
103 if flags.NArg() < 1 {
104 fmt.Fprintln(stdErr, "missing path to wasm file")
105 printCompileUsage(stdErr, flags)
106 return 1
107 }
108
109 if memProfile != "" {
110 defer writeHeapProfile(stdErr, memProfile)
111 }
112
113 if cpuProfile != "" {
114 stopCPUProfile := startCPUProfile(stdErr, cpuProfile)
115 defer stopCPUProfile()
116 }
117
118 wasmPath := flags.Arg(0)
119
120 wasm, err := os.ReadFile(wasmPath)
121 if err != nil {
122 fmt.Fprintf(stdErr, "error reading wasm binary: %v\n", err)
123 return 1
124 }
125
126 c := wazero.NewRuntimeConfig()
127 if rc, cache := maybeUseCacheDir(cacheDir, stdErr); rc != 0 {
128 return rc
129 } else if cache != nil {
130 c = c.WithCompilationCache(cache)
131 }
132
133 ctx := context.Background()
134
135 if maxProcs := runtime.GOMAXPROCS(0); *workers > maxProcs {
136 fmt.Fprintf(stdErr, "warning: desired number of compilation workers (%d) greater than GOMAXPROCS (%d) defaulting to GOMAXPROCS\n", *workers, maxProcs)
137 *workers = maxProcs
138 }
139
140 ctx = experimental.WithCompilationWorkers(ctx, *workers)
141
142 rt := wazero.NewRuntimeWithConfig(ctx, c)
143 defer rt.Close(ctx)
144
145 for count > 0 {
146 compiledModule, err := rt.CompileModule(ctx, wasm)
147 if err != nil {
148 fmt.Fprintf(stdErr, "error compiling wasm binary: %v\n", err)
149 return 1
150 }
151 if err := compiledModule.Close(ctx); err != nil {
152 fmt.Fprintf(stdErr, "error releasing compiled module: %v\n", err)
153 return 1
154 }
155 count--
156 }
157 return 0
158 }
159
160 func doRun(args []string, stdOut io.Writer, stdErr logging.Writer) int {
161 flags := flag.NewFlagSet("run", flag.ExitOnError)
162 flags.SetOutput(stdErr)
163
164 var help bool
165 flags.BoolVar(&help, "h", false, "Prints usage.")
166
167 var useInterpreter bool
168 flags.BoolVar(&useInterpreter, "interpreter", false,
169 "Interprets WebAssembly modules instead of compiling them into native code.")
170
171 var envs sliceFlag
172 flags.Var(&envs, "env", "key=value pair of environment variable to expose to the binary. "+
173 "Can be specified multiple times.")
174
175 var envInherit bool
176 flags.BoolVar(&envInherit, "env-inherit", false,
177 "Inherits any environment variables from the calling process. "+
178 "Variables specified with the <env> flag are appended to the inherited list.")
179
180 var mounts sliceFlag
181 flags.Var(&mounts, "mount",
182 "Filesystem path to expose to the binary in the form of <path>[:<wasm path>][:ro]. "+
183 "This may be specified multiple times. When <wasm path> is unset, <path> is used. "+
184 "For example, -mount=/:/ or c:\\:/ makes the entire host volume writeable by wasm. "+
185 "For read-only mounts, append the suffix ':ro'. "+
186 "Note that the volume mount inherently allows the guest to escape the volume via relative path lookups like '../../'. "+
187 "If that is not desired, use wazero as a library and implement a custom fs.FS.")
188
189 var listens sliceFlag
190 flags.Var(&listens, "listen",
191 "Open a TCP socket on the specified address of the form <host:port>. "+
192 "This may be specified multiple times. Host is optional, and port may be 0 to "+
193 "indicate a random port.")
194
195 var timeout time.Duration
196 flags.DurationVar(&timeout, "timeout", 0*time.Second,
197 "If a wasm binary runs longer than the given duration string, then exit abruptly. "+
198 "The duration string is an unsigned sequence of decimal numbers, "+
199 "each with optional fraction and a unit suffix, such as \"300ms\", \"1.5h\" or \"2h45m\". "+
200 "Valid time units are \"ns\", \"us\" (or \"ยตs\"), \"ms\", \"s\", \"m\", \"h\". "+
201 "If the duration is 0, the timeout is disabled. The default is disabled.")
202
203 var hostlogging logScopesFlag
204 flags.Var(&hostlogging, "hostlogging",
205 "A comma-separated list of host function scopes to log to stderr. "+
206 "This may be specified multiple times. Supported values: all,clock,filesystem,memory,proc,poll,random,sock")
207
208 var cpuProfile string
209 var memProfile string
210 if version.GetWazeroVersion() == version.Default {
211 flags.StringVar(&cpuProfile, "cpuprofile", "",
212 "Enables cpu profiling and writes the profile at the given path.")
213
214 flags.StringVar(&memProfile, "memprofile", "",
215 "Enables memory profiling and writes the profile at the given path.")
216 }
217
218 cacheDir := cacheDirFlag(flags)
219 workers := workersFlag(flags)
220
221 _ = flags.Parse(args)
222
223 if help {
224 printRunUsage(stdErr, flags)
225 return 0
226 }
227
228 if flags.NArg() < 1 {
229 fmt.Fprintln(stdErr, "missing path to wasm file")
230 printRunUsage(stdErr, flags)
231 return 1
232 }
233
234 if memProfile != "" {
235 defer writeHeapProfile(stdErr, memProfile)
236 }
237
238 if cpuProfile != "" {
239 stopCPUProfile := startCPUProfile(stdErr, cpuProfile)
240 defer stopCPUProfile()
241 }
242
243 wasmPath := flags.Arg(0)
244 wasmArgs := flags.Args()[1:]
245 if len(wasmArgs) > 1 {
246 // Skip "--" if provided
247 if wasmArgs[0] == "--" {
248 wasmArgs = wasmArgs[1:]
249 }
250 }
251
252 // Don't use map to preserve order
253 var env []string
254 if envInherit {
255 envs = append(os.Environ(), envs...)
256 }
257 for _, e := range envs {
258 fields := strings.SplitN(e, "=", 2)
259 if len(fields) != 2 {
260 fmt.Fprintf(stdErr, "invalid environment variable: %s\n", e)
261 return 1
262 }
263 env = append(env, fields[0], fields[1])
264 }
265
266 rc, _, fsConfig := validateMounts(mounts, stdErr)
267 if rc != 0 {
268 return rc
269 }
270
271 wasm, err := os.ReadFile(wasmPath)
272 if err != nil {
273 fmt.Fprintf(stdErr, "error reading wasm binary: %v\n", err)
274 return 1
275 }
276
277 wasmExe := filepath.Base(wasmPath)
278
279 var rtc wazero.RuntimeConfig
280 if useInterpreter {
281 rtc = wazero.NewRuntimeConfigInterpreter()
282 } else {
283 rtc = wazero.NewRuntimeConfig()
284 }
285
286 ctx := maybeHostLogging(context.Background(), logging.LogScopes(hostlogging), stdErr)
287
288 if rc, cache := maybeUseCacheDir(cacheDir, stdErr); rc != 0 {
289 return rc
290 } else if cache != nil {
291 rtc = rtc.WithCompilationCache(cache)
292 }
293
294 // Save the current state of the context for compilation.
295 // The -timeout flag is documented as only affecting the runtime of the module
296 // To honor this we must not pass the regular ctx as it will be potentially reassigned from this point onwards.
297 compilationCtx := ctx
298
299 if maxProcs := runtime.GOMAXPROCS(0); *workers > maxProcs {
300 fmt.Fprintf(stdErr, "warning: desired number of compilation workers (%d) greater than GOMAXPROCS (%d) defaulting to GOMAXPROCS\n", *workers, maxProcs)
301 *workers = maxProcs
302 }
303
304 compilationCtx = experimental.WithCompilationWorkers(compilationCtx, *workers)
305
306 if timeout > 0 {
307 newCtx, cancel := context.WithTimeout(ctx, timeout)
308 ctx = newCtx
309 defer cancel()
310 rtc = rtc.WithCloseOnContextDone(true)
311 } else if timeout < 0 {
312 fmt.Fprintf(stdErr, "timeout duration may not be negative, %v given\n", timeout)
313 printRunUsage(stdErr, flags)
314 return 1
315 }
316
317 if rc, sockCfg := validateListens(listens, stdErr); rc != 0 {
318 return rc
319 } else {
320 ctx = sock.WithConfig(ctx, sockCfg)
321 }
322
323 rt := wazero.NewRuntimeWithConfig(ctx, rtc)
324 defer rt.Close(ctx)
325
326 // Because we are running a binary directly rather than embedding in an application,
327 // we default to wiring up commonly used OS functionality.
328 conf := wazero.NewModuleConfig().
329 WithStdout(stdOut).
330 WithStderr(stdErr).
331 WithStdin(os.Stdin).
332 WithRandSource(rand.Reader).
333 WithFSConfig(fsConfig).
334 WithSysNanosleep().
335 WithSysNanotime().
336 WithSysWalltime().
337 WithArgs(append([]string{wasmExe}, wasmArgs...)...)
338 for i := 0; i < len(env); i += 2 {
339 conf = conf.WithEnv(env[i], env[i+1])
340 }
341
342 guest, err := rt.CompileModule(compilationCtx, wasm)
343 if err != nil {
344 fmt.Fprintf(stdErr, "error compiling wasm binary: %v\n", err)
345 return 1
346 }
347
348 switch detectImports(guest.ImportedFunctions()) {
349 case modeWasi:
350 wasi_snapshot_preview1.MustInstantiate(ctx, rt)
351 _, err = rt.InstantiateModule(ctx, guest, conf)
352 case modeWasiUnstable:
353 // Instantiate the current WASI functions under the wasi_unstable
354 // instead of wasi_snapshot_preview1.
355 wasiBuilder := rt.NewHostModuleBuilder("wasi_unstable")
356 wasi_snapshot_preview1.NewFunctionExporter().ExportFunctions(wasiBuilder)
357 _, err = wasiBuilder.Instantiate(ctx)
358 if err == nil {
359 // Instantiate our binary, but using the old import names.
360 _, err = rt.InstantiateModule(ctx, guest, conf)
361 }
362 case modeDefault:
363 _, err = rt.InstantiateModule(ctx, guest, conf)
364 }
365
366 if err != nil {
367 if exitErr, ok := err.(*sys.ExitError); ok {
368 exitCode := exitErr.ExitCode()
369 if exitCode == sys.ExitCodeDeadlineExceeded {
370 fmt.Fprintf(stdErr, "error: %v (timeout %v)\n", exitErr, timeout)
371 }
372 return int(exitCode)
373 }
374 fmt.Fprintf(stdErr, "error instantiating wasm binary: %v\n", err)
375 return 1
376 }
377
378 // We're done, _start was called as part of instantiating the module.
379 return 0
380 }
381
382 func validateMounts(mounts sliceFlag, stdErr logging.Writer) (rc int, rootPath string, config wazero.FSConfig) {
383 config = wazero.NewFSConfig()
384 for _, mount := range mounts {
385 if len(mount) == 0 {
386 fmt.Fprintln(stdErr, "invalid mount: empty string")
387 return 1, rootPath, config
388 }
389
390 readOnly := false
391 if trimmed := strings.TrimSuffix(mount, ":ro"); trimmed != mount {
392 mount = trimmed
393 readOnly = true
394 }
395
396 // TODO: Support wasm paths with colon in them.
397 var dir, guestPath string
398 if clnIdx := strings.LastIndexByte(mount, ':'); clnIdx != -1 {
399 dir, guestPath = mount[:clnIdx], mount[clnIdx+1:]
400 } else {
401 dir = mount
402 guestPath = dir
403 }
404
405 // Eagerly validate the mounts as we know they should be on the host.
406 if abs, err := filepath.Abs(dir); err != nil {
407 fmt.Fprintf(stdErr, "invalid mount: path %q invalid: %v\n", dir, err)
408 return 1, rootPath, config
409 } else {
410 dir = abs
411 }
412
413 if stat, err := os.Stat(dir); err != nil {
414 fmt.Fprintf(stdErr, "invalid mount: path %q error: %v\n", dir, err)
415 return 1, rootPath, config
416 } else if !stat.IsDir() {
417 fmt.Fprintf(stdErr, "invalid mount: path %q is not a directory\n", dir)
418 }
419
420 root := sysfs.DirFS(dir)
421 if readOnly {
422 root = &sysfs.ReadFS{FS: root}
423 }
424
425 config = config.(sysfs.FSConfig).WithSysFSMount(root, guestPath)
426
427 if internalsys.StripPrefixesAndTrailingSlash(guestPath) == "" {
428 rootPath = dir
429 }
430 }
431 return 0, rootPath, config
432 }
433
434 // validateListens returns a non-nil net.Config, if there were any listen flags.
435 func validateListens(listens sliceFlag, stdErr logging.Writer) (rc int, config sock.Config) {
436 for _, listen := range listens {
437 idx := strings.LastIndexByte(listen, ':')
438 if idx < 0 {
439 fmt.Fprintln(stdErr, "invalid listen")
440 return rc, config
441 }
442 port, err := strconv.Atoi(listen[idx+1:])
443 if err != nil {
444 fmt.Fprintln(stdErr, "invalid listen port:", err)
445 return rc, config
446 }
447 if config == nil {
448 config = sock.NewConfig()
449 }
450 config = config.WithTCPListener(listen[:idx], port)
451 }
452 return
453 }
454
455 const (
456 modeDefault importMode = iota
457 modeWasi
458 modeWasiUnstable
459 )
460
461 type importMode uint
462
463 func detectImports(imports []api.FunctionDefinition) importMode {
464 for _, f := range imports {
465 moduleName, _, _ := f.Import()
466 switch moduleName {
467 case wasi_snapshot_preview1.ModuleName:
468 return modeWasi
469 case "wasi_unstable":
470 return modeWasiUnstable
471 }
472 }
473 return modeDefault
474 }
475
476 func maybeHostLogging(ctx context.Context, scopes logging.LogScopes, stdErr logging.Writer) context.Context {
477 if scopes != 0 {
478 return experimental.WithFunctionListenerFactory(ctx, logging.NewHostLoggingListenerFactory(stdErr, scopes))
479 }
480 return ctx
481 }
482
483 func cacheDirFlag(flags *flag.FlagSet) *string {
484 return flags.String("cachedir", "", "Writeable directory for native code compiled from wasm. "+
485 "Contents are re-used for the same version of wazero.")
486 }
487
488 func workersFlag(flags *flag.FlagSet) *int {
489 return flags.Int("workers", 1, "(experimental) Number of desired compilation workers. "+
490 "Increasing this value may improve compilation speed at the cost of higher memory usage.")
491 }
492
493 func maybeUseCacheDir(cacheDir *string, stdErr io.Writer) (int, wazero.CompilationCache) {
494 if dir := *cacheDir; dir != "" {
495 if cache, err := wazero.NewCompilationCacheWithDir(dir); err != nil {
496 fmt.Fprintf(stdErr, "invalid cachedir: %v\n", err)
497 return 1, cache
498 } else {
499 return 0, cache
500 }
501 }
502 return 0, nil
503 }
504
505 func printUsage(stdErr io.Writer) {
506 fmt.Fprintln(stdErr, "wazero CLI")
507 fmt.Fprintln(stdErr)
508 fmt.Fprintln(stdErr, "Usage:\n wazero <command>")
509 fmt.Fprintln(stdErr)
510 fmt.Fprintln(stdErr, "Commands:")
511 fmt.Fprintln(stdErr, " compile\tPre-compiles a WebAssembly binary")
512 fmt.Fprintln(stdErr, " run\t\tRuns a WebAssembly binary")
513 fmt.Fprintln(stdErr, " version\tDisplays the version of wazero CLI")
514 }
515
516 func printCompileUsage(stdErr io.Writer, flags *flag.FlagSet) {
517 fmt.Fprintln(stdErr, "wazero CLI")
518 fmt.Fprintln(stdErr)
519 fmt.Fprintln(stdErr, "Usage:\n wazero compile <options> <path to wasm file>")
520 fmt.Fprintln(stdErr)
521 fmt.Fprintln(stdErr, "Options:")
522 flags.PrintDefaults()
523 }
524
525 func printRunUsage(stdErr io.Writer, flags *flag.FlagSet) {
526 fmt.Fprintln(stdErr, "wazero CLI")
527 fmt.Fprintln(stdErr)
528 fmt.Fprintln(stdErr, "Usage:\n wazero run <options> <path to wasm file> [--] <wasm args>")
529 fmt.Fprintln(stdErr)
530 fmt.Fprintln(stdErr, "Options:")
531 flags.PrintDefaults()
532 }
533
534 func startCPUProfile(stdErr io.Writer, path string) (stopCPUProfile func()) {
535 f, err := os.Create(path)
536 if err != nil {
537 fmt.Fprintf(stdErr, "error creating cpu profile output: %v\n", err)
538 return func() {}
539 }
540
541 if err := pprof.StartCPUProfile(f); err != nil {
542 f.Close()
543 fmt.Fprintf(stdErr, "error starting cpu profile: %v\n", err)
544 return func() {}
545 }
546
547 return func() {
548 defer f.Close()
549 pprof.StopCPUProfile()
550 }
551 }
552
553 func writeHeapProfile(stdErr io.Writer, path string) {
554 f, err := os.Create(path)
555 if err != nil {
556 fmt.Fprintf(stdErr, "error creating memory profile output: %v\n", err)
557 return
558 }
559 defer f.Close()
560 runtime.GC()
561 if err := pprof.WriteHeapProfile(f); err != nil {
562 fmt.Fprintf(stdErr, "error writing memory profile: %v\n", err)
563 }
564 }
565
566 type sliceFlag []string
567
568 func (f *sliceFlag) String() string {
569 return strings.Join(*f, ",")
570 }
571
572 func (f *sliceFlag) Set(s string) error {
573 *f = append(*f, s)
574 return nil
575 }
576
577 type logScopesFlag logging.LogScopes
578
579 func (f *logScopesFlag) String() string {
580 return logging.LogScopes(*f).String()
581 }
582
583 func (f *logScopesFlag) Set(input string) error {
584 for _, s := range strings.Split(input, ",") {
585 switch s {
586 case "":
587 continue
588 case "all":
589 *f |= logScopesFlag(logging.LogScopeAll)
590 case "clock":
591 *f |= logScopesFlag(logging.LogScopeClock)
592 case "filesystem":
593 *f |= logScopesFlag(logging.LogScopeFilesystem)
594 case "memory":
595 *f |= logScopesFlag(logging.LogScopeMemory)
596 case "proc":
597 *f |= logScopesFlag(logging.LogScopeProc)
598 case "poll":
599 *f |= logScopesFlag(logging.LogScopePoll)
600 case "random":
601 *f |= logScopesFlag(logging.LogScopeRandom)
602 case "sock":
603 *f |= logScopesFlag(logging.LogScopeSock)
604 default:
605 return errors.New("not a log scope")
606 }
607 }
608 return nil
609 }