api

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: Apache-2.0 Imports: 6 Imported by: 3 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package api includes constants and interfaces used by both end-users and internal implementations.

Example (CloseNotifier)

This shows how to implement a custom cleanup task on close.

package main

import (
	"context"

	"github.com/samyfodil/wazy/api"
)

var ctx context.Context

// This shows how to implement a custom cleanup task on close.
func main() {
	closeCh := make(chan struct{})
	ctx = api.WithCloseNotifier(
		context.Background(),
		api.CloseNotifyFunc(func(context.Context, uint32) { close(closeCh) }),
	)

	// ... create module, do some work. Sometime later in another goroutine:

	select {
	case <-closeCh:
		// do some cleanup
	default:
		// do some more work with the module
	}

}
Example (CustomListenerFactory)

This shows how to make a listener that counts go function calls.

package main

import (
	"context"
	"fmt"
	"log"
	"sort"

	_ "embed"
	"github.com/samyfodil/wazy"
	"github.com/samyfodil/wazy/api"
	"github.com/samyfodil/wazy/imports/wasi_snapshot_preview1"
)

// listenerWasm was generated by the following:
//
//	cd logging/testdata; wat2wasm --debug-names listener.wat
//
//go:embed testdata/listener.wasm
var listenerWasm []byte

// uniqGoFuncs implements both FunctionListenerFactory and FunctionListener
type uniqGoFuncs map[string]struct{}

// callees returns the go functions called.
func (u uniqGoFuncs) callees() []string {
	ret := make([]string, 0, len(u))
	for k := range u {
		ret = append(ret, k)
	}

	sort.Strings(ret)
	return ret
}

// NewFunctionListener implements FunctionListenerFactory.NewFunctionListener
func (u uniqGoFuncs) NewFunctionListener(def api.FunctionDefinition) api.FunctionListener {
	if def.GoFunction() == nil {
		return nil
	}
	return u
}

// Before implements FunctionListener.Before
func (u uniqGoFuncs) Before(ctx context.Context, _ api.Module, def api.FunctionDefinition, _ []uint64, _ api.StackIterator) {
	u[def.DebugName()] = struct{}{}
}

// After implements FunctionListener.After
func (u uniqGoFuncs) After(context.Context, api.Module, api.FunctionDefinition, []uint64) {}

// Abort implements FunctionListener.Abort
func (u uniqGoFuncs) Abort(context.Context, api.Module, api.FunctionDefinition, error) {}

func main() {
	u := uniqGoFuncs{}

	// Set context to one that has an experimental listener
	ctx := api.WithFunctionListenerFactory(context.Background(), u)

	r := wazy.NewRuntime(ctx)
	defer r.Close(ctx) // This closes everything this Runtime created.

	wasi_snapshot_preview1.MustInstantiate(ctx, r)

	mod, err := r.Instantiate(ctx, listenerWasm)
	if err != nil {
		log.Panicln(err)
	}

	for i := 0; i < 5; i++ {
		if _, err = mod.ExportedFunction("rand").Call(ctx, 4); err != nil {
			log.Panicln(err)
		}
	}

	// A Go function was called multiple times, but we should only see it once.
	for _, f := range u.callees() {
		fmt.Println(f)
	}

}
Output:
wasi_snapshot_preview1.fd_write
wasi_snapshot_preview1.random_get
Example (EnableSnapshotterKey)
package main

import (
	"context"
	_ "embed"
	"fmt"
	"log"

	"github.com/samyfodil/wazy"
	"github.com/samyfodil/wazy/api"
)

// snapshotWasm was generated by the following:
//
//	cd testdata; wat2wasm snapshot.wat
//
//go:embed testdata/snapshot.wasm
var snapshotWasm []byte

type snapshotsKey struct{}

func main() {
	ctx := context.Background()

	rt := wazy.NewRuntime(ctx)
	defer rt.Close(ctx) // This closes everything this Runtime created.

	// Enable experimental snapshotting functionality by setting it to context. We use this
	// context when invoking functions, indicating to wazy to enable it.
	ctx = api.WithSnapshotter(ctx)

	// Also place a mutable holder of snapshots to be referenced during restore.
	var snapshots []api.Snapshot
	ctx = context.WithValue(ctx, snapshotsKey{}, &snapshots)

	// Register host functions using snapshot and restore. Generally snapshot is saved
	// into a mutable location in context to be referenced during restore.
	b := rt.NewHostModuleBuilder("example")
	wazy.HostFunc1(b.NewFunctionBuilder(), func(ctx context.Context, mod api.Module, snapshotPtr uint32) int32 {
		// Because we enabled snapshots with WithSnapshotter, this is non-nil.
		snapshot := api.GetSnapshotter(ctx).Snapshot()

		// Get our mutable snapshots holder to be able to add to it. Our example only calls snapshot
		// and restore once but real programs will often call them at multiple layers within a call
		// stack with various e.g., try/catch statements.
		snapshots := ctx.Value(snapshotsKey{}).(*[]api.Snapshot)
		idx := len(*snapshots)
		*snapshots = append(*snapshots, snapshot)

		// Write a value to be passed back to restore. This is meant to be opaque to the guest
		// and used to re-reference the snapshot.
		ok := mod.Memory().WriteUint32Le(snapshotPtr, uint32(idx))
		if !ok {
			log.Panicln("failed to write snapshot index")
		}

		return 0
	}).Export("snapshot")
	wazy.HostProc1(b.NewFunctionBuilder(), func(ctx context.Context, mod api.Module, snapshotPtr uint32) {
		// Read the value written by snapshot to re-reference the snapshot.
		idx, ok := mod.Memory().ReadUint32Le(snapshotPtr)
		if !ok {
			log.Panicln("failed to read snapshot index")
		}

		// Get the snapshot
		snapshots := ctx.Value(snapshotsKey{}).(*[]api.Snapshot)
		snapshot := (*snapshots)[idx]

		// Restore! The invocation of this function will end as soon as we invoke
		// Restore, so we also pass in our return value. The guest function run
		// will finish with this return value.
		snapshot.Restore([]uint64{5})
	}).Export("restore")
	_, err := b.Instantiate(ctx)
	if err != nil {
		log.Panicln(err)
	}

	mod, err := rt.Instantiate(ctx, snapshotWasm) // Instantiate the actual code
	if err != nil {
		log.Panicln(err)
	}

	// Call the guest entrypoint.
	res, err := mod.ExportedFunction("run").Call(ctx)
	if err != nil {
		log.Panicln(err)
	}
	// We restored and returned the restore value, so it's our result. If restore
	// was instead a no-op, we would have returned 10 from normal code flow.
	fmt.Println(res[0])
}
Output:
5
Example (ImportResolver)
package main

import (
	"bytes"
	"context"
	_ "embed"
	"fmt"
	"log"

	"github.com/samyfodil/wazy"
	"github.com/samyfodil/wazy/api"
	"github.com/samyfodil/wazy/imports/wasi_snapshot_preview1"
)

