A WebAssembly interpreter written in GoML, supporting Core 1.0 numeric and control operations plus Core 2 multi-value, reference types, fixed-width SIMD and bulk memory/table operations. Decode and validate a binary module, bind explicitly supplied imports, instantiate it in a store, and call its exported functions. The implementation uses an explicit instruction loop and call frames. Runtime execution depends only on the GoML standard library.
Use the GoML toolchain pinned by the shared ecosystem verifier. Module coordinate: ecosystem::wasm.
use ecosystem::wasm;
fn run(bytes: Slice[u8]) -> Result[Vec[wasm::Value], wasm::Error] {
let module = wasm::Module::new(bytes)?;
let store = wasm::Store::new();
let instance = store.instantiate(module, wasm::Linker::new())?;
store.call(instance, "add", Vec::from_array([
wasm::Value::I32(20), wasm::Value::I32(22),
]))
}
examples/basic contains a complete, executable addition module and independent
consumer tests. goml run --example basic prints 42.
The implemented feature set follows
WebAssembly Core 2.0, including fixed-width SIMD.
The official wg-2.0 sources are pinned at
fffc6e12fa454e475455a7b58d3b5dc343980c10.
| Capability | Implemented scope |
|---|---|
| Binary decoding | Version 1 header, sections including data count, all element/data segment encodings, custom-section names, bounded signed/unsigned LEB128 including signed 33-bit block types and Core 3 u64 memory offsets/size limits |
| Validation | Operand/control stacks, unreachable polymorphism, instruction types, indexes, limits, const expressions, declared function references, imports, exports and start signature |
| Numeric values | i32, i64, f32, f64; 123 original numeric instructions, five sign extensions and eight saturating float-to-integer conversions |
| SIMD | v128, all 236 fixed-width SIMD instructions and all 20 relaxed SIMD instructions; includes lane operations, saturating arithmetic, conversions and indexed memory access |
| References | Nullable/non-null function and external references, recursive function groups, declared function subtyping, typed calls, null branches, typed tables/globals and select |
| Control | Multiple parameters/results, loop parameters, branches, direct/indirect/reference calls and their tail-call forms |
| State | Multiple wasm32/wasm64 linear memories, 32/64-bit indexed typed tables, mutable/immutable globals; active/passive data and active/passive/declarative elements |
| Bulk operations | Memory/table init, copy and fill; segment drop; table get/set, size and grow |
| Exceptions | Tags, throw, throw_ref, try_table, exception references and host-created exceptions |
| Embedding | All five import/export kinds, multi-result host functions, cross-instance calls and shared state within a store, Wasm backtraces |
| WASI Preview 1 | Explicit args/environment, buffered stdio, bounded in-memory preopens/files, clocks/random/poll callbacks and structured process exit |
Threads, components, text-format parsing, GC object types and JIT/AOT compilation remain future work. Unsupported binary features are rejected. WAT/WAST tooling generates test fixtures and is not a runtime dependency.
Value::V128(low, high) stores the first and second eight bytes of a vector as
little-endian u64 halves. Values are immutable and work with host arguments,
results, globals, locals, blocks and select. A vector counts as one operand for
stack limits; each SIMD instruction consumes the usual instruction fuel unit.
Loads and stores check their actual access width before any memory mutation,
including lane, extending and zeroing loads. Reserved SIMD opcodes are rejected;
lane, shuffle, alignment and memory indexes are validated even
in unreachable code.
The retained SIMD corpus contains all 58 official scripts and 25,478 binary commands. Its 510 WAT-only malformed assertions are explicitly recorded as outside the binary API. Sources and compiler are authenticated, and every fixture can be regenerated byte-for-byte. Together with the scalar corpus, the Core 2 fixtures retain 148 scripts and 52,915 binary commands; this is test coverage, not a claim that every possible Core 2 program has been verified.
Relaxed SIMD follows the Core 3 numeric rules
with all implementation-choice parameters fixed to zero for every execution:
strict swizzle and bitselect, saturating truncation and Q15 multiplication,
strict min/max, and separately rounded multiply then add. Negative multiply-add
negates its first operand before multiplication. Dot products wrap each pair to
16 bits before sign extension and accumulation. This profile is deterministic
apart from the existing permitted floating-point NaN payload choices.
The separate relaxed SIMD corpus retains all seven official scripts and 79
commands at spec revision f3268fa9dcb7d3a60d09546e743e7281e75cddb0, without
omissions. Alternative expected results are matched as complete vectors.
Core 3 encodes memory offsets and memory/table size limits as unsigned 64-bit LEB128 even for wasm32. The decoder preserves all 64 bits and accepts legal padding through ten bytes; validation checks the selected address type's bounds. Indexes, vector counts and opcode prefixes retain their unsigned 32-bit encoding rules. Eighteen exact historical Core 1/Core 2 assertion migrations retain the original binaries: six now validate, and twelve have valid encodings but fail semantic validation. Their outcomes were checked independently with authenticated wasm-tools 1.263.0.
Function/external reference types support nullability, nofunc/noextern,
recursive function groups and declared function subtyping. call_ref,
return_call_ref, ref.as_non_null, br_on_null and br_on_non_null are
implemented, including non-defaultable locals and explicitly initialized typed
tables. Function types retain recursive-group identity, member position, finality
and declared parents; matching uses the declared subtype relation across modules.
GC object heap types remain outside this scope; exception references are described below.
ValueType::Ref(RefType { nullable, heap }) represents the richer types;
legacy FuncRef/ExternRef still denote nullable abstract references. Module
metadata uses HeapType::TypeIndex for module-local indices. Use
Module::type_count, function_type, import_function_type_index and
export_function_type_index to inspect these declarations. Store::resolve_type
returns an opaque, store-owned DefinedType; Store::type_signature returns its
resolved signature. Host APIs reject unresolved indices and foreign-store handles.
Store::host_func_typed(module, type_index, callback) gives a host function the
exact declared type; Func::defined_type() retrieves its handle. The existing
host_func creates an anonymous final singleton type. Use typed_global and
typed_table_with_value / typed_table64_with_value for explicit reference types
and non-null initial values. Global::value_type() reports its declaration.
Value::kind() retains its broad runtime categories; Value::default_value
returns None for non-defaultable references. The legacy Value::zero returns a
null placeholder for such a type, which typed host boundaries reject.
Type normalization is bounded independently by max_validation_work; the store
limits canonical type count to max_items and cumulative canonical metadata
(including keys and ancestors) to max_validation_work. Queries use bounded
ancestor searches, and failed preflight does not publish staged type identities
or consume type quotas. Defined function and tag signature copies and per-instance type mappings also
consume store object slots and instantiation fuel. These limits are checked before
publication.
The retained function-reference suite includes 34 original official sources and 2,186 commands, including all 32 type-equivalence commands and the function-only recursive subtype cases. Its manifest records 177 exclusions: 58 text-only, one host-resource-limit declaration, 71 GC-dependent commands and 47 commands depending on excluded modules. Sources, excluded commands and dependency links are retained and authenticated; original assertion outcomes are unchanged.
ref.test, ref.cast, br_on_cast and br_on_cast_fail support function,
external and exception references, including nullable and bottom heap types.
Function tests and casts use declared canonical subtyping. Failed casts return
Trap::BadCast, which exception handlers cannot catch. Cast branches retain the
reference and the target label's preceding values; success and failure paths
apply the specified nullability refinement.
These six binary instructions are partial GC-instruction support. GC object heap types, structures, arrays, i31 values and their operations remain unsupported.
Tags, throw, throw_ref and try_table implement the modern Core 3 exception
instructions. The four catch forms transfer tag payloads and/or a non-null
exception reference to an outer label. Matching uses tag instance identity;
separately created tags with identical signatures remain distinct. Tag imports
require exact canonical type equivalence. Tag function types have no results.
Legacy try/catch/rethrow/delegate encodings are not supported.
Store::tag creates a host tag; tag_typed uses a module's exact declared type.
Module::import_tag_type_index and export_tag_type_index expose those indices;
Tag::defined_type and function_type return the canonical handle and a signature
snapshot. Tags are available through Extern::Tag and ExternType::Tag.
Store::exception(tag, values) validates ownership and payload types and copies
the values. Exception::tag and values expose the tag and a defensive payload
copy. Value::ExnRef carries nullable exception handles; HeapType::Exn and
NoExn form a separate reference family. throw_ref preserves exception identity.
An uncaught guest or host exception returns Error::Exception. Ordinary traps,
host errors, process exit and resource exhaustion cannot be caught by Wasm
handlers; throwing a null reference produces Trap::NullReference. Unwinding
searches handlers across active calls, excluding callers removed by tail calls.
Exception allocation, payload copying and handler search consume resource budgets.
The pinned exception corpus retains all five source scripts and executes 108
binary commands, including 18 exception assertions that only accept
Error::Exception. Only two WAT-only assertions are excluded; exception casts
are included. Fixture sources, omission hashes and compiler provenance are retained for offline reproduction.
Memory and table declarations select i32 or i64 addresses. Scalar/SIMD memory
accesses, size/grow, table access, indirect calls (including tail calls), active
segments and bulk operations honor that selection. Mixed-width copy uses each
operand's own address type and the narrower type for its length. Initialization
from passive segments keeps its source offset and length as i32. Range checks
precede conversion to host indices and writes; large addresses never wrap to a
low location.
The existing wasm32 constructors and accessors remain available. Use
Store::memory64, Store::table64 or Store::typed_table64 to create wide objects;
address_type() reports AddressType::I32 or AddressType::I64. Memory provides
pages64, read64, write64 and grow64; tables provide get64, get_value64,
set64, set_value64 and grow64. Import/export metadata distinguishes
ExternType::Memory64(SizeLimits64) and ExternType::Table64(TableType64);
imports require an exact address-width match. Existing exhaustive matches on
ExternType need to handle these two added variants.
Wide addresses do not remove resource limits: the default store permits 256
memory pages, the configurable cumulative page cap remains at most 65,536, and
table allocation remains subject to max_table_elements. Memory64 declarations
may specify a maximum of 2^48 pages and table64 a maximum of 2^64−1 elements;
growth still fails when the store budget cannot accommodate it. WASI Preview 1
functions that access memory require an exported wasm32 memory.
All 25 pinned official memory64/table64 scripts are retained, with 8,656 commands executed. The manifest explicitly records 59 text-only assertions, two commands requiring GC objects, and two compile-only declarations whose minimum sizes exceed supported host resource limits. Authenticated wasm-tools 1.263.0 reproduces the fixtures, including every excluded command, from unmodified official sources.
Modules may import and define multiple memories of either address width. Loads/stores, size/grow,
fill, init and copy use their declared memory indices; active data segments and
exports do likewise. memory.copy checks both complete ranges before writing,
including when distinct imported indices alias the same host memory. Memory page
limits remain cumulative across the store. WASI continues to use the caller's
export named memory.
The retained Core 1 and Core 2 corpora have 15 and 20 explicit multi-memory migrations respectively. Each migration checks the complete original command before applying its replacement; original official JSON files remain unchanged. An additional pinned official suite retains all 41 multi-memory scripts and 912 commands, with no omitted assertions. These run through the public API in the extensions example; retained WAST sources reproduce the binary fixtures using the authenticated WABT compiler.
The interpreter also accepts return_call and return_call_indirect, and
i32.add/sub/mul and i64.add/sub/mul in constant expressions. Tail calls
replace the active frame, including its locals, labels and unused operands;
ordinary callers retain their operands. Indirect tail calls retain table bounds,
null and signature checks. Host tail calls retain access to the calling
instance through Caller. Backtraces omit replaced frames. Invocation fuel and
stack limits still apply; an infinite tail recursion exhausts fuel.
Extended constants use wrapping integer arithmetic and are checked with a typed
operand stack. Each initializer instruction after the first, excluding end,
costs one additional fuel unit. Evaluation respects the store's stack limit.
Global initializers may read imported immutable globals and preceding defined
immutable globals. Segment expressions can read all defined immutable globals.
Self references, forward references and mutable-global reads are rejected.
Six historical Core 2 assertions use exact global-scope migrations.
This is partial Core 3 support; see the specification gap inventory.
Core 2 allows module forms that Core 1 rejected, including multiple function
results and tables. Active segment bounds failures now return a memory/table
Error::Trap, and earlier successful segments retain their effects. Constant
expressions now follow Core 3 global visibility rules described above. The original Core 1 corpus
is retained unchanged; its explicit, checked migration list records assertions
whose expected outcome changes under Core 2. See
conformance tests for details.
-
Module::new(bytes)andModule::with_limits(bytes, limits)decode and fully validate before producing a module. A module owns its decoded data and can be reused across instances and stores.Module::exports()returns a fresh list. -
Module::imports()returnsImportTyperecords withmodule,nameandkind;Module::export_types()returnsExportTyperecords withnameandkind. Both preserve binary declaration order, including repeated imports and exports that alias the same object. Queries need no store or import bindings and do not instantiate the module or execute its start function.ExternTypedescribes functions (FuncType), tables (TableType), memories (SizeLimits) and globals (GlobalType). Function signatures include all parameter/result types; table descriptions include their referencekindandlimits; global descriptions includekindandmutable.SizeLimitsexposes the declaredminand optionalmax, measured in 64 KiB pages for memories and elements for tables. These are module declarations, unaffected by instance growth or a linked import's actual size. Each query returns an independent list and copies every function signature, including signatures shared by multiple entries. Mutating the results cannot change the module, other entries or later queries. -
Store::new()uses standard limits;Store::with_limits(limits)selects them. A store owns instantiated functions and state for its lifetime. -
Linker::define(module, name, external)binds an import; duplicate bindings return a link error.Store::instantiate(module, linker)checks all import types and store identities before initialization. -
Store::call(instance, export, arguments)invokes an exported function.Store::invoke(function, arguments)also supports aFunchandle. -
Store::export(instance, name)returnsExtern::Func,Memory,TableorGlobal. Handles retain shared state and require their originating store. -
Store::host_func(signature, callback)copies its signature. The callback takes(Caller, Vec[Value]), returnsResult[Vec[Value], Error], and may access the calling instance's exports usingCaller::export. Return types are checked. Argument vectors are copied for callbacks; returned values are collected into an independent vector. -
Store::memory,tableandglobalcreate objects for host-defined imports. Memory reads return copies; writes check the complete range before mutation.Func::function_type()returns a copied signature. Table operations check indexes and function ownership; global writes enforce mutability and type. -
Store::typed_table(kind, minimum, maximum)creates afuncreforexternreftable.Table::element_type,get_value,set_valueandgrow(delta, value)support both types. ExistingStore::tableandTable::get/setremain convenient function-table APIs. Growth returnsNonewhen a limit prevents it. -
Store::extern_ref(data)creates a reference with a distinct identity and an opaqueu64host token;ExternRef::data()retrieves that token. Applications may use tokens to index their own host-object maps. Equal tokens do not make two references equal. Wasm cannot inspect the token. Reference arguments, callback results, globals and tables enforce store ownership. -
Store::backtrace()copies the most recent execution failure's active Wasm frames, innermost first. EachTrapFramecontains the store-local instance index (also available asInstance::id()), module function index (including imports), and module byte offset. Starting an invocation clears the previous trace. Host-only failures and failures before a Wasm frame is entered have no Wasm frames. Name sections and source/debug mappings are not yet exposed.
Stores and their mutable handles are intended for one executing host thread at a
time. Shared handles alias state; independent stores can execute separately.
Recursive host reentry into an executing store returns Error::Argument.
Callbacks may access memory, tables and globals, but must enforce their own I/O
and time limits. The interpreter's fuel cannot interrupt a blocking host callback.
Host callback errors propagate; a panic raised by host code remains a host panic.
Wasi binds the wasi_snapshot_preview1 ABI. The implementation follows the
pinned legacy WITX
and registers all 46 function signatures, including sock_accept. Its supported
resource model is a bounded in-memory filesystem and buffered standard streams.
let filesystem = wasm::WasiFs::new();
let directory = filesystem.preopen("/sandbox")
.map_err(|code| wasm::Error::Argument(f"WASI errno {code}"))?;
filesystem.write_file(directory, "input.txt", b"hello".as_slice())
.map_err(|code| wasm::Error::Argument(f"WASI errno {code}"))?;
let context = wasm::Wasi::with_config(wasm::WasiConfig {
args: Vec::from_array(["app", "/sandbox/input.txt"]),
env: Vec::from_array([("MODE", "demo")]),
filesystem,
..wasm::WasiConfig::standard(),
})?;
let linker = wasm::Linker::new();
context.link(store, linker)?;
let instance = store.instantiate(module, linker)?;
let exit_code = context.run(store, instance)?;
let output = context.stdout();
Filesystem setup methods return WASI errno values (u16); Wasi setup and
execution return Error. The example above maps filesystem errors into Error. The complete
examples/wasi handles both error types and runs a
real wasi-sdk C program. Memory-using imports access the caller's exported
memory; _start must have signature [] -> [].
WasiConfig::standard()inherits no process arguments, environment, input, directories, clocks or entropy.with_configvalidates and copies argument, environment and stdin data.stdout()andstderr()return copied buffers. Their combined captured size is bounded. Filesystem handles intentionally share state with the host and must be used serially, like aStore.WasiFs::preopen(name)creates an empty virtual root. Host code can populate it usingwrite_file; guest paths resolve beneath the directory descriptor used for the operation. Absolute paths and traversal above that directory are rejected. Rights are checked on every operation and can only be reduced. Files, directories, hard links, descriptor renumbering, seek, positional I/O, directory entries and explicit timestamp updates are supported.WasiSystem::disabled()is the default. Configure callbacks for deterministic execution or explicitly selectWasiSystem::host()for host realtime and monotonic clocks, cryptographic randomness and sleeping. CPU clocks are not provided byhost(). Unsupported clocks returnINVAL; unavailable randomness and sleeping returnNOTSUP. Custom callbacks must enforce their own time bounds; interpreter fuel cannot interrupt a blocked host callback.poll_oneoffreports buffered/file I/O readiness and supported clock events. Clock waits require a sleep callback and are capped bymax_poll_ns(one second by default). It rechecks deadlines after sleeping; callbacks that return before any deadline produceAGAIN, never a fabricated completion.proc_exitstops guest execution withError::Exit(code)without exiting the host process.Wasi::runconverts that into an exit code; normal_startreturn means zero. A context represents one process, retains its exit code, and rejects further guest WASI calls with the same exit signal. Create a new context for another process.linkis single-use and preflights all signatures, duplicate names and store quotas before registering anything.
Host filesystem mounts, symbolic links, sockets and process signals are not
implemented. Symbolic-link operations return NOTSUP; socket and signal imports
return NOSYS. File timestamps start at zero and change only through explicit
set-times calls. In-memory sync operations have no persistent storage to flush.
These limits are part of this release's WASI scope, not full OS emulation.
Default limits are 1 MiB per I/O operation, 1,024 iovecs, and 1 MiB combined
stdout/stderr. WasiFsLimits::standard() permits 4,096 cumulative inodes, 256
open descriptors (including stdin/stdout/stderr), 16 MiB per file, 64 MiB total
file contents, 4,096 total directory entries, 4,096-byte paths and 255-byte names.
Unlinked file contents are reclaimed after the last open descriptor closes;
inode slots remain counted. Shrinking files releases the previous backing buffer.
Directory and descriptor maps compact deleted entries to bound retained storage.
The ABI uses little-endian wasm32 pointers and checked lengths. Result pointers
and all scatter/gather ranges are validated before I/O effects. Out-of-bounds
pointers trap with MemoryOutOfBounds; misaligned typed pointers
trap with MisalignedPointer, as required by the pinned WITX pointer rules.
Exhausted resource budgets return errno values such as NOMEM,
NOSPC or FBIG. Each import charges 32 units of interpreter fuel in addition to
ordinary host-call accounting. Variable work charges include argument bytes,
iovecs, transferred bytes, file growth/shrink copies, directory sorting, metadata
compaction, random bytes and poll subscriptions. Caller::consume_fuel is also available to other
host callbacks. Fuel exhaustion remains an interpreter trap.
Error distinguishes Decode(byte_offset, message),
Validation(function_index, byte_offset, message), Link(message), Trap(kind),
Limit(message), invalid embedding Argument(message), and WASI Exit(code). Module-level
validation uses function index -1. Trap variants identify unreachable code,
integer arithmetic/conversion errors, memory/table bounds, indirect-call failures,
exhausted fuel/stack, and host failures.
Each memory/table bulk operation checks its complete source and destination ranges before mutation, including zero-length operations. Overlapping copies preserve source values. Segment drop is idempotent; dropped segments behave as empty. Segment state belongs to each instance, so dropping a segment leaves other instances of the same module unaffected.
Instantiation initializes active element segments, drops declarative elements, then initializes active data segments, in module order. An out-of-bounds segment traps; effects of earlier successful segments remain. A start function runs after initialization and similarly retains preceding effects on failure. Allocated objects remain owned by the store after initialization/start traps because imported tables can retain references to their functions. There is no rollback.
Limits::standard() supplies:
| Limit | Default |
|---|---|
| Module bytes | 16 MiB |
| Decoded structural items | 100,000 |
| Locals including parameters per function | 100,000 |
| Instructions across function bodies and initializers | 1,000,000 |
| Validation work across the module | 10,000,000 |
| Validation operand/control stack limit | 100,000 |
| Runtime value, local and label slots combined | 100,000 |
| Active Wasm call frames | 1,024 |
| Linear memory pages across a store | 256 (16 MiB) |
| Table elements across a store | 100,000 |
| Store objects across instances | 100,000 |
| Initial fuel | 10,000,000 |
Module::with_limits controls decoding and validation; store limits govern
allocation and execution. Structural counting includes section-vector entries,
function type entries, branch labels and expanded locals. max_validation_work
bounds cumulative type/operand/metadata checking, including multi-value and
branch-table comparisons. Store objects include
instances, functions, memories, tables, globals, imported bindings, host references,
segment records/element entries and copied host-signature entries. Input limits apply to the
already supplied byte slice; callers reading untrusted files should bound reads.
Fuel is shared across calls and initialization. Each executed instruction costs one unit; invocation costs one plus its parameter
count and defined local count, charged before argument/local allocation. Indirect calls,
including tail calls, additionally charge the expected parameter and result counts
before comparing signatures. Linking each function import from the same store
also charges its expected parameter and result counts before signature comparison;
failed linking may consume fuel but does not publish an instance. Initialization
additionally charges global count,
allocated memory pages/table elements, and copied segment bytes/elements.
Successful memory growth charges the requested page count; table growth charges
the new element count. Bulk operations charge bytes/elements processed, and
branches/returns charge values that must be moved within the operand stack.
Host result collection charges one unit per returned value. A growth rejected by
a declared/store maximum returns -1 without a page-allocation charge.
Store::fuel() inspects the remainder; set_fuel() resets it when idle. Fuel
exhaustion sets the remainder to zero and traps. Runtime limits may reject valid
modules or interrupt their execution; they do not extend the compatibility scope.
goml fmt --check
goml test
goml run --example basic
python3 tools/conformance.py check
python3 tools/differential.py check
python3 tools/extensions.py check
python3 tools/wasi_fixtures.py checkThe conformance example runs all 74 pinned official scripts offline: 18,902 binary commands, including cross-module registration and linking. The 492 WAT-syntax-only assertions are individually listed as outside the binary API. The additional Core 2 example runs all 90 top-level official scripts: 27,437 binary commands, with 581 WAT syntax assertions explicitly outside the binary API. Its 58 SIMD scripts run separately in the retained SIMD corpus described above. An additional 160 retained outcomes were produced by executing an independent WABT 1.0.42 interpreter (152 exact results and eight traps). Its provenance, regeneration instructions, coverage and exclusions are recorded beside those fixtures. Binary parser, validator, numeric edge and runtime regression tests supplement the official suite. GitHub Actions uses the ecosystem's pinned verification toolchain and independent registry checks. The WASI example adds real wasi-sdk command/reactor fixtures and an independently generated module checking every registered WASI function signature; regeneration tools authenticate the compiler and ABI sources.