From 7b9b3ec681e68280399d9c67e01433c2d3acb6c2 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Mon, 24 Aug 2026 15:47:05 +0200 Subject: feat: add host typed reference / gc APIs (#54) - add Store-aware handles for references, GC objects, and exceptions - simplify host value conversion, rooting, and exception propagation - update examples, tests, and documentation - Remove deprecated APIs Signed-off-by: Henry --- examples/rust.rs | 226 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 226 insertions(+) create mode 100644 examples/rust.rs (limited to 'examples/rust.rs') diff --git a/examples/rust.rs b/examples/rust.rs new file mode 100644 index 0000000..24b3b73 --- /dev/null +++ b/examples/rust.rs @@ -0,0 +1,226 @@ +use std::hint::black_box; + +use anyhow::{Result, anyhow}; +use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; + +/// Examples of using WebAssembly compiled from Rust with tinywasm. +/// +/// These examples are meant to be run with `cargo run --example rust `. +/// For example, `cargo run --example rust hello`. +/// +/// To run these, you first need to compile the Rust examples to WebAssembly: +/// +/// ```sh +/// ./examples/rust/build.sh +/// ``` +/// +/// This requires the `wasm32-unknown-unknown` target, `binaryen`, and `wabt` to be installed: +/// +/// `rustup target add wasm32-unknown-unknown`. +/// +/// +fn main() -> Result<()> { + pretty_env_logger::init(); + + if !std::path::Path::new("./examples/rust/out/").exists() { + return Err(anyhow!("No WebAssembly files found. See examples/rust.rs for instructions.")); + } + + let args = std::env::args().collect::>(); + if args.len() < 2 { + println!("Usage: cargo run --example rust "); + println!("Available examples:"); + println!(" hello"); + println!(" printi32"); + println!(" host_fn"); + println!(" fibonacci - calculate fibonacci(30)"); + println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); + println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); + println!(" argon2id - run argon2id(1000, 2, 1)"); + return Ok(()); + } + + match args[1].as_str() { + "hello" => hello()?, + "printi32" => printi32()?, + "fibonacci" => fibonacci()?, + "tinywasm" => tinywasm()?, + "tinywasm_no_std" => tinywasm_no_std()?, + "argon2id" => argon2id()?, + "host_fn" => host_fn()?, + "all" => { + println!("Running all examples"); + println!("\nhello.wasm:"); + hello()?; + println!("\nprinti32.wasm:"); + printi32()?; + println!("\nfibonacci.wasm:"); + fibonacci()?; + println!("\ntinywasm.wasm:"); + tinywasm()?; + println!("\ntinywasm_no_std.wasm:"); + tinywasm_no_std()?; + println!("argon2id.wasm:"); + argon2id()?; + println!("\nhost_fn.wasm:"); + host_fn()?; + } + _ => {} + } + + Ok(()) +} + +fn tinywasm() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm.opt.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; + + let hello = instance.func::<(), ()>(&store, "hello")?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + Ok(()) +} + +fn tinywasm_no_std() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; + + let hello = instance.func::<(), ()>(&store, "hello")?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + Ok(()) +} + +fn hello() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; + let mut store = Store::default(); + + // The host callback reads the guest's exported memory through FuncContext. + let print_utf8 = HostFunction::from(|ctx: FuncContext<'_>, (ptr, len): (i64, i32)| { + let mem = ctx.memory("memory")?; + let string = mem.read_string(ctx.store(), ptr as usize, len as usize)?; + println!("{string}"); + Ok(()) + }); + + let mut imports = Imports::new(); + imports.define("env", "print_utf8", print_utf8); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let arg_ptr = instance.func::<(), i32>(&store, "arg_ptr")?.call(&mut store, ())?; + let arg = b"world"; + + // Write the host argument into guest memory before calling the Rust export. + instance.memory("memory")?.copy_from_slice(&mut store, arg_ptr as usize, arg)?; + let hello = instance.func::(&store, "hello")?; + hello.call(&mut store, arg.len() as i32)?; + + Ok(()) +} + +fn host_fn() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/host_fn.opt.wasm")?; + let mut store = Store::default(); + + let bar = HostFunction::from(|_: FuncContext<'_>, (left, right): (i64, i32)| { + assert_eq!(left, 1); + assert_eq!(right, 2); + Ok(left as i32 + right) + }); + + let mut imports = Imports::new(); + imports.define("env", "bar", bar); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let host_fn = instance.func::<(), i32>(&store, "foo")?; + assert_eq!(host_fn.call(&mut store, ())?, 3); + Ok(()) +} + +fn printi32() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/print.opt.wasm")?; + let mut store = Store::default(); + + let printi32 = HostFunction::from(|_: FuncContext<'_>, x: i32| { + println!("{x}"); + Ok(()) + }); + + let mut imports = Imports::new(); + imports.define("env", "printi32", printi32); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; + add_and_print.call(&mut store, (1, 2))?; + + Ok(()) +} + +fn fibonacci() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/fibonacci.opt.wasm")?; + let mut store = Store::default(); + + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let fibonacci = instance.func::(&store, "fibonacci_recursive")?; + let n = 26; + let result = fibonacci.call(&mut store, n)?; + println!("fibonacci({n}) = {result}"); + + Ok(()) +} + +fn argon2id() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/argon2id.opt.wasm")?; + let mut store = Store::default(); + + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let argon2id = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; + argon2id.call(&mut store, (1000, 2, 1))?; + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hello() { + hello().unwrap(); + } + + #[test] + fn test_printi32() { + printi32().unwrap(); + } + + #[test] + fn test_fibonacci() { + fibonacci().unwrap(); + } + + #[test] + fn test_tinywasm() { + tinywasm().unwrap(); + } + + #[test] + fn test_tinywasm_no_std() { + tinywasm_no_std().unwrap(); + } + + #[test] + fn test_argon2id() { + argon2id().unwrap(); + } +} -- cgit v1.3.1 From 70b4ca7b8effb5b8f61c7a43ea15a77af0db0103 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 14 Sep 2026 11:14:37 +0200 Subject: chore: update changelog, fix clippy issues Signed-off-by: Henry --- CHANGELOG.md | 64 +++++++++++++++++++++++++++--------------- crates/tinywasm/Cargo.toml | 2 +- crates/types/src/archive.rs | 4 +-- examples/rust.rs | 14 ++++----- examples/rust/Cargo.toml | 4 +-- examples/rust/build.sh | 4 +-- examples/rust/src/print.twasm | Bin 155 -> 155 bytes 7 files changed, 55 insertions(+), 37 deletions(-) (limited to 'examples/rust.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index d674c30..a37655e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,23 +7,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +This release adds garbage collection and typed function reference support, single-pass parsing, and an optional tail-call dispatch backend. The internal instruction representation is now 8 bytes, down from 16, and pluggable memory backends were removed for performance reasons (however, `ResourceLimiter` was added to allow, reject, or trap memory allocation and growth requests). + +### Breaking Changes + +#### Functions and references + +- `Function::call` and `Function::call_resumable` now write to caller-provided result slices. Untyped host callbacks also receive a result slice and return `Result<()>`. +- Creating a `HostFunction` no longer requires a `Store`. Definitions require `Send + Sync` and can be reused across stores. +- Module instantiation now borrows `Imports`, allowing the same imports to be reused. +- `HostFunction::ty` and `WasmFunction::ty` were removed. Use `Function::ty(&Store)` for runtime types. +- Function and managed reference handles are tied to their originating `Store`. Managed references keep their referents live, so `WasmValue` is no longer `Copy`. +- Nullable typed references use `Option`, while bare typed references are non-null. +- `WasmTupleChain` was removed. Use direct tuples up to arity 20 or untyped functions for larger signatures. +- `ToWasmTypes` was renamed to `WasmTypes`, and `ToWasmType` was renamed to `WasmValueType`. +- Conversion traits now include `WasmTypes`, and `FromWasmValues::from_wasm_values` rejects unconsumed values directly. + +#### Memory, tables, and stores + +- Pluggable memory backends and `Config::with_trap_on_oom` were removed for performance reasons. Linear memory is always `Vec`-backed. Use `ResourceLimiter` to allow, reject, or trap memory allocation and growth requests. +- The `Memory`, `Table`, `Global`, and `Tag` constructors were renamed from `new` to `try_new`. +- Element types now use `RefType`, and module definitions use `TableDefinition { ty, init }`. +- `Table::grow` now returns `Result>`, matching `Memory::grow`. +- `Store::id` now returns `u32`, and `ModuleInstanceAddr` was renamed to `ModuleInstanceId`. + +#### Parser and archives + +- `Parser::new` now takes `ParserOptions`. Use `Parser::default()` for default settings. +- `Parser::with_options` was removed. +- `ParserOptions::optimize_rewrite` was renamed to `ParserOptions::optimize`. +- `ParserOptions::parser_threads` was renamed to `ParserOptions::threads`. +- The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions. + ### Added - Support for the typed function references, garbage collection, exception handling, and compact import section proposals. -- `ResourceLimiter` callbacks for memory and table allocation or growth -- A default `validate` Cargo feature & parser option to skip wasm validation -- Optional parse-time operand deduplication to reduce `.twasm` archive size -- Optional `send` support for moving stores and store-local handles across threads -- Optional portable atomic shared pointers and counters for targets without native compare-and-swap -- Optional `nightly-tail-calls` backend using Rust's unstable explicit tail calls for interpreter dispatch +- `ResourceLimiter` callbacks for memory and table allocation or growth. +- A default-enabled `validate` Cargo feature and a parser option to skip WebAssembly validation. +- Optional parse-time operand deduplication to reduce `.twasm` archive size. +- Optional `send` support for moving stores and store-local handles across threads. +- Optional portable atomic shared pointers and counters for targets without native compare-and-swap. +- Optional `nightly-tail-calls` backend using Rust's unstable explicit tail calls for interpreter dispatch. ### Changed +- Parsing now uses a single pass. - Typed functions now support tuples up to arity 20 and `[u8; 16]` values for `v128`. -- Module types now use one recursive type space. Runtime function types are available through `Function::ty(&Store)`. +- Module types now use one recursive type space. - Linear memory now uses contiguous `Vec`-backed storage. +- The internal instruction representation was reduced from 16 to 8 bytes. - The minimum supported Rust version increased from 1.95 to 1.98. -- The internal instruction represetaions size was reduced from 16 to 8 bytes. ### Fixed @@ -33,21 +66,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `memory.init` now performs correct bounds checks and operand lowering. - Memory64 now uses the correct default limits and host-size conversions, including on 32-bit targets. -### Breaking Changes - -- `Function::call` and `Function::call_resumable` now write to caller-provided result slices. Untyped host callbacks also receive a result slice and return `Result<()>`. -- Creating a `HostFunction` no longer requires a `Store`. Definitions require `Send + Sync` and can be reused across stores. Module instantiation now borrows `Imports` so the same imports can also be reused. -- `HostFunction::ty` and `WasmFunction::ty` were removed. Use `Function::ty(&Store)` for runtime types. -- Function and managed reference handles are tied to their originating `Store`. Managed references keep their referents live, so `WasmValue` is no longer `Copy`. Nullable typed references use `Option`, while bare typed references are non-null. -- The `Memory`, `Table`, `Global`, and `Tag` constructors were renamed from `new` to `try_new`. -- `Store::id` now returns `u32`, and `ModuleInstanceAddr` was renamed to `ModuleInstanceId`. -- Element types now use `RefType`, and module definitions use `TableDefinition { ty, init }`. `Table::grow` now returns `Result>`, matching `Memory::grow`. -- `Parser::new` now takes `ParserOptions`. Use `Parser::default()` for default settings. `Parser::with_options` was removed. -- Pluggable memory backends and `Config::with_trap_on_oom` were removed for performance reasons. Linear memory is always `Vec`-backed. Use `ResourceLimiter` to allow, reject, or trap memory allocation and growth requests. -- `WasmTupleChain` was removed. Use direct tuples up to arity 20 or untyped functions for larger signatures. -- `ToWasmTypes` was renamed to `WasmTypes`, and `ToWasmType` was renamed to `WasmValueType`. Conversion traits now include `WasmTypes`, and `FromWasmValues::from_wasm_values` rejects unconsumed values directly. -- The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions. - ## [0.10.0] - 2026-07-24 **All Commits**: https://github.com/explodingcamera/tinywasm/compare/v0.9.1...v0.10.0 diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 15744a3..d59d3dd 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -90,7 +90,7 @@ wat.workspace = true [features] default = ["full", "std"] -full = ["archive", "parallel-parser", "parser", "validate"] +full = ["archive", "debug", "parallel-parser", "parser", "validate"] log = ["dep:log", "tinywasm-parser?/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index bdce379..6a03605 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -7,7 +7,7 @@ use crate::Module; #[rustfmt::skip] const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS"; -const TWASM_VERSION: &[u8; 2] = b"06"; +const TWASM_VERSION: &[u8; 2] = b"05"; fn validate_magic(wasm: &[u8]) -> Result { if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX { @@ -97,7 +97,7 @@ mod tests { let module = Module::from(ModuleInner { funcs: Box::new([Shared::new(function)]), ..ModuleInner::default() }); let archive = module.serialize_twasm().expect("serialize archive"); - assert_eq!(&archive[..6], b"TWAS06"); + assert_eq!(&archive[..6], b"TWAS05"); let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); let function = &decoded.funcs[0]; diff --git a/examples/rust.rs b/examples/rust.rs index 24b3b73..77ba428 100644 --- a/examples/rust.rs +++ b/examples/rust.rs @@ -32,10 +32,10 @@ fn main() -> Result<()> { println!("Available examples:"); println!(" hello"); println!(" printi32"); - println!(" host_fn"); + println!(" host-fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); - println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); + println!(" tinywasm-no-std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); } @@ -45,9 +45,9 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, - "tinywasm_no_std" => tinywasm_no_std()?, + "tinywasm-no-std" => tinywasm_no_std()?, "argon2id" => argon2id()?, - "host_fn" => host_fn()?, + "host-fn" => host_fn()?, "all" => { println!("Running all examples"); println!("\nhello.wasm:"); @@ -58,11 +58,11 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; - println!("\ntinywasm_no_std.wasm:"); + println!("\ntinywasm-no-std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); argon2id()?; - println!("\nhost_fn.wasm:"); + println!("\nhost-fn.wasm:"); host_fn()?; } _ => {} @@ -129,7 +129,7 @@ fn hello() -> Result<()> { } fn host_fn() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/host_fn.opt.wasm")?; + let module = tinywasm::parse_file("./examples/rust/out/host-fn.opt.wasm")?; let mut store = Store::default(); let bar = HostFunction::from(|_: FuncContext<'_>, (left, right): (i64, i32)| { diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index e0bdba6..74d38e7 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -11,7 +11,7 @@ name = "hello" path = "src/hello.rs" [[bin]] -name = "host_fn" +name = "host-fn" path = "src/host_fn.rs" [[bin]] @@ -23,7 +23,7 @@ name = "tinywasm" path = "src/tinywasm.rs" [[bin]] -name = "tinywasm_no_std" +name = "tinywasm-no-std" path = "src/tinywasm_no_std.rs" [[bin]] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index 873028f..aa60d33 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") +bins=("host-fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") exclude_wat=("tinywasm") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" @@ -17,7 +17,7 @@ cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \ compile "src/print.wasm" --output "src/print.twasm" --force || exit # build no_std -RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features +RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm-no-std --no-default-features cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" wasm-opt "$dest_dir/tinywasm_no_std.wasm" -o "$dest_dir/tinywasm_no_std.opt.wasm" -O3 $wasmopt_features diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm index 967eda1..8ad32e3 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ -- cgit v1.3.1 From 741955aed21c814a0805386a4f9be997c2eb1199 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 14 Sep 2026 12:05:52 +0200 Subject: feat: add custom store state Signed-off-by: Henry --- CHANGELOG.md | 1 + README.md | 1 + crates/tinywasm/Cargo.toml | 7 +- crates/tinywasm/src/store/mod.rs | 63 ++++++++ crates/tinywasm/tests/store_state.rs | 36 +++++ examples/doom/Cargo.toml | 1 + examples/doom/src/main.rs | 2 +- examples/doom/src/runtime.rs | 305 ++++++++++++++++------------------- examples/rust.rs | 2 +- examples/rust/build.sh | 4 +- examples/state.rs | 51 ++++++ 11 files changed, 302 insertions(+), 171 deletions(-) create mode 100644 crates/tinywasm/tests/store_state.rs create mode 100644 examples/state.rs (limited to 'examples/rust.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index a37655e..dc59e5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ This release adds garbage collection and typed function reference support, singl ### Added +- Optional store-owned host state through `Store::with_state`, `Store::state`, and `Store::state_mut`. - Support for the typed function references, garbage collection, exception handling, and compact import section proposals. - `ResourceLimiter` callbacks for memory and table allocation or growth. - A default-enabled `validate` Cargo feature and a parser option to skip WebAssembly validation. diff --git a/README.md b/README.md index 383b007..eca0d97 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. - **`log`:** Enables integration with the `log` crate. Enabled by default. - **`send`:** Makes stores and store-local handles movable across threads. +- **`state`:** Adds store-owned host state for access from host callbacks. - **`portable-atomic`:** Supports targets without native atomic compare-and-swap. - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. - **`debug`:** Derives `Debug` for runtime types. Enabled by default. diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index d59d3dd..15b151c 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -11,7 +11,7 @@ keywords.workspace = true categories.workspace = true [package.metadata.docs.rs] -features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "debug", "guest-debug"] +features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "state", "debug", "guest-debug"] rustdoc-args = ["--cfg", "docsrs"] [lib] @@ -90,7 +90,7 @@ wat.workspace = true [features] default = ["full", "std"] -full = ["archive", "debug", "parallel-parser", "parser", "validate"] +full = ["archive", "debug", "parallel-parser", "parser", "state", "validate"] log = ["dep:log", "tinywasm-parser?/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] @@ -98,6 +98,9 @@ std = ["tinywasm-parser?/std", "tinywasm-types/std"] # make stores, instances, references, and host callbacks movable across threads send = [] +# store host state for access from host callbacks +state = [] + # support for parsing WebAssembly parser = ["dep:tinywasm-parser"] diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index e157240..ed9b4f0 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,4 +1,8 @@ +#[cfg(feature = "state")] +use alloc::collections::BTreeMap; use alloc::{boxed::Box, format, vec::Vec}; +#[cfg(feature = "state")] +use core::any::{Any, TypeId}; use core::hint::cold_path; use tinywasm_types::*; @@ -110,6 +114,25 @@ pub trait ResourceLimiter: Send + Sync { } } +/// A value stored as host state. +#[doc(hidden)] +#[cfg(all(feature = "state", not(feature = "send")))] +pub trait StoreState: Any {} +#[cfg(all(feature = "state", not(feature = "send")))] +impl StoreState for T {} + +/// A value stored as host state. +#[doc(hidden)] +#[cfg(all(feature = "state", feature = "send"))] +pub trait StoreState: Any + Send {} +#[cfg(all(feature = "state", feature = "send"))] +impl StoreState for T {} + +#[cfg(all(feature = "state", not(feature = "send")))] +type StoredState = dyn Any; +#[cfg(all(feature = "state", feature = "send"))] +type StoredState = dyn Any + Send; + /// Runtime state used by WebAssembly instances and host functions. /// /// ## Example @@ -133,6 +156,8 @@ pub struct Store { pub(crate) call_stack: CallStack, pub(crate) value_stack: ValueStack, value_scratch: ValueScratch, + #[cfg(feature = "state")] + host_state: BTreeMap>, } #[derive(Default)] @@ -238,9 +263,47 @@ impl Store { engine, execution_fuel: 0, execution_active: false, + #[cfg(feature = "state")] + host_state: BTreeMap::new(), } } + /// Adds host state to this store. + /// + /// Host callbacks can access the value through [`Store::state`] and + /// [`Store::state_mut`]. If state of the same type already exists, this + /// method replaces it. + /// + /// # Example + /// + /// ```rust + /// use tinywasm::Store; + /// + /// struct AppState { + /// requests: usize, + /// } + /// + /// let store = Store::default().with_state(AppState { requests: 0 }); + /// assert_eq!(store.state::().unwrap().requests, 0); + /// ``` + #[cfg(feature = "state")] + pub fn with_state(mut self, state: T) -> Self { + self.host_state.insert(TypeId::of::(), Box::new(state)); + self + } + + /// Get host state. + #[cfg(feature = "state")] + pub fn state(&self) -> Option<&T> { + self.host_state.get(&TypeId::of::()).and_then(|state| state.downcast_ref()) + } + + /// Get mutable access to host state. + #[cfg(feature = "state")] + pub fn state_mut(&mut self) -> Option<&mut T> { + self.host_state.get_mut(&TypeId::of::()).and_then(|state| state.downcast_mut()) + } + pub(crate) const fn id(&self) -> StoreId { self.id } diff --git a/crates/tinywasm/tests/store_state.rs b/crates/tinywasm/tests/store_state.rs new file mode 100644 index 0000000..573c250 --- /dev/null +++ b/crates/tinywasm/tests/store_state.rs @@ -0,0 +1,36 @@ +#![cfg(feature = "state")] + +use tinywasm::types::WasmValue; +use tinywasm::{HostFunction, Store}; + +struct Counter(i32); +struct Label(&'static str); + +#[test] +fn stores_state_by_type() { + let mut store = Store::default().with_state(Counter(1)).with_state(Label("first")).with_state(Counter(2)); + + assert_eq!(store.state::().unwrap().0, 2); + assert_eq!(store.state::