var (
	// These wasm files were generated by the following:
	// cd testdata
	// wat2wasm --debug-names inoutdispatcher.wat
	// wat2wasm --debug-names inoutdispatcherclient.wat

	//go:embed testdata/inoutdispatcher.wasm
	inoutdispatcherWasm []byte
	//go:embed testdata/inoutdispatcherclient.wasm
	inoutdispatcherclientWasm []byte
)

func main() {
	ctx := context.Background()

	r := wazy.NewRuntime(ctx)
	defer r.Close(ctx)

	// The client imports the inoutdispatcher module that reads from stdin and writes to stdout.
	// This means that we need multiple instances of the inoutdispatcher module to have different stdin/stdout.
	// This example demonstrates a way to do that.
	type mod struct {
		in  bytes.Buffer
		out bytes.Buffer

		client api.Module
	}

	wasi_snapshot_preview1.MustInstantiate(ctx, r)

	idm, err := r.CompileModule(ctx, inoutdispatcherWasm)
	if err != nil {
		log.Panicln(err)
	}
	idcm, err := r.CompileModule(ctx, inoutdispatcherclientWasm)
	if err != nil {
		log.Panicln(err)
	}

	const numInstances = 3
	mods := make([]*mod, numInstances)
	for i := range mods {
		mods[i] = &mod{}
		m := mods[i]

		const inoutDispatcherModuleName = "inoutdispatcher"

		dispatcherInstance, err := r.InstantiateModule(ctx, idm,
			wazy.NewModuleConfig().
				WithStdin(&m.in).
				WithStdout(&m.out).
				WithName("")) // Makes it an anonymous module.
		if err != nil {
			log.Panicln(err)
		}

		ctx = api.WithImportResolver(ctx, func(name string) api.Module {
			if name == inoutDispatcherModuleName {
				return dispatcherInstance
			}
			return nil
		})

		m.client, err = r.InstantiateModule(ctx, idcm, wazy.NewModuleConfig().WithName(fmt.Sprintf("m%d", i)))
		if err != nil {
			log.Panicln(err)
		}

	}

	for i, m := range mods {
		m.in.WriteString(fmt.Sprintf("Module instance #%d", i))
		_, err := m.client.ExportedFunction("dispatch").Call(ctx)
		if err != nil {
			log.Panicln(err)
		}
	}

	for i, m := range mods {
		fmt.Printf("out%d: %s\n", i, m.out.String())
	}

}
Output:
out0: Module instance #0
out1: Module instance #1
out2: Module instance #2
Example (StackIterator)
package main

import (
	"fmt"

	_ "embed"
	"github.com/samyfodil/wazy/api"
	"github.com/samyfodil/wazy/internal/wasm"
)

func main() {
	it := &fakeStackIterator{}

	for it.Next() {
		fn := it.Function()
		pc := it.ProgramCounter()
		fmt.Println("function:", fn.Definition().DebugName())
		fmt.Println("\tprogram counter:", pc)
		fmt.Println("\tsource offset:", fn.SourceOffsetForPC(pc))
	}

}

type fakeStackIterator struct {
	iteration    int
	def          api.FunctionDefinition
	args         []uint64
	pc           uint64
	sourceOffset uint64
}

func (s *fakeStackIterator) Next() bool {
	switch s.iteration {
	case 0:
		s.def = &mockFunctionDefinition{debugName: "fn0"}
		s.args = []uint64{1, 2, 3}
		s.pc = 5890831
		s.sourceOffset = 1234
	case 1:
		s.def = &mockFunctionDefinition{debugName: "fn1"}
		s.args = []uint64{}
		s.pc = 5899822
		s.sourceOffset = 7286
	case 2:
		s.def = &mockFunctionDefinition{debugName: "fn2"}
		s.args = []uint64{4}
		s.pc = 6820312
		s.sourceOffset = 935891
	case 3:
		return false
	}
	s.iteration++
	return true
}

func (s *fakeStackIterator) Function() api.InternalFunction {
	return internalFunction{
		definition:   s.def,
		sourceOffset: s.sourceOffset,
	}
}

func (s *fakeStackIterator) ProgramCounter() api.ProgramCounter {
	return api.ProgramCounter(s.pc)
}

type internalFunction struct {
	definition   api.FunctionDefinition
	sourceOffset uint64
}

func (f internalFunction) Definition() api.FunctionDefinition {
	return f.definition
}

func (f internalFunction) SourceOffsetForPC(pc api.ProgramCounter) uint64 {
	return f.sourceOffset
}

type mockFunctionDefinition struct {
	debugName string
	*wasm.FunctionDefinition
}

func (f *mockFunctionDefinition) DebugName() string {
	return f.debugName
}

func (f *mockFunctionDefinition) ParamTypes() []api.ValueType {
	return []api.ValueType{}
}

func (f *mockFunctionDefinition) ResultTypes() []api.ValueType {
	return []api.ValueType{}
}
Output:
function: fn0
	program counter: 5890831
	source offset: 1234
function: fn1
	program counter: 5899822
	source offset: 7286
function: fn2
	program counter: 6820312
	source offset: 935891

Index

Examples

Constants

View Source
const (
	// ExternTypeFuncName is the name of the WebAssembly 1.0 (20191205) Text Format field for ExternTypeFunc.
	ExternTypeFuncName = "func"
	// ExternTypeTableName is the name of the WebAssembly 1.0 (20191205) Text Format field for ExternTypeTable.
	ExternTypeTableName = "table"
	// ExternTypeMemoryName is the name of the WebAssembly 1.0 (20191205) Text Format field for ExternTypeMemory.
	ExternTypeMemoryName = "memory"
	// ExternTypeGlobalName is the name of the WebAssembly 1.0 (20191205) Text Format field for ExternTypeGlobal.
	ExternTypeGlobalName = "global"
)

The below are exported to consolidate parsing behavior for external types.

View Source
const CoreFeaturesV1 = CoreFeatureMutableGlobal

CoreFeaturesV1 are features included in the WebAssembly Core Specification 1.0. As of late 2022, this is the only version that is a Web Standard (W3C Recommendation).

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/

CoreFeaturesV2 are features included in the WebAssembly Core Specification 2.0 (20220419). As of late 2022, version 2.0 is a W3C working draft, not yet a Web Standard (W3C Recommendation).

See https://www.w3.org/TR/2022/WD-wasm-core-2-20220419/appendix/changes.html#release-1-1

Variables

This section is empty.

Functions

func BenchmarkFunctionListener

func BenchmarkFunctionListener(n int, module Module, stack []StackFrame, listener FunctionListener)

BenchmarkFunctionListener implements a benchmark for function listeners.

The benchmark calls Before and After methods repeatedly using the provided module an stack frames to invoke the methods.

The stack frame is a representation of the call stack that the Before method will be invoked with. The top of the stack is stored at index zero. The stack must contain at least one frame or the benchmark will fail.

