wasmer

package
v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2021 License: MIT Imports: 8 Imported by: 61

Documentation

Overview

Package wasmer is a complete and mature WebAssembly runtime for Go based on Wasmer (https://github.com/wasmerio/wasmer).

Features

• Easy to use: The wasmer API mimics the standard WebAssembly API,

• Fast: wasmer executes the WebAssembly modules as fast as possible, close to native speed,

• Safe: All calls to WebAssembly will be fast, but more importantly, complete safe and sandboxed.

Quick Introduction

The wasmer Go package brings the required API to execute WebAssembly modules. In a nutshell, wasmer compiles the WebAssembly module into compiled code, and then executes it. wasmer is designed to work in various environments and platforms: From nano single-board computers to large and powerful servers, including more exotic ones. To address those requirements, Wasmer provides 2 engines and 3 compilers.

Succinctly, an engine is responsible to drive the compilation and the execution of a WebAssembly module. By extension, a headless engine can only execute a WebAssembly module, i.e. a module that has previously been compiled, or compiled, serialized and deserialized. By default, the wasmer package comes with 2 headless engines:

• Universal, the compiled machine code lives in memory,

• Dylib, the compiled machine code lives in a shared object file (.so, .dylib, or .dll), and is natively executed.

The wasmer Go packages comes with 3 compilers:

• Singlepass: Super fast compilation times, slower execution times. Not prone to JIT-bombs. Ideal for blockchains.

• Cranelift: Fast compilation times, fast execution times. Ideal for development.

• LLVM: Slow compilation times, very fast execution times (close to native). Ideal for production.

WebAssembly C API standard

Wasmer —the runtime— is written in Rust; C and C++ bindings exist. This Go package relies on the so-called wasm_c_api, https://github.com/WebAssembly/wasm-c-api, which is the new standard C API, implemented inside Wasmer as the Wasmer C API, https://wasmerio.github.io/wasmer/crates/wasmer_c_api/. This standard is characterized as a living standard. The API is not yet stable, even though it shows maturity overtime. However, the Wasmer C API provides some extensions, like the wasi_* or wasmer_* types and functions, which aren't yet defined by the standard. The Go package commits to keep a semantic versioning over the API, regardless what happens with the C API.

Examples

The very basic example is the following

// Let's assume we don't have WebAssembly bytes at hand. We
// will write WebAssembly manually.
wasmBytes := []byte(`
	(module
	  (type (func (param i32 i32) (result i32)))
	  (func (type 0)
	    local.get 0
	    local.get 1
	    i32.add)
	  (export "sum" (func 0)))
`)

// Create an Engine
engine := wasmer.NewEngine()

// Create a Store
store := wasmer.NewStore(engine)

// Let's compile the module.
module, err := wasmer.NewModule(store, wasmBytes)

if err != nil {
	fmt.Println("Failed to compile module:", err)
}

// Create an empty import object.
importObject := wasmer.NewImportObject()

// Let's instantiate the WebAssembly module.
instance, err := wasmer.NewInstance(module, importObject)

if err != nil {
	panic(fmt.Sprintln("Failed to instantiate the module:", err))
}

// Now let's execute the `sum` function.
sum, err := instance.Exports.GetFunction("sum")

if err != nil {
	panic(fmt.Sprintln("Failed to get the `add_one` function:", err))
}

result, err := sum(1, 2)

if err != nil {
	panic(fmt.Sprintln("Failed to call the `add_one` function:", err))
}

fmt.Println("Results of `sum`:", result)

// Output:
// Results of `sum`: 3

That's it. Now explore the API! Some pointers for the adventurers:

• The basic elements are Module and Instance,

• Exports of an instance are represented by the Exports type,

• Maybe your module needs to import Function, Memory, Global or Table? Well, there is the ImportObject for that!

Index

Constants

View Source
const (
	// Represents the Cranelift compiler.
	CRANELIFT = CompilerKind(C.CRANELIFT)

	// Represents the LLVM compiler.
	LLVM = CompilerKind(C.LLVM)

	// Represents the Singlepass compiler.
	SINGLEPASS = CompilerKind(C.SINGLEPASS)
)
View Source
const (
	// Represents the Universal engine.
	UNIVERSAL = EngineKind(C.UNIVERSAL)

	// Represents the Dylib engine.
	DYLIB = EngineKind(C.DYLIB)

	// Deprecated constant. Please use UNIVERSAL instead.
	JIT = UNIVERSAL

	// Deprecated constant. Please use DYLIB instead.
	NATIVE = DYLIB
)
View Source
const (
	// Represents an extern of kind function.
	FUNCTION = ExternKind(C.WASM_EXTERN_FUNC)

	// Represents an extern of kind global.
	GLOBAL = ExternKind(C.WASM_EXTERN_GLOBAL)

	// Represents an extern of kind table.
	TABLE = ExternKind(C.WASM_EXTERN_TABLE)

	// Represents an extern of kind memory.
	MEMORY = ExternKind(C.WASM_EXTERN_MEMORY)
)
View Source
const (
	// Represents a global that is immutable.
	IMMUTABLE = GlobalMutability(C.WASM_CONST)

	// Represents a global that is mutable.
	MUTABLE = GlobalMutability(C.WASM_VAR)
)
View Source
const (
	// A 32-bit integer. In WebAssembly, integers are
	// sign-agnostic, i.E. this can either be signed or unsigned.
	I32 = ValueKind(C.WASM_I32)

	// A 64-bit integer. In WebAssembly, integers are
	// sign-agnostic, i.E. this can either be signed or unsigned.
	I64 = ValueKind(C.WASM_I64)

	// A 32-bit float.
	F32 = ValueKind(C.WASM_F32)

	// A 64-bit float.
	F64 = ValueKind(C.WASM_F64)

	// An externref value which can hold opaque data to the
	// WebAssembly instance itself.
	AnyRef = ValueKind(C.WASM_ANYREF)

	// A first-class reference to a WebAssembly function.
	FuncRef = ValueKind(C.WASM_FUNCREF)
)
View Source
const (
	// Latest version. It's a “floating” version, i.e. it's an
	// alias to the latest version. Using this version is a way to
	// ensure that modules will run only if they come with the
	// latest WASI version (in case of security issues for
	// instance), by just updating the runtime.
	WASI_VERSION_LATEST = WasiVersion(C.LATEST)

	// Represents the wasi_unstable version.
	WASI_VERSION_SNAPSHOT0 = WasiVersion(C.SNAPSHOT0)

	// Represents the wasi_snapshot_preview1 version.
	WASI_VERSION_SNAPSHOT1 = WasiVersion(C.SNAPSHOT1)

	// Represents an invalid version.
	WASI_VERSION_INVALID = WasiVersion(C.INVALID_VERSION)
)
View Source
const WasmMaxPages = uint(0x10000)

Represents the maximum number of pages.

View Source
const WasmMinPages = uint(0x100)

Represents the minimum number of pages.

View Source
const WasmPageSize = uint(0x10000)

Represents a memory page size.

Variables

This section is empty.

Functions

func IsCompilerAvailable added in v1.0.3

func IsCompilerAvailable(compiler CompilerKind) bool

IsCompilerAvailable checks that the given compiler is available in this current version of `wasmer-go`.

IsCompilerAvailable(CRANELIFT)

func IsEngineAvailable added in v1.0.3

func IsEngineAvailable(engine EngineKind) bool

IsEngineAvailable checks that the given engine is available in this current version of `wasmer-go`.

IsEngineAvailable(UNIVERSAL)

func LimitMaxUnbound

func LimitMaxUnbound() uint32

LimitMaxUnbound returns the value used to represent an unbound limit, i.e. when a limit only has a min but not a max. See Limit.

func ValidateModule

func ValidateModule(store *Store, bytes []byte) error

ValidateModule validates a new Module against the given Store.

It takes two arguments, the Store and the WebAssembly module as a byte array. The function returns an error describing why the bytes are invalid, otherwise it returns nil.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
err := wasmer.ValidateModule(store, wasmBytes)

isValid := err != nil

func Wat2Wasm

func Wat2Wasm(wat string) ([]byte, error)

Wat2Wasm parses a string as either WAT code or a binary Wasm module.

See https://webassembly.github.io/spec/core/text/index.html.

Note: This is not part of the standard Wasm C API. It is Wasmer specific.

wat := "(module)"
wasm, _ := Wat2Wasm(wat)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)

