diff options
Diffstat (limited to 'crates')
32 files changed, 1757 insertions, 1354 deletions
diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index ad1742e..2ca622d 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -177,20 +177,20 @@ impl WastRunner { .define("spectest", "global_i64", global_i64) .define("spectest", "global_f32", global_f32) .define("spectest", "global_f64", global_f64) - .define("spectest", "print", HostFunction::from(store, |_ctx: tinywasm::FuncContext, (): ()| Ok(()))) - .define("spectest", "print_i32", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: i32| Ok(()))) - .define("spectest", "print_i64", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: i64| Ok(()))) - .define("spectest", "print_f32", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: f32| Ok(()))) - .define("spectest", "print_f64", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: f64| Ok(()))) + .define("spectest", "print", HostFunction::from(|_ctx: tinywasm::FuncContext, (): ()| Ok(()))) + .define("spectest", "print_i32", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: i32| Ok(()))) + .define("spectest", "print_i64", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: i64| Ok(()))) + .define("spectest", "print_f32", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: f32| Ok(()))) + .define("spectest", "print_f64", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: f64| Ok(()))) .define( "spectest", "print_i32_f32", - HostFunction::from(store, |_ctx: tinywasm::FuncContext, _args: (i32, f32)| Ok(())), + HostFunction::from(|_ctx: tinywasm::FuncContext, _args: (i32, f32)| Ok(())), ) .define( "spectest", "print_f64_f64", - HostFunction::from(store, |_ctx: tinywasm::FuncContext, _args: (f64, f64)| Ok(())), + HostFunction::from(|_ctx: tinywasm::FuncContext, _args: (f64, f64)| Ok(())), ); for (name, module) in modules { @@ -235,7 +235,7 @@ impl WastRunner { let (name, bytes) = encode_quote_wat(module); let module = parse_module_bytes(&bytes).expect("failed to parse module bytes"); let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); - let module_instance = ModuleInstance::instantiate(&mut store, &module, Some(imports)) + let module_instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)) .expect("failed to instantiate module"); (name, module_instance) }) @@ -331,7 +331,7 @@ impl WastRunner { let module = parse_module_bytes(&wat.encode().expect("failed to encode module")) .expect("failed to parse module"); let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); - ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; return Ok(()); } wast::WastExecute::Get { .. } => panic!("get not supported"), @@ -376,7 +376,7 @@ impl WastRunner { let module = parse_module_bytes(&module.encode().expect("failed to encode module")) .expect("failed to parse module"); let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); - ModuleInstance::instantiate(&mut store, &module, Some(imports)) + ModuleInstance::instantiate(&mut store, &module, Some(&imports)) }); match res { Err(err) => test_group.add_result( diff --git a/crates/parser/README.md b/crates/parser/README.md index 05c2af2..cf1a6c4 100644 --- a/crates/parser/README.md +++ b/crates/parser/README.md @@ -16,10 +16,10 @@ use tinywasm_parser::{Parser, ParserOptions}; let bytes = include_bytes!("./file.wasm"); -let parser = Parser::new(); +let parser = Parser::default(); let module = parser.parse_module_bytes(bytes)?; -let parser = Parser::with_options(ParserOptions::default().with_rewrite_optimization(false)); +let parser = Parser::new(ParserOptions::default().with_rewrite_optimization(false)); let module = parser.parse_module_bytes(bytes)?; let module = parser.parse_module_file("path/to/file.wasm")?; @@ -27,4 +27,4 @@ let mut stream = std::fs::File::open("path/to/file.wasm")?; let module = parser.parse_module_stream(&mut stream)?; ``` -If you just want the default configuration, the top-level `parse_bytes`, `parse_file`, and `parse_stream` helpers are thin wrappers around `Parser::new()`. +If you just want the default configuration, the top-level `parse_bytes`, `parse_file`, and `parse_stream` helpers are thin wrappers around `Parser::default()`. diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 5439558..fe968d8 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -90,6 +90,11 @@ impl Default for ParserOptions { } impl ParserOptions { + /// Create parser options with default settings. + pub fn new() -> Self { + Self::default() + } + /// Enable or disable WebAssembly validation. /// /// Requires the `validate` feature to have any effect. @@ -152,13 +157,8 @@ pub struct Parser { } impl Parser { - /// Create a new parser instance - pub fn new() -> Self { - Self::default() - } - - /// Create a new parser with explicit options. - pub fn with_options(options: ParserOptions) -> Self { + /// Create a parser with the given options. + pub const fn new(options: ParserOptions) -> Self { Self { options } } @@ -352,17 +352,17 @@ impl TryFrom<ModuleReader<'_>> for Module { /// Parse a module from bytes pub fn parse_bytes(wasm: &[u8]) -> Result<Module> { - Parser::new().parse_module_bytes(wasm) + Parser::default().parse_module_bytes(wasm) } #[cfg(feature = "std")] /// Parse a module from a file. Requires the `std` feature. pub fn parse_file(path: impl AsRef<crate::std::path::Path> + Clone) -> Result<Module> { - Parser::new().parse_module_file(path) + Parser::default().parse_module_file(path) } #[cfg(feature = "std")] /// Parse a module from a stream. Requires the `std` feature. pub fn parse_stream(stream: impl crate::std::io::Read) -> Result<Module> { - Parser::new().parse_module_stream(stream) + Parser::default().parse_module_stream(stream) } diff --git a/crates/tinywasm/benches/argon2id.rs b/crates/tinywasm/benches/argon2id.rs index dbd86e5..d2845c5 100644 --- a/crates/tinywasm/benches/argon2id.rs +++ b/crates/tinywasm/benches/argon2id.rs @@ -6,7 +6,7 @@ use types::Module; const WASM: &[u8] = include_bytes!("../../../examples/rust/out/argon2id.wasm"); fn argon2id_parse() -> Result<Module> { - let parser = tinywasm_parser::Parser::new(); + let parser = tinywasm_parser::Parser::default(); let data = parser.parse_module_bytes(WASM)?; Ok(data) } diff --git a/crates/tinywasm/benches/fibonacci.rs b/crates/tinywasm/benches/fibonacci.rs index e0737da..1bf0791 100644 --- a/crates/tinywasm/benches/fibonacci.rs +++ b/crates/tinywasm/benches/fibonacci.rs @@ -6,7 +6,7 @@ use types::Module; const WASM: &[u8] = include_bytes!("../../../examples/rust/out/fibonacci.wasm"); fn fibonacci_parse() -> Result<Module> { - let parser = tinywasm_parser::Parser::new(); + let parser = tinywasm_parser::Parser::default(); let data = parser.parse_module_bytes(WASM)?; Ok(data) } diff --git a/crates/tinywasm/benches/tinywasm.rs b/crates/tinywasm/benches/tinywasm.rs index 67db886..3560d3c 100644 --- a/crates/tinywasm/benches/tinywasm.rs +++ b/crates/tinywasm/benches/tinywasm.rs @@ -1,13 +1,13 @@ use criterion::{Criterion, criterion_group, criterion_main}; use eyre::Result; use tinywasm::engine::Config; -use tinywasm::{Engine, FuncContext, HostFunction, Imports, MemoryBackend, ModuleInstance, Store, types}; +use tinywasm::{Engine, FuncContext, HostFunction, Imports, ModuleInstance, Store, types}; use types::Module; const WASM: &[u8] = include_bytes!("../../../examples/rust/out/tinywasm.wasm"); fn tinywasm_parse() -> Result<Module> { - let parser = tinywasm_parser::Parser::new(); + let parser = tinywasm_parser::Parser::default(); let data = parser.parse_module_bytes(WASM)?; Ok(data) } @@ -26,8 +26,8 @@ fn tinywasm_run(module: &Module) -> Result<()> { let engine = Engine::new(Config::default()); let mut store = Store::new(engine); let mut imports = Imports::default(); - imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, module, Some(imports)).expect("instantiate"); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports)).expect("instantiate"); let hello = instance.func::<(), ()>(&store, "hello").expect("func_typed"); hello.call(&mut store, ()).expect("call"); Ok(()) diff --git a/crates/tinywasm/benches/tinywasm_modes.rs b/crates/tinywasm/benches/tinywasm_modes.rs index ed89b7b..6c1badf 100644 --- a/crates/tinywasm/benches/tinywasm_modes.rs +++ b/crates/tinywasm/benches/tinywasm_modes.rs @@ -10,7 +10,7 @@ const TIME_BUDGET_PER_ROUND: core::time::Duration = core::time::Duration::from_m const BENCH_MEASUREMENT_TIME: core::time::Duration = core::time::Duration::from_secs(10); fn tinywasm_parse() -> Result<Module> { - let parser = tinywasm_parser::Parser::new(); + let parser = tinywasm_parser::Parser::default(); Ok(parser.parse_module_bytes(WASM)?) } @@ -21,9 +21,9 @@ fn setup_typed_func(module: &Module, engine: Option<Engine>) -> Result<(Store, F }; let mut imports = Imports::default(); - imports.define("env", "printi32", HostFunction::from(&mut store, |_: FuncContext<'_>, _: i32| Ok(()))); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports))?; let func = instance.func::<(), ()>(&store, "hello")?; Ok((store, func)) } diff --git a/crates/tinywasm/src/func.rs b/crates/tinywasm/src/func.rs deleted file mode 100644 index c4409cd..0000000 --- a/crates/tinywasm/src/func.rs +++ /dev/null @@ -1,892 +0,0 @@ -use crate::interpreter::stack::{CallFrame, ValueStack}; -use crate::reference::StoreItem; -use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store, Trap}; -use alloc::{borrow::Cow, boxed::Box, format, rc::Rc, vec, vec::Vec}; -use core::hint::cold_path; -use tinywasm_types::{ExternRef, FuncAddr, FuncRef, FuncType, ModuleInstanceId, TypeAddr, WasmType, WasmValue}; - -impl Function { - #[inline] - pub(crate) const fn addr(&self) -> FuncAddr { - self.item.addr - } - - /// Get this function's canonical type from its store. - /// - /// Concrete reference types are only meaningful in this store. - pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { - self.item.validate_store(store)?; - Ok(store.state.get_func_type(self.addr())) - } - - /// Call a function (Invocation) - /// - /// See <https://webassembly.github.io/spec/core/exec/modules.html#invocation> - #[inline] - pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result<Vec<WasmValue>> { - #[inline] - fn call_inner(func: &Function, store: &mut Store, params: &[WasmValue]) -> Result<Vec<WasmValue>> { - let func_instance = store.state.get_func(func.addr()).clone(); - let wasm_func = match &func_instance.kind { - crate::store::FunctionKind::Host(host_func) => { - let result = host_func.clone().call(FuncContext { store, module_id: func.module_id }, params)?; - return validate_host_results(store, func_instance.type_addr, result); - } - crate::store::FunctionKind::Wasm(wasm_func) => wasm_func, - }; - - // Reset stack, push args, allocate locals, create entry frame. - store.call_stack.clear(); - store.value_stack.clear(); - store.value_stack.extend_from_wasmvalues(params)?; - let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?; - let callframe = CallFrame::new(func.addr(), locals_base, wasm_func.func.locals); - - // Execute until completion and then collect result values from the stack. - InterpreterRuntime::exec(store, callframe, 0)?; - collect_call_results( - &mut store.value_stack, - &store.state, - store.state.get_canonical_func_type(func_instance.type_addr), - ) - } - - self.item.validate_store(store)?; - validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?; - let results_may_gc = store.state.get_func(self.addr()).gc.results; - - store.enter_execution()?; - let result = call_inner(self, store, params); - store.exit_execution(); - - if results_may_gc && let Ok(values) = &result { - store.state.pin_host_values(values); - } - - result - } - - /// Call a function and return a resumable execution handle. - /// - /// The returned handle keeps a mutable borrow of the [`Store`] until it - /// completes. Use [`FuncExecution::resume_with_fuel`] (or - /// `resume_with_time_budget` with `std`) to continue. - pub fn call_resumable<'store>( - &self, - store: &'store mut Store, - params: &[WasmValue], - ) -> Result<FuncExecution<'store>> { - #[inline] - fn call_resumable_inner( - func: &Function, - store: &mut Store, - params: &[WasmValue], - ) -> Result<FuncExecutionState> { - let func_instance = store.state.get_func(func.addr()).clone(); - match &func_instance.kind { - crate::store::FunctionKind::Host(host_func) => { - let result = host_func.clone().call(FuncContext { store, module_id: func.module_id }, params)?; - let result = validate_host_results(store, func_instance.type_addr, result)?; - Ok(FuncExecutionState::Completed { result: Some(result) }) - } - crate::store::FunctionKind::Wasm(wasm_func) => { - store.call_stack.clear(); - store.value_stack.clear(); - store.value_stack.extend_from_wasmvalues(params)?; - let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?; - let callframe = CallFrame::new(func.addr(), locals_base, wasm_func.func.locals); - - Ok(FuncExecutionState::Running { - exec_state: ExecutionState { callframe }, - root_func_addr: func.addr(), - }) - } - } - } - - self.item.validate_store(store)?; - validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?; - let results_may_gc = store.state.get_func(self.addr()).gc.results; - - store.enter_execution()?; - let result = call_resumable_inner(self, store, params); - store.exit_execution(); - - let state = result?; - if results_may_gc && let FuncExecutionState::Completed { result: Some(values) } = &state { - store.state.pin_host_values(values); - } - Ok(FuncExecution { store, state }) - } -} - -#[derive(Clone, PartialEq, Eq)] -/// Progress for fuel-limited function execution. -pub enum ExecProgress<T> { - /// Execution completed and produced a result. - Completed(T), - /// Execution suspended after exhausting fuel or time budget. - Suspended, -} - -#[derive(Clone)] -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub(crate) struct ExecutionState { - pub(crate) callframe: CallFrame, -} - -/// A function handle -#[derive(Clone)] -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub struct Function { - pub(crate) item: StoreItem, - pub(crate) module_id: ModuleInstanceId, -} - -/// A typed function handle -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub struct FunctionTyped<P, R> { - /// The underlying function handle - pub func: Function, - pub(crate) marker: core::marker::PhantomData<(P, R)>, -} - -/// A host function -pub struct HostFunction { - pub(crate) func: HostFuncInner, -} - -impl HostFunction { - /// Call the function - pub fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result<Vec<WasmValue>> { - (self.func)(ctx, args) - } - - /// Create a new untyped host function import. - /// - /// ## Example - /// ```rust - /// # fn main() -> tinywasm::Result<()> { - /// # use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; - /// # use tinywasm::types::{FuncType, WasmType, WasmValue}; - /// # let wasm = wat::parse_str(r#" - /// # (module - /// # (import "host" "add_one" (func $add_one (param i32) (result i32))) - /// # (func (export "call") (param i32) (result i32) - /// # local.get 0 - /// # call $add_one)) - /// # "#).expect("valid wat"); - /// # let module = tinywasm::parse_bytes(&wasm)?; - /// let mut store = Store::default(); - /// let ty = FuncType::new(&[WasmType::I32], &[WasmType::I32]); - /// let add_one = HostFunction::from_untyped(&mut store, &ty, |_ctx: FuncContext<'_>, args| { - /// let WasmValue::I32(value) = args[0] else { - /// return Err(tinywasm::Error::Other("expected i32".into())); - /// }; - /// Ok(vec![WasmValue::I32(value + 1)]) - /// }); - /// - /// let mut imports = Imports::new(); - /// imports.define("host", "add_one", add_one); - /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; - /// # let call = instance.func::<i32, i32>(&store, "call")?; - /// # assert_eq!(call.call(&mut store, 41)?, 42); - /// # Ok(()) - /// # } - /// ``` - pub fn from_untyped( - store: &mut Store, - ty: &FuncType, - func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + 'static, - ) -> Function { - let type_addr = store.register_host_type(ty); - let addr = store.add_func(FunctionInstance { - type_addr, - gc: store.state.func_gc_metadata(type_addr), - kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(func) })), - }); - Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } - } - - /// Create a new typed host function import. - /// - /// ## Example - /// ```rust - /// # fn main() -> tinywasm::Result<()> { - /// # use tinywasm::{HostFunction, Imports, ModuleInstance, Store}; - /// # let wasm = wat::parse_str(r#" - /// # (module - /// # (import "host" "add_one" (func $add_one (param i32) (result i32))) - /// # (func (export "call") (param i32) (result i32) - /// # local.get 0 - /// # call $add_one)) - /// # "#).expect("valid wat"); - /// # let module = tinywasm::parse_bytes(&wasm)?; - /// let mut store = Store::default(); - /// let add_one = HostFunction::from(&mut store, |_ctx, value: i32| Ok(value + 1)); - /// - /// let mut imports = Imports::new(); - /// imports.define("host", "add_one", add_one); - /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; - /// # let call = instance.func::<i32, i32>(&store, "call")?; - /// # assert_eq!(call.call(&mut store, 41)?, 42); - /// # Ok(()) - /// # } - /// ``` - pub fn from<P, R>(store: &mut Store, func: impl Fn(FuncContext<'_>, P) -> Result<R> + 'static) -> Function - where - P: FromWasmValues + ToWasmTypes, - R: IntoWasmValues + ToWasmTypes, - { - let inner_func = move |ctx: FuncContext<'_>, args: &[WasmValue]| -> Result<Vec<WasmValue>> { - Ok(func(ctx, P::from_wasm_values(args)?)?.into_wasm_values()) - }; - - let ty = tinywasm_types::FuncType::new(&P::wasm_types(), &R::wasm_types()); - let type_addr = store.register_host_type(&ty); - let addr = store.add_func(FunctionInstance { - type_addr, - gc: store.state.func_gc_metadata(type_addr), - kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(inner_func) })), - }); - Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } - } -} - -pub(crate) type HostFuncInner = Box<dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>>>; - -/// The context of a host-function call -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub struct FuncContext<'a> { - pub(crate) store: &'a mut crate::Store, - pub(crate) module_id: ModuleInstanceId, -} - -impl FuncContext<'_> { - /// Get the store. - pub fn store(&self) -> &crate::Store { - self.store - } - - /// Get mutable access to the store. - pub fn store_mut(&mut self) -> &mut crate::Store { - self.store - } - - /// Get the module instance. - pub fn module(&self) -> crate::ModuleInstance { - self.store - .get_module_instance(self.module_id) - .unwrap_or_else(|| unreachable!("invalid module instance id in host function context: {}", self.module_id)) - .clone() - } - - /// Get a memory export. - pub fn memory(&self, name: &str) -> Result<crate::Memory> { - self.module().memory(name) - } - - /// Get any exported extern value by name. - pub fn extern_item(&self, name: &str) -> Result<crate::ExternItem> { - self.module().extern_item(name) - } - - /// Get a table export. - pub fn table(&self, name: &str) -> Result<crate::Table> { - self.module().table(name) - } - - /// Get the value of a global export. - pub fn global_get(&self, name: &str) -> Result<WasmValue> { - self.module().global_get(self.store, name) - } - - /// Get a global export. - pub fn global(&self, name: &str) -> Result<crate::Global> { - self.module().global(name) - } - - /// Set the value of a mutable global export. - pub fn global_set(&mut self, name: &str, value: WasmValue) -> Result<()> { - self.module().global_set(self.store, name, value) - } - - /// Charge additional fuel from the currently running resumable invocation. - /// - /// This is a no-op when the current invocation is not using fuel-based - /// resumption. - pub fn charge_fuel(&mut self, fuel: u32) { - self.store.execution_fuel = self.store.execution_fuel.saturating_sub(fuel); - } - - /// Get remaining fuel for the current invocation. - /// - /// Returns `0` when fuel-based resumption is not active. - pub fn remaining_fuel(&self) -> u32 { - self.store.execution_fuel - } - - /// Call a function from within the current host-function invocation. - /// - /// This is the safe way for host functions to perform blocking reentrant - /// calls into Wasm. Unlike [`Function::call`], it preserves the active - /// invocation's stacks and resumes the host caller after the nested call - /// completes. - /// - /// Nested calls are currently blocking only. If the surrounding invocation - /// is resumed with fuel or a time budget, this method does not suspend and - /// later continue the host function in the middle of the nested call. - pub fn call_untyped(&mut self, func: &Function, args: &[WasmValue]) -> Result<Vec<WasmValue>> { - if !self.store.execution_active { - return Err(Error::other("FuncContext::call requires an active host-function invocation")); - } - - func.item.validate_store(self.store)?; - validate_call_params(&self.store.state, self.store.state.get_func_type(func.addr()), args)?; - - let func_instance = self.store.state.get_func(func.addr()).clone(); - let result = match func_instance.kind { - crate::store::FunctionKind::Host(host_func) => { - let result = - host_func.call(FuncContext { store: &mut *self.store, module_id: func.module_id }, args)?; - validate_host_results(self.store, func_instance.type_addr, result) - } - crate::store::FunctionKind::Wasm(wasm_func) => { - let call_stack_base = self.store.call_stack.len(); - let value_stack_base = self.store.value_stack.base(); - - self.store.value_stack.extend_from_wasmvalues(args).inspect_err(|_| { - self.store.value_stack.truncate_to_base(value_stack_base); - })?; - - let locals_base = self - .store - .value_stack - .enter_locals(&wasm_func.func.params, &wasm_func.func.locals) - .inspect_err(|_| self.store.value_stack.truncate_to_base(value_stack_base))?; - - let callframe = CallFrame::new(func.addr(), locals_base, wasm_func.func.locals); - InterpreterRuntime::exec(self.store, callframe, call_stack_base).inspect_err(|_| { - self.store.call_stack.truncate_to(call_stack_base); - self.store.value_stack.truncate_to_base(value_stack_base); - })?; - - collect_call_results( - &mut self.store.value_stack, - &self.store.state, - self.store.state.get_canonical_func_type(func_instance.type_addr), - ) - } - }; - if func_instance.gc.results - && let Ok(values) = &result - { - self.store.state.pin_host_values(values); - } - result - } - - /// Call a typed function from within the current host-function invocation. - /// - /// See [`Self::call_untyped`] for reentrancy and resumable-execution - /// limitations. - pub fn call<P, R>(&mut self, func: &FunctionTyped<P, R>, params: P) -> Result<R> - where - P: IntoWasmValues, - R: FromWasmValues, - { - R::from_wasm_values(&self.call_untyped(&func.func, ¶ms.into_wasm_values())?) - } -} - -impl core::ops::Deref for FuncContext<'_> { - type Target = crate::Store; - - fn deref(&self) -> &Self::Target { - self.store - } -} - -impl core::ops::DerefMut for FuncContext<'_> { - fn deref_mut(&mut self) -> &mut Self::Target { - self.store - } -} - -impl<'a> FuncContext<'a> { - /// Create a new host function context. - pub const fn new(store: &'a mut crate::Store, module_id: ModuleInstanceId) -> Self { - Self { store, module_id } - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for HostFunction { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("HostFunction").field("func", &"...").finish() - } -} - -/// Resumable execution for an untyped function call. -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub struct FuncExecution<'store> { - store: &'store mut Store, - state: FuncExecutionState, -} - -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -enum FuncExecutionState { - Running { exec_state: ExecutionState, root_func_addr: u32 }, - Completed { result: Option<Vec<WasmValue>> }, -} - -/// Resumable execution for a typed function call. -#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] -pub struct FuncExecutionTyped<'store, R> { - execution: FuncExecution<'store>, - marker: core::marker::PhantomData<R>, -} - -impl<'store> FuncExecution<'store> { - fn resume( - &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>, - ) -> Result<ExecProgress<Vec<WasmValue>>> { - let (callframe, root_func_addr) = match &mut self.state { - FuncExecutionState::Running { exec_state, root_func_addr } => (exec_state.callframe, *root_func_addr), - FuncExecutionState::Completed { result } => { - return match result.take() { - Some(res) => Ok(ExecProgress::Completed(res)), - None => Err(Error::other("execution already completed")), - }; - } - }; - - self.store.enter_execution()?; - let result = run(self.store, callframe); - self.store.exit_execution(); - - match result? { - crate::interpreter::ExecState::Completed => { - let func = self.store.state.get_func(root_func_addr); - let result_ty = func.type_addr; - let results_may_gc = func.gc.results; - self.state = FuncExecutionState::Completed { result: None }; - let values = collect_call_results( - &mut self.store.value_stack, - &self.store.state, - self.store.state.get_canonical_func_type(result_ty), - )?; - if results_may_gc { - self.store.state.pin_host_values(&values); - } - Ok(ExecProgress::Completed(values)) - } - crate::interpreter::ExecState::Suspended(callframe) => { - let FuncExecutionState::Running { exec_state, .. } = &mut self.state else { - unreachable!("invalid function execution state") - }; - exec_state.callframe = callframe; - Ok(ExecProgress::Suspended) - } - } - } - - /// Resume execution with up to `fuel` units of fuel. - /// - /// Fuel is accounted in chunks, so execution may overshoot the requested - /// fuel before returning [`ExecProgress::Suspended`] (currently the chunk size is 128 instructions between fuel checks, but this may change in the future). - /// - /// Returns [`ExecProgress::Suspended`] when fuel is exhausted, or - /// [`ExecProgress::Completed`] with the final values once the invocation - /// returns. - /// - /// Reentrant calls made by host functions through [`FuncContext::call`] are - /// currently blocking. They do not suspend and later resume the host - /// function in the middle of the nested call. - pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<Vec<WasmValue>>> { - self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel)) - } - - #[cfg(feature = "std")] - /// Resume execution for at most `time_budget` wall-clock time. - /// - /// Time is checked periodically, so execution may overshoot the requested - /// time budget before returning [`ExecProgress::Suspended`] (currently time is checked every 128 instructions, but this may change in the future). - /// - /// Returns [`ExecProgress::Suspended`] when the budget is exhausted, or - /// [`ExecProgress::Completed`] with the final values once the invocation - /// returns. - /// - /// Reentrant calls made by host functions through [`FuncContext::call`] are - /// currently blocking. They do not suspend and later resume the host - /// function in the middle of the nested call. - pub fn resume_with_time_budget( - &mut self, - time_budget: crate::std::time::Duration, - ) -> Result<ExecProgress<Vec<WasmValue>>> { - self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget)) - } -} - -fn validate_call_params(state: &crate::store::State, func_ty: &FuncType, params: &[WasmValue]) -> Result<()> { - if func_ty.params().len() != params.len() { - cold_path(); - return Err(Error::Other(format!( - "param count mismatch: expected {}, got {}", - func_ty.params().len(), - params.len() - ))); - } - - if !func_ty.params().iter().zip(params).all(|(ty, param)| state.value_matches_type(*param, *ty)) { - return Err(Error::other("Type mismatch")); - } - - Ok(()) -} - -pub(crate) fn validate_host_results( - store: &Store, - type_addr: TypeAddr, - result: Vec<WasmValue>, -) -> Result<Vec<WasmValue>> { - let expected = store.state.get_canonical_func_type(type_addr); - if result.len() == expected.results().len() - && result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty)) - { - return Ok(result); - } - - Err(Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result }) -} - -fn collect_call_results( - value_stack: &mut ValueStack, - state: &crate::store::State, - func_ty: &FuncType, -) -> Result<Vec<WasmValue>> { - debug_assert!(value_stack.len() >= func_ty.results().len()); // m values are on the top of the stack (Ensured by validation) - let results = func_ty.results(); - let mut res = vec![WasmValue::I32(0); results.len()]; - for (i, &ty) in results.iter().enumerate().rev() { - res[i] = value_stack.pop_wasmvalue(state, ty); - } - Ok(res) -} - -pub trait IntoWasmValues { - fn into_wasm_values(self) -> Vec<WasmValue>; -} - -pub trait FromWasmValues: Sized { - fn from_wasm_values(values: &[WasmValue]) -> Result<Self>; -} - -impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> { - /// Call a typed function - pub fn call(&self, store: &mut Store, params: P) -> Result<R> { - // Convert params into Vec<WasmValue> - let wasm_values = params.into_wasm_values(); - - // Call the underlying WASM function - let result = self.func.call(store, &wasm_values)?; - - // Convert the Vec<WasmValue> back to R - R::from_wasm_values(&result) - } - - /// Call a typed function and return a resumable execution handle. - /// - /// The handle keeps a mutable borrow of the [`Store`] until completion. - /// - /// ## Example - /// - /// ```rust - /// # fn main() -> tinywasm::Result<()> { - /// use tinywasm::{ExecProgress, ModuleInstance, Store}; - /// - /// let wasm = include_bytes!("../../../examples/wasm/add.wasm"); - /// let module = tinywasm::parse_bytes(wasm)?; - /// let mut store = Store::default(); - /// let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - /// let add = instance.func::<(i32, i32), i32>(&store, "add")?; - /// - /// let mut execution = add.call_resumable(&mut store, (20, 22))?; - /// assert!(matches!(execution.resume_with_fuel(0)?, ExecProgress::Suspended)); - /// assert!(matches!(execution.resume_with_fuel(16)?, ExecProgress::Completed(42))); - /// # Ok(()) - /// # } - /// ``` - pub fn call_resumable<'store>(&self, store: &'store mut Store, params: P) -> Result<FuncExecutionTyped<'store, R>> { - let wasm_values = params.into_wasm_values(); - let execution = self.func.call_resumable(store, &wasm_values)?; - Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }) - } -} - -impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { - /// Resume typed execution with up to `fuel` units of fuel. - /// - /// Fuel is accounted in chunks, so execution may overshoot the requested - /// fuel before returning [`ExecProgress::Suspended`]. - pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<R>> { - match self.execution.resume_with_fuel(fuel)? { - ExecProgress::Completed(values) => Ok(ExecProgress::Completed(R::from_wasm_values(&values)?)), - ExecProgress::Suspended => Ok(ExecProgress::Suspended), - } - } - - #[cfg(feature = "std")] - /// Resume typed execution for at most `time_budget` wall-clock time. - /// - /// Time is checked periodically, so execution may overshoot the requested - /// time budget before returning [`ExecProgress::Suspended`]. - pub fn resume_with_time_budget(&mut self, time_budget: crate::std::time::Duration) -> Result<ExecProgress<R>> { - match self.execution.resume_with_time_budget(time_budget)? { - ExecProgress::Completed(values) => Ok(ExecProgress::Completed(R::from_wasm_values(&values)?)), - ExecProgress::Suspended => Ok(ExecProgress::Suspended), - } - } -} - -/// Describes the WebAssembly value types produced by a Rust value or tuple shape. -pub trait ToWasmTypes { - /// Static WebAssembly types for this shape. - /// - /// Implementations that require runtime construction may set this to `None`, - /// but must then override [`Self::wasm_types`]. - const WASM_TYPES: Option<&'static [WasmType]>; - - /// Return the flattened WebAssembly value types for this tuple shape. - fn wasm_types() -> Cow<'static, [WasmType]> { - Cow::Borrowed(Self::WASM_TYPES.expect("dynamic ToWasmTypes implementation must override wasm_types")) - } -} - -/// Describes the WebAssembly value types produced by a scalar Rust type. -pub trait ToWasmType { - /// The single WebAssembly value type for this scalar type. - const WASM_TYPE: WasmType; -} - -macro_rules! impl_scalar_wasm_traits { - ($($T:ty => $val_ty:expr),+ $(,)?) => { - $( - impl ToWasmType for $T { - const WASM_TYPE: WasmType = $val_ty; - } - - impl ToWasmTypes for $T { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$val_ty]); - } - - impl IntoWasmValues for $T { - #[inline] - fn into_wasm_values(self) -> Vec<WasmValue> { - vec![self.into()] - } - } - - impl FromWasmValues for $T { - #[inline] - fn from_wasm_values(values: &[WasmValue]) -> Result<Self> { - let value = *values.first().ok_or_else(|| { - core::hint::cold_path(); - Error::other("Not enough elements in &[WasmValue]") - })?; - - <$T>::try_from(value).map_err(|e| { - core::hint::cold_path(); - Error::Other(format!( - "FromWasmValues: Could not convert WasmValue to expected type: {e:?}" - )) - }) - } - } - )+ - }; -} - -macro_rules! impl_tuple_traits { - ($($T:ident),+) => { - impl<$($T),+> ToWasmTypes for ($($T,)+) - where - $($T: ToWasmType,)+ - { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$($T::WASM_TYPE,)+]); - } - - impl<$($T),+> IntoWasmValues for ($($T,)+) - where - $($T: Into<WasmValue>,)+ - { - #[allow(non_snake_case)] - #[inline] - fn into_wasm_values(self) -> Vec<WasmValue> { - let ($($T,)+) = self; - vec![$($T.into(),)+] - } - } - - impl<$($T),+> FromWasmValues for ($($T,)+) - where - $($T: TryFrom<WasmValue, Error = ()>,)+ - { - #[inline] - fn from_wasm_values(values: &[WasmValue]) -> Result<Self> { - let mut iter = values.iter(); - - Ok(($( - $T::try_from(*iter.next().ok_or(Error::other("Not enough values in WasmValue vector"))?) - .map_err(|e| Error::Other(format!("FromWasmValues: Could not convert WasmValue to expected type: {e:?}")))?, - )+)) - } - } - } -} - -macro_rules! impl_tuple { - ($macro:ident) => { - $macro!(T1); - $macro!(T1, T2); - $macro!(T1, T2, T3); - $macro!(T1, T2, T3, T4); - $macro!(T1, T2, T3, T4, T5); - $macro!(T1, T2, T3, T4, T5, T6); - $macro!(T1, T2, T3, T4, T5, T6, T7); - $macro!(T1, T2, T3, T4, T5, T6, T7, T8); - $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9); - $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); - $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); - $macro!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); - }; -} - -impl_scalar_wasm_traits!( - i32 => WasmType::I32, - i64 => WasmType::I64, - f32 => WasmType::F32, - f64 => WasmType::F64, - FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF), - ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF), -); -impl_tuple!(impl_tuple_traits); - -/// A helper type for using tuples of arbitrary number of elements as function parameters or results, -/// by concatenating the Wasm types of each element. -/// -/// This is useful when a function signature exceeds tuple arity 12. `tinywasm` only implements -/// direct tuple conversions up to arity 12, but `WasmTupleChain` lets you describe longer -/// signatures by combining smaller tuples at the type level. -/// -/// ## Example -/// ```rust -/// # fn main() -> tinywasm::Result<()> { -/// # use tinywasm::{ModuleInstance, Store, WasmTupleChain}; -/// # let wasm = wat::parse_str(r#" -/// # (module -/// # (func (export "echo13") -/// # (param i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32) -/// # (result i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32) -/// # local.get 0 -/// # local.get 1 -/// # local.get 2 -/// # local.get 3 -/// # local.get 4 -/// # local.get 5 -/// # local.get 6 -/// # local.get 7 -/// # local.get 8 -/// # local.get 9 -/// # local.get 10 -/// # local.get 11 -/// # local.get 12) -/// # ) -/// # "#).expect("valid wat"); -/// # let module = tinywasm::parse_bytes(&wasm)?; -/// # let mut store = Store::default(); -/// # let instance = ModuleInstance::instantiate(&mut store, &module, None)?; -/// -/// type Params = -/// WasmTupleChain<(i32, i32, i32, i32, i32, i32), (i32, i32, i32, i32, i32, i32, i32)>; -/// type Results = -/// WasmTupleChain<(i32, i32, i32, i32, i32, i32), (i32, i32, i32, i32, i32, i32, i32)>; -/// -/// let echo13 = instance.func::<Params, Results>(&store, "echo13")?; -/// let result = echo13.call(&mut store, ((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12, 13)).into())?; -/// assert_eq!(result.into_inner(), ((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12, 13))); -/// # Ok(()) -/// # } -/// ``` -#[derive(Default)] -pub struct WasmTupleChain<T1, T2>(T1, T2); - -impl<T1, T2> WasmTupleChain<T1, T2> { - /// Create a new concatenated tuple wrapper. - pub const fn new(left: T1, right: T2) -> Self { - Self(left, right) - } - - /// Split the wrapper back into its two component values. - pub fn into_inner(self) -> (T1, T2) { - (self.0, self.1) - } -} - -impl<T1, T2> From<(T1, T2)> for WasmTupleChain<T1, T2> { - fn from((left, right): (T1, T2)) -> Self { - Self::new(left, right) - } -} - -impl<T1: ToWasmTypes, T2: ToWasmTypes> ToWasmTypes for WasmTupleChain<T1, T2> { - const WASM_TYPES: Option<&'static [WasmType]> = None; - - #[inline] - fn wasm_types() -> Cow<'static, [WasmType]> { - let mut types = Vec::new(); - types.extend_from_slice(&T1::wasm_types()); - types.extend_from_slice(&T2::wasm_types()); - Cow::Owned(types) - } -} - -impl<T1: IntoWasmValues, T2: IntoWasmValues> IntoWasmValues for WasmTupleChain<T1, T2> { - #[inline] - fn into_wasm_values(self) -> Vec<WasmValue> { - let (left, right) = self.into_inner(); - let mut values = Vec::new(); - values.extend(left.into_wasm_values()); - values.extend(right.into_wasm_values()); - values - } -} - -impl<T1: FromWasmValues + ToWasmTypes, T2: FromWasmValues> FromWasmValues for WasmTupleChain<T1, T2> { - #[inline] - fn from_wasm_values(values: &[WasmValue]) -> Result<Self> { - let left_len = T1::wasm_types().len(); - let left = T1::from_wasm_values(&values[..values.len().min(left_len)])?; - let right = T2::from_wasm_values(values.get(left_len..).unwrap_or(&[]))?; - Ok(Self::new(left, right)) - } -} - -impl ToWasmTypes for () { - const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]); -} - -impl IntoWasmValues for () { - #[inline] - fn into_wasm_values(self) -> Vec<WasmValue> { - vec![] - } -} - -impl FromWasmValues for () { - #[inline] - fn from_wasm_values(_values: &[WasmValue]) -> Result<Self> { - Ok(()) - } -} diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs new file mode 100644 index 0000000..95a2cec --- /dev/null +++ b/crates/tinywasm/src/func/context.rs @@ -0,0 +1,151 @@ +use alloc::vec::Vec; +use tinywasm_types::{ModuleInstanceId, WasmValue}; + +use crate::{Error, FromWasmValues, Function, FunctionTyped, IntoWasmValues, Result}; + +/// The context of a host-function call +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +pub struct FuncContext<'a> { + pub(crate) store: &'a mut crate::Store, + pub(crate) module_id: ModuleInstanceId, +} + +impl FuncContext<'_> { + /// Get the store. + pub fn store(&self) -> &crate::Store { + self.store + } + + /// Get mutable access to the store. + pub fn store_mut(&mut self) -> &mut crate::Store { + self.store + } + + /// Get the module instance. + pub fn module(&self) -> crate::ModuleInstance { + self.store + .get_module_instance(self.module_id) + .unwrap_or_else(|| unreachable!("invalid module instance id in host function context: {}", self.module_id)) + .clone() + } + + /// Get a memory export. + pub fn memory(&self, name: &str) -> Result<crate::Memory> { + self.module().memory(name) + } + + /// Get any exported extern value by name. + pub fn extern_item(&self, name: &str) -> Result<crate::ExternItem> { + self.module().extern_item(name) + } + + /// Get a table export. + pub fn table(&self, name: &str) -> Result<crate::Table> { + self.module().table(name) + } + + /// Get the value of a global export. + pub fn global_get(&self, name: &str) -> Result<WasmValue> { + self.module().global_get(self.store, name) + } + + /// Get a global export. + pub fn global(&self, name: &str) -> Result<crate::Global> { + self.module().global(name) + } + + /// Set the value of a mutable global export. + pub fn global_set(&mut self, name: &str, value: WasmValue) -> Result<()> { + self.module().global_set(self.store, name, value) + } + + /// Charge additional fuel from the currently running resumable invocation. + /// + /// This is a no-op when the current invocation is not using fuel-based + /// resumption. + pub fn charge_fuel(&mut self, fuel: u32) { + self.store.execution_fuel = self.store.execution_fuel.saturating_sub(fuel); + } + + /// Get remaining fuel for the current invocation. + /// + /// Returns `0` when fuel-based resumption is not active. + pub fn remaining_fuel(&self) -> u32 { + self.store.execution_fuel + } + + /// Call a function from within the current host-function invocation. + /// + /// This is the safe way for host functions to perform blocking reentrant + /// calls into Wasm. Unlike [`Function::call`], it preserves the active + /// invocation's stacks and resumes the host caller after the nested call + /// completes. + /// + /// Nested calls are currently blocking only. If the surrounding invocation + /// is resumed with fuel or a time budget, this method does not suspend and + /// later continue the host function in the middle of the nested call. + pub fn call_untyped(&mut self, func: &Function, args: &[WasmValue]) -> Result<Vec<WasmValue>> { + if !self.store.execution_active { + return Err(Error::other("FuncContext::call requires an active host-function invocation")); + } + + func.item.validate_store(self.store)?; + func.validate_params(self.store, args)?; + + let call_stack_base = self.store.call_stack.len(); + let value_stack_base = self.store.value_stack.base(); + func.call_untyped(self.store, args, call_stack_base, value_stack_base) + } + + /// Call a typed function from within the current host-function invocation. + /// + /// See [`Self::call_untyped`] for reentrancy and resumable-execution + /// limitations. + pub fn call<P, R>(&mut self, func: &FunctionTyped<P, R>, params: P) -> Result<R> + where + P: IntoWasmValues, + R: FromWasmValues, + { + if !self.store.execution_active { + return Err(Error::other("FuncContext::call requires an active host-function invocation")); + } + func.func.item.validate_store(self.store)?; + let func_instance = self.store.state.get_func(func.func.addr()).clone(); + if matches!(&func_instance.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + let params = params.into_wasm_values().collect::<Vec<_>>(); + let results = self.call_untyped(&func.func, ¶ms)?; + let mut values = results.into_iter(); + let result = R::from_wasm_values(&mut values)?; + return if values.next().is_none() { + Ok(result) + } else { + Err(Error::other("typed conversion did not consume all WebAssembly values")) + }; + } + + let call_stack_base = self.store.call_stack.len(); + let value_stack_base = self.store.value_stack.base(); + func.func.call_typed(self.store, &func_instance, params.into_wasm_values(), call_stack_base, value_stack_base) + } +} + +impl core::ops::Deref for FuncContext<'_> { + type Target = crate::Store; + + fn deref(&self) -> &Self::Target { + self.store + } +} + +impl core::ops::DerefMut for FuncContext<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.store + } +} + +impl<'a> FuncContext<'a> { + /// Create a new host function context. + pub const fn new(store: &'a mut crate::Store, module_id: ModuleInstanceId) -> Self { + Self { store, module_id } + } +} diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs new file mode 100644 index 0000000..83b17f9 --- /dev/null +++ b/crates/tinywasm/src/func/host.rs @@ -0,0 +1,259 @@ +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType, WasmValue}; + +use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes}; +use crate::{Function, FunctionInstance, Result, Store}; + +/// A reusable host function definition. +#[derive(Clone)] +pub struct HostFunction(Arc<HostFunctionInner>); + +impl HostFunction { + fn instantiate_canonical(&self, store: &mut Store, ty: &FuncType) -> Function { + let type_addr = store.register_host_type(ty); + let addr = store.add_func(FunctionInstance { + type_addr, + gc: store.state.func_gc_metadata(type_addr), + kind: crate::store::FunctionKind::Host(self.clone()), + }); + Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } + } + + /// Instantiates this definition after resolving the importing module's types. + pub(crate) fn instantiate_for_import(&self, store: &mut Store, type_addrs: &[TypeAddr]) -> Result<Function> { + let resolve = |ty: WasmType| -> Result<WasmType> { + let WasmType::Ref(ref_ty) = ty else { return Ok(ty) }; + let Some(module_addr) = ref_ty.type_index() else { return Ok(ty) }; + let canonical = *type_addrs + .get(module_addr as usize) + .ok_or_else(|| crate::Error::other("host function signature contains an invalid concrete type"))?; + Ok(WasmType::Ref( + tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical) + .expect("canonical type addresses fit in references"), + )) + }; + let params = self.0.ty.params().iter().copied().map(resolve).collect::<Result<Vec<_>>>()?; + let results = self.0.ty.results().iter().copied().map(resolve).collect::<Result<Vec<_>>>()?; + Ok(self.instantiate_canonical(store, &FuncType::new(¶ms, &results))) + } + + /// Calls the host function through its untyped value interface. + pub(crate) fn call_values( + &self, + store: &mut Store, + module_id: ModuleInstanceId, + type_addr: TypeAddr, + args: &[WasmValue], + ) -> Result<Vec<WasmValue>> { + let result = match &self.0.callback { + HostCallback::Untyped(func) => func(FuncContext { store, module_id }, args), + HostCallback::Typed(func) => func.call(FuncContext { store, module_id }, args), + }?; + let expected = store.state.get_canonical_func_type(type_addr); + if result.len() == expected.results().len() + && result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty)) + { + Ok(result) + } else { + Err(crate::Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result }) + } + } + + /// Returns the allocation-free typed callback when one is available. + pub(crate) fn typed_callback(&self) -> Option<&dyn TypedHostCallback> { + match &self.0.callback { + HostCallback::Untyped(_) => None, + HostCallback::Typed(func) => Some(&**func), + } + } + + /// Create a directly callable, store-owned function from this definition. + /// + /// The returned [`Function`] can only be used with `store`. + /// + /// Host functions intended as module imports usually do not need to be + /// instantiated manually. Pass the reusable definition to + /// [`crate::Imports::define`] instead. TinyWasm will then match any GC + /// reference types to the module that imports the function. + /// + /// # Errors + /// + /// Returns an error if the signature uses a store-specific reference type + /// that is not registered in `store`. + /// + /// ## Example + /// + /// ```rust + /// # fn main() -> tinywasm::Result<()> { + /// use tinywasm::types::WasmValue; + /// use tinywasm::{HostFunction, Store}; + /// + /// let mut store = Store::default(); + /// let add_one = HostFunction::from(|_ctx, value: i32| Ok(value + 1)); + /// let function = add_one.instantiate(&mut store)?; + /// + /// assert_eq!(function.call(&mut store, &[WasmValue::I32(41)])?, [WasmValue::I32(42)]); + /// # Ok(()) + /// # } + /// ``` + pub fn instantiate(&self, store: &mut Store) -> Result<Function> { + if self + .0 + .ty + .params() + .iter() + .chain(self.0.ty.results()) + .filter_map(|ty| match ty { + WasmType::Ref(ty) => ty.type_index(), + _ => None, + }) + .any(|type_addr| type_addr as usize >= store.state.canonical_types.len()) + { + return Err(crate::Error::other("host function signature contains a concrete type from another store")); + } + Ok(self.instantiate_canonical(store, &self.0.ty)) + } + + /// Create a new untyped host function. + /// + /// To call Wasm from inside the callback, use [`FuncContext::call`] or + /// [`FuncContext::call_untyped`]. + /// + /// ## Example + /// ```rust + /// # fn main() -> tinywasm::Result<()> { + /// # use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; + /// # use tinywasm::types::{FuncType, WasmType, WasmValue}; + /// # let wasm = wat::parse_str(r#" + /// # (module + /// # (import "host" "add_one" (func $add_one (param i32) (result i32))) + /// # (func (export "call") (param i32) (result i32) + /// # local.get 0 + /// # call $add_one)) + /// # "#).expect("valid wat"); + /// # let module = tinywasm::parse_bytes(&wasm)?; + /// let mut store = Store::default(); + /// let ty = FuncType::new(&[WasmType::I32], &[WasmType::I32]); + /// let add_one = HostFunction::from_untyped(&ty, |_ctx: FuncContext<'_>, args| { + /// let WasmValue::I32(value) = args[0] else { + /// return Err(tinywasm::Error::Other("expected i32".into())); + /// }; + /// Ok(vec![WasmValue::I32(value + 1)]) + /// }); + /// + /// let mut imports = Imports::new(); + /// imports.define("host", "add_one", add_one); + /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + /// # let call = instance.func::<i32, i32>(&store, "call")?; + /// # assert_eq!(call.call(&mut store, 41)?, 42); + /// # Ok(()) + /// # } + /// ``` + pub fn from_untyped( + ty: &FuncType, + func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + Send + Sync + 'static, + ) -> Self { + Self(Arc::new(HostFunctionInner { ty: ty.clone(), callback: HostCallback::Untyped(Box::new(func)) })) + } + + /// Create a new typed host function. + /// + /// To call Wasm from inside the callback, use [`FuncContext::call`] or + /// [`FuncContext::call_untyped`]. + /// + /// ## Example + /// ```rust + /// # fn main() -> tinywasm::Result<()> { + /// # use tinywasm::{HostFunction, Imports, ModuleInstance, Store}; + /// # let wasm = wat::parse_str(r#" + /// # (module + /// # (import "host" "add_one" (func $add_one (param i32) (result i32))) + /// # (func (export "call") (param i32) (result i32) + /// # local.get 0 + /// # call $add_one)) + /// # "#).expect("valid wat"); + /// # let module = tinywasm::parse_bytes(&wasm)?; + /// let mut store = Store::default(); + /// let add_one = HostFunction::from(|_ctx, value: i32| Ok(value + 1)); + /// + /// let mut imports = Imports::new(); + /// imports.define("host", "add_one", add_one); + /// # let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + /// # let call = instance.func::<i32, i32>(&store, "call")?; + /// # assert_eq!(call.call(&mut store, 41)?, 42); + /// # Ok(()) + /// # } + /// ``` + pub fn from<P, R>(func: impl Fn(FuncContext<'_>, P) -> Result<R> + Send + Sync + 'static) -> Self + where + P: FromWasmValues + ToWasmTypes + 'static, + R: IntoWasmValues + ToWasmTypes + 'static, + { + let ty = FuncType::new(&P::wasm_types(), &R::wasm_types()); + let func = TypedHostCallbackImpl { func, marker: core::marker::PhantomData }; + Self(Arc::new(HostFunctionInner { ty, callback: HostCallback::Typed(Box::new(func)) })) + } +} + +struct HostFunctionInner { + ty: FuncType, + callback: HostCallback, +} + +enum HostCallback { + Untyped(Box<UntypedHostCallback>), + Typed(Box<dyn TypedHostCallback>), +} + +type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result<Vec<WasmValue>> + Send + Sync; + +pub(crate) trait TypedHostCallback: Send + Sync { + fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result<Vec<WasmValue>>; + fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()>; +} + +struct TypedHostCallbackImpl<F, P, R> { + func: F, + marker: core::marker::PhantomData<fn(P) -> R>, +} + +impl<F, P, R> TypedHostCallback for TypedHostCallbackImpl<F, P, R> +where + F: Fn(FuncContext<'_>, P) -> Result<R> + Send + Sync, + P: FromWasmValues, + R: IntoWasmValues, +{ + fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result<Vec<WasmValue>> { + let mut values = args.iter().copied(); + let params = P::from_wasm_values(&mut values)?; + if values.next().is_some() { + return Err(crate::Error::other("typed conversion did not consume all WebAssembly values")); + } + Ok((self.func)(ctx, params)?.into_wasm_values().collect()) + } + + fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()> { + let params = store.state.get_canonical_func_type(type_addr).params(); + let base = store.value_stack.base_before(params.iter().collect()); + let mut values = store.value_stack.wasm_values(&store.state, params, base, true); + let params = P::from_wasm_values(&mut values).and_then(|params| { + if values.next().is_some() { + Err(crate::Error::other("typed conversion did not consume all WebAssembly values")) + } else { + Ok(params) + } + }); + drop(values); + store.value_stack.truncate_to_base(base); + let params = params?; + let result = (self.func)(FuncContext { store, module_id }, params)?; + store.push_typed_values::<true>(type_addr, result.into_wasm_values(), base) + } +} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for HostFunction { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("HostFunction").field("ty", &self.0.ty).finish_non_exhaustive() + } +} diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs new file mode 100644 index 0000000..34a1938 --- /dev/null +++ b/crates/tinywasm/src/func/mod.rs @@ -0,0 +1,201 @@ +use crate::interpreter::stack::{CallFrame, StackBase}; +use crate::reference::StoreItem; +use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store}; +use alloc::{format, vec::Vec}; +use core::hint::cold_path; +use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId, WasmValue}; + +mod context; +mod host; +mod resume; +mod values; +pub use context::FuncContext; +pub use host::HostFunction; +pub use resume::{ExecProgress, FuncExecution, FuncExecutionTyped}; +#[allow(deprecated)] +pub use values::WasmTupleChain; +pub use values::{FromWasmValues, IntoWasmValues, ToWasmType, ToWasmTypes}; + +/// A function handle +#[derive(Clone)] +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +pub struct Function { + pub(crate) item: StoreItem, + pub(crate) module_id: ModuleInstanceId, +} + +impl Function { + #[inline] + /// Returns the function's address in its store. + pub(crate) const fn addr(&self) -> FuncAddr { + self.item.addr + } + + /// Get this function's canonical type from its store. + /// + /// Concrete reference types are only meaningful in this store. + pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { + self.item.validate_store(store)?; + Ok(store.state.get_func_type(self.addr())) + } + + /// Call a function (Invocation) + /// + /// See <https://webassembly.github.io/spec/core/exec/modules.html#invocation> + #[inline] + pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result<Vec<WasmValue>> { + self.item.validate_store(store)?; + self.validate_params(store, params)?; + + store.enter_execution()?; + store.call_stack.clear(); + store.value_stack.clear(); + let result = self.call_untyped(store, params, 0, StackBase::default()); + store.exit_execution(); + result + } + + fn validate_params(&self, store: &Store, params: &[WasmValue]) -> Result<()> { + let func_ty = store.state.get_func_type(self.addr()); + if func_ty.params().len() != params.len() { + cold_path(); + return Err(Error::Other(format!( + "param count mismatch: expected {}, got {}", + func_ty.params().len(), + params.len() + ))); + } + + if !func_ty.params().iter().zip(params).all(|(ty, param)| store.state.value_matches_type(*param, *ty)) { + cold_path(); + #[cfg(feature = "debug")] + return Err(Error::Other(format!( + "param type mismatch: expected {:?}, got {:?}", + func_ty.params(), + params.iter().map(|v| v.ty()).collect::<Vec<_>>() + ))); + #[cfg(not(feature = "debug"))] + return Err(Error::Other("param type mismatch".into())); + } + Ok(()) + } + + #[inline] + fn call_untyped( + &self, + store: &mut Store, + params: &[WasmValue], + call_stack_base: u32, + value_stack_base: StackBase, + ) -> Result<Vec<WasmValue>> { + let instance = store.state.get_func(self.addr()); + let type_addr = instance.type_addr; + let results_may_gc = instance.gc.results; + let result = match &instance.kind { + crate::store::FunctionKind::Host(host) => { + let host = host.clone(); + host.call_values(store, self.module_id, type_addr, params) + } + crate::store::FunctionKind::Wasm(wasm) => { + let wasm_params = wasm.func.params; + let wasm_locals = wasm.func.locals; + let locals_base = + store.value_stack.enter_wasm_call(params, wasm_params, wasm_locals, value_stack_base)?; + let callframe = CallFrame::new(self.addr(), locals_base, wasm_locals); + InterpreterRuntime::exec(store, callframe, call_stack_base).inspect_err(|_| { + store.call_stack.truncate_to(call_stack_base); + store.value_stack.truncate_to_base(value_stack_base); + })?; + let result_types = store.state.get_canonical_func_type(type_addr).results(); + Ok(store.value_stack.pop_wasmvalues(&store.state, result_types)) + } + }; + if results_may_gc && let Ok(values) = &result { + store.state.pin_host_values(values); + } + result + } + + fn prepare_typed( + &self, + store: &mut Store, + instance: &FunctionInstance, + params: impl Iterator<Item = WasmValue>, + stack_base: StackBase, + ) -> Result<Option<CallFrame>> { + store.push_typed_values::<false>(instance.type_addr, params, stack_base)?; + match &instance.kind { + crate::store::FunctionKind::Wasm(wasm) => { + let locals_base = store + .value_stack + .enter_locals(&wasm.func.params, &wasm.func.locals) + .inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?; + Ok(Some(CallFrame::new(self.addr(), locals_base, wasm.func.locals))) + } + crate::store::FunctionKind::Host(host) => { + host.typed_callback() + .expect("typed host function") + .call_stack(store, self.module_id, instance.type_addr) + .inspect_err(|_| store.value_stack.truncate_to_base(stack_base))?; + Ok(None) + } + } + } + + #[inline] + fn call_typed<R: FromWasmValues>( + &self, + store: &mut Store, + instance: &FunctionInstance, + params: impl Iterator<Item = WasmValue>, + call_stack_base: u32, + value_stack_base: StackBase, + ) -> Result<R> { + if let Some(callframe) = self.prepare_typed(store, instance, params, value_stack_base)? { + InterpreterRuntime::exec(store, callframe, call_stack_base).inspect_err(|_| { + store.call_stack.truncate_to(call_stack_base); + store.value_stack.truncate_to_base(value_stack_base); + })?; + } + store.take_typed_results(instance.type_addr, value_stack_base, instance.gc.results) + } +} + +/// A typed function handle. +/// +/// Parameter and result tuples are supported up to arity 20. Use +/// [`crate::ModuleInstance::func_untyped`] for larger signatures. +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +pub struct FunctionTyped<P, R> { + /// The underlying function handle + pub func: Function, + pub(crate) marker: core::marker::PhantomData<(P, R)>, +} + +impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> { + /// Call a typed function + pub fn call(&self, store: &mut Store, params: P) -> Result<R> { + self.func.item.validate_store(store)?; + let func = store.state.get_func(self.func.addr()).clone(); + if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + let params = params.into_wasm_values().collect::<Vec<_>>(); + let result = self.func.call(store, ¶ms)?; + let mut values = result.into_iter(); + let result = R::from_wasm_values(&mut values)?; + return if values.next().is_none() { + Ok(result) + } else { + Err(Error::other("typed conversion did not consume all WebAssembly values")) + }; + } + + store.enter_execution()?; + let result: Result<R> = { + store.call_stack.clear(); + store.value_stack.clear(); + self.func.call_typed(store, &func, params.into_wasm_values(), 0, StackBase::default()) + }; + store.exit_execution(); + result + } +} diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs new file mode 100644 index 0000000..a71be32 --- /dev/null +++ b/crates/tinywasm/src/func/resume.rs @@ -0,0 +1,265 @@ +use alloc::vec::Vec; +use tinywasm_types::{FuncAddr, TypeAddr, WasmValue}; + +use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues}; +use crate::interpreter::stack::{CallFrame, StackBase}; +use crate::{Error, InterpreterRuntime, Result, Store, Trap}; + +#[derive(Clone, PartialEq, Eq)] +/// Progress for fuel-limited function execution. +pub enum ExecProgress<T> { + /// Execution completed and produced a result. + Completed(T), + /// Execution suspended after exhausting fuel or time budget. + Suspended, +} + +/// Resumable execution for an untyped function call. +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +pub struct FuncExecution<'store> { + store: &'store mut Store, + state: FuncExecutionState, +} + +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +enum FuncExecutionState { + Running { callframe: CallFrame, root_func_addr: FuncAddr }, + Completed(Option<CallResult>), +} + +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +enum CallResult { + Stack { type_addr: TypeAddr, pin_refs: bool }, + Values(Vec<WasmValue>), +} + +/// Resumable execution for a typed function call. +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +pub struct FuncExecutionTyped<'store, R> { + execution: FuncExecution<'store>, + marker: core::marker::PhantomData<R>, +} + +impl Function { + /// Call a function and return a resumable execution handle. + /// + /// The returned handle keeps a mutable borrow of the [`Store`] until it + /// completes. Use [`FuncExecution::resume_with_fuel`] (or + /// `resume_with_time_budget` with `std`) to continue. + pub fn call_resumable<'store>( + &self, + store: &'store mut Store, + params: &[WasmValue], + ) -> Result<FuncExecution<'store>> { + self.item.validate_store(store)?; + self.validate_params(store, params)?; + let results_may_gc = store.state.get_func(self.addr()).gc.results; + + store.enter_execution()?; + let result: Result<FuncExecutionState> = (|| { + let func_instance = store.state.get_func(self.addr()).clone(); + match &func_instance.kind { + crate::store::FunctionKind::Host(host_func) => { + let result = + host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params)?; + Ok(FuncExecutionState::Completed(Some(CallResult::Values(result)))) + } + crate::store::FunctionKind::Wasm(wasm_func) => { + store.call_stack.clear(); + store.value_stack.clear(); + let locals = wasm_func.func.locals; + let locals_base = store.value_stack.enter_wasm_call( + params, + wasm_func.func.params, + locals, + StackBase::default(), + )?; + let callframe = CallFrame::new(self.addr(), locals_base, locals); + + Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() }) + } + } + })(); + store.exit_execution(); + + let state = result?; + if results_may_gc && let FuncExecutionState::Completed(Some(CallResult::Values(values))) = &state { + store.state.pin_host_values(values); + } + Ok(FuncExecution { store, state }) + } +} + +impl<'store> FuncExecution<'store> { + fn resume_raw( + &mut self, + run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>, + ) -> Result<ExecProgress<CallResult>> { + let (callframe, root_func_addr) = match &mut self.state { + FuncExecutionState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), + FuncExecutionState::Completed(result) => { + return result + .take() + .map(ExecProgress::Completed) + .ok_or_else(|| Error::other("execution already completed")); + } + }; + + self.store.enter_execution()?; + let result = run(self.store, callframe); + self.store.exit_execution(); + + match result? { + crate::interpreter::ExecState::Completed => { + let func = self.store.state.get_func(root_func_addr); + let result_ty = func.type_addr; + let results_may_gc = func.gc.results; + self.state = FuncExecutionState::Completed(None); + Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty, pin_refs: results_may_gc })) + } + crate::interpreter::ExecState::Suspended(callframe) => { + let FuncExecutionState::Running { callframe: current, .. } = &mut self.state else { + unreachable!("invalid function execution state") + }; + *current = callframe; + Ok(ExecProgress::Suspended) + } + } + } + + fn resume( + &mut self, + run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>, + ) -> Result<ExecProgress<Vec<WasmValue>>> { + match self.resume_raw(run)? { + ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => { + let types = self.store.state.get_canonical_func_type(type_addr).results(); + let values = self.store.value_stack.pop_wasmvalues(&self.store.state, types); + if pin_refs { + self.store.state.pin_host_values(&values); + } + Ok(ExecProgress::Completed(values)) + } + ExecProgress::Completed(CallResult::Values(values)) => Ok(ExecProgress::Completed(values)), + ExecProgress::Suspended => Ok(ExecProgress::Suspended), + } + } + + /// Resume execution with up to `fuel` units of fuel. + /// + /// Fuel is accounted in chunks, so execution may overshoot the requested + /// fuel before returning [`ExecProgress::Suspended`] (currently the chunk size is 128 instructions between fuel checks, but this may change in the future). + /// + /// Returns [`ExecProgress::Suspended`] when fuel is exhausted, or + /// [`ExecProgress::Completed`] with the final values once the invocation + /// returns. + /// + /// Reentrant calls made by host functions through [`crate::FuncContext::call`] are + /// currently blocking. They do not suspend and later resume the host + /// function in the middle of the nested call. + pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<Vec<WasmValue>>> { + self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel)) + } + + #[cfg(feature = "std")] + /// Resume execution for at most `time_budget` wall-clock time. + /// + /// Time is checked periodically, so execution may overshoot the requested + /// time budget before returning [`ExecProgress::Suspended`] (currently time + /// is checked every 128 instructions, but this may change in the future). + /// + /// Reentrant calls made by host functions through [`crate::FuncContext::call`] + /// are blocking and do not suspend in the middle of the host callback. + pub fn resume_with_time_budget( + &mut self, + time_budget: crate::std::time::Duration, + ) -> Result<ExecProgress<Vec<WasmValue>>> { + self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget)) + } +} + +impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> { + /// Call a typed function and return a resumable execution handle. + /// + /// The handle keeps a mutable borrow of the [`Store`] until completion. + /// + /// ## Example + /// + /// ```rust + /// # fn main() -> tinywasm::Result<()> { + /// use tinywasm::{ExecProgress, ModuleInstance, Store}; + /// + /// let wasm = include_bytes!("../../../../examples/wasm/add.wasm"); + /// let module = tinywasm::parse_bytes(wasm)?; + /// let mut store = Store::default(); + /// let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + /// let add = instance.func::<(i32, i32), i32>(&store, "add")?; + /// + /// let mut execution = add.call_resumable(&mut store, (20, 22))?; + /// assert!(matches!(execution.resume_with_fuel(0)?, ExecProgress::Suspended)); + /// assert!(matches!(execution.resume_with_fuel(16)?, ExecProgress::Completed(42))); + /// # Ok(()) + /// # } + /// ``` + pub fn call_resumable<'store>(&self, store: &'store mut Store, params: P) -> Result<FuncExecutionTyped<'store, R>> { + self.func.item.validate_store(store)?; + let func = store.state.get_func(self.func.addr()).clone(); + if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { + let params = params.into_wasm_values().collect::<Vec<_>>(); + let execution = self.func.call_resumable(store, ¶ms)?; + return Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }); + } + + store.enter_execution()?; + let result: Result<FuncExecutionState> = (|| { + store.call_stack.clear(); + store.value_stack.clear(); + match self.func.prepare_typed(store, &func, params.into_wasm_values(), StackBase::default())? { + Some(callframe) => Ok(FuncExecutionState::Running { callframe, root_func_addr: self.func.addr() }), + None => Ok(FuncExecutionState::Completed(Some(CallResult::Stack { + type_addr: func.type_addr, + pin_refs: func.gc.results, + }))), + } + })(); + store.exit_execution(); + let execution = FuncExecution { store, state: result? }; + Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }) + } +} + +impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { + fn resume( + &mut self, + run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>, + ) -> Result<ExecProgress<R>> { + match self.execution.resume_raw(run)? { + ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => Ok(ExecProgress::Completed( + self.execution.store.take_typed_results(type_addr, StackBase::default(), pin_refs)?, + )), + ExecProgress::Completed(CallResult::Values(values)) => { + let mut values = values.into_iter(); + let result = R::from_wasm_values(&mut values)?; + if values.next().is_some() { + return Err(Error::other("typed conversion did not consume all WebAssembly values")); + } + Ok(ExecProgress::Completed(result)) + } + ExecProgress::Suspended => Ok(ExecProgress::Suspended), + } + } + + /// Resume typed execution with up to `fuel` units of fuel. + pub fn resume_with_fuel(&mut self, fuel: u32) -> Result<ExecProgress<R>> { + self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel)) + } + + #[cfg(feature = "std")] + /// Resume typed execution for at most `time_budget` wall-clock time. + /// + /// Time is checked periodically, so execution may overshoot the requested + /// time budget before returning [`ExecProgress::Suspended`]. + pub fn resume_with_time_budget(&mut self, time_budget: crate::std::time::Duration) -> Result<ExecProgress<R>> { + self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget)) + } +} diff --git a/crates/tinywasm/src/func/values.rs b/crates/tinywasm/src/func/values.rs new file mode 100644 index 0000000..319b493 --- /dev/null +++ b/crates/tinywasm/src/func/values.rs @@ -0,0 +1,201 @@ +use crate::{Error, Result}; +use alloc::{borrow::Cow, vec::Vec}; +use tinywasm_types::{ExternRef, FuncRef, WasmType, WasmValue}; + +/// Convert a Rust value or tuple into WebAssembly values. +pub trait IntoWasmValues { + /// Return the flattened WebAssembly values. + fn into_wasm_values(self) -> impl Iterator<Item = WasmValue>; +} + +/// Convert WebAssembly values into a Rust value or tuple. +pub trait FromWasmValues: Sized { + /// Read this value from a flattened WebAssembly value iterator. + fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self>; +} + +/// Describes the WebAssembly value types produced by a Rust value or tuple shape. +pub trait ToWasmTypes { + /// Static WebAssembly types for this shape. + /// + /// Implementations that require runtime construction may set this to `None`, + /// but must then override [`Self::wasm_types`]. + const WASM_TYPES: Option<&'static [WasmType]>; + + /// Return the flattened WebAssembly value types for this tuple shape. + fn wasm_types() -> Cow<'static, [WasmType]> { + Cow::Borrowed(Self::WASM_TYPES.expect("dynamic ToWasmTypes implementation must override wasm_types")) + } +} + +/// Describes the WebAssembly value types produced by a scalar Rust type. +pub trait ToWasmType { + /// The single WebAssembly value type for this scalar type. + const WASM_TYPE: WasmType; +} + +fn next_value<T: TryFrom<WasmValue, Error = ()>>(values: &mut impl Iterator<Item = WasmValue>) -> Result<T> { + let value = values.next().ok_or_else(|| { + core::hint::cold_path(); + Error::other("not enough WebAssembly values") + })?; + T::try_from(value).map_err(|_| { + core::hint::cold_path(); + Error::other("WebAssembly value does not match the expected type") + }) +} + +macro_rules! impl_scalar_wasm_traits { + ($($T:ty => $val_ty:expr),+ $(,)?) => { + $( + impl ToWasmType for $T { + const WASM_TYPE: WasmType = $val_ty; + } + + impl ToWasmTypes for $T { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$val_ty]); + } + + impl IntoWasmValues for $T { + #[inline] + fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> { + core::iter::once(self.into()) + } + } + + impl FromWasmValues for $T { + #[inline] + fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { + next_value(values) + } + } + )+ + }; +} + +macro_rules! impl_tuple_traits { + (@next $head:ident, $($tail:ident),+) => { + impl_tuple_traits!($($tail),+); + }; + (@next $head:ident) => {}; + ($($T:ident),+) => { + impl<$($T),+> ToWasmTypes for ($($T,)+) + where + $($T: ToWasmType,)+ + { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[$($T::WASM_TYPE,)+]); + } + + impl<$($T),+> IntoWasmValues for ($($T,)+) + where + $($T: Into<WasmValue>,)+ + { + #[allow(non_snake_case)] + #[inline] + fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> { + let ($($T,)+) = self; + [$($T.into(),)+].into_iter() + } + } + + impl<$($T),+> FromWasmValues for ($($T,)+) + where + $($T: TryFrom<WasmValue, Error = ()>,)+ + { + #[inline] + fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { + Ok(($(next_value::<$T>(values)?,)+)) + } + } + + impl_tuple_traits!(@next $($T),+); + } +} + +impl_scalar_wasm_traits!( + i32 => WasmType::I32, + i64 => WasmType::I64, + f32 => WasmType::F32, + f64 => WasmType::F64, + FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF), + ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF), +); +impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20); + +/// Concatenates two typed parameter or result groups. +/// +/// Direct tuple conversions are supported up to arity 20. Use untyped functions +/// for larger signatures. +#[deprecated(note = "direct tuples are supported up to arity 20, use untyped functions for larger signatures")] +#[derive(Default)] +pub struct WasmTupleChain<T1, T2>(T1, T2); + +#[allow(deprecated)] +impl<T1, T2> WasmTupleChain<T1, T2> { + /// Create a new concatenated tuple wrapper. + pub const fn new(left: T1, right: T2) -> Self { + Self(left, right) + } + + /// Split the wrapper back into its two component values. + pub fn into_inner(self) -> (T1, T2) { + (self.0, self.1) + } +} + +#[allow(deprecated)] +impl<T1, T2> From<(T1, T2)> for WasmTupleChain<T1, T2> { + fn from((left, right): (T1, T2)) -> Self { + Self::new(left, right) + } +} + +#[allow(deprecated)] +impl<T1: ToWasmTypes, T2: ToWasmTypes> ToWasmTypes for WasmTupleChain<T1, T2> { + const WASM_TYPES: Option<&'static [WasmType]> = None; + + #[inline] + fn wasm_types() -> Cow<'static, [WasmType]> { + let mut types = Vec::new(); + types.extend_from_slice(&T1::wasm_types()); + types.extend_from_slice(&T2::wasm_types()); + Cow::Owned(types) + } +} + +#[allow(deprecated)] +impl<T1: IntoWasmValues, T2: IntoWasmValues> IntoWasmValues for WasmTupleChain<T1, T2> { + #[inline] + fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> { + let (left, right) = self.into_inner(); + left.into_wasm_values().chain(right.into_wasm_values()) + } +} + +#[allow(deprecated)] +impl<T1: FromWasmValues, T2: FromWasmValues> FromWasmValues for WasmTupleChain<T1, T2> { + #[inline] + fn from_wasm_values(values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { + let left = T1::from_wasm_values(values)?; + let right = T2::from_wasm_values(values)?; + Ok(Self::new(left, right)) + } +} + +impl ToWasmTypes for () { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]); +} + +impl IntoWasmValues for () { + #[inline] + fn into_wasm_values(self) -> impl Iterator<Item = WasmValue> { + core::iter::empty() + } +} + +impl FromWasmValues for () { + #[inline] + fn from_wasm_values(_values: &mut impl Iterator<Item = WasmValue>) -> Result<Self> { + Ok(()) + } +} diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 6a399ee..a35cf2c 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -1,14 +1,13 @@ use alloc::collections::BTreeMap; use alloc::string::{String, ToString}; use alloc::vec::Vec; -use core::fmt::Debug; use core::hint::cold_path; -use crate::{Function, Global, LinkingError, Memory, Result, Table}; +use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table}; use tinywasm_types::*; #[derive(Clone)] -#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] #[non_exhaustive] /// An external import value. pub enum Extern { @@ -20,43 +19,28 @@ pub enum Extern { Memory(Memory), /// A function import. Function(Function), + /// A reusable host function definition. + HostFunction(HostFunction), } -impl From<Global> for Extern { - fn from(value: Global) -> Self { - Self::Global(value) - } -} - -impl From<Table> for Extern { - fn from(value: Table) -> Self { - Self::Table(value) - } -} - -impl From<Memory> for Extern { - fn from(value: Memory) -> Self { - Self::Memory(value) - } -} - -impl From<Function> for Extern { - fn from(value: Function) -> Self { - Self::Function(value) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)] -/// Name of an import -pub struct ExternName { - module: String, - name: String, +macro_rules! impl_conv { + ($($ty:ty => $variant:ident),* $(,)?) => { + $( + impl From<$ty> for Extern { + fn from(value: $ty) -> Self { + Self::$variant(value) + } + } + )* + }; } -impl From<&Import> for ExternName { - fn from(import: &Import) -> Self { - Self { module: import.module.to_string(), name: import.name.to_string() } - } +impl_conv! { + Global => Global, + Table => Table, + Memory => Memory, + Function => Function, + HostFunction => HostFunction, } /// Imports for a module instance @@ -75,7 +59,7 @@ impl From<&Import> for ExternName { /// # let my_other_instance = ModuleInstance::instantiate(&mut store, &module, None)?; /// let mut imports = Imports::new(); /// -/// let print_i32 = HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, arg: i32| { +/// let print_i32 = HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, arg: i32| { /// log::debug!("print_i32: {}", arg); /// Ok(()) /// }); @@ -101,11 +85,13 @@ impl From<&Import> for ExternName { /// # Ok(()) /// # } /// ``` -/// Now, the imports object can be passed to [`crate::ModuleInstance::instantiate`]. +/// Host function definitions are store-independent, so the imports object can be borrowed by +/// [`crate::ModuleInstance::instantiate`] for multiple stores. +/// TinyWasm also matches GC reference types to each module when it links an imported host function. #[derive(Default, Clone)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct Imports { - externs: BTreeMap<ExternName, Extern>, + externs: BTreeMap<String, BTreeMap<String, Extern>>, modules: BTreeMap<String, crate::ModuleInstance>, } @@ -124,7 +110,9 @@ impl Imports { /// Merge two import sets pub fn merge(mut self, other: Self) -> Self { - self.externs.extend(other.externs); + for (module, externs) in other.externs { + self.externs.entry(module).or_default().extend(externs); + } self.modules.extend(other.modules); self } @@ -138,15 +126,46 @@ impl Imports { } /// Define an import value. + /// + /// A [`Function`], [`Global`], [`Table`], or [`Memory`] handle belongs to + /// one store and can only be imported into that store. A [`HostFunction`] + /// is a reusable definition and can be imported into multiple stores. + /// + /// ## Example + /// + /// ```rust + /// # fn main() -> tinywasm::Result<()> { + /// use tinywasm::{HostFunction, Imports, ModuleInstance, Store}; + /// + /// let wasm = wat::parse_str( + /// r#" + /// (module + /// (import "host" "answer" (func $answer (result i32))) + /// (export "answer" (func $answer))) + /// "#, + /// ) + /// .expect("valid wat"); + /// let module = tinywasm::parse_bytes(&wasm)?; + /// let mut imports = Imports::new(); + /// imports.define("host", "answer", HostFunction::from(|_ctx, ()| Ok(42_i32))); + /// + /// let mut first_store = Store::default(); + /// let first = ModuleInstance::instantiate(&mut first_store, &module, Some(&imports))?; + /// assert_eq!(first.func::<(), i32>(&first_store, "answer")?.call(&mut first_store, ())?, 42); + /// + /// let mut second_store = Store::default(); + /// let second = ModuleInstance::instantiate(&mut second_store, &module, Some(&imports))?; + /// assert_eq!(second.func::<(), i32>(&second_store, "answer")?.call(&mut second_store, ())?, 42); + /// # Ok(()) + /// # } + /// ``` pub fn define(&mut self, module: &str, name: &str, value: impl Into<Extern>) -> &mut Self { - let name = ExternName { module: module.to_string(), name: name.to_string() }; - self.externs.insert(name, value.into()); + self.externs.entry(module.to_string()).or_default().insert(name.to_string(), value.into()); self } pub(crate) fn take_defined(&self, import: &Import) -> Option<Extern> { - let name = ExternName::from(import); - self.externs.get(&name).cloned() + self.externs.get(import.module.as_ref())?.get(import.name.as_ref()).cloned() } fn compare_types<T: PartialEq>(import: &Import, actual: &T, expected: &T) -> Result<()> { @@ -237,10 +256,12 @@ impl Imports { (ExternVal::Memory(memory.0.addr), None) } Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)), + Extern::HostFunction(func) => { + (ExternVal::Func(func.instantiate_for_import(store, type_addrs)?.addr()), None) + } } } else { - let name = ExternName::from(import); - let Some(instance) = self.modules.get(&name.module) else { + let Some(instance) = self.modules.get(import.module.as_ref()) else { cold_path(); return Err(LinkingError::unknown_import(import).into()); }; diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index be38419..52bb948 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -45,7 +45,7 @@ pub struct ModuleInstance(Rc<ModuleInstanceInner>); #[cfg_attr(feature = "debug", derive(Debug))] struct ModuleInstanceInner { - store_id: usize, + store_id: u32, id: ModuleInstanceId, type_addrs: Box<[TypeAddr]>, func_addrs: Box<[FuncAddr]>, @@ -117,7 +117,7 @@ impl ModuleInstance { /// Instantiate the module in the given store /// /// See <https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation> - pub fn instantiate(store: &mut Store, module: &Module, imports: Option<Imports>) -> Result<Self> { + pub fn instantiate(store: &mut Store, module: &Module, imports: Option<&Imports>) -> Result<Self> { let instance = ModuleInstance::instantiate_no_start(store, module, imports)?; let _ = instance.start(store)?; Ok(instance) @@ -150,15 +150,13 @@ impl ModuleInstance { /// ``` /// /// See <https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation> - pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option<Imports>) -> Result<Self> { + pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option<&Imports>) -> Result<Self> { let type_addrs = store.register_module_types(&module.types); let id = store.next_module_instance_id(); - let mut addrs = imports.unwrap_or_default().link(store, module, &type_addrs)?; - let local_type_addrs = module.func_type_idxs[addrs.funcs.len()..] - .iter() - .map(|&addr| type_addrs[addr as usize]) - .collect::<Box<[_]>>(); - addrs.funcs.extend(store.init_funcs(&module.funcs, id, &local_type_addrs)); + let default_imports = Imports::default(); + let mut addrs = imports.unwrap_or(&default_imports).link(store, module, &type_addrs)?; + let imported_funcs = addrs.funcs.len(); + addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); match module.local_memory_allocation { LocalMemoryAllocation::Skip => { #[cfg(feature = "guest-debug")] @@ -246,13 +244,10 @@ impl ModuleInstance { pub fn exports(&self) -> impl Iterator<Item = (&str, ExternItem)> + '_ { self.0.exports.iter().map(move |export| { let item = match export.kind { - ExternalKind::Func => { - let func_addr = self.resolve_func_addr(export.index); - ExternItem::Func(Function { - item: StoreItem::new(self.0.store_id, func_addr), - module_id: self.id(), - }) - } + ExternalKind::Func => ExternItem::Func(Function { + item: StoreItem::new(self.0.store_id, self.resolve_func_addr(export.index)), + module_id: self.id(), + }), ExternalKind::Table => { ExternItem::Table(Table(StoreItem::new(self.0.store_id, self.resolve_table_addr(export.index)))) } @@ -364,7 +359,6 @@ impl ModuleInstance { pub fn func_by_index(&self, store: &Store, func_index: FuncAddr) -> Result<Function> { self.validate_store(store)?; let func_addr = Self::index_addr(&self.0.func_addrs, func_index, "function")?; - Ok(Function { item: StoreItem::new(self.0.store_id, func_addr), module_id: self.id() }) } @@ -392,8 +386,7 @@ impl ModuleInstance { /// /// For untyped access, see [`Self::func_untyped`] and [`Self::extern_item`]. /// - /// For signatures that exceed tuple arity 12, see [`crate::WasmTupleChain`], which can be used - /// directly as `instance.func::<crate::WasmTupleChain<_, _>, _>(...)`. + /// Tuples are supported up to arity 20. Use [`Self::func_untyped`] for larger signatures. pub fn func<P: IntoWasmValues + ToWasmTypes, R: FromWasmValues + ToWasmTypes>( &self, store: &Store, diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 1c80dac..f5c9351 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -5,7 +5,6 @@ use core::hint::cold_path; use super::no_std_floats::NoStdFloatExt; use alloc::boxed::Box; -use alloc::rc::Rc; use alloc::vec::Vec; use alloc::sync::Arc; @@ -16,7 +15,7 @@ use super::ExecState; use super::num_helpers::*; use super::values::*; use crate::engine::FuelPolicy; -use crate::func::{FuncContext, HostFunction}; +use crate::func::HostFunction; use crate::interpreter::Value128; use crate::*; @@ -1042,10 +1041,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_host<const TAIL: bool>( &mut self, - host_func: Rc<HostFunction>, + host_func: HostFunction, type_addr: TypeAddr, params_may_gc: bool, ) -> Result<bool, Trap> { + if let Some(host_func) = host_func.typed_callback() { + if let Err(error) = host_func.call_stack(self.store, self.module.id(), type_addr) { + cold_path(); + return Err(Trap::HostFunction(Box::new(error))); + } + if TAIL { + return Ok(self.exec_return()); + } + self.cf.instr_ptr += 1; + return Ok(false); + } + let param_types = self.store.state.get_canonical_func_type(type_addr).params(); let mut params = Vec::new(); params.try_reserve_exact(param_types.len()).map_err(|_| Trap::OutOfMemory)?; @@ -1056,8 +1067,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if params_may_gc { self.store.state.pin_host_values(¶ms); } - let result = host_func.call(FuncContext { store: self.store, module_id: self.module.id() }, ¶ms); - let res = match result.and_then(|result| crate::func::validate_host_results(self.store, type_addr, result)) { + let res = match host_func.call_values(self.store, self.module.id(), type_addr, ¶ms) { Ok(res) => res, Err(err) => { cold_path(); diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 852618d..1824d20 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -1,4 +1,4 @@ -use alloc::vec::Vec; +use alloc::{vec, vec::Vec}; use core::hint::cold_path; use tinywasm_types::{ValueCounts, WasmType, WasmValue}; @@ -18,6 +18,66 @@ pub(crate) struct ValueStack { pub(crate) stack_128: Stack<Value128>, } +struct WasmValues<'a> { + stack: &'a ValueStack, + state: &'a crate::store::State, + types: core::slice::Iter<'a, WasmType>, + index: StackBase, + pin_refs: bool, +} + +impl Iterator for WasmValues<'_> { + type Item = WasmValue; + + fn next(&mut self) -> Option<Self::Item> { + let value = match *self.types.next()? { + WasmType::I32 => { + let value = *self.stack.stack_32.get(self.index.s32 as usize) as i32; + self.index.s32 += 1; + WasmValue::I32(value) + } + WasmType::I64 => { + let value = *self.stack.stack_64.get(self.index.s64 as usize) as i64; + self.index.s64 += 1; + WasmValue::I64(value) + } + WasmType::F32 => { + let value = f32::from_bits(*self.stack.stack_32.get(self.index.s32 as usize)); + self.index.s32 += 1; + WasmValue::F32(value) + } + WasmType::F64 => { + let value = f64::from_bits(*self.stack.stack_64.get(self.index.s64 as usize)); + self.index.s64 += 1; + WasmValue::F64(value) + } + WasmType::Ref(ty) => { + let value = + self.state.to_ref_value(ValueRef::from_raw(*self.stack.stack_32.get(self.index.s32 as usize)), ty); + self.index.s32 += 1; + WasmValue::Ref(value) + } + WasmType::V128 => { + let value = self.stack.stack_128.get(self.index.s128 as usize).0; + self.index.s128 += 1; + WasmValue::V128(value) + } + }; + if self.pin_refs + && let WasmValue::Ref(value) = value + { + self.state.pin_host_ref(value); + } + Some(value) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.types.size_hint() + } +} + +impl ExactSizeIterator for WasmValues<'_> {} + #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct Stack<T: Copy + Default> { data: Vec<T>, @@ -202,6 +262,15 @@ impl ValueStack { } } + pub(crate) fn base_before(&self, counts: ValueCounts) -> StackBase { + let base = self.base(); + StackBase { + s32: base.s32 - counts.c32 as u32, + s64: base.s64 - counts.c64 as u32, + s128: base.s128 - counts.c128 as u32, + } + } + #[inline(always)] pub(crate) fn len(&self) -> usize { self.stack_32.len() + self.stack_64.len() + self.stack_128.len() @@ -228,6 +297,19 @@ impl ValueStack { Ok(StackBase { s32: locals_base32, s64: locals_base64, s128: locals_base128 }) } + #[inline] + /// Pushes call arguments and allocates the function's local lanes. + pub(crate) fn enter_wasm_call( + &mut self, + values: &[WasmValue], + params: ValueCounts, + locals: ValueCounts, + base: StackBase, + ) -> Result<StackBase, Trap> { + self.extend_from_wasmvalues(values).inspect_err(|_| self.truncate_to_base(base))?; + self.enter_locals(¶ms, &locals).inspect_err(|_| self.truncate_to_base(base)) + } + #[inline(always)] pub(crate) fn truncate_keep_counts(&mut self, base: StackBase, keep: ValueCounts) { self.stack_32.truncate_keep(base.s32 as usize, keep.c32 as usize); @@ -262,17 +344,41 @@ impl ValueStack { } } + /// Pops values in their logical WebAssembly order. + pub(crate) fn pop_wasmvalues(&mut self, state: &crate::store::State, types: &[WasmType]) -> Vec<WasmValue> { + debug_assert!(self.len() >= types.len()); + let mut values = vec![WasmValue::I32(0); types.len()]; + for (index, &ty) in types.iter().enumerate().rev() { + values[index] = self.pop_wasmvalue(state, ty); + } + values + } + + pub(crate) fn wasm_values<'a>( + &'a self, + state: &'a crate::store::State, + types: &'a [WasmType], + index: StackBase, + pin_refs: bool, + ) -> impl ExactSizeIterator<Item = WasmValue> + 'a { + WasmValues { stack: self, state, types: types.iter(), index, pin_refs } + } + pub(crate) fn extend_from_wasmvalues(&mut self, values: &[WasmValue]) -> Result<(), Trap> { + self.extend_wasmvalues(values.iter().copied()) + } + + pub(crate) fn extend_wasmvalues(&mut self, values: impl Iterator<Item = WasmValue>) -> Result<(), Trap> { for value in values { match value { - WasmValue::I32(v) => self.stack_32.push(*v as u32)?, - WasmValue::I64(v) => self.stack_64.push(*v as u64)?, + WasmValue::I32(v) => self.stack_32.push(v as u32)?, + WasmValue::I64(v) => self.stack_64.push(v as u64)?, WasmValue::F32(v) => self.stack_32.push(v.to_bits())?, WasmValue::F64(v) => self.stack_64.push(v.to_bits())?, WasmValue::Ref(v) => { - self.stack_32.push(TinyWasmValue::from(WasmValue::Ref(*v)).as_ref().unwrap().raw())? + self.stack_32.push(TinyWasmValue::from(WasmValue::Ref(v)).as_ref().unwrap().raw())? } - WasmValue::V128(v) => self.stack_128.push((*v).into())?, + WasmValue::V128(v) => self.stack_128.push(v.into())?, } } Ok(()) diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index 1c2bcb4..2e2dce0 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -105,9 +105,11 @@ pub(crate) mod log { mod error; pub use error::*; +#[allow(deprecated)] +pub use func::WasmTupleChain; pub use func::{ - ExecProgress, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, HostFunction, ToWasmTypes, - WasmTupleChain, + ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, + HostFunction, IntoWasmValues, ToWasmType, ToWasmTypes, }; pub use imports::*; pub use instance::{ExternItem, ModuleInstance}; diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index 00f966e..6e904af 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -13,13 +13,14 @@ use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct StoreItem { - pub(crate) store_id: usize, + pub(crate) store_id: u32, pub(crate) addr: Addr, } impl StoreItem { #[inline] - pub(crate) const fn new(store_id: usize, addr: Addr) -> Self { + /// Creates a handle for an address owned by a store. + pub(crate) const fn new(store_id: u32, addr: Addr) -> Self { Self { store_id, addr } } @@ -75,11 +76,7 @@ pub struct MemoryCursor<'a> { } #[cfg(feature = "std")] -impl<'a> MemoryCursor<'a> { - fn new(memory: &'a mut MemoryInstance, position: u64) -> Self { - Self { memory, position } - } - +impl MemoryCursor<'_> { fn offset(&self) -> crate::std::io::Result<usize> { usize::try_from(self.position).map_err(|_| { crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position exceeds usize") @@ -199,7 +196,7 @@ impl Memory { /// Available with the `std` feature enabled. #[cfg(feature = "std")] pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result<MemoryCursor<'a>> { - Ok(MemoryCursor::new(self.instance_mut(store)?, position)) + Ok(MemoryCursor { memory: self.instance_mut(store)?, position }) } #[inline] @@ -375,12 +372,6 @@ impl Table { Ok(store.state.get_table(self.0.addr)) } - #[inline] - fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut TableInstance, Trap> { - self.0.validate_store(store)?; - Ok(store.state.get_table_mut(self.0.addr)) - } - /// Get the type of the table. pub fn ty(&self, store: &Store) -> Result<TableType> { Ok(self.instance(store)?.kind) @@ -428,7 +419,8 @@ impl Table { /// Copy elements within the same table. pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<(), Trap> { - self.instance_mut(store)?.copy_within(dst, src, len) + self.0.validate_store(store)?; + store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) } /// Grow the table and return the previous size. diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs new file mode 100644 index 0000000..201a1e1 --- /dev/null +++ b/crates/tinywasm/src/store/const_expr.rs @@ -0,0 +1,194 @@ +use alloc::{format, vec::Vec}; +use core::hint::cold_path; +use tinywasm_types::*; + +use super::{State, default_value}; +use crate::interpreter::{TinyWasmValue, ValueRef}; +use crate::{Error, Result, Trap}; + +#[inline] +pub(super) fn eval_const( + state: &mut State, + instructions: &[ConstInstruction], + global_addrs: &[GlobalAddr], + func_addrs: &[FuncAddr], + type_addrs: &[TypeAddr], +) -> Result<TinyWasmValue> { + use ConstInstruction::*; + + let global_value = |state: &State, index: u32| -> Result<TinyWasmValue> { + let addr = + *global_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("global {index} not found")))?; + Ok(state.globals.get(addr)) + }; + let func_ref = |index: u32| -> Result<ValueRef> { + let addr = + *func_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("function {index} not found")))?; + Ok(ValueRef::from_category_addr(addr)) + }; + let type_addr = |index: TypeAddr| -> Result<TypeAddr> { + type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found")) + }; + let pop_value = |stack: &mut Vec<TinyWasmValue>, storage: StorageType| -> Result<TinyWasmValue> { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + match (storage, value) { + (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), + (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), + (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) + | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) + | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) + | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), + _ => Err(Error::other("type mismatch in GC constant")), + } + }; + + if let [instruction] = instructions { + match instruction { + I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)), + I64Const(value) => return Ok(TinyWasmValue::Value64(*value as u64)), + F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())), + F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())), + V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())), + GlobalGet(index) => return global_value(state, *index), + Ref(RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), + Ref(RefValue::Func(func)) => return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?)), + _ => {} + } + } + + let mut stack = Vec::new(); + for instruction in instructions { + match instruction { + I32Const(value) => stack.push(TinyWasmValue::Value32(*value as u32)), + I64Const(value) => stack.push(TinyWasmValue::Value64(*value as u64)), + F32Const(value) => stack.push(TinyWasmValue::Value32(value.to_bits())), + F64Const(value) => stack.push(TinyWasmValue::Value64(value.to_bits())), + V128Const(value) => stack.push(TinyWasmValue::Value128((*value).into())), + GlobalGet(index) => stack.push(global_value(state, *index)?), + Ref(RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), + Ref(RefValue::Func(func)) => stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?)), + Ref(_) => { + cold_path(); + return Err(Error::other("unsupported reference constant")); + } + RefI31 => { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + let TinyWasmValue::Value32(value) = value else { + return Err(Error::other("type mismatch in const ref.i31")); + }; + stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32))); + } + AnyConvertExtern | ExternConvertAny => { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + if !matches!(value, TinyWasmValue::ValueRef(_)) { + return Err(Error::other("type mismatch in const reference conversion")); + } + stack.push(value); + } + StructNew(type_index) | StructNewDefault(type_index) => { + let type_addr = type_addr(*type_index)?; + let fields = state + .get_type(type_addr) + .as_struct() + .ok_or_else(|| Error::other("GC constant type is not a struct"))? + .fields + .clone(); + let default = matches!(instruction, StructNewDefault(_)); + let mut values = Vec::new(); + values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + if default { + values.extend(fields.iter().map(|field| default_value(field.storage))); + } else { + for field in fields.iter().rev() { + values.push(pop_value(&mut stack, field.storage)?); + } + values.reverse(); + } + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + ArrayNew(type_index) | ArrayNewDefault(type_index) => { + let type_addr = type_addr(*type_index)?; + let storage = state + .get_type(type_addr) + .as_array() + .ok_or_else(|| Error::other("GC constant type is not an array"))? + .field + .storage; + let Some(TinyWasmValue::Value32(len)) = stack.pop() else { + return Err(Error::other("type mismatch in const array length")); + }; + let value = if matches!(instruction, ArrayNewDefault(_)) { + default_value(storage) + } else { + pop_value(&mut stack, storage)? + }; + let mut values = Vec::new(); + values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; + values.resize(len as usize, value); + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + ArrayNewFixed(type_index, len) => { + let type_addr = type_addr(*type_index)?; + let storage = state + .get_type(type_addr) + .as_array() + .ok_or_else(|| Error::other("GC constant type is not an array"))? + .field + .storage; + let mut values = Vec::new(); + values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?; + for _ in 0..*len { + values.push(pop_value(&mut stack, storage)?); + } + values.reverse(); + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + I32Add | I32Sub | I32Mul => { + let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + let (TinyWasmValue::Value32(lhs), TinyWasmValue::Value32(rhs)) = (lhs, rhs) else { + cold_path(); + return Err(Error::other("type mismatch in const i32 op")); + }; + let out = match instruction { + I32Add => (lhs as i32).wrapping_add(rhs as i32), + I32Sub => (lhs as i32).wrapping_sub(rhs as i32), + I32Mul => (lhs as i32).wrapping_mul(rhs as i32), + _ => unreachable!(), + }; + stack.push(TinyWasmValue::Value32(out as u32)); + } + I64Add | I64Sub | I64Mul => { + let rhs = stack.pop(); + let lhs = stack.pop(); + let (Some(TinyWasmValue::Value64(lhs)), Some(TinyWasmValue::Value64(rhs))) = (lhs, rhs) else { + cold_path(); + return Err(Error::other("type mismatch in const i64 op")); + }; + let out = match instruction { + I64Add => (lhs as i64).wrapping_add(rhs as i64), + I64Sub => (lhs as i64).wrapping_sub(rhs as i64), + I64Mul => (lhs as i64).wrapping_mul(rhs as i64), + _ => unreachable!(), + }; + stack.push(TinyWasmValue::Value64(out as u64)); + } + } + } + + let Some(value) = stack.pop() else { + cold_path(); + return Err(Error::other("empty const expression")); + }; + if !stack.is_empty() { + cold_path(); + return Err(Error::other("const expression did not reduce to single value")); + } + Ok(value) +} diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs index 367fadb..3580e9d 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -1,4 +1,4 @@ -use alloc::{rc::Rc, sync::Arc}; +use alloc::sync::Arc; use tinywasm_types::*; use crate::func::HostFunction; @@ -25,7 +25,7 @@ pub(crate) struct FunctionGcMetadata { #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) enum FunctionKind { /// A host function - Host(Rc<HostFunction>), + Host(HostFunction), /// A pointer to a WebAssembly function Wasm(WasmFunctionInstance), diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index c685d89..638b01d 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -15,6 +15,11 @@ impl<T> Default for GlobalLane<T> { } impl<T: Copy> GlobalLane<T> { + fn reserve(&mut self, additional: usize) { + self.values.reserve_exact(additional); + self.types.reserve_exact(additional); + } + fn push(&mut self, ty: GlobalType, value: T) -> usize { debug_assert_eq!(self.values.len(), self.types.len()); let index = self.values.len(); @@ -57,6 +62,20 @@ impl Globals { const LANE_64: u32 = 1 << Self::LANE_SHIFT; const LANE_128: u32 = 2 << Self::LANE_SHIFT; + pub(crate) fn reserve(&mut self, globals: &[Global]) { + let (mut count_32, mut count_64, mut count_128) = (0, 0, 0); + for global in globals { + match global.ty.ty { + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => count_32 += 1, + WasmType::I64 | WasmType::F64 => count_64 += 1, + WasmType::V128 => count_128 += 1, + } + } + self.globals_32.reserve(count_32); + self.globals_64.reserve(count_64); + self.globals_128.reserve(count_128); + } + fn addr(lane: u32, index: usize) -> GlobalAddr { assert!(index <= Self::INDEX_MASK as usize, "too many globals in one value lane"); lane | index as u32 diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 9d5622a..0cd5e5b 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,12 +1,14 @@ use alloc::{boxed::Box, format, vec::Vec}; use core::hint::cold_path; -use core::sync::atomic::{AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicU32, Ordering}; use tinywasm_types::*; -use crate::interpreter::stack::{CallStack, ValueStack}; +use crate::func::FromWasmValues; +use crate::interpreter::stack::{CallStack, StackBase, ValueStack}; use crate::interpreter::{TinyWasmValue, ValueRef}; use crate::{Engine, Error, ModuleInstance, Result, Trap}; +mod const_expr; mod data; mod element; mod function; @@ -17,6 +19,7 @@ mod state; mod table; mod types; +use const_expr::eval_const; pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; pub(crate) use memory::{MemValue, MemoryInstance}; @@ -25,7 +28,7 @@ pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; pub(crate) use {data::*, element::*, function::*, global::*, table::*}; // global store id counter -static STORE_ID: AtomicUsize = AtomicUsize::new(0); +static STORE_ID: AtomicU32 = AtomicU32::new(0); /// Global state that can be manipulated by WebAssembly programs /// @@ -46,7 +49,7 @@ static STORE_ID: AtomicUsize = AtomicUsize::new(0); /// /// See <https://webassembly.github.io/spec/core/exec/runtime.html#store> pub struct Store { - id: usize, + id: u32, pub(crate) module_instances: Vec<ModuleInstance>, pub(crate) engine: Engine, @@ -68,12 +71,24 @@ impl core::fmt::Debug for Store { } } +impl PartialEq for Store { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl Default for Store { + fn default() -> Self { + Self::new(Engine::default()) + } +} + impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { - let id = STORE_ID.fetch_add(1, Ordering::Relaxed); - let state = - State { gc: Box::new(gc::GcHeap::new(engine.config().gc_collection_threshold)), ..State::default() }; + let id = + STORE_ID.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)).expect("too many stores"); + let state = State::new(engine.config().gc_collection_threshold); Self { id, module_instances: Vec::new(), @@ -86,45 +101,16 @@ impl Store { } } + /// Get the store's ID (unique per process) + pub fn id(&self) -> u32 { + self.id + } + /// Get a module instance by the internal id pub fn get_module_instance(&self, id: ModuleInstanceId) -> Option<&ModuleInstance> { self.module_instances.get(id as usize) } - pub(crate) fn enter_execution(&mut self) -> Result<()> { - if self.execution_active { - return Err(Trap::Other( - "cannot call a function while another invocation is active; use FuncContext::call from host functions", - ) - .into()); - } - self.execution_active = true; - Ok(()) - } - - pub(crate) fn exit_execution(&mut self) { - self.execution_active = false; - } -} - -impl PartialEq for Store { - fn eq(&self, other: &Self) -> bool { - self.id == other.id - } -} - -impl Default for Store { - fn default() -> Self { - Self::new(Engine::default()) - } -} - -impl Store { - /// Get the store's ID (unique per process) - pub fn id(&self) -> usize { - self.id - } - pub(crate) fn next_module_instance_id(&self) -> ModuleInstanceId { self.module_instances.len() as ModuleInstanceId } @@ -151,19 +137,87 @@ impl Store { pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool { self.state.value_matches_type(value, ty) } -} -impl Store { + /// Marks the store as executing and rejects nested root calls. + pub(crate) fn enter_execution(&mut self) -> Result<()> { + if self.execution_active { + return Err(Trap::Other( + "cannot call a function while another invocation is active; use FuncContext::call from host functions", + ) + .into()); + } + self.execution_active = true; + Ok(()) + } + + /// Marks the current root execution as complete. + pub(crate) fn exit_execution(&mut self) { + self.execution_active = false; + } + + /// Validates and pushes typed parameters or results onto the value stack. + pub(crate) fn push_typed_values<const RESULTS: bool>( + &mut self, + type_addr: TypeAddr, + values: impl Iterator<Item = WasmValue>, + stack_base: StackBase, + ) -> Result<()> { + let result: Result<()> = (|| { + let ty = self.state.get_canonical_func_type(type_addr); + let expected = if RESULTS { ty.results() } else { ty.params() }; + let mut values = values; + for &ty in expected { + let value = values.next().ok_or_else(|| Error::other("not enough typed function values"))?; + if !self.state.value_matches_type(value, ty) { + return Err(Error::other("typed function value does not match its signature")); + } + self.value_stack.extend_wasmvalues(core::iter::once(value))?; + } + if values.next().is_some() { + return Err(Error::other("too many typed function values")); + } + Ok(()) + })(); + if result.is_err() { + self.value_stack.truncate_to_base(stack_base); + } + result + } + + /// Reads typed results from the value stack and restores its previous base. + pub(crate) fn take_typed_results<R: FromWasmValues>( + &mut self, + type_addr: TypeAddr, + stack_base: StackBase, + pin_refs: bool, + ) -> Result<R> { + let types = self.state.get_canonical_func_type(type_addr).results(); + let mut values = self.value_stack.wasm_values(&self.state, types, stack_base, pin_refs); + let result = R::from_wasm_values(&mut values).and_then(|result| { + if values.next().is_some() { + Err(Error::other("typed conversion did not consume all WebAssembly values")) + } else { + Ok(result) + } + }); + drop(values); + self.value_stack.truncate_to_base(stack_base); + result + } + /// Add functions to the store, returning their addresses in the store pub(crate) fn init_funcs( &mut self, funcs: &[alloc::sync::Arc<WasmFunction>], owner: ModuleInstanceId, + module_type_idxs: &[TypeAddr], type_addrs: &[TypeAddr], ) -> impl ExactSizeIterator<Item = FuncAddr> { let start = self.state.funcs.len() as FuncAddr; - debug_assert_eq!(funcs.len(), type_addrs.len()); - for (func, &type_addr) in funcs.iter().cloned().zip(type_addrs) { + debug_assert_eq!(funcs.len(), module_type_idxs.len()); + self.state.funcs.reserve_exact(funcs.len()); + for (func, &type_idx) in funcs.iter().cloned().zip(module_type_idxs) { + let type_addr = type_addrs[type_idx as usize]; self.state.funcs.push(FunctionInstance { type_addr, gc: self.state.func_gc_metadata(type_addr), @@ -185,7 +239,7 @@ impl Store { self.state.tables.reserve_exact(tables.len()); for table in tables { let init = match &table.init { - Some(expr) => match self.eval_const(expr, global_addrs, func_addrs, type_addrs)? { + Some(expr) => match eval_const(&mut self.state, expr, global_addrs, func_addrs, type_addrs)? { TinyWasmValue::ValueRef(value) => value, _ => return Err(Error::other("table initializer is not a reference value")), }, @@ -208,6 +262,7 @@ impl Store { init: impl Fn(MemoryType, &MemoryBackend) -> Result<MemoryInstance>, ) -> Result<impl ExactSizeIterator<Item = MemAddr>> { let start = self.state.memories.len() as MemAddr; + self.state.memories.reserve_exact(memories.len()); for mem in memories { self.state.memories.push(match init(*mem, &self.engine.config().memory_backend) { Ok(mem) => mem, @@ -228,8 +283,9 @@ impl Store { func_addrs: &[FuncAddr], type_addrs: &[TypeAddr], ) -> Result<()> { + self.state.globals.reserve(globals); for global in globals { - let value = match self.eval_const(&global.init, out, func_addrs, type_addrs) { + let value = match eval_const(&mut self.state, &global.init, out, func_addrs, type_addrs) { Ok(val) => val, Err(e) => { cold_path(); @@ -251,7 +307,7 @@ impl Store { type_addrs: &[TypeAddr], ) -> Result<ValueRef> { match item { - ElementItem::Expr(expr) => match self.eval_const(expr, globals, funcs, type_addrs)? { + ElementItem::Expr(expr) => match eval_const(&mut self.state, expr, globals, funcs, type_addrs)? { TinyWasmValue::ValueRef(value) => Ok(value), other => { cold_path(); @@ -279,9 +335,10 @@ impl Store { global_addrs: &[Addr], elements: &[Element], type_addrs: &[TypeAddr], - ) -> Result<(Box<[Addr]>, Option<Trap>)> { + ) -> Result<(Box<[ElemAddr]>, Option<Trap>)> { let elem_count = self.state.elements.len(); let mut elem_addrs = Vec::with_capacity(elements.len()); + self.state.elements.reserve_exact(elements.len()); for (i, element) in elements.iter().enumerate() { let elem_addr = self.state.elements.len(); self.state.elements.push(ElementInstance { @@ -302,7 +359,11 @@ impl Store { // this one is active, so we need to initialize it (essentially a `table.init` instruction) ElementKind::Active { offset, table } => { - let offset = self.eval_size_const(offset, global_addrs, func_addrs, type_addrs)?; + let offset = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? { + TinyWasmValue::Value32(value) => u64::from(value), + TinyWasmValue::Value64(value) => value, + other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), + }; let table_addr = table_addrs .get(*table as usize) .copied() @@ -339,8 +400,7 @@ impl Store { elements[elem_addr].drop(); } } - - elem_addrs.push((i + elem_count) as Addr); + elem_addrs.push((i + elem_count) as ElemAddr); } // this should be optimized out by the compiler @@ -355,9 +415,10 @@ impl Store { func_addrs: &[FuncAddr], data: &[Data], type_addrs: &[TypeAddr], - ) -> Result<(Box<[Addr]>, Option<Trap>)> { + ) -> Result<(Box<[DataAddr]>, Option<Trap>)> { let data_count = self.state.data.len(); - let mut data_addrs = Vec::with_capacity(data_count); + let mut data_addrs = Vec::with_capacity(data.len()); + self.state.data.reserve_exact(data.len()); for (i, data) in data.iter().enumerate() { let data_val = match &data.kind { tinywasm_types::DataKind::Active { mem: mem_addr, offset } => { @@ -365,7 +426,11 @@ impl Store { return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}"))); }; - let offset = self.eval_size_const(offset, global_addrs, func_addrs, type_addrs)?; + let offset = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? { + TinyWasmValue::Value32(value) => u64::from(value), + TinyWasmValue::Value64(value) => value, + other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), + }; let Some(mem) = self.state.memories.get_mut(*mem_addr as usize) else { return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}"))); }; @@ -389,241 +454,17 @@ impl Store { }; self.state.data.push(DataInstance { data: data_val }); - data_addrs.push((i + data_count) as Addr); + data_addrs.push((i + data_count) as DataAddr); } // this should be optimized out by the compiler Ok((data_addrs.into_boxed_slice(), None)) } + /// Adds a function and returns its store address. pub(crate) fn add_func(&mut self, func: FunctionInstance) -> FuncAddr { + let addr = self.state.funcs.len() as FuncAddr; self.state.funcs.push(func); - self.state.funcs.len() as FuncAddr - 1 - } - - /// Evaluate a constant expression that's either a i32 or a i64 as a global or a const instruction - fn eval_size_const( - &mut self, - const_instrs: &[tinywasm_types::ConstInstruction], - module_global_addrs: &[Addr], - module_func_addrs: &[FuncAddr], - module_type_addrs: &[TypeAddr], - ) -> Result<u64> { - let value = self.eval_const(const_instrs, module_global_addrs, module_func_addrs, module_type_addrs)?; - match value { - TinyWasmValue::Value32(i) => Ok(u64::from(i)), - TinyWasmValue::Value64(i) => Ok(i), - other => Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), - } - } - - /// Evaluate a constant expression - #[inline] - fn eval_const( - &mut self, - const_instrs: &[tinywasm_types::ConstInstruction], - module_global_addrs: &[Addr], - module_func_addrs: &[FuncAddr], - module_type_addrs: &[TypeAddr], - ) -> Result<TinyWasmValue> { - use tinywasm_types::ConstInstruction::*; - - let global_value = |state: &State, index: u32| -> Result<TinyWasmValue> { - let addr = *module_global_addrs - .get(index as usize) - .ok_or_else(|| Error::Other(format!("global {index} not found")))?; - Ok(state.globals.get(addr)) - }; - let func_ref = |index: u32| -> Result<ValueRef> { - let addr = *module_func_addrs - .get(index as usize) - .ok_or_else(|| Error::Other(format!("function {index} not found")))?; - Ok(ValueRef::from_category_addr(addr)) - }; - let type_addr = |index: TypeAddr| -> Result<TypeAddr> { - module_type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found")) - }; - let pop_value = |stack: &mut Vec<TinyWasmValue>, storage: StorageType| -> Result<TinyWasmValue> { - let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - match (storage, value) { - (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), - (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), - (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) - | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) - | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) - | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), - _ => Err(Error::other("type mismatch in GC constant")), - } - }; - - if let [instr] = const_instrs { - match instr { - I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)), - I64Const(value) => return Ok(TinyWasmValue::Value64(*value as u64)), - F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())), - F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())), - V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())), - GlobalGet(index) => return global_value(&self.state, *index), - Ref(tinywasm_types::RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(tinywasm_types::RefValue::Func(func)) => { - return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?)); - } - _ => {} - } - } - - let mut stack = Vec::new(); - for instr in const_instrs { - match instr { - I32Const(i) => stack.push(TinyWasmValue::Value32(*i as u32)), - I64Const(i) => stack.push(TinyWasmValue::Value64(*i as u64)), - F32Const(f) => stack.push(TinyWasmValue::Value32(f.to_bits())), - F64Const(f) => stack.push(TinyWasmValue::Value64(f.to_bits())), - V128Const(i) => stack.push(TinyWasmValue::Value128((*i).into())), - GlobalGet(index) => stack.push(global_value(&self.state, *index)?), - Ref(tinywasm_types::RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(tinywasm_types::RefValue::Func(func)) => { - stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?)) - } - Ref(_) => { - cold_path(); - return Err(Error::other("unsupported reference constant")); - } - RefI31 => { - let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let TinyWasmValue::Value32(value) = value else { - return Err(Error::other("type mismatch in const ref.i31")); - }; - stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32))); - } - AnyConvertExtern | ExternConvertAny => { - let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - if !matches!(value, TinyWasmValue::ValueRef(_)) { - return Err(Error::other("type mismatch in const reference conversion")); - } - stack.push(value); - } - StructNew(type_index) | StructNewDefault(type_index) => { - let type_addr = type_addr(*type_index)?; - let fields = self - .state - .get_type(type_addr) - .as_struct() - .ok_or_else(|| Error::other("GC constant type is not a struct"))? - .fields - .clone(); - let default = matches!(instr, StructNewDefault(_)); - let mut values = Vec::new(); - values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; - if default { - values.extend(fields.iter().map(|field| default_value(field.storage))); - } else { - for field in fields.iter().rev() { - values.push(pop_value(&mut stack, field.storage)?); - } - values.reverse(); - } - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = self.state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); - } - ArrayNew(type_index) | ArrayNewDefault(type_index) => { - let type_addr = type_addr(*type_index)?; - let storage = self - .state - .get_type(type_addr) - .as_array() - .ok_or_else(|| Error::other("GC constant type is not an array"))? - .field - .storage; - let Some(TinyWasmValue::Value32(len)) = stack.pop() else { - return Err(Error::other("type mismatch in const array length")); - }; - let value = if matches!(instr, ArrayNewDefault(_)) { - default_value(storage) - } else { - pop_value(&mut stack, storage)? - }; - let mut values = Vec::new(); - values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; - values.resize(len as usize, value); - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = self.state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); - } - ArrayNewFixed(type_index, len) => { - let type_addr = type_addr(*type_index)?; - let storage = self - .state - .get_type(type_addr) - .as_array() - .ok_or_else(|| Error::other("GC constant type is not an array"))? - .field - .storage; - let mut values = Vec::new(); - values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?; - for _ in 0..*len { - values.push(pop_value(&mut stack, storage)?); - } - values.reverse(); - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = self.state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); - } - I32Add | I32Sub | I32Mul => { - let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let (TinyWasmValue::Value32(lhs), TinyWasmValue::Value32(rhs)) = (lhs, rhs) else { - cold_path(); - return Err(Error::other("type mismatch in const i32 op")); - }; - let lhs = lhs as i32; - let rhs = rhs as i32; - let out = match instr { - I32Add => lhs.wrapping_add(rhs), - I32Sub => lhs.wrapping_sub(rhs), - I32Mul => lhs.wrapping_mul(rhs), - _ => { - cold_path(); - return Err(Error::other("invalid const instruction in i32 op")); - } - }; - stack.push(TinyWasmValue::Value32(out as u32)); - } - I64Add | I64Sub | I64Mul => { - let rhs = stack.pop(); - let lhs = stack.pop(); - let (Some(TinyWasmValue::Value64(lhs)), Some(TinyWasmValue::Value64(rhs))) = (lhs, rhs) else { - cold_path(); - return Err(Error::other("type mismatch in const i64 op")); - }; - - let lhs = lhs as i64; - let rhs = rhs as i64; - let out = match instr { - I64Add => lhs.wrapping_add(rhs), - I64Sub => lhs.wrapping_sub(rhs), - I64Mul => lhs.wrapping_mul(rhs), - _ => { - cold_path(); - return Err(Error::other("invalid const instruction in i64 op")); - } - }; - stack.push(TinyWasmValue::Value64(out as u64)); - } - } - } - - let Some(value) = stack.pop() else { - cold_path(); - return Err(Error::other("empty const expression")); - }; - - if !stack.is_empty() { - cold_path(); - return Err(Error::other("const expression did not reduce to single value")); - } - - Ok(value) + addr } } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 5cb561a..3371d4c 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -2,7 +2,6 @@ use alloc::vec::Vec; use super::*; -#[derive(Default)] /// Global state that can be manipulated by WebAssembly programs /// /// Data should only be addressable by the module that owns it @@ -21,6 +20,20 @@ pub(crate) struct State { } impl State { + pub(crate) fn new(gc_collection_threshold: usize) -> Self { + Self { + canonical_types: Vec::new(), + canonical_rec_group_lengths: Vec::new(), + funcs: Vec::new(), + tables: Vec::new(), + memories: Vec::new(), + globals: Globals::default(), + elements: Vec::new(), + data: Vec::new(), + gc: Box::new(gc::GcHeap::new(gc_collection_threshold)), + } + } + /// Returns whether values of this type can contain a managed GC object. pub(crate) fn type_may_contain_gc(&self, ty: &WasmType) -> bool { Self::type_may_contain_gc_in(&self.canonical_types, ty) @@ -406,3 +419,9 @@ impl State { Ok(()) } } + +impl Default for State { + fn default() -> Self { + Self::new(1024 * 1024) + } +} diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index b3b5048..35e0d9b 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,6 +1,6 @@ use eyre::Result; use std::fmt::Write; -use tinywasm::types::{FuncType, RefValue, WasmType, WasmValue}; +use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; use tinywasm::{FuncContext, HostFunction, Imports, Module, ModuleInstance, Store}; use tinywasm_types::ExternRef; @@ -34,10 +34,10 @@ fn test_return_invalid_type() -> Result<()> { for returned_values in VAL_LISTS { let mut store = Store::default(); let mut imports = Imports::new(); - let hfn = HostFunction::from_untyped(&mut store, &ty, |_: FuncContext<'_>, _| Ok(returned_values.to_vec())); + let hfn = HostFunction::from_untyped(&ty, |_: FuncContext<'_>, _| Ok(returned_values.to_vec())); imports.define("host", "hfn", hfn); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports)).unwrap(); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap(); let caller = instance.func_untyped(&store, "call_hfn").unwrap(); // Return-type mismatch is only observable at call time. let should_succeed = returned_values.len() == ty.results().len() @@ -56,13 +56,12 @@ fn test_linking_invalid_untyped_func() -> Result<()> { for (module, expected_func_ty, _) in &cases { for (_, ty, _) in &cases { let mut store = Store::default(); - let tried_fn = - HostFunction::from_untyped(&mut store, ty, |_: FuncContext<'_>, _| panic!("not intended to be called")); + let tried_fn = HostFunction::from_untyped(ty, |_: FuncContext<'_>, _| panic!("not intended to be called")); let mut imports = Imports::new(); imports.define("host", "hfn", tried_fn); let should_succeed = ty == expected_func_ty; - let link_res = ModuleInstance::instantiate(&mut store, module, Some(imports)); + let link_res = ModuleInstance::instantiate(&mut store, module, Some(&imports)); assert_eq!(link_res.is_ok(), should_succeed); } } @@ -80,26 +79,18 @@ fn test_linking_invalid_typed_func() -> Result<()> { for (module, _, _) in cases { let mut store = Store::default(); let matching_none = vec![ - HostFunction::from(&mut store, |_, _: NonMatchingTuple| -> tinywasm::Result<Existing> { + HostFunction::from(|_, _: NonMatchingTuple| -> tinywasm::Result<Existing> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingTuple| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<Existing> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: Existing| -> tinywasm::Result<NonMatchingTuple> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: Existing| -> tinywasm::Result<NonMatchingSingle> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: ()| -> tinywasm::Result<NonMatchingSingle> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: ()| -> tinywasm::Result<NonMatchingTuple> { panic!("{DONT_CALL}") }), + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingTuple> { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: NonMatchingTuple| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<Existing> { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<()> { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: Existing| -> tinywasm::Result<NonMatchingTuple> { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: Existing| -> tinywasm::Result<NonMatchingSingle> { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: ()| -> tinywasm::Result<NonMatchingSingle> { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: ()| -> tinywasm::Result<NonMatchingTuple> { panic!("{DONT_CALL}") }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingTuple> { - panic!("{DONT_CALL}") - }), - HostFunction::from(&mut store, |_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingSingle> { + HostFunction::from(|_, _: NonMatchingSingle| -> tinywasm::Result<NonMatchingSingle> { panic!("{DONT_CALL}") }), ]; @@ -107,7 +98,7 @@ fn test_linking_invalid_typed_func() -> Result<()> { for typed_fn in matching_none { let mut imports = Imports::new(); imports.define("host", "hfn", typed_fn); - let link_failure = ModuleInstance::instantiate(&mut store, &module, Some(imports)); + let link_failure = ModuleInstance::instantiate(&mut store, &module, Some(&imports)); assert!(link_failure.is_err(), "Expected linking to fail for mismatched typed func, but it succeeded"); } } @@ -142,10 +133,11 @@ fn concrete_host_references_use_canonical_types() -> Result<()> { let param_ty = instance.func_untyped(&store, "takes-a")?.ty(&store)?.clone(); let wrong_result = wrong_ref.clone(); - let wrong_return = HostFunction::from_untyped(&mut store, &return_ty, move |_, _| Ok(wrong_result.clone())); + let wrong_return = + HostFunction::from_untyped(&return_ty, move |_, _| Ok(wrong_result.clone())).instantiate(&mut store)?; assert!(wrong_return.call(&mut store, &[]).is_err()); - let accept_a = HostFunction::from_untyped(&mut store, ¶m_ty, |_, _| Ok(Vec::new())); + let accept_a = HostFunction::from_untyped(¶m_ty, |_, _| Ok(Vec::new())).instantiate(&mut store)?; assert!(accept_a.call(&mut store, &wrong_ref).is_err()); assert!(accept_a.call(&mut store, &right_ref).is_ok()); @@ -153,6 +145,34 @@ fn concrete_host_references_use_canonical_types() -> Result<()> { } #[test] +fn imported_host_functions_resolve_concrete_types() -> Result<()> { + let wasm = wat::parse_str( + r#" + (module + (type $object (struct)) + (import "host" "inspect" (func $inspect (param (ref null $object)))) + (func (export "call") + ref.null $object + call $inspect)) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let concrete = RefType::new_concrete(true, 0).expect("valid module-local type index"); + let host_ty = FuncType::new(&[WasmType::Ref(concrete)], &[]); + let host = HostFunction::from_untyped(&host_ty, |_, args| { + assert_eq!(args, &[WasmValue::Ref(RefValue::Null)]); + Ok(Vec::new()) + }); + let mut imports = Imports::new(); + imports.define("host", "inspect", host); + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + + instance.func::<(), ()>(&store, "call")?.call(&mut store, ())?; + Ok(()) +} + +#[test] fn host_tail_calls_return_from_the_current_frame() -> Result<()> { let wasm = wat::parse_str( r#" @@ -178,8 +198,8 @@ fn host_tail_calls_return_from_the_current_frame() -> Result<()> { let module = tinywasm::parse_bytes(&wasm)?; let mut store = Store::default(); let mut imports = Imports::new(); - imports.define("host", "answer", HostFunction::from(&mut store, |_, ()| Ok(42_i32))); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + imports.define("host", "answer", HostFunction::from(|_, ()| Ok(42_i32))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; for name in ["direct", "indirect", "reference"] { assert_eq!(instance.func::<(), i32>(&store, name)?.call(&mut store, ())?, 42); @@ -190,13 +210,14 @@ fn host_tail_calls_return_from_the_current_frame() -> Result<()> { } #[test] -fn host_calls_reject_unknown_function_references() { +fn host_calls_reject_unknown_function_references() -> Result<()> { let mut store = Store::default(); let ty = FuncType::new(&[WasmType::Ref(tinywasm::types::RefType::FUNCREF)], &[]); - let host = HostFunction::from_untyped(&mut store, &ty, |_, _| Ok(Vec::new())); + let host = HostFunction::from_untyped(&ty, |_, _| Ok(Vec::new())).instantiate(&mut store)?; let invalid = WasmValue::Ref(RefValue::Func(tinywasm::types::FuncRef::new(u32::MAX))); assert!(host.call(&mut store, &[invalid]).is_err()); + Ok(()) } fn to_name(ty: &WasmType) -> &str { diff --git a/crates/tinywasm/tests/host_import_arg_order.rs b/crates/tinywasm/tests/host_import_arg_order.rs index 2004641..b04ef77 100644 --- a/crates/tinywasm/tests/host_import_arg_order.rs +++ b/crates/tinywasm/tests/host_import_arg_order.rs @@ -15,17 +15,16 @@ fn multi_arg_host_imports_preserve_source_order() { .unwrap(); let module = tinywasm::parse_bytes(&wasm).unwrap(); - let mut store = Store::default(); - - let pair = HostFunction::from(&mut store, |_ctx, (left, right): (i32, i32)| -> tinywasm::Result<i32> { - Ok(left * 1000 + right) - }); - + let pair = + HostFunction::from(|_ctx, (left, right): (i32, i32)| -> tinywasm::Result<i32> { Ok(left * 1000 + right) }); let mut imports = Imports::new(); imports.define("env", "pair", pair); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports)).unwrap(); - let func = instance.func::<(i32, i32), i32>(&store, "call_pair").unwrap(); + for _ in 0..2 { + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap(); + let func = instance.func::<(i32, i32), i32>(&store, "call_pair").unwrap(); - assert_eq!(func.call(&mut store, (12, 34)).unwrap(), 12034); + assert_eq!(func.call(&mut store, (12, 34)).unwrap(), 12034); + } } diff --git a/crates/tinywasm/tests/import_linking.rs b/crates/tinywasm/tests/import_linking.rs index e7948fa..1d5db1b 100644 --- a/crates/tinywasm/tests/import_linking.rs +++ b/crates/tinywasm/tests/import_linking.rs @@ -34,7 +34,7 @@ fn link_module_links_same_store_instance() -> Result<()> { let mut imports = Imports::new(); imports.link_module("adder", add_instance)?; - let instance = ModuleInstance::instantiate(&mut store, &import_module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &import_module, Some(&imports))?; let main = instance.func::<(), i32>(&store, "main")?; assert_eq!(main.call(&mut store, ())?, 3); Ok(()) @@ -51,7 +51,7 @@ fn link_module_rejects_cross_store_instance() -> Result<()> { let mut imports = Imports::new(); imports.link_module("adder", add_instance)?; - let err = ModuleInstance::instantiate(&mut target_store, &import_module, Some(imports)).unwrap_err(); + let err = ModuleInstance::instantiate(&mut target_store, &import_module, Some(&imports)).unwrap_err(); assert_eq!(err, Error::from(Trap::InvalidStore)); Ok(()) } diff --git a/crates/tinywasm/tests/imported_table_init.rs b/crates/tinywasm/tests/imported_table_init.rs index d7ed636..ca52e9e 100644 --- a/crates/tinywasm/tests/imported_table_init.rs +++ b/crates/tinywasm/tests/imported_table_init.rs @@ -19,11 +19,11 @@ fn imported_table_uses_provided_init_value() -> Result<()> { let module = tinywasm::parse_bytes(&wasm)?; let mut store = Store::default(); let mut imports = Imports::new(); - let _function_at_zero = HostFunction::from(&mut store, |_, ()| Ok(())); + let _function_at_zero = HostFunction::from(|_, ()| Ok(())).instantiate(&mut store)?; let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 3, None), FuncRef::new(0).into())?; imports.define("host", "table", table); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let slot_is_null = instance.func::<i32, i32>(&store, "slot_is_null")?; assert_eq!(slot_is_null.call(&mut store, 0)?, 0); diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs index 04279cc..196ad0a 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -117,9 +117,9 @@ fn extern_item_and_exports_use_actual_function_type() -> Result<()> { imports.define( "host", "imported", - tinywasm::HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())), + tinywasm::HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())), ); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let ExternItem::Func(func) = instance.extern_item("f")? else { panic!("expected function export") }; assert_eq!(func.call(&mut store, &[])?, vec![]); @@ -166,9 +166,9 @@ fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<() imports.define( "spectest", "print_i64", - tinywasm::HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())), + tinywasm::HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, _arg: i64| Ok(())), ); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let ExternItem::Func(func) = instance.extern_item("f")? else { panic!("expected function export") }; assert_eq!(func.call(&mut store, &[])?, vec![]); @@ -192,7 +192,8 @@ fn start_resolves_module_func_index_to_store_addr() -> Result<()> { let module = tinywasm::parse_bytes(&wasm)?; let mut store = Store::default(); - let _unused = tinywasm::HostFunction::from(&mut store, |_ctx: tinywasm::FuncContext<'_>, (): ()| Ok(())); + let _unused = + tinywasm::HostFunction::from(|_ctx: tinywasm::FuncContext<'_>, (): ()| Ok(())).instantiate(&mut store)?; let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; instance.start(&mut store)?; diff --git a/crates/tinywasm/tests/memory_backends.rs b/crates/tinywasm/tests/memory_backends.rs index c231bc1..0cf5707 100644 --- a/crates/tinywasm/tests/memory_backends.rs +++ b/crates/tinywasm/tests/memory_backends.rs @@ -190,7 +190,7 @@ fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> Result< ) "#, )?; - let parser = Parser::with_options(ParserOptions::default().with_local_memory_allocation_optimization(false)); + let parser = Parser::new(ParserOptions::default().with_local_memory_allocation_optimization(false)); let module = parser.parse_module_bytes(&wasm)?; let created = instantiate_module_with_counting_backend(module)?; diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index 6cae984..bcb8e07 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -98,7 +98,7 @@ fn global_import_rejects_wrong_store() -> Result<()> { imports.define("env", "g", global); let mut other_store = Store::default(); - let err = ModuleInstance::instantiate(&mut other_store, &module, Some(imports)).unwrap_err(); + let err = ModuleInstance::instantiate(&mut other_store, &module, Some(&imports)).unwrap_err(); assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore)); Ok(()) } diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index 80494e0..9d88ec8 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -85,7 +85,7 @@ fn imported_global_keeps_its_typed_store_address() -> Result<()> { let global = Global::new(&mut store, GlobalType::new(WasmType::I64, true), WasmValue::I64(1))?; let mut imports = Imports::default(); imports.define("env", "g", global); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; assert_eq!(instance.func::<i64, i64>(&store, "roundtrip")?.call(&mut store, 42)?, 42); assert_eq!(global.get(&store)?, WasmValue::I64(42)); |