func DecodeExternref

func DecodeExternref(input uint64) uintptr

DecodeExternref decodes the input as a ValueTypeExternref.

See EncodeExternref

func DecodeF32

func DecodeF32(input uint64) float32

DecodeF32 decodes the input as a ValueTypeF32.

See EncodeF32

func DecodeF64

func DecodeF64(input uint64) float64

DecodeF64 decodes the input as a ValueTypeF64.

See EncodeF64

func DecodeI32

func DecodeI32(input uint64) int32

DecodeI32 decodes the input as a ValueTypeI32.

func DecodeU32

func DecodeU32(input uint64) uint32

DecodeU32 decodes the input as a ValueTypeI32.

func EncodeExternref

func EncodeExternref(input uintptr) uint64

EncodeExternref encodes the input as a ValueTypeExternref.

See DecodeExternref

func EncodeF32

func EncodeF32(input float32) uint64

EncodeF32 encodes the input as a ValueTypeF32.

See DecodeF32

func EncodeF64

func EncodeF64(input float64) uint64

EncodeF64 encodes the input as a ValueTypeF64.

See EncodeF32

func EncodeI32

func EncodeI32(input int32) uint64

EncodeI32 encodes the input as a ValueTypeI32.

func EncodeI64

func EncodeI64(input int64) uint64

EncodeI64 encodes the input as a ValueTypeI64.

func EncodeU32

func EncodeU32(input uint32) uint64

EncodeU32 encodes the input as a ValueTypeI32.

func ExternTypeName

func ExternTypeName(et ExternType) string

ExternTypeName returns the name of the WebAssembly 1.0 (20191205) Text Format field of the given type.

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#exports%E2%91%A4

func GetCompilationWorkers

func GetCompilationWorkers(ctx context.Context) int

GetCompilationWorkers returns the desired number of compilation workers. The minimum value returned is 1.

func ValueTypeName

func ValueTypeName(t ValueType) string

ValueTypeName returns the type name of the given ValueType as a string. These type names match the names used in the WebAssembly text format.

Note: This returns "unknown", if an undefined ValueType value is passed.

func WithCloseNotifier

func WithCloseNotifier(ctx context.Context, notifier CloseNotifier) context.Context

WithCloseNotifier registers the given CloseNotifier into the given context.Context.

func WithCompilationWorkers

func WithCompilationWorkers(ctx context.Context, workers int) context.Context

WithCompilationWorkers sets the desired number of compilation workers.

func WithFunctionListenerFactory

func WithFunctionListenerFactory(ctx context.Context, factory FunctionListenerFactory) context.Context

WithFunctionListenerFactory registers a FunctionListenerFactory with the context.

func WithImportResolver

func WithImportResolver(ctx context.Context, resolver ImportResolver) context.Context

WithImportResolver returns a new context with the given ImportResolver.

func WithMemoryAllocator

func WithMemoryAllocator(ctx context.Context, allocator MemoryAllocator) context.Context

WithMemoryAllocator registers the given MemoryAllocator into the given context.Context. The context must be passed when initializing a module.

func WithSnapshotter

func WithSnapshotter(ctx context.Context) context.Context

WithSnapshotter enables snapshots. Passing the returned context to a exported function invocation enables snapshots, and allows host functions to retrieve the Snapshotter using GetSnapshotter.

Types

type CloseNotifier

type CloseNotifier interface {
	// CloseNotify is a notification that occurs *before* an api.Module is
	// closed. `exitCode` is zero on success or in the case there was no exit
	// code.
	//
	// Notes:
	//   - This does not return an error because the module will be closed
	//     unconditionally.
	//   - Do not panic from this function as it doing so could cause resource
	//     leaks.
	//   - While this is only called once per module, if configured for
	//     multiple modules, it will be called for each, e.g. on runtime close.
	CloseNotify(ctx context.Context, exitCode uint32)
}

CloseNotifier is a notification hook, invoked when a module is closed.

Note: This is experimental progress towards #1197, and likely to change. Do not expose this in shared libraries as it can cause version locks.

type CloseNotifyFunc

type CloseNotifyFunc func(ctx context.Context, exitCode uint32)

CloseNotifyFunc is a convenience for defining inlining a CloseNotifier.

func (CloseNotifyFunc) CloseNotify

func (f CloseNotifyFunc) CloseNotify(ctx context.Context, exitCode uint32)

CloseNotify implements CloseNotifier.CloseNotify.

type Closer

type Closer interface {
	// Close closes the resource.
	//
	// Note: The context parameter is used for value lookup, such as for
	// logging. A canceled or otherwise done context will not prevent Close
	// from succeeding.
	Close(context.Context) error
}

Closer closes a resource.

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type CoreFeatures

type CoreFeatures uint64

CoreFeatures is a bit flag of WebAssembly Core specification features. See https://github.com/WebAssembly/proposals for proposals and their status.

Constants define individual features, such as CoreFeatureMultiValue, or groups of "finished" features, assigned to a WebAssembly Core Specification version, e.g. CoreFeaturesV1 or CoreFeaturesV2.

Note: Numeric values are not intended to be interpreted except as bit flags.

