diff options
Diffstat (limited to 'crates')
27 files changed, 716 insertions, 593 deletions
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 069a4e2..861d349 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -32,15 +32,12 @@ pretty_env_logger.workspace = true serde = { workspace = true, optional = true } serde_json = { workspace = true, optional = true } tinywasm = { workspace = true, features = [ - "archive", "canonicalize-nans", "debug", + "full", "guest-debug", "log", - "parallel-parser", - "parser", "std", - "validate", ] } wasm-testsuite = { workspace = true, optional = true } wast = { workspace = true, optional = true } diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 0cd5c34..02add87 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -669,17 +669,20 @@ struct TestCase { fn expand_paths(paths: &[PathBuf]) -> Result<Vec<PathBuf>> { let mut files = Vec::new(); - for path in paths { + let mut pending = paths.to_vec(); + while let Some(path) = pending.pop() { if path.is_dir() { - for entry in std::fs::read_dir(path)? { + for entry in std::fs::read_dir(&path)? { let entry = entry?; let path = entry.path(); - if path.extension().is_some_and(|ext| ext == "wast") { + if entry.file_type()?.is_dir() { + pending.push(path); + } else if path.extension().is_some_and(|ext| ext == "wast") { files.push(path); } } } else { - files.push(path.clone()); + files.push(path); } } files.sort(); @@ -974,6 +977,18 @@ mod tests { } #[test] + fn recursively_runs_wast_files_and_ignores_other_files() { + let dir = tempfile::tempdir().unwrap(); + let nested = dir.path().join("nested"); + std::fs::create_dir(&nested).unwrap(); + std::fs::write(dir.path().join("README.md"), "not a wast file").unwrap(); + std::fs::write(nested.join("simple.wast"), "(module)").unwrap(); + + let mut runner = WastRunner::new(); + runner.run_paths(&[dir.path().to_path_buf()]).unwrap(); + } + + #[test] fn runs_module_definition_and_instance_directives() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("instance.wast"); diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs index d0dfb66..4a64f77 100644 --- a/crates/parser/src/optimize/rewrite.rs +++ b/crates/parser/src/optimize/rewrite.rs @@ -107,6 +107,8 @@ fn rewrite( output.extend([LocalGet32(local), I32Add3]); read = output.len() - 1; } + } else { + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); } } raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { @@ -117,7 +119,10 @@ fn rewrite( if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { continue; } - rewrite_sign_extend32(&mut output, &mut read, data, op); + if rewrite_sign_extend32(&mut output, &mut read, data, op) { + continue; + } + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); } raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { let op = int_bin_op(raw).unwrap(); @@ -129,6 +134,8 @@ fn rewrite( if op == BinOp::IAdd { rewrite!(output, read, [Const64(index)] => AddConst64(index)); rewrite!(output, read, [I64Add] => I64Add3); + } else { + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); } } raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { @@ -138,7 +145,10 @@ fn rewrite( if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { continue; } - rewrite_sign_extend64(&mut output, &mut read, data, op); + if rewrite_sign_extend64(&mut output, &mut read, data, op) { + continue; + } + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); } raw if cmp_op(raw).is_some() => { let op = cmp_op(raw).unwrap(); @@ -149,23 +159,31 @@ fn rewrite( let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - rewrite_scalar_const32(&mut output, &mut read, data, op, true)?; + if !rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); + } } raw @ (F32Sub | F32Div | F32Copysign) => { let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - rewrite_scalar_const32(&mut output, &mut read, data, op, false)?; + if !rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { + rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); + } } raw @ (F64Add | F64Mul | F64Min | F64Max) => { let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite_scalar_const64(&mut output, &mut read, data, op, true)?; + if !rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); + } } raw @ (F64Sub | F64Div | F64Copysign) => { let op = float_bin_op(raw).unwrap(); rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite_scalar_const64(&mut output, &mut read, data, op, false)?; + if !rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { + rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); + } } raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { let op = bin_op_128(raw).unwrap(); @@ -299,6 +317,8 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + Instruction::AndLocalConst32(arg) => Some((BinOp::IAnd, arg.local, arg.value)), + Instruction::ShrULocalConst32(arg) => Some((BinOp::IShrU, arg.local, arg.value)), Instruction::BinOpLocalConst32(packed) => { let value = data.operand64(packed.index); Some((packed.op, value.a(), value.b() as i32)) @@ -348,6 +368,8 @@ fn rewrite_scalar_const32( BinOp::IAdd => Instruction::AddLocalConst32(arg), BinOp::ISub => Instruction::SubLocalConst32(arg), BinOp::IMul => Instruction::MulLocalConst32(arg), + BinOp::IAnd => Instruction::AndLocalConst32(arg), + BinOp::IShrU => Instruction::ShrULocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, @@ -362,6 +384,7 @@ fn rewrite_scalar_const32( match op { BinOp::IAdd => Instruction::AddLocalConst32(arg), BinOp::IMul => Instruction::MulLocalConst32(arg), + BinOp::IAnd => Instruction::AndLocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, @@ -380,6 +403,15 @@ fn rewrite_scalar_const32( Ok(true) } +fn stack_const32(op: BinOp, value: i32) -> Instruction { + match op { + BinOp::IAnd => Instruction::AndConst32(value), + BinOp::IXor => Instruction::XorConst32(value), + BinOp::IShrU => Instruction::ShrUConst32(value), + _ => Instruction::BinOpStackConst32(op, value), + } +} + fn rewrite_scalar_const64( output: &mut CompactOutput, read: &mut usize, @@ -568,7 +600,7 @@ fn rewrite_store64( if let [ Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), Instruction::LoadLocal64(arg), - Instruction::Const64(one), + Instruction::AddConst64(one), ] = previous && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } && addr == u16::from(arg.local1) @@ -820,6 +852,12 @@ fn rewrite_local_tee32( } if *read > output.block_start { match output[*read - 1] { + Instruction::AndConst32(value) => { + replace!(output, *read, 1 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); + } + Instruction::BinOpStackConst32(BinOp::ISub, value) => { + replace!(output, *read, 1 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); + } Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), Instruction::BinOpLocalLocal32(op, left, right) => { let replacement = if op == BinOp::IAdd { @@ -886,6 +924,12 @@ fn rewrite_local_tee64( } if *read > output.block_start { match output[*read - 1] { + Instruction::BinOpStackConst64(packed) if packed.op == BinOp::IAnd => { + replace!(output, *read, 1 => Instruction::AndConstTee64(PackedOp::new(dst, packed.index))); + } + Instruction::BinOpStackConst64(packed) if packed.op == BinOp::ISub => { + replace!(output, *read, 1 => Instruction::SubConstTee64(PackedOp::new(dst, packed.index))); + } Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), Instruction::BinOpLocalLocal64(op, left, right) => { let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; @@ -1222,6 +1266,34 @@ fn rewrite_conditional( replace!(output, *read, 3 => replacement); return Ok(()); } + if *read >= output.block_start + 3 { + let update = match [output[*read - 3], output[*read - 2], output[*read - 1]] { + [Instruction::XorConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] + if local == cond => + { + Some((BinOp::IXor, value, local)) + } + [Instruction::ShrUConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] + if local == cond => + { + Some((BinOp::IShrU, value, local)) + } + [ + Instruction::BinOpStackConst32(op, value), + Instruction::LocalTee32(local), + Instruction::LocalGet32(cond), + ] if local == cond => Some((op, value, local)), + _ => None, + }; + if let Some((op, value, local)) = update { + let replacement = Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?, + )); + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } if *read >= output.block_start + 2 { let update = match [output[*read - 2], output[*read - 1]] { [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 954ae40..e20f6c6 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -11,16 +11,7 @@ keywords.workspace = true categories.workspace = true [package.metadata.docs.rs] -features = [ - "std", - "validate", - "parser", - "archive", - "log", - "canonicalize-nans", - "debug", - "guest-debug" -] +features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "debug", "guest-debug"] rustdoc-args = ["--cfg", "docsrs"] [lib] @@ -98,16 +89,8 @@ wasm-testsuite.workspace = true wat.workspace = true [features] -default = [ - "archive", - "canonicalize-nans", - "debug", - "log", - "parallel-parser", - "parser", - "std", - "validate" -] +default = ["full", "std"] +full = ["archive", "parallel-parser", "parser", "validate"] log = ["dep:log", "tinywasm-parser?/log", "tinywasm-types/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] @@ -119,10 +102,10 @@ send = [] parser = ["dep:tinywasm-parser"] # validate WebAssembly while parsing -validate = ["parser", "tinywasm-parser/validate"] +validate = ["tinywasm-parser?/validate"] # parallelize function parsing/validation across threads (requires std) -parallel-parser = ["parser", "tinywasm-parser?/parallel"] +parallel-parser = ["tinywasm-parser?/parallel"] # support targets without native atomic CAS portable-atomic = ["dep:portable-atomic", "tinywasm-parser?/portable-atomic", "tinywasm-types/portable-atomic"] diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index bdc50a3..9a05f8b 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -22,10 +22,7 @@ impl FuncContext<'_> { /// Get the module instance. pub fn module(&self) -> &crate::ModuleInstance { - unwrap_or_unreachable!( - self.store.get_module_instance(self.module_id), - "invalid module instance id in host function context" - ) + self.store.get_module_instance(self.module_id).expect("invalid module instance id in host function context") } /// Get a memory export. @@ -88,17 +85,17 @@ impl FuncContext<'_> { return Err(Error::other("FuncContext::call requires an active host-function invocation")); } - func.validate_call(self.store, args, results.len())?; + let type_addr = func.validate_call(self.store, args, results.len())?; let call_stack_base = self.store.call_stack.len(); let value_stack_base = self.store.value_stack.base(); - func.call_untyped(self.store, args, results, call_stack_base, value_stack_base) + func.call_untyped(self.store, type_addr, args, results, call_stack_base, value_stack_base) } /// Calls a Store-aware function reference in the current module context. pub fn call_ref(&mut self, func: FuncRef, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { let addr = func.addr(self.store.id()).ok_or(crate::Trap::InvalidStore)?; - if self.store.state.funcs.get(addr as usize).is_none() { + if !self.store.state.funcs.contains(addr) { return Err(crate::Trap::InvalidReference.into()); } let function = Function { item: crate::StoreItem::new(self.store.id(), addr), module_id: self.module_id }; @@ -118,32 +115,9 @@ impl FuncContext<'_> { 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.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) - { - let ty = self.store.state.get_canonical_func_type(func_instance.type_addr); - let (param_count, result_count) = (ty.params().len(), ty.results().len()); - self.store.with_scratch_values(param_count + result_count, |store, values| { - super::write_typed_params(&mut values[..param_count], params.into_wasm_values())?; - let (params, results) = values.split_at_mut(param_count); - func.func.validate_call(store, params, results.len())?; - let call_stack_base = store.call_stack.len(); - let value_stack_base = store.value_stack.base(); - func.func.call_untyped(store, params, results, call_stack_base, value_stack_base)?; - values.drain(..param_count); - R::from_wasm_values(&mut values.drain(..)) - }) - } else { - 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, - ) - } + let call_stack_base = self.store.call_stack.len(); + let value_stack_base = self.store.value_stack.base(); + func.func.call_typed(self.store, params.into_wasm_values(), call_stack_base, value_stack_base) } } diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 5e3fefa..ec81926 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -4,7 +4,7 @@ use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType}; use super::{FromWasmValues, FuncContext, IntoWasmValues}; use crate::shared::StoreShared; use crate::store::FuncValueTypes; -use crate::{Function, FunctionInstance, Result, Store, WasmValue}; +use crate::{Function, Result, Store, WasmValue}; /// Trait bounds required for a host callback in the current build mode. #[doc(hidden)] @@ -31,8 +31,7 @@ pub struct HostFunction(StoreShared<HostFunctionInner>); impl HostFunction { /// Instantiates the function with an already registered canonical type. pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function { - let addr = store - .add_func(FunctionInstance { type_addr, inner: crate::store::FunctionInstanceInner::Host(self.clone()) }); + let addr = store.add_host_func(type_addr, self.clone()); Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } } @@ -64,22 +63,28 @@ impl HostFunction { args: &[WasmValue], results: &mut [WasmValue], ) -> Result<()> { - let expected = store.state.get_canonical_func_type(type_addr).clone(); - if results.len() != expected.results().len() { - return Err(crate::Error::other("host result buffer has the wrong length")); - } - for (result, ty) in results.iter_mut().zip(expected.results()) { - *result = match ty { - WasmType::I32 => WasmValue::I64(0), - _ => WasmValue::I32(0), - }; + { + let expected = store.state.get_canonical_func_type(type_addr); + if results.len() != expected.results().len() { + return Err(crate::Error::other("host result buffer has the wrong length")); + } + for (result, ty) in results.iter_mut().zip(expected.results()) { + *result = match ty { + WasmType::I32 => WasmValue::I64(0), + _ => WasmValue::I32(0), + }; + } } match &self.0.callback { HostCallback::Untyped(func) => func(FuncContext { store, module_id }, args, results)?, HostCallback::Typed(func) => func.call(FuncContext { store, module_id }, args, results)?, } + let expected = store.state.get_canonical_func_type(type_addr); if !results.iter().zip(expected.results()).all(|(value, &ty)| store.value_matches_type(value, ty)) { - return Err(crate::Error::InvalidHostFnReturn { expected: Box::new(expected), actual: results.to_vec() }); + return Err(crate::Error::InvalidHostFnReturn { + expected: Box::new(expected.clone()), + actual: results.to_vec(), + }); } Ok(()) } diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index 3f5ef54..744356d 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -1,6 +1,6 @@ use crate::interpreter::stack::{CallFrame, StackBase}; use crate::reference::StoreItem; -use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store}; +use crate::{Error, InterpreterRuntime, Result, Store}; use alloc::format; use core::hint::cold_path; use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId}; @@ -65,19 +65,36 @@ impl Function { /// match the function signature. #[inline] pub fn call(&self, store: &mut Store, params: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { - self.validate_call(store, params, results.len())?; + let type_addr = self.validate_call(store, params, results.len())?; store.enter_execution()?; store.call_stack.clear(); store.value_stack.clear(); - let result = self.call_untyped(store, params, results, 0, StackBase::default()); + let result = self.call_untyped(store, type_addr, params, results, 0, StackBase::default()); store.exit_execution(); result } - fn validate_call(&self, store: &Store, params: &[WasmValue], result_count: usize) -> Result<()> { + fn validate_call( + &self, + store: &Store, + params: &[WasmValue], + result_count: usize, + ) -> Result<tinywasm_types::TypeAddr> { self.item.validate_store(store)?; - let func_ty = store.state.get_func_type(self.addr()); + let type_addr = store.state.funcs.type_addr(self.addr()); + self.validate_call_type(store, type_addr, params, result_count)?; + Ok(type_addr) + } + + fn validate_call_type( + &self, + store: &Store, + type_addr: tinywasm_types::TypeAddr, + params: &[WasmValue], + result_count: usize, + ) -> Result<()> { + let func_ty = store.state.get_canonical_func_type(type_addr); if func_ty.params().len() != params.len() { cold_path(); return Err(Error::Other(format!( @@ -117,62 +134,33 @@ impl Function { fn call_untyped( &self, store: &mut Store, + type_addr: tinywasm_types::TypeAddr, params: &[WasmValue], results: &mut [WasmValue], call_stack_base: u32, value_stack_base: StackBase, ) -> Result<()> { - let instance = store.state.get_func(self.addr()); - let type_addr = instance.type_addr; - match &instance.inner { - crate::store::FunctionInstanceInner::Host(host) => { - let host = host.clone(); - host.call_values(store, self.module_id, type_addr, params, results) - } - crate::store::FunctionInstanceInner::Wasm(wasm) => { + if store.state.funcs.is_host(self.addr()) { + let host = store.state.funcs.host(self.addr()).func.clone(); + host.call_values(store, self.module_id, type_addr, params, results) + } else { + let (wasm_params, wasm_locals) = { + let wasm = store.state.funcs.wasm(self.addr()); let wasm_params = wasm.func.params; let wasm_locals = wasm.func.locals; - store - .push_wasm_values(params.iter().cloned()) - .inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?; - let locals_base = store - .value_stack - .enter_locals(&wasm_params, &wasm_locals) - .inspect_err(|_| store.value_stack.truncate_to_base(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_type = store.state.get_canonical_func_type(type_addr).clone(); - store.pop_stack_values(result_type.results(), results) - } - } - } - - 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.inner { - crate::store::FunctionInstanceInner::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::FunctionInstanceInner::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) - } + (wasm_params, wasm_locals) + }; + store.push_wasm_values(params).inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?; + let locals_base = store + .value_stack + .enter_locals(&wasm_params, &wasm_locals) + .inspect_err(|_| store.value_stack.truncate_to_base(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); + })?; + store.pop_stack_values(type_addr, results) } } @@ -180,18 +168,53 @@ impl Function { 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); - })?; + if store.state.funcs.is_host(self.addr()) { + let (type_addr, host) = { + let host = store.state.funcs.host(self.addr()); + (host.type_addr, host.func.clone()) + }; + return match host.typed_callback() { + Some(callback) => { + store.push_typed_values::<false>(type_addr, params, value_stack_base)?; + callback + .call_stack(store, self.module_id, type_addr) + .inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?; + store.take_typed_results(type_addr, value_stack_base) + } + None => { + let ty = store.state.get_canonical_func_type(type_addr); + let (param_count, result_count) = (ty.params().len(), ty.results().len()); + store.with_scratch_values(param_count + result_count, |store, values| { + write_typed_params(&mut values[..param_count], params)?; + let (params, results) = values.split_at_mut(param_count); + self.validate_call_type(store, type_addr, params, results.len())?; + host.call_values(store, self.module_id, type_addr, params, results)?; + values.drain(..param_count); + R::from_wasm_values(&mut values.drain(..)) + }) + } + }; } - store.take_typed_results(instance.type_addr, value_stack_base) + + let (type_addr, wasm_params, wasm_locals) = { + let wasm = store.state.funcs.wasm(self.addr()); + (wasm.type_addr, wasm.func.params, wasm.func.locals) + }; + store.push_typed_values::<false>(type_addr, params, value_stack_base)?; + let locals_base = store + .value_stack + .enter_locals(&wasm_params, &wasm_locals) + .inspect_err(|_| store.value_stack.truncate_to_base(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); + })?; + store.take_typed_results(type_addr, value_stack_base) } } @@ -210,26 +233,11 @@ 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.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { - let ty = store.state.get_canonical_func_type(func.type_addr); - let (param_count, result_count) = (ty.params().len(), ty.results().len()); - store.with_scratch_values(param_count + result_count, |store, values| { - write_typed_params(&mut values[..param_count], params.into_wasm_values())?; - let (params, results) = values.split_at_mut(param_count); - self.func.call(store, params, results)?; - values.drain(..param_count); - R::from_wasm_values(&mut values.drain(..)) - }) - } else { - 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 - } + store.enter_execution()?; + store.call_stack.clear(); + store.value_stack.clear(); + let result = self.func.call_typed(store, 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 index c0d7f23..95c5bde 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -57,27 +57,36 @@ impl Function { params: &[WasmValue], results: &'store mut [WasmValue], ) -> Result<FuncExecution<'store>> { - self.validate_call(store, params, results.len())?; + let type_addr = self.validate_call(store, params, results.len())?; store.enter_execution()?; let result: Result<ExecState> = (|| { - let func_instance = store.state.get_func(self.addr()).clone(); - match &func_instance.inner { - crate::store::FunctionInstanceInner::Host(host_func) => { - host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params, results)?; - Ok(ExecState::Completed(Some(CallResult::Written))) - } - crate::store::FunctionInstanceInner::Wasm(wasm_func) => { - store.call_stack.clear(); - store.value_stack.clear(); - store.push_wasm_values(params.iter().cloned())?; - let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals)?; - let callframe = CallFrame::new(self.addr(), locals_base, wasm_func.func.locals); - - Ok(ExecState::Running { callframe, root_func_addr: self.addr() }) - } + if store.state.funcs.is_host(self.addr()) { + let func = { + let func = store.state.funcs.host(self.addr()); + func.func.clone() + }; + func.call_values(store, self.module_id, type_addr, params, results)?; + return Ok(ExecState::Completed(Some(CallResult::Written))); } + + let (wasm_params, wasm_locals) = { + let wasm = store.state.funcs.wasm(self.addr()); + (wasm.func.params, wasm.func.locals) + }; + + store.call_stack.clear(); + store.value_stack.clear(); + store.push_wasm_values(params)?; + let locals_base = store.value_stack.enter_locals(&wasm_params, &wasm_locals)?; + let callframe = CallFrame::new(self.addr(), locals_base, wasm_locals); + + Ok(ExecState::Running { callframe, root_func_addr: self.addr() }) })(); + if result.is_err() { + store.call_stack.clear(); + store.value_stack.clear(); + } store.exit_execution(); let state = result?; @@ -116,8 +125,7 @@ impl ExecutionInner<'_> { match result { crate::interpreter::ExecState::Completed => { - let func = self.store.state.get_func(root_func_addr); - let result_ty = func.type_addr; + let result_ty = self.store.state.funcs.type_addr(root_func_addr); self.state = ExecState::Completed(None); Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty })) } @@ -139,8 +147,7 @@ impl FuncExecution<'_> { ) -> Result<ExecProgress<()>> { match self.execution.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr }) => { - let ty = self.execution.store.state.get_canonical_func_type(type_addr).clone(); - self.execution.store.pop_stack_values(ty.results(), self.results)?; + self.execution.store.pop_stack_values(type_addr, self.results)?; Ok(ExecProgress::Completed(())) } ExecProgress::Completed(CallResult::Written) => Ok(ExecProgress::Completed(())), @@ -203,21 +210,27 @@ impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> { /// ``` 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.inner, crate::store::FunctionInstanceInner::Host(host) if host.typed_callback().is_none()) { + if store.state.funcs.is_host(self.func.addr()) { let result = self.call(store, params)?; let execution = ExecutionInner { store, state: ExecState::Completed(None) }; return Ok(FuncExecutionTyped { execution, result: Some(result) }); } + let (type_addr, wasm_params, wasm_locals) = { + let wasm = store.state.funcs.wasm(self.func.addr()); + (wasm.type_addr, wasm.func.params, wasm.func.locals) + }; store.enter_execution()?; let result: Result<ExecState> = (|| { store.call_stack.clear(); store.value_stack.clear(); - match self.func.prepare_typed(store, &func, params.into_wasm_values(), StackBase::default())? { - Some(callframe) => Ok(ExecState::Running { callframe, root_func_addr: self.func.addr() }), - None => Ok(ExecState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), - } + store.push_typed_values::<false>(type_addr, params.into_wasm_values(), StackBase::default())?; + let locals_base = store + .value_stack + .enter_locals(&wasm_params, &wasm_locals) + .inspect_err(|_| store.value_stack.clear())?; + let callframe = CallFrame::new(self.func.addr(), locals_base, wasm_locals); + Ok(ExecState::Running { callframe, root_func_addr: self.func.addr() }) })(); store.exit_execution(); let execution = ExecutionInner { store, state: result? }; diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 6859bbf..35affab 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -328,8 +328,7 @@ impl Imports { (ExternVal::Func(func_addr), ImportKind::Function(ty)) => { let expected_type_addr = type_addrs.get(*ty as usize).ok_or_else(|| LinkingError::incompatible_import_type(import))?; - if !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr) - { + if !store.state.type_addr_is_subtype(store.state.funcs.type_addr(func_addr), *expected_type_addr) { return cold!(Err(LinkingError::incompatible_import_type(import).into())); } imports.funcs.push(func_addr); diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 08682e3..581eb9e 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -68,25 +68,25 @@ struct ModuleInstanceInner { impl ModuleInstance { #[inline] pub(crate) fn resolve_type_addr(&self, type_addr: TypeAddr) -> TypeAddr { - *unwrap_or_unreachable!(self.0.type_addrs.get(type_addr as usize), "invalid type address: {type_addr}") + self.0.type_addrs[type_addr as usize] } /// resolve a function address to the global store address #[inline] pub(crate) fn resolve_func_addr(&self, addr: FuncAddr) -> FuncAddr { - *unwrap_or_unreachable!(self.0.func_addrs.get(addr as usize), "invalid function address: {addr}") + self.0.func_addrs[addr as usize] } /// resolve a table address to the global store address #[inline] pub(crate) fn resolve_table_addr(&self, addr: TableAddr) -> TableAddr { - *unwrap_or_unreachable!(self.0.table_addrs.get(addr as usize), "invalid table address: {addr}") + self.0.table_addrs[addr as usize] } /// resolve a memory address to the global store address #[inline] pub(crate) fn resolve_mem_addr(&self, addr: MemAddr) -> MemAddr { - *unwrap_or_unreachable!(self.0.mem_addrs.get(addr as usize), "invalid memory address: {addr}") + self.0.mem_addrs[addr as usize] } /// The resolved store address of the module's first memory, or `MemAddr::MAX` when the module @@ -103,24 +103,24 @@ impl ModuleInstance { /// resolve a data address to the global store address #[inline] pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr { - *unwrap_or_unreachable!(self.0.data_addrs.get(addr as usize), "invalid data address: {addr}") + self.0.data_addrs[addr as usize] } /// resolve an element address to the global store address #[inline] pub(crate) fn resolve_elem_addr(&self, addr: ElemAddr) -> ElemAddr { - *unwrap_or_unreachable!(self.0.elem_addrs.get(addr as usize), "invalid element address: {addr}") + self.0.elem_addrs[addr as usize] } /// resolve a global address to the global store address #[inline] pub(crate) fn resolve_global_addr(&self, addr: GlobalAddr) -> GlobalAddr { - *unwrap_or_unreachable!(self.0.global_addrs.get(addr as usize), "invalid global address: {addr}") + self.0.global_addrs[addr as usize] } #[inline] pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr { - *unwrap_or_unreachable!(self.0.tag_addrs.get(addr as usize), "invalid tag address: {addr}") + self.0.tag_addrs[addr as usize] } #[inline] diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index fa3f3f1..5266084 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -1,4 +1,4 @@ -use core::ops::ControlFlow; +use core::{convert::identity, ops::ControlFlow}; #[cfg(not(feature = "std"))] #[allow(unused_imports)] @@ -31,38 +31,12 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> { impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self { - let wasm_func = store.state.get_wasm_func(cf.func_addr); - let module = - unwrap_or_unreachable!(store.get_module_instance(wasm_func.owner), "invalid module instance").clone(); + let wasm_func = store.state.funcs.wasm(cf.func_addr); + let module = store.get_module_instance(wasm_func.owner).expect("invalid module instance").clone(); let mem0 = module.mem0_addr(); Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 } } - /// Resolves a module-local memory index to its store address, caching the common memory-0 case. - #[inline(always)] - fn mem_addr(&self, idx: MemAddr) -> MemAddr { - if idx == 0 { self.mem0 } else { self.module.resolve_mem_addr(idx) } - } - - /// Switches the executor to another module, keeping the cached memory-0 address in sync. - #[inline] - fn set_module(&mut self, owner: ModuleInstanceId) { - self.module = unwrap_or_unreachable!(self.store.get_module_instance(owner), "invalid module instance").clone(); - self.mem0 = self.module.mem0_addr(); - } - - #[inline(always)] - fn charge_call_fuel(&mut self, total_fuel_cost: u32) { - if BUDGETED { - let extra = match self.store.engine.config().fuel_policy { - FuelPolicy::PerInstruction => 0, - FuelPolicy::Weighted => total_fuel_cost.saturating_sub(1), - }; - - self.store.execution_fuel = self.store.execution_fuel.saturating_sub(extra); - } - } - #[inline(always)] fn exec(&mut self, instr_ptr: usize) -> Result<ControlFlow<(), usize>> { macro_rules! exec_op { @@ -179,7 +153,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(*c)); }, + AndConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value & *c); }, + XorConst32(c) => { i32::stack_update(&mut self.store.value_stack, |value| value ^ *c); }, + ShrUConst32(c) => { u32::stack_update(&mut self.store.value_stack, |value| value.wrapping_shr(*c as u32)); }, AddConst64(idx) => { let rhs = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, |value| value.wrapping_add(rhs)); }, + BinOpStackConst32(op, rhs) => { u32::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, *rhs as u32)); }, + BinOpStackConst64(packed) => { let rhs = packed.index.resolve(&self.func.data).value() as u64; u64::stack_update(&mut self.store.value_stack, |lhs| packed.op.exec(lhs, rhs)); }, IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |value| value.wrapping_add(arg.value)); }, IncLocal64(packed) => { let rhs = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |value| value.wrapping_add(rhs)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), @@ -204,24 +183,26 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { AddLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAdd)?, SubLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::ISub)?, MulLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IMul)?, + AndLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAnd)?, + ShrULocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IShrU)?, BinOpLocalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, true>(v.a(), v.b(), None, packed.op)?; }, BinOpLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, true>(v.a(), v.b(), None, packed.op)?; }, BinOpLocalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_local_const::<Value128, true>(v.a(), rhs, None, packed.op)?; }, - BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value32>(v.a(), v.b(), packed.op)?; }, - BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value64>(v.a(), v.b(), packed.op)?; }, - BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::<Value128>(v.a(), rhs, packed.op)?; }, BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, false>(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, true>(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, false>(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, true>(v.a(), v.c(), Some(v.b()), packed.op)?; }, BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::<Value128, false>(v.a(), rhs, Some(v.b()), packed.op)?; }, BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::<Value128, true>(v.a(), rhs, Some(v.b()), packed.op)?; }, - BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::<Value32>(*global_index, *op)?, - BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::<Value64>(*global_index, *op)?, BinOpStackLocal32(op, local) => self.exec_binop_stack_local::<Value32, true>(*local, None, *op)?, BinOpStackLocalSet32(op, local, dst) => self.exec_binop_stack_local::<Value32, false>(*local, Some(*dst), *op)?, BinOpStackLocalTee32(op, local, dst) => self.exec_binop_stack_local::<Value32, true>(*local, Some(*dst), *op)?, BinOpStackLocal128(op, local) => self.exec_binop_stack_local::<Value128, true>(*local, None, *op)?, + BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::<Value32>(*global_index, *op)?, + BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::<Value64>(*global_index, *op)?, + BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value32>(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value64>(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::<Value128>(v.a(), rhs, packed.op)?; }, SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), SetLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.resolve(&self.func.data).value())), @@ -230,14 +211,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { StoreLocalLocal32(arg) => self.exec_store_local_local::<u32, 4>(arg.memory_arg_idx, arg.local1, arg.local2)?, StoreLocalLocal64(arg) => self.exec_store_local_local::<i64, 8>(arg.memory_arg_idx, arg.local1, arg.local2)?, StoreLocalLocal128(arg) => self.exec_store_local_local::<Value128, 16>(arg.memory_arg_idx, arg.local1, arg.local2)?, - LoadLocal32(arg) => self.exec_load_local::<i32, 4, _, false, false>(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, - LoadLocal64(arg) => self.exec_load_local::<i64, 8, _, false, false>(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, + LoadLocal32(arg) => self.exec_load_local::<i32, 4, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?, + LoadLocal64(arg) => self.exec_load_local::<i64, 8, _, false, false>(arg.memory_arg_idx, arg.local1, 0, identity)?, LoadLocal8S32(arg) => self.exec_load_local::<i8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, LoadLocal8U32(arg) => self.exec_load_local::<u8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, LoadLocal16S32(arg) => self.exec_load_local::<i16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, LoadLocal16U32(arg) => self.exec_load_local::<u16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?, - LoadLocalTee32(arg) => self.exec_load_local::<i32, 4, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, - LoadLocalSet32(arg) => self.exec_load_local::<i32, 4, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalTee32(arg) => self.exec_load_local::<i32, 4, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet32(arg) => self.exec_load_local::<i32, 4, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, LoadLocalTee8S32(arg) => self.exec_load_local::<i8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalTee8U32(arg) => self.exec_load_local::<u8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalTee16S32(arg) => self.exec_load_local::<i16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, @@ -246,8 +227,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LoadLocalSet8U32(arg) => self.exec_load_local::<u8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalSet16S32(arg) => self.exec_load_local::<i16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, LoadLocalSet16U32(arg) => self.exec_load_local::<u16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, - LoadLocalTee128(arg) => self.exec_load_local::<Value128, 16, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, - LoadLocalSet128(arg) => self.exec_load_local::<Value128, 16, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalTee128(arg) => self.exec_load_local::<Value128, 16, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, + LoadLocalSet128(arg) => self.exec_load_local::<Value128, 16, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, identity)?, AndConstTee32(arg) => self.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::IAnd)?, SubConstTee32(arg) => self.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::ISub)?, AndConstTee64(packed) => self.exec_binop_const_tee::<Value64>(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::IAnd)?, @@ -405,10 +386,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { TableCopy(idx) => self.exec_table_copy(*idx)?, // Core memory load/store operations - I32Store(idx) => self.exec_mem_store::<i32, i32, 4>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - I64Store(idx) => self.exec_mem_store::<i64, i64, 8>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F32Store(idx) => self.exec_mem_store::<f32, f32, 4>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F64Store(idx) => self.exec_mem_store::<f64, f64, 8>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I32Store(idx) => self.exec_mem_store::<i32, i32, 4>(idx.resolve(&self.func.data), identity)?, + I64Store(idx) => self.exec_mem_store::<i64, i64, 8>(idx.resolve(&self.func.data), identity)?, + F32Store(idx) => self.exec_mem_store::<f32, f32, 4>(idx.resolve(&self.func.data), identity)?, + F64Store(idx) => self.exec_mem_store::<f64, f64, 8>(idx.resolve(&self.func.data), identity)?, FMaStoreF32(m) => self.exec_fma_store::<f32, 4>(*m)?, FMaStoreF64(m) => self.exec_fma_store::<f64, 8>(*m)?, I32Store8(idx) => self.exec_mem_store::<i32, i8, 1>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, @@ -416,10 +397,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Store8(idx) => self.exec_mem_store::<i64, i8, 1>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, I64Store16(idx) => self.exec_mem_store::<i64, i16, 2>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, I64Store32(idx) => self.exec_mem_store::<i64, i32, 4>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i32)?, - I32Load(idx) => self.exec_mem_load::<i32, 4, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - I64Load(idx) => self.exec_mem_load::<i64, 8, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F32Load(idx) => self.exec_mem_load::<f32, 4, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, - F64Load(idx) => self.exec_mem_load::<f64, 8, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I32Load(idx) => self.exec_mem_load::<i32, 4, _>(idx.resolve(&self.func.data), identity)?, + I64Load(idx) => self.exec_mem_load::<i64, 8, _>(idx.resolve(&self.func.data), identity)?, + F32Load(idx) => self.exec_mem_load::<f32, 4, _>(idx.resolve(&self.func.data), identity)?, + F64Load(idx) => self.exec_mem_load::<f64, 8, _>(idx.resolve(&self.func.data), identity)?, I32Load8S(idx) => self.exec_mem_load::<i8, 1, _>(idx.resolve(&self.func.data), i32::from)?, I32Load8U(idx) => self.exec_mem_load::<u8, 1, _>(idx.resolve(&self.func.data), i32::from)?, I32Load16S(idx) => self.exec_mem_load::<i16, 2, _>(idx.resolve(&self.func.data), i32::from)?, @@ -501,7 +482,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(idx) => self.exec_mem_load::<Value128, 16, _>(idx.resolve(&self.func.data), |v| v)?, + V128Load(idx) => self.exec_mem_load::<Value128, 16, _>(idx.resolve(&self.func.data), identity)?, V128Load8x8S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, V128Load8x8U(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, V128Load16x4S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, @@ -512,7 +493,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128Load16Splat(idx) => self.exec_mem_load::<i16, 2, Value128>(idx.resolve(&self.func.data), Value128::splat_i16)?, V128Load32Splat(idx) => self.exec_mem_load::<i32, 4, Value128>(idx.resolve(&self.func.data), Value128::splat_i32)?, V128Load64Splat(idx) => self.exec_mem_load::<i64, 8, Value128>(idx.resolve(&self.func.data), Value128::splat_i64)?, - V128Store(idx) => self.exec_mem_store::<Value128, Value128, 16>(idx.resolve(&self.func.data), |v| v)?, + V128Store(idx) => self.exec_mem_store::<Value128, Value128, 16>(idx.resolve(&self.func.data), identity)?, V128Store8Lane(arg) => self.exec_mem_store_lane::<i8, 1>(*arg)?, V128Store16Lane(arg) => self.exec_mem_store_lane::<i16, 2>(*arg)?, V128Store32Lane(arg) => self.exec_mem_store_lane::<i32, 4>(*arg)?, @@ -753,6 +734,31 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(ControlFlow::Continue(instr_ptr + 1)) } + /// Resolves a module-local memory index to its store address, caching the common memory-0 case. + #[inline(always)] + fn mem_addr(&self, idx: MemAddr) -> MemAddr { + if idx == 0 { self.mem0 } else { self.module.resolve_mem_addr(idx) } + } + + /// Switches the executor to another module, keeping the cached memory-0 address in sync. + #[inline] + fn set_module(&mut self, owner: ModuleInstanceId) { + self.module = self.store.get_module_instance(owner).expect("invalid module instance").clone(); + self.mem0 = self.module.mem0_addr(); + } + + #[inline(always)] + fn charge_call_fuel(&mut self, total_fuel_cost: u32) { + if BUDGETED { + let extra = match self.store.engine.config().fuel_policy { + FuelPolicy::PerInstruction => 0, + FuelPolicy::Weighted => total_fuel_cost.saturating_sub(1), + }; + + self.store.execution_fuel = self.store.execution_fuel.saturating_sub(extra); + } + } + #[inline(always)] fn exec_jump_if_ref<const ON_NULL: bool>(&mut self) -> bool { let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); @@ -765,7 +771,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_br_on_cast<const ON_MATCH: bool>(&self, index: Operand64Idx<(u32, u32)>) -> Option<usize> { let operand = index.resolve(&self.func.data); - let ty = unwrap_or_unreachable!(RefType::from_bits(operand.b())); + let ty = RefType::from_bits(operand.b()).expect("invalid ref type"); (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize) } @@ -821,7 +827,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ) -> Option<usize> { let operand = packed.index.resolve(&self.func.data); let lhs = i32::local_update(&mut self.store.value_stack, &self.cf, operand.local(), |value| { - value.wrapping_add(operand.value()) + packed.op.0.exec(value as u32, operand.value() as u32) as i32 }); let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize) @@ -959,6 +965,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64) } + #[inline(always)] fn exec_simd_extract_lane<TO: InternalValue>( &mut self, lane: u8, @@ -968,6 +975,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { TO::stack_push(&mut self.store.value_stack, operation(vector, lane)) } + #[inline(always)] fn exec_simd_replace_lane<VALUE: InternalValue>( &mut self, lane: u8, @@ -1210,8 +1218,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return; } - let wasm_func = self.store.state.get_wasm_func(self.cf.func_addr); - self.func = wasm_func.func.clone(); + let wasm_func = self.store.state.funcs.wasm(self.cf.func_addr); + if !Shared::ptr_eq(&self.func, &wasm_func.func) { + self.func = wasm_func.func.clone(); + } if wasm_func.owner != self.module.id() { self.set_module(wasm_func.owner); } @@ -1253,54 +1263,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Ok(None); }; self.switch_to_frame(caller); - protected_ip = unwrap_or_unreachable!(self.cf.instr_ptr.checked_sub(1), "invalid caller IP"); + protected_ip = self.cf.instr_ptr.checked_sub(1).expect("invalid caller IP"); } } - fn exec_call( - &mut self, - wasm_func: Shared<WasmFunction>, - owner: ModuleInstanceId, - func_addr: FuncAddr, - return_instr_ptr: usize, - ) -> Result<(), Trap> { - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); - }; - - self.store.call_stack.push(self.cf, return_instr_ptr)?; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals); - if !Shared::ptr_eq(&self.func, &wasm_func) { - self.func = wasm_func; - } - if owner != self.module.id() { - self.set_module(owner); - } - - Ok(()) - } - - fn exec_return_call( - &mut self, - wasm_func: Shared<WasmFunction>, - owner: ModuleInstanceId, - func_addr: FuncAddr, - ) -> Result<(), Trap> { - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.params); - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); - }; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.locals); - if !Shared::ptr_eq(&self.func, &wasm_func) { - self.func = wasm_func; - } - if owner != self.module.id() { - self.set_module(owner); - } - - Ok(()) - } - fn exec_call_host<const TAIL: bool>( &mut self, host_func: HostFunction, @@ -1332,7 +1298,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { host_func .call_values(store, module_id, type_addr, params, results) .map_err(|error| Error::Trap(Trap::HostFunction(Box::new(error))))?; - store.push_wasm_values(results.iter().cloned()) + store.push_wasm_values(results) }) .map_err(|error| match error { Error::Trap(trap) => trap, @@ -1344,30 +1310,56 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result<ControlFlow<(), usize>> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr); - match &func.inner { - crate::store::FunctionInstanceInner::Wasm(wasm_func) => { - self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr, return_instr_ptr)?; - Ok(ControlFlow::Continue(0)) + if self.store.state.funcs.is_host(addr) { + let host_func = self.store.state.funcs.host(addr); + let type_addr = host_func.type_addr; + let host_func = host_func.func.clone(); + self.exec_call_host::<false>(host_func, type_addr, return_instr_ptr) + } else { + let wasm_func = self.store.state.funcs.wasm(addr); + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) + else { + return cold!(Err(Trap::CallStackOverflow.into())); + }; + + self.store.call_stack.push(self.cf, return_instr_ptr)?; + self.cf = CallFrame::new(addr, locals_base, wasm_func.func.locals); + if !Shared::ptr_eq(&self.func, &wasm_func.func) { + self.func = wasm_func.func.clone(); } - crate::store::FunctionInstanceInner::Host(host_func) => { - self.exec_call_host::<false>(host_func.clone(), func.type_addr, return_instr_ptr) + if wasm_func.owner != self.module.id() { + self.set_module(wasm_func.owner); } + Ok(ControlFlow::Continue(0)) } } fn exec_return_call_direct(&mut self, v: u32) -> Result<ControlFlow<(), usize>> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr); - match &func.inner { - crate::store::FunctionInstanceInner::Wasm(wasm_func) => { - self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, addr)?; - Ok(ControlFlow::Continue(0)) + if self.store.state.funcs.is_host(addr) { + let host_func = self.store.state.funcs.host(addr); + let type_addr = host_func.type_addr; + let host_func = host_func.func.clone(); + self.exec_call_host::<true>(host_func, type_addr, 0) + } else { + let wasm_func = self.store.state.funcs.wasm(addr); + let (params, locals, owner, next_func) = { + let next_func = (!Shared::ptr_eq(&self.func, &wasm_func.func)).then(|| wasm_func.func.clone()); + (wasm_func.func.params, wasm_func.func.locals, wasm_func.owner, next_func) + }; + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params); + let Ok(locals_base) = self.store.value_stack.enter_locals(¶ms, &locals) else { + return cold!(Err(Trap::CallStackOverflow.into())); + }; + self.cf = CallFrame::new(addr, locals_base, locals); + if let Some(next_func) = next_func { + self.func = next_func; } - crate::store::FunctionInstanceInner::Host(host_func) => { - self.exec_call_host::<true>(host_func.clone(), func.type_addr, 0) + if owner != self.module.id() { + self.set_module(owner); } + Ok(ControlFlow::Continue(0)) } } @@ -1378,7 +1370,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; let new = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); self.store.call_stack.push(core::mem::replace(&mut self.cf, new), return_instr_ptr)?; - Ok(ControlFlow::Continue(0)) } @@ -1424,23 +1415,51 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { expected_type_addr: TypeAddr, return_instr_ptr: usize, ) -> Result<ControlFlow<(), usize>> { - let func = self.store.state.get_func(func_addr); - if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { + if self.store.state.funcs.is_host(func_addr) { + let host_func = self.store.state.funcs.host(func_addr); + let type_addr = host_func.type_addr; + if !self.store.state.type_addr_is_subtype(type_addr, expected_type_addr) { + return cold!(Err(Trap::IndirectCallTypeMismatch { + actual: Box::new(self.store.state.get_canonical_func_type(type_addr).clone()), + expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), + } + .into())); + } + let host_func = host_func.func.clone(); + return self.exec_call_host::<IS_RETURN_CALL>(host_func, type_addr, return_instr_ptr); + } + + let wasm_func = self.store.state.funcs.wasm(func_addr); + let type_addr = wasm_func.type_addr; + if !self.store.state.type_addr_is_subtype(type_addr, expected_type_addr) { return cold!(Err(Trap::IndirectCallTypeMismatch { - actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), + actual: Box::new(self.store.state.get_canonical_func_type(type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), } .into())); } - match &func.inner { - crate::store::FunctionInstanceInner::Wasm(wasm_func) => match IS_RETURN_CALL { - true => self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, func_addr), - false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr, return_instr_ptr), - }, - crate::store::FunctionInstanceInner::Host(host_func) => { - return self.exec_call_host::<IS_RETURN_CALL>(host_func.clone(), func.type_addr, return_instr_ptr); - } + let (params, locals, owner, next_func) = { + let next_func = (!Shared::ptr_eq(&self.func, &wasm_func.func)).then(|| wasm_func.func.clone()); + (wasm_func.func.params, wasm_func.func.locals, wasm_func.owner, next_func) + }; + let locals_base = if IS_RETURN_CALL { + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, params); + self.store.value_stack.enter_locals(¶ms, &locals) + } else { + self.store.value_stack.enter_locals(¶ms, &locals) }?; + if IS_RETURN_CALL { + self.cf = CallFrame::new(func_addr, locals_base, locals); + } else { + self.store.call_stack.push(self.cf, return_instr_ptr)?; + self.cf = CallFrame::new(func_addr, locals_base, locals); + } + if let Some(next_func) = next_func { + self.func = next_func; + } + if owner != self.module.id() { + self.set_module(owner); + } Ok(ControlFlow::Continue(0)) } @@ -1572,27 +1591,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cold_err!(fma.store_at(&mut mem.inner, addr)) } - fn exec_load_local_value<T: MemValue<N>, const N: usize>( - &self, - memarg: Operand64<CompactMemoryOperand>, - addr_local: u8, - ) -> Result<T, Trap> { - let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory()))); - let addr = if mem.is_64bit() { - let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; - let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { - offset: usize::MAX, - len: N, - max: mem.inner.len(), - }))?; - cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))? - } else { - let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - cold_err!(mem.effective_addr::<N>(base as usize, u64::from(memarg.offset())))? - }; - cold_err!(T::load_at(&mem.inner, addr)) - } - fn exec_load_local< LOAD: MemValue<N>, const N: usize, @@ -1607,7 +1605,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { let memarg = index.resolve(&self.func.data); - let value = cast(self.exec_load_local_value::<LOAD, N>(memarg, addr_local)?); + + let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory()))); + let base = if mem.is_64bit() { + let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; + cold_err!(usize::try_from(base)).map_err(|_| Trap::MemoryOutOfBounds { + offset: usize::MAX, + len: N, + max: mem.inner.len(), + })? + } else { + u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as usize + }; + + let addr = cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))?; + let value = cast(cold_err!(LOAD::load_at(&mem.inner, addr))?); + if SET_LOCAL { TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); } @@ -1953,7 +1966,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let src = self.store.value_stack.pop_memory_operand(src_arch)?; let dst = self.store.value_stack.pop_memory_operand(dst_arch)?; - if dst_mem == src_mem { + if dst_mem_addr == src_mem_addr { // copy within the same memory let mem = self.store.state.get_mem_mut(dst_mem_addr); mem.copy_within(dst, src, size)?; @@ -2218,7 +2231,7 @@ impl<'store> Executor<'store, false> { loop { match self.exec(instr_ptr)? { ControlFlow::Continue(next_instr_ptr) => instr_ptr = next_instr_ptr, - ControlFlow::Break(()) => return Ok(()), + ControlFlow::Break(()) => return cold!(Ok(())), } } } diff --git a/crates/tinywasm/src/interpreter/stack/call_stack.rs b/crates/tinywasm/src/interpreter/stack/call_stack.rs index 8506a04..d2c515a 100644 --- a/crates/tinywasm/src/interpreter/stack/call_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/call_stack.rs @@ -36,27 +36,13 @@ impl CallStack { } #[inline(always)] - pub(crate) fn push(&mut self, mut call_frame: CallFrame, return_instr_ptr: usize) -> Result<(), Trap> { - self.ensure_capacity_for(self.stack.len() + 1)?; - call_frame.instr_ptr = return_instr_ptr; - self.stack.push(call_frame); - Ok(()) - } - - #[inline(always)] - fn ensure_capacity_for(&mut self, required_len: usize) -> Result<(), Trap> { - if required_len <= self.stack.capacity() { - return Ok(()); - } - - if required_len > self.max_size || !self.dynamic { + pub(crate) fn push(&mut self, mut call_frame: CallFrame, instr_ptr: usize) -> Result<(), Trap> { + if self.stack.len() == self.stack.capacity() && (!self.dynamic || self.stack.len() >= self.max_size) { return cold!(Err(Trap::CallStackOverflow)); } - let target_capacity = required_len.max(self.stack.capacity().max(1).saturating_mul(2)).min(self.max_size); - let Ok(()) = self.stack.try_reserve(target_capacity.saturating_sub(self.stack.len())) else { - return cold!(Err(Trap::CallStackOverflow)); - }; + call_frame.instr_ptr = instr_ptr; + self.stack.push(call_frame); Ok(()) } } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 92b4d93..a9c86b7 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -1,5 +1,4 @@ use alloc::vec::Vec; -use core::hint::cold_path; use tinywasm_types::{MemoryArch, ValueCounts}; use super::StackBase; @@ -41,20 +40,18 @@ impl<T: Copy + Default> Stack<T> { #[inline(always)] pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> { - if !self.ensure_capacity_for(self.data.len() + 1) { + if self.data.len() == self.data.capacity() && (!self.dynamic || self.data.len() >= self.max_size) { return cold!(Err(Trap::ValueStackOverflow)); } - self.data.push(value); Ok(()) } #[inline(always)] pub(crate) fn push_copy(&mut self, index: usize) -> Result<(), Trap> { - if !self.ensure_capacity_for(self.data.len() + 1) { + if self.data.len() == self.data.capacity() && (!self.dynamic || self.data.len() >= self.max_size) { return cold!(Err(Trap::ValueStackOverflow)); } - let value = self.data[index]; self.data.push(value); Ok(()) @@ -62,12 +59,18 @@ impl<T: Copy + Default> Stack<T> { #[inline(always)] pub(crate) fn pop(&mut self) -> T { - unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug") + match self.data.pop() { + Some(value) => value, + None => cold!(unreachable!("ValueStack underflow, this is a bug")), + } } #[inline(always)] pub(crate) fn last(&self) -> &T { - unwrap_or_unreachable!(self.data.last(), "ValueStack underflow, this is a bug") + match self.data.last() { + Some(value) => value, + None => cold!(unreachable!("ValueStack underflow, this is a bug")), + } } #[inline(always)] @@ -107,12 +110,12 @@ impl<T: Copy + Default> Stack<T> { #[inline(always)] pub(crate) fn truncate_to_one_tail(&mut self, n: usize) { debug_assert!(n < self.data.len()); - let last = unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug"); + let last = self.pop(); self.data.truncate(n); self.data.push(last); } - #[inline(always)] + #[inline] pub(crate) fn enter_locals(&mut self, param_count: usize, local_count: usize) -> Result<u32, Trap> { debug_assert!(param_count <= local_count); debug_assert!(param_count <= self.data.len()); @@ -122,13 +125,13 @@ impl<T: Copy + Default> Stack<T> { let end = start + local_count; if end > self.data.capacity() { - cold_path(); + core::hint::cold_path(); if end > self.max_size || !self.dynamic { return Err(Trap::ValueStackOverflow); } let cap = self.data.capacity(); let target = end.max(cap.max(1).saturating_mul(2)).min(self.max_size); - if self.data.try_reserve_exact(target - len).is_err() { + if self.data.try_reserve(target - len).is_err() { return Err(Trap::ValueStackOverflow); } } @@ -137,26 +140,6 @@ impl<T: Copy + Default> Stack<T> { Ok(start as u32) } - fn ensure_capacity_for(&mut self, required_len: usize) -> bool { - let cap = self.data.capacity(); - - if required_len > cap { - cold_path(); - - if required_len > self.max_size || !self.dynamic { - return false; - } - let doubled = cap.max(1).saturating_mul(2); - let target = required_len.max(doubled).min(self.max_size); - let additional = target - cap; - if self.data.try_reserve_exact(additional).is_err() { - return false; - } - } - - true - } - #[inline(always)] pub(crate) fn select_many(&mut self, count: usize, condition: bool) { if count == 0 { @@ -164,7 +147,7 @@ impl<T: Copy + Default> Stack<T> { } let len = self.data.len(); - let needed = unwrap_or_unreachable!(count.checked_mul(2), "Stack underflow, this is a bug"); + let needed = count.wrapping_mul(2); if len < needed { unreachable!("Stack underflow, this is a bug"); diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 38b7a04..b610fd8 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -135,19 +135,19 @@ macro_rules! impl_internalvalue { #[inline(always)] fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self { let $from_stack_v = - *stack.$stack.get(frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize); + *stack.$stack.get(frame.locals_base.$stack_base as usize + index as usize); $from_stack } #[inline(always)] fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap> { - stack.$stack.push_copy(frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize) + stack.$stack.push_copy(frame.locals_base.$stack_base as usize + index as usize) } #[inline(always)] fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self) { let $to_stack_v = value; - let abs_index = frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize; + let abs_index = frame.locals_base.$stack_base as usize + index as usize; stack.$stack.set(abs_index, $to_stack); } @@ -158,7 +158,7 @@ macro_rules! impl_internalvalue { index: LocalAddr, f: impl FnOnce(Self) -> Self, ) -> Self { - let abs_index = frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize; + let abs_index = frame.locals_base.$stack_base as usize + index as usize; let $from_stack_v = *stack.$stack.get(abs_index); let value = f($from_stack); let $to_stack_v = value; @@ -168,8 +168,8 @@ macro_rules! impl_internalvalue { #[inline(always)] fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr) { - let from = frame.locals_base.$stack_base.wrapping_add(u32::from(from)) as usize; - let to = frame.locals_base.$stack_base.wrapping_add(u32::from(to)) as usize; + let from = frame.locals_base.$stack_base as usize + from as usize; + let to = frame.locals_base.$stack_base as usize + to as usize; stack.$stack.copy(from, to); } @@ -258,55 +258,101 @@ pub(crate) trait CmpOpExt<T>: Copy { } macro_rules! impl_value_ops { - ($unsigned:ty, $signed:ty, $float:ty) => { + ($unsigned:ty, $signed:ty, $binop:ident, $cmp:ident) => { impl BinOpExt<$unsigned> for BinOp { #[inline(always)] fn exec(self, lhs: $unsigned, rhs: $unsigned) -> $unsigned { - match self { - BinOp::IAdd => lhs.wrapping_add(rhs), - BinOp::ISub => lhs.wrapping_sub(rhs), - BinOp::IMul => lhs.wrapping_mul(rhs), - BinOp::IAnd => lhs & rhs, - BinOp::IOr => lhs | rhs, - BinOp::IXor => lhs ^ rhs, - BinOp::IShl => (lhs as $signed).wrapping_shl(rhs as u32) as $unsigned, - BinOp::IShrS => (lhs as $signed).wrapping_shr(rhs as u32) as $unsigned, - BinOp::IShrU => lhs.wrapping_shr(rhs as u32), - BinOp::IRotl => (lhs as $signed).rotate_left(rhs as u32) as $unsigned, - BinOp::IRotr => (lhs as $signed).rotate_right(rhs as u32) as $unsigned, - BinOp::FAdd => (<$float>::from_bits(lhs) + <$float>::from_bits(rhs)).to_bits(), - BinOp::FSub => (<$float>::from_bits(lhs) - <$float>::from_bits(rhs)).to_bits(), - BinOp::FMul => (<$float>::from_bits(lhs) * <$float>::from_bits(rhs)).to_bits(), - BinOp::FDiv => (<$float>::from_bits(lhs) / <$float>::from_bits(rhs)).to_bits(), - BinOp::FMin => <$float>::from_bits(lhs).tw_minimum(<$float>::from_bits(rhs)).to_bits(), - BinOp::FMax => <$float>::from_bits(lhs).tw_maximum(<$float>::from_bits(rhs)).to_bits(), - BinOp::FCopysign => <$float>::from_bits(lhs).copysign(<$float>::from_bits(rhs)).to_bits(), - } + $binop(self, lhs, rhs) } } impl CmpOpExt<$signed> for CmpOp { #[inline(always)] fn cmp(self, lhs: $signed, rhs: $signed) -> bool { - match self { - CmpOp::Eq => lhs == rhs, - CmpOp::Ne => lhs != rhs, - CmpOp::LtS => lhs < rhs, - CmpOp::LtU => (lhs as $unsigned) < (rhs as $unsigned), - CmpOp::GtS => lhs > rhs, - CmpOp::GtU => (lhs as $unsigned) > (rhs as $unsigned), - CmpOp::LeS => lhs <= rhs, - CmpOp::LeU => (lhs as $unsigned) <= (rhs as $unsigned), - CmpOp::GeS => lhs >= rhs, - CmpOp::GeU => (lhs as $unsigned) >= (rhs as $unsigned), - } + $cmp(self, lhs, rhs) } } }; } -impl_value_ops!(Value32, i32, f32); -impl_value_ops!(Value64, i64, f64); +impl_value_ops!(Value32, i32, exec_binop_32, exec_cmp_32); +impl_value_ops!(Value64, i64, exec_binop_64, exec_cmp_64); + +fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, + BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, + BinOp::IShrU => lhs.wrapping_shr(rhs), + BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, + BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, + BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), + BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), + BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), + BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), + BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), + } +} + +fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, + BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, + BinOp::IShrU => lhs.wrapping_shr(rhs as u32), + BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, + BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, + BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), + BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), + BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), + BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), + BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), + } +} + +fn exec_cmp_32(op: CmpOp, lhs: i32, rhs: i32) -> bool { + match op { + CmpOp::Eq => lhs == rhs, + CmpOp::Ne => lhs != rhs, + CmpOp::LtS => lhs < rhs, + CmpOp::LtU => (lhs as u32) < (rhs as u32), + CmpOp::GtS => lhs > rhs, + CmpOp::GtU => (lhs as u32) > (rhs as u32), + CmpOp::LeS => lhs <= rhs, + CmpOp::LeU => (lhs as u32) <= (rhs as u32), + CmpOp::GeS => lhs >= rhs, + CmpOp::GeU => (lhs as u32) >= (rhs as u32), + } +} + +fn exec_cmp_64(op: CmpOp, lhs: i64, rhs: i64) -> bool { + match op { + CmpOp::Eq => lhs == rhs, + CmpOp::Ne => lhs != rhs, + CmpOp::LtS => lhs < rhs, + CmpOp::LtU => (lhs as u64) < (rhs as u64), + CmpOp::GtS => lhs > rhs, + CmpOp::GtU => (lhs as u64) > (rhs as u64), + CmpOp::LeS => lhs <= rhs, + CmpOp::LeU => (lhs as u64) <= (rhs as u64), + CmpOp::GeS => lhs >= rhs, + CmpOp::GeU => (lhs as u64) >= (rhs as u64), + } +} impl BinOpExt<Value128> for BinOp128 { #[inline(always)] diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index e2ee684..fe74fcf 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -63,6 +63,7 @@ //! //! ## Cargo features //! +//! - **`full`:** Enables `archive`, `parallel-parser`, `parser`, and `validate`. Enabled by default. //! - **`std`:** Enables `std` and parsing from files and streams. Enabled by default. //! - **`log`:** Enables integration with the `log` crate. Enabled by default. //! - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default. diff --git a/crates/tinywasm/src/macros.rs b/crates/tinywasm/src/macros.rs index 96a2e40..351ae88 100644 --- a/crates/tinywasm/src/macros.rs +++ b/crates/tinywasm/src/macros.rs @@ -16,18 +16,3 @@ macro_rules! cold_err { } }; } - -macro_rules! unwrap_or_unreachable { - ($value:expr) => {{ - match $value { - Some(value) => value, - None => cold!(unreachable!()), - } - }}; - ($value:expr, $($arg:tt)+) => {{ - match $value { - Some(value) => value, - None => cold!(unreachable!($($arg)+)), - } - }}; -} diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs index 88fff5d..3eae3ab 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -1,30 +1,84 @@ +use alloc::vec::Vec; +use core::ops::Range; use tinywasm_types::*; use crate::func::HostFunction; -/// A WebAssembly Function Instance -/// -/// See <https://webassembly.github.io/spec/core/exec/runtime.html#function-instances> -#[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct FunctionInstance { +pub(crate) struct HostFunctionInstance { pub(crate) type_addr: TypeAddr, - pub(crate) inner: FunctionInstanceInner, + pub(crate) func: HostFunction, } -#[derive(Clone)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) enum FunctionInstanceInner { - /// A host function - Host(HostFunction), - - /// A pointer to a WebAssembly function - Wasm(WasmFunctionInstance), -} - -#[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct WasmFunctionInstance { + pub(crate) type_addr: TypeAddr, pub(crate) func: Shared<WasmFunction>, pub(crate) owner: ModuleInstanceId, } + +#[derive(Default)] +pub(crate) struct Functions { + wasm: Vec<WasmFunctionInstance>, + host: Vec<HostFunctionInstance>, +} + +impl Functions { + const HOST_TAG: u32 = 1 << 29; + const INDEX_MASK: u32 = Self::HOST_TAG - 1; + const MAX_ADDR: u32 = Self::HOST_TAG | Self::INDEX_MASK; + + #[inline(always)] + pub(crate) const fn is_host(&self, addr: FuncAddr) -> bool { + addr & Self::HOST_TAG != 0 + } + + #[inline(always)] + fn index(addr: FuncAddr) -> usize { + (addr & Self::INDEX_MASK) as usize + } + + pub(crate) fn extend_wasm( + &mut self, + funcs: impl ExactSizeIterator<Item = (TypeAddr, Shared<WasmFunction>)>, + owner: ModuleInstanceId, + ) -> Range<FuncAddr> { + let start = self.wasm.len(); + let end = start.checked_add(funcs.len()).expect("too many Wasm functions"); + assert!(end <= Self::HOST_TAG as usize, "too many Wasm functions"); + self.wasm.reserve_exact(funcs.len()); + self.wasm.extend(funcs.map(|(type_addr, func)| WasmFunctionInstance { type_addr, func, owner })); + start as FuncAddr..end as FuncAddr + } + + pub(crate) fn push_host(&mut self, type_addr: TypeAddr, func: HostFunction) -> FuncAddr { + let index = self.host.len(); + assert!(index <= Self::INDEX_MASK as usize, "too many host functions"); + self.host.push(HostFunctionInstance { type_addr, func }); + Self::HOST_TAG | index as FuncAddr + } + + #[inline] + pub(crate) fn type_addr(&self, addr: FuncAddr) -> TypeAddr { + if self.is_host(addr) { self.host[Self::index(addr)].type_addr } else { self.wasm[Self::index(addr)].type_addr } + } + + pub(crate) fn contains(&self, addr: FuncAddr) -> bool { + if addr > Self::MAX_ADDR { + return false; + } + if self.is_host(addr) { Self::index(addr) < self.host.len() } else { Self::index(addr) < self.wasm.len() } + } + + #[inline] + pub(crate) fn wasm(&self, addr: FuncAddr) -> &WasmFunctionInstance { + debug_assert!(!self.is_host(addr), "host address used for a Wasm function"); + &self.wasm[Self::index(addr)] + } + + #[inline] + pub(crate) fn host(&self, addr: FuncAddr) -> &HostFunctionInstance { + debug_assert!(self.is_host(addr), "Wasm address used for a host function"); + &self.host[Self::index(addr)] + } +} diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 42a2acf..75aa163 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -3,17 +3,12 @@ use tinywasm_types::*; use crate::interpreter::{RuntimeValue, Value32, Value64, Value128}; +#[derive(Default)] struct GlobalLane<T> { values: Vec<T>, types: Vec<GlobalType>, } -impl<T> Default for GlobalLane<T> { - fn default() -> Self { - Self { values: Vec::new(), types: Vec::new() } - } -} - impl<T: Copy> GlobalLane<T> { fn reserve(&mut self, additional: usize) { self.values.reserve_exact(additional); @@ -28,18 +23,18 @@ impl<T: Copy> GlobalLane<T> { index } - #[inline(always)] - fn get(&self, index: usize, addr: GlobalAddr) -> T { - *unwrap_or_unreachable!(self.values.get(index), "invalid global address: {addr}") + #[inline] + fn get(&self, index: usize) -> T { + self.values[index] } - #[inline(always)] - fn set(&mut self, index: usize, addr: GlobalAddr, value: T) { - *unwrap_or_unreachable!(self.values.get_mut(index), "invalid global address: {addr}") = value; + #[inline] + fn set(&mut self, index: usize, value: T) { + self.values[index] = value; } - fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType { - *unwrap_or_unreachable!(self.types.get(index), "invalid global address: {addr}") + fn ty(&self, index: usize) -> GlobalType { + self.types[index] } } @@ -90,9 +85,9 @@ impl Globals { /// Returns a global's logical type and mutability. pub(crate) fn ty(&self, addr: GlobalAddr) -> GlobalType { match addr & !Self::INDEX_MASK { - Self::LANE_32 => self.globals_32.ty(Self::index(addr, Self::LANE_32), addr), - Self::LANE_64 => self.globals_64.ty(Self::index(addr, Self::LANE_64), addr), - Self::LANE_128 => self.globals_128.ty(Self::index(addr, Self::LANE_128), addr), + Self::LANE_32 => self.globals_32.ty(Self::index(addr, Self::LANE_32)), + Self::LANE_64 => self.globals_64.ty(Self::index(addr, Self::LANE_64)), + Self::LANE_128 => self.globals_128.ty(Self::index(addr, Self::LANE_128)), _ => unreachable!("invalid global address: {addr}"), } } @@ -119,37 +114,37 @@ impl Globals { /// Returns a raw value from the 32-bit lane. #[inline(always)] pub(crate) fn get_32(&self, addr: GlobalAddr) -> Value32 { - self.globals_32.get(Self::index(addr, Self::LANE_32), addr) + self.globals_32.get(Self::index(addr, Self::LANE_32)) } /// Returns a raw value from the 64-bit lane. #[inline(always)] pub(crate) fn get_64(&self, addr: GlobalAddr) -> Value64 { - self.globals_64.get(Self::index(addr, Self::LANE_64), addr) + self.globals_64.get(Self::index(addr, Self::LANE_64)) } /// Returns a raw value from the 128-bit lane. #[inline(always)] pub(crate) fn get_128(&self, addr: GlobalAddr) -> Value128 { - self.globals_128.get(Self::index(addr, Self::LANE_128), addr) + self.globals_128.get(Self::index(addr, Self::LANE_128)) } /// Sets a raw value in the 32-bit lane. #[inline(always)] pub(crate) fn set_32(&mut self, addr: GlobalAddr, value: Value32) { - self.globals_32.set(Self::index(addr, Self::LANE_32), addr, value); + self.globals_32.set(Self::index(addr, Self::LANE_32), value); } /// Sets a raw value in the 64-bit lane. #[inline(always)] pub(crate) fn set_64(&mut self, addr: GlobalAddr, value: Value64) { - self.globals_64.set(Self::index(addr, Self::LANE_64), addr, value); + self.globals_64.set(Self::index(addr, Self::LANE_64), value); } /// Sets a raw value in the 128-bit lane. #[inline(always)] pub(crate) fn set_128(&mut self, addr: GlobalAddr, value: Value128) { - self.globals_128.set(Self::index(addr, Self::LANE_128), addr, value); + self.globals_128.set(Self::index(addr, Self::LANE_128), value); } /// Iterates over globals in the 32-bit lane for root tracing. diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index 3a478fb..b947916 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -4,6 +4,8 @@ use crate::{Error, ResourceLimiter, Result, Trap}; use super::{MemoryStorage, memory_oob}; +const MEMORY64_MAX_BYTES: u64 = 16 * 1024 * 1024 * 1024; + /// A WebAssembly Memory Instance /// /// See <https://webassembly.github.io/spec/core/exec/runtime.html#memory-instances> @@ -31,6 +33,14 @@ impl MemoryInstance { kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX)) } + #[inline] + fn page_count_max(kind: MemoryType) -> u64 { + match kind.arch() { + MemoryArch::I32 => kind.page_count_max(), + MemoryArch::I64 => kind.page_count_max().min(MEMORY64_MAX_BYTES / kind.page_size()), + } + } + #[cfg(target_pointer_width = "64")] #[inline(always)] pub(crate) fn effective_addr<const N: usize>(&self, base: usize, offset: u64) -> Result<usize, Trap> { @@ -50,6 +60,13 @@ impl MemoryInstance { } pub(crate) fn new(kind: MemoryType, limiter: Option<&dyn ResourceLimiter>) -> Result<Self> { + if kind.page_size() == 0 { + return Err(Error::UnsupportedFeature("zero-byte memory pages")); + } + let max_pages = Self::page_count_max(kind); + if kind.page_count_initial() > max_pages { + return Err(Trap::OutOfMemory.into()); + } let initial_len = cold_err!( Self::host_size(kind, kind.page_count_initial()) .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space")) @@ -68,7 +85,8 @@ impl MemoryInstance { return cold!(Err(Trap::OutOfMemory.into())); } - let storage = MemoryStorage::try_new(initial_len)?; + let max_len = Self::host_size(kind, max_pages).unwrap_or(usize::MAX); + let storage = MemoryStorage::try_new(kind.arch(), initial_len, max_len)?; Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize }) } @@ -85,7 +103,11 @@ impl MemoryInstance { ) -> Result<(), Trap> { cold_err!(src_mem.inner.checked_range(src, len).ok_or_else(|| memory_oob(src, len, src_mem.inner.len())))?; cold_err!(self.inner.checked_range(dst, len).ok_or_else(|| memory_oob(dst, len, self.inner.len())))?; - self.inner.copy_from(dst, &src_mem.inner, src, len); + cold_err!(self.inner.copy_from(dst, &src_mem.inner, src, len).ok_or_else(|| memory_oob( + dst, + len, + self.inner.len() + )))?; Ok(()) } @@ -103,7 +125,7 @@ impl MemoryInstance { else { return cold!(Ok(None)); }; - let max_pages = self.kind.page_count_max().try_into().unwrap_or(usize::MAX); + let max_pages = Self::page_count_max(self.kind).try_into().unwrap_or(usize::MAX); if new_pages > max_pages { return cold!({ diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs index 4d701ae..9f059ac 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -7,10 +7,6 @@ pub(crate) use instance::MemoryInstance; pub(crate) use vec::VecMemory; /// Internal storage for a linear memory. -/// -/// This is the boundary between the interpreter and the backing representation. Keeping it a -/// concrete type selected at compile time means the executor's load and store paths stay the same -/// whether the memory is `Vec`-backed or, later, mmap-backed. pub(crate) type MemoryStorage = VecMemory; /// A trait for types that can be converted to and from static byte arrays. diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index ef2d4df..c2daa16 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -1,20 +1,19 @@ use alloc::vec::Vec; use core::ops::Range; +use tinywasm_types::MemoryArch; use super::memory_oob; /// A contiguous `Vec<u8>`-backed linear memory storage. /// -/// This is the internal storage boundary for [`super::MemoryInstance`]. Keeping it a concrete type -/// rather than a `Vec<u8>` directly means the backing representation can later be swapped for an -/// mmap-backed implementation without touching the interpreter's load and store paths. +/// This is the default internal storage for [`super::MemoryInstance`]. pub(crate) struct VecMemory { data: Vec<u8>, } impl VecMemory { /// Tries to create a new memory with `len` zero-initialized bytes. - pub(crate) fn try_new(len: usize) -> Result<Self, crate::Trap> { + pub(crate) fn try_new(_arch: MemoryArch, len: usize, _max_len: usize) -> Result<Self, crate::Trap> { let mut data = Vec::new(); cold_err!(data.try_reserve(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); @@ -125,9 +124,12 @@ impl VecMemory { Some(()) } - /// Copies a previously checked range from another memory. + /// Copies a valid range from another memory. #[inline(always)] - pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) { - self.data[dst..dst + len].copy_from_slice(&src_memory.data[src..src + len]); + pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) -> Option<()> { + let src_range = src_memory.checked_range(src, len)?; + let dst_range = self.checked_range(dst, len)?; + self.data[dst_range].copy_from_slice(&src_memory.data[src_range]); + Some(()) } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 862cb4f..e157240 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -2,7 +2,7 @@ use alloc::{boxed::Box, format, vec::Vec}; use core::hint::cold_path; use tinywasm_types::*; -use crate::func::FromWasmValues; +use crate::func::{FromWasmValues, HostFunction}; use crate::interpreter::stack::{CallStack, StackBase, ValueStack}; use crate::interpreter::{RuntimeValue, ValueRef}; use crate::reference::{ReferentKind, RootedItem, StoreId, StoredRef}; @@ -363,7 +363,7 @@ impl Store { Ok(StackValueIter { store: self, type_addr, types, index, position: 0, len }) } - pub(crate) fn push_wasm_values(&mut self, values: impl IntoIterator<Item = WasmValue>) -> Result<()> { + pub(crate) fn push_wasm_values(&mut self, values: &[WasmValue]) -> Result<()> { for value in values { let value = value.to_runtime(self)?; self.value_stack.push_dyn(value)?; @@ -371,14 +371,19 @@ impl Store { Ok(()) } - pub(crate) fn pop_stack_values(&mut self, types: &[WasmType], results: &mut [WasmValue]) -> Result<()> { - if types.len() != results.len() { + pub(crate) fn pop_stack_values(&mut self, type_addr: TypeAddr, results: &mut [WasmValue]) -> Result<()> { + let (result_count, result_counts) = { + let types = self.state.get_canonical_func_type(type_addr).results(); + (types.len(), types.iter().collect()) + }; + if result_count != results.len() { return Err(Error::other("result buffer has the wrong length")); } - let base = self.value_stack.base_before(types.iter().collect()); + let base = self.value_stack.base_before(result_counts); let result = (|| { let mut index = base; - for (&ty, result) in types.iter().zip(results) { + for (position, result) in results.iter_mut().enumerate() { + let ty = self.state.get_canonical_func_type(type_addr).results()[position]; let value = self.stack_value(ty, &mut index); *result = value.into_wasm(self, ty)?; } @@ -503,17 +508,10 @@ impl Store { module_type_idxs: &[TypeAddr], type_addrs: &[TypeAddr], ) -> impl ExactSizeIterator<Item = FuncAddr> { - let start = self.state.funcs.len() as FuncAddr; 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, - inner: FunctionInstanceInner::Wasm(WasmFunctionInstance { func, owner }), - }); - } - start..start + funcs.len() as FuncAddr + let funcs = + funcs.iter().cloned().zip(module_type_idxs).map(|(func, &type_idx)| (type_addrs[type_idx as usize], func)); + self.state.funcs.extend_wasm(funcs, owner) } /// Add tags to the store, returning their addresses in the store. @@ -752,9 +750,7 @@ impl Store { } /// 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); - addr + pub(crate) fn add_host_func(&mut self, type_addr: TypeAddr, func: HostFunction) -> FuncAddr { + self.state.funcs.push_host(type_addr, func) } } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index cad0208..f1ba616 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -12,7 +12,7 @@ pub(crate) struct State { // Concrete type indexes in store instances address this canonical type space. pub(crate) canonical_types: Vec<SubType>, pub(crate) canonical_rec_group_lengths: Vec<u32>, - pub(crate) funcs: Vec<FunctionInstance>, + pub(crate) funcs: Functions, pub(crate) tables: Vec<TableInstance>, pub(crate) memories: Vec<MemoryInstance>, pub(crate) globals: Globals, @@ -28,7 +28,7 @@ impl State { Self { canonical_types: Vec::new(), canonical_rec_group_lengths: Vec::new(), - funcs: Vec::new(), + funcs: Functions::default(), tables: Vec::new(), memories: Vec::new(), globals: Globals::default(), @@ -250,8 +250,11 @@ impl State { || expected.abstract_heap_type() == Some(AbstractHeapType::Func); if expected_func { let Some(func_addr) = value.addr() else { return false }; - let Some(func) = self.funcs.get(func_addr as usize) else { return false }; - return self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected); + if !self.funcs.contains(func_addr) { + return false; + } + let type_addr = self.funcs.type_addr(func_addr); + return self.ref_type_is_subtype(RefType::new_concrete(false, type_addr), expected); } if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) { return matches!(self.gc.get(value).map(|object| object.kind), Some(gc::GcObjectKind::Exception(_))); @@ -271,12 +274,12 @@ impl State { #[inline] pub(crate) fn get_func_type(&self, addr: FuncAddr) -> &FuncType { - self.get_canonical_func_type(self.get_func(addr).type_addr) + self.get_canonical_func_type(self.funcs.type_addr(addr)) } #[inline] pub(crate) fn get_type(&self, addr: TypeAddr) -> &SubType { - Self::get(&self.canonical_types, addr, "canonical type") + &self.canonical_types[addr as usize] } #[inline] @@ -284,14 +287,7 @@ impl State { self.get_type(addr).as_func().expect("validated function address references a function type") } - pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { - unwrap_or_unreachable!(items.get(addr as usize), "invalid {kind} address: {addr}") - } - - fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T { - unwrap_or_unreachable!(items.get_mut(addr as usize), "invalid {kind} address: {addr}") - } - + #[inline] fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) { let [item_a, item_b] = items .get_disjoint_mut([addr as usize, addr2 as usize]) @@ -299,46 +295,39 @@ impl State { (item_a, item_b) } - /// Get the function at the actual index in the store - pub(crate) fn get_func(&self, addr: FuncAddr) -> &FunctionInstance { - Self::get(&self.funcs, addr, "function") - } - + #[inline] pub(crate) fn get_tag(&self, addr: TagAddr) -> &TagInstance { - Self::get(&self.tags, addr, "tag") - } - - /// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator) - pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance { - match self.funcs.get(addr as usize).map(|func| &func.inner) { - Some(FunctionInstanceInner::Wasm(wasm_func)) => wasm_func, - _ => unreachable!("invalid wasm function address: {addr}"), - } + &self.tags[addr as usize] } /// Get the memory at the actual index in the store + #[inline] pub(crate) fn get_mem(&self, addr: MemAddr) -> &MemoryInstance { - Self::get(&self.memories, addr, "memory") + &self.memories[addr as usize] } /// Get the memory at the actual index in the store + #[inline] pub(crate) fn get_mem_mut(&mut self, addr: MemAddr) -> &mut MemoryInstance { - Self::get_mut(&mut self.memories, addr, "memory") + &mut self.memories[addr as usize] } /// Get the memory at the actual index in the store + #[inline] pub(crate) fn get_mems_mut(&mut self, addr: MemAddr, addr2: MemAddr) -> (&mut MemoryInstance, &mut MemoryInstance) { Self::get_disjoint_mut(&mut self.memories, addr, addr2, "memory") } /// Get the table at the actual index in the store + #[inline] pub(crate) fn get_table(&self, addr: TableAddr) -> &TableInstance { - Self::get(&self.tables, addr, "table") + &self.tables[addr as usize] } /// Get the table at the actual index in the store + #[inline] pub(crate) fn get_table_mut(&mut self, addr: TableAddr) -> &mut TableInstance { - Self::get_mut(&mut self.tables, addr, "table") + &mut self.tables[addr as usize] } /// Get two mutable tables at the actual index in the store @@ -351,13 +340,15 @@ impl State { } /// Get the data at the actual index in the store + #[inline] pub(crate) fn get_data_mut(&mut self, addr: DataAddr) -> &mut DataInstance { - Self::get_mut(&mut self.data, addr, "data") + &mut self.data[addr as usize] } /// Get the element at the actual index in the store + #[inline] pub(crate) fn get_elem_mut(&mut self, addr: ElemAddr) -> &mut ElementInstance { - Self::get_mut(&mut self.elements, addr, "element") + &mut self.elements[addr as usize] } /// Returns a global in its internal value representation. diff --git a/crates/tinywasm/tests/test-wast.rs b/crates/tinywasm/tests/test-wast.rs index 004bafa..fcf3044 100644 --- a/crates/tinywasm/tests/test-wast.rs +++ b/crates/tinywasm/tests/test-wast.rs @@ -15,13 +15,7 @@ fn main() -> Result<(), Box<dyn core::error::Error>> { let arg = cwd.join(input); println!("running tests in {:?}", arg); - let files = if arg.is_dir() { - std::fs::read_dir(&arg)?.map(|entry| entry.map(|e| e.path())).collect::<Result<Vec<_>, _>>()? - } else { - vec![arg] - }; - let mut test_suite = WastRunner::new(); - test_suite.run_paths(&files)?; + test_suite.run_paths(&[arg])?; Ok(()) } diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml index 7f701cf..091bb9f 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -20,7 +20,7 @@ serde = { version = "1.0", default-features = false, features = ["alloc"], optio default = ["archive", "debug", "log", "std"] # support serializing and deserializing twasm archives -archive = ["dep:postcard", "dep:serde", "serde/rc", "portable-atomic-util?/serde"] +archive = ["dep:postcard", "dep:serde", "portable-atomic-util?/serde", "serde/rc"] # derive Debug for runtime and module types debug = [] diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index b92a0f4..6a357ea 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -511,8 +511,9 @@ pub enum BinOp128 { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum Instruction { LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr), - AddConst32(i32), AddConst64(Operand64Idx<i64>), + AddConst32(i32), AndConst32(i32), XorConst32(i32), ShrUConst32(i32), AddConst64(Operand64Idx<i64>), IncLocal32(I32LocalArg), IncLocal64(PackedOp64<LocalAddr, i64>), + // The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results. BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr), @@ -520,18 +521,25 @@ pub enum Instruction { AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg), BinOpLocalLocalSet32(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalSet64(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalSet128(PackedOp64<BinOp128, (u16, u16, u16)>), BinOpLocalLocalTee32(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalTee64(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalTee128(PackedOp64<BinOp128, (u16, u16, u16)>), + AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg), + AndLocalConst32(I32LocalArg), ShrULocalConst32(I32LocalArg), BinOpLocalConst32(PackedOp64<BinOp, (u16, u32)>), BinOpLocalConst64(PackedOp128<BinOp, (u16, u64)>), - BinOpGlobalConst32(PackedOp64<BinOp, (u32, u32)>), BinOpGlobalConst64(PackedOp128<BinOp, (u32, u64)>), - BinOpGlobalConst128(PackedOp64<BinOp128, (u32, Operand128Idx<[u8; 16]>)>), BinOpLocalConst128(PackedOp64<BinOp128, (u16, Operand128Idx<[u8; 16]>)>), + BinOpLocalConst128(PackedOp64<BinOp128, (u16, Operand128Idx<[u8; 16]>)>), BinOpLocalConstSet32(PackedOp64<BinOp, (u16, u16, u32)>), BinOpLocalConstSet64(PackedOp128<BinOp, (u16, u16, u64)>), BinOpLocalConstSet128(PackedOp64<BinOp128, (u16, u16, Operand128Idx<[u8; 16]>)>), BinOpLocalConstTee32(PackedOp64<BinOp, (u16, u16, u32)>), BinOpLocalConstTee64(PackedOp128<BinOp, (u16, u16, u64)>), BinOpLocalConstTee128(PackedOp64<BinOp128, (u16, u16, Operand128Idx<[u8; 16]>)>), + + BinOpStackConst32(BinOp, i32), BinOpStackConst64(PackedOp64<BinOp, i64>), + BinOpStackLocal32(BinOp, LocalAddr), BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), BinOpStackLocal128(BinOp128, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), + BinOpGlobalConst32(PackedOp64<BinOp, (u32, u32)>), BinOpGlobalConst64(PackedOp128<BinOp, (u32, u64)>), + BinOpGlobalConst128(PackedOp64<BinOp128, (u32, Operand128Idx<[u8; 16]>)>), + SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp64<LocalAddr, i64>), SetLocalConst128(PackedOp128<LocalAddr, [u8; 16]>), IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg), StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg), diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs index edbab26..af1b17f 100644 --- a/crates/types/src/operands.rs +++ b/crates/types/src/operands.rs @@ -146,26 +146,11 @@ macro_rules! define_operand { define_operand!(Operand64, 8); define_operand!(Operand128, 16); -macro_rules! unwrap_or_unreachable { - ($value:expr) => {{ - match $value { - Some(value) => value, - None => { core::hint::cold_path(); unreachable!() }, - } - }}; - ($value:expr, $($arg:tt)+) => {{ - match $value { - Some(value) => value, - None => { core::hint::cold_path(); unreachable!($($arg)+) }, - } - }}; -} - impl<T> Operand64Idx<T> { /// Resolves this index to a copied 64-bit packed operand. #[inline(always)] pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand64<T> { - (*unwrap_or_unreachable!(data.operands64.get(self.index()), "invalid 64-bit operand index")).cast() + data.operands64[self.index as usize].cast() } } @@ -173,7 +158,7 @@ impl<T> Operand128Idx<T> { /// Resolves this index to a copied 128-bit packed operand. #[inline(always)] pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand128<T> { - (*unwrap_or_unreachable!(data.operands128.get(self.index()), "invalid 128-bit operand index")).cast() + data.operands128[self.index as usize].cast() } } |