Types

type CompilerKind added in v1.0.3

type CompilerKind C.wasmer_compiler_t

CompilerKind represents the possible compiler types.

func (CompilerKind) String added in v1.0.3

func (self CompilerKind) String() string

Strings returns the CompilerKind as a string.

CRANELIFT.String() // "cranelift"
LLVM.String() // "llvm"

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config holds the compiler and the Engine used by the Store.

func NewConfig

func NewConfig() *Config

NewConfig instantiates and returns a new Config.

config := NewConfig()

func (*Config) UseCraneliftCompiler

func (self *Config) UseCraneliftCompiler() *Config

UseCraneliftCompiler sets the compiler to Cranelift in the configuration.

config := NewConfig()
config.UseCraneliftCompiler()

This method might fail if the Cranelift compiler isn't available. Check `IsCompilerAvailable` to learn more.

func (*Config) UseDylibEngine added in v1.0.4

func (self *Config) UseDylibEngine() *Config

UseDylibEngine sets the engine to Dylib in the configuration.

config := NewConfig()
config.UseDylibEngine()

This method might fail if the Dylib engine isn't available. Check `IsEngineAvailable` to learn more.

func (*Config) UseJITEngine

func (self *Config) UseJITEngine() *Config

UseJITEngine is a deprecated method. Please use UseUniversalEngine instead.

func (*Config) UseLLVMCompiler

func (self *Config) UseLLVMCompiler() *Config

UseLLVMCompiler sets the compiler to LLVM in the configuration.

config := NewConfig()
config.UseLLVMCompiler()

This method might fail if the LLVM compiler isn't available. Check `IsCompilerAvailable` to learn more.

func (*Config) UseNativeEngine

func (self *Config) UseNativeEngine() *Config

UseNativeEngine is a deprecated method. Please use UseDylibEngine instead.

func (*Config) UseSinglepassCompiler added in v1.0.3

func (self *Config) UseSinglepassCompiler() *Config

UseSinglepassCompiler sets the compiler to Singlepass in the configuration.

config := NewConfig()
config.UseSinglepassCompiler()

This method might fail if the Singlepass compiler isn't available. Check `IsCompilerAvailable` to learn more.

func (*Config) UseTarget

func (self *Config) UseTarget(target *Target) *Config

Use a specific target for doing cross-compilation.

triple, _ := NewTriple("aarch64-unknown-linux-gnu")
cpuFeatures := NewCpuFeatures()
target := NewTarget(triple, cpuFeatures)

config := NewConfig()
config.UseTarget(target)

func (*Config) UseUniversalEngine added in v1.0.4

func (self *Config) UseUniversalEngine() *Config

UseNativeEngine sets the engine to Universal in the configuration.

config := NewConfig()
config.UseUniversalEngine()

This method might fail if the Universal engine isn't available. Check `IsEngineAvailable` to learn more.

type CpuFeatures

type CpuFeatures struct {
	// contains filtered or unexported fields
}

CpuFeatures holds a set of CPU features. They are identified by their stringified names. The reference is the GCC options:

https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html,

https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html,

https://gcc.gnu.org/onlinedocs/gcc/AArch64-Options.html.

At the time of writing this documentation (it might be outdated in the future), the supported featurse are the following:

• sse2,

• sse3,

• ssse3,

• sse4.1,

• sse4.2,

• popcnt,

• avx,

• bmi,

• bmi2,

• avx2,

• avx512dq,

• avx512vl,

• lzcnt.

func NewCpuFeatures

func NewCpuFeatures() *CpuFeatures

NewCpuFeatures creates a new CpuFeatures, which is a set of CPU features.

func (*CpuFeatures) Add

func (self *CpuFeatures) Add(feature string) error

Add adds a new CPU feature to the existing set.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is used by the Store to drive the compilation and the execution of a WebAssembly module.

func NewDylibEngine added in v1.0.4

func NewDylibEngine() *Engine

NewDylibEngine instantiates and returns a new Dylib engine.

engine := NewDylibEngine()

func NewEngine

func NewEngine() *Engine

NewEngine instantiates and returns a new Engine with the default configuration.

engine := NewEngine()

func NewEngineWithConfig

func NewEngineWithConfig(config *Config) *Engine

NewEngineWithConfig instantiates and returns a new Engine with the given configuration.

config := NewConfig()
engine := NewEngineWithConfig(config)

func NewJITEngine

func NewJITEngine() *Engine

NewJITEngine is a deprecated function. Please use NewUniversalEngine instead.

func NewNativeEngine

func NewNativeEngine() *Engine

NewNativeEngine is a deprecated function. Please use NewDylibEngine instead.

func NewUniversalEngine added in v1.0.4

func NewUniversalEngine() *Engine

NewUniversalEngine instantiates and returns a new Universal engine.

engine := NewUniversalEngine()

type EngineKind added in v1.0.3

type EngineKind C.wasmer_engine_t

EngineKind represents the possible engine types.

func (EngineKind) String added in v1.0.3

func (self EngineKind) String() string

Strings returns the EngineKind as a string.

