wazy

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 31 Imported by: ? modules, 0 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.

README

wazy

A WebAssembly runtime written in pure Go — guest code from other languages, sandboxed, inside your process, with nothing to install at runtime.

Run code you didn't write. Ship a plugin system, execute a customer's untrusted script, or use a Rust or C library you would otherwise reach through cgo: compiled to Wasm it becomes a byte slice you go:embed and a function you call. The guest starts with nothing — no files beyond what you mount, no sockets unless you allow them, a fake clock on the WASI 0.1 path — you cap its memory with WithMemoryLimitPages, and a context deadline kills even a tight compiled loop with WithCloseOnContextDone. CI builds and runs guests from Rust, C, C++, Zig, TinyGo, AssemblyScript and Go, CGO_ENABLED=0, with no dependency beyond golang.org/x/sys.

Plugin contracts with types in them. Embedding Wasm normally means fn.Call(ctx, ptr, len), decoding a pair of i32s out of the guest's memory, and both halves hand-agreeing on layout and on who frees what. wazy runs WebAssembly components — a .wasm that carries its own typed interface — so string, records, lists, option and result cross as Go values, and a handle to a host object is a lifetime the runtime tracks and drops for you the moment you hand it a destructor.

Declare the contract in a small .wit interface file and implement your half in ordinary Go; the other half is anything that compiles to Wasm. A binary a stranger produced with cargo build --target wasm32-wasip2 runs unmodified, on the 114 WASI 0.2 host functions wazy implements: stdio, args and env, clocks, a mounted filesystem, randomness, TCP/UDP and DNS, HTTP in both directions. Sockets and HTTP stay unregistered until you switch them on; the filesystem hands over nothing until you mount something.

Guests that suspend and resume. wazy runs the WASI 0.3 async ABI: stream<T> and future<T>, subtasks, cancellation, backpressure and cooperative threads, with goroutines and channels as the substrate. It passes all 31 official async conformance suites. You call an async export exactly like a synchronous one — the scheduler runs underneath and Call returns when the task completes.

Cheap. Instantiating a compiled 37 KB module takes 1.7 µs and 3.3 KB of heap, so every request gets its own fresh linear memory instead of a pooled one you scrub between calls. A host call costs 48 ns and allocates nothing on the stack-reusing path, so your host API stays fine-grained instead of batching to hide the boundary. wazy serves a warm wasi:http component — a guest that answers HTTP requests — through net/http in 3.37 µs and 45 allocations; two orders of magnitude up, a 6.5 MB Rust document converter turns a 7.5 MB PDF in 0.75 s inside a pure-Go host (go-anydoc's measurement, #29). Every first-party figure is a benchmark in this repo: commands under Benchmarks, method and the optimizations measured and rejected in OPTIMIZATIONS.md.

Run it

go get github.com/samyfodil/wazy@latest
package main

import (
	"context"
	_ "embed"
	"os"

	"github.com/samyfodil/wazy"
	"github.com/samyfodil/wazy/component"
	"github.com/samyfodil/wazy/imports/wasip2"
)

// A genuine rustc component: cargo build --target wasm32-wasip2
//
//go:embed testdata/hello.wasm
var helloWasm []byte

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

	r := wazy.NewRuntime(ctx)
	defer r.Close(ctx) // Closes everything this runtime created.

	// Stdout, and nothing else: no files mounted, no sockets registered.
	inst, err := component.Instantiate(ctx, r, helloWasm,
		wasip2.With(wasip2.Config{Stdout: os.Stdout})...)
	if err != nil {
		panic(err)
	}
	defer inst.Close(ctx)

	if _, err := inst.Call(ctx, "wasi:cli/run@0.2.3#run"); err != nil {
		panic(err)
	}
}

That is examples/component, minus the error handling. Values cross typed, so a component exporting run: func() -> string hands back a Go string rather than a pointer and a length:

out, err := inst.Call(ctx, "run")
fmt.Println(out[0].(string))

Declare that contract yourself in a .wit file and implement the host half in Go: examples/custom-wit. Plain core modules and WASI 0.1 work the same way, through r.Instantiate and mod.ExportedFunction — examples/basic. More in examples/.

Why run Wasm inside your Go process?

The library you need exists only in Rust or C, or the code you must run is your customers'. Today that means cgo, a subprocess, a container, an embedded interpreter, or trust.

Instead of It costs wazy
cgo, to reach a Rust or C library CGO_ENABLED=0 and cross-compilation; the race detector and pprof stop at the library boundary; a bad pointer is your process's The same library as one .wasm. go-anydoc converts a 7.5 MB PDF through a Rust crate and still cross-compiles to s390x
A subprocess, an RPC plugin, or a container per request a second artifact per OS/arch, a process or image to supervise, a serialized round trip per call One file to version and sign; a fresh sandbox per request, 48 ns per host call, no daemon
An embedded interpreter (goja, yaegi, Starlark) one language, forever Any of the languages above — one example runs the same guest built by four toolchains
Trusting the code a dependency's init() runs with your files, your credentials, your network Deny by default: nothing mounted, no sockets registered, and a fake WASI 0.1 clock until you hand over a real one

Where the alternative still wins. cgo, when the library must spawn OS threads of its own: wazy exposes shared memory and atomics (experimental.CoreFeaturesThreads) but not wasi-threads spawn — or the host machine itself. A container or microVM, when you need kernel-enforced CPU quotas per tenant: wazy caps memory and enforces a deadline, but there is no fuel metering. Starlark, when the code is config-shaped and your authors will not install a Wasm toolchain. Trust, when the code is first-party and what you wanted was extensibility, not safety.

The Component Model and WASI 0.2

Standard
Core Wasm 1.0 / 2.0 ✅
Core Wasm 3.0 ✅
WASI 0.1  (wasip1) ✅
WASI 0.2 · Component Model  (wasip2) ✅
WASI 0.3 async ABI  (stream, future, tasks, threads) ✅

Core Wasm 3.0 means all eight proposals it folded in: tail calls, extended const, exception handling, typed function references, relaxed SIMD, multiple memories, memory64 and garbage collection. Turn them on together with api.CoreFeaturesV3; the default stays api.CoreFeaturesV2.

Components stay components: genuine wasm32-wasip2 binaries from rustc and wasm-tools, not flattened to core modules or hand-written .wat. What the Component Model and WASI 0.2 layer covers:

  • The Canonical ABI — the value conversions, both directions, for every type (primitives, string, list, record, variant, enum, flags, option, result, tuple) and own/borrow resource handles, including drop/rep and cross-instance borrows.
  • WASI 0.2 host interfaces — wasi:cli, wasi:clocks, wasi:filesystem, wasi:io, wasi:random, wasi:sockets, wasi:http; capabilities opt in per instantiation (filesystem preopens, AllowTCP, AllowUDP, a custom Dialer, EnableHTTP).
  • Multi-module component graphs — nested instances, canonical lowering of host imports, resource lifetimes and the wasip2 adapter wiring, so a real rustc wasi:cli/command runs end to end and prints hello world; with a CompileCache, re-instantiating that whole graph costs 350.5 µs.
inst, err := component.Instantiate(ctx, r, helloWasm,
	wasip2.With(wasip2.Config{Stdout: os.Stdout})...)
if err != nil {
	return err
}
defer inst.Close(ctx)

// A wasi:cli/command component: run its entry point.
_, err = inst.Call(ctx, "wasi:cli/run@0.2.3#run")

Call an interface export directly with inst.CallExport(ctx, "component:adder/calc", "add", uint32(2), uint32(3)), or hand a wasi:http/incoming-handler component to wasip2.Handler(inst), which returns an http.Handler — somebody else's handler, as a route on your mux. examples/custom-wit goes the other way: a WIT plugin API, resources and result<list<string>, variant> included, implemented host-side in Go.

Async — the WASI 0.3 async ABI

wazy runs the WASI 0.3 async ABI: components that suspend, await, and resume.

  • Callback and stackful lift — both shapes. A task returning WAIT/YIELD is driven by a deterministic per-composition scheduler; a stackful task suspends on a goroutine with an unbuffered-channel baton, so exactly one runs at a time — race-free by construction, verified under -race.
  • Streams, futures, task lifecycle — stream<T>/future<T> with rendezvous copy and per-element own<R> transfer, sync and async read/write; subtasks, cancellation, backpressure, context-local storage, borrow scopes that hold across async calls.
  • thread.* — a cooperative fiber runtime (thread.new-indirect, yield, suspend, yield-then-resume) on that same primitive.

Goroutines and channels back futures, streams and threads, so a parked guest costs one goroutine. You call an async export exactly like a synchronous one — the scheduler runs underneath and Call returns when the task completes — while CallAsync returns a pending call another goroutine resolves. examples/component runs an async export, a thread-spawning component and a five-thread map-reduce over one shared array. What runs is the Component Model async ABI, the machinery WASI 0.3 is built on; the reworked 0.3 host-interface worlds (wasi:io/wasi:sockets/wasi:http 0.3) land once that spec settles, and no wasm32-wasip3 target exists yet, here or anywhere.

Host functions, typed and allocation-free

Instead of a reflect-per-call path, typed generic helpers derive the Wasm signature from Go's types at compile time:

b := r.NewHostModuleBuilder("env")

wazy.HostFunc2(b.NewFunctionBuilder(), func(ctx context.Context, mod api.Module, x, y uint32) uint32 {
	return x + y
}).Export("add")

env, err := b.Instantiate(ctx)

HostFunc0–HostFunc16 and HostProc0–HostProc16 cover 16 parameters, one result or none; WithGoModuleFunction handles the rest. Dispatch allocates nothing. Call allocates the slice it returns results in, so a hot loop wants CallWithStack — the 48 ns path.

CLI and engines

A standalone runner ships in the box — the same binary the wasi-testsuite runs against. It takes core modules and WASI 0.1; components go through the library.

go install github.com/samyfodil/wazy/cmd/wazy@latest
wazy run -mount=.:/:ro -env-inherit app.wasm arg1 arg2

run also takes -listen host:port, -timeout, -interpreter, -cachedir and -hostlogging (clock,filesystem,memory,proc,poll,random,sock); wazy compile precompiles into the cache ahead of time. Release binaries for Linux, macOS and Windows are built CGO_ENABLED=0. wazy.NewRuntime(ctx) picks the optimizing compiler on amd64 and arm64 and falls back to the interpreter elsewhere; force either with wazy.NewRuntimeWithConfig(ctx, wazy.NewRuntimeConfigInterpreter()). The compiler translates each module to machine code during CompileModule — 4x to 45x faster than the interpreter across the go-anydoc runs below; the interpreter has no architecture-specific code, so it runs anywhere Go does.

Platform support

