Documentation ¶
Overview ¶
Package wasmtime is a WebAssembly runtime for Go powered by Wasmtime.
This package provides everything necessary to compile and execute WebAssembly modules as part of a Go program. Wasmtime is a JIT compiler written in Rust, and can be found at https://github.com/bytecodealliance/wasmtime. This package is 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 is under-documented here then you may have luck consulting the Rust documentation as well. As always though feel free to file any issues at https://github.com/bytecodealliance/wasmtime-go/issues/new.
It's also worth pointing out that the authors of this package up to this point primarily work in Rust, so if you've got suggestions of how to make this package more idiomatic for Go we'd love to hear your thoughts!
Example ¶
An example of instantiating a small wasm module which imports functionality from 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 first store := NewStore(NewEngine()) // Compiling modules requires WebAssembly binary input, but the wasmtime // package also supports converting the WebAssembly text format to the // binary format. wasm, err := 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 := NewModule(store.Engine, wasm) check(err) // Our `hello.wat` file imports one item, so we create that function // here. item := 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 := NewInstance(store, module, []*Extern{item.AsExtern()}) check(err) // After we've instantiated we can lookup our `run` function and call // it. run := instance.GetExport("run").Func() _, err = run.Call() check(err)
Output: Hello from Go!
Example (Gcd) ¶
An example of a wasm module which calculates the GCD of two numbers
store := NewStore(NewEngine()) wasm, err := Wat2Wasm(GcdWat) check(err) module, err := NewModule(store.Engine, wasm) check(err) instance, err := NewInstance(store, module, []*Extern{}) check(err) run := instance.GetExport("gcd").Func() result, err := run.Call(6, 27) check(err) fmt.Printf("gcd(6, 27) = %d\n", result.(int32))
Output: gcd(6, 27) = 3
Example (Memory) ¶
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. wasmtimeStore := NewStore(NewEngine()) wasm, err := 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") ) `) check(err) module, err := NewModule(wasmtimeStore.Engine, wasm) check(err) instance, err := NewInstance(wasmtimeStore, module, []*Extern{}) check(err) // Load up our exports from the instance memory := instance.GetExport("memory").Memory() size := instance.GetExport("size").Func() load := instance.GetExport("load").Func() store := instance.GetExport("store").Func() // some helper functions we'll use below call32 := func(f *Func, args ...interface{}) int32 { ret, err := f.Call(args...) check(err) return ret.(int32) } call := func(f *Func, args ...interface{}) { _, err := f.Call(args...) check(err) } assertTraps := func(f *Func, args ...interface{}) { _, err := f.Call(args...) _, ok := err.(*Trap) if !ok { panic("expected a trap") } } // Check the initial memory sizes/contents assert(memory.Size() == 2) assert(memory.DataSize() == 0x20000) buf := memory.UnsafeData() assert(buf[0] == 0) assert(buf[0x1000] == 1) assert(buf[0x1003] == 4) assert(call32(size) == 2) assert(call32(load, 0) == 0) assert(call32(load, 0x1000) == 1) assert(call32(load, 0x1003) == 4) assert(call32(load, 0x1ffff) == 0) assertTraps(load, 0x20000) // We can mutate memory as well buf[0x1003] = 5 call(store, 0x1002, 6) assertTraps(store, 0x20000, 0) assert(buf[0x1002] == 6) assert(buf[0x1003] == 5) assert(call32(load, 0x1002) == 6) assert(call32(load, 0x1003) == 5) // And like wasm instructions, we can grow memory assert(memory.Grow(1)) assert(memory.Size() == 3) assert(memory.DataSize() == 0x30000) assert(call32(load, 0x20000) == 0) call(store, 0x20000, 0) assertTraps(load, 0x30000) assertTraps(store, 0x30000, 0) // Memory can fail to grow assert(!memory.Grow(1)) assert(memory.Grow(0)) // 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 := NewMemoryType(Limits{Min: 5, Max: 5}) memory2 := NewMemory(wasmtimeStore, memorytype) assert(memory2.Size() == 5) assert(!memory2.Grow(1)) assert(memory2.Grow(0))
Output:
Example (Multi) ¶
An example of enabling the multi-value feature of WebAssembly and interacting 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 := NewConfig() config.SetWasmMultiValue(true) store := NewStore(NewEngineWithConfig(config)) wasm, err := 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) ) `) check(err) module, err := NewModule(store.Engine, wasm) check(err) callback := WrapFunc(store, func(a int32, b int64) (int64, int32) { return b + 1, a + 1 }) instance, err := NewInstance(store, module, []*Extern{callback.AsExtern()}) check(err) g := instance.GetExport("g").Func() results, err := g.Call(1, 3) check(err) arr := results.([]Val) a := arr[0].I64() b := arr[1].I32() fmt.Printf("> %d %d\n", a, b) assert(a == 4) assert(b == 2) roundTripMany := instance.GetExport("round_trip_many").Func() results, err = roundTripMany.Call(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) check(err) arr = results.([]Val) for i := 0; i < len(arr); i++ { fmt.Printf(" %d", arr[i].Get()) assert(arr[i].I64() == int64(i)) }
Output: > 4 2 0 1 2 3 4 5 6 7 8 9
Example (Wasi) ¶
An example of linking WASI to the runtime in order to interact with the system. It uses the WAT code from https://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-tutorial.md#web-assembly-text-example
dir, err := ioutil.TempDir("", "out") check(err) defer os.RemoveAll(dir) stdoutPath := filepath.Join(dir, "stdout") engine := NewEngine() store := NewStore(engine) linker := NewLinker(store) // Configure WASI imports to write stdout into a file. wasiConfig := NewWasiConfig() wasiConfig.SetStdoutFile(stdoutPath) // Set the version to the same as in the WAT. wasi, err := NewWasiInstance(store, wasiConfig, "wasi_snapshot_preview1") check(err) // Link WASI err = linker.DefineWasi(wasi) check(err) // Create our module wasm, err := Wat2Wasm(TextWat) check(err) module, err := NewModule(store.Engine, wasm) check(err) instance, err := linker.Instantiate(module) check(err) // Run the function nom := instance.GetExport("_start").Func() _, err = nom.Call() check(err) // Print WASM stdout out, err := ioutil.ReadFile(stdoutPath) check(err) fmt.Print(string(out))
Output: hello world
Index ¶
- Constants
- func ModuleValidate(store *Store, 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) SetCraneliftDebugVerifier(enabled bool)
- func (cfg *Config) SetCraneliftOptLevel(level OptLevel)
- func (cfg *Config) SetDebugInfo(enabled bool)
- func (cfg *Config) SetInterruptable(interruptable bool)
- func (cfg *Config) SetProfiler(profiler ProfilingStrategy) error
- func (cfg *Config) SetStrategy(strat Strategy) error
- func (cfg *Config) SetWasmBulkMemory(enabled bool)
- func (cfg *Config) SetWasmModuleLinking(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 InstanceType
- type InterruptHandle
- type Limits
- type Linker
- func (l *Linker) AllowShadowing(allow bool)
- func (l *Linker) Define(module, name string, item AsExtern) error
- func (l *Linker) DefineFunc(module, name string, f interface{}) error
- func (l *Linker) DefineInstance(module string, instance *Instance) error
- func (l *Linker) DefineWasi(instance *WasiInstance) error
- func (l *Linker) Instantiate(module *Module) (*Instance, error)
- type Memory
- type MemoryType
- type Module
- type ModuleType
- type OptLevel
- type ProfilingStrategy
- type Store
- type Strategy
- type Table
- type TableType
- type Trap
- 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
- type WasiInstance
Examples ¶
Constants ¶
const LimitsMaxNone = 0xffffffff
LimitsMaxNone is the value for the Max field in Limits
Variables ¶
This section is empty.
Functions ¶
func ModuleValidate ¶
ModuleValidate validates whether `wasm` would be a valid wasm module according to the configuration in `store`
Types ¶
type AsExtern ¶
type AsExtern interface {
AsExtern() *Extern
}
AsExtern is an interface for all types which can be imported or exported as an Extern
type AsExternType ¶
type AsExternType interface {
AsExternType() *ExternType
}
AsExternType is an interface for all types which can be ExternType.
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config holds options used to create an Engine and customize its behavior.
func NewConfig ¶
func NewConfig() *Config
NewConfig creates a new `Config` with all default options configured.
func (*Config) CacheConfigLoad ¶ added in v0.16.0
CacheConfigLoad enables compiled code caching for this `Config` using the settings specified in the configuration file `path`.
For more information about caching and configuration options see https://bytecodealliance.github.io/wasmtime/cli-cache.html
func (*Config) CacheConfigLoadDefault ¶ added in v0.16.0
CacheConfigLoadDefault enables compiled code caching for this `Config` using the default settings configuration can be found.
For more information about caching see https://bytecodealliance.github.io/wasmtime/cli-cache.html
func (*Config) SetCraneliftDebugVerifier ¶
SetCraneliftDebugVerifier configures whether the cranelift debug verifier will be active when cranelift 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) SetInterruptable ¶ added in v0.16.0
SetInterruptable configures whether generated wasm code can be interrupted via interrupt handles.
func (*Config) SetProfiler ¶
func (cfg *Config) SetProfiler(profiler ProfilingStrategy) error
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) SetWasmModuleLinking ¶ added in v0.22.0
SetWasmModuleLinking configures whether the wasm module linking 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
type Engine ¶
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 modules and such.
func NewEngine ¶
func NewEngine() *Engine
NewEngine creates a new `Engine` with default configuration.
func NewEngineWithConfig ¶
NewEngineWithConfig creates a new `Engine` with the `Config` provided
Note that once a `Config` is passed to this method it cannot be used again.
type ExportType ¶
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.
func NewExportType ¶
func NewExportType(name string, ty AsExternType) *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
type Extern ¶
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) Instance ¶ added in v0.22.0
Instance returns a Instance if this export is a module or nil otherwise
func (*Extern) Module ¶ added in v0.22.0
Module returns a Module if this export is a module or nil otherwise
type ExternType ¶
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 function type. 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`.
type Frame ¶
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 in v0.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 in v0.16.0
ModuleOffset returns offset of this frame's instruction into the original module
type Func ¶
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)
func NewFunc ¶
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 called the `f` callback receives two arguments. The first is a `Caller` to learn information about the calling context and the second is a list of arguments represented as a `Val`. The parameters are guaranteed to match the parameters types specified in `ty`.
The `f` callback is expected to produce one of two values. Results can be returned as an array of `[]Val`. The number and types of these results much match the `ty` given, otherwise the program will panic. The `f` callback can also produce a trap which will trigger trap unwinding in wasm, and the trap will be returned to the original caller.
If the `f` callback panics then the panic will be propagated to the caller as well.
func WrapFunc ¶
WrapFunc wraps a native Go function, `f`, as a wasm `Func`.
This function differs from `NewFunc` in that it will determine the type signature of the wasm function given the input value `f`. The `f` value provided must be a Go function. It may take any number of the following types as arguments:
`int32` - a wasm `i32`
`int64` - a wasm `i64`
`float32` - a wasm `f32`
`float64` - a wasm `f32`
`*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 of primitive wasm values (integers/floats), and the last return value may optionally be `*Trap`. If a `*Trap` returned is `nil` then the other values are returned from the wasm function. Otherwise the `*Trap` is returned and it's considered as if the host function trapped.
If the function `f` panics then the panic will be propagated to the caller.
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 checked at 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{}` return argument will be the result of the function. If there were 0 results then this 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{}` value will be `nil` and a non-`nil` `*Trap` will be returned with information about the trap that happened.
3. If a panic in Go ends up happening somewhere, then this function will panic.
func (*Func) ParamArity ¶
ParamArity returns the numer of parameters this function expects
func (*Func) ResultArity ¶
ResultArity returns the numer of results this function produces
type FuncType ¶
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.
func NewFuncType ¶
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`
type Global ¶
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)
type GlobalType ¶
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.
func NewGlobalType ¶
func NewGlobalType(content *ValType, mutable bool) *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
type ImportType ¶
type ImportType struct {
// contains filtered or unexported fields
}
ImportType is one of the imports component A module defines a set of imports that are required for instantiation.
func NewImportType ¶
func NewImportType(module, name string, ty AsExternType) *ImportType
NewImportType creates a new `ImportType` with the given `module` and `name` and the type provided.
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 proposal where 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
type Instance ¶
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.
func NewInstance ¶
NewInstance instantiates a WebAssembly `module` with the `imports` provided.
This function will attempt to create a new wasm instance given the provided imports. This can fail if the wrong number of imports are specified, the imports aren't of the right type, or for other resource-related issues.
This will also run the `start` function of the instance, returning an error if 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 of the associated `Module`.
func (*Instance) GetExport ¶
GetExport attempts to find an export on this instance by `name`
May return `nil` if this instance has no export named `name`
func (*Instance) Type ¶ added in v0.22.0
func (i *Instance) Type() *InstanceType
Type returns an `InstanceType` that corresponds for this instance.
type InstanceType ¶ added in v0.22.0
type InstanceType struct {
// contains filtered or unexported fields
}
InstanceType describes the exports of an instance.
func (*InstanceType) AsExternType ¶ added in v0.22.0
func (ty *InstanceType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
func (*InstanceType) Exports ¶ added in v0.22.0
func (ty *InstanceType) Exports() []*ExportType
Exports returns a list of `ExportType` items which are the items that will be exported by this instance after instantiation.
type InterruptHandle ¶ added in v0.16.0
type InterruptHandle struct {
// contains filtered or unexported fields
}
InterruptHandle is used to interrupt the execution of currently running wasm code.
For more information see https://bytecodealliance.github.io/wasmtime/api/wasmtime/struct.Store.html#method.interrupt_handle
func (*InterruptHandle) Interrupt ¶ added in v0.16.0
func (i *InterruptHandle) Interrupt()
Interrupt interrupts currently executing WebAssembly code, if it's currently running, or interrupts wasm the next time it starts running.
For more information see https://bytecodealliance.github.io/wasmtime/api/wasmtime/struct.Store.html#method.interrupt_handle
type Limits ¶
type Limits struct { // The minimum size of this resource, in units specified by the resource // itself. Min uint32 // The maximum size of this resource, in units specified by the resource // itself. // // A value of LimitsMaxNone will mean that there is no maximum. Max uint32 }
Limits is the resource limits specified for a TableType and MemoryType
type Linker ¶
type Linker struct { Store *Store // 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 := NewStore(NewEngine()) // Compile two wasm modules where the first references the second wasm1, err := 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) ) `) check(err) wasm2, err := Wat2Wasm(` (module (func (export "double") (param i32) (result i32) local.get 0 i32.const 2 i32.mul) ) `) check(err) // Next compile both modules module1, err := NewModule(store.Engine, wasm1) check(err) module2, err := NewModule(store.Engine, wasm2) check(err) linker := NewLinker(store) // 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(module2) check(err) err = linker.DefineInstance("wasm2", instance2) check(err) // And now we can instantiate our first module, executing the result // afterwards instance1, err := linker.Instantiate(module1) check(err) doubleAndAdd := instance1.GetExport("double_and_add").Func() result, err := doubleAndAdd.Call(2, 3) check(err) fmt.Print(result.(int32))
Output: 7
func (*Linker) AllowShadowing ¶
AllowShadowing configures whether names can be redefined after they've already been defined in this linker.
func (*Linker) Define ¶
Define defines a new item in this linker with the given module/name pair. Returns an 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) DefineWasi ¶
func (l *Linker) DefineWasi(instance *WasiInstance) error
DefineWasi links a WASI module into this linker, ensuring that all exported functions are available for linking.
Returns an error if shadowing is disabled and names are already defined.
func (*Linker) Instantiate ¶
Instantiate instantates a module with all imports defined in this linker.
Returns an error if the instance's imports couldn't be satisfied, had the wrong types, or if a trap happened executing the start function.
type Memory ¶
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()`
func NewMemory ¶
func NewMemory(store *Store, ty *MemoryType) *Memory
NewMemory creates a new `Memory` in the given `Store` with the specified `ty`.
func (*Memory) UnsafeData ¶ added in v0.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 byte slice 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.
type MemoryType ¶
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.
func NewMemoryType ¶
func NewMemoryType(limits Limits) *MemoryType
NewMemoryType creates a new `MemoryType` with the `limits` on size provided
func (*MemoryType) AsExternType ¶
func (ty *MemoryType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
func (*MemoryType) Limits ¶
func (ty *MemoryType) Limits() Limits
Limits returns the limits on the size of this memory type
type Module ¶
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.
func NewModule ¶
NewModule compiles a new `Module` from the `wasm` provided with the given configuration in `engine`.
func NewModuleDeserialize ¶ added in v0.20.0
NewModuleDeserialize decodes and deserializes in-memory bytes previously produced by `module.Serialize()`.
This function does not take a WebAssembly binary as input. It takes as input the results of a previous call to `Serialize()`, and only takes that 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 beeen produced with an `Engine` that has the same commpilation options as the provided engine, and from the same version of this library.
func NewModuleFromFile ¶
NewModuleFromFile reads the contents of the `file` provided and interprets them as either the text 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` items which are the items that will be exported by this module after instantiation.
func (*Module) Imports ¶
func (m *Module) Imports() []*ImportType
Imports returns a list of `ImportType` items which are the items imported by this module and are required for instantiation.
func (*Module) Serialize ¶ added in v0.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 stored elsewhere from this `Module`. The returned bytes can, for example, be stored on disk or in an object store. The `NewModuleDeserialize` function can be used to deserialize the returned bytes at a later date to get the module back.
func (*Module) Type ¶ added in v0.22.0
func (m *Module) Type() *ModuleType
Type returns a `ModuleType` that corresponds for this module.
type ModuleType ¶ added in v0.22.0
type ModuleType struct {
// contains filtered or unexported fields
}
ModuleType describes the imports/exports of a module.
func (*ModuleType) AsExternType ¶ added in v0.22.0
func (ty *ModuleType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
func (*ModuleType) Exports ¶ added in v0.22.0
func (m *ModuleType) Exports() []*ExportType
Exports returns a list of `ExportType` items which are the items that will be exported by this module after instantiation.
func (*ModuleType) Imports ¶ added in v0.22.0
func (m *ModuleType) Imports() []*ImportType
Imports returns a list of `ImportType` items which are the items imported by this module and are required for instantiation.
type OptLevel ¶
type OptLevel C.wasmtime_opt_level_t
OptLevel decides what degree of optimization wasmtime will perform on generated machine code
const ( // OptLevelNone will perform no optimizations OptLevelNone OptLevel = C.WASMTIME_OPT_LEVEL_NONE // OptLevelSpeed will optimize machine code to be as fast as possible OptLevelSpeed OptLevel = C.WASMTIME_OPT_LEVEL_SPEED // OptLevelSpeedAndSize will optimize machine code for speed, but also optimize // to be small, sometimes at the cost of speed. OptLevelSpeedAndSize OptLevel = C.WASMTIME_OPT_LEVEL_SPEED_AND_SIZE )
type ProfilingStrategy ¶
type ProfilingStrategy C.wasmtime_profiling_strategy_t
ProfilingStrategy decides what sort of profiling to enable, if any.
const ( // ProfilingStrategyNone means no profiler will be used ProfilingStrategyNone ProfilingStrategy = C.WASMTIME_PROFILING_STRATEGY_NONE // ProfilingStrategyJitdump will use the "jitdump" linux support ProfilingStrategyJitdump ProfilingStrategy = C.WASMTIME_PROFILING_STRATEGY_JITDUMP )
type Store ¶
type Store struct { Engine *Engine // contains filtered or unexported fields }
Store is a general group of wasm instances, and many objects must all be created with and reference the same `Store`
func (*Store) GC ¶ added in v0.20.0
func (store *Store) GC()
GC will clean up any `externref` values that are no longer actually referenced.
This function is not required to be called for correctness, it's only an optimization if desired to clean out any extra `externref` values.
func (*Store) InterruptHandle ¶ added in v0.16.0
func (store *Store) InterruptHandle() (*InterruptHandle, error)
type Strategy ¶
type Strategy C.wasmtime_strategy_t
Strategy is the compilation strategies for wasmtime
const ( // StrategyAuto will let wasmtime automatically pick an appropriate compilation strategy StrategyAuto Strategy = C.WASMTIME_STRATEGY_AUTO // StrategyCranelift will force wasmtime to use the Cranelift backend StrategyCranelift Strategy = C.WASMTIME_STRATEGY_CRANELIFT // StrategyLightbeam will force wasmtime to use the lightbeam backend StrategyLightbeam Strategy = C.WASMTIME_STRATEGY_LIGHTBEAM )
type Table ¶
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 was specified 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)
func NewTable ¶ added in v0.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) Get ¶ added in v0.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 (which may be internally null) if the index is in bounds corresponding to the entry at the specified index.
func (*Table) Grow ¶ added in v0.16.2
Grow grows this table by the number of units specified, using the specified initializer value for new slots.
Returns an error if the table failed to grow, or the previous size of the table if growth was successful.
func (*Table) Set ¶ added in v0.16.2
Set sets an item in this table at the specified index.
Returns an error if the index is out of bounds.
type TableType ¶
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.
func NewTableType ¶
NewTableType creates a new `TableType` with the `element` type provided as well as `limits` on its size.
func (*TableType) AsExternType ¶
func (ty *TableType) AsExternType() *ExternType
AsExternType converts this type to an instance of `ExternType`
type Trap ¶
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.
type Val ¶
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.
func ValExternref ¶ added in v0.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 WebAssembly module for it to store. Later, when you get a `Val`, you can extract the type with the `Externref()` method.
func ValFuncref ¶ added in v0.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 in v0.19.0
func (v Val) Externref() interface{}
Externref returns the underlying value if this is an `externref`, or panics.
Note that a null `externref` is returned as `nil`.
func (Val) Funcref ¶ added in v0.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 (v Val) Get() interface{}
Get returns the underlying 64-bit float if this is an `f64`, or panics.
type ValKind ¶
type ValKind C.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. KindI32 ValKind = 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. KindI64 ValKind = 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. KindF32 ValKind = 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. KindF64 ValKind = C.WASM_F64 // TODO: Unknown KindExternref ValKind = C.WASM_ANYREF // KindFuncref is the infinite union of all function types. KindFuncref ValKind = C.WASM_FUNCREF )
type ValType ¶
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.
func NewValType ¶
NewValType creates a new `ValType` with the `kind` provided
type WasiConfig ¶
type WasiConfig struct {
// contains filtered or unexported fields
}
func NewWasiConfig ¶
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, guestPath string) 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(path string) error
func (*WasiConfig) SetStdinFile ¶
func (c *WasiConfig) SetStdinFile(path string) error
func (*WasiConfig) SetStdoutFile ¶
func (c *WasiConfig) SetStdoutFile(path string) error
type WasiInstance ¶
type WasiInstance struct {
// contains filtered or unexported fields
}
func NewWasiInstance ¶
func NewWasiInstance(store *Store, config *WasiConfig, name string) (*WasiInstance, error)
NewWasiInstance creates a new instance of WASI with the given configuration.
The version of WASI must be explicitly requested via `name`.
func (*WasiInstance) BindImport ¶
func (i *WasiInstance) BindImport(imp *ImportType) *Extern
BindImport attempts to bind the `imp` import provided, returning an Extern suitable for satisfying the import if one can be found.
If `imp` isn't defined by this instance of WASI then `nil` is returned.
Source Files ¶
- config.go
- doc.go
- engine.go
- error.go
- exporttype.go
- extern.go
- externtype.go
- ffi.go
- freelist.go
- func.go
- functype.go
- global.go
- globaltype.go
- importtype.go
- instance.go
- instancetype.go
- limits.go
- linker.go
- maybe_gc_no.go
- memory.go
- memorytype.go
- module.go
- moduletype.go
- slab.go
- store.go
- table.go
- tabletype.go
- trap.go
- val.go
- valtype.go
- wasi.go
- wat2wasm.go