const (
	// CoreFeatureBulkMemoryOperations adds instructions modify ranges of
	// memory or table entries ("bulk-memory-operations"). This is included in
	// CoreFeaturesV2, but not CoreFeaturesV1.
	//
	// Here are the notable effects:
	//   - Adds `memory.fill`, `memory.init`, `memory.copy` and `data.drop`
	//     instructions.
	//   - Adds `table.init`, `table.copy` and `elem.drop` instructions.
	//   - Introduces a "passive" form of element and data segments.
	//   - Stops checking "active" element and data segment boundaries at
	//     compile-time, meaning they can error at runtime.
	//
	// Note: "bulk-memory-operations" is mixed with the "reference-types"
	// proposal due to the WebAssembly Working Group merging them
	// "mutually dependent". Therefore, enabling this feature requires enabling
	// CoreFeatureReferenceTypes, and vice-versa.
	//
	// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/bulk-memory-operations/Overview.md
	// https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/reference-types/Overview.md and
	// https://github.com/WebAssembly/spec/pull/1287
	CoreFeatureBulkMemoryOperations CoreFeatures = 1 << iota

	// CoreFeatureMultiValue enables multiple values ("multi-value"). This is
	// included in CoreFeaturesV2, but not CoreFeaturesV1.
	//
	// Here are the notable effects:
	//   - Function (`func`) types allow more than one result.
	//   - Block types (`block`, `loop` and `if`) can be arbitrary function
	//     types.
	//
	// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/multi-value/Overview.md
	CoreFeatureMultiValue

	// CoreFeatureMutableGlobal allows globals to be mutable. This is included
	// in both CoreFeaturesV1 and CoreFeaturesV2.
	//
	// When false, an api.Global can never be cast to an api.MutableGlobal, and
	// any wasm that includes global vars will fail to parse.
	CoreFeatureMutableGlobal

	// CoreFeatureNonTrappingFloatToIntConversion enables non-trapping
	// float-to-int conversions ("nontrapping-float-to-int-conversion"). This
	// is included in CoreFeaturesV2, but not CoreFeaturesV1.
	//
	// The only effect of enabling is allowing the following instructions,
	// which return 0 on NaN instead of panicking.
	//   - `i32.trunc_sat_f32_s`
	//   - `i32.trunc_sat_f32_u`
	//   - `i32.trunc_sat_f64_s`
	//   - `i32.trunc_sat_f64_u`
	//   - `i64.trunc_sat_f32_s`
	//   - `i64.trunc_sat_f32_u`
	//   - `i64.trunc_sat_f64_s`
	//   - `i64.trunc_sat_f64_u`
	//
	// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/nontrapping-float-to-int-conversion/Overview.md
	CoreFeatureNonTrappingFloatToIntConversion

	// CoreFeatureReferenceTypes enables various instructions and features
	// related to table and new reference types. This is included in
	// CoreFeaturesV2, but not CoreFeaturesV1.
	//
	//   - Introduction of new value types: `funcref` and `externref`.
	//   - Support for the following new instructions:
	//     - `ref.null`
	//     - `ref.func`
	//     - `ref.is_null`
	//     - `table.fill`
	//     - `table.get`
	//     - `table.grow`
	//     - `table.set`
	//     - `table.size`
	//   - Support for multiple tables per module:
	//     - `call_indirect`, `table.init`, `table.copy` and `elem.drop`
	//   - Support for instructions can take non-zero table index.
	//     - Element segments can take non-zero table index.
	//
	// Note: "reference-types" is mixed with the "bulk-memory-operations"
	// proposal due to the WebAssembly Working Group merging them
	// "mutually dependent". Therefore, enabling this feature requires enabling
	// CoreFeatureBulkMemoryOperations, and vice-versa.
	//
	// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/bulk-memory-operations/Overview.md
	// https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/reference-types/Overview.md and
	// https://github.com/WebAssembly/spec/pull/1287
	CoreFeatureReferenceTypes

	// CoreFeatureSignExtensionOps enables sign extension instructions
	// ("sign-extension-ops"). This is included in CoreFeaturesV2, but not
	// CoreFeaturesV1.
	//
	// Adds instructions:
	//   - `i32.extend8_s`
	//   - `i32.extend16_s`
	//   - `i64.extend8_s`
	//   - `i64.extend16_s`
	//   - `i64.extend32_s`
	//
	// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/sign-extension-ops/Overview.md
	CoreFeatureSignExtensionOps

	// CoreFeatureSIMD enables the vector value type and vector instructions
	// (aka SIMD). This is included in CoreFeaturesV2, but not CoreFeaturesV1.
	//
	// Note: The instruction list is too long to enumerate in godoc.
	// See https://github.com/WebAssembly/spec/blob/wg-2.0.draft1/proposals/simd/SIMD.md
	CoreFeatureSIMD
)
const CoreFeatureExceptionHandling CoreFeatures = CoreFeatureSIMD << 4

CoreFeatureExceptionHandling enables exception handling instructions. See https://github.com/WebAssembly/exception-handling for further details.

const CoreFeatureExtendedConst CoreFeatures = CoreFeatureSIMD << 3

CoreFeatureExtendedConst enables extended constant expressions.

  • Enables i32.add/sub/mul and i64.add/sub/mul in constant expressions.
  • Enables references to any previous global index in constant expressions, instead of just imported globals.

See https://github.com/WebAssembly/extended-const for further details.

const CoreFeatureTailCall CoreFeatures = CoreFeatureSIMD << 2

CoreFeatureTailCall enables tail call instructions ("tail-call").

const CoreFeatureTypedFunctionReferences CoreFeatures = CoreFeatureSIMD << 5

CoreFeatureTypedFunctionReferences enables typed function references. See https://github.com/WebAssembly/function-references for further details.

func (CoreFeatures) IsEnabled

func (f CoreFeatures) IsEnabled(feature CoreFeatures) bool

IsEnabled returns true if the feature (or group of features) is enabled.

func (CoreFeatures) RequireEnabled

func (f CoreFeatures) RequireEnabled(feature CoreFeatures) error

RequireEnabled returns an error if the feature (or group of features) is not enabled.

func (CoreFeatures) SetEnabled

func (f CoreFeatures) SetEnabled(feature CoreFeatures, val bool) CoreFeatures

SetEnabled enables or disables the feature or group of features.

func (CoreFeatures) String

func (f CoreFeatures) String() string

String implements fmt.Stringer by returning each enabled feature.

type CustomSection

type CustomSection interface {
	// Name is the name of the custom section
	Name() string
	// Data is the raw data of the custom section
	Data() []byte

	internalapi.WazyOnly
}

CustomSection contains the name and raw data of a custom section.

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type ExportDefinition

type ExportDefinition interface {
	// ModuleName is the possibly empty name of the module defining this
	// export.
	//
	// Note: This may be different from Module.Name, because a compiled module
	// can be instantiated multiple times as different names.
	ModuleName() string

	// Index is the position in the module's index, imports first.
	Index() uint32

	// Import returns true with the module and name when this was imported.
	// Otherwise, it returns false.
	//
	// Note: Empty string is valid for both names in the WebAssembly Core
	// Specification, so "" "" is possible.
	Import() (moduleName, name string, isImport bool)

	// ExportNames include all exported names.
	//
	// Note: The empty name is allowed in the WebAssembly Core Specification,
	// so "" is possible.
	ExportNames() []string

	internalapi.WazyOnly
}

ExportDefinition is a WebAssembly type exported in a module (wazy.CompiledModule).

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#exports%E2%91%A0

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type ExternType

type ExternType = byte

ExternType classifies imports and exports with their respective types.

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#external-types%E2%91%A0

const (
	ExternTypeFunc   ExternType = 0x00
	ExternTypeTable  ExternType = 0x01
	ExternTypeMemory ExternType = 0x02
	ExternTypeGlobal ExternType = 0x03
)

type Function