Full suite + spec corpora, every commit linux/amd64, windows/amd64, darwin/arm64, on two Go versions, plus a -race -short run and four fuzz targets — three differential against the interpreter, one for validation.
Test binaries run, every commit linux/arm64 and linux/amd64 in a scratch container (one variant with PROT_EXEC denied); FreeBSD, OpenBSD, NetBSD, DragonFly and illumos on amd64. The scratch runs exclude the spectest packages; the BSD and illumos runs also exclude imports/**, sysfs and the generated 3.0 corpus.
Cross-compiled every commit plan9, js/wasm, wasip1/wasm, aix/ppc64, linux/{s390x,ppc64le,arm,386}, freebsd/amd64 — they build and run the interpreter; CI does not execute their suites. riscv64 runs locally under qemu-riscv64-static, because the hosted runner never completes.

On a 32-bit host, linear memory tops out just under two gibibytes rather than the four a 32-bit Wasm memory may declare, bound by what a Go slice holds; a module asking for more is rejected, which the specification allows. If you depend on a target in the lower rows, open an issue and ask for CI coverage.

Conformance

Correctness here is a pass count against somebody else's suite, not a claim.

Suite Source Result
Core spec tests WebAssembly/testsuite + the proposal repos 13 corpora, 711 generated case files, no skip list; the 3.0 corpus runs on both engines.
Component Model async the official async .wast suites 31 suites, 0 skipped, 0 failed.
Canonical ABI values the official test/values suites 7 suites, 0 skipped, 0 failed, through wasm-tools json-from-wast — every vendored module instantiates.
wasi-testsuite WebAssembly/wasi-testsuite AssemblyScript, C and Rust, no skipped tests, on Linux, macOS and Windows, through the wazy CLI.
Cross-proposal interaction wasmtime's tests/misc_testsuite 9 .wast vendored from wasmtime, beside 5 written here.
go test ./internal/integration_test/spectest/...  # core spec corpora
go test ./internal/component/...                  # component ABI + async .wast

The Canonical ABI skip list is empty, and that is enforced. wastKnownSkips in internal/component/instance/wast_conformance_test.go is map[string]map[string]string{} — every vendored module of every suite instantiates — and the harness fails if that set changes in either direction: a new entry is a regression, a stale one means a gap closed and the list must shrink. The last four (types.11, fused.22, fused.23, resources.14) were all a nested component naming a definition an enclosing component owns; closing them meant modelling the core-module and component index spaces separately, linking each component to its outer one at decode time so an alias outer resolves, and masking flags to their label count on lift. The mechanism exists because a silent skip once hid a bug (#25). A separate workflow runs the Zig standard-library test binary, the Go wasip1 standard-library tests on two Go versions and libsodium's suite on every push; a differential trace-oracle byte-compares the async runtime against the spec's reference implementation (definitions.py). One official async fixture is broken; the 31/31 above runs against a corrected copy, and the fix is filed upstream as component-model#679.

Benchmarks

Run them yourself — the numbers at the top come from these suites, the first a separate module that compiles the same workloads against a pinned wazero:

cd benchmarks/vs-wazero && go test -bench .    # Instantiate, HostCall, Compile, Execute
go test -bench . ./imports/wasip2/... ./internal/integration_test/bench/...

Figures on this page come from two machines, each stated where it matters: the head-to-head and cumulative numbers on an Apple M4, memory.grow and the interruptible-loop numbers on a core-pinned i9-12900HK. Both used benchstat over interleaved A/B runs with upstream wazero as a control in the same runs. Method, per-optimization numbers and the optimizations measured and rejected (including one that made arm64 8% slower) are in OPTIMIZATIONS.md.

Head to head with wazero

Measured against wazero in the same runs, on the same workloads:

Path wazy vs wazero What & why
Instantiate 9.1x 1.724 µs vs 15.74 µs, on a 37 KB TinyGo module.
Interruptible loops (WithCloseOnContextDone) 9.8x vs wazero with the option on The check is a register decrement and a predicted-not-taken branch, not a Go round-trip. Enabling it costs wazy +18% on fibonacci and wazero +1057% -- each against its own build with the option off -- which is where the 9.8x head-to-head comes from. A near-empty spin kernel is the worst case at +44%; a host-call-dense loop pays +2% against wazero's +86%. Measured on a core with no uop cache, because code placement swamps smaller differences on Skylake -- see docs/performance.md. Against wazero@main.
Compiled execution memory-heavy code leads string_manipulation −18%, reverse_array −14%, base64 −12%, fibonacci a wash — the advantage tracks memory-access intensity, not arithmetic.
memory.fill 1.68x Geomean over a size sweep, against wazero at HEAD — i.e. with its own inline-store rewrite already in it. 7.1x at 15 bytes and 4.6x at 31, down to parity once the fill is memory-bandwidth-bound at 64 KiB. Constant-size clears 1.8–2.5x.
Host calls (Go ↔ Wasm) a tie 47.8 ns here, 48.3 ns there, on the WithGoModuleFunction arm both runtimes implement the same way. The win is structural, not per-call: see below.
Cumulative geomean −17.8%, B/op −22.9% Across internal/integration_test/bench, versus the wazero fork point, with upstream wazero as a control in the same runs — its arms stayed flat.

What the rewrite bought

These are wazy before and after its own optimization work — not a wazero comparison. They are why the absolute numbers at the top of this page look the way they do:

Path Before → after
Host calls, reflection removed 1086 ns / 6 allocs → 74.9 ns / 0 allocs 14.5x
memory.grow (in-capacity, amd64) 2.441 µs → 109.0 ns, 0 allocs/op 22x
Interpreter a benchmark that allocated 1.35M times now allocates twice ~30%
Memory per call 11784 B / 3 allocs → 1551 B / 2 allocs −87%
Compile, real modules 5 KB Zig 753.3 µs → 556.4 µs; 10 KB Rust 1132.7 µs → 871.3 µs −23% to −26%
memory.fill a size sweep, geomean; −91% at 64 bytes −79%

The host-call row is the one worth reading twice. wazy deleted reflection-based registration rather than optimizing it, so the 14.5x is against the path that no longer exists — wazero still ships one. memory.grow is opt-in via WithMemoryCapacityReservePages; out-of-capacity, shared and imported memories keep the safe Go path.

The head-to-head module also carries a three-way comparison against wasmtime (BenchmarkExecute3, BenchmarkCompile3, BenchmarkExecute3Heavy, BenchmarkRelaxedSimd); those arms link wasmtime-go, so they need cgo — an irony worth stating on a page selling CGO_ENABLED=0.

At scale: a 6.5 MB Rust module

The suites above are kernels. go-anydoc is two orders of magnitude up: a 6.5 MB wasm32-wasip1 command module (Rust 1.88, opt-level = 3, wasm-opt -O3) run as a single instantiate — stdin in, stdout out, a long stretch of compute between. Same .wasm, same input, same machine, identical output, CompileModule excluded from every timing.

Converting wazero v1.12.0 wazy
1 KB docx, compiled 0.45 ms 0.11 ms 4.1x
5 MB docx body, compiled 1.07 s 0.22 s 4.9x
1 KB docx, interpreted 2.62 ms 1.53 ms 1.7x
5 MB docx body, interpreted 13.1 s 7.7 s 1.7x

Those compiled rows carry WithCloseOnContextDone(true), and most of the 4.9x is what that option costs wazero rather than what its code generator produces. go-anydoc sets it unconditionally — cancelling a context has to interrupt a conversion already running inside the guest — so every run of its benchmark carries it, while benchmarks/vs-wazero above never sets it. The two suites were not measuring the same configuration. Toggling only that call, same module, same 5 MB body:

Compiled, 5 MB docx body wazero v1.12.0 wazy v0.3.0
close-on-context-done on 0.94 s 0.19 s 5.0x
off 0.14 s 0.11 s 1.3x
what the option costs 6.5x 1.7x

With it off the two compilers are ~30% apart. Against an interpreter the option is free on both — 6.79 s with it and 6.87 s without on wazy, 11.96 s and 11.91 s on wazero — so the 1.7x in the interpreted rows is the engines and nothing else. go-pdfium measured the same effect across 5,000 PDFs, at ~4.5x for wazero and ~1.4x for wazy. wazero's #2533 solves the same problem on their side; wazy's own check became native in #71, which is in this branch, so the 1.7x above is what v0.3.0 cost and not what main costs. On main it is 1.04x–1.28x depending on the core, against 1.01x–1.10x for wazero with its three in-flight PRs — level on x86, behind on the M4, and faster than both in absolute time. All three machines are in docs/performance.md.

So: long compute is where the compiler wins, but 4.9x is the figure for a caller who needs cancellation, and ~1.3x is the figure for the code generators. The small-document row measures something else again: instantiation dominates it and the conversion is noise, so it is setup cost rather than throughput. That row used to be the weak one. go-anydoc's own report had wazy losing it at 0.6x, and reproducing it here found two independent causes, both since fixed. A funcref memo scanned a list, so taking a reference for each of the module's 593 element-segment entries in turn made instantiation quadratic. And a linear memory was allocated at exactly its initial page count, so a guest whose allocator grew the heap even once reallocated and copied the whole memory on every instantiation — then filed the grown buffer in a pool bucket that no later instantiation ever asked for, so nothing was reused either. See OPTIMIZATIONS.md for both diagnoses.

Apple M4, native arm64, Go 1.26, CGO_ENABLED=0, anydoc.wasm 6,542,355 bytes. Run go test -run '^$' -bench ConvertDOCX in a checkout of go-anydoc; inputs are generated by the harness, so a checkout is enough to reproduce it. Arms interleaved, min of 8 (small) and 4 (large) — the M4 has performance and efficiency cores and no taskset, which makes medians on this machine untrustworthy. The original third-party report, including PDF figures this table omits because no PDF worth measuring is small enough to commit, is #29.

The toggle table is a separate third-party run — Apple M5 Pro (18-core), macOS 26.5, Go 1.26.1, CGO_ENABLED=0, anydoc.wasm 6,781,177 bytes (the module has since been rebuilt on anydoc 0.2.3), wazy v0.3.0 against wazero v1.12.0, min of 3 at -benchtime 3x. Reproduce it with go test -run '^$' -bench CloseOnContextDone -benchtime 3x -count 3 in a checkout of go-anydoc, which carries a benchmark that toggles the option on both engines; the wazero column is the same benchmark with the three imports in its anydoc.go pointed at wazero. Different machine and a newer module than the table above, so read the ratios rather than the milliseconds.

Moving fast

The API is stable. wazy broke compatibility with wazero once, over host-function registration, and that break is behind it — typed generics replaced the reflection path and the surface has settled. What keeps moving is everything under it: performance work lands continuously, guarded by the conformance, differential and fuzzing suites above rather than by a release cadence. Those same suites judge a contribution, not its author, machine-generated or human.

Users

  • taubyte/tau — the open-source platform behind Taubyte clouds runs WebAssembly workloads on wazy.
  • go-anydoc — Go bindings for a Rust document converter; the 6.5 MB module measured above is theirs.

Using wazy in production? Open a PR to add yourself.

Credit

wazy started from wazero's code (Copyright 2020-2023 wazero authors) and still draws on its WebAssembly semantics, WASI implementation, and compliance and fuzzing test suites. wazy keeps neither wazero's API compatibility nor its architecture: the goals are pure Go, performance, and conformance to the standard. See RATIONALE.md for wazero's original design rationale and LICENSE for the Apache 2.0 license.

The specification conformance suites are built from WebAssembly/testsuite and the individual proposal repositories (Apache 2.0); the Canonical ABI suites are the official WebAssembly/component-model test/values cases. The cross-proposal cases in internal/integration_test/spectest/v3-interaction named wasmtime-*.wast are vendored from wasmtime's tests/misc_testsuite (Apache 2.0 WITH LLVM-exception); the wazy-*.wast beside them are this repository's. imports/http_handler and its nethttp subpackage are a port of http-wasm-host-go (Apache 2.0), whose Technology Compatibility Kit is vendored to test them; imports/wasi_http reimplements the pre-standard WASI-HTTP ABI from wasi-go (Apache 2.0).

License

Apache 2.0. See LICENSE.

Documentation

Overview

Example

This is an example of how to extend a Go application with an addition function defined in WebAssembly.

Since addWasm was compiled with TinyGo's `wasi` target, we need to configure WASI host imports.

A complete project that does the same as this is available here: https://github.com/samyfodil/wazy/tree/main/examples/basic

package main

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

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

// addWasm was generated by the following:
//
//	cd examples/basic/testdata; tinygo build -o add.wasm -target=wasi add.go
//
//go:embed examples/basic/testdata/add.wasm
var addWasm []byte

// This is an example of how to extend a Go application with an addition
// function defined in WebAssembly.
//
// Since addWasm was compiled with TinyGo's `wasi` target, we need to configure
// WASI host imports.
//
// A complete project that does the same as this is available here:
// https://github.com/samyfodil/wazy/tree/main/examples/basic
func main() {
	// Choose the context to use for function calls.
	ctx := context.Background()

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

	// Instantiate WASI, which implements host functions needed for TinyGo to
	// implement `panic`.
	wasi_snapshot_preview1.MustInstantiate(ctx, r)

	// Instantiate the guest Wasm into the same runtime. It exports the `add`
	// function, implemented in WebAssembly.
	mod, err := r.InstantiateWithConfig(ctx, addWasm, wazy.NewModuleConfig().WithStartFunctions("_initialize"))
	if err != nil {
		log.Panicln(err)
	}

	// Call the `add` function and print the results to the console.
	x, y := uint64(1), uint64(2)
	results, err := mod.ExportedFunction("add").Call(ctx, x, y)
	if err != nil {
		log.Panicln(err)
	}

	fmt.Printf("%d + %d = %d\n", x, y, results[0])

}
Output:
1 + 2 = 3
Example (CompileCache)

This is a basic example of using the file system compilation cache via wazy.NewCompilationCacheWithDir. The main goal is to show how it is configured.

package main

import (
	"context"
	_ "embed"
	"log"
	"os"

	"github.com/samyfodil/wazy"
)

// This is a basic example of using the file system compilation cache via wazy.NewCompilationCacheWithDir.
// The main goal is to show how it is configured.
func main() {
	// Prepare a cache directory.
	cacheDir, err := os.MkdirTemp("", "example")
	if err != nil {
		log.Panicln(err)
	}
	defer os.RemoveAll(cacheDir)

	ctx := context.Background()

	// Create a runtime config which shares a compilation cache directory.
	cache := newCompilationCacheWithDir(cacheDir)
	defer cache.Close(ctx)
	config := wazy.NewRuntimeConfig().WithCompilationCache(cache)

	// Using the same wazy.CompilationCache instance allows the in-memory cache sharing.
	newRuntimeCompileClose(ctx, config)
	newRuntimeCompileClose(ctx, config)

	// Since the above stored compiled functions to disk as well, below won't compile from scratch.
	// Instead, compilation result stored in the directory is re-used.
	newRuntimeCompileClose(ctx, config.WithCompilationCache(newCompilationCacheWithDir(cacheDir)))
	newRuntimeCompileClose(ctx, config.WithCompilationCache(newCompilationCacheWithDir(cacheDir)))

}

func newCompilationCacheWithDir(cacheDir string) wazy.CompilationCache {
	cache, err := wazy.NewCompilationCacheWithDir(cacheDir)
	if err != nil {
		log.Panicln(err)
	}
	return cache
}

// newRuntimeCompileClose creates a new wazy.Runtime, compile a binary, and then delete the runtime.
func newRuntimeCompileClose(ctx context.Context, config wazy.RuntimeConfig) {
	r := wazy.NewRuntimeWithConfig(ctx, config)
	defer r.Close(ctx) // This closes everything this Runtime created except the file system cache.

	_, err := r.CompileModule(ctx, addWasm)
	if err != nil {
		log.Panicln(err)
	}
}
Example (FsConfig)

This example shows how to configure an embed.FS.

package main

import (
	"embed"
	"io/fs"
	"log"

	"github.com/samyfodil/wazy"
)

//go:embed testdata/index.html
var testdataIndex embed.FS

var moduleConfig wazy.ModuleConfig

// This example shows how to configure an embed.FS.
func main() {
	// Strip the embedded path testdata/
	rooted, err := fs.Sub(testdataIndex, "testdata")
	if err != nil {
		log.Panicln(err)
	}

	moduleConfig = wazy.NewModuleConfig().
		// Make "index.html" accessible to the guest as "/index.html".
		WithFSConfig(wazy.NewFSConfig().WithFSMount(rooted, "/"))

}
Example (RuntimeConfig_WithCustomSections)

This is a basic example of retrieving custom sections using RuntimeConfig.WithCustomSections.

package main

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

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

// This is a basic example of retrieving custom sections using RuntimeConfig.WithCustomSections.
func main() {
	ctx := context.Background()
	config := wazy.NewRuntimeConfig().WithCustomSections(true)

	r := wazy.NewRuntimeWithConfig(ctx, config)
	defer r.Close(ctx)

	m, err := r.CompileModule(ctx, addWasm)
	if err != nil {
		log.Panicln(err)
	}

	if m.CustomSections() == nil {
		log.Panicln("Custom sections should not be nil")
	}

	mustContain(m.CustomSections(), "producers")
	mustContain(m.CustomSections(), "target_features")

}

func mustContain(ss []api.CustomSection, name string) {
	for _, s := range ss {
		if s.Name() == name {
			return
		}
	}
	log.Panicf("Could not find section named %s\n", name)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrCompilationCacheMiss means the cache has no entry for the module.
	ErrCompilationCacheMiss = filecache.ErrMiss
	// ErrCompilationCacheStale means the entry was written by a different
	// version of wazy.
	ErrCompilationCacheStale = filecache.ErrStale
	// ErrCompilationCacheCorrupt means the entry could not be read or decoded.
	ErrCompilationCacheCorrupt = filecache.ErrCorrupt
	// ErrCompilationCacheUnsupported means the runtime uses the interpreter,
	// which has nothing to load from a persistent cache.
	ErrCompilationCacheUnsupported = filecache.ErrUnsupported
)

Errors from a cache made by NewCompilationCacheWithDirReadOnly, which can be told apart with errors.Is.

Functions

This section is empty.

Types

type CompilationCache

type CompilationCache interface{ api.Closer }

CompilationCache reduces time spent compiling (Runtime.CompileModule) the same wasm module.

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.
  • Instances of this can be reused across multiple runtimes, if configured via RuntimeConfig.
  • The cache check happens before the compilation, so if multiple Goroutines are trying to compile the same module simultaneously, it is possible that they all compile the module. The design here is that the lock isn't held for the action "Compile" but only for checking and saving the compiled result. Therefore, we strongly recommend that the embedder does the centralized compilation in a single Goroutines (or multiple Goroutines per Wasm binary) to generate cache rather than trying to Compile in parallel for a single module. In other words, we always recommend to produce CompiledModule share it across multiple Goroutines to avoid trying to compile the same module simultaneously.

func NewCompilationCache

func NewCompilationCache() CompilationCache

NewCompilationCache returns a new CompilationCache to be passed to RuntimeConfig. This configures only in-memory cache, and doesn't persist to the file system. See wazy.NewCompilationCacheWithDir for detail.

The returned CompilationCache can be used to share the in-memory compilation results across multiple instances of wazy.Runtime.

func NewCompilationCacheWithDir

func NewCompilationCacheWithDir(dirname string) (CompilationCache, error)

NewCompilationCacheWithDir is like wazy.NewCompilationCache except the result also writes state into the directory specified by `dirname` parameter.

If the dirname doesn't exist, this creates it or returns an error.

Those running wazy as a CLI or frequently restarting a process using the same wasm should use this feature to reduce time waiting to compile the same module a second time.

The contents written into dirname are wazy-version specific, meaning different versions of wazy will duplicate entries for the same input wasm.

Note: The embedder must safeguard this directory from external changes.

func NewCompilationCacheWithDirReadOnly added in v0.4.0

func NewCompilationCacheWithDirReadOnly(dirname string) (CompilationCache, error)

NewCompilationCacheWithDirReadOnly opens a compilation cache that an earlier NewCompilationCacheWithDir populated, and only serves hits from it.

Compiling a guest module that it doesn't hold fails, with ErrCompilationCacheMiss, ErrCompilationCacheStale or ErrCompilationCacheCorrupt, before any compilation starts. Use it where compiling is not an option: a read-only file system, which would let the compile run only for the write to fail, or a memory budget sized for loading native code rather than generating it. A warm hit needs a fraction of the memory of a compile.

dirname, and the version-specific directory inside it, must exist; nothing in them is ever created, written or deleted. A runtime using the interpreter, including on a platform without the compiler, rejects guest modules with ErrCompilationCacheUnsupported. Host modules always work.

Entries are trusted executable code, as with NewCompilationCacheWithDir: protect the directory, and populate it with the same version of wazy, on the same kind of CPU, with the same compilation configuration.

type CompiledModule

type CompiledModule interface {
	// Name returns the module name encoded into the binary or empty if not.
	Name() string

	// ImportedFunctions returns all the imported functions
	// (api.FunctionDefinition) in this module or nil if there are none.
	//
	// Note: Unlike ExportedFunctions, there is no unique constraint on
	// imports.
	ImportedFunctions() []api.FunctionDefinition

	// ExportedFunctions returns all the exported functions
	// (api.FunctionDefinition) in this module keyed on export name.
	ExportedFunctions() map[string]api.FunctionDefinition

	// ImportedMemories returns all the imported memories
	// (api.MemoryDefinition) in this module or nil if there are none.
	//
	// ## Notes
	//   - As of WebAssembly Core Specification 2.0, there can be at most one
	//     memory.
	//   - Unlike ExportedMemories, there is no unique constraint on imports.
	ImportedMemories() []api.MemoryDefinition

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

	// CustomSections returns all the custom sections
	// (api.CustomSection) in this module keyed on the section name.
	CustomSections() []api.CustomSection

	// Close releases all the allocated resources for this CompiledModule.
	//
	// Note: It is safe to call Close while having outstanding calls from an
	// api.Module instantiated from this.
	Close(context.Context) error
}

CompiledModule is a WebAssembly module ready to be instantiated (Runtime.InstantiateModule) as an api.Module.

In WebAssembly terminology, this is a decoded, validated, and possibly also compiled module. wazy avoids using the name "Module" for both before and after instantiation as the name conflation has caused confusion. See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#semantic-phases%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 CompiledModule it compiled.

type FSConfig

type FSConfig interface {
	// WithDirMount assigns a directory at `dir` to any paths beginning at
	// `guestPath`.
	//
	// For example, `dirPath` as / (or c:\ in Windows), makes the entire host
	// volume writeable to the path on the guest. The `guestPath` is always a
	// POSIX style path, slash (/) delimited, even if run on Windows.
	//
	// If the same `guestPath` was assigned before, this overrides its value,
	// retaining the original precedence. See the documentation of FSConfig for
	// more details on `guestPath`.
	//
	// # Isolation
	//
	// The guest has full access to this directory -- creating, writing, and
	// deleting files, limited only by host-level access controls -- but not
	// to anything outside it: both runtimes reject a guest path that escapes
	// the descriptor it is resolved against ("../../..." and rooted paths
	// alike) before the path ever reaches this filesystem. See
	// wasi_snapshot_preview1's atPath and, for components,
	// internal/component/instance's wasiJoinFSPath, which apply the same
	// path.Clean + fs.ValidPath rule. There is no way to turn that off: to
	// give a guest a second directory, add a second mount.
	//
	// That check is lexical. A *symlink* inside `dir` that points outside it
	// is still followed, since it is resolved by the host OS well below this
	// layer -- so a directory holding symlinks you do not control is not
	// safe to mount.
	//
	// # os.DirFS
	//
	// This configuration optimizes for WASI compatibility which is sometimes
	// at odds with the behavior of os.DirFS. Hence, this will not behave
	// exactly the same as os.DirFS. See /RATIONALE.md for more.
	WithDirMount(dir, guestPath string) FSConfig

	// WithReadOnlyDirMount assigns a directory at `dir` to any paths
	// beginning at `guestPath`.
	//
	// This is the same as WithDirMount except only read operations are
	// permitted. However, escaping the directory via relative path lookups
	// like "../../" is still allowed.
	WithReadOnlyDirMount(dir, guestPath string) FSConfig

	// WithFSMount assigns a fs.FS file system for any paths beginning at
	// `guestPath`.
	//
	// If the same `guestPath` was assigned before, this overrides its value,
	// retaining the original precedence. See the documentation of FSConfig for
	// more details on `guestPath`.
	//
	// # Isolation
	//
	// fs.FS does not restrict the ability to overwrite returned files via
	// io.Writer. Moreover, os.DirFS documentation includes important notes
	// about isolation, which also applies to fs.Sub. As of Go 1.19, the
	// built-in file-systems are not jailed (chroot). See
	// https://github.com/golang/go/issues/42322
	//
	// # os.DirFS
	//
	// Due to limited control and functionality available in os.DirFS, we
	// advise using WithDirMount instead. There will be behavior differences
	// between os.DirFS and WithDirMount, as the latter biases towards what's
	// expected from WASI implementations.
	//
	// # Custom fs.FileInfo
	//
	// The underlying implementation supports data not usually in fs.FileInfo
	// when `info.Sys` returns *sys.Stat_t. For example, a custom fs.FS can use
	// this approach to generate or mask sys.Inode data. Such a filesystem
	// needs to decorate any functions that can return fs.FileInfo:
	//
	//   - `Stat` as defined on `fs.File` (always)
	//   - `Readdir` as defined on `os.File` (if defined)
	//
	// See sys.NewStat_t for examples.
	WithFSMount(fs fs.FS, guestPath string) FSConfig

	// WithSysFSMount assigns a sys.FS file system for any paths beginning at
	// `guestPath`.
	//
	// This is the writable counterpart to WithFSMount: io/fs.FS has no write
	// surface at all, so a third-party filesystem the guest must be able to
	// create, write, rename, or delete in implements sys.FS and mounts here.
	//
	// If the same `guestPath` was assigned before, this overrides its value,
	// retaining the original precedence. See the documentation of FSConfig for
	// more details on `guestPath`.
	WithSysFSMount(fs sys.FS, guestPath string) FSConfig
}

FSConfig configures filesystem paths the embedding host allows the wasm guest to access. Unconfigured paths are not allowed, so functions like `path_open` result in unsupported errors (e.g. syscall.ENOSYS).

Guest Path

`guestPath` is the name of the path the guest should use a filesystem for, or empty for any files.

All `guestPath` paths are normalized, specifically removing any leading or trailing slashes. This means "/", "./" or "." all coerce to empty "".

Multiple `guestPath` values can be configured, but the last longest match wins. For example, if "tmp", then "" were added, a request to open "tmp/foo.txt" use the filesystem associated with "tmp" even though a wider path, "" (all files), was added later.

A `guestPath` of "." coerces to the empty string "" because the current directory is handled by the guest. In other words, the guest resolves ites current directory prior to requesting files.

More notes on `guestPath`

  • Working directories are typically tracked in wasm, though possible some relative paths are requested. For example, TinyGo may attempt to resolve a path "../.." in unit tests.
  • Zig uses the first path name it sees as the initial working directory of the process.

Scope

Configuration here is module instance scoped. This means you can use the same configuration for multiple calls to Runtime.InstantiateModule. Each module will have a different file descriptor table. Any errors accessing resources allowed here are deferred to instantiation time of each module.

Any host resources present at the time of configuration, but deleted before Runtime.InstantiateModule will trap/panic when the guest wasm initializes or calls functions like `fd_read`.

Windows

While wazy supports Windows as a platform, all known compilers use POSIX conventions at runtime. For example, even when running on Windows, paths used by wasm are separated by forward slash (/), not backslash (\).

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.
  • FSConfig is immutable. Each WithXXX function returns a new instance including the corresponding change.
  • RATIONALE.md includes design background and relationship to WebAssembly System Interfaces (WASI).

func NewFSConfig

func NewFSConfig() FSConfig

NewFSConfig returns a FSConfig that can be used for configuring module instantiation.

type HostFunctionBuilder

type HostFunctionBuilder interface {
	// WithGoFunction registers a host function from an explicit WebAssembly
	// signature and an api.GoFunction that reads parameters from, and writes
	// results to, the raw stack. It is the lower-level counterpart to the
	// typed HostFunc0-HostFunc16/HostProc0-HostProc16 helpers, and is the right
	// tool when their fixed "numeric, ctx+mod prefix" shape does not fit.
	//
	// Here's an example addition function:
	//
	//	builder.WithGoFunction(api.GoFunc(func(ctx context.Context, stack []uint64) {
	//		x, y := api.DecodeI32(stack[0]), api.DecodeI32(stack[1])
	//		sum := x + y
	//		stack[0] = api.EncodeI32(sum)
	//	}), []api.ValueType{api.ValueTypeI32, api.ValueTypeI32}, []api.ValueType{api.ValueTypeI32})
	//
	// As you can see above, defining in this way implies knowledge of which
	// WebAssembly api.ValueType is appropriate for each parameter and result.
	//
	// See WithGoModuleFunction if you also need to access the calling module.
	WithGoFunction(fn api.GoFunction, params, results []api.ValueType) HostFunctionBuilder

	// WithGoModuleFunction registers a host function from an explicit
	// WebAssembly signature and an api.GoModuleFunction that reads parameters
	// from, and writes results to, the raw stack. It is the lower-level
	// counterpart to the typed HostFunc0-HostFunc16/HostProc0-HostProc16
	// helpers, and is the right tool when their fixed "numeric, ctx+mod
	// prefix" shape does not fit.
	//
	// Here's an example addition function that loads operands from memory:
	//
	//	builder.WithGoModuleFunction(api.GoModuleFunc(func(ctx context.Context, m api.Module, stack []uint64) {
	//		mem := m.Memory()
	//		offset := api.DecodeU32(stack[0])
	//
	//		x, _ := mem.ReadUint32Le(ctx, offset)
	//		y, _ := mem.ReadUint32Le(ctx, offset + 4) // 32 bits == 4 bytes!
	//		sum := x + y
	//
	//		stack[0] = api.EncodeU32(sum)
	//	}), []api.ValueType{api.ValueTypeI32}, []api.ValueType{api.ValueTypeI32})
	//
	// As you can see above, defining in this way implies knowledge of which
	// WebAssembly api.ValueType is appropriate for each parameter and result.
	//
	// See WithGoFunction if you don't need access to the calling module.
	WithGoModuleFunction(fn api.GoModuleFunction, params, results []api.ValueType) HostFunctionBuilder

	// WithName defines the optional module-local name of this function, e.g.
	// "random_get"
	//
	// Note: This is not required to match the Export name.
	WithName(name string) HostFunctionBuilder

	// WithParameterNames defines optional parameter names of the function
	// signature, e.x. "buf", "buf_len"
	//
	// Note: When defined, names must be provided for all parameters.
	WithParameterNames(names ...string) HostFunctionBuilder

	// WithResultNames defines optional result names of the function
	// signature, e.x. "errno"
	//
	// Note: When defined, names must be provided for all results.
	WithResultNames(names ...string) HostFunctionBuilder

	// Export exports this to the HostModuleBuilder as the given name, e.g.
	// "random_get"
	Export(name string) HostModuleBuilder
}

HostFunctionBuilder defines a host function (in Go), so that a WebAssembly binary (e.g. %.wasm file) can import and use it.

There are two ways to define a host function's implementation and its WebAssembly signature:

  • The strongly-typed HostFunc0-HostFunc16 and HostProc0-HostProc16 helpers (in the root wazy package) derive the WebAssembly signature from a Go function whose parameters and result are numeric (a HostValue), prefixed by context.Context and api.Module. They are chainable:

    wazy.HostFunc2(b, func(ctx context.Context, mod api.Module, x, y uint32) uint32 { return x + y }).Export("add")

  • WithGoModuleFunction (and WithGoFunction, when the calling module is not needed) take an explicit WebAssembly signature and read parameters from, and write results to, the raw stack. Use these for signatures the typed helpers cannot express: more than 16 parameters, multiple results, or no context.Context/api.Module prefix.

Memory

All host functions act on the importing api.Module, including any memory exported in its binary (%.wasm file). If you are reading or writing memory, it is sand-boxed Wasm memory defined by the guest.

Below, `m` is the importing module, defined in Wasm. `fn` is a host function added via Export. This means that `x` was read from memory defined in Wasm, not arbitrary memory in the process.

fn := func(ctx context.Context, m api.Module, offset uint32) uint32 {
	x, _ := m.Memory().ReadUint32Le(ctx, offset)
	return x
}

Notes

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

func HostFunc0

HostFunc0 defines a host function taking no parameters besides the implicit context.Context and api.Module, returning a single HostValue.

HostFunc0-HostFunc16 (and HostProc0-HostProc16 for functions that return nothing) are the compile-time-typed way to register a host function whose signature is "numeric-only, with a context.Context and api.Module prefix". The WebAssembly api.ValueType signature is derived from Go's type system, and the call decodes parameters and encodes the result directly, with no reflection and no per-call allocation - the same cost as hand-writing HostFunctionBuilder.WithGoModuleFunction.

Use these when your function's arity is fixed at compile time and every parameter and result is a HostValue. Reach for WithGoFunction or WithGoModuleFunction directly when you need something these can't express: more than 16 parameters, more than one result, a signature without the context.Context/api.Module prefix, or fine control over the raw stack.

Here's the addition example from HostFunctionBuilder's docs, this time with HostFunc2 (two parameters, one result):

wazy.HostFunc2(builder, func(ctx context.Context, mod api.Module, x, y uint32) uint32 {
	return x + y
}).Export("add")

func HostFunc1

func HostFunc1[P1, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1) R) HostFunctionBuilder

HostFunc1 is HostFunc0 with one parameter. See HostFunc0.

func HostFunc2

func HostFunc2[P1, P2, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2) R) HostFunctionBuilder

HostFunc2 is HostFunc0 with two parameters. See HostFunc0.

func HostFunc3

func HostFunc3[P1, P2, P3, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3) R) HostFunctionBuilder

HostFunc3 is HostFunc0 with three parameters. See HostFunc0.

func HostFunc4

func HostFunc4[P1, P2, P3, P4, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4) R) HostFunctionBuilder

HostFunc4 is HostFunc0 with four parameters. See HostFunc0.

func HostFunc5

func HostFunc5[P1, P2, P3, P4, P5, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5) R) HostFunctionBuilder

HostFunc5 is HostFunc0 with five parameters. See HostFunc0.

func HostFunc6

func HostFunc6[P1, P2, P3, P4, P5, P6, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6) R) HostFunctionBuilder

HostFunc6 is HostFunc0 with six parameters. See HostFunc0.

func HostFunc7

func HostFunc7[P1, P2, P3, P4, P5, P6, P7, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7) R) HostFunctionBuilder

HostFunc7 is HostFunc0 with seven parameters. See HostFunc0.

func HostFunc8

func HostFunc8[P1, P2, P3, P4, P5, P6, P7, P8, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8) R) HostFunctionBuilder

HostFunc8 is HostFunc0 with eight parameters. See HostFunc0.

func HostFunc9 added in v0.1.2

func HostFunc9[P1, P2, P3, P4, P5, P6, P7, P8, P9, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9) R) HostFunctionBuilder

HostFunc9 is HostFunc0 with nine parameters. See HostFunc0.

func HostFunc10 added in v0.1.2

func HostFunc10[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10) R) HostFunctionBuilder

HostFunc10 is HostFunc0 with ten parameters. See HostFunc0.

func HostFunc11 added in v0.1.2

func HostFunc11[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11) R) HostFunctionBuilder

HostFunc11 is HostFunc0 with eleven parameters. See HostFunc0.

func HostFunc12 added in v0.1.2

func HostFunc12[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) R) HostFunctionBuilder

HostFunc12 is HostFunc0 with twelve parameters. See HostFunc0.

func HostFunc13 added in v0.1.2

func HostFunc13[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13) R) HostFunctionBuilder

HostFunc13 is HostFunc0 with thirteen parameters. See HostFunc0.

func HostFunc14 added in v0.1.2

func HostFunc14[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14) R) HostFunctionBuilder

HostFunc14 is HostFunc0 with fourteen parameters. See HostFunc0.

func HostFunc15 added in v0.1.2

func HostFunc15[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15) R) HostFunctionBuilder

HostFunc15 is HostFunc0 with fifteen parameters. See HostFunc0.

func HostFunc16 added in v0.1.2

func HostFunc16[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16) R) HostFunctionBuilder

HostFunc16 is HostFunc0 with sixteen parameters. See HostFunc0.

func HostProc0

HostProc0 defines a host function with no result, taking no parameters besides the implicit context.Context and api.Module. See HostFunc0 for when to use this family of functions instead of WithGoModuleFunction.

func HostProc1

HostProc1 is HostProc0 with one parameter. See HostFunc0 and HostProc0.

func HostProc2

func HostProc2[P1, P2 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2)) HostFunctionBuilder

HostProc2 is HostProc0 with two parameters. See HostFunc0 and HostProc0.

func HostProc3

func HostProc3[P1, P2, P3 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3)) HostFunctionBuilder

HostProc3 is HostProc0 with three parameters. See HostFunc0 and HostProc0.

func HostProc4

func HostProc4[P1, P2, P3, P4 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4)) HostFunctionBuilder

HostProc4 is HostProc0 with four parameters. See HostFunc0 and HostProc0.

func HostProc5

func HostProc5[P1, P2, P3, P4, P5 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5)) HostFunctionBuilder

HostProc5 is HostProc0 with five parameters. See HostFunc0 and HostProc0.

func HostProc6

func HostProc6[P1, P2, P3, P4, P5, P6 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6)) HostFunctionBuilder

HostProc6 is HostProc0 with six parameters. See HostFunc0 and HostProc0.

func HostProc7

func HostProc7[P1, P2, P3, P4, P5, P6, P7 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7)) HostFunctionBuilder

HostProc7 is HostProc0 with seven parameters. See HostFunc0 and HostProc0.

func HostProc8

func HostProc8[P1, P2, P3, P4, P5, P6, P7, P8 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8)) HostFunctionBuilder

HostProc8 is HostProc0 with eight parameters. See HostFunc0 and HostProc0.

func HostProc9 added in v0.1.2

func HostProc9[P1, P2, P3, P4, P5, P6, P7, P8, P9 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9)) HostFunctionBuilder

HostProc9 is HostProc0 with nine parameters. See HostFunc0 and HostProc0.

func HostProc10 added in v0.1.2

func HostProc10[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10)) HostFunctionBuilder

HostProc10 is HostProc0 with ten parameters. See HostFunc0 and HostProc0.

func HostProc11 added in v0.1.2

func HostProc11[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11)) HostFunctionBuilder

HostProc11 is HostProc0 with eleven parameters. See HostFunc0 and HostProc0.

func HostProc12 added in v0.1.2

func HostProc12[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12)) HostFunctionBuilder

HostProc12 is HostProc0 with twelve parameters. See HostFunc0 and HostProc0.

func HostProc13 added in v0.1.2

func HostProc13[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13)) HostFunctionBuilder

HostProc13 is HostProc0 with thirteen parameters. See HostFunc0 and HostProc0.

func HostProc14 added in v0.1.2

func HostProc14[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14)) HostFunctionBuilder

HostProc14 is HostProc0 with fourteen parameters. See HostFunc0 and HostProc0.

func HostProc15 added in v0.1.2

func HostProc15[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15)) HostFunctionBuilder

HostProc15 is HostProc0 with fifteen parameters. See HostFunc0 and HostProc0.

func HostProc16 added in v0.1.2

func HostProc16[P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16 HostValue](b HostFunctionBuilder, fn func(context.Context, api.Module, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16)) HostFunctionBuilder

HostProc16 is HostProc0 with sixteen parameters. See HostFunc0 and HostProc0.

type HostModuleBuilder

type HostModuleBuilder interface {

	// NewFunctionBuilder begins the definition of a host function.
	NewFunctionBuilder() HostFunctionBuilder

	// Compile returns a CompiledModule that can be instantiated by Runtime.
	Compile(context.Context) (CompiledModule, error)

	// Instantiate is a convenience that calls Compile, then Runtime.InstantiateModule.
	// This can fail for reasons documented on Runtime.InstantiateModule.
	//
	// Here's an example:
	//
	//	ctx := context.Background()
	//	r := wazy.NewRuntime(ctx)
	//	defer r.Close(ctx) // This closes everything this Runtime created.
	//
	//	hello := func(context.Context, api.Module) {
	//		println("hello!")
	//	}
	//	env, _ := wazy.HostProc0(r.NewHostModuleBuilder("env").NewFunctionBuilder(), hello).
	//		Export("hello").
	//		Instantiate(ctx)
	//
	// # Notes
	//
	//   - Closing the Runtime has the same effect as closing the result.
	//   - Fields in the builder are copied during instantiation: Later changes do not affect the instantiated result.
	//   - To avoid using configuration defaults, use Compile instead.
	Instantiate(context.Context) (api.Module, error)
}

HostModuleBuilder is a way to define host functions (in Go), so that a WebAssembly binary (e.g. %.wasm file) can import and use them.

Specifically, this implements the host side of an Application Binary Interface (ABI) like WASI or AssemblyScript.

For example, this defines and instantiates a module named "env" with one function:

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

hello := func(context.Context, api.Module) {
	println("hello!")
}
env, _ := wazy.HostProc0(r.NewHostModuleBuilder("env").NewFunctionBuilder(), hello).
	Export("hello").
	Instantiate(ctx)

If the same module may be instantiated multiple times, it is more efficient to separate steps. Here's an example using WithGoModuleFunction for a function whose signature the typed helpers don't cover:

compiled, _ := r.NewHostModuleBuilder("env").
	NewFunctionBuilder().
	WithGoModuleFunction(getRandomString, nil, []api.ValueType{api.ValueTypeI32}).
	Export("get_random_string").
	Compile(ctx)

env1, _ := r.InstantiateModule(ctx, compiled, wazy.NewModuleConfig().WithName("env.1"))
env2, _ := r.InstantiateModule(ctx, compiled, wazy.NewModuleConfig().WithName("env.2"))

See HostFunctionBuilder for valid host function signatures and other details.

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.
  • HostModuleBuilder is mutable: each method returns the same instance for chaining.
  • methods do not return errors, to allow chaining. Any validation errors are deferred until Compile.
  • Functions are indexed in order of calls to NewFunctionBuilder as insertion ordering is needed by ABI such as Emscripten (invoke_*).
  • 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.

type HostValue

type HostValue interface {
	uint32 | int32 | uint64 | int64 | float32 | float64 | uintptr
}

HostValue is the set of Go types that HostFunc0-HostFunc16 and HostProc0-HostProc16 accept as a parameter or result. Each corresponds 1:1 to a WebAssembly numeric api.ValueType:

  • uint32, int32 map to api.ValueTypeI32
  • uint64, int64 map to api.ValueTypeI64
  • float32 maps to api.ValueTypeF32
  • float64 maps to api.ValueTypeF64
  • uintptr maps to api.ValueTypeExternref

These are the exact predeclared types: a named type such as `type Pages uint32` is not a HostValue and will not compile as a type argument. Convert explicitly at the call boundary instead (for example, take a uint32 parameter and cast it to Pages inside the function body). Keeping the constraint to exact types lets decodeHostValue/encodeHostValue resolve at compile time, with no reflection and no per-call allocation.

type ModuleConfig

type ModuleConfig interface {
	// WithArgs assigns command-line arguments visible to an imported function that reads an arg vector (argv). Defaults to
	// none. Runtime.InstantiateModule errs if any arg is empty.
	//
	// These values are commonly read by the functions like "args_get" in "wasi_snapshot_preview1" although they could be
	// read by functions imported from other modules.
	//
	// Similar to os.Args and exec.Cmd Env, many implementations would expect a program name to be argv[0]. However, neither
	// WebAssembly nor WebAssembly System Interfaces (WASI) define this. Regardless, you may choose to set the first
	// argument to the same value set via WithName.
	//
	// Note: This does not default to os.Args as that violates sandboxing.
	//
	// See https://linux.die.net/man/3/argv and https://en.wikipedia.org/wiki/Null-terminated_string
	WithArgs(...string) ModuleConfig

	// WithEnv sets an environment variable visible to a Module that imports functions. Defaults to none.
	// Runtime.InstantiateModule errs if the key is empty or contains a NULL(0) or equals("") character.
	//
	// Validation is the same as os.Setenv on Linux and replaces any existing value. Unlike exec.Cmd Env, this does not
	// default to the current process environment as that would violate sandboxing. This also does not preserve order.
	//
	// Environment variables are commonly read by the functions like "environ_get" in "wasi_snapshot_preview1" although
	// they could be read by functions imported from other modules.
	//
	// While similar to process configuration, there are no assumptions that can be made about anything OS-specific. For
	// example, neither WebAssembly nor WebAssembly System Interfaces (WASI) define concerns processes have, such as
	// case-sensitivity on environment keys. For portability, define entries with case-insensitively unique keys.
	//
	// See https://linux.die.net/man/3/environ and https://en.wikipedia.org/wiki/Null-terminated_string
	WithEnv(key, value string) ModuleConfig

	// WithFS is a convenience that calls WithFSConfig with an FSConfig of the
	// input for the root ("/") guest path.
	WithFS(fs.FS) ModuleConfig

	// WithFSConfig configures the filesystem available to each guest
	// instantiated with this configuration. By default, no file access is
	// allowed, so functions like `path_open` result in unsupported errors
	// (e.g. syscall.ENOSYS).
	WithFSConfig(FSConfig) ModuleConfig

	// WithName configures the module name. Defaults to what was decoded from
	// the name section. Duplicate names are not allowed in a single Runtime.
	//
	// Calling this with the empty string "" makes the module anonymous.
	// That is useful when you want to instantiate the same CompiledModule multiple times like below:
	//
	// 	for i := 0; i < N; i++ {
	//		// Instantiate a new Wasm module from the already compiled `compiledWasm` anonymously without a name.
	//		instance, err := r.InstantiateModule(ctx, compiledWasm, wazy.NewModuleConfig().WithName(""))
	//		// ....
	//	}
	//
	// See the `concurrent-instantiation` example for a complete usage.
	//
	// Non-empty named modules are available for other modules to import by name.
	WithName(string) ModuleConfig

	// WithStartFunctions configures the functions to call after the module is
	// instantiated. Defaults to "_start".
	//
	// Clearing the default is supported, via `WithStartFunctions()`.
	//
	// # Notes
	//
	//   - If a start function doesn't exist, it is skipped. However, any that
	//     do exist are called in order.
	//   - Start functions are not intended to be called multiple times.
	//     Functions that should be called multiple times should be invoked
	//     manually via api.Module's `ExportedFunction` method.
	//   - Start functions commonly exit the module during instantiation,
	//     preventing use of any functions later. This is the case in "wasip1",
	//     which defines the default value "_start".
	//   - See /RATIONALE.md for motivation of this feature.
	WithStartFunctions(...string) ModuleConfig

	// WithStderr configures where standard error (file descriptor 2) is written. Defaults to io.Discard.
	//
	// This writer is most commonly used by the functions like "fd_write" in "wasi_snapshot_preview1" although it could
	// be used by functions imported from other modules.
	//
	// # Notes
	//
	//   - The caller is responsible to close any io.Writer they supply: It is not closed on api.Module Close.
	//   - This does not default to os.Stderr as that both violates sandboxing and prevents concurrent modules.
	//
	// See https://linux.die.net/man/3/stderr
	WithStderr(io.Writer) ModuleConfig

	// WithStdin configures where standard input (file descriptor 0) is read. Defaults to return io.EOF.
	//
	// This reader is most commonly used by the functions like "fd_read" in "wasi_snapshot_preview1" although it could
	// be used by functions imported from other modules.
	//
	// # Notes
	//
	//   - The caller is responsible to close any io.Reader they supply: It is not closed on api.Module Close.
	//   - This does not default to os.Stdin as that both violates sandboxing and prevents concurrent modules.
	//
	// See https://linux.die.net/man/3/stdin
	WithStdin(io.Reader) ModuleConfig

	// WithStdout configures where standard output (file descriptor 1) is written. Defaults to io.Discard.
	//
	// This writer is most commonly used by the functions like "fd_write" in "wasi_snapshot_preview1" although it could
	// be used by functions imported from other modules.
	//
	// # Notes
	//
	//   - The caller is responsible to close any io.Writer they supply: It is not closed on api.Module Close.
	//   - This does not default to os.Stdout as that both violates sandboxing and prevents concurrent modules.
	//
	// See https://linux.die.net/man/3/stdout
	WithStdout(io.Writer) ModuleConfig

	// WithWalltime configures the wall clock, sometimes referred to as the
	// real time clock. sys.Walltime returns the current unix/epoch time,
	// seconds since midnight UTC 1 January 1970, with a nanosecond fraction.
	// This defaults to a fake result that increases by 1ms on each reading.
	//
	// Here's an example that uses a custom clock:
	//	moduleConfig = moduleConfig.
	//		WithWalltime(func(context.Context) (sec int64, nsec int32) {
	//			return clock.walltime()
	//		}, sys.ClockResolution(time.Microsecond.Nanoseconds()))
	//
	// # Notes:
	//   - This does not default to time.Now as that violates sandboxing.
	//   - This is used to implement host functions such as WASI
	//     `clock_time_get` with the `realtime` clock ID.
	//   - Use WithSysWalltime for a usable implementation.
	WithWalltime(sys.Walltime, sys.ClockResolution) ModuleConfig

	// WithSysWalltime uses time.Now for sys.Walltime with a resolution of 1us
	// (1000ns).
	//
	// See WithWalltime
	WithSysWalltime() ModuleConfig

	// WithNanotime configures the monotonic clock, used to measure elapsed
	// time in nanoseconds. Defaults to a fake result that increases by 1ms
	// on each reading.
	//
	// Here's an example that uses a custom clock:
	//	moduleConfig = moduleConfig.
	//		WithNanotime(func(context.Context) int64 {
	//			return clock.nanotime()
	//		}, sys.ClockResolution(time.Microsecond.Nanoseconds()))
	//
	// # Notes:
	//   - This does not default to time.Since as that violates sandboxing.
	//   - This is used to implement host functions such as WASI
	//     `clock_time_get` with the `monotonic` clock ID.
	//   - Some compilers implement sleep by looping on sys.Nanotime (e.g. Go).
	//   - If you set this, you should probably set WithNanosleep also.
	//   - Use WithSysNanotime for a usable implementation.
	WithNanotime(sys.Nanotime, sys.ClockResolution) ModuleConfig

	// WithSysNanotime uses time.Now for sys.Nanotime with a resolution of 1us.
	//
	// See WithNanotime
	WithSysNanotime() ModuleConfig

	// WithNanosleep configures the how to pause the current goroutine for at
	// least the configured nanoseconds. Defaults to return immediately.
	//
	// This example uses a custom sleep function:
	//	moduleConfig = moduleConfig.
	//		WithNanosleep(func(ns int64) {
	//			rel := unix.NsecToTimespec(ns)
	//			remain := unix.Timespec{}
	//			for { // loop until no more time remaining
	//				err := unix.ClockNanosleep(unix.CLOCK_MONOTONIC, 0, &rel, &remain)
	//			--snip--
	//
	// # Notes:
	//   - This does not default to time.Sleep as that violates sandboxing.
	//   - This is used to implement host functions such as WASI `poll_oneoff`.
	//   - Some compilers implement sleep by looping on sys.Nanotime (e.g. Go).
	//   - If you set this, you should probably set WithNanotime also.
	//   - Use WithSysNanosleep for a usable implementation.
	WithNanosleep(sys.Nanosleep) ModuleConfig

	// WithOsyield yields the processor, typically to implement spin-wait
	// loops. Defaults to return immediately.
	//
	// # Notes:
	//   - This primarily supports `sched_yield` in WASI
	//   - This does not default to runtime.osyield as that violates sandboxing.
	WithOsyield(sys.Osyield) ModuleConfig

	// WithSysNanosleep uses time.Sleep for sys.Nanosleep.
	//
	// See WithNanosleep
	WithSysNanosleep() ModuleConfig

	// WithRandSource configures a source of random bytes. Defaults to return a
	// deterministic source. You might override this with crypto/rand.Reader
	//
	// This reader is most commonly used by the functions like "random_get" in
	// "wasi_snapshot_preview1", "seed" in AssemblyScript standard "env", and
	// "getRandomData" when runtime.GOOS is "js".
	//
	// Note: The caller is responsible to close any io.Reader they supply: It
	// is not closed on api.Module Close.
	WithRandSource(io.Reader) ModuleConfig
}

ModuleConfig configures resources needed by functions that have low-level interactions with the host operating system. Using this, resources such as STDIN can be isolated, so that the same module can be safely instantiated multiple times.

Here's an example:

// Initialize base configuration:
config := wazy.NewModuleConfig().WithStdout(buf).WithSysNanotime()

// Assign different configuration on each instantiation
mod, _ := r.InstantiateModule(ctx, compiled, config.WithName("rotate").WithArgs("rotate", "angle=90", "dir=cw"))

While wazy supports Windows as a platform, host functions using ModuleConfig follow a UNIX dialect. See RATIONALE.md for design background and relationship to WebAssembly System Interfaces (WASI).

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.
  • ModuleConfig is immutable. Each WithXXX function returns a new instance including the corresponding change.

func NewModuleConfig

func NewModuleConfig() ModuleConfig

NewModuleConfig returns a ModuleConfig that can be used for configuring module instantiation.

type Runtime

type Runtime interface {
	// Instantiate instantiates a module from the WebAssembly binary (%.wasm)
	// with default configuration, which notably calls the "_start" function,
	// if it exists.
	//
	// Here's an example:
	//	ctx := context.Background()
	//	r := wazy.NewRuntime(ctx)
	//	defer r.Close(ctx) // This closes everything this Runtime created.
	//
	//	mod, _ := r.Instantiate(ctx, wasm)
	//
	// # Notes
	//
	//   - See notes on InstantiateModule for error scenarios.
	//   - See InstantiateWithConfig for configuration overrides.
	Instantiate(ctx context.Context, source []byte) (api.Module, error)

	// InstantiateWithConfig instantiates a module from the WebAssembly binary
	// (%.wasm) or errs for reasons including exit or validation.
	//
	// Here's an example:
	//	ctx := context.Background()
	//	r := wazy.NewRuntime(ctx)
	//	defer r.Close(ctx) // This closes everything this Runtime created.
	//
	//	mod, _ := r.InstantiateWithConfig(ctx, wasm,
	//		wazy.NewModuleConfig().WithName("rotate"))
	//
	// # Notes
	//
	//   - See notes on InstantiateModule for error scenarios.
	//   - If you aren't overriding defaults, use Instantiate.
	//   - This is a convenience utility that chains CompileModule with
	//     InstantiateModule. To instantiate the same source multiple times,
	//     use CompileModule as InstantiateModule avoids redundant decoding
	//     and/or compilation.
	InstantiateWithConfig(ctx context.Context, source []byte, config ModuleConfig) (api.Module, error)

	// NewHostModuleBuilder lets you create modules out of functions defined in Go.
	//
	// Below defines and instantiates a module named "env" with one function:
	//
	//	ctx := context.Background()
	//	hello := func(context.Context, api.Module) {
	//		fmt.Fprintln(stdout, "hello!")
	//	}
	//	_, err := wazy.HostProc0(r.NewHostModuleBuilder("env").NewFunctionBuilder(), hello).
	//		Export("hello").
	//		Instantiate(ctx, r)
	//
	// Note: empty `moduleName` is not allowed.
	NewHostModuleBuilder(moduleName string) HostModuleBuilder

	// CompileModule decodes the WebAssembly binary (%.wasm) or errs if invalid.
	// Any pre-compilation done after decoding wasm is dependent on RuntimeConfig.
	//
	// There are two main reasons to use CompileModule instead of Instantiate:
	//   - Improve performance when the same module is instantiated multiple times under different names
	//   - Reduce the amount of errors that can occur during InstantiateModule.
	//
	// # Notes
	//
	//   - The resulting module name defaults to what was binary from the custom name section.
	//   - Any pre-compilation done after decoding the source is dependent on RuntimeConfig.
	//
	// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#name-section%E2%91%A0
	CompileModule(ctx context.Context, binary []byte) (CompiledModule, error)

	// InstantiateModule instantiates the module or errs for reasons including
	// exit or validation.
	//
	// Here's an example:
	//	mod, _ := n.InstantiateModule(ctx, compiled, wazy.NewModuleConfig().
	//		WithName("prod"))
	//
	// # Errors
	//
	// While CompiledModule is pre-validated, there are a few situations which
	// can cause an error:
	//   - The module name is already in use.
	//   - The module has a table element initializer that resolves to an index
	//     outside the Table minimum size.
	//   - The module has a start function, and it failed to execute.
	//   - The module was compiled to WASI and exited with a non-zero exit
	//     code, you'll receive a sys.ExitError.
	//   - RuntimeConfig.WithCloseOnContextDone was enabled and a context
	//     cancellation or deadline triggered before a start function returned.
	InstantiateModule(ctx context.Context, compiled CompiledModule, config ModuleConfig) (api.Module, error)

	// CloseWithExitCode closes all the modules that have been initialized in this Runtime with the provided exit code.
	// An error is returned if any module returns an error when closed.
	//
	// Here's an example:
	//	ctx := context.Background()
	//	r := wazy.NewRuntime(ctx)
	//	defer r.CloseWithExitCode(ctx, 2) // This closes everything this Runtime created.
	//
	//	// Everything below here can be closed, but will anyway due to above.
	//	_, _ = wasi_snapshot_preview1.InstantiateSnapshotPreview1(ctx, r)
	//	mod, _ := r.Instantiate(ctx, wasm)
	CloseWithExitCode(ctx context.Context, exitCode uint32) error

	// Module returns an instantiated module in this runtime or nil if there aren't any.
	Module(moduleName string) api.Module

	// Closer closes all compiled code by delegating to CloseWithExitCode with an exit code of zero.
	api.Closer
}

Runtime allows embedding of WebAssembly modules.

The below is an example of basic initialization:

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

mod, _ := r.Instantiate(ctx, wasm)

Notes

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

func NewRuntime

func NewRuntime(ctx context.Context) Runtime

NewRuntime returns a runtime with a configuration assigned by NewRuntimeConfig.

func NewRuntimeWithConfig

func NewRuntimeWithConfig(ctx context.Context, rConfig RuntimeConfig) Runtime

NewRuntimeWithConfig returns a runtime with the given configuration.

type RuntimeConfig

type RuntimeConfig interface {
	// WithCoreFeatures sets the WebAssembly Core specification features this
	// runtime supports. Defaults to api.CoreFeaturesV2.
	//
	// Example of disabling a specific feature:
	//	features := api.CoreFeaturesV2.SetEnabled(api.CoreFeatureMutableGlobal, false)
	//	rConfig = wazy.NewRuntimeConfig().WithCoreFeatures(features)
	//
	// Example of the whole of WebAssembly 3.0, which wazy implements but does
	// not enable by default:
	//	rConfig = wazy.NewRuntimeConfig().WithCoreFeatures(api.CoreFeaturesV3)
	//
	// # Why default to version 2.0?
	//
	// Many compilers that target WebAssembly require features after
	// api.CoreFeaturesV1 by default. For example, TinyGo v0.24+ requires
	// api.CoreFeatureBulkMemoryOperations. To avoid runtime errors, wazy
	// defaults to api.CoreFeaturesV2, even though it is not yet a Web
	// Standard (REC).
	WithCoreFeatures(api.CoreFeatures) RuntimeConfig

	// WithMemoryLimitPages overrides the maximum pages allowed per memory. The
	// default is 65536, allowing 4GB total memory per instance if the maximum is
	// not encoded in a Wasm binary. Setting a value larger than default will panic.
	//
	// This example reduces the largest possible memory size from 4GB to 128KB:
	//	rConfig = wazy.NewRuntimeConfig().WithMemoryLimitPages(2)
	//
	// Note: Wasm has 32-bit memory and each page is 65536 (2^16) bytes. This
	// implies a max of 65536 (2^16) addressable pages.
	// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#grow-mem
	//
	// Note: on a platform whose int is 32 bits wide (GOARCH=386, arm, wasm) a
	// memory can never reach four gibibytes, because that is more than a Go
	// slice can hold. The effective ceiling there is 32767 pages whatever is
	// configured here, and a module asking for more fails to instantiate
	// rather than panicking in the allocator.
	//
	// Note: this bounds a memory declared with an i64 index type as well, so
	// that enabling api.CoreFeatureMemory64 cannot quietly undo it. Set that
	// ceiling independently -- above or below this one -- with
	// WithMemory64LimitPages, which then wins whichever order the two are
	// configured in.
	WithMemoryLimitPages(memoryLimitPages uint32) RuntimeConfig

	// WithMemoryCapacityFromMax eagerly allocates max memory, unless max is
	// not defined. The default is false, which means minimum memory is
	// allocated and any call to grow memory results in re-allocations.
	//
	// This example ensures any memory.grow instruction will never re-allocate:
	//	rConfig = wazy.NewRuntimeConfig().WithMemoryCapacityFromMax(true)
	//
	// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#grow-mem
	//
	// Note: if the memory maximum is not encoded in a Wasm binary, this
	// results in allocating 4GB. See the doc on WithMemoryLimitPages for detail.
	WithMemoryCapacityFromMax(memoryCapacityFromMax bool) RuntimeConfig

	// WithMemory64LimitPages overrides the maximum pages a memory declared with
	// an i64 index type may actually occupy. Unset, it follows
	// WithMemoryLimitPages -- 65536 by default -- so enabling
	// api.CoreFeatureMemory64 does not by itself let a module claim more host
	// memory than a 32-bit one could, and tightening the general limit tightens
	// this one too. Setting it here pins it whichever order the two are
	// configured in. Setting a value larger than 2^48, the specification's own
	// ceiling for a 64-bit memory, will panic.
	//
	// This example lets a 64-bit memory reach 16GB:
	//	rConfig = wazy.NewRuntimeConfig().
	//		WithCoreFeatures(api.CoreFeaturesV2 | api.CoreFeatureMemory64).
	//		WithMemory64LimitPages(1 << 18)
	//
	// Unlike WithMemoryLimitPages, this bounds what is *allocated* rather than
	// what may be declared: the specification requires a module whose declared
	// limits exceed anything a host could allocate to still be valid, so such a
	// module still compiles. It fails to instantiate if its minimum is over the
	// limit, and memory.grow returns -1 rather than growing past it.
	//
	// The same platform ceiling WithMemoryLimitPages documents applies here,
	// and is the binding one for any value over it: a Go slice cannot exceed
	// math.MaxInt bytes, so a memory tops out at 2^47-1 pages on a 64-bit
	// platform and 32767 pages on a 32-bit one.
	//
	// A module's memories are also summed: whatever index types it mixes,
	// their declared minimums together may not exceed the larger of this
	// limit and WithMemoryLimitPages'.
	//
	// See https://github.com/WebAssembly/memory64
	WithMemory64LimitPages(memory64LimitPages uint64) RuntimeConfig

	// WithMemoryCapacityReservePages allocates a backing reserve beyond a memory's
	// initial size. This can make memory.grow cheaper without reserving the
	// memory's entire maximum. Go fallback growth reapplies the reserve to the
	// new logical size. Capacity is capped by both the module maximum and
	// WithMemoryLimitPages. The logical size is tracked separately from this
	// backing allocation. The default is zero fixed pages; ordinary fallback
	// growth still uses deterministic geometric doubling.
	//
	// This example reserves up to 4MB beyond each memory's initial size:
	//	rConfig = wazy.NewRuntimeConfig().WithMemoryCapacityReservePages(64)
	//
	// WithMemoryCapacityFromMax(true) takes precedence over this setting.
	WithMemoryCapacityReservePages(memoryCapacityReservePages uint32) RuntimeConfig

	// WithDebugInfoEnabled toggles DWARF based stack traces in the face of
	// runtime errors. Defaults to true.
	//
	// Those who wish to disable this, can like so:
	//
	//	r := wazy.NewRuntimeWithConfig(wazy.NewRuntimeConfig().WithDebugInfoEnabled(false)
	//
	// When disabled, a stack trace message looks like:
	//
	//	wasm stack trace:
	//		.runtime._panic(i32)
	//		.myFunc()
	//		.main.main()
	//		.runtime.run()
	//		._start()
	//
	// When enabled, the stack trace includes source code information:
	//
	//	wasm stack trace:
	//		.runtime._panic(i32)
	//		  0x16e2: /opt/homebrew/Cellar/tinygo/0.26.0/src/runtime/runtime_tinygowasm.go:73:6
	//		.myFunc()
	//		  0x190b: /Users/XXXXX/wazy/internal/testing/dwarftestdata/testdata/main.go:19:7
	//		.main.main()
	//		  0x18ed: /Users/XXXXX/wazy/internal/testing/dwarftestdata/testdata/main.go:4:3
	//		.runtime.run()
	//		  0x18cc: /opt/homebrew/Cellar/tinygo/0.26.0/src/runtime/scheduler_none.go:26:10
	//		._start()
	//		  0x18b6: /opt/homebrew/Cellar/tinygo/0.26.0/src/runtime/runtime_wasm_wasi.go:22:5
	//
	// Note: This only takes into effect when the original Wasm binary has the
	// DWARF "custom sections" that are often stripped, depending on
	// optimization flags passed to the compiler.
	WithDebugInfoEnabled(bool) RuntimeConfig

	// WithCompilationCache configures how runtime caches the compiled modules. In the default configuration, compilation results are
	// only in-memory until Runtime.Close is closed, and not shareable by multiple Runtime.
	//
	// Below defines the shared cache across multiple instances of Runtime:
	//
	//	// Creates the new Cache and the runtime configuration with it.
	//	cache := wazy.NewCompilationCache()
	//	defer cache.Close()
	//	config := wazy.NewRuntimeConfig().WithCompilationCache(c)
	//
	//	// Creates two runtimes while sharing compilation caches.
	//	foo := wazy.NewRuntimeWithConfig(context.Background(), config)
	// 	bar := wazy.NewRuntimeWithConfig(context.Background(), config)
	//
	// # Cache Key
	//
	// Cached files are keyed on the version of wazy. This is obtained from go.mod of your application,
	// and we use it to verify the compatibility of caches against the currently-running wazy.
	// However, if you use this in tests of a package not named as `main`, then wazy cannot obtain the correct
	// version of wazy due to the known issue of debug.BuildInfo function: https://github.com/golang/go/issues/33976.
	// As a consequence, your cache won't contain the correct version information and always be treated as `dev` version.
	// To avoid this issue, you can pass -ldflags "-X github.com/samyfodil/wazy/internal/version.version=foo" when running tests.
	WithCompilationCache(CompilationCache) RuntimeConfig

	// WithCustomSections toggles parsing of "custom sections". Defaults to false.
	//
	// When enabled, it is possible to retrieve custom sections from a CompiledModule:
	//
	//	config := wazy.NewRuntimeConfig().WithCustomSections(true)
	//	r := wazy.NewRuntimeWithConfig(ctx, config)
	//	c, err := r.CompileModule(ctx, wasm)
	//	customSections := c.CustomSections()
	WithCustomSections(bool) RuntimeConfig

	// WithCloseOnContextDone ensures the executions of functions to be terminated under one of the following circumstances:
	//
	// 	- context.Context passed to the Call method of api.Function is canceled during execution. (i.e. ctx by context.WithCancel)
	// 	- context.Context passed to the Call method of api.Function reaches timeout during execution. (i.e. ctx by context.WithTimeout or context.WithDeadline)
	// 	- Close or CloseWithExitCode of api.Module is explicitly called during execution.
	//
	// This is especially useful when one wants to run untrusted Wasm binaries since otherwise, any invocation of
	// api.Function can potentially block the corresponding Goroutine forever. Moreover, it might block the
	// entire underlying OS thread which runs the api.Function call. See "Why it's safe to execute runtime-generated
	// machine codes against async Goroutine preemption" section in RATIONALE.md for detail.
	//
	// Upon the termination of the function executions, api.Module is closed.
	//
	// Note that this comes with a bit of extra cost when enabled. The reason is that internally this forces
	// interpreter and compiler runtimes to insert the periodical checks on the conditions above. For that reason,
	// this is disabled by default.
	//
	// In the compiler the check is a decrement of a reserved register and a predicted-not-taken branch at every
	// function entry and every loop back-edge. When the counter runs out the guest returns to Go, which checks
	// whether the module has been closed and yields its P so the cancellation watchdog can run -- which is what
	// makes the option work at all, since compiled code is otherwise not preemptible. The shape that pays most
	// is a near-empty compute kernel, which has no body to dilute the per-back-edge check against. See
	// docs/performance.md for measured numbers.
	//
	// See examples in context_done_example_test.go for the end-to-end demonstrations.
	//
	// When the invocations of api.Function are closed due to this, sys.ExitError is raised to the callers and
	// the api.Module from which the functions are derived is made closed.
	WithCloseOnContextDone(bool) RuntimeConfig
}

RuntimeConfig controls runtime behavior, with the default implementation as NewRuntimeConfig

The example below explicitly limits to Wasm Core 1.0 features as opposed to relying on defaults:

rConfig = wazy.NewRuntimeConfig().WithCoreFeatures(api.CoreFeaturesV1)

Notes

  • This is an interface for decoupling, not third-party implementations. All implementations are in wazy.
  • RuntimeConfig is immutable. Each WithXXX function returns a new instance including the corresponding change.

func NewRuntimeConfig

func NewRuntimeConfig() RuntimeConfig

NewRuntimeConfig returns a RuntimeConfig using the compiler if it is supported in this environment, or the interpreter otherwise.

func NewRuntimeConfigCompiler

func NewRuntimeConfigCompiler() RuntimeConfig

NewRuntimeConfigCompiler compiles WebAssembly modules into runtime.GOARCH-specific assembly for optimal performance.

The default implementation is AOT (Ahead of Time) compilation, applied at Runtime.CompileModule. This allows consistent runtime performance, as well the ability to reduce any first request penalty.

Note: While this is technically AOT, this does not imply any action on your part. wazy automatically performs ahead-of-time compilation as needed when Runtime.CompileModule is invoked.

Warning

  • This panics at runtime if the runtime.GOOS or runtime.GOARCH does not support compiler. Use NewRuntimeConfig to safely detect and fallback to NewRuntimeConfigInterpreter if needed.

  • If you are using wazy in buildmode=c-archive or c-shared, make sure that you set up the alternate signal stack by using, e.g. `sigaltstack` combined with `SA_ONSTACK` flag on `sigaction` on Linux, before calling any api.Function. This is because the Go runtime does not set up the alternate signal stack for c-archive or c-shared modes, and wazy uses the different stack than the calling Goroutine. Hence, the signal handler might get invoked on the wazy's stack, which may cause a stack overflow. https://github.com/samyfodil/wazy/blob/2092c0a879f30d49d7b37f333f4547574b8afe0d/internal/integration_test/fuzz/fuzz/tests/sigstack.rs#L19-L36

func NewRuntimeConfigInterpreter

func NewRuntimeConfigInterpreter() RuntimeConfig

NewRuntimeConfigInterpreter interprets WebAssembly modules instead of compiling them into assembly.

Directories

Path Synopsis
Package api includes constants and interfaces used by both end-users and internal implementations.
Package api includes constants and interfaces used by both end-users and internal implementations.
benchmarks
coldstart command
Command coldstart runs a wasip2 *command* component (one exporting wasi:cli/run) end to end -- decode, compile, instantiate, invoke run() -- and exits.
Command coldstart runs a wasip2 *command* component (one exporting wasi:cli/run) end to end -- decode, compile, instantiate, invoke run() -- and exits.
cmd
wazy command
Package component runs WebAssembly Component Model components -- and the WASI 0.2 (wasip2) world built on it -- on a wazy Runtime.
Package component runs WebAssembly Component Model components -- and the WASI 0.2 (wasip2) world built on it -- on a wazy Runtime.
componenttest
Package componenttest provides utilities for testing a host implementation of a component interface.
Package componenttest provides utilities for testing a host implementation of a component interface.
examples
allocation/rust command
allocation/zig command
basic command
component command
custom-wit command
import-go command
imports
assemblyscript
Package assemblyscript contains Go-defined special functions imported by AssemblyScript under the module name "env".
Package assemblyscript contains Go-defined special functions imported by AssemblyScript under the module name "env".
emscripten
Package emscripten contains Go-defined special functions imported by Emscripten under the module name "env".
Package emscripten contains Go-defined special functions imported by Emscripten under the module name "env".
http_handler
Package http_handler runs guests built against the http-wasm handler ABI, the middleware ABI used by Traefik's and dapr's WebAssembly plugin systems.
Package http_handler runs guests built against the http-wasm handler ABI, the middleware ABI used by Traefik's and dapr's WebAssembly plugin systems.
http_handler/nethttp
Package nethttp wraps an http-wasm guest as a net/http.Handler, so a guest can act as HTTP middleware in front of an existing handler.
Package nethttp wraps an http-wasm guest as a net/http.Handler, so a guest can act as HTTP middleware in front of an existing handler.
http_handler/nethttp/internal/tck
Package tck is the http-wasm Technology Compatibility Kit, vendored from github.com/http-wasm/http-wasm-host-go (Apache 2.0): its guest binary (tck.wasm), the backend handler that guest expects, and the assertions that exercise the ABI over real HTTP.
Package tck is the http-wasm Technology Compatibility Kit, vendored from github.com/http-wasm/http-wasm-host-go (Apache 2.0): its guest binary (tck.wasm), the backend handler that guest expects, and the assertions that exercise the ABI over real HTTP.
wasi_http
Package wasi_http implements the pre-standard WASI-HTTP host ABI defined by github.com/stealthrocket/wasi-go, so guests built against its client bindings (the dev-wasm Go, Rust, C, AssemblyScript and dotnet examples, and anything else compiled against them) run on wazy unmodified.
Package wasi_http implements the pre-standard WASI-HTTP host ABI defined by github.com/stealthrocket/wasi-go, so guests built against its client bindings (the dev-wasm Go, Rust, C, AssemblyScript and dotnet examples, and anything else compiled against them) run on wazy unmodified.
wasi_otel
Package wasi_otel implements the host side of the wasi:otel proposal, so a component instrumented with OpenTelemetry reports its spans, logs and metrics to the embedder rather than needing a collector of its own.
Package wasi_otel implements the host side of the wasi:otel proposal, so a component instrumented with OpenTelemetry reports its spans, logs and metrics to the embedder rather than needing a collector of its own.
wasi_snapshot_preview1
Package wasi_snapshot_preview1 contains Go-defined functions to access system calls, such as opening a file, similar to Go's x/sys package.
Package wasi_snapshot_preview1 contains Go-defined functions to access system calls, such as opening a file, similar to Go's x/sys package.
wasip2/wit
Package wit declares the WASI 0.2 WIT types that more than one host implementation needs.
Package wit declares the WASI 0.2 WIT types that more than one host implementation needs.
wasmedge
Package wasmedge implements the WasmEdge sockets extension to WASI preview 1, so a guest built against WasmEdge's socket SDKs -- the raw TCP and UDP access WASI preview 1 has no equivalent for -- runs on wazy.
Package wasmedge implements the WasmEdge sockets extension to WASI preview 1, so a guest built against WasmEdge's socket SDKs -- the raw TCP and UDP access WASI preview 1 has no equivalent for -- runs on wazy.
internal
component/abi
Package abi implements the Canonical ABI for the WebAssembly Component Model.
Package abi implements the Canonical ABI for the WebAssembly Component Model.
component/instance
Package instance instantiates a decoded WebAssembly component and exposes its exported functions for calling.
Package instance instantiates a decoded WebAssembly component and exposes its exported functions for calling.
component/testfixtures
Package testfixtures holds guest components shared by more than one package's tests.
Package testfixtures holds guest components shared by more than one package's tests.
engine/native/backend
Package backend must be free of Wasm-specific concept.
Package backend must be free of Wasm-specific concept.
engine/native/backend/regalloc
Package regalloc performs register allocation.
Package regalloc performs register allocation.
engine/native/frontend
Package frontend implements the translation of WebAssembly to SSA IR using the ssa package.
Package frontend implements the translation of WebAssembly to SSA IR using the ssa package.
engine/native/ssa
Package ssa is used to construct SSA function.
Package ssa is used to construct SSA function.
expctxkeys
Package expctxkeys provides keys for the context used to store the experimental APIs.
Package expctxkeys provides keys for the context used to store the experimental APIs.
fstest
Package fstest defines filesystem test cases that help validate host functions implementing WASI.
Package fstest defines filesystem test cases that help validate host functions implementing WASI.
logging
Package logging includes utilities used to log function calls.
Package logging includes utilities used to log function calls.
platform
Package platform includes runtime-specific code needed for the compiler or otherwise.
Package platform includes runtime-specific code needed for the compiler or otherwise.
sys
sysfs
Package sysfs includes a low-level filesystem interface and utilities needed for WebAssembly host functions (ABI) such as WASI.
Package sysfs includes a low-level filesystem interface and utilities needed for WebAssembly host functions (ABI) such as WASI.
testing/require
Package require includes test assertions that fail the test immediately.
Package require includes test assertions that fail the test immediately.
u32
u64
wasip1
Package wasip1 is a helper to remove package cycles re-using constants.
Package wasip1 is a helper to remove package cycles re-using constants.
wasmdebug
Package wasmdebug contains utilities used to give consistent search keys between stack traces and error messages.
Package wasmdebug contains utilities used to give consistent search keys between stack traces and error messages.
wasmruntime
Package wasmruntime contains internal symbols shared between modules for error handling.
Package wasmruntime contains internal symbols shared between modules for error handling.
Package sys includes constants and types used by both public and internal APIs.
Package sys includes constants and types used by both public and internal APIs.
Package sysfs includes a low-level filesystem interface and utilities needed for WebAssembly host functions (ABI) such as WASI.
Package sysfs includes a low-level filesystem interface and utilities needed for WebAssembly host functions (ABI) such as WASI.

Jump to

Keyboard shortcuts

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