Movatterモバイル変換


[0]ホーム

URL:


wasmer

package
v1.0.4Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2021 License:MITImports:8Imported by:67

Details

Repository

github.com/wasmerio/wasmer-go

Links

Documentation

Overview

Package wasmer is a complete and mature WebAssembly runtime for Gobased 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 WebAssemblymodules. In a nutshell, wasmer compiles the WebAssembly module intocompiled code, and then executes it. wasmer is designed to work invarious environments and platforms: From nano single-boardcomputers to large and powerful servers, including more exoticones. To address those requirements, Wasmer provides 2 engines and3 compilers.

Succinctly, an engine is responsible to drive the compilation andthe execution of a WebAssembly module. By extension, a headlessengine can only execute a WebAssembly module, i.e. a module thathas previously been compiled, or compiled, serialized anddeserialized. By default, the wasmer package comes with 2 headlessengines:

• 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 executiontimes. Not prone to JIT-bombs. Ideal for blockchains.

• Cranelift: Fast compilation times, fast execution times. Idealfor development.

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

WebAssembly C API standard

Wasmer —the runtime— is written in Rust; C and C++ bindingsexist. This Go package relies on the so-called wasm_c_api,https://github.com/WebAssembly/wasm-c-api, which is the newstandard C API, implemented inside Wasmer as the Wasmer C API,https://wasmerio.github.io/wasmer/crates/wasmer_c_api/. Thisstandard is characterized as a living standard. The API is not yetstable, even though it shows maturity overtime. However, the WasmerC API provides some extensions, like the wasi_* or wasmer_* typesand functions, which aren't yet defined by the standard. The Gopackage 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 Engineengine := wasmer.NewEngine()// Create a Storestore := 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 orTable? 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

funcIsCompilerAvailableadded inv1.0.3

func IsCompilerAvailable(compilerCompilerKind)bool

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

IsCompilerAvailable(CRANELIFT)

funcIsEngineAvailableadded inv1.0.3

func IsEngineAvailable(engineEngineKind)bool

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

IsEngineAvailable(UNIVERSAL)

funcLimitMaxUnbound

func LimitMaxUnbound()uint32

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

funcValidateModule

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 abyte array. The function returns an error describing why the bytesare invalid, otherwise it returns nil.

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

funcWat2Wasm

func Wat2Wasm(watstring) ([]byte,error)

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

Seehttps://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

typeCompilerKindadded inv1.0.3

type CompilerKindC.wasmer_compiler_t

CompilerKind represents the possible compiler types.

func (CompilerKind)Stringadded inv1.0.3

func (selfCompilerKind) String()string

Strings returns the CompilerKind as a string.

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

typeConfig

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

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

funcNewConfig

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'tavailable. Check `IsCompilerAvailable` to learn more.

func (*Config)UseDylibEngineadded inv1.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 UseUniversalEngineinstead.

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 useUseDylibEngine instead.

func (*Config)UseSinglepassCompileradded inv1.0.3

func (self *Config) UseSinglepassCompiler() *Config

UseSinglepassCompiler sets the compiler to Singlepass in theconfiguration.

config := NewConfig()config.UseSinglepassCompiler()

This method might fail if the Singlepass compiler isn'tavailable. 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)UseUniversalEngineadded inv1.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'tavailable. Check `IsEngineAvailable` to learn more.

typeCpuFeatures

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

CpuFeatures holds a set of CPU features. They are identified bytheir 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 inthe future), the supported featurse are the following:

• sse2,

• sse3,

• ssse3,

• sse4.1,

• sse4.2,

• popcnt,

• avx,

• bmi,

• bmi2,

• avx2,

• avx512dq,

• avx512vl,

• lzcnt.

funcNewCpuFeatures

func NewCpuFeatures() *CpuFeatures

NewCpuFeatures creates a new CpuFeatures, which is a set of CPUfeatures.

func (*CpuFeatures)Add

func (self *CpuFeatures) Add(featurestring)error

Add adds a new CPU feature to the existing set.

typeEngine

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

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

funcNewDylibEngineadded inv1.0.4