type Function interface {
	// Definition is metadata about this function from its defining module.
	Definition() FunctionDefinition

	// Call invokes the function with the given parameters and returns any
	// results or an error for any failure looking up or invoking the function.
	//
	// Encoding is described in Definition, and supplying an incorrect count of
	// parameters vs FunctionDefinition.ParamTypes is an error.
	//
	// If the exporting Module was closed during this call, the error returned
	// may be a sys.ExitError. See Module.CloseWithExitCode for details.
	//
	// Call is not goroutine-safe, therefore it is recommended to create
	// another Function if you want to invoke the same function concurrently.
	// On the other hand, sequential invocations of Call is allowed.
	// However, this should not be called multiple times until the previous Call returns.
	//
	// To safely encode/decode params/results expressed as uint64, users are encouraged to
	// use api.EncodeXXX or DecodeXXX functions. See the docs on api.ValueType.
	//
	// When RuntimeConfig.WithCloseOnContextDone is toggled, the invocation of this Call method is ensured to be closed
	// whenever one of the three conditions is met. In the event of close, sys.ExitError will be returned and
	// the api.Module from which this api.Function is derived will be made closed. See the documentation of
	// WithCloseOnContextDone on wazy.RuntimeConfig for detail. See examples in context_done_example_test.go for
	// the end-to-end demonstrations of how these terminations can be performed.
	Call(ctx context.Context, params ...uint64) ([]uint64, error)

	// CallWithStack is an optimized variation of Call that saves memory
	// allocations when the stack slice is reused across calls.
	//
	// Stack length must be at least the max of parameter or result length.
	// The caller adds parameters in order to the stack, and reads any results
	// in order from the stack, except in the error case.
	//
	// For example, the following reuses the same stack slice to call searchFn
	// repeatedly saving one allocation per iteration:
	//
	//	stack := make([]uint64, 4)
	//	for i, search := range searchParams {
	//		// copy the next params to the stack
	//		copy(stack, search)
	//		if err := searchFn.CallWithStack(ctx, stack); err != nil {
	//			return err
	//		} else if stack[0] == 1 { // found
	//			return i // searchParams[i] matched!
	//		}
	//	}
	//
	// # Notes
	//
	//   - This is similar to GoModuleFunction, except for using calling functions
	//     instead of implementing them. Moreover, this is used regardless of
	//     whether the callee is a host or wasm defined function.
	CallWithStack(ctx context.Context, stack []uint64) error

	internalapi.WazyOnly
}

Function is a WebAssembly function exported from an instantiated module (wazy.Runtime InstantiateModule).

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#syntax-func

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type FunctionDefinition

type FunctionDefinition interface {
	ExportDefinition

	// Name is the module-defined name of the function, which is not necessarily
	// the same as its export name.
	Name() string

	// DebugName identifies this function based on its Index or Name in the
	// module. This is used for errors and stack traces. e.g. "env.abort".
	//
	// When the function name is empty, a substitute name is generated by
	// prefixing '$' to its position in the index. Ex ".$0" is the
	// first function (possibly imported) in an unnamed module.
	//
	// The format is dot-delimited module and function name, but there are no
	// restrictions on the module and function name. This means either can be
	// empty or include dots. e.g. "x.x.x" could mean module "x" and name "x.x",
	// or it could mean module "x.x" and name "x".
	//
	// Note: This name is stable regardless of import or export. For example,
	// if Import returns true, the value is still based on the Name or Index
	// and not the imported function name.
	DebugName() string

	// GoFunction is non-nil when implemented by the embedder instead of a wasm
	// binary, e.g. via wazy.HostModuleBuilder
	//
	// The expected results are nil, GoFunction or GoModuleFunction.
	GoFunction() interface{}

	// ParamTypes are the possibly empty sequence of value types accepted by a
	// function with this signature.
	//
	// See ValueType documentation for encoding rules.
	ParamTypes() []ValueType

	// ParamNames are index-correlated with ParamTypes or nil if not available
	// for one or more parameters.
	ParamNames() []string

	// ResultTypes are the results of the function.
	//
	// When WebAssembly 1.0 (20191205), there can be at most one result.
	// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#result-types%E2%91%A0
	//
	// See ValueType documentation for encoding rules.
	ResultTypes() []ValueType

	// ResultNames are index-correlated with ResultTypes or nil if not
	// available for one or more results.
	ResultNames() []string

	internalapi.WazyOnly
}

FunctionDefinition is a WebAssembly function exported in a module (wazy.CompiledModule).

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#exports%E2%91%A0

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type FunctionListener

type FunctionListener interface {
	// Before is invoked before a function is called.
	//
	// There is always one corresponding call to After or Abort for each call to
	// Before. This guarantee allows the listener to maintain an internal stack
	// to perform correlations between the entry and exit of functions.
	//
	// # Params
	//
	//   - ctx: the context of the caller function which must be the same
	//	   instance or parent of the result.
	//   - mod: the calling module.
	//   - def: the function definition.
	//   - params:  api.ValueType encoded parameters.
	//   - stackIterator: iterator on the call stack. At least one entry is
	//     guaranteed (the called function), whose Args() will be equal to
	//     params. The iterator will be reused between calls to Before.
	//
	// Note: api.Memory is meant for inspection, not modification.
	// mod can be cast to InternalModule to read non-exported globals.
	Before(ctx context.Context, mod Module, def FunctionDefinition, params []uint64, stackIterator StackIterator)

	// After is invoked after a function is called.
	//
	// # Params
	//
	//   - ctx: the context of the caller function.
	//   - mod: the calling module.
	//   - def: the function definition.
	//   - results: api.ValueType encoded results.
	//
	// # Notes
	//
	//   - api.Memory is meant for inspection, not modification.
	//   - This is not called when a host function panics, or a guest function traps.
	//      See Abort for more details.
	After(ctx context.Context, mod Module, def FunctionDefinition, results []uint64)

	// Abort is invoked when a function does not return due to a trap or panic.
	//
	// # Params
	//
	//   - ctx: the context of the caller function.
	//   - mod: the calling module.
	//   - def: the function definition.
	//   - err: the error value representing the reason why the function aborted.
	//
	// # Notes
	//
	//   - api.Memory is meant for inspection, not modification.
	Abort(ctx context.Context, mod Module, def FunctionDefinition, err error)
}

FunctionListener can be registered for any function via FunctionListenerFactory to be notified when the function is called.

type FunctionListenerFactory

type FunctionListenerFactory interface {
	// NewFunctionListener returns a FunctionListener for a defined function.
	// If nil is returned, no listener will be notified.
	NewFunctionListener(FunctionDefinition) FunctionListener
}

FunctionListenerFactory returns FunctionListeners to be notified when a function is called.

func MultiFunctionListenerFactory

func MultiFunctionListenerFactory(factories ...FunctionListenerFactory) FunctionListenerFactory

MultiFunctionListenerFactory constructs a FunctionListenerFactory which combines the listeners created by each of the factories passed as arguments.

This function is useful when multiple listeners need to be hooked to a module because the propagation mechanism based on installing a listener factory in the context.Context used when instantiating modules allows for a single listener to be installed.

The stack iterator passed to the Before method is reset so that each listener can iterate the call stack independently without impacting the ability of other listeners to do so.

type FunctionListenerFactoryFunc

type FunctionListenerFactoryFunc func(FunctionDefinition) FunctionListener

FunctionListenerFactoryFunc is a function type implementing the FunctionListenerFactory interface, making it possible to use regular functions and methods as factory of function listeners.

func (FunctionListenerFactoryFunc) NewFunctionListener

NewFunctionListener satisfies the FunctionListenerFactory interface, calls f.

type FunctionListenerFunc

type FunctionListenerFunc func(context.Context, Module, FunctionDefinition, []uint64, StackIterator)