JIT.String() // "jit"
NATIVE.String() // "native"

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error represents a Wasmer runtime error.

func (*Error) Error

func (error *Error) Error() string

Error returns the Error's message.

type ExportType

type ExportType struct {
	// contains filtered or unexported fields
}

ExportType is a descriptor for an exported WebAssembly value.

func NewExportType

func NewExportType(name string, ty IntoExternType) *ExportType

NewExportType instantiates a new ExportType with a name and an extern type.

Note: An extern type is anything implementing IntoExternType: FunctionType, GlobalType, MemoryType, TableType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
exportType := NewExportType("a_global", globalType)

func (*ExportType) Close added in v1.0.4

func (self *ExportType) Close()

Force to close the ExportType.

A runtime finalizer is registered on the ExportType, but it is possible to force the destruction of the ExportType by calling Close manually.

func (*ExportType) Name

func (self *ExportType) Name() string

Name returns the name of the export type.

exportType := NewExportType("a_global", globalType)
exportType.Name() // "global"

func (*ExportType) Type

func (self *ExportType) Type() *ExternType

Type returns the type of the export type.

exportType := NewExportType("a_global", globalType)
exportType.Type() // ExternType

type Exports

type Exports struct {
	// contains filtered or unexported fields
}

Exports is a special kind of map that allows easily unwrapping the types of instances.

func (*Exports) Close added in v1.0.4

func (self *Exports) Close()

Force to close the Exports.

A runtime finalizer is registered on the Exports, but it is possible to force the destruction of the Exports by calling Close manually.

func (*Exports) Get

func (self *Exports) Get(name string) (*Extern, error)

Get retrieves and returns an Extern by its name.

Note: If the name does not refer to an existing export, Get will return an Error.

instance, _ := NewInstance(module, NewImportObject())
extern, error := instance.Exports.Get("an_export")

func (*Exports) GetFunction

func (self *Exports) GetFunction(name string) (NativeFunction, error)

GetFunction retrieves a exported function by its name and returns it as a native Go function.

The difference with GetRawFunction is that Function.Native has been called on the exported function.

Note: If the name does not refer to an existing export, GetFunction will return an Error.

Note: If the export is not a function, GetFunction will return nil as its result.

instance, _ := NewInstance(module, NewImportObject())
exportedFunc, error := instance.Exports.GetFunction("an_exported_function")

if error != nil && exportedFunc != nil {
    exportedFunc()
}

func (*Exports) GetGlobal

func (self *Exports) GetGlobal(name string) (*Global, error)

GetGlobal retrieves and returns a exported Global by its name.

Note: If the name does not refer to an existing export, GetGlobal will return an Error.

Note: If the export is not a global, GetGlobal will return nil as a result.

instance, _ := NewInstance(module, NewImportObject())
exportedGlobal, error := instance.Exports.GetGlobal("an_exported_global")

func (*Exports) GetMemory

func (self *Exports) GetMemory(name string) (*Memory, error)

GetMemory retrieves and returns a exported Memory by its name.

Note: If the name does not refer to an existing export, GetMemory will return an Error.

Note: If the export is not a memory, GetMemory will return nil as a result.

instance, _ := NewInstance(module, NewImportObject())
exportedMemory, error := instance.Exports.GetMemory("an_exported_memory")

func (*Exports) GetRawFunction

func (self *Exports) GetRawFunction(name string) (*Function, error)

GetRawFunction retrieves and returns an exported Function by its name.

Note: If the name does not refer to an existing export, GetRawFunction will return an Error.

Note: If the export is not a function, GetRawFunction will return nil as its result.

instance, _ := NewInstance(module, NewImportObject())
exportedFunc, error := instance.Exports.GetRawFunction("an_exported_function")

if error != nil && exportedFunc != nil {
    exportedFunc.Call()
}

func (*Exports) GetTable

func (self *Exports) GetTable(name string) (*Table, error)

GetTable retrieves and returns a exported Table by its name.

Note: If the name does not refer to an existing export, GetTable will return an Error.

Note: If the export is not a table, GetTable will return nil as a result.

instance, _ := NewInstance(module, NewImportObject())
exportedTable, error := instance.Exports.GetTable("an_exported_table")

func (*Exports) GetWasiStartFunction

func (self *Exports) GetWasiStartFunction() (NativeFunction, error)

GetWasiStartFunction is similar to GetFunction("_start"). It saves you the cost of knowing the name of the WASI start function.

type Extern

type Extern struct {
	// contains filtered or unexported fields
}

Extern is the runtime representation of an entity that can be imported or exported.

func (*Extern) IntoExtern

func (self *Extern) IntoExtern() *Extern

func (*Extern) IntoFunction

func (self *Extern) IntoFunction() *Function

IntoFunction converts the Extern into a Function.

Note:️ If the Extern is not a Function, IntoFunction will return nil as its result.

function, _ := instance.Exports.GetFunction("exported_function")
extern = function.IntoExtern()
_ := extern.IntoFunction()

func (*Extern) IntoGlobal

func (self *Extern) IntoGlobal() *Global

IntoGlobal converts the Extern into a Global.

Note:️ If the Extern is not a Global, IntoGlobal will return nil as its result.

global, _ := instance.Exports.GetGlobal("exported_global")
extern = global.IntoExtern()
_ := extern.IntoGlobal()

func (*Extern) IntoMemory

func (self *Extern) IntoMemory() *Memory

IntoMemory converts the Extern into a Memory.

Note:️ If the Extern is not a Memory, IntoMemory will return nil as its result.

memory, _ := instance.Exports.GetMemory("exported_memory")
extern = memory.IntoExtern()
_ := extern.IntoMemory()

func (*Extern) IntoTable

func (self *Extern) IntoTable() *Table

IntoTable converts the Extern into a Table.

Note:️ If the Extern is not a Table, IntoTable will return nil as its result.

table, _ := instance.Exports.GetTable("exported_table")
extern = table.IntoExtern()
_ := extern.IntoTable()

func (*Extern) Kind

func (self *Extern) Kind() ExternKind

Kind returns the Extern's ExternKind.

global, _ := instance.Exports.GetGlobal("exported_global")
_ = global.IntoExtern().Kind()

func (*Extern) Type

func (self *Extern) Type() *ExternType

Type returns the Extern's ExternType.

global, _ := instance.Exports.GetGlobal("exported_global")
_ = global.IntoExtern().Type()

type ExternKind

type ExternKind C.wasm_externkind_t

Represents the kind of an Extern.

func (ExternKind) String

func (self ExternKind) String() string

String returns the ExternKind as a string.

FUNCTION.String() // "func"
GLOBAL.String()   // "global"
TABLE.String()    // "table"
MEMORY.String()   // "memory"

