summaryrefslogtreecommitdiff
path: root/crates/parser/src
diff options
context:
space:
mode:
authorHenry <mail@henrygressmann.de>2026-08-09 18:07:51 +0200
committerHenry <mail@henrygressmann.de>2026-08-09 18:07:51 +0200
commite005e5afd144f5659e2ed19afa8ee94ff924be55 (patch)
tree75b66c1a750f2c4a86efe9573fb25a19e186abb0 /crates/parser/src
parent9893a51d2712f82a2ee57316a66bc26500eb3fdd (diff)
feat: initial exception support
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/parser/src')
-rw-r--r--crates/parser/src/conversion.rs11
-rw-r--r--crates/parser/src/lib.rs1
-rw-r--r--crates/parser/src/macros.rs1
-rw-r--r--crates/parser/src/module.rs36
-rw-r--r--crates/parser/src/optimize.rs42
-rw-r--r--crates/parser/src/visit.rs127
6 files changed, 209 insertions, 9 deletions
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));