This prepares for exposing operations like Memory.Grow while keeping the ability to trace what did that, by adding a `context.Context` initial parameter. This adds this to all API methods that mutate or return mutated data. Before, we made a change to trace functions and general lifecycle commands, but we missed this part. Ex. We track functions, but can't track what closed the module, changed memory or a mutable constant. Changing to do this now is not only more consistent, but helps us optimize at least the interpreter to help users identify otherwise opaque code that can cause harm. This is critical before we add more functions that can cause harm, such as Memory.Grow. Signed-off-by: Adrian Cole <adrian@tetrate.io>
54 lines
1.4 KiB
Go
54 lines
1.4 KiB
Go
package wasi
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
|
|
"github.com/tetratelabs/wazero"
|
|
"github.com/tetratelabs/wazero/sys"
|
|
)
|
|
|
|
// This is an example of how to use WebAssembly System Interface (WASI) with its simplest function: "proc_exit".
|
|
//
|
|
// See https://github.com/tetratelabs/wazero/tree/main/examples/wasi for another example.
|
|
func Example() {
|
|
// Choose the context to use for function calls.
|
|
ctx := context.Background()
|
|
|
|
// Create a new WebAssembly Runtime.
|
|
r := wazero.NewRuntime()
|
|
|
|
// Instantiate WASI, which implements system I/O such as console output.
|
|
wm, err := InstantiateSnapshotPreview1(ctx, r)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer wm.Close(testCtx)
|
|
|
|
// Override default configuration (which discards stdout).
|
|
config := wazero.NewModuleConfig().WithStdout(os.Stdout)
|
|
|
|
// InstantiateModuleFromCodeWithConfig runs the "_start" function which is like a "main" function.
|
|
_, err = r.InstantiateModuleFromCodeWithConfig(ctx, []byte(`
|
|
(module
|
|
(import "wasi_snapshot_preview1" "proc_exit" (func $wasi.proc_exit (param $rval i32)))
|
|
|
|
(func $main
|
|
i32.const 2 ;; push $rval onto the stack
|
|
call $wasi.proc_exit ;; return a sys.ExitError to the caller
|
|
)
|
|
(export "_start" (func $main))
|
|
)
|
|
`), config.WithName("wasi-demo"))
|
|
|
|
// Print the exit code
|
|
if exitErr, ok := err.(*sys.ExitError); ok {
|
|
fmt.Printf("exit_code: %d\n", exitErr.ExitCode())
|
|
}
|
|
|
|
// Output:
|
|
// exit_code: 2
|
|
}
|