func NewDylibEngine() *Engine

NewDylibEngine instantiates and returns a new Dylib engine.

engine := NewDylibEngine()

funcNewEngine

func NewEngine() *Engine

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

engine := NewEngine()

funcNewEngineWithConfig

func NewEngineWithConfig(config *Config) *Engine

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

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

funcNewJITEngine

func NewJITEngine() *Engine

NewJITEngine is a deprecated function. Please use NewUniversalEngine instead.

funcNewNativeEngine

func NewNativeEngine() *Engine

NewNativeEngine is a deprecated function. Please use NewDylibEngine instead.

funcNewUniversalEngineadded inv1.0.4

func NewUniversalEngine() *Engine

NewUniversalEngine instantiates and returns a new Universal engine.

engine := NewUniversalEngine()

typeEngineKindadded inv1.0.3

type EngineKindC.wasmer_engine_t

EngineKind represents the possible engine types.

func (EngineKind)Stringadded inv1.0.3

func (selfEngineKind) String()string

Strings returns the EngineKind as a string.

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

typeError

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.

typeExportType

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

ExportType is a descriptor for an exported WebAssembly value.

funcNewExportType

func NewExportType(namestring, tyIntoExternType) *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)Closeadded inv1.0.4

func (self *ExportType) Close()

Force to close the ExportType.

A runtime finalizer is registered on the ExportType, but it ispossible to force the destruction of the ExportType by callingClose 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

typeExports

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

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

func (*Exports)Closeadded inv1.0.4

func (self *Exports) Close()

Force to close the Exports.

A runtime finalizer is registered on the Exports, but it ispossible to force the destruction of the Exports by calling Closemanually.

func (*Exports)Get

func (self *Exports) Get(namestring) (*Extern,error)

Get retrieves and returns an Extern by its name.

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

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

func (*Exports)GetFunction

func (self *Exports) GetFunction(namestring) (NativeFunction,error)

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

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

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

Note: If the export is not a function, GetFunction will return nilas 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(namestring) (*Global,error)

GetGlobal retrieves and returns a exported Global by its name.

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

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

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

func (*Exports)GetMemory

func (self *Exports) GetMemory(namestring) (*Memory,error)

GetMemory retrieves and returns a exported Memory by its name.

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

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

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

func (*Exports)GetRawFunction

func (self *Exports) GetRawFunction(namestring) (*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 returnnil 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(namestring) (*Table,error)

GetTable retrieves and returns a exported Table by its name.

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

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

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 savesyou the cost of knowing the name of the WASI start function.

typeExtern

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

Extern is the runtime representation of an entity that can beimported 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 nilas 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 asits 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 asits 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 asits 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()

typeExternKind

type ExternKindC.wasm_externkind_t

Represents the kind of an Extern.

func (ExternKind)String

func (selfExternKind) String()string

String returns the ExternKind as a string.

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

typeExternType

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, IntoFunctionTypewill 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 willreturn 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 willreturn 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 willreturn 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()

typeFrame

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 originalWebAssembly module that this frame corresponds to.

func (*Frame)FunctionOffset

func (self *Frame) FunctionOffset()uint

FunctionOffset returns the byte offset from the beginning of thefunction in the original WebAssembly file to the instruction thisframe 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 theoriginal WebAssembly file to the instruction this frame points to.

typeFunction

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

Function is a WebAssembly function instance.

funcNewFunction

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 thedefinition for the Function.

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

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

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

funcNewFunctionWithEnvironment

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

NewFunctionWithEnvironment is similar to NewFunction except thatthe user-defined host function (in Go) accepts an additional firstparameter which is an environment. This environment can beanything. It is typed as interface{}.

type MyEnvironment struct {foo int32}environment := &MyEnvironment {foo: 42,}hostFunction := wasmer.NewFunction(store,wasmer.NewFunctionType(wasmer.NewValueTypes(), // zero argumentwasmer.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()

typeFunctionType

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

FunctionType classifies the signature of functions, mapping avector of parameters to a vector of results. They are also used toclassify the inputs and outputs of instructions.

See also

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

funcNewFunctionType

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

NewFunctionType instantiates a new FunctionType from two ValueTypearrays: 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 asa 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 aValueType array

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

typeGlobal

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

funcNewGlobal

func NewGlobal(store *Store, ty *GlobalType, valueValue) *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{}, kindValueKind)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()

typeGlobalMutability

type GlobalMutabilityC.wasm_mutability_t

func (GlobalMutability)String

func (selfGlobalMutability) String()string

String returns the GlobalMutability as a string.

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

typeGlobalType

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

funcNewGlobalType

func NewGlobalType(valueType *ValueType, mutabilityGlobalMutability) *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"

typeImportObject

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

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

funcNewImportObject

func NewImportObject() *ImportObject

NewImportObject instantiates a new empty ImportObject.

imports := NewImportObject()

func (*ImportObject)ContainsNamespace

func (self *ImportObject) ContainsNamespace(namestring)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(namespaceNamestring, 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,},)

typeImportType

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

ImportType is a descriptor for an imported value into a WebAssemblymodule.

funcNewImportType

func NewImportType(modulestring, namestring, tyIntoExternType) *ImportType

NewImportType instantiates a new ImportType with a module name (ornamespace), 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)Closeadded inv1.0.4

