wasmtime
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
Installation
go get -u github.com/bytecodealliance/wasmtime-go@v1.0.0
Be sure to check out theAPI documentation!
This Go library uses CGO to consume the C API of theWasmtimeproject which is written in Rust. Precompiled binaries of Wasmtimeare checked into this repository on tagged releases so you won't have to installWasmtime locally, but it means that this project only works on Linux x86_64,macOS x86_64 , and Windows x86_64 currently. Building on other platforms willneed to arrange to build Wasmtime and useCGO_*
env vars to compile correctly.
This project has been tested with Go 1.13 or later.
If you are a bazel user, add following to your WORKSPACE file:
go_repository( name = "com_github_bytecodealliance_wasmtime_go", importpath = "github.com/bytecodealliance/wasmtime-go", version = "v1.0.0",)
Usage
A "Hello, world!" example of using this package looks like:
package mainimport ( "fmt" "github.com/bytecodealliance/wasmtime-go")func main() { // Almost all operations in wasmtime require a contextual `store` // argument to share, so create that first store := wasmtime.NewStore(wasmtime.NewEngine()) // Compiling modules requires WebAssembly binary input, but the wasmtime // package also supports converting the WebAssembly text format to the // binary format. wasm, err := wasmtime.Wat2Wasm(` (module (import "" "hello" (func $hello)) (func (export "run") (call $hello)) ) `) check(err) // Once we have our binary `wasm` we can compile that into a `*Module` // which represents compiled JIT code. module, err := wasmtime.NewModule(store.Engine, wasm) check(err) // Our `hello.wat` file imports one item, so we create that function // here. item := wasmtime.WrapFunc(store, func() { fmt.Println("Hello from Go!") }) // Next up we instantiate a module which is where we link in all our // imports. We've got one import so we pass that in here. instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{item}) check(err) // After we've instantiated we can lookup our `run` function and call // it. run := instance.GetFunc(store, "run") if run == nil { panic("not a function") } _, err = run.Call(store) check(err)}func check(e error) { if e != nil { panic(e) }}
Contributing
So far this extension has been written by folks who are primarily Rustprogrammers, so it's highly likely that there's some faux pas in terms of Goidioms. Feel free to send a PR to help make things more idiomatic if you seesomething!
To work on this extension locally you'll first want to clone the project:
$ git clone https://github.com/bytecodealliance/wasmtime-go
Next up you'll want to have alocal Wasmtime buildavailable.
You'll need to build at least thewasmtime-c-api
crate, which, at the time ofthis writing, would be:
$ cargo build -p wasmtime-c-api
Once you've got that you can set up the environment of this library with:
$ ./ci/local.sh /path/to/wasmtime
This will create abuild
directory which has the compiled libraries and headerfiles. Next up you can run normal commands such as:
$ go test
And after that you should be good to go!
Documentation¶
Overview¶
Package wasmtime is a WebAssembly runtime for Go powered by Wasmtime.
This package provides everything necessary to compile and execute WebAssemblymodules as part of a Go program. Wasmtime is a JIT compiler written in Rust,and can be found athttps://github.com/bytecodealliance/wasmtime. This packageis a binding to the C API provided by Wasmtime.
The API of this Go package is intended to mirror the Rust API(https://docs.rs/wasmtime) relatively closely, so if you find something isunder-documented here then you may have luck consulting the Rust documentationas well. As always though feel free to file any issues athttps://github.com/bytecodealliance/wasmtime-go/issues/new.
It's also worth pointing out that the authors of this package up to this pointprimarily work in Rust, so if you've got suggestions of how to make this packagemore idiomatic for Go we'd love to hear your thoughts!
Example (Gcd)¶
An example of a wasm module which calculates the GCD of two numbers
store := wasmtime.NewStore(wasmtime.NewEngine())wasm, err := wasmtime.Wat2Wasm(`(module (func $gcd (param i32 i32) (result i32) (local i32) block ;; label = @1 block ;; label = @2 local.get 0 br_if 0 (;@2;) local.get 1 local.set 2 br 1 (;@1;) end loop ;; label = @2 local.get 1 local.get 0 local.tee 2 i32.rem_u local.set 0 local.get 2 local.set 1 local.get 0 br_if 0 (;@2;) end end local.get 2 ) (export "gcd" (func $gcd)))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(store.Engine, wasm)if err != nil {log.Fatal(err)}instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{})if err != nil {log.Fatal(err)}run := instance.GetFunc(store, "gcd")result, err := run.Call(store, 6, 27)if err != nil {log.Fatal(err)}fmt.Printf("gcd(6, 27) = %d\n", result.(int32))
Output:gcd(6, 27) = 3
Example (Hello)¶
An example of instantiating a small wasm module which imports functionalityfrom the host, then calling into wasm which calls back into the host.
// Almost all operations in wasmtime require a contextual `store`// argument to share, so create that firststore := wasmtime.NewStore(wasmtime.NewEngine())// Compiling modules requires WebAssembly binary input, but the wasmtime// package also supports converting the WebAssembly text format to the// binary format.wasm, err := wasmtime.Wat2Wasm(`(module (import "" "hello" (func $hello)) (func (export "run") (call $hello) ))`)if err != nil {log.Fatal(err)}// Once we have our binary `wasm` we can compile that into a `*Module`// which represents compiled JIT code.module, err := wasmtime.NewModule(store.Engine, wasm)if err != nil {log.Fatal(err)}// Our `hello.wat` file imports one item, so we create that function// here.item := wasmtime.WrapFunc(store, func() {fmt.Println("Hello from Go!")})// Next up we instantiate a module which is where we link in all our// imports. We've got one import so we pass that in here.instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{item})if err != nil {log.Fatal(err)}// After we've instantiated we can lookup our `run` function and call// it.run := instance.GetFunc(store, "run")_, err = run.Call(store)if err != nil {log.Fatal(err)}
Output:Hello from Go!
Index¶
- func ModuleValidate(engine *Engine, wasm []byte) error
- func Wat2Wasm(wat string) ([]byte, error)
- type AsExtern
- type AsExternType
- type Caller
- type Config
- func (cfg *Config) CacheConfigLoad(path string) error
- func (cfg *Config) CacheConfigLoadDefault() error
- func (cfg *Config) SetConsumeFuel(enabled bool)
- func (cfg *Config) SetCraneliftDebugVerifier(enabled bool)
- func (cfg *Config) SetCraneliftOptLevel(level OptLevel)
- func (cfg *Config) SetDebugInfo(enabled bool)
- func (cfg *Config) SetEpochInterruption(enable bool)
- func (cfg *Config) SetProfiler(profiler ProfilingStrategy)
- func (cfg *Config) SetStrategy(strat Strategy)
- func (cfg *Config) SetWasmBulkMemory(enabled bool)
- func (cfg *Config) SetWasmMemory64(enabled bool)
- func (cfg *Config) SetWasmMultiMemory(enabled bool)
- func (cfg *Config) SetWasmMultiValue(enabled bool)
- func (cfg *Config) SetWasmReferenceTypes(enabled bool)
- func (cfg *Config) SetWasmSIMD(enabled bool)
- func (cfg *Config) SetWasmThreads(enabled bool)
- type Engine
- type Error
- type ExportType
- type Extern
- type ExternType
- type Frame
- type Func
- type FuncType
- type Global
- type GlobalType
- type ImportType
- type Instance
- type Linker
- func (l *Linker) AllowShadowing(allow bool)
- func (l *Linker) Define(module, name string, item AsExtern) error
- func (l *Linker) DefineFunc(store Storelike, module, name string, f interface{}) error
- func (l *Linker) DefineInstance(store Storelike, module string, instance *Instance) error
- func (l *Linker) DefineModule(store Storelike, name string, module *Module) error
- func (l *Linker) DefineWasi() error
- func (l *Linker) FuncNew(module, name string, ty *FuncType, f func(*Caller, []Val) ([]Val, *Trap)) error
- func (l *Linker) FuncWrap(module, name string, f interface{}) error
- func (l *Linker) Get(store Storelike, module, name string) *Extern
- func (l *Linker) GetDefault(store Storelike, name string) (*Func, error)
- func (l *Linker) Instantiate(store Storelike, module *Module) (*Instance, error)
- type Memory
- func (mem *Memory) AsExtern() C.wasmtime_extern_t
- func (mem *Memory) Data(store Storelike) unsafe.Pointer
- func (mem *Memory) DataSize(store Storelike) uintptr
- func (mem *Memory) Grow(store Storelike, delta uint64) (uint64, error)
- func (mem *Memory) Size(store Storelike) uint64
- func (mem *Memory) Type(store Storelike) *MemoryType
- func (mem *Memory) UnsafeData(store Storelike) []byte
- type MemoryType
- type Module
- type OptLevel
- type ProfilingStrategy
- type Store
- func (store *Store) AddFuel(fuel uint64) error
- func (store *Store) ConsumeFuel(fuel uint64) (uint64, error)
- func (store *Store) Context() *C.wasmtime_context_t
- func (store *Store) FuelConsumed() (uint64, bool)
- func (store *Store) GC()
- func (store *Store) SetEpochDeadline(deadline uint64)
- func (store *Store) SetWasi(wasi *WasiConfig)
- type Storelike
- type Strategy
- type Table
- func (t *Table) AsExtern() C.wasmtime_extern_t
- func (t *Table) Get(store Storelike, idx uint32) (Val, error)
- func (t *Table) Grow(store Storelike, delta uint32, init Val) (uint32, error)
- func (t *Table) Set(store Storelike, idx uint32, val Val) error
- func (t *Table) Size(store Storelike) uint32
- func (t *Table) Type(store Storelike) *TableType
- type TableType
- type Trap
- type TrapCode
- type Val
- type ValKind
- type ValType
- type WasiConfig
- func (c *WasiConfig) InheritArgv()
- func (c *WasiConfig) InheritEnv()
- func (c *WasiConfig) InheritStderr()
- func (c *WasiConfig) InheritStdin()
- func (c *WasiConfig) InheritStdout()
- func (c *WasiConfig) PreopenDir(path, guestPath string) error
- func (c *WasiConfig) SetArgv(argv []string)
- func (c *WasiConfig) SetEnv(keys, values []string)
- func (c *WasiConfig) SetStderrFile(path string) error
- func (c *WasiConfig) SetStdinFile(path string) error
- func (c *WasiConfig) SetStdoutFile(path string) error
Examples¶
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcModuleValidate¶
ModuleValidate validates whether `wasm` would be a valid wasm module according to theconfiguration in `store`
Types¶
typeAsExtern¶
type AsExtern interface {AsExtern()C.wasmtime_extern_t}
AsExtern is an interface for all types which can be imported or exported as an Extern
typeAsExternType¶
type AsExternType interface {AsExternType() *ExternType}
AsExternType is an interface for all types which can be ExternType.
typeCaller¶
type Caller struct {// contains filtered or unexported fields}
Caller is provided to host-defined functions when they're invoked fromWebAssembly.
A `Caller` can be used for `Storelike` arguments to allow recursive executionor creation of wasm objects. Additionally `Caller` can be used to learn aboutthe exports of the calling instance.
func (*Caller)Context¶added inv0.28.0
func (c *Caller) Context() *C.wasmtime_context_t
Implementation of the `Storelike` interface for `Caller`.
typeConfig¶
type Config struct {// contains filtered or unexported fields}
Config holds options used to create an Engine and customize its behavior.
Example (Fuel)¶
Example of limiting a WebAssembly function's runtime using "fuel consumption".
config := wasmtime.NewConfig()config.SetConsumeFuel(true)engine := wasmtime.NewEngineWithConfig(config)store := wasmtime.NewStore(engine)err := store.AddFuel(10000)if err != nil {log.Fatal(err)}// Compile and instantiate a small example with an infinite loop.wasm, err := wasmtime.Wat2Wasm(`(module (func $fibonacci (param $n i32) (result i32) (if (i32.lt_s (local.get $n) (i32.const 2)) (return (local.get $n)) ) (i32.add (call $fibonacci (i32.sub (local.get $n) (i32.const 1))) (call $fibonacci (i32.sub (local.get $n) (i32.const 2))) ) ) (export "fibonacci" (func $fibonacci)))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(store.Engine, wasm)if err != nil {log.Fatal(err)}instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{})if err != nil {log.Fatal(err)}// Invoke `fibonacci` export with higher and higher numbers until we exhaust our fuel.fibonacci := instance.GetFunc(store, "fibonacci")if fibonacci == nil {log.Fatal("Failed to find function export `fibonacci`")}for n := 0; ; n++ {fuelBefore, _ := store.FuelConsumed()output, err := fibonacci.Call(store, n)if err != nil {break}fuelAfter, _ := store.FuelConsumed()fmt.Printf("fib(%d) = %d [consumed %d fuel]\n", n, output, fuelAfter-fuelBefore)err = store.AddFuel(fuelAfter - fuelBefore)if err != nil {log.Fatal(err)}}
Output:fib(0) = 0 [consumed 6 fuel]fib(1) = 1 [consumed 6 fuel]fib(2) = 1 [consumed 26 fuel]fib(3) = 2 [consumed 46 fuel]fib(4) = 3 [consumed 86 fuel]fib(5) = 5 [consumed 146 fuel]fib(6) = 8 [consumed 246 fuel]fib(7) = 13 [consumed 406 fuel]fib(8) = 21 [consumed 666 fuel]fib(9) = 34 [consumed 1086 fuel]fib(10) = 55 [consumed 1766 fuel]fib(11) = 89 [consumed 2866 fuel]fib(12) = 144 [consumed 4646 fuel]fib(13) = 233 [consumed 7526 fuel]
Example (Interrupt)¶
Small example of how you can interrupt the execution of a wasm module toensure that it doesn't run for too long.
// Enable interruptable code via `Config` and then create an interrupt// handle which we'll use later to interrupt running code.config := wasmtime.NewConfig()config.SetEpochInterruption(true)engine := wasmtime.NewEngineWithConfig(config)store := wasmtime.NewStore(engine)store.SetEpochDeadline(1)// Compile and instantiate a small example with an infinite loop.wasm, err := wasmtime.Wat2Wasm(`(module (func (export "run") (loop br 0) ))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(store.Engine, wasm)if err != nil {log.Fatal(err)}instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{})if err != nil {log.Fatal(err)}run := instance.GetFunc(store, "run")if run == nil {log.Fatal("Failed to find function export `run`")}// Spin up a goroutine to send us an interrupt in a secondgo func() {time.Sleep(1 * time.Second)fmt.Println("Interrupting!")engine.IncrementEpoch()}()fmt.Println("Entering infinite loop ...")_, err = run.Call(store)var trap *wasmtime.Trapif !errors.As(err, &trap) {log.Fatal("Unexpected error")}fmt.Println("trap received...")if !strings.Contains(trap.Message(), "wasm trap: interrupt") {log.Fatalf("Unexpected trap: %s", trap.Message())}
Output:Entering infinite loop ...Interrupting!trap received...
Example (Multi)¶
An example of enabling the multi-value feature of WebAssembly andinteracting with multi-value functions.
// Configure our `Store`, but be sure to use a `Config` that enables the// wasm multi-value feature since it's not stable yet.config := wasmtime.NewConfig()config.SetWasmMultiValue(true)store := wasmtime.NewStore(wasmtime.NewEngineWithConfig(config))wasm, err := wasmtime.Wat2Wasm(`(module (func $f (import "" "f") (param i32 i64) (result i64 i32)) (func $g (export "g") (param i32 i64) (result i64 i32) (call $f (local.get 0) (local.get 1)) ) (func $round_trip_many (export "round_trip_many") (param i64 i64 i64 i64 i64 i64 i64 i64 i64 i64) (result i64 i64 i64 i64 i64 i64 i64 i64 i64 i64) local.get 0 local.get 1 local.get 2 local.get 3 local.get 4 local.get 5 local.get 6 local.get 7 local.get 8 local.get 9 ))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(store.Engine, wasm)if err != nil {log.Fatal(err)}callback := wasmtime.WrapFunc(store, func(a int32, b int64) (int64, int32) {return b + 1, a + 1})instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{callback})if err != nil {log.Fatal(err)}g := instance.GetFunc(store, "g")results, err := g.Call(store, 1, 3)if err != nil {log.Fatal(err)}arr := results.([]wasmtime.Val)a := arr[0].I64()b := arr[1].I32()fmt.Printf("> %d %d\n", a, b)if a != 4 {log.Fatal("unexpected value for a")}if b != 2 {log.Fatal("unexpected value for b")}roundTripMany := instance.GetFunc(store, "round_trip_many")results, err = roundTripMany.Call(store, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)if err != nil {log.Fatal(err)}arr = results.([]wasmtime.Val)for i := 0; i < len(arr); i++ {fmt.Printf(" %d", arr[i].Get())if arr[i].I64() != int64(i) {log.Fatal("unexpected value for arr[i]")}}
Output:> 4 2 0 1 2 3 4 5 6 7 8 9
funcNewConfig¶
func NewConfig() *Config
NewConfig creates a new `Config` with all default options configured.
func (*Config)CacheConfigLoad¶added inv0.16.0
CacheConfigLoad enables compiled code caching for this `Config` using the settings specifiedin the configuration file `path`.
For more information about caching and configuration options seehttps://bytecodealliance.github.io/wasmtime/cli-cache.html
func (*Config)CacheConfigLoadDefault¶added inv0.16.0
CacheConfigLoadDefault enables compiled code caching for this `Config` using the default settingsconfiguration can be found.
For more information about caching seehttps://bytecodealliance.github.io/wasmtime/cli-cache.html
func (*Config)SetConsumeFuel¶added inv0.34.0
SetConsumFuel configures whether fuel is enabled
func (*Config)SetCraneliftDebugVerifier¶
SetCraneliftDebugVerifier configures whether the cranelift debug verifier will be active whencranelift is used to compile wasm code.
func (*Config)SetCraneliftOptLevel¶
SetCraneliftOptLevel configures the cranelift optimization level for generated code
func (*Config)SetDebugInfo¶
SetDebugInfo configures whether dwarf debug information for JIT code is enabled
func (*Config)SetEpochInterruption¶added inv0.36.0
SetEpochInterruption enables epoch-based instrumentation of generated code tointerrupt WebAssembly execution when the current engine epoch exceeds adefined threshold.
func (*Config)SetProfiler¶
func (cfg *Config) SetProfiler(profilerProfilingStrategy)
SetProfiler configures what profiler strategy to use for generated code
func (*Config)SetStrategy¶
SetStrategy configures what compilation strategy is used to compile wasm code
func (*Config)SetWasmBulkMemory¶
SetWasmBulkMemory configures whether the wasm bulk memory proposal is enabled
func (*Config)SetWasmMemory64¶added inv0.30.0
SetWasmMemory64 configures whether the wasm memory64 proposal is enabled
func (*Config)SetWasmMultiMemory¶added inv0.29.0
SetWasmMultiMemory configures whether the wasm multi memory proposal is enabled
func (*Config)SetWasmMultiValue¶
SetWasmMultiValue configures whether the wasm multi value proposal is enabled
func (*Config)SetWasmReferenceTypes¶
SetWasmReferenceTypes configures whether the wasm reference types proposal is enabled
func (*Config)SetWasmSIMD¶
SetWasmSIMD configures whether the wasm SIMD proposal is enabled
func (*Config)SetWasmThreads¶
SetWasmThreads configures whether the wasm threads proposal is enabled
typeEngine¶
type Engine struct {// contains filtered or unexported fields}
Engine is an instance of a wasmtime engine which is used to create a `Store`.
Engines are a form of global configuration for wasm compilations and modulesand such.
funcNewEngineWithConfig¶
NewEngineWithConfig creates a new `Engine` with the `Config` provided
Note that once a `Config` is passed to this method it cannot be used again.
func (*Engine)IncrementEpoch¶added inv0.36.0
func (engine *Engine) IncrementEpoch()
IncrementEpoch will increase the current epoch number by 1 within thecurrent engine which will cause any connected stores with their epochdeadline exceeded to now be interrupted.
This method is safe to call from any goroutine.
typeExportType¶
type ExportType struct {// contains filtered or unexported fields}
ExportType is one of the exports component.A module defines a set of exports that become accessible to the host environment once the module has been instantiated.
funcNewExportType¶
func NewExportType(namestring, tyAsExternType) *ExportType
NewExportType creates a new `ExportType` with the `name` and the type provided.
func (*ExportType)Name¶
func (ty *ExportType) Name()string
Name returns the name in the module this export type is exporting
func (*ExportType)Type¶
func (ty *ExportType) Type() *ExternType
Type returns the type of item this export type expects
typeExtern¶
type Extern struct {// contains filtered or unexported fields}
Extern is an external value, which is the runtime representation of an entity that can be imported or exported.It is an address denoting either a function instance, table instance, memory instance, or global instances in the shared store.Read more in [spec](https://webassembly.github.io/spec/core/exec/runtime.html#external-values)
func (*Extern)AsExtern¶
func (e *Extern) AsExtern()C.wasmtime_extern_t
func (*Extern)Type¶
func (e *Extern) Type(storeStorelike) *ExternType
Type returns the type of this export
typeExternType¶
type ExternType struct {// contains filtered or unexported fields}
ExternType means one of external types which classify imports and external values with their respective types.
func (*ExternType)AsExternType¶
func (ty *ExternType) AsExternType() *ExternType
AsExternType returns this type itself
func (*ExternType)FuncType¶
func (ty *ExternType) FuncType() *FuncType
FuncType returns the underlying `FuncType` for this `ExternType` if it's a functiontype. Otherwise returns `nil`.
func (*ExternType)GlobalType¶
func (ty *ExternType) GlobalType() *GlobalType
GlobalType returns the underlying `GlobalType` for this `ExternType` if it's a *global* type.Otherwise returns `nil`.
func (*ExternType)MemoryType¶
func (ty *ExternType) MemoryType() *MemoryType
MemoryType returns the underlying `MemoryType` for this `ExternType` if it's a *memory* type.Otherwise returns `nil`.
func (*ExternType)TableType¶
func (ty *ExternType) TableType() *TableType
TableType returns the underlying `TableType` for this `ExternType` if it's a *table* type.Otherwise returns `nil`.
typeFrame¶
type Frame struct {// contains filtered or unexported fields}
Frame is one of activation frames which carry the return arity n of the respective function,hold the values of its locals (including arguments) in the order corresponding to their static local indices,and a reference to the function’s own module instance
func (*Frame)FuncIndex¶
FuncIndex returns the function index in the wasm module that this frame represents
func (*Frame)FuncOffset¶added inv0.16.0
FuncOffset returns offset of this frame's instruction into the original function
func (*Frame)ModuleName¶
ModuleName returns the name, if available, for this frame's module
func (*Frame)ModuleOffset¶added inv0.16.0
ModuleOffset returns offset of this frame's instruction into the original module
typeFunc¶
type Func struct {// contains filtered or unexported fields}
Func is a function instance, which is the runtime representation of a function.It effectively is a closure of the original function over the runtime module instance of its originating module.The module instance is used to resolve references to other definitions during execution of the function.Read more in [spec](https://webassembly.github.io/spec/core/exec/runtime.html#function-instances)
funcNewFunc¶
NewFunc creates a new `Func` with the given `ty` which, when called, will call `f`
The `ty` given is the wasm type signature of the `Func` to create. When calledthe `f` callback receives two arguments. The first is a `Caller` to learninformation about the calling context and the second is a list of argumentsrepresented as a `Val`. The parameters are guaranteed to match the parameterstypes specified in `ty`.
The `f` callback is expected to produce one of two values. Results can bereturned as an array of `[]Val`. The number and types of these results muchmatch the `ty` given, otherwise the program will panic. The `f` callback canalso produce a trap which will trigger trap unwinding in wasm, and the trapwill be returned to the original caller.
If the `f` callback panics then the panic will be propagated to the calleras well.
funcWrapFunc¶
WrapFunc wraps a native Go function, `f`, as a wasm `Func`.
This function differs from `NewFunc` in that it will determine the typesignature of the wasm function given the input value `f`. The `f` valueprovided must be a Go function. It may take any number of the followingtypes as arguments:
`int32` - a wasm `i32`
`int64` - a wasm `i64`
`float32` - a wasm `f32`
`float64` - a wasm `f64`
`*Caller` - information about the caller's instance
`*Func` - a wasm `funcref`
anything else - a wasm `externref`
The Go function may return any number of values. It can return any number ofprimitive wasm values (integers/floats), and the last return value mayoptionally be `*Trap`. If a `*Trap` returned is `nil` then the other valuesare returned from the wasm function. Otherwise the `*Trap` is returned andit's considered as if the host function trapped.
If the function `f` panics then the panic will be propagated to the caller.
func (*Func)AsExtern¶
func (f *Func) AsExtern()C.wasmtime_extern_t
Implementation of the `AsExtern` interface for `Func`
func (*Func)Call¶
Call invokes this function with the provided `args`.
This variadic function must be invoked with the correct number and type of`args` as specified by the type of this function. This property is checkedat runtime. Each `args` may have one of the following types:
`int32` - a wasm `i32`
`int64` - a wasm `i64`
`float32` - a wasm `f32`
`float64` - a wasm `f64`
`Val` - correspond to a wasm value
`*Func` - a wasm `funcref`
anything else - a wasm `externref`
This function will have one of three results:
1. If the function returns successfully, then the `interface{}` returnargument will be the result of the function. If there were 0 results thenthis value is `nil`. If there was one result then this is that result.Otherwise if there were multiple results then `[]Val` is returned.
2. If this function invocation traps, then the returned `interface{}` valuewill be `nil` and a non-`nil` `*Trap` will be returned with informationabout the trap that happened.
3. If a panic in Go ends up happening somewhere, then this function willpanic.
typeFuncType¶
type FuncType struct {// contains filtered or unexported fields}
FuncType is one of function types which classify the signature of functions, mapping a vector of parameters to a vector of results.They are also used to classify the inputs and outputs of instructions.
funcNewFuncType¶
NewFuncType creates a new `FuncType` with the `kind` provided
func (*FuncType)AsExternType¶
func (ty *FuncType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
typeGlobal¶
type Global struct {// contains filtered or unexported fields}
Global is a global instance, which is the runtime representation of a global variable.It holds an individual value and a flag indicating whether it is mutable.Read more in [spec](https://webassembly.github.io/spec/core/exec/runtime.html#global-instances)
funcNewGlobal¶
func NewGlobal(storeStorelike,ty *GlobalType,valVal,) (*Global,error)
NewGlobal creates a new `Global` in the given `Store` with the specified `ty` andinitial value `val`.
func (*Global)AsExtern¶
func (g *Global) AsExtern()C.wasmtime_extern_t
func (*Global)Type¶
func (g *Global) Type(storeStorelike) *GlobalType
Type returns the type of this global
typeGlobalType¶
type GlobalType struct {// contains filtered or unexported fields}
GlobalType is a ValType, which classify global variables and hold a value and can either be mutable or immutable.
funcNewGlobalType¶
func NewGlobalType(content *ValType, mutablebool) *GlobalType
NewGlobalType creates a new `GlobalType` with the `kind` provided and whether it's`mutable` or not
func (*GlobalType)AsExternType¶
func (ty *GlobalType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
func (*GlobalType)Content¶
func (ty *GlobalType) Content() *ValType
Content returns the type of value stored in this global
func (*GlobalType)Mutable¶
func (ty *GlobalType) Mutable()bool
Mutable returns whether this global type is mutable or not
typeImportType¶
type ImportType struct {// contains filtered or unexported fields}
ImportType is one of the imports componentA module defines a set of imports that are required for instantiation.
funcNewImportType¶
func NewImportType(module, namestring, tyAsExternType) *ImportType
NewImportType creates a new `ImportType` with the given `module` and `name` and the typeprovided.
func (*ImportType)Module¶
func (ty *ImportType) Module()string
Module returns the name in the module this import type is importing
func (*ImportType)Name¶
func (ty *ImportType) Name() *string
Name returns the name in the module this import type is importing.
Note that the returned string may be `nil` with the module linking proposalwhere this field is optional in the import type.
func (*ImportType)Type¶
func (ty *ImportType) Type() *ExternType
Type returns the type of item this import type expects
typeInstance¶
type Instance struct {// contains filtered or unexported fields}
Instance is an instantiated module instance.Once a module has been instantiated as an Instance, any exported function can be invoked externally via its function address funcaddr in the store S and an appropriate list val∗ of argument values.
funcNewInstance¶
NewInstance instantiates a WebAssembly `module` with the `imports` provided.
This function will attempt to create a new wasm instance given the providedimports. This can fail if the wrong number of imports are specified, theimports aren't of the right type, or for other resource-related issues.
This will also run the `start` function of the instance, returning an errorif it traps.
func (*Instance)Exports¶
Exports returns a list of exports from this instance.
Each export is returned as a `*Extern` and lines up with the exports list ofthe associated `Module`.
typeLinker¶
type Linker struct {Engine *Engine// contains filtered or unexported fields}
Linker implements a wasmtime Linking module, which can link instantiated modules together.More details you can see [examples for C](https://bytecodealliance.github.io/wasmtime/examples-c-linking.html) or[examples for Rust](https://bytecodealliance.github.io/wasmtime/examples-rust-linking.html)
Example¶
store := wasmtime.NewStore(wasmtime.NewEngine())// Compile two wasm modules where the first references the secondwasm1, err := wasmtime.Wat2Wasm(`(module (import "wasm2" "double" (func $double (param i32) (result i32))) (func (export "double_and_add") (param i32 i32) (result i32) local.get 0 call $double local.get 1 i32.add ))`)if err != nil {log.Fatal(err)}wasm2, err := wasmtime.Wat2Wasm(`(module (func (export "double") (param i32) (result i32) local.get 0 i32.const 2 i32.mul ))`)if err != nil {log.Fatal(err)}// Next compile both modulesmodule1, err := wasmtime.NewModule(store.Engine, wasm1)if err != nil {log.Fatal(err)}module2, err := wasmtime.NewModule(store.Engine, wasm2)if err != nil {log.Fatal(err)}linker := wasmtime.NewLinker(store.Engine)// The second module is instantiated first since it has no imports, and// then we insert the instance back into the linker under the name// the first module expects.instance2, err := linker.Instantiate(store, module2)if err != nil {log.Fatal(err)}err = linker.DefineInstance(store, "wasm2", instance2)if err != nil {log.Fatal(err)}// And now we can instantiate our first module, executing the result// afterwardsinstance1, err := linker.Instantiate(store, module1)if err != nil {log.Fatal(err)}doubleAndAdd := instance1.GetFunc(store, "double_and_add")result, err := doubleAndAdd.Call(store, 2, 3)if err != nil {log.Fatal(err)}fmt.Print(result.(int32))
Output:7
func (*Linker)AllowShadowing¶
AllowShadowing configures whether names can be redefined after they've already been definedin this linker.
func (*Linker)Define¶
Define defines a new item in this linker with the given module/name pair. Returnsan error if shadowing is disallowed and the module/name is already defined.
func (*Linker)DefineFunc¶
DefineFunc acts as a convenience wrapper to calling Define and WrapFunc.
Returns an error if shadowing is disabled and the name is already defined.
func (*Linker)DefineInstance¶
DefineInstance defines all exports of an instance provided under the module name provided.
Returns an error if shadowing is disabled and names are already defined.
func (*Linker)DefineModule¶added inv0.25.0
DefineModule defines automatic instantiations of the module in this linker.
The `name` of the module is the name within the linker, and the `module` isthe one that's being instantiated. This function automatically handlesWASI Commands and Reactors for instantiation and initialization. For moreinformation see the Rust documentation --https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.module.
func (*Linker)DefineWasi¶
DefineWasi links a WASI module into this linker, ensuring that all exported functionsare available for linking.
Returns an error if shadowing is disabled and names are already defined.
func (*Linker)FuncNew¶added inv0.29.0
func (l *Linker) FuncNew(module, namestring, ty *FuncType, f func(*Caller, []Val) ([]Val, *Trap))error
FuncNew defines a function in this linker in the same style as `NewFunc`
Note that this function does not require a `Storelike`, which isintentional. This function can be used to insert store-independent functionsinto this linker which allows this linker to be used for instantiatingmodules in multiple different stores.
Returns an error if shadowing is disabled and the name is already defined.
func (*Linker)FuncWrap¶added inv0.29.0
FuncWrap defines a function in this linker in the same style as `WrapFunc`
Note that this function does not require a `Storelike`, which isintentional. This function can be used to insert store-independent functionsinto this linker which allows this linker to be used for instantiatingmodules in multiple different stores.
Returns an error if shadowing is disabled and the name is already defined.
func (*Linker)Get¶added inv0.28.0
GetOneByName loads an item by name from this linker.
If the item isn't defined then nil is returned, otherwise the item isreturned.
func (*Linker)GetDefault¶added inv0.25.0
GetDefault acquires the "default export" of the named module in this linker.
If there is no default item then an error is returned, otherwise the defaultfunction is returned.
For more information see the Rust documentation --https://docs.wasmtime.dev/api/wasmtime/struct.Linker.html#method.get_default.
func (*Linker)Instantiate¶
Instantiate instantiates a module with all imports defined in this linker.
Returns an error if the instance's imports couldn't be satisfied, had thewrong types, or if a trap happened executing the start function.
typeMemory¶
type Memory struct {// contains filtered or unexported fields}
Memory instance is the runtime representation of a linear memory.It holds a vector of bytes and an optional maximum size, if one was specified at the definition site of the memory.Read more in [spec](https://webassembly.github.io/spec/core/exec/runtime.html#memory-instances)In wasmtime-go, you can get the vector of bytes by the unsafe pointer of memory from `Memory.Data()`, or go style byte slice from `Memory.UnsafeData()`
Example¶
An example of working with the Memory type to read/write wasm memory.
// Create our `Store` context and then compile a module and create an// instance from the compiled module all in one go.store := wasmtime.NewStore(wasmtime.NewEngine())wasm, err := wasmtime.Wat2Wasm(`(module (memory (export "memory") 2 3) (func (export "size") (result i32) (memory.size)) (func (export "load") (param i32) (result i32) (i32.load8_s (local.get 0)) ) (func (export "store") (param i32 i32) (i32.store8 (local.get 0) (local.get 1)) ) (data (i32.const 0x1000) "\01\02\03\04"))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(store.Engine, wasm)if err != nil {log.Fatal(err)}instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{})if err != nil {log.Fatal(err)}// Load up our exports from the instancememory := instance.GetExport(store, "memory").Memory()sizeFn := instance.GetFunc(store, "size")loadFn := instance.GetFunc(store, "load")storeFn := instance.GetFunc(store, "store")// some helper functions we'll use belowcall32 := func(f *wasmtime.Func, args ...interface{}) int32 {ret, err := f.Call(store, args...)if err != nil {log.Fatal(err)}return ret.(int32)}call := func(f *wasmtime.Func, args ...interface{}) {_, err := f.Call(store, args...)if err != nil {log.Fatal(err)}}assertTraps := func(f *wasmtime.Func, args ...interface{}) {_, err := f.Call(store, args...)_, ok := err.(*wasmtime.Trap)if !ok {log.Fatal("expected a trap")}}assert := func(b bool) {if !b {log.Fatal("assertion failed")}}// Check the initial memory sizes/contentsassert(memory.Size(store) == 2)assert(memory.DataSize(store) == 0x20000)buf := memory.UnsafeData(store)assert(buf[0] == 0)assert(buf[0x1000] == 1)assert(buf[0x1003] == 4)assert(call32(sizeFn) == 2)assert(call32(loadFn, 0) == 0)assert(call32(loadFn, 0x1000) == 1)assert(call32(loadFn, 0x1003) == 4)assert(call32(loadFn, 0x1ffff) == 0)assertTraps(loadFn, 0x20000)// We can mutate memory as wellbuf[0x1003] = 5call(storeFn, 0x1002, 6)assertTraps(storeFn, 0x20000, 0)assert(buf[0x1002] == 6)assert(buf[0x1003] == 5)assert(call32(loadFn, 0x1002) == 6)assert(call32(loadFn, 0x1003) == 5)// And like wasm instructions, we can grow memory_, err = memory.Grow(store, 1)assert(err == nil)assert(memory.Size(store) == 3)assert(memory.DataSize(store) == 0x30000)assert(call32(loadFn, 0x20000) == 0)call(storeFn, 0x20000, 0)assertTraps(loadFn, 0x30000)assertTraps(storeFn, 0x30000, 0)// Memory can fail to grow_, err = memory.Grow(store, 1)assert(err != nil)_, err = memory.Grow(store, 0)assert(err == nil)// Ensure that `memory` lives long enough to cover all our usages of// using its internal buffer we read from `UnsafeData()`runtime.KeepAlive(memory)// Finally we can also create standalone memories to get imported by// wasm modules too.memorytype := wasmtime.NewMemoryType(5, true, 5)memory2, err := wasmtime.NewMemory(store, memorytype)assert(err == nil)assert(memory2.Size(store) == 5)_, err = memory2.Grow(store, 1)assert(err != nil)_, err = memory2.Grow(store, 0)assert(err == nil)
funcNewMemory¶
func NewMemory(storeStorelike, ty *MemoryType) (*Memory,error)
NewMemory creates a new `Memory` in the given `Store` with the specified `ty`.
func (*Memory)AsExtern¶
func (mem *Memory) AsExtern()C.wasmtime_extern_t
func (*Memory)Type¶
func (mem *Memory) Type(storeStorelike) *MemoryType
Type returns the type of this memory
func (*Memory)UnsafeData¶added inv0.16.2
UnsafeData returns the raw memory backed by this `Memory` as a byte slice (`[]byte`).
This is not a safe method to call, hence the "unsafe" in the name. The byteslice returned from this function is not managed by the Go garbage collector.You need to ensure that `m`, the original `Memory`, lives longer than the`[]byte` returned.
Note that you may need to use `runtime.KeepAlive` to keep the original memory`m` alive for long enough while you're using the `[]byte` slice. If the`[]byte` slice is used after `m` is GC'd then that is undefined behavior.
typeMemoryType¶
type MemoryType struct {// contains filtered or unexported fields}
MemoryType is one of Memory types which classify linear memories and their size range.The limits constrain the minimum and optionally the maximum size of a memory. The limits are given in units of page size.
funcNewMemoryType¶
func NewMemoryType(minuint32, has_maxbool, maxuint32) *MemoryType
NewMemoryType creates a new `MemoryType` with the limits on size provided
The `min` value is the minimum size, in WebAssembly pages, of this memory.The `has_max` boolean indicates whether a maximum size is present, and if so`max` is used as the maximum size of memory, in wasm pages.
Note that this will create a 32-bit memory type, the default outside of thememory64 proposal.
funcNewMemoryType64¶added inv0.30.0
func NewMemoryType64(minuint64, has_maxbool, maxuint64) *MemoryType
NewMemoryType64 creates a new 64-bit `MemoryType` with the provided limits
The `min` value is the minimum size, in WebAssembly pages, of this memory.The `has_max` boolean indicates whether a maximum size is present, and if so`max` is used as the maximum size of memory, in wasm pages.
Note that 64-bit memories are part of the memory64 WebAssembly proposal.
func (*MemoryType)AsExternType¶
func (ty *MemoryType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
func (*MemoryType)Is64¶added inv0.30.0
func (ty *MemoryType) Is64()bool
Is64 returns whether this is a 64-bit memory or not.
func (*MemoryType)Maximum¶added inv0.30.0
func (ty *MemoryType) Maximum() (bool,uint64)
Maximum returns the maximum size of this memory, in WebAssembly pages, ifspecified.
If the maximum size is not specified then `(false, 0)` is returned, otherwise`(true, N)` is returned where `N` is the listed maximum size of this memory.
func (*MemoryType)Minimum¶added inv0.30.0
func (ty *MemoryType) Minimum()uint64
Minimum returns the minimum size of this memory, in WebAssembly pages
typeModule¶
type Module struct {// contains filtered or unexported fields}
Module is a module which collects definitions for types, functions, tables, memories, and globals.In addition, it can declare imports and exports and provide initialization logic in the form of data and element segments or a start function.Modules organized WebAssembly programs as the unit of deployment, loading, and compilation.
Example (Serialize)¶
Small example of how to serialize a compiled wasm module, and theninstantiate it from the compilation artifacts.
// Configure the initial compilation environment.engine := wasmtime.NewEngine()// Compile the wasm module into an in-memory instance of a `Module`.wasm, err := wasmtime.Wat2Wasm(`(module (func $hello (import "" "hello")) (func (export "run") (call $hello)))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(engine, wasm)if err != nil {log.Fatal(err)}bytes, err := module.Serialize()if err != nil {log.Fatal(err)}// Configure the initial compilation environment.store := wasmtime.NewStore(wasmtime.NewEngine())// Deserialize the compiled module.module, err = wasmtime.NewModuleDeserialize(store.Engine, bytes)if err != nil {log.Fatal(err)}// Here we handle the imports of the module, which in this case is our// `helloFunc` callback.helloFunc := wasmtime.WrapFunc(store, func() {fmt.Println("Calling back...")fmt.Println("> Hello World!")})// Once we've got that all set up we can then move to the instantiation// phase, pairing together a compiled module as well as a set of imports.// Note that this is where the wasm `start` function, if any, would run.instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{helloFunc})if err != nil {log.Fatal(err)}// Next we poke around a bit to extract the `run` function from the module.run := instance.GetFunc(store, "run")if run == nil {log.Fatal("Failed to find function export `run`")}// And last but not least we can call it!fmt.Println("Calling export...")_, err = run.Call(store)if err != nil {log.Fatal(err)}
Output:Calling export...Calling back...> Hello World!
funcNewModule¶
NewModule compiles a new `Module` from the `wasm` provided with the given configurationin `engine`.
funcNewModuleDeserialize¶added inv0.20.0
NewModuleDeserialize decodes and deserializes in-memory bytes previouslyproduced by `module.Serialize()`.
This function does not take a WebAssembly binary as input. It takesas input the results of a previous call to `Serialize()`, and only takesthat as input.
If deserialization is successful then a compiled module is returned,otherwise nil and an error are returned.
Note that to deserialize successfully the bytes provided must have beenproduced with an `Engine` that has the same compilation options as theprovided engine, and from the same version of this library.
funcNewModuleDeserializeFile¶added inv0.30.0
NewModuleDeserializeFile is the same as `NewModuleDeserialize` except thatthe bytes are read from a file instead of provided as an argument.
funcNewModuleFromFile¶
NewModuleFromFile reads the contents of the `file` provided and interprets them as either thetext format or the binary format for WebAssembly.
Afterwards delegates to the `NewModule` constructor with the contents read.
func (*Module)Exports¶
func (m *Module) Exports() []*ExportType
Exports returns a list of `ExportType` which are the items that will beexported by this module after instantiation.
func (*Module)Imports¶
func (m *Module) Imports() []*ImportType
Imports returns a list of `ImportType` which are the items imported bythis module and are required for instantiation
func (*Module)Serialize¶added inv0.20.0
Serialize will convert this in-memory compiled module into a list of bytes.
The purpose of this method is to extract an artifact which can be storedelsewhere from this `Module`. The returned bytes can, for example, be storedon disk or in an object store. The `NewModuleDeserialize` function can beused to deserialize the returned bytes at a later date to get the moduleback.
typeOptLevel¶
type OptLevelC.wasmtime_opt_level_t
OptLevel decides what degree of optimization wasmtime will perform on generated machine code
const (// OptLevelNone will perform no optimizationsOptLevelNoneOptLevel =C.WASMTIME_OPT_LEVEL_NONE// OptLevelSpeed will optimize machine code to be as fast as possibleOptLevelSpeedOptLevel =C.WASMTIME_OPT_LEVEL_SPEED// OptLevelSpeedAndSize will optimize machine code for speed, but also optimize// to be small, sometimes at the cost of speed.OptLevelSpeedAndSizeOptLevel =C.WASMTIME_OPT_LEVEL_SPEED_AND_SIZE)
typeProfilingStrategy¶
type ProfilingStrategyC.wasmtime_profiling_strategy_t
ProfilingStrategy decides what sort of profiling to enable, if any.
const (// ProfilingStrategyNone means no profiler will be usedProfilingStrategyNoneProfilingStrategy =C.WASMTIME_PROFILING_STRATEGY_NONE// ProfilingStrategyJitdump will use the "jitdump" linux supportProfilingStrategyJitdumpProfilingStrategy =C.WASMTIME_PROFILING_STRATEGY_JITDUMP)
typeStore¶
type Store struct {// The `Engine` that this store uses for compilation and environment// settings.Engine *Engine// contains filtered or unexported fields}
Store is a general group of wasm instances, and many objectsmust all be created with and reference the same `Store`
func (*Store)AddFuel¶added inv0.34.0
AddFuel adds fuel to this context's store for wasm to consume while executing.
For this method to work fuel consumption must be enabled via`Config.SetConsumeFuel`. By default a store starts with 0 fuelfor wasm to execute with (meaning it will immediately trap).This function must be called for the store to havesome fuel to allow WebAssembly to execute.
Note that at this time when fuel is entirely consumed it will causewasm to trap. More usages of fuel are planned for the future.
If fuel is not enabled within this store then an error is returned.
func (*Store)ConsumeFuel¶added inv0.34.0
ConsumeFuel attempts to manually consume fuel from the store.
If fuel consumption is not enabled via `Config.SetConsumeFuel` thenthis function will return an error. Otherwise this will attempt to consumethe specified amount of `fuel` from the store. If successful the remainingamount of fuel is returned. If `fuel` couldn't be consumedthen an error is returned.
Also note that fuel, if enabled, must be originally configured via`Store.AddFuel`.
func (*Store)Context¶added inv0.28.0
func (store *Store) Context() *C.wasmtime_context_t
Implementation of the `Storelike` interface
func (*Store)FuelConsumed¶added inv0.34.0
FuelConsumed returns the amount of fuel consumed by this context's storeexecution so far.
If fuel consumption is not enabled via `Config.SetConsumeFuel` then this functionwill return false. Otherwise true is returned and the fuel parameter isfilled in with fuel consumed so far.
Also note that fuel, if enabled, must be originally configured via `Store.AddFuel`.
func (*Store)GC¶added inv0.20.0
func (store *Store) GC()
GC will clean up any `externref` values that are no longer actuallyreferenced.
This function is not required to be called for correctness, it's only anoptimization if desired to clean out any extra `externref` values.
func (*Store)SetEpochDeadline¶added inv0.36.0
SetEpochDeadline will configure the relative deadline, from the currentengine's epoch number, after which wasm code will be interrupted.
func (*Store)SetWasi¶added inv0.28.0
func (store *Store) SetWasi(wasi *WasiConfig)
SetWasi will configure the WASI state to use for instances within this`Store`.
The `wasi` argument cannot be reused for another `Store`, it's consumed bythis function.
typeStorelike¶added inv0.28.0
type Storelike interface {// Returns the wasmtime context pointer this store is attached to.Context() *C.wasmtime_context_t}
Storelike represents types that can be used to contextually reference a`Store`.
This interface is implemented by `*Store` and `*Caller` and is pervasivelyused throughout this library. You'll want to pass one of those two objectsinto functions that take a `Storelike`.
typeStrategy¶
type StrategyC.wasmtime_strategy_t
Strategy is the compilation strategies for wasmtime
const (// StrategyAuto will let wasmtime automatically pick an appropriate compilation strategyStrategyAutoStrategy =C.WASMTIME_STRATEGY_AUTO// StrategyCranelift will force wasmtime to use the Cranelift backendStrategyCraneliftStrategy =C.WASMTIME_STRATEGY_CRANELIFT)
typeTable¶
type Table struct {// contains filtered or unexported fields}
Table is a table instance, which is the runtime representation of a table.
It holds a vector of reference types and an optional maximum size, if one wasspecified in the table type at the table’s definition site.Read more in [spec](https://webassembly.github.io/spec/core/exec/runtime.html#table-instances)
funcNewTable¶added inv0.16.2
NewTable creates a new `Table` in the given `Store` with the specified `ty`.
The `ty` must be a reference type (`funref` or `externref`) and `init`is the initial value for all table slots and must have the type specified by`ty`.
func (*Table)AsExtern¶
func (t *Table) AsExtern()C.wasmtime_extern_t
func (*Table)Get¶added inv0.16.2
Get gets an item from this table from the specified index.
Returns an error if the index is out of bounds, or returns a value (whichmay be internally null) if the index is in bounds corresponding to the entryat the specified index.
func (*Table)Grow¶added inv0.16.2
Grow grows this table by the number of units specified, using thespecified initializer value for new slots.
Returns an error if the table failed to grow, or the previous size of thetable if growth was successful.
func (*Table)Set¶added inv0.16.2
Set sets an item in this table at the specified index.
Returns an error if the index is out of bounds.
typeTableType¶
type TableType struct {// contains filtered or unexported fields}
TableType is one of table types which classify tables over elements of element types within a size range.
funcNewTableType¶
NewTableType creates a new `TableType` with the `element` type provided aswell as limits on its size.
The `min` value is the minimum size, in elements, of this table. The`has_max` boolean indicates whether a maximum size is present, and if so`max` is used as the maximum size of the table, in elements.
func (*TableType)AsExternType¶
func (ty *TableType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
typeTrap¶
type Trap struct {// contains filtered or unexported fields}
Trap is the trap instruction which represents the occurrence of a trap.Traps are bubbled up through nested instruction sequences, ultimately reducing the entire program to a single trap instruction, signalling abrupt termination.
typeTrapCode¶added inv0.29.0
type TrapCodeuint8
TrapCode is the code of an instruction trap.
const (// StackOverflow: the current stack space was exhausted.StackOverflowTrapCode =iota// MemoryOutOfBounds: out-of-bounds memory access.MemoryOutOfBounds// HeapMisaligned: a wasm atomic operation was presented with a not-naturally-aligned linear-memory address.HeapMisaligned// TableOutOfBounds: out-of-bounds access to a table.TableOutOfBounds// IndirectCallToNull: indirect call to a null table entry.IndirectCallToNull// BadSignature: signature mismatch on indirect call.BadSignature// IntegerOverflow: an integer arithmetic operation caused an overflow.IntegerOverflow// IntegerDivisionByZero: integer division by zero.IntegerDivisionByZero// BadConversionToInteger: failed float-to-int conversion.BadConversionToInteger// UnreachableCodeReached: code that was supposed to have been unreachable was reached.UnreachableCodeReached// Interrupt: execution has been interrupted.Interrupt)
typeVal¶
type Val struct {// contains filtered or unexported fields}
Val is a primitive numeric value.Moreover, in the definition of programs, immutable sequences of values occur to represent more complex data, such as text strings or other vectors.
funcValExternref¶added inv0.19.0
func ValExternref(val interface{})Val
ValExternref converts a go value to a externref Val
Using `externref` is a way to pass arbitrary Go data into a WebAssemblymodule for it to store. Later, when you get a `Val`, you can extract the typewith the `Externref()` method.
funcValFuncref¶added inv0.19.0
ValFuncref converts a Func to a funcref Val
Note that `f` can be `nil` to represent a null `funcref`.
func (Val)Externref¶added inv0.19.0
func (vVal) Externref() interface{}
Externref returns the underlying value if this is an `externref`, or panics.
Note that a null `externref` is returned as `nil`.
Example¶
Small example of how to use `externref`s.
config := wasmtime.NewConfig()config.SetWasmReferenceTypes(true)store := wasmtime.NewStore(wasmtime.NewEngineWithConfig(config))wasm, err := wasmtime.Wat2Wasm(`(module (table $table (export "table") 10 externref) (global $global (export "global") (mut externref) (ref.null extern)) (func (export "func") (param externref) (result externref) local.get 0 ))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(store.Engine, wasm)if err != nil {log.Fatal(err)}instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{})if err != nil {log.Fatal(err)}// Create a new `externref` value.value := wasmtime.ValExternref("Hello, World!")// The `externref`'s wrapped data should be the string "Hello, World!".externRef := value.Externref()if externRef != "Hello, World!" {log.Fatal("unexpected value")}// Lookup the `table` export.table := instance.GetExport(store, "table").Table()// Set `table[3]` to our `externref`.err = table.Set(store, 3, value)if err != nil {log.Fatal(err)}// `table[3]` should now be our `externref`.tableValue, err := table.Get(store, 3)if err != nil {log.Fatal(err)}if tableValue.Externref() != externRef {log.Fatal("unexpected value in table")}// Lookup the `global` export.global := instance.GetExport(store, "global").Global()// Set the global to our `externref`.err = global.Set(store, value)if err != nil {log.Fatal(err)}// Get the global, and it should return our `externref` again.globalValue := global.Get(store)if globalValue.Externref() != externRef {log.Fatal("unexpected value in global")}// Lookup the `func` export.fn := instance.GetFunc(store, "func")// And call it!result, err := fn.Call(store, value)if err != nil {log.Fatal(err)}// `func` returns the same reference we gave it, so `results` should be// our `externref`.if result != externRef {log.Fatal("unexpected value from func")}
func (Val)Funcref¶added inv0.19.0
Funcref returns the underlying function if this is a `funcref`, or panics.
Note that a null `funcref` is returned as `nil`.
func (Val)Get¶
func (vVal) Get() interface{}
Get returns the underlying 64-bit float if this is an `f64`, or panics.
typeValKind¶
type ValKindC.wasm_valkind_t
ValKind enumeration of different kinds of value types
const (// KindI32 is the types i32 classify 32 bit integers. Integers are not inherently signed or unsigned, their interpretation is determined by individual operations.KindI32ValKind =C.WASM_I32// KindI64 is the types i64 classify 64 bit integers. Integers are not inherently signed or unsigned, their interpretation is determined by individual operations.KindI64ValKind =C.WASM_I64// KindF32 is the types f32 classify 32 bit floating-point data. They correspond to the respective binary floating-point representations, also known as single and double precision, as defined by the IEEE 754-2019 standard.KindF32ValKind =C.WASM_F32// KindF64 is the types f64 classify 64 bit floating-point data. They correspond to the respective binary floating-point representations, also known as single and double precision, as defined by the IEEE 754-2019 standard.KindF64ValKind =C.WASM_F64// TODO: UnknownKindExternrefValKind =C.WASM_ANYREF// KindFuncref is the infinite union of all function types.KindFuncrefValKind =C.WASM_FUNCREF)
typeValType¶
type ValType struct {// contains filtered or unexported fields}
ValType means one of the value types, which classify the individual values that WebAssembly code can compute with and the values that a variable accepts.
funcNewValType¶
NewValType creates a new `ValType` with the `kind` provided
typeWasiConfig¶
type WasiConfig struct {// contains filtered or unexported fields}
Example¶
An example of linking WASI to the runtime in order to interact with the system.It uses the WAT code fromhttps://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-tutorial.md#web-assembly-text-example
dir, err := os.MkdirTemp("", "out")if err != nil {log.Fatal(err)}defer os.RemoveAll(dir)stdoutPath := filepath.Join(dir, "stdout")engine := wasmtime.NewEngine()// Create our modulewasm, err := wasmtime.Wat2Wasm(`(module ;; Import the required fd_write WASI function which will write the given io vectors to stdout ;; The function signature for fd_write is: ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32))) (memory 1) (export "memory" (memory 0)) ;; Write 'hello world\n' to memory at an offset of 8 bytes ;; Note the trailing newline which is required for the text to appear (data (i32.const 8) "hello world\n") (func $main (export "_start") ;; Creating a new io vector within linear memory (i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string (i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string (call $fd_write (i32.const 1) ;; file_descriptor - 1 for stdout (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0 (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one. (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written ) drop ;; Discard the number of bytes written from the top of the stack ))`)if err != nil {log.Fatal(err)}module, err := wasmtime.NewModule(engine, wasm)if err != nil {log.Fatal(err)}// Create a linker with WASI functions defined within itlinker := wasmtime.NewLinker(engine)err = linker.DefineWasi()if err != nil {log.Fatal(err)}// Configure WASI imports to write stdout into a file, and then create// a `Store` using this wasi configuration.wasiConfig := wasmtime.NewWasiConfig()wasiConfig.SetStdoutFile(stdoutPath)store := wasmtime.NewStore(engine)store.SetWasi(wasiConfig)instance, err := linker.Instantiate(store, module)if err != nil {log.Fatal(err)}// Run the functionnom := instance.GetFunc(store, "_start")_, err = nom.Call(store)if err != nil {log.Fatal(err)}// Print WASM stdoutout, err := os.ReadFile(stdoutPath)if err != nil {log.Fatal(err)}fmt.Print(string(out))
Output:hello world
funcNewWasiConfig¶
func NewWasiConfig() *WasiConfig
func (*WasiConfig)InheritArgv¶
func (c *WasiConfig) InheritArgv()
func (*WasiConfig)InheritEnv¶
func (c *WasiConfig) InheritEnv()
func (*WasiConfig)InheritStderr¶
func (c *WasiConfig) InheritStderr()
func (*WasiConfig)InheritStdin¶
func (c *WasiConfig) InheritStdin()
func (*WasiConfig)InheritStdout¶
func (c *WasiConfig) InheritStdout()
func (*WasiConfig)PreopenDir¶
func (c *WasiConfig) PreopenDir(path, guestPathstring)error
func (*WasiConfig)SetArgv¶
func (c *WasiConfig) SetArgv(argv []string)
SetArgv will explicitly configure the argv for this WASI configuration.Note that this field can only be set, it cannot be read
func (*WasiConfig)SetEnv¶
func (c *WasiConfig) SetEnv(keys, values []string)
SetEnv configures environment variables to be returned for this WASI configuration.The pairs provided must be an iterable list of key/value pairs of environment variables.Note that this field can only be set, it cannot be read
func (*WasiConfig)SetStderrFile¶
func (c *WasiConfig) SetStderrFile(pathstring)error
func (*WasiConfig)SetStdinFile¶
func (c *WasiConfig) SetStdinFile(pathstring)error
func (*WasiConfig)SetStdoutFile¶
func (c *WasiConfig) SetStdoutFile(pathstring)error