type ExternType

type ExternType struct {
	// contains filtered or unexported fields
}

ExternType classifies imports and external values with their respective types.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#external-types

func (*ExternType) IntoFunctionType

func (self *ExternType) IntoFunctionType() *FunctionType

IntoFunctionType converts the ExternType into a FunctionType.

Note:️ If the ExternType is not a FunctionType, IntoFunctionType will return nil as its result.

function, _ := instance.Exports.GetFunction("exported_function")
externType = function.IntoExtern().Type()
_ := externType.IntoFunctionType()

func (*ExternType) IntoGlobalType

func (self *ExternType) IntoGlobalType() *GlobalType

IntoGlobalType converts the ExternType into a GlobalType.

Note:️ If the ExternType is not a GlobalType, IntoGlobalType will return nil as its result.

global, _ := instance.Exports.GetGlobal("exported_global")
externType = global.IntoExtern().Type()
_ := externType.IntoGlobalType()

func (*ExternType) IntoMemoryType

func (self *ExternType) IntoMemoryType() *MemoryType

IntoMemoryType converts the ExternType into a MemoryType.

Note:️ If the ExternType is not a MemoryType, IntoMemoryType will return nil as its result.

memory, _ := instance.Exports.GetMemory("exported_memory")
externType = memory.IntoExtern().Type()
_ := externType.IntoMemoryType()

func (*ExternType) IntoTableType

func (self *ExternType) IntoTableType() *TableType

IntoTableType converts the ExternType into a TableType.

Note:️ If the ExternType is not a TableType, IntoTableType will return nil as its result.

table, _ := instance.Exports.GetTable("exported_table")
externType = table.IntoExtern().Type()
_ := externType.IntoTableType()

func (*ExternType) Kind

func (self *ExternType) Kind() ExternKind

Kind returns the ExternType's ExternKind

global, _ := instance.Exports.GetGlobal("exported_global")
extern = global.IntoExtern()
_ = extern.Kind()

type Frame

type Frame struct {
	// contains filtered or unexported fields
}

Frame represents a frame of a WebAssembly stack trace.

func (*Frame) FunctionIndex

func (self *Frame) FunctionIndex() uint32

FunctionIndex returns the function index in the original WebAssembly module that this frame corresponds to.

func (*Frame) FunctionOffset

func (self *Frame) FunctionOffset() uint

FunctionOffset returns the byte offset from the beginning of the function in the original WebAssembly file to the instruction this frame points to.

func (*Frame) Instance

func (self *Frame) Instance()

func (*Frame) ModuleOffset

func (self *Frame) ModuleOffset() uint

ModuleOffset returns the byte offset from the beginning of the original WebAssembly file to the instruction this frame points to.

type Function

type Function struct {
	// contains filtered or unexported fields
}

Function is a WebAssembly function instance.

func NewFunction

func NewFunction(store *Store, ty *FunctionType, function func([]Value) ([]Value, error)) *Function

NewFunction instantiates a new Function in the given Store.

It takes three arguments, the Store, the FunctionType and the definition for the Function.

The function definition must be a native Go function with a Value array as its single argument. The function must return a Value array or an error.

Note:️ Even if the function does not take any argument (or use any argument) it must receive a Value array as its single argument. At runtime, this array will be empty. The same applies to the result.

hostFunction := wasmer.NewFunction(
	store,
	wasmer.NewFunctionType(
		wasmer.NewValueTypes(), // zero argument
		wasmer.NewValueTypes(wasmer.I32), // one i32 result
	),
	func(args []wasmer.Value) ([]wasmer.Value, error) {
		return []wasmer.Value{wasmer.NewI32(42)}, nil
	},
)

func NewFunctionWithEnvironment

func NewFunctionWithEnvironment(store *Store, ty *FunctionType, userEnvironment interface{}, functionWithEnv func(interface{}, []Value) ([]Value, error)) *Function

NewFunctionWithEnvironment is similar to NewFunction except that the user-defined host function (in Go) accepts an additional first parameter which is an environment. This environment can be anything. It is typed as interface{}.

type MyEnvironment struct {
	foo int32
}

environment := &MyEnvironment {
	foo: 42,
}

hostFunction := wasmer.NewFunction(
	store,
	wasmer.NewFunctionType(
		wasmer.NewValueTypes(), // zero argument
		wasmer.NewValueTypes(wasmer.I32), // one i32 result
	),
	environment,
	func(environment interface{}, args []wasmer.Value) ([]wasmer.Value, error) {
		_ := environment.(*MyEnvironment)

		return []wasmer.Value{wasmer.NewI32(42)}, nil
	},
)

func (*Function) Call

func (self *Function) Call(parameters ...interface{}) (interface{}, error)

Call will call the Function and return its results as native Go values.

function, _ := instance.Exports.GetFunction("exported_function")
_ = function.Call(1, 2, 3)

func (*Function) IntoExtern

func (self *Function) IntoExtern() *Extern

IntoExtern converts the Function into an Extern.

function, _ := instance.Exports.GetFunction("exported_function")
extern := function.IntoExtern()

func (*Function) Native

func (self *Function) Native() NativeFunction

Native will turn the Function into a native Go function that can be then called.

function, _ := instance.Exports.GetFunction("exported_function")
nativeFunction = function.Native()
_ = nativeFunction(1, 2, 3)

func (*Function) ParameterArity

func (self *Function) ParameterArity() uint

ParameterArity returns the number of arguments the Function expects as per its definition.

function, _ := instance.Exports.GetFunction("exported_function")
arity := function.ParameterArity()

func (*Function) ResultArity

func (self *Function) ResultArity() uint

ParameterArity returns the number of results the Function will return.

function, _ := instance.Exports.GetFunction("exported_function")
arity := function.ResultArity()

func (*Function) Type

func (self *Function) Type() *FunctionType

Type returns the Function's FunctionType.

function, _ := instance.Exports.GetFunction("exported_function")
ty := function.Type()

type FunctionType

type FunctionType struct {
	// contains filtered or unexported fields
}

FunctionType classifies 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.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#function-types

func NewFunctionType

func NewFunctionType(params []*ValueType, results []*ValueType) *FunctionType

NewFunctionType instantiates a new FunctionType from two ValueType arrays: the parameters and the results.

params := wasmer.NewValueTypes()
results := wasmer.NewValueTypes(wasmer.I32)
functionType := wasmer.NewFunctionType(params, results)

func (*FunctionType) IntoExternType

func (self *FunctionType) IntoExternType() *ExternType

IntoExternType converts the FunctionType into an ExternType.

function, _ := instance.Exports.GetFunction("exported_function")
functionType := function.Type()
externType = functionType.IntoExternType()

func (*FunctionType) Params

func (self *FunctionType) Params() []*ValueType