FunctionListenerFunc is a function type implementing the FunctionListener interface, making it possible to use regular functions and methods as listeners of function invocation.

The FunctionListener interface declares two methods (Before and After), but this type invokes its value only when Before is called. It is best suites for cases where the host does not need to perform correlation between the start and end of the function call.

func (FunctionListenerFunc) Abort

Abort is declared to satisfy the FunctionListener interface, but it does nothing.

func (FunctionListenerFunc) After

After is declared to satisfy the FunctionListener interface, but it does nothing.

func (FunctionListenerFunc) Before

func (f FunctionListenerFunc) Before(ctx context.Context, mod Module, def FunctionDefinition, params []uint64, stackIterator StackIterator)

Before satisfies the FunctionListener interface, calls f.

type Global

type Global interface {
	fmt.Stringer

	// Type describes the numeric type of the global.
	Type() ValueType

	// Get returns the last known value of this global.
	//
	// See Type for how to decode this value to a Go type.
	Get() uint64
}

Global is a WebAssembly 1.0 (20191205) global exported from an instantiated module (wazy.Runtime InstantiateModule).

For example, if the value is not mutable, you can read it once:

offset := module.ExportedGlobal("memory.offset").Get()

Globals are allowed by specification to be mutable. However, this can be disabled by configuration. When in doubt, safe cast to find out if the value can change. Here's an example:

offset := module.ExportedGlobal("memory.offset")
if _, ok := offset.(api.MutableGlobal); ok {
	// value can change
} else {
	// value is constant
}

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#globals%E2%91%A0

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type GoFunc

type GoFunc func(ctx context.Context, stack []uint64)

GoFunc is a convenience for defining an inlined function.

For example, the following returns the sum of two uint32 parameters:

api.GoFunc(func(ctx context.Context, stack []uint64) {
	x, y := api.DecodeU32(stack[0]), api.DecodeU32(stack[1])
	stack[0] = api.EncodeU32(x + y)
})

func (GoFunc) Call

func (f GoFunc) Call(ctx context.Context, stack []uint64)

Call implements GoFunction.Call.

type GoFunction

type GoFunction interface {
	Call(ctx context.Context, stack []uint64)
}

GoFunction is an optimized form of GoModuleFunction which doesn't require the Module parameter. See GoFunc for an example.

For example, this function does not need to use the importing module's memory or exported functions.

type GoModuleFunc

type GoModuleFunc func(ctx context.Context, mod Module, stack []uint64)

GoModuleFunc is a convenience for defining an inlined function.

For example, the following returns an uint32 value read from parameter zero:

api.GoModuleFunc(func(ctx context.Context, mod api.Module, stack []uint64) {
	offset := api.DecodeU32(stack[0]) // read the parameter from the stack

	ret, ok := mod.Memory().ReadUint32Le(offset)
	if !ok {
		panic("out of memory")
	}

	stack[0] = api.EncodeU32(ret) // add the result back to the stack.
})

func (GoModuleFunc) Call

func (f GoModuleFunc) Call(ctx context.Context, mod Module, stack []uint64)

Call implements GoModuleFunction.Call.

type GoModuleFunction

type GoModuleFunction interface {
	Call(ctx context.Context, mod Module, stack []uint64)
}

GoModuleFunction is a Function implemented in Go instead of a wasm binary. The Module parameter is the calling module, used to access memory or exported functions. See GoModuleFunc for an example.

The stack is includes any parameters encoded according to their ValueType. Its length is the max of parameter or result length. When there are results, write them in order beginning at index zero. Do not use the stack after the function returns.

Here's a typical way to read three parameters and write back one.

// read parameters off the stack in index order
argv, argvBuf := api.DecodeU32(stack[0]), api.DecodeU32(stack[1])

// write results back to the stack in index order
stack[0] = api.EncodeU32(ErrnoSuccess)

This function can be non-deterministic or cause side effects. It also has special properties not defined in the WebAssembly Core specification. Notably, this uses the caller's memory (via Module.Memory). See https://www.w3.org/TR/wasm-core-1/#host-functions%E2%91%A0

Most end users will not define functions directly with this, as they will use reflection or code generators instead. These approaches are more idiomatic as they can map go types to ValueType. This type is exposed for those willing to trade usability and safety for performance.

To safely decode/encode values from/to the uint64 stack, users are encouraged to use api.EncodeXXX or api.DecodeXXX functions. See the docs on api.ValueType.

type ImportResolver

type ImportResolver func(name string) Module

ImportResolver is an experimental func type that, if set, will be used as the first step in resolving imports. See issue 2294. If the import name is not found, it should return nil.

type InternalFunction

type InternalFunction interface {
	// Definition provides introspection into the function's names and
	// signature.
	Definition() FunctionDefinition

	// SourceOffsetForPC resolves a program counter into its corresponding
	// offset in the Code section of the module this function belongs to.
	// The source offset is meant to help map the function calls to their
	// location in the original source files. Returns 0 if the offset cannot
	// be calculated.
	SourceOffsetForPC(pc ProgramCounter) uint64
}

InternalFunction exposes some information about a function instance.

type InternalModule

type InternalModule interface {
	Module

	// NumGlobal returns the count of all globals in the module.
	NumGlobal() int

	// Global provides a read-only view for a given global index.
	//
	// The methods panics if i is out of bounds.
	Global(i int) Global
}

InternalModule is an api.Module that exposes additional information.

type LinearMemory

type LinearMemory interface {
	// Reallocates the linear memory to size bytes in length.
	//
	// Notes:
	//   - To back a shared memory, Reallocate can't change the address of the
	//     backing []byte (only its length/capacity may change).
	//   - Reallocate may return nil if fails to grow the LinearMemory. This
	//     condition may or may not be handled gracefully by the Wasm module.
	Reallocate(size uint64) []byte
	// Free the backing memory buffer.
	Free()
}

LinearMemory is an expandable []byte that backs a Wasm linear memory.

type Memory