func (self *ImportType) Close()

Force to close the ImportType.

A runtime finalizer is registered on the ImportType, but it ispossible to force the destruction of the ImportType by callingClose 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()

typeInstance

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

funcNewInstance

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'sstart 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)Closeadded inv1.0.4

func (self *Instance) Close()

Force to close the Instance.

A runtime finalizer is registered on the Instance, but it ispossible to force the destruction of the Instance by calling Closemanually.

typeIntoExtern

type IntoExtern interface {IntoExtern() *Extern}

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

typeIntoExternType

type IntoExternType interface {IntoExternType() *ExternType}

typeLimits

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

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

See also

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

funcNewLimits

func NewLimits(minimumuint32, maximumuint32) (*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.

typeMemory

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

funcNewMemory

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(deltaPages)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()

typeMemoryType

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

funcNewMemoryType

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()

typeModule

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

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

WebAssembly programs are organized into modules, which are the unitof deployment, loading, and compilation. A module collectsdefinitions for types, functions, tables, memories, and globals. Inaddition, it can declare imports and exports and provideinitialization logic in the form of data and element segments or astart function.

See also

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

funcDeserializeModule

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)

funcNewModule

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 bytearray of WAT code.

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

func (*Module)Closeadded inv1.0.4

func (self *Module) Close()

Force to close the Module.

A runtime finalizer is registered on the Module, but it is possibleto 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()

typeNativeFunction

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

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

typePages

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()

typeStore

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

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

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

See also

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

funcNewStore

func NewStore(engine *Engine) *Store

NewStore instantiates a new Store with an Engine.

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

func (*Store)Closeadded inv1.0.4

func (self *Store) Close()

Force to close the Store.

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

typeTable

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

A table instance is the runtime representation of a table. It holdsa vector of function elements and an optional maximum size, if onewas 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()

typeTableSize

type TableSizeC.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()

typeTableType

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

funcNewTableType

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()

typeTarget

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

Target represents a triple + CPU features pairs.

funcNewTarget

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)

typeTraceadded inv1.0.2

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

Trace represents a WebAssembly trap.

typeTrap

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

Trap stores trace message with backtrace when an error happened.

funcNewTrap

func NewTrap(store *Store, messagestring) *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 forthis trap.

frame := trap.Origin()

func (*Trap)Trace

func (self *Trap) Trace() *Trace

Trace returns the trace of WebAssembly frames for this trap.

typeTrapError

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.

typeTriple

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

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

funcNewTriple

func NewTriple(triplestring) (*Triple,error)

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

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

funcNewTripleFromHost

func NewTripleFromHost() *Triple

NewTripleFromHost creates a new triple from the current host.

typeValue

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

funcNewF32

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)

funcNewF64

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)

funcNewI32

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)

funcNewI64

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)

funcNewValue

func NewValue(value interface{}, kindValueKind)Value