Params returns the parameters definitions from the FunctionType as a ValueType array

params := wasmer.NewValueTypes()
results := wasmer.NewValueTypes(wasmer.I32)
functionType := wasmer.NewFunctionType(params, results)
paramsValueTypes = functionType.Params()

func (*FunctionType) Results

func (self *FunctionType) Results() []*ValueType

Results returns the results definitions from the FunctionType as a ValueType array

params := wasmer.NewValueTypes()
results := wasmer.NewValueTypes(wasmer.I32)
functionType := wasmer.NewFunctionType(params, results)
resultsValueTypes = functionType.Results()

type Global

type Global struct {
	// contains filtered or unexported fields
}

Global stores a single value of the given GlobalType.

See also

https://webassembly.github.io/spec/core/syntax/modules.html#globals

func NewGlobal

func NewGlobal(store *Store, ty *GlobalType, value Value) *Global

NewGlobal instantiates a new Global in the given Store.

It takes three arguments, the Store, the GlobalType and the Value for the Global.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
global := NewGlobal(store, globalType, NewValue(42, I32))

func (*Global) Get

func (self *Global) Get() (interface{}, error)

Get returns the Global's value as a native Go value.

global, _ := instance.Exports.GetGlobal("exported_global")
value, _ := global.Get()

func (*Global) IntoExtern

func (self *Global) IntoExtern() *Extern

IntoExtern converts the Global into an Extern.

global, _ := instance.Exports.GetGlobal("exported_global")
extern := global.IntoExtern()

func (*Global) Set

func (self *Global) Set(value interface{}, kind ValueKind) error

Set sets the Global's value.

It takes two arguments, the Global's value as a native Go value and the value's ValueKind.

global, _ := instance.Exports.GetGlobal("exported_global")
_ = global.Set(1, I32)

func (*Global) Type

func (self *Global) Type() *GlobalType

Type returns the Global's GlobalType.

global, _ := instance.Exports.GetGlobal("exported_global")
ty := global.Type()

type GlobalMutability

type GlobalMutability C.wasm_mutability_t

func (GlobalMutability) String

func (self GlobalMutability) String() string

String returns the GlobalMutability as a string.

IMMUTABLE.String() // "const"
MUTABLE.String()   // "var"

type GlobalType

type GlobalType struct {
	// contains filtered or unexported fields
}

GlobalType classifies global variables, which hold a value and can either be mutable or immutable.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#global-types

func NewGlobalType

func NewGlobalType(valueType *ValueType, mutability GlobalMutability) *GlobalType

NewGlobalType instantiates a new GlobalType from a ValueType and a GlobalMutability

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)

func (*GlobalType) IntoExternType

func (self *GlobalType) IntoExternType() *ExternType

IntoExternType converts the GlobalType into an ExternType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)
externType = globalType.IntoExternType()

func (*GlobalType) Mutability

func (self *GlobalType) Mutability() GlobalMutability

Mutability returns the GlobalType's GlobalMutability

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)
globalType.Mutability().String() // "const"

func (*GlobalType) ValueType

func (self *GlobalType) ValueType() *ValueType

ValueType returns the GlobalType's ValueType

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)
globalType.ValueType().Kind().String() // "i32"

type ImportObject

type ImportObject struct {
	// contains filtered or unexported fields
}

ImportObject contains all of the import data used when instantiating a WebAssembly module.

func NewImportObject

func NewImportObject() *ImportObject

NewImportObject instantiates a new empty ImportObject.

imports := NewImportObject()

func (*ImportObject) ContainsNamespace

func (self *ImportObject) ContainsNamespace(name string) bool

ContainsNamespace returns true if the ImportObject contains the given namespace (or module name)

imports := NewImportObject()
_ = imports.ContainsNamespace("env") // false

func (*ImportObject) Register

func (self *ImportObject) Register(namespaceName string, namespace map[string]IntoExtern)

Register registers a namespace (or module name) in the ImportObject.

It takes two arguments: the namespace name and a map with imports names as key and externs as values.

Note:️ An extern is anything implementing IntoExtern: Function, Global, Memory, Table.

 imports := NewImportObject()
 importObject.Register(
 	"env",
 	map[string]wasmer.IntoExtern{
 		"host_function": hostFunction,
 		"host_global": hostGlobal,
 	},
)

Note:️ The namespace (or module name) may be empty:

imports := NewImportObject()
importObject.Register(
	"",
	map[string]wasmer.IntoExtern{
 		"host_function": hostFunction,
		"host_global": hostGlobal,
	},
)

type ImportType

type ImportType struct {
	// contains filtered or unexported fields
}

ImportType is a descriptor for an imported value into a WebAssembly module.

func NewImportType

func NewImportType(module string, name string, ty IntoExternType) *ImportType

NewImportType instantiates a new ImportType with a module name (or namespace), a name and an extern type.

Note:️ An extern type is anything implementing IntoExternType: FunctionType, GlobalType, MemoryType, TableType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)

func (*ImportType) Close added in v1.0.4

func (self *ImportType) Close()

Force to close the ImportType.

A runtime finalizer is registered on the ImportType, but it is possible to force the destruction of the ImportType by calling Close manually.

func (*ImportType) Module

func (self *ImportType) Module() string

Module returns the ImportType's module name (or namespace).

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)
_ = importType.Module()

func (*ImportType) Name

func (self *ImportType) Name() string

Name returns the ImportType's name.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)
_ = importType.Name()

func (*ImportType) Type

func (self *ImportType) Type() *ExternType

Type returns the ImportType's type as an ExternType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)
_ = importType.Type()

type Instance

type Instance struct {
	Exports *Exports
	// contains filtered or unexported fields
}

func NewInstance

func NewInstance(module *Module, imports *ImportObject) (*Instance, error)

NewInstance instantiates a new Instance.

It takes two arguments, the Module and an ImportObject.

Note:️ Instantiating a module may return TrapError if the module's start function traps.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, err := wasmer.NewModule(store, wasmBytes)
importObject := wasmer.NewImportObject()
instance, err := wasmer.NewInstance(module, importObject)

func (*Instance) Close added in v1.0.4

func (self *Instance) Close()

Force to close the Instance.

A runtime finalizer is registered on the Instance, but it is possible to force the destruction of the Instance by calling Close manually.

type IntoExtern

type IntoExtern interface {
	IntoExtern() *Extern
}

IntoExtern is an interface implemented by entity that can be imported of exported.

type IntoExternType

type IntoExternType interface {
	IntoExternType() *ExternType
}

type Limits

type Limits struct {
	// contains filtered or unexported fields
}

Limits classify the size range of resizeable storage associated with memory types and table types.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#limits

func NewLimits