type Memory interface {
	// Definition is metadata about this memory from its defining module.
	Definition() MemoryDefinition

	// Size returns the memory size in bytes available.
	// e.g. If the underlying memory has 1 page: 65536
	//
	// # Notes
	//
	//   - This overflows (returns zero) if the memory has the maximum 65536 pages.
	// 	   As a workaround until wazy v2 to fix the return type, use Grow(0) to obtain the current pages and
	//     multiply by 65536.
	//
	// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#-hrefsyntax-instr-memorymathsfmemorysize%E2%91%A0
	Size() uint32

	// Grow increases memory by the delta in pages (65536 bytes per page).
	// The return val is the previous memory size in pages, or false if the
	// delta was ignored as it exceeds MemoryDefinition.Max.
	//
	// # Notes
	//
	//   - This is the same as the "memory.grow" instruction defined in the
	//	   WebAssembly Core Specification, except returns false instead of -1.
	//   - When this returns true, any shared views via Read must be refreshed.
	//
	// See MemorySizer Read and https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#grow-mem
	Grow(deltaPages uint32) (previousPages uint32, ok bool)

	// ReadByte reads a single byte from the underlying buffer at the offset or returns false if out of range.
	ReadByte(offset uint32) (byte, bool)

	// ReadUint16Le reads a uint16 in little-endian encoding from the underlying buffer at the offset in or returns
	// false if out of range.
	ReadUint16Le(offset uint32) (uint16, bool)

	// ReadUint32Le reads a uint32 in little-endian encoding from the underlying buffer at the offset in or returns
	// false if out of range.
	ReadUint32Le(offset uint32) (uint32, bool)

	// ReadFloat32Le reads a float32 from 32 IEEE 754 little-endian encoded bits in the underlying buffer at the offset
	// or returns false if out of range.
	// See math.Float32bits
	ReadFloat32Le(offset uint32) (float32, bool)

	// ReadUint64Le reads a uint64 in little-endian encoding from the underlying buffer at the offset or returns false
	// if out of range.
	ReadUint64Le(offset uint32) (uint64, bool)

	// ReadFloat64Le reads a float64 from 64 IEEE 754 little-endian encoded bits in the underlying buffer at the offset
	// or returns false if out of range.
	//
	// See math.Float64bits
	ReadFloat64Le(offset uint32) (float64, bool)

	// Read reads byteCount bytes from the underlying buffer at the offset or
	// returns false if out of range.
	//
	// For example, to search for a NUL-terminated string:
	//	buf, _ = memory.Read(offset, byteCount)
	//	n := bytes.IndexByte(buf, 0)
	//	if n < 0 {
	//		// Not found!
	//	}
	//
	// Write-through
	//
	// This returns a view of the underlying memory, not a copy. This means any
	// writes to the slice returned are visible to Wasm, and any updates from
	// Wasm are visible reading the returned slice.
	//
	// For example:
	//	buf, _ = memory.Read(offset, byteCount)
	//	buf[1] = 'a' // writes through to memory, meaning Wasm code see 'a'.
	//
	// If you don't intend-write through, make a copy of the returned slice.
	//
	// When to refresh Read
	//
	// The returned slice disconnects on any capacity change. For example,
	// `buf = append(buf, 'a')` might result in a slice that is no longer
	// shared. The same exists Wasm side. For example, if Wasm changes its
	// memory capacity, ex via "memory.grow"), the host slice is no longer
	// shared. Those who need a stable view must set Wasm memory min=max, or
	// use wazy.RuntimeConfig WithMemoryCapacityPages to ensure max is always
	// allocated.
	Read(offset, byteCount uint32) ([]byte, bool)

	// WriteByte writes a single byte to the underlying buffer at the offset in or returns false if out of range.
	WriteByte(offset uint32, v byte) bool

	// WriteUint16Le writes the value in little-endian encoding to the underlying buffer at the offset in or returns
	// false if out of range.
	WriteUint16Le(offset uint32, v uint16) bool

	// WriteUint32Le writes the value in little-endian encoding to the underlying buffer at the offset in or returns
	// false if out of range.
	WriteUint32Le(offset, v uint32) bool

	// WriteFloat32Le writes the value in 32 IEEE 754 little-endian encoded bits to the underlying buffer at the offset
	// or returns false if out of range.
	//
	// See math.Float32bits
	WriteFloat32Le(offset uint32, v float32) bool

	// WriteUint64Le writes the value in little-endian encoding to the underlying buffer at the offset in or returns
	// false if out of range.
	WriteUint64Le(offset uint32, v uint64) bool

	// WriteFloat64Le writes the value in 64 IEEE 754 little-endian encoded bits to the underlying buffer at the offset
	// or returns false if out of range.
	//
	// See math.Float64bits
	WriteFloat64Le(offset uint32, v float64) bool

	// Write writes the slice to the underlying buffer at the offset or returns false if out of range.
	Write(offset uint32, v []byte) bool

	// WriteString writes the string to the underlying buffer at the offset or returns false if out of range.
	WriteString(offset uint32, v string) bool

	internalapi.WazyOnly
}

Memory allows restricted access to a module's memory. Notably, this does not allow growing.

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#storage%E2%91%A0

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.
  • This includes all value types available in WebAssembly 1.0 (20191205) and all are encoded little-endian.

type MemoryAllocator

type MemoryAllocator interface {
	// Allocate should create a new LinearMemory with the given specification:
	// cap is the suggested initial capacity for the backing []byte,
	// and max the maximum length that will ever be requested.
	//
	// Notes:
	//   - To back a shared memory, the address of the backing []byte cannot
	//     change. This is checked at runtime. Implementations should document
	//     if the returned LinearMemory meets this requirement.
	Allocate(cap, max uint64) LinearMemory
}

MemoryAllocator is a memory allocation hook, invoked to create a LinearMemory.

type MemoryAllocatorFunc

type MemoryAllocatorFunc func(cap, max uint64) LinearMemory

MemoryAllocatorFunc is a convenience for defining inlining a MemoryAllocator.

func (MemoryAllocatorFunc) Allocate

func (f MemoryAllocatorFunc) Allocate(cap, max uint64) LinearMemory

Allocate implements MemoryAllocator.Allocate.

type MemoryDefinition

type MemoryDefinition interface {
	ExportDefinition

	// Min returns the possibly zero initial count of 64KB pages.
	Min() uint32

	// Max returns the possibly zero max count of 64KB pages, or false if
	// unbounded.
	Max() (uint32, bool)

	internalapi.WazyOnly
}

MemoryDefinition is a WebAssembly memory exported in a module (wazy.CompiledModule). Units are in pages (64KB).

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#exports%E2%91%A0

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type Module

