diff options
| author | Mica White <botahamec@outlook.com> | 2026-10-31 11:10:49 -0400 |
|---|---|---|
| committer | Mica White <botahamec@outlook.com> | 2026-10-31 11:10:49 -0400 |
| commit | 264ea48cc8c6dd9c3c9e0fe1a559252863fc9962 (patch) | |
| tree | 84a4a58de14442f4fcfa06bd0d82480508f82759 /examples | |
| parent | 7877eca4e8be283e7c51168ee3a3b05d9000f39c (diff) | |
| parent | b45a98a85c776d956a797773acd2f198c06b40ed (diff) | |
Merge branch 'main' into bota-tortuise
Diffstat (limited to 'examples')
| -rw-r--r-- | examples/archive.rs | 10 | ||||
| -rw-r--r-- | examples/basic.rs (renamed from examples/simple.rs) | 8 | ||||
| -rw-r--r-- | examples/doom/Cargo.toml | 3 | ||||
| -rw-r--r-- | examples/doom/src/main.rs | 10 | ||||
| -rw-r--r-- | examples/doom/src/runtime.rs | 346 | ||||
| -rw-r--r-- | examples/exceptions.rs | 28 | ||||
| -rw-r--r-- | examples/funcref_callbacks.rs | 124 | ||||
| -rw-r--r-- | examples/gc.rs | 33 | ||||
| -rw-r--r-- | examples/linking.rs | 16 | ||||
| -rw-r--r-- | examples/reentrance.rs | 11 | ||||
| -rw-r--r-- | examples/references.rs | 34 | ||||
| -rw-r--r-- | examples/resumable.rs | 4 | ||||
| -rw-r--r-- | examples/rust.rs (renamed from examples/wasm-rust.rs) | 47 | ||||
| -rw-r--r-- | examples/rust/Cargo.toml | 16 | ||||
| -rw-r--r-- | examples/rust/README.md | 4 | ||||
| -rwxr-xr-x | examples/rust/build.sh | 11 | ||||
| -rw-r--r-- | examples/rust/src/hello.rs | 12 | ||||
| -rw-r--r-- | examples/rust/src/print.rs | 4 | ||||
| -rw-r--r-- | examples/rust/src/print.twasm | bin | 0 -> 155 bytes | |||
| -rw-r--r-- | examples/rust/src/tinywasm.rs | 4 | ||||
| -rw-r--r-- | examples/rust/src/tinywasm_no_std.rs | 10 | ||||
| -rw-r--r-- | examples/simple2.rs | 21 | ||||
| -rw-r--r-- | examples/state.rs | 51 | ||||
| -rw-r--r-- | examples/wasi_p1.rs | 42 |
24 files changed, 439 insertions, 410 deletions
diff --git a/examples/archive.rs b/examples/archive.rs index 7a2ebab..3f118f2 100644 --- a/examples/archive.rs +++ b/examples/archive.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{Module, ModuleInstance, Store, parser::Parser}; const WASM: &str = r#" @@ -11,13 +11,13 @@ const WASM: &str = r#" "#; fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("Failed to parse WAT"); + let wasm = wat::parse_str(WASM)?; let module = Parser::default().parse_module_bytes(wasm)?; - let twasm = module.serialize_twasm()?; - // Now, you could e.g. write `twasm` to a file called `add.twasm` - // and load it later in a different program. + // Serialize the optimized module for storage or distribution. + let twasm = module.serialize_twasm()?; + // Archived modules load without parsing Wasm again and should only come from trusted sources. let module = Module::try_from_twasm(&twasm)?; let mut store = Store::default(); let instance = ModuleInstance::instantiate(&mut store, &module, None)?; diff --git a/examples/simple.rs b/examples/basic.rs index a902b4c..1f717c5 100644 --- a/examples/simple.rs +++ b/examples/basic.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; const WASM: &str = r#" @@ -11,10 +11,14 @@ const WASM: &str = r#" "#; fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); + let wasm = wat::parse_str(WASM)?; let module = tinywasm::parse_bytes(&wasm)?; + + // Module is reusable, while Store owns the runtime state for this instance. let mut store = Store::default(); let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + // Typed handles validate parameters and results. Use func_untyped for dynamic values. let add = instance.func::<(i32, i32), i32>(&store, "add")?; assert_eq!(add.call(&mut store, (1, 2))?, 3); diff --git a/examples/doom/Cargo.toml b/examples/doom/Cargo.toml index 38e16c4..c096db6 100644 --- a/examples/doom/Cargo.toml +++ b/examples/doom/Cargo.toml @@ -7,13 +7,14 @@ publish = false [workspace] [dependencies] -eyre = "0.6" +anyhow = "1.0" log = "0.4" pretty_env_logger = "0.5" 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 095183d..a8e98ef 100644 --- a/examples/doom/src/main.rs +++ b/examples/doom/src/main.rs @@ -4,7 +4,7 @@ use std::num::NonZeroU32; use std::path::{Path, PathBuf}; use std::rc::Rc; -use eyre::{ContextCompat, Result, bail, eyre}; +use anyhow::{Context, Result, anyhow, bail}; use runtime::{Runtime, SCREEN_HEIGHT, SCREEN_WIDTH}; use softbuffer::{Context as SoftbufferContext, Surface}; use winit::application::ApplicationHandler; @@ -60,10 +60,10 @@ impl DoomApp { surface .resize(NonZeroU32::new(SCREEN_WIDTH as u32).unwrap(), NonZeroU32::new(SCREEN_HEIGHT as u32).unwrap()) - .map_err(|err| eyre!(err.to_string()))?; - let mut buffer = surface.buffer_mut().map_err(|err| eyre!(err.to_string()))?; + .map_err(|err| anyhow!(err.to_string()))?; + let mut buffer = surface.buffer_mut().map_err(|err| anyhow!(err.to_string()))?; self.runtime.write_framebuffer(&mut buffer)?; - buffer.present().map_err(|err| eyre!(err.to_string()))?; + buffer.present().map_err(|err| anyhow!(err.to_string()))?; Ok(()) } } @@ -129,7 +129,7 @@ impl ApplicationHandler for DoomApp { window.request_redraw(); } - if self.runtime.host_state.borrow().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 980dc21..2e50a20 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -1,12 +1,10 @@ -use std::cell::RefCell; 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::rc::Rc; -use std::time::Instant; +use std::time::{Duration, Instant}; -use eyre::Result; +use anyhow::{Context, Result}; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; const IMPORT_MODULE: &str = "env"; @@ -20,17 +18,14 @@ pub struct Runtime { key_down: tinywasm::FunctionTyped<i32, ()>, key_up: tinywasm::FunctionTyped<i32, ()>, memory: tinywasm::Memory, - framebuffer_bytes: Vec<u8>, - pub host_state: Rc<RefCell<HostState>>, } impl Runtime { pub fn new(wad_path: PathBuf, guest_path: PathBuf) -> Result<Self> { let module = tinywasm::parse_file(&guest_path)?; - let mut store = Store::default(); - let host_state = Rc::new(RefCell::new(HostState::new(wad_path))); - let imports = build_imports(&mut store, host_state.clone()); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + 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")?; let init = instance.func::<(), ()>(&store, "tinywasm_doom_init")?; @@ -41,23 +36,11 @@ impl Runtime { let memory = instance.memory("memory")?; let buf_ptr = wad_path_buf.call(&mut store, ())? as usize; - let wad_path_string = host_state.borrow().wad_path.to_string_lossy().into_owned(); + let wad_path_string = store.state::<HostState>().unwrap().wad_path.to_string_lossy().into_owned(); memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?; init.call(&mut store, ())?; - let width = SCREEN_WIDTH; - let height = SCREEN_HEIGHT; - - Ok(Self { - store, - update, - framebuffer, - key_down, - key_up, - memory, - framebuffer_bytes: vec![0; width * height * 4], - host_state, - }) + Ok(Self { store, update, framebuffer, key_down, key_up, memory }) } pub fn tick(&mut self) -> Result<()> { @@ -66,11 +49,15 @@ impl Runtime { } pub fn write_framebuffer(&mut self, dst: &mut [u32]) -> Result<()> { - let ptr = self.framebuffer.call(&mut self.store, ())? as usize; - self.memory.read_exact(&self.store, ptr, &mut self.framebuffer_bytes)?; - for (index, pixel) in dst.iter_mut().enumerate() { - let byte_index = index * 4; - let chunk = &self.framebuffer_bytes[byte_index..byte_index + 4]; + let ptr = self.framebuffer.call(&mut self.store, ())? as u32 as usize; + let framebuffer = self + .memory + .data(&self.store)? + .get(ptr..) + .and_then(|data| data.get(..SCREEN_WIDTH * SCREEN_HEIGHT * 4)) + .context("framebuffer is outside guest memory")?; + anyhow::ensure!(dst.len() <= SCREEN_WIDTH * SCREEN_HEIGHT, "framebuffer destination is too large"); + for (pixel, chunk) in dst.iter_mut().zip(framebuffer.chunks_exact(4)) { *pixel = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32; } Ok(()) @@ -85,15 +72,19 @@ impl Runtime { self.key_up.call(&mut self.store, key)?; Ok(()) } + + pub fn exited(&self) -> bool { + self.store.state::<HostState>().unwrap().exit_code.is_some() + } } pub struct HostState { - pub wad_path: PathBuf, + wad_path: PathBuf, runtime_dir: PathBuf, start: Instant, files: BTreeMap<i32, File>, next_file: i32, - pub exit_code: Option<i32>, + exit_code: Option<i32>, } impl HostState { @@ -161,183 +152,164 @@ impl HostState { } } -fn build_imports(store: &mut Store, state: Rc<RefCell<HostState>>) -> Imports { +fn build_imports() -> Imports { let mut imports = Imports::new(); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_open", - HostFunction::from(store, 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.borrow_mut(); - 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::<HostState>().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(store, move |_ctx: FuncContext<'_>, handle: i32| { - state.borrow_mut().files.remove(&handle); - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_close", + HostFunction::from(|mut ctx: FuncContext<'_>, handle: i32| { + ctx.state_mut::<HostState>().unwrap().files.remove(&handle); + Ok(()) + }), + ); - { - let state = state.clone(); - imports.define( - IMPORT_MODULE, - "host_read", - HostFunction::from(store, move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { - let mut state = state.borrow_mut(); + 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::<HostState>().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(store, 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.borrow_mut(); - 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(|ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + let data = ctx.memory("memory")?.data(ctx.store())?; + let offset = buf_ptr as u32 as usize; + let len = count.max(0) as usize; + let data = data + .get(offset..) + .and_then(|data| data.get(..len)) + .ok_or(tinywasm::Trap::MemoryOutOfBounds { offset, len, max: data.len() })?; + let state = ctx.state::<HostState>().unwrap(); + let Some(mut file) = state.files.get(&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(store, 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.borrow_mut(); - 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::<HostState>().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(store, move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.borrow_mut(); - 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::<HostState>().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(store, move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.borrow_mut(); - 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::<HostState>().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(store, move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { - let elapsed = state.borrow().start.elapsed(); - 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::<HostState>().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(store, move |_ctx: FuncContext<'_>, code: i32| { - state.borrow_mut().exit_code = Some(code); - Ok(()) - }), - ); - } + imports.define( + IMPORT_MODULE, + "host_exit", + HostFunction::from(|mut ctx: FuncContext<'_>, code: i32| { + ctx.state_mut::<HostState>().unwrap().exit_code = Some(code); + Ok(()) + }), + ); imports.define( IMPORT_MODULE, "host_print", - HostFunction::from(store, 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/exceptions.rs b/examples/exceptions.rs new file mode 100644 index 0000000..7c2f88e --- /dev/null +++ b/examples/exceptions.rs @@ -0,0 +1,28 @@ +use anyhow::{Result, bail}; +use tinywasm::{Error, ModuleInstance, Store, WasmValue}; + +const WASM: &str = r#" +(module + (tag $failure (export "failure") (param i32)) + (func (export "fail") (param i32) + local.get 0 + throw $failure)) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let fail = instance.func::<i32, ()>(&store, "fail")?; + + // Uncaught guest exceptions cross the host boundary as owned ExnRef handles. + let Err(Error::Exception(exception)) = fail.call(&mut store, 42) else { + bail!("expected a guest exception"); + }; + + // The handle exposes the exception tag and typed payload values. + assert_eq!(exception.tag(&store)?, instance.tag("failure")?); + assert_eq!(exception.fields(&mut store)?, [WasmValue::I32(42)]); + Ok(()) +} diff --git a/examples/funcref_callbacks.rs b/examples/funcref_callbacks.rs deleted file mode 100644 index 8ff9b49..0000000 --- a/examples/funcref_callbacks.rs +++ /dev/null @@ -1,124 +0,0 @@ -use eyre::Result; -use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store, types::FuncRef}; - -const LHS: i32 = 5; -const RHS: i32 = 3; - -fn main() -> Result<()> { - run_passed_funcref_example()?; - run_returned_funcref_example()?; - Ok(()) -} - -fn run_passed_funcref_example() -> Result<()> { - // Host receives funcref and calls it via an exported proxy. - const WASM: &str = r#" - (module - (import "host" "call_this" (func $host_callback_caller (param funcref))) - (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32))) - - (func $tell_host_to_call (export "tell_host_to_call") - (call $host_callback_caller (ref.func $add)) - (call $host_callback_caller (ref.func $sub)) - (call $host_callback_caller (ref.func $host_mul)) - ) - - (type $binop (func (param i32 i32) (result i32))) - - (table 3 funcref) - (elem (i32.const 0) $add $sub $host_mul) - (func $add (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add - ) - (func $sub (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.sub - ) - - (table $callback_register 1 funcref) - (func (export "call_binop_by_ref") (param funcref i32 i32) (result i32) - (table.set $callback_register (i32.const 0) (local.get 0)) - (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0)) - ) - ) - "#; - - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - - let mul = HostFunction::from(&mut store, |_, (lhs, rhs): (i32, i32)| -> tinywasm::Result<i32> { Ok(lhs * rhs) }); - let call_this = - HostFunction::from(&mut store, |mut ctx: FuncContext<'_>, func_ref: FuncRef| -> tinywasm::Result<()> { - // Host cannot call a funcref directly, so it routes through Wasm. - let call_by_ref = ctx.module().func::<(FuncRef, i32, i32), i32>(ctx.store(), "call_binop_by_ref")?; - let _result = call_by_ref.call(ctx.store_mut(), (func_ref, LHS, RHS))?; - Ok(()) - }); - - let mut imports = Imports::new(); - imports.define("host", "call_this", call_this).define("host", "mul", mul); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; - let caller = instance.func::<(), ()>(&store, "tell_host_to_call")?; - - caller.call(&mut store, ())?; - - Ok(()) -} - -fn run_returned_funcref_example() -> Result<()> { - // Wasm returns funcref values, host executes them through the same proxy. - const WASM: &str = r#" - (module - (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32))) - (type $binop (func (param i32 i32) (result i32))) - (table 3 funcref) - (elem (i32.const 0) $add $sub $host_mul) - (func $add (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add - ) - (func $sub (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.sub - ) - (func $ref_to_funcs (export "what_should_host_call") (result funcref funcref funcref) - (ref.func $add) - (ref.func $sub) - (ref.func $host_mul) - ) - - (table $callback_register 1 funcref) - (func $call (export "call_binop_by_ref") (param funcref i32 i32) (result i32) - (table.set $callback_register (i32.const 0) (local.get 0)) - (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0)) - ) - ) - "#; - - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let mut imports = Imports::new(); - - let mul = HostFunction::from(&mut store, |_, (lhs, rhs): (i32, i32)| -> tinywasm::Result<i32> { Ok(lhs * rhs) }); - imports.define("host", "mul", mul); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; - let (add_ref, sub_ref, mul_ref) = { - let get_funcrefs = instance.func::<(), (FuncRef, FuncRef, FuncRef)>(&store, "what_should_host_call")?; - get_funcrefs.call(&mut store, ())? - }; - - let call_by_ref = instance.func::<(FuncRef, i32, i32), i32>(&store, "call_binop_by_ref")?; - for func_ref in [add_ref, sub_ref, mul_ref] { - let _result = call_by_ref.call(&mut store, (func_ref, LHS, RHS))?; - } - Ok(()) -} diff --git a/examples/gc.rs b/examples/gc.rs new file mode 100644 index 0000000..9a73d04 --- /dev/null +++ b/examples/gc.rs @@ -0,0 +1,33 @@ +use anyhow::Result; +use tinywasm::{ModuleInstance, Store, StructRef, WasmValue}; + +const WASM: &str = r#" +(module + (type $cube (struct (field (mut i32)) (field (mut i32)))) + (func $make-cube (result (ref $cube)) + i32.const 3 + i32.const 4 + struct.new $cube) + (func (export "cube") (result (ref struct)) + call $make-cube)) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let cube = instance.func::<(), StructRef>(&store, "cube")?.call(&mut store, ())?; + + // GC handles are Store-bound and expose typed field access through that Store. + assert_eq!(cube.fields(&mut store)?, [WasmValue::I32(3), WasmValue::I32(4)]); + cube.set_field(&mut store, 0, WasmValue::I32(5))?; + + // Cloned handles keep their guest objects live across explicit collection. + let retained = cube.clone(); + drop(cube); + store.gc()?; + + assert_eq!(retained.field(&mut store, 0)?, WasmValue::I32(5)); // still alive + Ok(()) +} diff --git a/examples/linking.rs b/examples/linking.rs index b3164ae..92c0b7d 100644 --- a/examples/linking.rs +++ b/examples/linking.rs @@ -1,7 +1,6 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; -// WebAssembly module defining and exporting an `add` function. const WASM_ADD: &str = r#" (module (func $add (param $lhs i32) (param $rhs i32) (result i32) @@ -11,7 +10,6 @@ const WASM_ADD: &str = r#" (export "add" (func $add))) "#; -// WebAssembly module importing an `add` function and using it. const WASM_IMPORT: &str = r#" (module (import "adder" "add" (func $add (param i32 i32) (result i32))) @@ -24,25 +22,23 @@ const WASM_IMPORT: &str = r#" "#; fn main() -> Result<()> { - let wasm_add = wat::parse_str(WASM_ADD).expect("failed to parse wat"); - let wasm_import = wat::parse_str(WASM_IMPORT).expect("failed to parse wat"); + let wasm_add = wat::parse_str(WASM_ADD)?; + let wasm_import = wat::parse_str(WASM_IMPORT)?; let add_module = tinywasm::parse_bytes(&wasm_add)?; let import_module = tinywasm::parse_bytes(&wasm_import)?; let mut store = Store::default(); - // Instantiate the `add` module. let add_instance = ModuleInstance::instantiate(&mut store, &add_module, None)?; - // Link the `adder` namespace to the `add` module's instance. + // Imports can link a module namespace and define individual host items together. let mut imports = tinywasm::Imports::new(); imports.link_module("adder", add_instance)?; - // Instantiate the `import` module with the linked imports. - let import_instance = ModuleInstance::instantiate(&mut store, &import_module, Some(imports))?; + let import_instance = ModuleInstance::instantiate(&mut store, &import_module, Some(&imports))?; - // Call the `main` function, which uses the imported `add` function. + // Calling `main` crosses the linked module boundary to `add`. let main = import_instance.func::<(), i32>(&store, "main")?; assert_eq!(main.call(&mut store, ())?, 3); diff --git a/examples/reentrance.rs b/examples/reentrance.rs index 432fac7..cf57891 100644 --- a/examples/reentrance.rs +++ b/examples/reentrance.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; const WASM: &str = r#" @@ -22,11 +22,12 @@ fn main() -> Result<()> { let module = tinywasm::parse_bytes(&wasm)?; let mut store = Store::default(); - let call_add_twice = HostFunction::from(&mut store, |mut ctx: FuncContext<'_>, value: i32| { + let call_add_twice = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| { + // FuncContext exposes the active module and its Store to the callback. let add_one = ctx.module().func::<i32, i32>(ctx.store(), "add_one")?; - // Use ctx.call for reentrant calls from host functions. Function::call - // starts a root invocation and cannot preserve the active call stacks. + // Use ctx.call while a host callback has an active Wasm invocation. + // Function::call only starts top-level invocations. let value = ctx.call(&add_one, value)?; ctx.call(&add_one, value) }); @@ -34,7 +35,7 @@ fn main() -> Result<()> { let mut imports = Imports::new(); imports.define("host", "call_add_twice", call_add_twice); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let run = instance.func::<i32, i32>(&store, "run")?; assert_eq!(run.call(&mut store, 40)?, 52); diff --git a/examples/references.rs b/examples/references.rs new file mode 100644 index 0000000..b02dd07 --- /dev/null +++ b/examples/references.rs @@ -0,0 +1,34 @@ +use anyhow::Result; +use tinywasm::{FuncRef, HostFunction, Imports, ModuleInstance, Store}; + +const WASM: &str = r#" +(module + (type $callback (func (param i32) (result i32))) + (import "host" "double" (func $double (type $callback))) + (elem declare func $double) + (func (export "callback") (result funcref) + ref.func $double) + (func (export "apply") (param funcref i32) (result i32) + local.get 1 + local.get 0 + ref.cast (ref $callback) + call_ref $callback)) +"#; + +fn main() -> Result<()> { + let mut store = Store::default(); + let mut imports = Imports::new(); + // Imports resolve reusable host definitions against each module's runtime types. + // HostFunction::instantiate is available when a standalone Function is needed. + imports.define("host", "double", HostFunction::from(|_, value: i32| -> tinywasm::Result<i32> { Ok(value * 2) })); + + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + // Option<FuncRef> maps nullable funcref. Bare FuncRef maps a non-null reference. + let callback = instance.func::<(), Option<FuncRef>>(&store, "callback")?.call(&mut store, ())?; + let apply = instance.func::<(Option<FuncRef>, i32), i32>(&store, "apply")?; + + assert_eq!(apply.call(&mut store, (callback, 21))?, 42); + Ok(()) +} diff --git a/examples/resumable.rs b/examples/resumable.rs index 0163414..70b0db1 100644 --- a/examples/resumable.rs +++ b/examples/resumable.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ExecProgress, ModuleInstance, Store}; const WASM: &str = r#" @@ -29,10 +29,12 @@ fn main() -> Result<()> { let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let count_down = instance.func::<i32, i32>(&store, "count_down")?; + // A resumable call returns execution state instead of running to completion. let mut execution = count_down.call_resumable(&mut store, 10_000)?; let fuel_per_round = 128; let mut fuel_rounds = 0; + // Each resume call limits one round. std builds also support wall-clock budgets. let result = loop { fuel_rounds += 1; match execution.resume_with_fuel(fuel_per_round)? { diff --git a/examples/wasm-rust.rs b/examples/rust.rs index e0b9968..58fd11e 100644 --- a/examples/wasm-rust.rs +++ b/examples/rust.rs @@ -1,12 +1,12 @@ use std::hint::black_box; -use eyre::{Result, eyre}; +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 wasm-rust <example>`. -/// For example, `cargo run --example wasm-rust hello`. +/// These examples are meant to be run with `cargo run --example rust <example>`. +/// For example, `cargo run --example rust hello`. /// /// To run these, you first need to compile the Rust examples to WebAssembly: /// @@ -23,18 +23,19 @@ fn main() -> Result<()> { pretty_env_logger::init(); if !std::path::Path::new("./examples/rust/out/").exists() { - return Err(eyre!("No WebAssembly files found. See examples/wasm-rust.rs for instructions.")); + return Err(anyhow!("No WebAssembly files found. See examples/rust.rs for instructions.")); } let args = std::env::args().collect::<Vec<_>>(); if args.len() < 2 { - println!("Usage: cargo run --example wasm-rust <rust_example>"); + println!("Usage: cargo run --example rust <rust_example>"); 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!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); } @@ -44,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:"); @@ -57,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()?; } _ => {} @@ -75,8 +76,8 @@ fn tinywasm() -> Result<()> { let mut store = Store::default(); let mut imports = Imports::new(); - imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _x: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(imports)))?; + 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(()))?; @@ -86,12 +87,12 @@ 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(); - imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _x: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(imports)))?; + 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(()))?; @@ -104,7 +105,8 @@ fn hello() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; let mut store = Store::default(); - let print_utf8 = HostFunction::from(&mut store, |ctx: FuncContext<'_>, (ptr, len): (i64, i32)| { + // 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}"); @@ -114,10 +116,11 @@ fn hello() -> Result<()> { let mut imports = Imports::new(); imports.define("env", "print_utf8", print_utf8); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + 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::<i32, ()>(&store, "hello")?; hello.call(&mut store, arg.len() as i32)?; @@ -126,10 +129,10 @@ 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(&mut store, |_: FuncContext<'_>, (left, right): (i64, i32)| { + let bar = HostFunction::from(|_: FuncContext<'_>, (left, right): (i64, i32)| { assert_eq!(left, 1); assert_eq!(right, 2); Ok(left as i32 + right) @@ -138,7 +141,7 @@ fn host_fn() -> Result<()> { let mut imports = Imports::new(); imports.define("env", "bar", bar); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + 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(()) @@ -148,7 +151,7 @@ fn printi32() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/print.opt.wasm")?; let mut store = Store::default(); - let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, x: i32| { + let printi32 = HostFunction::from(|_: FuncContext<'_>, x: i32| { println!("{x}"); Ok(()) }); @@ -156,7 +159,7 @@ fn printi32() -> Result<()> { let mut imports = Imports::new(); imports.define("env", "printi32", printi32); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + 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))?; diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index efce27a..74d38e7 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-wasm-examples" -edition = "2021" +edition = "2024" publish = false # treat this as an independent package @@ -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]] @@ -35,17 +35,17 @@ name = "argon2id" path = "src/argon2id.rs" [dependencies] -argon2 = { version = "0.5" } +argon2 = { version = "0.6", default-features = false, features = ["alloc"] } dlmalloc = { version = "0.2", features = ["global"] } -tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [ - "archive", - "parser" -] } +tinywasm = { path = "../../crates/tinywasm", default-features = false, features = ["archive", "parser"] } [features] default = ["std"] std = ["tinywasm/std"] +[lints.clippy] +missing_safety_doc = "allow" + [profile.wasm] inherits = "release" opt-level = 3 diff --git a/examples/rust/README.md b/examples/rust/README.md index 8d3178a..305a29c 100644 --- a/examples/rust/README.md +++ b/examples/rust/README.md @@ -1,9 +1,9 @@ # WebAssembly Rust Examples This is a separate crate that generates WebAssembly from Rust code. -It is used by the `wasm-rust` example. +It is used by the `rust` example. Requires the `wasm32-unknown-unknown` target to be installed. -To build the example artifacts used by `cargo run --example wasm-rust -- <name>`, run `./examples/rust/build.sh`. +To build the example artifacts used by `cargo run --example rust -- <name>`, run `./examples/rust/build.sh`. That script also requires `binaryen` and `wabt` to be installed. diff --git a/examples/rust/build.sh b/examples/rust/build.sh index db4cb43..e19b8b8 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" @@ -12,9 +12,14 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl # ensure out dir exists mkdir -p "$dest_dir" +# Keep the embedded archive synchronized with the current archive version and instruction layout. +cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \ + compile "src/print.wasm" --output "src/print.twasm" --force || exit + # build no_std -cargo build --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/" +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 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/rust/src/hello.rs b/examples/rust/src/hello.rs index 3d9f400..06ef5c9 100644 --- a/examples/rust/src/hello.rs +++ b/examples/rust/src/hello.rs @@ -19,10 +19,12 @@ pub unsafe extern "C" fn arg_size() -> i32 { #[unsafe(no_mangle)] pub unsafe extern "C" fn hello(len: i32) { - let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap(); - let res = format!("Hello, {}!", arg).as_bytes().to_vec(); + unsafe { + let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap(); + let res = format!("Hello, {}!", arg).as_bytes().to_vec(); - let len = res.len() as i32; - let ptr = res.leak().as_ptr() as i64; - print_utf8(ptr, len); + let len = res.len() as i32; + let ptr = res.leak().as_ptr() as i64; + print_utf8(ptr, len); + } } diff --git a/examples/rust/src/print.rs b/examples/rust/src/print.rs index d2934f0..991ea4a 100644 --- a/examples/rust/src/print.rs +++ b/examples/rust/src/print.rs @@ -7,5 +7,7 @@ unsafe extern "C" { #[unsafe(no_mangle)] pub unsafe extern "C" fn add_and_print(lh: i32, rh: i32) { - printi32(lh + rh); + unsafe { + printi32(lh + rh); + } } diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm Binary files differnew file mode 100644 index 0000000..8ad32e3 --- /dev/null +++ b/examples/rust/src/print.twasm diff --git a/examples/rust/src/tinywasm.rs b/examples/rust/src/tinywasm.rs index 70de73e..b0a2e47 100644 --- a/examples/rust/src/tinywasm.rs +++ b/examples/rust/src/tinywasm.rs @@ -15,7 +15,7 @@ fn run() -> tinywasm::Result<()> { let module = tinywasm::parse_stream(&include_bytes!("./print.wasm")[..])?; let mut store = tinywasm::Store::default(); - let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, v: i32| { + let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { unsafe { printi32(v) } Ok(()) }); @@ -23,7 +23,7 @@ fn run() -> tinywasm::Result<()> { let mut imports = tinywasm::Imports::new(); imports.define("env", "printi32", printi32); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + 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(()) diff --git a/examples/rust/src/tinywasm_no_std.rs b/examples/rust/src/tinywasm_no_std.rs index c1dd910..a70abb9 100644 --- a/examples/rust/src/tinywasm_no_std.rs +++ b/examples/rust/src/tinywasm_no_std.rs @@ -1,7 +1,7 @@ #![no_main] #![no_std] use dlmalloc::GlobalDlmalloc; -use tinywasm::{FuncContext, HostFunction, ModuleInstance}; +use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; extern crate alloc; @@ -28,17 +28,15 @@ fn run() -> tinywasm::Result<()> { let mut store = tinywasm::Store::default(); let mut imports = tinywasm::Imports::new(); - let res = tinywasm::parser::Parser::new().parse_module_bytes(include_bytes!("./print.wasm"))?; - let twasm = res.serialize_twasm()?; - let module = tinywasm::parse_bytes(&twasm)?; + let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; - let printi32 = HostFunction::from(&mut store, |_: FuncContext<'_>, v: i32| { + let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { unsafe { printi32(v) } Ok(()) }); imports.define("env", "printi32", printi32); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + 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(()) diff --git a/examples/simple2.rs b/examples/simple2.rs deleted file mode 100644 index da7def7..0000000 --- a/examples/simple2.rs +++ /dev/null @@ -1,21 +0,0 @@ -use eyre::Result; -use tinywasm::{ModuleInstance, Store}; - -const WASM: &str = r#" -(module - (func $return (param $lhs i32) (param $rhs i64) (result i32 i64) - local.get $lhs - local.get $rhs) - (export "return" (func $return))) -"#; - -fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let add = instance.func::<(i32, i64), (i32, i64)>(&store, "return")?; - - assert_eq!(add.call(&mut store, (1, 2))?, (1, 2)); - Ok(()) -} 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::<State>().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::<State>().unwrap().calls, 2); + Ok(()) +} diff --git a/examples/wasi_p1.rs b/examples/wasi_p1.rs new file mode 100644 index 0000000..22024dc --- /dev/null +++ b/examples/wasi_p1.rs @@ -0,0 +1,42 @@ +use anyhow::Result; +use tinywasm::{ModuleInstance, Store}; +use tinywasm_wasi::p1::{WasiCtx, imports}; + +const WASM: &str = r#" +(module + (import "wasi_snapshot_preview1" "fd_write" + (func $fd_write (param i32 i32 i32 i32) (result i32))) + (memory (export "memory") 1) + (data (i32.const 16) "Hello from WASI Preview 1!\n") + + (func (export "_start") + i32.const 0 + i32.const 16 + i32.store + i32.const 4 + i32.const 27 + i32.store + + i32.const 1 + i32.const 0 + i32.const 1 + i32.const 8 + call $fd_write + drop)) +"#; + +// Requires TinyWasm's `parser`, `std`, and `state` features. +// Run with `cargo run --example wasi_p1` from the repository root. +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + + // The host explicitly chooses what the guest can observe. + let wasi = WasiCtx::new().with_args(["wasi_p1.wasm", "example"])?.with_env([("MODE", "example")])?.inherit_stdio(); + let mut store = Store::default().with_state(wasi); + + // Preview 1 imports are reusable because their state comes from the Store. + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports()))?; + instance.func::<(), ()>(&store, "_start")?.call(&mut store, ())?; + Ok(()) +} |