func NewLimits(minimum uint32, maximum uint32) (*Limits, error)

NewLimits instantiates a new Limits which describes the Memory used. The minimum and maximum parameters are "number of memory pages".

️Note: Each page is 64 KiB in size.

Note: You cannot Memory.Grow the Memory beyond the maximum defined here.

func (*Limits) Maximum

func (self *Limits) Maximum() uint32

Maximum returns the maximum size of the Memory allocated in "number of pages".

Each page is 64 KiB in size.

Note: You cannot Memory.Grow beyond this defined maximum size.

func (*Limits) Minimum

func (self *Limits) Minimum() uint32

Minimum returns the minimum size of the Memory allocated in "number of pages".

Note:️ Each page is 64 KiB in size.

type Memory

type Memory struct {
	// contains filtered or unexported fields
}

Memory is a vector of raw uninterpreted bytes.

See also

Specification: https://webassembly.github.io/spec/core/syntax/modules.html#memories

func NewMemory

func NewMemory(store *Store, ty *MemoryType) *Memory

NewMemory instantiates a new Memory in the given Store.

It takes two arguments, the Store and the MemoryType for the Memory.

memory := wasmer.NewMemory(
    store,
    wasmer.NewMemoryType(wasmer.NewLimits(1, 4)),
)

func (*Memory) Data

func (self *Memory) Data() []byte

Data returns the Memory's contents as an byte array.

memory, _ := instance.Exports.GetMemory("exported_memory")
data := memory.Data()

func (*Memory) DataSize

func (self *Memory) DataSize() uint

Size returns the Memory's size as a number of bytes.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.DataSize()

func (*Memory) Grow

func (self *Memory) Grow(delta Pages) bool

Grow grows the Memory's size by a given number of Pages (the delta).

memory, _ := instance.Exports.GetMemory("exported_memory")
grown := memory.Grow(2)

func (*Memory) IntoExtern

func (self *Memory) IntoExtern() *Extern

IntoExtern converts the Memory into an Extern.

memory, _ := instance.Exports.GetMemory("exported_memory")
extern := memory.IntoExtern()

func (*Memory) Size

func (self *Memory) Size() Pages

Size returns the Memory's size as Pages.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.Size()

func (*Memory) Type

func (self *Memory) Type() *MemoryType

Type returns the Memory's MemoryType.

memory, _ := instance.Exports.GetMemory("exported_memory")
ty := memory.Type()

type MemoryType

type MemoryType struct {
	// contains filtered or unexported fields
}

MemoryType classifies linear memories and their size range.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#memory-types

func NewMemoryType

func NewMemoryType(limits *Limits) *MemoryType

NewMemoryType instantiates a new MemoryType given some Limits.

limits := NewLimits(1, 4)
memoryType := NewMemoryType(limits)

func (*MemoryType) IntoExternType

func (self *MemoryType) IntoExternType() *ExternType

IntoExternType converts the MemoryType into an ExternType.

limits := NewLimits(1, 4)
memoryType := NewMemoryType(limits)
externType = memoryType.IntoExternType()

func (*MemoryType) Limits

func (self *MemoryType) Limits() *Limits

Limits returns the MemoryType's Limits.

limits := NewLimits(1, 4)
memoryType := NewMemoryType(limits)
_ = memoryType.Limits()

type Module

type Module struct {
	// contains filtered or unexported fields
}

Module contains stateless WebAssembly code that has already been compiled and can be instantiated multiple times.

WebAssembly programs are organized into modules, which are the unit of deployment, loading, and compilation. A module 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.

See also

Specification: https://webassembly.github.io/spec/core/syntax/modules.html#modules

func DeserializeModule

func DeserializeModule(store *Store, bytes []byte) (*Module, error)

DeserializeModule deserializes an byte array to a Module.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
bytes := module.Serialize()
//...
deserializedModule := wasmer.DeserializeModule(store, bytes)

func NewModule

func NewModule(store *Store, bytes []byte) (*Module, error)

NewModule instantiates a new Module with the given Store.

It takes two arguments, the Store and the Wasm module as a byte array of WAT code.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, err := wasmer.NewModule(store, wasmBytes)

func (*Module) Close added in v1.0.4

func (self *Module) Close()

Force to close the Module.

A runtime finalizer is registered on the Module, but it is possible to force the destruction of the Module by calling Close manually.

func (*Module) Exports

func (self *Module) Exports() []*ExportType

Exports returns the Module's exports as an ExportType array.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
exports := module.Exports()

func (*Module) Imports

func (self *Module) Imports() []*ImportType

Imports returns the Module's imports as an ImportType array.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
imports := module.Imports()

func (*Module) Name

func (self *Module) Name() string

Name returns the Module's name.

Note:️ This is not part of the standard Wasm C API. It is Wasmer specific.

