wa-lang.org/wazero@v1.0.2/experimental/fs_example_test.go (about) 1 package experimental_test 2 3 import ( 4 "context" 5 _ "embed" 6 "fmt" 7 "log" 8 "os" 9 10 "wa-lang.org/wazero" 11 "wa-lang.org/wazero/experimental" 12 "wa-lang.org/wazero/imports/wasi_snapshot_preview1" 13 ) 14 15 // fsWasm was generated by the following: 16 // 17 // cd testdata; wat2wasm --debug-names fs.wat 18 // 19 //go:embed testdata/fs.wasm 20 var fsWasm []byte 21 22 // This is a basic example of overriding the file system via WithFS. The main 23 // goal is to show how it is configured. 24 func Example_withFS() { 25 ctx := context.Background() 26 27 r := wazero.NewRuntime(ctx) 28 defer r.Close(ctx) // This closes everything this Runtime created. 29 30 wasi_snapshot_preview1.MustInstantiate(ctx, r) 31 32 // Instantiate a module exporting a WASI function that uses the filesystem. 33 mod, err := r.InstantiateModuleFromBinary(ctx, fsWasm) 34 if err != nil { 35 log.Panicln(err) 36 } 37 38 // Setup the filesystem overlay, noting that it can fail if the directory is 39 // invalid and must be closed. 40 ctx, closer := experimental.WithFS(ctx, os.DirFS(".")) 41 defer closer.Close(ctx) 42 43 fdPrestatDirName := mod.ExportedFunction("fd_prestat_dir_name") 44 fd := 3 // after stderr 45 pathLen := 1 // length we expect the path to be. 46 pathOffset := 0 // where to write pathLen bytes. 47 48 // By default, there are no pre-opened directories. If the configuration 49 // was wrong, this call would fail. 50 results, err := fdPrestatDirName.Call(ctx, uint64(fd), uint64(pathOffset), uint64(pathLen)) 51 if err != nil { 52 log.Panicln(err) 53 } 54 if results[0] != 0 { 55 log.Panicf("received errno %d\n", results[0]) 56 } 57 58 // Try to read the path! 59 if path, ok := mod.Memory().Read(ctx, uint32(pathOffset), uint32(pathLen)); !ok { 60 log.Panicln("out of memory reading path") 61 } else { 62 fmt.Println(string(path)) 63 } 64 65 // Output: 66 // / 67 }