diff options
| author | Henry <mail@henrygressmann.de> | 2026-08-09 18:07:51 +0200 |
|---|---|---|
| committer | Henry <mail@henrygressmann.de> | 2026-08-09 18:07:51 +0200 |
| commit | e005e5afd144f5659e2ed19afa8ee94ff924be55 (patch) | |
| tree | 75b66c1a750f2c4a86efe9573fb25a19e186abb0 /crates | |
| parent | 9893a51d2712f82a2ee57316a66bc26500eb3fdd (diff) | |
feat: initial exception support
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates')
25 files changed, 742 insertions, 102 deletions
diff --git a/crates/cli/src/output.rs b/crates/cli/src/output.rs index 40a271e..a2bd287 100644 --- a/crates/cli/src/output.rs +++ b/crates/cli/src/output.rs @@ -77,6 +77,7 @@ pub fn format_export_type(ty: ExportType<'_>) -> String { ExportType::Memory(ty) => format_memory_type(ty), ExportType::Table(ty) => format_table_type(ty), ExportType::Global(ty) => format_global_type(ty), + ExportType::Tag(ty) => format!("tag {}", format_func_type(ty)), } } @@ -86,5 +87,6 @@ pub fn format_import_type(ty: ImportType<'_>) -> String { ImportType::Memory(ty) => format_memory_type(ty), ImportType::Table(ty) => format_table_type(ty), ImportType::Global(ty) => format_global_type(ty), + ImportType::Tag(ty) => format!("tag {}", format_func_type(ty)), } } diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 2ca622d..24483b6 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -19,53 +19,63 @@ const TEST_MAX_SUSPENSIONS: u32 = 1000; #[derive(Default)] struct ModuleRegistry { - modules: HashMap<String, ModuleInstance>, - named_modules: HashMap<String, ModuleInstance>, - last_module: Option<ModuleInstance>, + definitions: HashMap<String, Module>, + instances: HashMap<String, ModuleInstance>, + registered: HashMap<String, ModuleInstance>, + last_definition: Option<Module>, + last_instance: Option<ModuleInstance>, } impl ModuleRegistry { - fn modules(&self) -> &HashMap<String, ModuleInstance> { - &self.modules + fn registered(&self) -> &HashMap<String, ModuleInstance> { + &self.registered } - fn update_last_module(&mut self, module: ModuleInstance, name: Option<String>) { - self.last_module = Some(module.clone()); + fn define(&mut self, module: Module, name: Option<String>) { + self.last_definition = Some(module.clone()); if let Some(name) = name { - self.named_modules.insert(name, module); + self.definitions.insert(name, module); } } - fn register(&mut self, name: String, module: ModuleInstance) { + fn definition(&self, id: Option<wast::token::Id<'_>>) -> Option<Module> { + match id { + Some(id) => self.definitions.get(id.name()).cloned(), + None => self.last_definition.clone(), + } + } + + fn update_last_instance(&mut self, instance: ModuleInstance, name: Option<String>) { + self.last_instance = Some(instance.clone()); + if let Some(name) = name { + self.instances.insert(name, instance); + } + } + + fn register(&mut self, name: String, id: Option<wast::token::Id<'_>>) -> bool { + let Some(instance) = self.get(id) else { return false }; debug!("registering module: {name}"); - self.modules.insert(name.clone(), module.clone()); - self.last_module = Some(module.clone()); - self.named_modules.insert(name, module); + self.registered.insert(name, instance); + true } fn get_idx(&self, module_id: Option<wast::token::Id<'_>>) -> Option<u32> { match module_id { - Some(module) => self - .modules - .get(module.name()) - .or_else(|| self.named_modules.get(module.name())) - .map(ModuleInstance::id), - None => self.last_module.as_ref().map(ModuleInstance::id), + Some(module) => { + self.registered.get(module.name()).or_else(|| self.instances.get(module.name())).map(ModuleInstance::id) + } + None => self.last_instance.as_ref().map(ModuleInstance::id), } } fn get(&self, module_id: Option<wast::token::Id<'_>>) -> Option<ModuleInstance> { match module_id { Some(module_id) => { - self.modules.get(module_id.name()).or_else(|| self.named_modules.get(module_id.name())).cloned() + self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).cloned() } - None => self.last_module.clone(), + None => self.last_instance.clone(), } } - - fn last(&self) -> Option<ModuleInstance> { - self.last_module.clone() - } } #[derive(Default)] @@ -200,6 +210,11 @@ impl WastRunner { Ok(imports) } + fn instantiate_module(store: &mut Store, registry: &ModuleRegistry, module: &Module) -> Result<ModuleInstance> { + let imports = Self::imports(store, registry.registered())?; + Ok(ModuleInstance::instantiate(store, module, Some(&imports))?) + } + pub fn run_file(&mut self, file: TestFile<'_>) -> Result<()> { let test_group = self.test_group(file.name(), file.parent()); let wast_raw = file.raw(); @@ -213,51 +228,72 @@ impl WastRunner { for (i, directive) in directives.into_iter().enumerate() { let span = directive.span(); use wast::WastDirective::{ - AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, AssertUnlinkable, Invoke, - Module as Wat, ModuleDefinition, Register, + AssertException, AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, + AssertUnlinkable, Invoke, Module as Wat, ModuleDefinition, ModuleInstance as Instance, Register, }; match directive { - Register { span, name, .. } => { - let Some(last) = module_registry.last() else { + Register { span, name, module } => { + if !module_registry.register(name.to_string(), module) { test_group.add_result( &format!("Register({i})"), span.linecol_in(wast_raw), - Err(eyre!("no module to register")), + Err(eyre!("module instance to register was not found")), ); continue; - }; - module_registry.register(name.to_string(), last); + } test_group.add_result(&format!("Register({i})"), span.linecol_in(wast_raw), Ok(())); } Wat(module) => { let result = catch_unwind_silent(|| { - let (name, bytes) = encode_quote_wat(module); - let module = parse_module_bytes(&bytes).expect("failed to parse module bytes"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); - let module_instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)) + let (name, module) = parse_quote_module(module).expect("failed to parse module bytes"); + let instance = Self::instantiate_module(&mut store, &module_registry, &module) .expect("failed to instantiate module"); - (name, module_instance) + (name, instance) }) .map_err(|e| eyre!("failed to parse wat module: {}", try_downcast_panic(e))); match &result { Err(err) => debug!("failed to parse module: {err:?}"), - Ok((name, module)) => module_registry.update_last_module(module.clone(), name.clone()), + Ok((name, instance)) => module_registry.update_last_instance(instance.clone(), name.clone()), }; test_group.add_result(&format!("Wat({i})"), span.linecol_in(wast_raw), result.map(|_| ())); } ModuleDefinition(module) => { + let result = + catch_unwind_silent(|| parse_quote_module(module).expect("failed to parse module definition")) + .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))); + + if let Ok((name, module)) = &result { + module_registry.define(module.clone(), name.clone()); + } + + test_group.add_result( + &format!("ModuleDefinition({i})"), + span.linecol_in(wast_raw), + result.map(|_| ()), + ); + } + Instance { span, instance, module } => { + let name = instance.map(|id| id.name().to_string()); let result = catch_unwind_silent(|| { - let (_, bytes) = encode_quote_wat(module); - parse_module_bytes(&bytes) + let module = module_registry + .definition(module) + .ok_or_else(|| eyre!("module definition was not found"))?; + Self::instantiate_module(&mut store, &module_registry, &module) }) - .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))) - .and_then(|result| result) - .map(|_| ()); + .map_err(|err| eyre!("failed to instantiate module definition: {}", try_downcast_panic(err))) + .and_then(|result| result); - test_group.add_result(&format!("ModuleDefinition({i})"), span.linecol_in(wast_raw), result); + if let Ok(instance) = &result { + module_registry.update_last_instance(instance.clone(), name); + } + test_group.add_result( + &format!("ModuleInstance({i})"), + span.linecol_in(wast_raw), + result.map(|_| ()), + ); } AssertMalformed { span, mut module, message } => { let Ok(encoded) = module.encode() else { @@ -330,7 +366,7 @@ impl WastRunner { wast::WastExecute::Wat(mut wat) => { let module = parse_module_bytes(&wat.encode().expect("failed to encode module")) .expect("failed to parse module"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; return Ok(()); } @@ -371,11 +407,37 @@ impl WastRunner { ), } } + AssertException { exec, span } => { + let res: Result<tinywasm::Result<()>, _> = catch_unwind_silent(|| { + let invoke = match exec { + wast::WastExecute::Wat(mut wat) => { + let module = parse_module_bytes(&wat.encode().expect("failed to encode module")) + .expect("failed to parse module"); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); + ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + return Ok(()); + } + wast::WastExecute::Get { .. } => panic!("get not supported"), + wast::WastExecute::Invoke(invoke) => invoke, + }; + let module = module_registry.get_idx(invoke.module); + let args = + convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) + }); + let result = match res { + Err(err) => Err(eyre!("test panicked: {}", try_downcast_panic(err))), + Ok(Err(tinywasm::Error::Exception(_))) => Ok(()), + Ok(Err(err)) => Err(eyre!("expected exception, got: {err:?}")), + Ok(Ok(())) => Err(eyre!("expected exception, got Ok")), + }; + test_group.add_result(&format!("AssertException({i})"), span.linecol_in(wast_raw), result); + } AssertUnlinkable { mut module, span, message } => { let res = catch_unwind_silent(|| { let module = parse_module_bytes(&module.encode().expect("failed to encode module")) .expect("failed to parse module"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); ModuleInstance::instantiate(&mut store, &module, Some(&imports)) }); match res { @@ -729,6 +791,11 @@ fn parse_module_bytes(bytes: &[u8]) -> Result<Module> { Ok(tinywasm::parse_bytes(bytes)?) } +fn parse_quote_module(module: QuoteWat) -> Result<(Option<String>, Module)> { + let (name, bytes) = encode_quote_wat(module); + Ok((name, parse_module_bytes(&bytes)?)) +} + fn convert_wastargs(args: Vec<wast::WastArg>) -> Result<Vec<WasmValue>> { args.into_iter().map(wastarg2tinywasmvalue).collect() } @@ -947,4 +1014,26 @@ mod tests { let mut runner = WastRunner::new(); runner.run_paths(&[path]).unwrap(); } + + #[test] + fn runs_module_definition_and_instance_directives() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("instance.wast"); + std::fs::write( + &path, + r#" + (module definition $M (global (export "g") i32 (i32.const 42))) + (module instance $I $M) + (register "I" $I) + (module + (import "I" "g" (global $g i32)) + (func (export "get") (result i32) global.get $g)) + (assert_return (invoke "get") (i32.const 42)) + "#, + ) + .unwrap(); + + let mut runner = WastRunner::new(); + runner.run_paths(&[path]).unwrap(); + } } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 4073a8e..7b52363 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -76,9 +76,7 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result<Im wasmparser::TypeRef::Global(ty) => { ImportKind::Global(GlobalType::new(convert_valtype(&ty.content_type)?, ty.mutable)) } - wasmparser::TypeRef::Tag(ty) => { - return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {ty:?}"))); - } + wasmparser::TypeRef::Tag(ty) => ImportKind::Tag(convert_tag_type(ty)), _ => { return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {:?}", import.ty))); } @@ -116,7 +114,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex wasmparser::ExternalKind::Table => ExternalKind::Table, wasmparser::ExternalKind::Memory => ExternalKind::Memory, wasmparser::ExternalKind::Global => ExternalKind::Global, - wasmparser::ExternalKind::Tag | wasmparser::ExternalKind::FuncExact => { + wasmparser::ExternalKind::Tag => ExternalKind::Tag, + wasmparser::ExternalKind::FuncExact => { return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported export kind: {:?}", export.kind))); } }; @@ -124,6 +123,10 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex Ok(Export { index: export.index, name: Box::from(export.name), kind }) } +pub(crate) const fn convert_tag_type(ty: wasmparser::TagType) -> TagType { + TagType::new(ty.func_type_idx) +} + fn extend_local_types(local_types: &mut Vec<ValueLane>, count: u32, ty: wasmparser::ValType) -> Result<()> { let size = value_lane(ty); let count = diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index fe968d8..8b6cb39 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -189,6 +189,7 @@ impl Parser { | WasmFeatures::SIMD | WasmFeatures::MEMORY64 | WasmFeatures::CUSTOM_PAGE_SIZES + | WasmFeatures::EXCEPTIONS | WasmFeatures::WIDE_ARITHMETIC; self.options.validation().then(|| Validator::new_with_features(features)) } diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index db1402d..98312ab 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -160,6 +160,7 @@ pub(crate) mod visit { (@@tail_call $($rest:tt)* ) => {}; (@@function_references $($rest:tt)* ) => {}; (@@gc $($rest:tt)* ) => {}; + (@@exceptions $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output { diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 237478c..bbe2cf8 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -57,6 +57,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, + pub(crate) tags: Box<[TagType]>, pub(crate) imports: Box<[Import]>, pub(crate) data: Box<[Data]>, pub(crate) elements: Box<[Element]>, @@ -78,6 +79,7 @@ impl<'a> ModuleReader<'a> { &self.globals, &self.memory_types, &self.tables, + &self.tags, ))); } self.translation_metadata.as_deref().unwrap() @@ -182,6 +184,25 @@ impl<'a> ModuleReader<'a> { self.memory_types = reader.into_iter().map(|memory| Ok(convert_module_memory(memory?))).collect::<Result<_>>()?; } + Payload::TagSection(reader) => { + check_section("tag", !self.tags.is_empty())?; + #[cfg(feature = "validate")] + if let Some(validator) = validator.as_mut() { + validator.tag_section(&reader)?; + } + let mut tags = Vec::with_capacity(reader.count() as usize); + for tag in reader { + let tag = convert_tag_type(tag?); + let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!("tag type index does not reference a function: {}", tag.type_idx)) + })?; + if !ty.results().is_empty() { + return Err(ParseError::Other(format!("tag type must not have results: {}", tag.type_idx))); + } + tags.push(tag); + } + self.tags = tags.into_boxed_slice(); + } Payload::ElementSection(reader) => { debug!("Found element section"); #[cfg(feature = "validate")] @@ -249,6 +270,20 @@ impl<'a> ModuleReader<'a> { self.imported_func_count += 1; } ImportKind::Memory(_) => self.imported_memory_count += 1, + ImportKind::Tag(tag) => { + let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!( + "tag import type index does not reference a function: {}", + tag.type_idx + )) + })?; + if !ty.results().is_empty() { + return Err(ParseError::Other(format!( + "tag import type must not have results: {}", + tag.type_idx + ))); + } + } _ => {} } imports.push(import); @@ -553,6 +588,7 @@ impl<'a> ModuleReader<'a> { exports: self.exports, elements: self.elements, memory_types: self.memory_types, + tags: self.tags, local_memory_allocation, } .into()) diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 74a9fc0..be37e5e 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -910,11 +910,28 @@ fn is_unconditional_terminator(instr: Instruction) -> bool { | Instruction::ReturnCallSelf | Instruction::ReturnCallIndirect(..) | Instruction::ReturnCallRef(_) + | Instruction::Throw(_) + | Instruction::ThrowRef ) } fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result<Vec<bool>> { let mut boundaries = alloc::vec![false; instructions.len() + 1]; + for handler in &function_data.exception_handlers { + for target in [handler.start_ip, handler.end_ip] { + let boundary = boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) + })?; + *boundary = true; + } + for catch in &handler.catches { + let target = catch.landing_pad(); + let boundary = boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))?; + *boundary = true; + } + } for instr in instructions { if let Some(target) = instruction_target(instr) { let boundary = boundaries @@ -948,6 +965,31 @@ fn finalize( imported_memory_count: u32, ) -> Result<bool> { let len = instructions.len() as u32; + for handler in &mut function_data.exception_handlers { + if let Some(old_to_new) = old_to_new { + handler.start_ip = *old_to_new.get(handler.start_ip as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.start_ip)) + })?; + handler.end_ip = *old_to_new.get(handler.end_ip as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.end_ip)) + })?; + for catch in &mut handler.catches { + let landing_pad = match catch { + tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } + | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, + }; + *landing_pad = *old_to_new.get(*landing_pad as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception landing pad out of bounds: {landing_pad}")) + })?; + } + } + if handler.start_ip > handler.end_ip || handler.end_ip > len { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + if handler.catches.iter().any(|catch| catch.landing_pad() >= len) { + return Err(ParseError::Other("exception landing pad out of bounds".into())); + } + } for target in &mut function_data.branch_table_targets { if let Some(old_to_new) = old_to_new { *target = *old_to_new diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 46d1f9f..c462d05 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -6,8 +6,8 @@ use crate::{ use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TypeSection, - ValueCounts, ValueLane, WasmFunctionData, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TagType, + TypeSection, ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -20,6 +20,7 @@ enum BlockKind { Block, Loop, If, + TryTable(usize), } struct ControlFrame { @@ -48,6 +49,7 @@ pub(crate) struct ModuleMetadata { globals: Vec<ValueLane>, memories: Vec<ValueLane>, tables: Vec<ValueLane>, + tags: Vec<u32>, types: Vec<SubType>, } @@ -55,6 +57,7 @@ pub(crate) struct ModuleMetadata { struct FunctionDataBuilder { v128_constants: Vec<[u8; 16]>, branch_table_targets: Vec<u32>, + exception_handlers: Vec<tinywasm_types::ExceptionHandler>, } pub(crate) struct FunctionBuilder<'a> { @@ -133,11 +136,13 @@ impl ModuleMetadata { globals: &[Global], memories: &[MemoryType], tables: &[TableDefinition], + tags: &[TagType], ) -> Self { let mut functions = Vec::with_capacity(imports.len() + code_type_addrs.len()); let mut global_sizes = Vec::with_capacity(imports.len() + globals.len()); let mut memory_sizes = Vec::with_capacity(imports.len() + memories.len()); let mut table_sizes = Vec::with_capacity(imports.len() + tables.len()); + let mut tag_types = Vec::with_capacity(imports.len() + tags.len()); for import in imports { match &import.kind { @@ -145,6 +150,7 @@ impl ModuleMetadata { ImportKind::Global(ty) => global_sizes.push(ValueLane::from(&ty.ty)), ImportKind::Memory(ty) => memory_sizes.push(Self::address_lane(ty.arch())), ImportKind::Table(ty) => table_sizes.push(Self::address_lane(ty.arch())), + ImportKind::Tag(ty) => tag_types.push(ty.type_idx), } } @@ -152,6 +158,7 @@ impl ModuleMetadata { global_sizes.extend(globals.iter().map(|global| ValueLane::from(&global.ty.ty))); memory_sizes.extend(memories.iter().map(|ty| Self::address_lane(ty.arch()))); table_sizes.extend(tables.iter().map(|table| Self::address_lane(table.ty.arch()))); + tag_types.extend(tags.iter().map(|tag| tag.type_idx)); let signatures = types .types @@ -169,6 +176,7 @@ impl ModuleMetadata { globals: global_sizes, memories: memory_sizes, tables: table_sizes, + tags: tag_types, types: types.types.to_vec(), } } @@ -188,6 +196,14 @@ impl ModuleMetadata { self.signature(ty) } + fn tag_signature(&self, idx: u32) -> Result<&Signature> { + let ty = *self + .tags + .get(idx as usize) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("tag index out of bounds: {idx}")))?; + self.signature(ty) + } + fn global_size(&self, idx: u32) -> Result<ValueLane> { Self::indexed_size(&self.globals, "global", idx) } @@ -284,6 +300,7 @@ pub(crate) fn process_operators( let data = WasmFunctionData { v128_constants: builder.data.v128_constants.into_boxed_slice(), branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), + exception_handlers: builder.data.exception_handlers.into_boxed_slice(), }; Ok((builder.instructions, data, reader.into_allocations())) } @@ -320,6 +337,7 @@ pub(crate) fn process_operators_and_validate( let data = WasmFunctionData { v128_constants: builder.data.v128_constants.into_boxed_slice(), branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), + exception_handlers: builder.data.exception_handlers.into_boxed_slice(), }; Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations())) } @@ -648,6 +666,89 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) } + fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Self::Output { + let signature = self.block_signature(try_table.ty)?; + for &size in signature.params.iter().rev() { + self.pop_expect(size)?; + } + let height = self.operand_stack.len(); + let base = self.lane_counts; + let entry_unreachable = self.is_unreachable(); + + let body_jump = self.instructions.len(); + self.instructions.push(Instruction::Jump(0)); + let mut catches = Vec::with_capacity(try_table.catches.len()); + for catch in try_table.catches { + let (tag, depth, with_ref) = match catch { + wasmparser::Catch::One { tag, label } => (Some(tag), label, false), + wasmparser::Catch::OneRef { tag, label } => (Some(tag), label, true), + wasmparser::Catch::All { label } => (None, label, false), + wasmparser::Catch::AllRef { label } => (None, label, true), + }; + if let Some(tag) = tag { + self.metadata.tag_signature(tag)?; + } + let target_idx = self.get_ctx_idx(depth)?; + let target_base = self.control_stack[target_idx].base; + let landing_pad = u32::try_from(self.instructions.len()) + .map_err(|_| crate::ParseError::Other("function body is too large".into()))?; + match self.control_stack[target_idx].kind { + BlockKind::Function => self.instructions.push(Instruction::Return), + BlockKind::Loop => { + self.instructions.push(Instruction::Jump(self.control_stack[target_idx].start_ip as u32)); + } + BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { + self.control_stack[target_idx].branch_jumps.push(self.instructions.len()); + self.control_stack[target_idx].end_reachable = true; + self.instructions.push(Instruction::Jump(0)); + } + } + catches.push(match tag { + Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref }, + None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref }, + }); + } + + let body_start = self.instructions.len(); + self.patch_jump(body_jump, body_start); + let handler_idx = self.data.exception_handlers.len(); + self.data.exception_handlers.push(tinywasm_types::ExceptionHandler { + start_ip: body_start as u32, + end_ip: 0, + catches: catches.into_boxed_slice(), + }); + self.push_sizes(&signature.params)?; + self.control_stack.push(ControlFrame { + kind: BlockKind::TryTable(handler_idx), + has_else: false, + start_ip: body_start, + branch_jumps: Vec::new(), + height, + base, + params: signature.params, + results: signature.results, + unreachable: entry_unreachable, + entry_unreachable, + end_reachable: false, + }); + Ok(()) + } + + fn visit_throw(&mut self, tag_index: u32) -> Self::Output { + let signature = self.metadata.tag_signature(tag_index)?.clone(); + self.apply_effect(&signature.params, &[])?; + self.instructions.push(Instruction::Throw(tag_index)); + self.mark_unreachable(); + Ok(()) + } + + fn visit_throw_ref(&mut self) -> Self::Output { + self.apply_effect(&[ValueLane::S32], &[])?; + self.instructions.push(Instruction::ThrowRef); + self.mark_unreachable(); + Ok(()) + } + fn visit_else(&mut self) -> Self::Output { let (cond_jump_ip, height, base, params, entry_unreachable) = { let ctx = self @@ -672,6 +773,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_end(&mut self) -> Self::Output { let ctx = self.control_stack.pop().ok_or_else(|| crate::ParseError::Other("end without control frame".into()))?; + if let BlockKind::TryTable(handler_idx) = ctx.kind { + self.data.exception_handlers[handler_idx].end_ip = self.instructions.len() as u32; + } if matches!(ctx.kind, BlockKind::Function) { self.instructions.push(Instruction::Return); } else { @@ -1184,11 +1288,24 @@ impl FunctionBuilder<'_> { /// Enters a control frame with its parameters restored above the saved base. fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option<usize>) -> Result<()> { - let signature = match ty { + let signature = self.block_signature(ty)?; + self.push_control_signature(kind, signature, initial_jump) + } + + fn block_signature(&self, ty: wasmparser::BlockType) -> Result<Signature> { + Ok(match ty { wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), - }; + }) + } + + fn push_control_signature( + &mut self, + kind: BlockKind, + signature: Signature, + initial_jump: Option<usize>, + ) -> Result<()> { for &size in signature.params.iter().rev() { self.pop_expect(size)?; } @@ -1264,7 +1381,7 @@ impl FunctionBuilder<'_> { match self.control_stack[ctx_idx].kind { BlockKind::Function => self.instructions.push(Instruction::Return), BlockKind::Loop => self.instructions.push(Instruction::Jump(self.control_stack[ctx_idx].start_ip as u32)), - BlockKind::Block | BlockKind::If => { + BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { self.control_stack[ctx_idx].branch_jumps.push(self.instructions.len()); self.control_stack[ctx_idx].end_reachable = true; self.instructions.push(Instruction::Jump(0)); diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 6cf9b17..67d0742 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -34,7 +34,6 @@ name = "test-wasm-1" [[test]] harness = false name = "test-wasm-3" -test = false [[test]] harness = false @@ -43,7 +42,6 @@ name = "test-wasm-2" [[test]] harness = false name = "test-wasm-latest" -test = false [[test]] harness = false diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index ebd0470..0597847 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -2,8 +2,8 @@ use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::{Debug, Display}; -use tinywasm_types::FuncType; use tinywasm_types::archive::TwasmError; +use tinywasm_types::{ExnRef, FuncType}; #[cfg(feature = "parser")] pub use tinywasm_parser::ParseError; @@ -14,6 +14,9 @@ pub enum Error { /// A WebAssembly trap occurred Trap(Trap), + /// An uncaught WebAssembly exception occurred. + Exception(ExnRef), + /// A linking error occurred Linker(LinkingError), @@ -50,6 +53,7 @@ impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Trap(a), Self::Trap(b)) => a == b, + (Self::Exception(a), Self::Exception(b)) => a == b, (Self::Linker(a), Self::Linker(b)) => a == b, (Self::UnsupportedFeature(a), Self::UnsupportedFeature(b)) => a == b, (Self::Other(a), Self::Other(b)) => a == b, @@ -274,6 +278,7 @@ impl Display for Error { Self::Twasm(err) => write!(f, "serialization error: {err}"), Self::Trap(trap) => write!(f, "trap: {trap}"), + Self::Exception(_) => write!(f, "uncaught WebAssembly exception"), Self::Linker(err) => write!(f, "linking error: {err}"), Self::InvalidLabelType => write!(f, "invalid label type"), Self::Other(message) => write!(f, "unknown error: {message}"), diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index a71be32..892aa05 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -3,7 +3,7 @@ use tinywasm_types::{FuncAddr, TypeAddr, WasmValue}; use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues}; use crate::interpreter::stack::{CallFrame, StackBase}; -use crate::{Error, InterpreterRuntime, Result, Store, Trap}; +use crate::{Error, InterpreterRuntime, Result, Store}; #[derive(Clone, PartialEq, Eq)] /// Progress for fuel-limited function execution. @@ -93,7 +93,7 @@ impl Function { impl<'store> FuncExecution<'store> { fn resume_raw( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>, + run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState>, ) -> Result<ExecProgress<CallResult>> { let (callframe, root_func_addr) = match &mut self.state { FuncExecutionState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), @@ -109,7 +109,17 @@ impl<'store> FuncExecution<'store> { let result = run(self.store, callframe); self.store.exit_execution(); - match result? { + let result = match result { + Ok(result) => result, + Err(error) => { + self.store.call_stack.clear(); + self.store.value_stack.clear(); + self.state = FuncExecutionState::Completed(None); + return Err(error); + } + }; + + match result { crate::interpreter::ExecState::Completed => { let func = self.store.state.get_func(root_func_addr); let result_ty = func.type_addr; @@ -129,7 +139,7 @@ impl<'store> FuncExecution<'store> { fn resume( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>, + run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState>, ) -> Result<ExecProgress<Vec<WasmValue>>> { match self.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => { @@ -231,7 +241,7 @@ impl<P: IntoWasmValues, R: FromWasmValues> FunctionTyped<P, R> { impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { fn resume( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState, Trap>, + run: impl FnOnce(&mut Store, CallFrame) -> Result<crate::interpreter::ExecState>, ) -> Result<ExecProgress<R>> { match self.execution.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => Ok(ExecProgress::Completed( diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index a35cf2c..8232a90 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -3,7 +3,7 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::hint::cold_path; -use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table}; +use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table, Tag}; use tinywasm_types::*; #[derive(Clone)] @@ -21,6 +21,8 @@ pub enum Extern { Function(Function), /// A reusable host function definition. HostFunction(HostFunction), + /// A tag instance. + Tag(Tag), } macro_rules! impl_conv { @@ -41,6 +43,7 @@ impl_conv! { Memory => Memory, Function => Function, HostFunction => HostFunction, + Tag => Tag, } /// Imports for a module instance @@ -100,6 +103,7 @@ pub(crate) struct ResolvedImports { pub(crate) tables: Vec<TableAddr>, pub(crate) memories: Vec<MemAddr>, pub(crate) funcs: Vec<FuncAddr>, + pub(crate) tags: Vec<TagAddr>, } impl Imports { @@ -127,7 +131,7 @@ impl Imports { /// Define an import value. /// - /// A [`Function`], [`Global`], [`Table`], or [`Memory`] handle belongs to + /// A [`Function`], [`Global`], [`Table`], [`Memory`], or [`Tag`] handle belongs to /// one store and can only be imported into that store. A [`HostFunction`] /// is a reusable definition and can be imported into multiple stores. /// @@ -225,12 +229,13 @@ impl Imports { module: &Module, type_addrs: &[TypeAddr], ) -> Result<ResolvedImports> { - let (global_count, table_count, mem_count, func_count) = - module.imports.iter().fold((0, 0, 0, 0), |(g, t, m, f), import| match import.kind { - ImportKind::Global(_) => (g + 1, t, m, f), - ImportKind::Table(_) => (g, t + 1, m, f), - ImportKind::Memory(_) => (g, t, m + 1, f), - ImportKind::Function(_) => (g, t, m, f + 1), + let (global_count, table_count, mem_count, func_count, tag_count) = + module.imports.iter().fold((0, 0, 0, 0, 0), |(g, t, m, f, e), import| match import.kind { + ImportKind::Global(_) => (g + 1, t, m, f, e), + ImportKind::Table(_) => (g, t + 1, m, f, e), + ImportKind::Memory(_) => (g, t, m + 1, f, e), + ImportKind::Function(_) => (g, t, m, f + 1, e), + ImportKind::Tag(_) => (g, t, m, f, e + 1), }); let mut imports = ResolvedImports { @@ -238,6 +243,7 @@ impl Imports { tables: Vec::with_capacity(table_count + module.tables.len()), memories: Vec::with_capacity(mem_count + module.memory_types.len()), funcs: Vec::with_capacity(func_count + module.funcs.len()), + tags: Vec::with_capacity(tag_count + module.tags.len()), }; for import in &*module.imports { @@ -259,6 +265,10 @@ impl Imports { Extern::HostFunction(func) => { (ExternVal::Func(func.instantiate_for_import(store, type_addrs)?.addr()), None) } + Extern::Tag(tag) => { + tag.0.validate_store(store)?; + (ExternVal::Tag(tag.0.addr), None) + } } } else { let Some(instance) = self.modules.get(import.module.as_ref()) else { @@ -317,6 +327,16 @@ impl Imports { } imports.funcs.push(func_addr); } + (ExternVal::Tag(tag_addr), ImportKind::Tag(ty)) => { + let expected_type_addr = type_addrs + .get(ty.type_idx as usize) + .ok_or_else(|| LinkingError::incompatible_import_type(import))?; + if store.state.get_tag(tag_addr).type_addr != *expected_type_addr { + cold_path(); + return Err(LinkingError::incompatible_import_type(import).into()); + } + imports.tags.push(tag_addr); + } _ => unreachable!("import kind checked above"), } } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 52bb948..23bb298 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -4,7 +4,7 @@ use tinywasm_types::*; use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes}; use crate::store::MemoryInstance; -use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Trap}; +use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap}; /// A typed view over an exported extern value. pub enum ExternItem { @@ -16,6 +16,8 @@ pub enum ExternItem { Table(Table), /// Exported global reference. Global(Global), + /// Exported tag reference. + Tag(Tag), } /// An instantiated WebAssembly module @@ -52,6 +54,7 @@ struct ModuleInstanceInner { table_addrs: Box<[TableAddr]>, mem_addrs: Box<[MemAddr]>, global_addrs: Box<[GlobalAddr]>, + tag_addrs: Box<[TagAddr]>, elem_addrs: Box<[ElemAddr]>, data_addrs: Box<[DataAddr]>, func_start: Option<FuncAddr>, @@ -101,6 +104,11 @@ impl ModuleInstance { } #[inline] + pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr { + *self.0.tag_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid tag address: {addr}")) + } + + #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { if self.0.store_id != store.id() { cold_path(); @@ -157,6 +165,7 @@ impl ModuleInstance { let mut addrs = imports.unwrap_or(&default_imports).link(store, module, &type_addrs)?; let imported_funcs = addrs.funcs.len(); addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); + addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); match module.local_memory_allocation { LocalMemoryAllocation::Skip => { #[cfg(feature = "guest-debug")] @@ -185,6 +194,7 @@ impl ModuleInstance { table_addrs: addrs.tables.into_boxed_slice(), mem_addrs: addrs.memories.into_boxed_slice(), global_addrs: addrs.globals.into_boxed_slice(), + tag_addrs: addrs.tags.into_boxed_slice(), elem_addrs, data_addrs, func_start: module.start_func, @@ -209,6 +219,7 @@ impl ModuleInstance { ExternalKind::Table => self.0.table_addrs.get(export.index as usize)?, ExternalKind::Memory => self.0.mem_addrs.get(export.index as usize)?, ExternalKind::Global => self.0.global_addrs.get(export.index as usize)?, + ExternalKind::Tag => self.0.tag_addrs.get(export.index as usize)?, }; Some(ExternVal::new(export.kind, *addr)) } @@ -257,6 +268,9 @@ impl ModuleInstance { ExternalKind::Global => { ExternItem::Global(Global(StoreItem::new(self.0.store_id, self.resolve_global_addr(export.index)))) } + ExternalKind::Tag => { + ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, self.resolve_tag_addr(export.index)))) + } }; (export.name.as_ref(), item) @@ -309,6 +323,7 @@ impl ModuleInstance { ExternVal::Memory(addr) => Ok(ExternItem::Memory(Memory(StoreItem::new(self.0.store_id, addr)))), ExternVal::Table(addr) => Ok(ExternItem::Table(Table(StoreItem::new(self.0.store_id, addr)))), ExternVal::Global(addr) => Ok(ExternItem::Global(Global(StoreItem::new(self.0.store_id, addr)))), + ExternVal::Tag(addr) => Ok(ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, addr)))), } } @@ -487,6 +502,21 @@ impl ModuleInstance { Ok(Table(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.table_addrs, table_index, "table")?))) } + /// Get a tag export by name. + pub fn tag(&self, name: &str) -> Result<Tag> { + match self.require_export(name)? { + ExternVal::Tag(tag_addr) => Ok(Tag(StoreItem::new(self.0.store_id, tag_addr))), + _ => Err(Error::Other(format!("Export is not a tag: {name}"))), + } + } + + /// Get a tag by its module-local index. + #[cfg_attr(docsrs, doc(cfg(feature = "guest-debug")))] + #[cfg(feature = "guest-debug")] + pub fn tag_by_index(&self, tag_index: TagAddr) -> Result<Tag> { + Ok(Tag(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.tag_addrs, tag_index, "tag")?))) + } + /// Get the value of a global export by name. pub fn global_get(&self, store: &Store, name: &str) -> Result<WasmValue> { self.global(name)?.get(store) diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index f5c9351..22c8441 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -65,7 +65,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec(&mut self) -> Result<Option<()>, Trap> { + fn exec(&mut self) -> Result<Option<()>> { macro_rules! stack_op { (unary $ty:ty, |$v:ident| $expr:expr) => { stack_op!(unary $ty => $ty, |$v| $expr) @@ -223,7 +223,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { use tinywasm_types::Instruction::*; #[rustfmt::skip] match &self.func.instructions[self.cf.instr_ptr] { - Unreachable => { cold_path(); return Err(Trap::Unreachable) }, + Unreachable => { cold_path(); return Err(Trap::Unreachable.into()) }, Drop32 => { _ = Value32::stack_pop(&mut self.store.value_stack)}, Drop64 => { _ = Value64::stack_pop(&mut self.store.value_stack)}, Drop128 => { _ = Value128::stack_pop(&mut self.store.value_stack)}, @@ -239,6 +239,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ReturnCallSelf => { self.exec_return_call_self()?; return Ok(None); } ReturnCallIndirect(ty, table) => { if self.exec_call_indirect::<true>(*ty, *table)? { return Ok(Some(())); } return Ok(None); } ReturnCallRef(ty) => { if self.exec_call_ref::<true>(*ty)? { return Ok(Some(())); } return Ok(None); } + Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } + ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } JumpIfZero32(ip) => if self.exec_jump_zero_32(*ip) { return Ok(None) }, JumpIfNonZero32(ip) => if self.exec_jump_non_zero_32(*ip) { return Ok(None) }, @@ -472,7 +474,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { RefCast(ty) => { if !self.exec_ref_matches(*ty) { cold_path(); - return Err(Trap::CastFailure); + return Err(Trap::CastFailure.into()); } } // GC objects @@ -992,6 +994,135 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.truncate_keep_counts(base, drop_keep.keep); } + fn create_exception(&mut self, tag_index: TagAddr) -> Result<ExnAddr, Trap> { + let tag_addr = self.module.resolve_tag_addr(tag_index); + let type_addr = self.store.state.get_tag(tag_addr).type_addr; + let addr = u32::try_from(self.store.state.exceptions.len()).map_err(|_| Trap::OutOfMemory)?; + self.store.state.exceptions.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; + let params = self.store.state.get_canonical_func_type(type_addr).params(); + let mut payload = Vec::new(); + payload.try_reserve_exact(params.len()).map_err(|_| Trap::OutOfMemory)?; + for &ty in params.iter().rev() { + payload.push(match ty { + WasmType::I32 | WasmType::F32 => { + TinyWasmValue::Value32(Value32::stack_pop(&mut self.store.value_stack)) + } + WasmType::I64 | WasmType::F64 => { + TinyWasmValue::Value64(Value64::stack_pop(&mut self.store.value_stack)) + } + WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(&mut self.store.value_stack)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(&mut self.store.value_stack)), + }); + } + payload.reverse(); + self.store + .state + .exceptions + .push(crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }); + Ok(addr) + } + + fn exec_throw(&mut self, tag_index: TagAddr) -> Result<()> { + let exception = self.create_exception(tag_index)?; + let outcome = match self.dispatch_exception(exception) { + Ok(outcome) => outcome, + Err(trap) => { + _ = self.store.state.exceptions.pop(); + return Err(trap.into()); + } + }; + match outcome { + Some(catch) if !catch.with_ref() => { + debug_assert_eq!(self.store.state.exceptions.len() - 1, exception as usize); + _ = self.store.state.exceptions.pop(); + Ok(()) + } + Some(_) => Ok(()), + None => Err(Error::Exception(ExnRef::new(exception))), + } + } + + fn exec_throw_ref(&mut self) -> Result<()> { + let exception = ValueRef::stack_pop(&mut self.store.value_stack); + let exception = exception + .addr() + .filter(|addr| self.store.state.exceptions.get(*addr as usize).is_some()) + .ok_or(Trap::NullReference)?; + match self.dispatch_exception(exception)? { + Some(_) => Ok(()), + None => Err(Error::Exception(ExnRef::new(exception))), + } + } + + fn matching_catch(&self, protected_ip: usize, tag_addr: TagAddr) -> Option<ExceptionCatch> { + let handlers = &self.func.data.exception_handlers; + let end = handlers.partition_point(|handler| handler.start_ip as usize <= protected_ip); + handlers[..end] + .iter() + .rev() + .filter(|handler| protected_ip < handler.end_ip as usize) + .flat_map(|handler| handler.catches.iter().copied()) + .find(|catch| match catch { + ExceptionCatch::Tag { tag, .. } => self.module.resolve_tag_addr(*tag) == tag_addr, + ExceptionCatch::All { .. } => true, + }) + } + + fn switch_to_frame(&mut self, frame: CallFrame) { + let previous = core::mem::replace(&mut self.cf, frame); + if previous.func_addr == self.cf.func_addr { + return; + } + + let wasm_func = self.store.state.get_wasm_func(self.cf.func_addr); + self.func = wasm_func.func.clone(); + if wasm_func.owner != self.module.id() { + self.module = self + .store + .get_module_instance(wasm_func.owner) + .unwrap_or_else(|| unreachable!("invalid module instance")) + .clone(); + } + } + + fn dispatch_exception(&mut self, exception_addr: ExnAddr) -> Result<Option<ExceptionCatch>, Trap> { + let tag_addr = self.store.state.exceptions[exception_addr as usize].tag_addr; + let mut protected_ip = self.cf.instr_ptr; + loop { + if let Some(catch) = self.matching_catch(protected_ip, tag_addr) { + let (landing_pad, base, with_ref, include_payload) = match catch { + ExceptionCatch::Tag { landing_pad, base, with_ref, .. } => (landing_pad, base, with_ref, true), + ExceptionCatch::All { landing_pad, base, with_ref } => (landing_pad, base, with_ref, false), + }; + let stack_base = self.cf.stack_base(); + let target = interpreter::stack::StackBase { + s32: stack_base.s32 + base.c32 as u32, + s64: stack_base.s64 + base.c64 as u32, + s128: stack_base.s128 + base.c128 as u32, + }; + self.store.value_stack.truncate_to_base(target); + if include_payload { + let Store { state, value_stack, .. } = self.store; + for value in state.exceptions[exception_addr as usize].payload.iter().copied() { + value_stack.push_dyn(value)?; + } + } + if with_ref { + self.store.value_stack.push(ValueRef::from_category_addr(exception_addr))?; + } + self.cf.instr_ptr = landing_pad as usize; + return Ok(Some(catch)); + } + + self.store.value_stack.truncate_to_base(self.cf.locals_base); + let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { + return Ok(None); + }; + self.switch_to_frame(caller); + protected_ip = self.cf.instr_ptr.checked_sub(1).unwrap_or_else(|| unreachable!("invalid caller IP")); + } + } + fn exec_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> { if !Arc::ptr_eq(&self.func, &wasm_func.func) { self.func = wasm_func.func.clone(); @@ -1207,20 +1338,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { return true; }; - if caller.func_addr == self.cf.func_addr { - self.cf = caller; - return false; - } - let wasm_func = self.store.state.get_wasm_func(caller.func_addr); - self.func = wasm_func.func.clone(); - if wasm_func.owner != self.module.id() { - self.module = self - .store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); - } - self.cf = caller; + self.switch_to_frame(caller); false } @@ -1922,7 +2040,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { impl<'store> Executor<'store, false> { #[inline(always)] - pub(crate) fn run_to_completion(&mut self) -> Result<(), Trap> { + pub(crate) fn run_to_completion(&mut self) -> Result<()> { // ideally we use `loop_match` / `become` once thats stabilized loop { if self.exec()?.is_some() { @@ -1933,7 +2051,7 @@ impl<'store> Executor<'store, false> { #[cfg(feature = "std")] #[inline(always)] - pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result<ExecState, Trap> { + pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result<ExecState> { use crate::std::time::Instant; let start = Instant::now(); if time_budget.is_zero() { @@ -1956,7 +2074,7 @@ impl<'store> Executor<'store, false> { impl<'store> Executor<'store, true> { #[inline(always)] - pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result<ExecState, Trap> { + pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result<ExecState> { self.store.execution_fuel = fuel; if self.store.execution_fuel == 0 { return Ok(ExecState::Suspended(self.cf)); diff --git a/crates/tinywasm/src/interpreter/mod.rs b/crates/tinywasm/src/interpreter/mod.rs index cece36a..6e6912c 100644 --- a/crates/tinywasm/src/interpreter/mod.rs +++ b/crates/tinywasm/src/interpreter/mod.rs @@ -7,7 +7,7 @@ pub(crate) mod values; #[cfg(not(feature = "std"))] mod no_std_floats; -use crate::{Result, Store, Trap, interpreter::stack::CallFrame}; +use crate::{Result, Store, interpreter::stack::CallFrame}; pub(crate) use simd::*; pub(crate) use values::*; @@ -26,11 +26,11 @@ pub(crate) enum ExecState { pub(crate) struct InterpreterRuntime; impl InterpreterRuntime { - pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<(), Trap> { + pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<()> { executor::Executor::<false>::new(store, cf, call_stack_base).run_to_completion() } - pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result<ExecState, Trap> { + pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result<ExecState> { executor::Executor::<true>::new(store, cf, 0).run_with_fuel(fuel) } @@ -39,7 +39,7 @@ impl InterpreterRuntime { store: &mut Store, cf: CallFrame, time_budget: core::time::Duration, - ) -> Result<ExecState, Trap> { + ) -> Result<ExecState> { executor::Executor::<false>::new(store, cf, 0).run_with_time_budget(time_budget) } } diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs index 7b3807e..783b10b 100644 --- a/crates/tinywasm/src/interpreter/num_helpers.rs +++ b/crates/tinywasm/src/interpreter/num_helpers.rs @@ -32,11 +32,11 @@ macro_rules! checked_conv_float { let (min, max) = float_min_max!($from, $intermediate); if v.is_nan() { core::hint::cold_path(); - return Err(crate::Trap::InvalidConversionToInt); + return Err(crate::Trap::InvalidConversionToInt.into()); } if v <= min || v >= max { core::hint::cold_path(); - return Err(crate::Trap::IntegerOverflow); + return Err(crate::Trap::IntegerOverflow.into()); } $self.store.value_stack.push::<$to>((v as $intermediate as $to).into())?; }}; diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index 6e904af..55f9e3b 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -8,7 +8,9 @@ use alloc::vec::Vec; use crate::interpreter::ValueRef; use crate::store::TableInstance; use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; +use tinywasm_types::{ + Addr, FuncType, GlobalType, MemAddr, MemoryType, TableAddr, TableType, TagAddr, WasmType, WasmValue, +}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -66,6 +68,11 @@ pub struct Table(pub(crate) StoreItem); #[cfg_attr(feature = "debug", derive(Debug))] pub struct Global(pub(crate) StoreItem); +/// A tag instance in a store. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Tag(pub(crate) StoreItem); + /// A cursor over a [`Memory`] instance. /// /// Available with the `std` feature enabled. @@ -471,3 +478,22 @@ impl Global { store.state.set_global_wasmvalue(self.0.addr, value) } } + +impl Tag { + /// Create a new exception tag in the given store. + pub fn new(store: &mut Store, ty: FuncType) -> Result<Self> { + if !ty.results().is_empty() { + return Err(Error::other("tag types must not have results")); + } + let type_addr = store.register_host_type(&ty); + let addr = store.state.tags.len() as TagAddr; + store.state.tags.push(crate::store::TagInstance { type_addr }); + Ok(Self(StoreItem::new(store.id(), addr))) + } + + /// Get the payload type of the tag. + pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { + self.0.validate_store(store)?; + Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr)) + } +} diff --git a/crates/tinywasm/src/store/exception.rs b/crates/tinywasm/src/store/exception.rs new file mode 100644 index 0000000..0725cda --- /dev/null +++ b/crates/tinywasm/src/store/exception.rs @@ -0,0 +1,10 @@ +use alloc::boxed::Box; +use tinywasm_types::TagAddr; + +use crate::interpreter::TinyWasmValue; + +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct ExceptionInstance { + pub(crate) tag_addr: TagAddr, + pub(crate) payload: Box<[TinyWasmValue]>, +} diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 0cd5e5b..84a52b5 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -11,12 +11,14 @@ use crate::{Engine, Error, ModuleInstance, Result, Trap}; mod const_expr; mod data; mod element; +mod exception; mod function; mod gc; mod global; mod memory; mod state; mod table; +mod tag; mod types; use const_expr::eval_const; @@ -25,7 +27,7 @@ pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, Vec pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; -pub(crate) use {data::*, element::*, function::*, global::*, table::*}; +pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table::*, tag::*}; // global store id counter static STORE_ID: AtomicU32 = AtomicU32::new(0); @@ -227,6 +229,18 @@ impl Store { start..start + funcs.len() as FuncAddr } + /// Add tags to the store, returning their addresses in the store. + pub(crate) fn init_tags( + &mut self, + tags: &[TagType], + type_addrs: &[TypeAddr], + ) -> impl ExactSizeIterator<Item = TagAddr> { + let start = self.state.tags.len() as TagAddr; + self.state.tags.reserve_exact(tags.len()); + self.state.tags.extend(tags.iter().map(|tag| TagInstance { type_addr: type_addrs[tag.type_idx as usize] })); + start..start + tags.len() as TagAddr + } + /// Add tables to the store, returning their addresses in the store pub(crate) fn init_tables( &mut self, diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 3371d4c..e6a213f 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -14,6 +14,8 @@ pub(crate) struct State { pub(crate) tables: Vec<TableInstance>, pub(crate) memories: Vec<MemoryInstance>, pub(crate) globals: Globals, + pub(crate) tags: Vec<TagInstance>, + pub(crate) exceptions: Vec<ExceptionInstance>, pub(crate) elements: Vec<ElementInstance>, pub(crate) data: Vec<DataInstance>, pub(crate) gc: Box<gc::GcHeap>, @@ -28,6 +30,8 @@ impl State { tables: Vec::new(), memories: Vec::new(), globals: Globals::default(), + tags: Vec::new(), + exceptions: Vec::new(), elements: Vec::new(), data: Vec::new(), gc: Box::new(gc::GcHeap::new(gc_collection_threshold)), @@ -104,6 +108,11 @@ impl State { .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) .flat_map(|element| element.items.iter().flatten().copied()), ) + .chain( + self.exceptions + .iter() + .flat_map(|exception| exception.payload.iter().filter_map(|value| value.as_ref())), + ) .chain(values.iter().filter_map(|value| value.as_ref())); self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?; } @@ -261,6 +270,9 @@ impl State { let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); return self.ref_type_is_subtype(actual, expected); } + if expected.is_exn() { + return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); + } if value.is_i31() { let actual = RefType::new_abstract(false, AbstractHeapType::I31); return self.ref_type_is_subtype(actual, expected); @@ -304,6 +316,9 @@ impl State { { false } + (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) if expected.is_exn() => { + self.exceptions.get(value.addr() as usize).is_some() + } (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => { self.value_ref_matches(ValueRef::from_raw(value.raw()), expected) } @@ -332,6 +347,10 @@ impl State { Self::get(&self.funcs, addr, "function") } + 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.kind) { diff --git a/crates/tinywasm/src/store/tag.rs b/crates/tinywasm/src/store/tag.rs new file mode 100644 index 0000000..49c16d8 --- /dev/null +++ b/crates/tinywasm/src/store/tag.rs @@ -0,0 +1,7 @@ +use tinywasm_types::TypeAddr; + +#[derive(Clone, Copy)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct TagInstance { + pub(crate) type_addr: TypeAddr, +} diff --git a/crates/tinywasm/tests/generated/wasm-3.csv b/crates/tinywasm/tests/generated/wasm-3.csv index 7d3961c..fdc0e86 100644 --- a/crates/tinywasm/tests/generated/wasm-3.csv +++ b/crates/tinywasm/tests/generated/wasm-3.csv @@ -1,3 +1,3 @@ 0.9.0,20776,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20778,450,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,21151,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21228,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":34,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-latest.csv b/crates/tinywasm/tests/generated/wasm-latest.csv index 94a8b58..b25ec13 100644 --- a/crates/tinywasm/tests/generated/wasm-latest.csv +++ b/crates/tinywasm/tests/generated/wasm-latest.csv @@ -1,3 +1,3 @@ 0.9.0,20777,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20697,536,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":14,"failed":35},{"name":"return_call_indirect.wast","passed":30,"failed":51},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,21156,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21233,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":34,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index b920ac7..aff9e24 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,4 +1,6 @@ -use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TypeAddr, ValueCounts}; +use alloc::boxed::Box; + +use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue}; /// Represents a memory immediate in a WebAssembly memory instruction. @@ -20,6 +22,46 @@ pub struct DropKeep { pub keep: ValueCounts, } +/// A catch clause attached to a lowered `try_table` instruction. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum ExceptionCatch { + /// Catch exceptions carrying the specified module-local tag. + Tag { tag: TagAddr, landing_pad: u32, base: ValueCounts, with_ref: bool }, + /// Catch any exception. + All { landing_pad: u32, base: ValueCounts, with_ref: bool }, +} + +impl ExceptionCatch { + /// Returns the catch landing pad instruction pointer. + pub const fn landing_pad(self) -> u32 { + match self { + Self::Tag { landing_pad, .. } | Self::All { landing_pad, .. } => landing_pad, + } + } + + /// Returns whether this clause exposes the caught exception reference. + pub const fn with_ref(self) -> bool { + match self { + Self::Tag { with_ref, .. } | Self::All { with_ref, .. } => with_ref, + } + } +} + +/// A statically lowered exception handler range. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct ExceptionHandler { + /// First protected instruction, inclusive. + pub start_ip: u32, + /// End of the protected instruction range, exclusive. + pub end_ip: u32, + /// Catch clauses in source order. + pub catches: Box<[ExceptionCatch]>, +} + impl From<(ValueCounts, ValueCounts)> for DropKeep { fn from((base, keep): (ValueCounts, ValueCounts)) -> Self { Self { base, keep } @@ -229,6 +271,8 @@ pub enum Instruction { ReturnCallSelf, ReturnCallIndirect(TypeAddr, TableAddr), ReturnCallRef(TypeAddr), + Throw(TagAddr), + ThrowRef, // > Parametric Instructions // See <https://webassembly.github.io/spec/core/binary/instructions.html#parametric-instructions> diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 0fd4e81..78a8d0d 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -111,6 +111,11 @@ pub struct ModuleInner { /// Corresponds to the `memory` section of the original WebAssembly module. pub memory_types: Box<[MemoryType]>, + /// Tag components of the WebAssembly module. + /// + /// Corresponds to the `tag` section of the original WebAssembly module. + pub tags: Box<[TagType]>, + /// Imports of the WebAssembly module. /// /// Corresponds to the `import` section of the original WebAssembly module. @@ -141,6 +146,7 @@ impl Module { ImportKind::Table(table_ty) => Some(ImportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ImportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ImportType::Global(global_ty)), + ImportKind::Tag(tag_ty) => Some(ImportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?)), }?; Some(ModuleImport { module: import.module.as_ref(), name: import.name.as_ref(), ty }) @@ -162,6 +168,7 @@ impl Module { | (ExternalKind::Table, ImportKind::Table(_)) | (ExternalKind::Memory, ImportKind::Memory(_)) | (ExternalKind::Global, ImportKind::Global(_)) + | (ExternalKind::Tag, ImportKind::Tag(_)) ) }) .count() @@ -175,6 +182,7 @@ impl Module { | (ExternalKind::Table, ImportKind::Table(_)) | (ExternalKind::Memory, ImportKind::Memory(_)) | (ExternalKind::Global, ImportKind::Global(_)) + | (ExternalKind::Tag, ImportKind::Tag(_)) ) }); let import = imports.nth(index)?; @@ -184,6 +192,7 @@ impl Module { ImportKind::Table(table_ty) => Some(ExportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ExportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ExportType::Global(global_ty)), + ImportKind::Tag(tag_ty) => Some(ExportType::Tag(module.types.get(tag_ty.type_idx)?.as_func()?)), } } @@ -223,6 +232,15 @@ impl Module { ExportType::Global(&self.0.globals.get(idx - imported_globals)?.ty) } } + ExternalKind::Tag => { + let imported_tags = imported_count(&self.0, ExternalKind::Tag); + if idx < imported_tags { + imported_type(&self.0, ExternalKind::Tag, idx)? + } else { + let tag_ty = self.0.tags.get(idx - imported_tags)?; + ExportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?) + } + } }; Some(ModuleExport { name: export.name.as_ref(), ty }) @@ -258,6 +276,8 @@ pub enum ImportType<'a> { Memory(&'a MemoryType), /// Imported global type. Global(&'a GlobalType), + /// Imported tag type. + Tag(&'a FuncType), } /// Exported entity type. @@ -270,6 +290,8 @@ pub enum ExportType<'a> { Memory(&'a MemoryType), /// Exported global type. Global(&'a GlobalType), + /// Exported tag type. + Tag(&'a FuncType), } /// How instantiation should prepare local memories declared by the module. @@ -301,6 +323,8 @@ pub enum ExternalKind { Memory, /// A WebAssembly Global. Global, + /// A WebAssembly Tag. + Tag, } /// A WebAssembly Address. @@ -315,6 +339,8 @@ pub type FuncAddr = Addr; pub type TableAddr = Addr; pub type MemAddr = Addr; pub type GlobalAddr = Addr; +pub type TagAddr = Addr; +pub type ExnAddr = Addr; pub type ElemAddr = Addr; pub type DataAddr = Addr; pub type ExternAddr = Addr; @@ -338,6 +364,7 @@ pub enum ExternVal { Table(TableAddr), Memory(MemAddr), Global(GlobalAddr), + Tag(TagAddr), } impl ExternVal { @@ -348,6 +375,7 @@ impl ExternVal { Self::Table(_) => ExternalKind::Table, Self::Memory(_) => ExternalKind::Memory, Self::Global(_) => ExternalKind::Global, + Self::Tag(_) => ExternalKind::Tag, } } @@ -358,6 +386,7 @@ impl ExternVal { ExternalKind::Table => Self::Table(addr), ExternalKind::Memory => Self::Memory(addr), ExternalKind::Global => Self::Global(addr), + ExternalKind::Tag => Self::Tag(addr), } } } @@ -444,6 +473,7 @@ pub struct WasmFunction { pub struct WasmFunctionData { pub v128_constants: Box<[[u8; 16]]>, pub branch_table_targets: Box<[u32]>, + pub exception_handlers: Box<[ExceptionHandler]>, } impl WasmFunctionData { @@ -638,6 +668,22 @@ pub enum MemoryArch { I64, } +/// A WebAssembly tag type. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct TagType { + /// The module-local function type index used by this tag. + pub type_idx: TypeAddr, +} + +impl TagType { + /// Creates a tag type from a module-local function type index. + pub const fn new(type_idx: TypeAddr) -> Self { + Self { type_idx } + } +} + #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -655,6 +701,7 @@ pub enum ImportKind { Table(TableType), Memory(MemoryType), Global(GlobalType), + Tag(TagType), } impl From<&ImportKind> for ExternalKind { @@ -664,6 +711,7 @@ impl From<&ImportKind> for ExternalKind { ImportKind::Table(_) => Self::Table, ImportKind::Memory(_) => Self::Memory, ImportKind::Global(_) => Self::Global, + ImportKind::Tag(_) => Self::Tag, } } } |