type Module interface {
	fmt.Stringer

	// Name is the name this module was instantiated with. Exported functions can be imported with this name.
	Name() string

	// Memory returns a memory defined in this module or nil if there are none wasn't.
	Memory() Memory

	// ExportedFunction returns a function exported from this module or nil if it wasn't.
	//
	// # Notes
	//   - The default wazy.ModuleConfig attempts to invoke `_start`, which
	//     in rare cases can close the module. When in doubt, check IsClosed prior
	//     to invoking a function export after instantiation.
	//   - The semantics of host functions assumes the existence of an "importing module" because, for example, the host function needs access to
	//     the memory of the importing module. Therefore, direct use of ExportedFunction is forbidden for host modules.
	//     Practically speaking, it is usually meaningless to directly call a host function from Go code as it is already somewhere in Go code.
	ExportedFunction(name string) Function

	// ExportedFunctionDefinitions returns all the exported function
	// definitions in this module, keyed on export name.
	ExportedFunctionDefinitions() map[string]FunctionDefinition

	// ExportedMemory returns a memory exported from this module or nil if it wasn't.
	//
	// WASI modules require exporting a Memory named "memory". This means that a module successfully initialized
	// as a WASI Command or Reactor will never return nil for this name.
	//
	// See https://github.com/WebAssembly/WASI/blob/snapshot-01/design/application-abi.md#current-unstable-abi
	ExportedMemory(name string) Memory

	// ExportedMemoryDefinitions returns all the exported memory definitions
	// in this module, keyed on export name.
	//
	// Note: As of WebAssembly Core Specification 2.0, there can be at most one
	// memory.
	ExportedMemoryDefinitions() map[string]MemoryDefinition

	// ExportedGlobal a global exported from this module or nil if it wasn't.
	ExportedGlobal(name string) Global

	// CloseWithExitCode releases resources allocated for this Module. Use a non-zero exitCode parameter to indicate a
	// failure to ExportedFunction callers.
	//
	// The error returned here, if present, is about resource de-allocation (such as I/O errors). Only the last error is
	// returned, so a non-nil return means at least one error happened. Regardless of error, this Module will
	// be removed, making its name available again.
	//
	// Calling this inside a host function is safe, and may cause ExportedFunction callers to receive a sys.ExitError
	// with the exitCode.
	CloseWithExitCode(ctx context.Context, exitCode uint32) error

	// Closer closes this module by delegating to CloseWithExitCode with an exit code of zero.
	Closer

	// IsClosed returns true if the module is closed, so no longer usable.
	//
	// This can happen for the following reasons:
	//   - Closer was called directly.
	//   - A guest function called Closer indirectly, such as `_start` calling
	//     `proc_exit`, which internally closed the module.
	//   - wazy.RuntimeConfig `WithCloseOnContextDone` was enabled and a
	//     context completion closed the module.
	//
	// Where any of the above are possible, check this value before calling an
	// ExportedFunction, even if you didn't formerly receive a sys.ExitError.
	// sys.ExitError is only returned on non-zero code, something that closes
	// the module successfully will not result it one.
	IsClosed() bool

	internalapi.WazyOnly
}

Module is a sandboxed, ready to execute Wasm module. This can be used to get exported functions, etc.

In WebAssembly terminology, this corresponds to a "Module Instance", but wazy calls pre-instantiation module as "Compiled Module" as in wazy.CompiledModule, therefore we call this post-instantiation module simply "Module". See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#module-instances%E2%91%A0

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.
  • Closing the wazy.Runtime closes any Module it instantiated.

type MutableGlobal

type MutableGlobal interface {
	Global

	// Set updates the value of this global.
	//
	// See Global.Type for how to encode this value from a Go type.
	Set(v uint64)

	internalapi.WazyOnly
}

MutableGlobal is a Global whose value can be updated at runtime (variable).

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.

type ProgramCounter

type ProgramCounter uint64

ProgramCounter is an opaque value representing a specific execution point in a module. It is meant to be used with Function.SourceOffsetForPC and StackIterator.

type Snapshot

type Snapshot interface {
	// Restore sets the Wasm execution state to the capture. Because a host function
	// calling this is resetting the pointer to the executation stack, the host function
	// will not be able to return values in the normal way. ret is a slice of values the
	// host function intends to return from the restored function.
	Restore(ret []uint64)
}

Snapshot holds the execution state at the time of a Snapshotter.Snapshot call.

type Snapshotter

type Snapshotter interface {
	// Snapshot captures the current execution state.
	Snapshot() Snapshot
}

Snapshotter allows host functions to snapshot the WebAssembly execution environment.

func GetSnapshotter

func GetSnapshotter(ctx context.Context) Snapshotter

GetSnapshotter gets the Snapshotter from a host function. It is only present if WithSnapshotter was called with the function invocation context.

type StackFrame

type StackFrame struct {
	Function     Function
	Params       []uint64
	Results      []uint64
	PC           uint64
	SourceOffset uint64
}

StackFrame represents a frame on the call stack.

type StackIterator

type StackIterator interface {
	// Next moves the iterator to the next function in the stack. Returns
	// false if it reached the bottom of the stack.
	Next() bool
	// Function describes the function called by the current frame.
	Function() InternalFunction
	// ProgramCounter returns the program counter associated with the
	// function call.
	ProgramCounter() ProgramCounter
}

StackIterator allows iterating on each function of the call stack, starting from the top. At least one call to Next() is required to start the iteration.

Note: The iterator provides a view of the call stack at the time of iteration. As a result, parameter values may be different than the ones their function was called with.

func NewStackIterator

func NewStackIterator(stack ...StackFrame) StackIterator

NewStackIterator constructs a stack iterator from a list of stack frames. The top most frame is the last one.

type ValueType

type ValueType = byte

ValueType describes a parameter or result type mapped to a WebAssembly function signature.

The following describes how to convert between Wasm and Golang types:

  • ValueTypeI32 - EncodeU32 DecodeU32 for uint32 / EncodeI32 DecodeI32 for int32
  • ValueTypeI64 - uint64(int64)
  • ValueTypeF32 - EncodeF32 DecodeF32 from float32
  • ValueTypeF64 - EncodeF64 DecodeF64 from float64
  • ValueTypeExternref - unintptr(unsafe.Pointer(p)) where p is any pointer type in Go (e.g. *string)

e.g. Given a Text Format type use (param i64) (result i64), no conversion is necessary.

results, _ := fn(ctx, input)
result := result[0]

e.g. Given a Text Format type use (param f64) (result f64), conversion is necessary.

results, _ := fn(ctx, api.EncodeF64(input))
result := api.DecodeF64(result[0])

Note: This is a type alias as it is easier to encode and decode in the binary format.

See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-valtype

const (
	// ValueTypeI32 is a 32-bit integer.
	ValueTypeI32 ValueType = 0x7f
	// ValueTypeI64 is a 64-bit integer.
	ValueTypeI64 ValueType = 0x7e
	// ValueTypeF32 is a 32-bit floating point number.
	ValueTypeF32 ValueType = 0x7d
	// ValueTypeF64 is a 64-bit floating point number.
	ValueTypeF64 ValueType = 0x7c

	// ValueTypeExternref is a externref type.
	//
	// Note: in wazy, externref type value are opaque raw 64-bit pointers,
	// and the ValueTypeExternref type in the signature will be translated as
	// uintptr in wazy's API level.
	//
	// For example, given the import function:
	//	(func (import "env" "f") (param externref) (result externref))
	//
	// This can be defined in Go as:
	//  r.NewHostModuleBuilder("env").
	//		NewFunctionBuilder().
	//		WithGoFunction(api.GoFunc(func(ctx context.Context, stack []uint64) {
	//			// stack[0] holds the externref parameter as a uintptr; the
	//			// result is written back to stack[0].
	//		}), []api.ValueType{api.ValueTypeExternref}, []api.ValueType{api.ValueTypeExternref}).
	//		Export("f")
	//
	// Note: The usage of this type is toggled with api.CoreFeatureBulkMemoryOperations.
	ValueTypeExternref ValueType = 0x6f
)

Jump to

Keyboard shortcuts

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