toywasmx 0.2.0

Safe, Wasmtime/Wasmi-inspired Rust bindings for the toywasm WebAssembly interpreter
Documentation

toywasmx

Rust bindings for the toywasm WebAssembly interpreter (written in C), with a safe API inspired by Wasmi and Wasmtime.

The goal is to make it easy to embed the toywasm interpreter from Rust behind a safe, idiomatic, RAII-based API.

Crates

Crate Description
toywasmx-sys Raw FFI bindings; builds the vendored C sources with cc + bindgen.
toywasmx Safe, RAII, Wasmtime/Wasmi-inspired wrapper. Use this one.

Usage

use toywasmx::{Linker, Module, Store, Val};

let store = Store::new();
let wasm = wat::parse_str(
    r#"(module (func (export "add") (param i32 i32) (result i32)
           local.get 0 local.get 1 i32.add))"#,
)?;
let module = Module::new(&store, &wasm)?;
let mut instance = Linker::new().instantiate(&store, module)?;

let add = instance.get_func("add")?;
let mut results = [Val::I32(0)];
add.call(&mut instance, &[Val::I32(2), Val::I32(3)], &mut results)?;
assert_eq!(results[0], Val::I32(5));

Exported globals are reachable too, via Instance::get_global (Global::get / Global::set).

Host functions are registered on a Linker and may be any closure (not just a bare fn), so adapters can bridge callbacks that speak a different value type:

# use toywasmx::{FuncType, Linker, Val, ValType};
let mut linker = Linker::new();
linker.func_new(
    "env",
    "add",
    &FuncType::new([ValType::I32, ValType::I32], [ValType::I32]),
    |params: &[Val], results: &mut [Val]| {
        let (Val::I32(a), Val::I32(b)) = (params[0], params[1]) else { return };
        results[0] = Val::I32(a + b);
    },
);

Relationship to Wasmtime/Wasmi

The API is intentionally close to Wasmtime/Wasmi, but does not add types that have no meaning for toywasm: there is no Engine, because toywasm chooses its configuration entirely at compile time (via the Cargo features below), and a Module is created from a Store rather than an engine, because toywasm ties a module to a memory context.

Building

Requirements:

  • A C compiler (used via the cc crate).

  • libclang (used by bindgen). On macOS, brew install llvm and set LIBCLANG_PATH=$(brew --prefix llvm)/lib if it is not found automatically.

  • The toywasm sources, checked out as a git submodule:

    git submodule update --init --recursive
    

The C sources are compiled with NDEBUG by default (matching toywasm's default Release build and enabling all feature combinations to compile). Set TOYWASM_C_ASSERTS=1 to keep the C assertions enabled.

Features

Every compile-time toggle from toywasm's cmake/ToywasmConfig.cmake is exposed as a Cargo feature on toywasmx-sys (and re-exported 1:1 by toywasmx). The default feature set mirrors toywasm's own upstream defaults: WASI, SIMD and the name section on; the performance toggles (small cells, tail-call optimization, cell-index tables, …) on; and the not-yet-default Wasm proposals off.

Because Cargo features are additive, toggles that are on upstream live in default. For a minimal build, use --no-default-features and re-add what you need. Numeric knobs use build-time environment variables: TOYWASM_JUMP_CACHE2_SIZE and TOYWASM_EXCEPTION_MAX_CELLS (both default 4).

Selected proposal features: simd, tail-call, multi-memory, extended-const, exception-handling, custom-page-sizes, threads; WASI-related: wasi, wasi-threads, wasi-littlefs, dyld.

Caveat: a few upstream toggle combinations do not compile in toywasm itself. In particular, disabling writer fails to build (module.c's module_print_stats uses a variable guarded by TOYWASM_ENABLE_WRITER), so writer is kept in default. The default set and additive proposal combinations are the supported configurations.

Design notes

toywasm's C API differs from Wasmtime/Wasmi in a few places; the wrapper follows toywasm's invariants on a best-effort basis:

  • A Store owns toywasm's mem_context. It must outlive every module and instance created from it, so Module and Instance share it via Rc and it is cleared only once the last of them is dropped.
  • Module owns its input bytes, because module_create keeps pointers into them, and is created within a Store (toywasm ties modules to a memory context).
  • Host functions: toywasm's callback receives its host_instance but no function index, so each registered function gets its own host_instance wrapper carrying its slot, exposed through a per-function import_object chained via import_object.next. A single trampoline recovers the slot.

License

toywasmx and toywasmx-sys are licensed under either of Apache-2.0 or MIT at your option. The vendored toywasm submodule is distributed under its own license (see crates/toywasmx-sys/toywasm/LICENSE).