wasmBytes := []byte(`(module $moduleName)`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
name := module.Name()

func (*Module) Serialize

func (self *Module) Serialize() ([]byte, error)

Serialize serializes the module and returns the Wasm code as an byte array.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
bytes := module.Serialize()

type NativeFunction

type NativeFunction = func(...interface{}) (interface{}, error)

NativeFunction is a type alias representing a host function that can be called as any Go function.

type Pages

type Pages C.wasm_memory_pages_t

Units of WebAssembly pages (as specified to be 65,536 bytes).

func (*Pages) ToBytes

func (self *Pages) ToBytes() uint

ToBytes converts a Pages to a native Go uint which is the Pages' size in bytes.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.Size().ToBytes()

func (*Pages) ToUint32

func (self *Pages) ToUint32() uint32

ToUint32 converts a Pages to a native Go uint32 which is the Pages' size.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.Size().ToUint32()

type Store

type Store struct {
	Engine *Engine
	// contains filtered or unexported fields
}

Store represents all global state that can be manipulated by WebAssembly programs. It consists of the runtime representation of all instances of functions, tables, memories, and globals that have been allocated during the life time of the abstract machine.

The Store holds the Engine (that is — amongst many things — used to compile the Wasm bytes into a valid module artifact).

See also

Specification: https://webassembly.github.io/spec/core/exec/runtime.html#store

func NewStore

func NewStore(engine *Engine) *Store

NewStore instantiates a new Store with an Engine.

engine := NewEngine()
store := NewStore(engine)

func (*Store) Close added in v1.0.4

func (self *Store) Close()

Force to close the Store.

A runtime finalizer is registered on the Store, but it is possible to force the destruction of the Store by calling Close manually.

type Table

type Table struct {
	// contains filtered or unexported fields
}

A table instance is the runtime representation of a table. It holds a vector of function elements and an optional maximum size, if one was specified in the table type at the table’s definition site.

See also

Specification: https://webassembly.github.io/spec/core/exec/runtime.html#table-instances

func (*Table) IntoExtern

func (self *Table) IntoExtern() *Extern

IntoExtern converts the Table into an Extern.

table, _ := instance.Exports.GetTable("exported_table")
extern := table.IntoExtern()

func (*Table) Size

func (self *Table) Size() TableSize

Size returns the Table's size.

table, _ := instance.Exports.GetTable("exported_table")
size := table.Size()

type TableSize

type TableSize C.wasm_table_size_t

TableSize represents the size of a table.

func (*TableSize) ToUint32

func (self *TableSize) ToUint32() uint32

ToUint32 converts a TableSize to a native Go uint32.

table, _ := instance.Exports.GetTable("exported_table")
size := table.Size().ToUint32()

type TableType

type TableType struct {
	// contains filtered or unexported fields
}

TableType classifies tables over elements of element types within a size range.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#table-types

func NewTableType

func NewTableType(valueType *ValueType, limits *Limits) *TableType

NewTableType instantiates a new TableType given a ValueType and some Limits.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.IntoExternType()

func (*TableType) IntoExternType

func (self *TableType) IntoExternType() *ExternType

IntoExternType converts the TableType into an ExternType.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.IntoExternType()

func (*TableType) Limits

func (self *TableType) Limits() *Limits

Limits returns the TableType's Limits.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.Limits()

func (*TableType) ValueType

func (self *TableType) ValueType() *ValueType

ValueType returns the TableType's ValueType.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.ValueType()

type Target

type Target struct {
	// contains filtered or unexported fields
}

Target represents a triple + CPU features pairs.

func NewTarget

func NewTarget(triple *Triple, cpuFeatures *CpuFeatures) *Target

NewTarget creates a new target.

triple, err := NewTriple("aarch64-unknown-linux-gnu")
cpuFeatures := NewCpuFeatures()
target := NewTarget(triple, cpuFeatures)

type Trace added in v1.0.2

type Trace struct {
	// contains filtered or unexported fields
}

Trace represents a WebAssembly trap.

type Trap

type Trap struct {
	// contains filtered or unexported fields
}

Trap stores trace message with backtrace when an error happened.

func NewTrap

func NewTrap(store *Store, message string) *Trap

Creates a new trap with a message.

engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
trap := NewTrap(store, "oops")

func (*Trap) Message

func (self *Trap) Message() string

Message returns the message attached to the current Trap.

func (*Trap) Origin

func (self *Trap) Origin() *Frame

Origin returns the top frame of WebAssembly stack responsible for this trap.

frame := trap.Origin()

func (*Trap) Trace

func (self *Trap) Trace() *Trace

Trace returns the trace of WebAssembly frames for this trap.

type TrapError

type TrapError struct {
	// contains filtered or unexported fields
}

TrapError represents a trap produced during Wasm execution.

See also

Specification: https://webassembly.github.io/spec/core/intro/overview.html#trap

func (*TrapError) Error

func (self *TrapError) Error() string

Error returns the TrapError's message.

func (*TrapError) Origin

func (self *TrapError) Origin() *Frame

Origin returns the TrapError's origin as a Frame.

func (*TrapError) Trace

func (self *TrapError) Trace() []*Frame

Trace returns the TrapError's trace as a Frame array.

type Triple

type Triple struct {
	// contains filtered or unexported fields
}

Triple; historically such things had three fields, though they have added additional fields over time.

func NewTriple

func NewTriple(triple string) (*Triple, error)

NewTriple creates a new triple, otherwise it returns an error specifying why the provided triple isn't valid.

triple, err := NewTriple("aarch64-unknown-linux-gnu")

func NewTripleFromHost

func NewTripleFromHost() *Triple

NewTripleFromHost creates a new triple from the current host.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value; WebAssembly computations manipulate values of basic value types:

• Integer (32 or 64 bit width),

• Floating-point (32 or 64 bit width),

• Vectors (128 bits, with 32 or 64 bit lanes).

See Also

Specification: https://webassembly.github.io/spec/core/exec/runtime.html#values

func NewF32

func NewF32(value interface{}) Value

NewF32 instantiates a new F32 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewF32 will panic.

value := NewF32(4.2)

func NewF64

func NewF64(value interface{}) Value

NewF64 instantiates a new F64 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewF64 will panic.

value := NewF64(4.2)

func NewI32

func NewI32(value interface{}) Value

NewI32 instantiates a new I32 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewI32 will panic.

value := NewI32(42)

func NewI64

func NewI64(value interface{}) Value

NewI64 instantiates a new I64 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewI64 will panic.

value := NewI64(42)

func NewValue

func NewValue(value interface{}, kind ValueKind) Value

NewValue instantiates a new Value with the given value and ValueKind.

Note: If a Wasm value cannot be created from the given value,

value := NewValue(42, I32)

func (*Value) F32

func (self *Value) F32() float32

F32 returns the Value's value as a native Go float32.

Note: It panics if the value is not of type F32.

value := NewF32(4.2)
_ = value.F32()

func (*Value) F64

func (self *Value) F64() float64

F64 returns the Value's value as a native Go float64.

Note: It panics if the value is not of type F64.

value := NewF64(4.2)
_ = value.F64()

func (*Value) I32

func (self *Value) I32() int32

I32 returns the Value's value as a native Go int32.

Note: It panics if the value is not of type I32.

value := NewI32(42)
_ = value.I32()

func (*Value) I64

func (self *Value) I64() int64

I64 returns the Value's value as a native Go int64.

Note: It panics if the value is not of type I64.

value := NewI64(42)
_ = value.I64()

func (*Value) Kind

func (self *Value) Kind() ValueKind

Kind returns the Value's ValueKind.

value := NewF64(4.2)
_ = value.Kind()

func (*Value) Unwrap

func (self *Value) Unwrap() interface{}

Unwrap returns the Value's value as a native Go value.

value := NewF64(4.2)
_ = value.Unwrap()

type ValueKind

type ValueKind C.wasm_valkind_t

ValueKind represents the kind of a value.

func (ValueKind) IsNumber

func (self ValueKind) IsNumber() bool

IsNumber returns true if the ValueKind is a number type.

I32.IsNumber()     // true
I64.IsNumber()     // true
F32.IsNumber()     // true
F64.IsNumber()     // true
AnyRef.IsNumber()  // false
FuncRef.IsNumber() // false

func (ValueKind) IsReference

func (self ValueKind) IsReference() bool

IsReference returns true if the ValueKind is a reference.

I32.IsReference()     // false
I64.IsReference()     // false
F32.IsReference()     // false
F64.IsReference()     // false
AnyRef.IsReference()  // true
FuncRef.IsReference() // true

func (ValueKind) String

func (self ValueKind) String() string

String returns the ValueKind as a string.

I32.String()     // "i32"
I64.String()     // "i64"
F32.String()     // "f32"
F64.String()     // "f64"
AnyRef.String()  // "anyref"
FuncRef.String() // "funcref"

type ValueType

type ValueType struct {
	// contains filtered or unexported fields
}

ValueType classifies the individual values that WebAssembly code can compute with and the values that a variable accepts.

func NewValueType

func NewValueType(kind ValueKind) *ValueType

NewValueType instantiates a new ValueType given a ValueKind.

valueType := NewValueType(I32)

func NewValueTypes

func NewValueTypes(kinds ...ValueKind) []*ValueType

NewValueTypes instantiates a new ValueType array from a list of ValueKind. Not that the list may be empty.

valueTypes := NewValueTypes(I32, I64, F32)

Note:️ NewValueTypes is specifically designed to help you declare function types, e.g. with NewFunctionType:

functionType := NewFunctionType(
	NewValueTypes(), // arguments
	NewValueTypes(I32), // results
)

func (*ValueType) Kind

func (self *ValueType) Kind() ValueKind

Kind returns the ValueType's ValueKind

valueType := NewValueType(I32)
_ = valueType.Kind()

type WasiEnvironment

type WasiEnvironment struct {
	// contains filtered or unexported fields
}

WasiEnvironment represents the environment provided to the WASI imports (see NewFunctionWithEnvironment which is designed for user-defined host function; that's the same idea here but applied to WASI functions and other imports).

func (*WasiEnvironment) GenerateImportObject

func (self *WasiEnvironment) GenerateImportObject(store *Store, module *Module) (*ImportObject, error)

GenerateImportObject generates an import object, that can be extended and passed to NewInstance.

wasiEnv, _ := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("ABC", "DEF").
	Environment("X", "ZY").
	MapDirectory("the_host_current_directory", ".").
	Finalize()

importObject, _ := wasiEnv.GenerateImportObject(store, module)
instance, _ := NewInstance(module, importObject)
start, _ := instance.Exports.GetWasiStartFunction()

start()

func (*WasiEnvironment) ReadStderr added in v1.0.2

func (self *WasiEnvironment) ReadStderr() []byte

ReadStderr reads the WASI module stderr if captured with WasiStateBuilder.CaptureStderr. See ReadStdout to see an example.

func (*WasiEnvironment) ReadStdout added in v1.0.2

func (self *WasiEnvironment) ReadStdout() []byte

ReadStdout reads the WASI module stdout if captured with WasiStateBuilder.CaptureStdout

wasiEnv, _ := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("ABC", "DEF").
	Environment("X", "ZY").
	MapDirectory("the_host_current_directory", ".").
	CaptureStdout().
	Finalize()

importObject, _ := wasiEnv.GenerateImportObject(store, module)
instance, _ := NewInstance(module, importObject)
start, _ := instance.Exports.GetWasiStartFunction()

start()

stdout := string(wasiEnv.ReadStdout())

type WasiStateBuilder

type WasiStateBuilder struct {
	// contains filtered or unexported fields
}

WasiStateBuilder is a convenient API for configuring WASI.

func NewWasiStateBuilder

func NewWasiStateBuilder(programName string) *WasiStateBuilder

NewWasiStateBuilder creates a new WASI state builder, starting by configuring the WASI program name.

wasiStateBuilder := NewWasiStateBuilder("test-program")

func (*WasiStateBuilder) Argument added in v1.0.1

func (self *WasiStateBuilder) Argument(argument string) *WasiStateBuilder

Argument configures a new argument to the WASI module.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo")

func (*WasiStateBuilder) CaptureStderr added in v1.0.1

func (self *WasiStateBuilder) CaptureStderr() *WasiStateBuilder

CaptureStderr configures the WASI module to capture its stderr.

func (*WasiStateBuilder) CaptureStdout added in v1.0.1

func (self *WasiStateBuilder) CaptureStdout() *WasiStateBuilder

CaptureStdout configures the WASI module to capture its stdout.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	MapDirectory("the_host_current_directory", ".")
	CaptureStdout()

func (*WasiStateBuilder) Environment added in v1.0.1

func (self *WasiStateBuilder) Environment(key string, value string) *WasiStateBuilder

Environment configures a new environment variable for the WASI module.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE")

func (*WasiStateBuilder) Finalize added in v1.0.1

func (self *WasiStateBuilder) Finalize() (*WasiEnvironment, error)

Finalize tells the state builder to produce a WasiEnvironment. It consumes the current WasiStateBuilder.

It can return an error if the state builder contains invalid configuration.

wasiEnvironment, err := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	MapDirectory("the_host_current_directory", ".")
	CaptureStdout().
  Finalize()

func (*WasiStateBuilder) InheritStderr added in v1.0.1

func (self *WasiStateBuilder) InheritStderr() *WasiStateBuilder

InheritStderr configures the WASI module to inherit the stderr from the host.

func (*WasiStateBuilder) InheritStdin added in v1.0.1

func (self *WasiStateBuilder) InheritStdin() *WasiStateBuilder

InheritStdin configures the WASI module to inherit the stdin from the host.

func (*WasiStateBuilder) InheritStdout added in v1.0.1

func (self *WasiStateBuilder) InheritStdout() *WasiStateBuilder

InheritStdout configures the WASI module to inherit the stdout from the host.

func (*WasiStateBuilder) MapDirectory added in v1.0.1

func (self *WasiStateBuilder) MapDirectory(alias string, directory string) *WasiStateBuilder

MapDirectory configures a new directory to pre-open with a different name exposed to the WASI module.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	MapDirectory("the_host_current_directory", ".")

func (*WasiStateBuilder) PreopenDirectory added in v1.0.1

func (self *WasiStateBuilder) PreopenDirectory(preopenDirectory string) *WasiStateBuilder

PreopenDirectory configures a new directory to pre-open.

This opens the given directory at the virtual root /, and allows the WASI module to read and write to the given directory.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	PreopenDirectory("bar")

type WasiVersion

type WasiVersion C.wasi_version_t

WasiVersion represents the possible WASI versions.

func GetWasiVersion

func GetWasiVersion(module *Module) WasiVersion

GetWasiVersion returns the WASI version of the given Module if any, WASI_VERSION_INVALID otherwise.

wasiVersion := GetWasiVersion(module)

func (WasiVersion) String

func (self WasiVersion) String() string

String returns the WasiVersion as a string.

WASI_VERSION_SNAPSHOT0.String() //  "wasi_unstable"
WASI_VERSION_SNAPSHOT1.String() // "wasi_snapshot_preview1"

Directories

Path Synopsis
packaged
include
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/darwin-aarch64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/darwin-amd64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/linux-aarch64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/linux-amd64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL