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 --- 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 ++++++++ 6 files changed, 196 insertions(+), 169 deletions(-) create mode 100644 examples/state.rs (limited to 'examples') diff --git a/examples/doom/Cargo.toml b/examples/doom/Cargo.toml index abec73d..c096db6 100644 --- a/examples/doom/Cargo.toml +++ b/examples/doom/Cargo.toml @@ -14,6 +14,7 @@ softbuffer = "0.4" tinywasm = { path = "../../crates/tinywasm", features = [ "archive", "canonicalize-nans", + "state", "debug", "log", "parallel-parser", diff --git a/examples/doom/src/main.rs b/examples/doom/src/main.rs index c5e49b5..a8e98ef 100644 --- a/examples/doom/src/main.rs +++ b/examples/doom/src/main.rs @@ -129,7 +129,7 @@ impl ApplicationHandler for DoomApp { window.request_redraw(); } - if self.runtime.host_state.lock().unwrap().exit_code.is_some() { + if self.runtime.exited() { event_loop.exit(); } } diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs index 2ad02ae..745e3bd 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -2,7 +2,6 @@ use std::collections::BTreeMap; use std::fs::{File, OpenOptions, create_dir_all}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::Result; @@ -20,15 +19,13 @@ pub struct Runtime { key_up: tinywasm::FunctionTyped, memory: tinywasm::Memory, framebuffer_bytes: Vec, - pub host_state: Arc>, } impl Runtime { pub fn new(wad_path: PathBuf, guest_path: PathBuf) -> Result { let module = tinywasm::parse_file(&guest_path)?; - let mut store = Store::default(); - let host_state = Arc::new(Mutex::new(HostState::new(wad_path))); - let imports = build_imports(host_state.clone()); + let mut store = Store::default().with_state(HostState::new(wad_path)); + let imports = build_imports(); let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let wad_path_buf = instance.func::<(), i32>(&store, "tinywasm_doom_wad_path_buf")?; @@ -40,7 +37,7 @@ impl Runtime { let memory = instance.memory("memory")?; let buf_ptr = wad_path_buf.call(&mut store, ())? as usize; - let wad_path_string = host_state.lock().unwrap().wad_path.to_string_lossy().into_owned(); + let wad_path_string = store.state::().unwrap().wad_path.to_string_lossy().into_owned(); memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?; init.call(&mut store, ())?; @@ -55,7 +52,6 @@ impl Runtime { key_up, memory, framebuffer_bytes: vec![0; width * height * 4], - host_state, }) } @@ -84,15 +80,19 @@ impl Runtime { self.key_up.call(&mut self.store, key)?; Ok(()) } + + pub fn exited(&self) -> bool { + self.store.state::().unwrap().exit_code.is_some() + } } pub struct HostState { - pub wad_path: PathBuf, + wad_path: PathBuf, runtime_dir: PathBuf, start: Instant, files: BTreeMap, next_file: i32, - pub exit_code: Option, + exit_code: Option, } impl HostState { @@ -160,183 +160,158 @@ impl HostState { } } -fn build_imports(state: Arc>) -> Imports { +fn build_imports() -> Imports { let mut imports = Imports::new(); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_open", - HostFunction::from(move |ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| { - let memory = ctx.memory("memory")?; - let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?; - let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?; - let filename = filename.to_string_lossy(); - let mode = mode.to_string_lossy(); - let mut state = state.lock().unwrap(); - let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) { - state.wad_path.clone() - } else { - state.resolve_path(&filename) - }; + imports.define( + IMPORT_MODULE, + "host_open", + HostFunction::from(|mut ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| { + let memory = ctx.memory("memory")?; + let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?; + let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?; + let filename = filename.to_string_lossy(); + let mode = mode.to_string_lossy(); + let state = ctx.state_mut::().unwrap(); + let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) { + state.wad_path.clone() + } else { + state.resolve_path(&filename) + }; + + if path.is_dir() { + log::debug!("guest open rejected directory: path={} mode={}", path.display(), mode); + return Ok(-1); + } - if path.is_dir() { - log::debug!("guest open rejected directory: path={} mode={}", path.display(), mode); + let file = match HostState::open_mode_options(&mode).open(&path) { + Ok(file) => file, + Err(err) => { + log::debug!("guest open failed: path={} mode={} err={err}", path.display(), mode); return Ok(-1); } + }; - let file = match HostState::open_mode_options(&mode).open(&path) { - Ok(file) => file, - Err(err) => { - log::debug!("guest open failed: path={} mode={} err={err}", path.display(), mode); - return Ok(-1); - } - }; - - let handle = state.next_file; - state.next_file += 1; - state.files.insert(handle, file); - Ok(handle) - }), - ); - } + let handle = state.next_file; + state.next_file += 1; + state.files.insert(handle, file); + Ok(handle) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_close", - HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - state.lock().unwrap().files.remove(&handle); - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_close", + HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| { + ctx.state_mut::().unwrap().files.remove(&handle); + Ok(()) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_read", - HostFunction::from(move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { - let mut state = state.lock().unwrap(); + imports.define( + IMPORT_MODULE, + "host_read", + HostFunction::from(|mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + let mut buffer = vec![0; count.max(0) as usize]; + let read = { + let state = ctx.state_mut::().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(0); }; - let mut buffer = vec![0; count.max(0) as usize]; - let read = file.read(&mut buffer).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - ctx.memory("memory")?.copy_from_slice(ctx.store_mut(), buf_ptr as usize, &buffer[..read])?; - Ok(read as i32) - }), - ); - } + file.read(&mut buffer).map_err(|err| tinywasm::Error::Other(err.to_string()))? + }; + ctx.memory("memory")?.copy_from_slice(ctx.store_mut(), buf_ptr as usize, &buffer[..read])?; + Ok(read as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_write", - HostFunction::from(move |ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { - let data = ctx.memory("memory")?.read_vec(ctx.store(), buf_ptr as usize, count.max(0) as usize)?; - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(-1); - }; - let written = file.write(&data).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - Ok(written as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_write", + HostFunction::from(|mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + let data = ctx.memory("memory")?.read_vec(ctx.store(), buf_ptr as usize, count.max(0) as usize)?; + let state = ctx.state_mut::().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(-1); + }; + let written = file.write(&data).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + Ok(written as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_seek", - HostFunction::from(move |_ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| { - let seek_from = match origin { - 0 => SeekFrom::Start(offset.max(0) as u64), - 1 => SeekFrom::Current(offset as i64), - 2 => SeekFrom::End(offset as i64), - _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))), - }; - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(-1); - }; - let pos = file.seek(seek_from).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - Ok(pos.min(i32::MAX as u64) as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_seek", + HostFunction::from(|mut ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| { + let seek_from = match origin { + 0 => SeekFrom::Start(offset.max(0) as u64), + 1 => SeekFrom::Current(offset as i64), + 2 => SeekFrom::End(offset as i64), + _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))), + }; + let state = ctx.state_mut::().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(-1); + }; + let pos = file.seek(seek_from).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + Ok(pos.min(i32::MAX as u64) as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_tell", - HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(-1); - }; - let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; - Ok(pos.min(i32::MAX as u64) as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_tell", + HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| { + let state = ctx.state_mut::().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(-1); + }; + let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; + Ok(pos.min(i32::MAX as u64) as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_eof", - HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.lock().unwrap(); - let Some(file) = state.files.get_mut(&handle) else { - return Ok(1); - }; - let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; - let len = file.metadata().map_err(|err| tinywasm::Error::Other(err.to_string()))?.len(); - Ok((pos >= len) as i32) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_eof", + HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| { + let state = ctx.state_mut::().unwrap(); + let Some(file) = state.files.get_mut(&handle) else { + return Ok(1); + }; + let pos = file.stream_position().map_err(|err| tinywasm::Error::Other(err.to_string()))?; + let len = file.metadata().map_err(|err| tinywasm::Error::Other(err.to_string()))?.len(); + Ok((pos >= len) as i32) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_gettime", - HostFunction::from(move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { - let elapsed = state.lock().unwrap().start.elapsed() + Duration::from_secs(1); - let sec = elapsed.as_secs().min(i32::MAX as u64) as i32; - let usec = elapsed.subsec_micros() as i32; - let memory = ctx.memory("memory")?; - memory.copy_from_slice(ctx.store_mut(), sec_ptr as usize, &sec.to_le_bytes())?; - memory.copy_from_slice(ctx.store_mut(), usec_ptr as usize, &usec.to_le_bytes())?; - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_gettime", + HostFunction::from(|mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { + let elapsed = ctx.state::().unwrap().start.elapsed() + Duration::from_secs(1); + let sec = elapsed.as_secs().min(i32::MAX as u64) as i32; + let usec = elapsed.subsec_micros() as i32; + let memory = ctx.memory("memory")?; + memory.copy_from_slice(ctx.store_mut(), sec_ptr as usize, &sec.to_le_bytes())?; + memory.copy_from_slice(ctx.store_mut(), usec_ptr as usize, &usec.to_le_bytes())?; + Ok(()) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_exit", - HostFunction::from(move |_ctx: FuncContext<'_>, code: i32| { - state.lock().unwrap().exit_code = Some(code); - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_exit", + HostFunction::from(|mut ctx: FuncContext<'_>, code: i32| { + ctx.state_mut::().unwrap().exit_code = Some(code); + Ok(()) + }), + ); imports.define( IMPORT_MODULE, "host_print", - HostFunction::from(move |ctx: FuncContext<'_>, ptr: i32| { + HostFunction::from(|ctx: FuncContext<'_>, ptr: i32| { let text = ctx.memory("memory")?.read_cstring_until_null(ctx.store(), ptr as usize, 4096)?; log::info!("guest: {}", text.to_string_lossy()); Ok(()) diff --git a/examples/rust.rs b/examples/rust.rs index 77ba428..58fd11e 100644 --- a/examples/rust.rs +++ b/examples/rust.rs @@ -87,7 +87,7 @@ fn tinywasm() -> Result<()> { } fn tinywasm_no_std() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?; + let module = tinywasm::parse_file("./examples/rust/out/tinywasm-no-std.wasm")?; let mut store = Store::default(); let mut imports = Imports::new(); diff --git a/examples/rust/build.sh b/examples/rust/build.sh index aa60d33..e19b8b8 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -18,8 +18,8 @@ cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \ # 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 -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 +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 for bin in "${bins[@]}"; do RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=std,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin "$bin" diff --git a/examples/state.rs b/examples/state.rs new file mode 100644 index 0000000..ecc74fd --- /dev/null +++ b/examples/state.rs @@ -0,0 +1,51 @@ +use anyhow::Result; +use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; + +const WASM: &str = r#" +(module + (import "host" "record" (func $record (param i32) (result i32))) + + (func (export "run") (result i32) + i32.const 20 + call $record + drop + i32.const 22 + call $record)) +"#; + +#[derive(Default)] +struct State { + calls: u32, + total: i32, +} + +// Requires the `parser`, `std`, and `state` features. +// Run with `cargo run --example state` from the repository root. +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + + // State is owned by the Store and is available to its host-function calls. + let mut store = Store::default().with_state(State::default()); + + let record = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| { + // FuncContext accesses the active Store without captured shared state. + let state = ctx.state_mut::().expect("State was added to the store"); + state.calls += 1; + state.total += value; + Ok(state.total) + }); + + // The import definition captures no state and can be reused with other stores. + let mut imports = Imports::new(); + imports.define("host", "record", record); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let run = instance.func::<(), i32>(&store, "run")?; + + assert_eq!(run.call(&mut store, ())?, 42); + + // Host code can inspect the same state after guest execution. + assert_eq!(store.state::().unwrap().calls, 2); + Ok(()) +} -- cgit v1.3.1