NewValue instantiates a new Value with the given value andValueKind.

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()

typeValueKind

type ValueKindC.wasm_valkind_t

ValueKind represents the kind of a value.

func (ValueKind)IsNumber

func (selfValueKind) IsNumber()bool

IsNumber returns true if the ValueKind is a number type.

I32.IsNumber()     // trueI64.IsNumber()     // trueF32.IsNumber()     // trueF64.IsNumber()     // trueAnyRef.IsNumber()  // falseFuncRef.IsNumber() // false

func (ValueKind)IsReference

func (selfValueKind) IsReference()bool

IsReference returns true if the ValueKind is a reference.

I32.IsReference()     // falseI64.IsReference()     // falseF32.IsReference()     // falseF64.IsReference()     // falseAnyRef.IsReference()  // trueFuncRef.IsReference() // true

func (ValueKind)String

func (selfValueKind) 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"

typeValueType

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

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

funcNewValueType

func NewValueType(kindValueKind) *ValueType

NewValueType instantiates a new ValueType given a ValueKind.

valueType := NewValueType(I32)

funcNewValueTypes

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

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

valueTypes := NewValueTypes(I32, I64, F32)

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

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

func (*ValueType)Kind

func (self *ValueType) Kind()ValueKind

Kind returns the ValueType's ValueKind

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

typeWasiEnvironment

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

WasiEnvironment represents the environment provided to the WASIimports (see NewFunctionWithEnvironment which is designed foruser-defined host function; that's the same idea here but appliedto 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 beextended 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)ReadStderradded inv1.0.2

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

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

func (*WasiEnvironment)ReadStdoutadded inv1.0.2

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

ReadStdout reads the WASI module stdout if captured withWasiStateBuilder.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())

typeWasiStateBuilder

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

WasiStateBuilder is a convenient API for configuring WASI.

funcNewWasiStateBuilder

func NewWasiStateBuilder(programNamestring) *WasiStateBuilder

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

wasiStateBuilder := NewWasiStateBuilder("test-program")

func (*WasiStateBuilder)Argumentadded inv1.0.1

func (self *WasiStateBuilder) Argument(argumentstring) *WasiStateBuilder

Argument configures a new argument to the WASI module.

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

func (*WasiStateBuilder)CaptureStderradded inv1.0.1

func (self *WasiStateBuilder) CaptureStderr() *WasiStateBuilder

CaptureStderr configures the WASI module to capture its stderr.

func (*WasiStateBuilder)CaptureStdoutadded inv1.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)Environmentadded inv1.0.1

func (self *WasiStateBuilder) Environment(keystring, valuestring) *WasiStateBuilder

Environment configures a new environment variable for the WASI module.

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

func (*WasiStateBuilder)Finalizeadded inv1.0.1

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

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

It can return an error if the state builder contains invalidconfiguration.

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

func (*WasiStateBuilder)InheritStderradded inv1.0.1

func (self *WasiStateBuilder) InheritStderr() *WasiStateBuilder

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

func (*WasiStateBuilder)InheritStdinadded inv1.0.1

func (self *WasiStateBuilder) InheritStdin() *WasiStateBuilder

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

func (*WasiStateBuilder)InheritStdoutadded inv1.0.1

func (self *WasiStateBuilder) InheritStdout() *WasiStateBuilder

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

func (*WasiStateBuilder)MapDirectoryadded inv1.0.1

func (self *WasiStateBuilder) MapDirectory(aliasstring, directorystring) *WasiStateBuilder

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

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

func (*WasiStateBuilder)PreopenDirectoryadded inv1.0.1

func (self *WasiStateBuilder) PreopenDirectory(preopenDirectorystring) *WasiStateBuilder

PreopenDirectory configures a new directory to pre-open.

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

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

typeWasiVersion

type WasiVersionC.wasi_version_t

WasiVersion represents the possible WASI versions.

funcGetWasiVersion

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 (selfWasiVersion) String()string

String returns the WasiVersion as a string.

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

Source Files

View all Source files

Directories

PathSynopsis
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 orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp