diff options
Diffstat (limited to 'crates/parser')
| -rw-r--r-- | crates/parser/src/conversion.rs | 48 | ||||
| -rw-r--r-- | crates/parser/src/macros.rs | 2 | ||||
| -rw-r--r-- | crates/parser/src/module.rs | 17 | ||||
| -rw-r--r-- | crates/parser/src/visit.rs | 73 |
4 files changed, 93 insertions, 47 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 7b52363..694c639 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -14,11 +14,14 @@ pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane { } } -pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> { +pub(crate) fn convert_module_element( + element: wasmparser::Element<'_>, + global_types: &[WasmType], +) -> Result<tinywasm_types::Element> { let kind = match element.kind { wasmparser::ElementKind::Active { table_index, offset_expr } => tinywasm_types::ElementKind::Active { table: table_index.unwrap_or(0), - offset: process_const_operators(offset_expr.get_operators_reader())?, + offset: process_const_operators(offset_expr.get_operators_reader(), global_types)?, }, wasmparser::ElementKind::Passive => tinywasm_types::ElementKind::Passive, wasmparser::ElementKind::Declared => tinywasm_types::ElementKind::Declared, @@ -38,7 +41,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result wasmparser::ElementItems::Expressions(ty, exprs) => { let items = exprs .into_iter() - .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader())?))) + .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader(), global_types)?))) .collect::<Result<Vec<_>>>()? .into_boxed_slice(); @@ -47,13 +50,16 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result } } -pub(crate) fn convert_module_data(data: wasmparser::Data<'_>) -> Result<tinywasm_types::Data> { +pub(crate) fn convert_module_data( + data: wasmparser::Data<'_>, + global_types: &[WasmType], +) -> Result<tinywasm_types::Data> { Ok(tinywasm_types::Data { data: data.data.to_vec().into_boxed_slice(), range: data.range, kind: match data.kind { wasmparser::DataKind::Active { memory_index, offset_expr } => { - let offset = process_const_operators(offset_expr.get_operators_reader())?; + let offset = process_const_operators(offset_expr.get_operators_reader(), global_types)?; tinywasm_types::DataKind::Active { mem: memory_index, offset } } wasmparser::DataKind::Passive => tinywasm_types::DataKind::Passive, @@ -96,16 +102,17 @@ pub(crate) fn convert_module_memory(memory: wasmparser::MemoryType) -> MemoryTyp pub(crate) fn convert_module_globals( globals: wasmparser::SectionLimited<'_, wasmparser::Global<'_>>, + global_types: &mut Vec<WasmType>, ) -> Result<Box<[Global]>> { - globals - .into_iter() - .map(|global| { - let global = global?; - let ty = convert_valtype(&global.ty.content_type)?; - let ops = global.init_expr.get_operators_reader(); - Ok(Global { init: process_const_operators(ops)?, ty: GlobalType::new(ty, global.ty.mutable) }) - }) - .collect::<Result<Box<_>>>() + let mut out = Vec::with_capacity(globals.count() as usize); + for global in globals { + let global = global?; + let ty = convert_valtype(&global.ty.content_type)?; + let init = process_const_operators(global.init_expr.get_operators_reader(), global_types)?; + global_types.push(ty); + out.push(Global { init, ty: GlobalType::new(ty, global.ty.mutable) }); + } + Ok(out.into_boxed_slice()) } pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Export> { @@ -313,7 +320,10 @@ fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32, } } -pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[ConstInstruction]>> { +pub(crate) fn process_const_operators( + ops: OperatorsReader<'_>, + global_types: &[WasmType], +) -> Result<Box<[ConstInstruction]>> { let mut out = Vec::new(); let mut operator_count = 0; let mut end_reached = false; @@ -353,7 +363,13 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C wasmparser::Operator::F32Const { value } => ConstInstruction::F32Const(f32::from_bits(value.bits())), wasmparser::Operator::F64Const { value } => ConstInstruction::F64Const(f64::from_bits(value.bits())), wasmparser::Operator::V128Const { value } => ConstInstruction::V128Const(*value.bytes()), - wasmparser::Operator::GlobalGet { global_index } => ConstInstruction::GlobalGet(global_index), + wasmparser::Operator::GlobalGet { global_index } => match global_types.get(global_index as usize) { + Some(WasmType::I32 | WasmType::F32) => ConstInstruction::GlobalGet32(global_index), + Some(WasmType::I64 | WasmType::F64) => ConstInstruction::GlobalGet64(global_index), + Some(WasmType::V128) => ConstInstruction::GlobalGet128(global_index), + Some(WasmType::Ref(_)) => ConstInstruction::GlobalGetRef(global_index), + None => return Err(crate::ParseError::Other(format!("global index out of bounds: {global_index}"))), + }, wasmparser::Operator::I32Add => ConstInstruction::I32Add, wasmparser::Operator::I32Sub => ConstInstruction::I32Sub, wasmparser::Operator::I32Mul => ConstInstruction::I32Mul, diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 98312ab..9fa7a01 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -89,7 +89,7 @@ pub(crate) mod visit { $visit:ident($type_index:ident: $type_ty:ty $(, $arg:ident: $arg_ty:ty)*) => $instr:ident ) => { fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output { - let size = ModuleMetadata::storage_size(self.metadata.array_field($type_index)?.storage); + let size = self.metadata.array_field($type_index)?; lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*] Instruction::$instr($type_index $(, $arg)*).into()) } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index bbe2cf8..3d38ad6 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -64,6 +64,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) end_reached: bool, imported_func_count: usize, imported_memory_count: u32, + global_types: Vec<WasmType>, #[cfg(parallel_parser)] pending_functions: Option<Vec<crate::parallel::PendingFunction<'a>>>, @@ -148,7 +149,7 @@ impl<'a> ModuleReader<'a> { if let Some(validator) = validator.as_mut() { validator.global_section(&reader)?; } - self.globals = convert_module_globals(reader)?; + self.globals = convert_module_globals(reader, &mut self.global_types)?; } Payload::TableSection(reader) => { check_section("table", !self.tables.is_empty())?; @@ -168,7 +169,7 @@ impl<'a> ModuleReader<'a> { let init = match table.init { wasmparser::TableInit::RefNull => None, wasmparser::TableInit::Expr(expr) => { - Some(process_const_operators(expr.get_operators_reader())?) + Some(process_const_operators(expr.get_operators_reader(), &self.global_types)?) } }; tables.push(TableDefinition { ty, init }); @@ -209,8 +210,10 @@ impl<'a> ModuleReader<'a> { if let Some(validator) = validator.as_mut() { validator.element_section(&reader)?; } - self.elements = - reader.into_iter().map(|element| convert_module_element(element?)).collect::<Result<_>>()?; + self.elements = reader + .into_iter() + .map(|element| convert_module_element(element?, &self.global_types)) + .collect::<Result<_>>()?; } Payload::DataSection(reader) => { check_section("data", !self.data.is_empty())?; @@ -218,7 +221,10 @@ impl<'a> ModuleReader<'a> { if let Some(validator) = validator.as_mut() { validator.data_section(&reader)?; } - self.data = reader.into_iter().map(|data| convert_module_data(data?)).collect::<Result<_>>()?; + self.data = reader + .into_iter() + .map(|data| convert_module_data(data?, &self.global_types)) + .collect::<Result<_>>()?; } Payload::DataCountSection { count, range } => { debug!("Found data count section"); @@ -270,6 +276,7 @@ impl<'a> ModuleReader<'a> { self.imported_func_count += 1; } ImportKind::Memory(_) => self.imported_memory_count += 1, + ImportKind::Global(ty) => self.global_types.push(ty.ty), ImportKind::Tag(tag) => { let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { ParseError::Other(format!( diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index c462d05..063bef4 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -3,11 +3,10 @@ use crate::{ conversion::{convert_heap_type, value_lane}, macros::visit::*, }; -use alloc::string::ToString; -use alloc::vec::Vec; +use alloc::{boxed::Box, string::ToString, vec::Vec}; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TagType, - TypeSection, ValueCounts, ValueLane, WasmFunctionData, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, TableDefinition, TagType, TypeSection, + ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -50,7 +49,13 @@ pub(crate) struct ModuleMetadata { memories: Vec<ValueLane>, tables: Vec<ValueLane>, tags: Vec<u32>, - types: Vec<SubType>, + aggregate_fields: Vec<AggregateFields>, +} + +enum AggregateFields { + Other, + Struct(Box<[ValueLane]>), + Array(ValueLane), } #[derive(Default)] @@ -109,7 +114,7 @@ impl<'a> FunctionBuilder<'a> { field_index: u32, instruction: fn(u32, u32) -> Instruction, ) -> Result<()> { - let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + let size = self.metadata.struct_field(type_index, field_index)?; self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) } } @@ -170,6 +175,19 @@ impl ModuleMetadata { }) }) .collect(); + let aggregate_fields = types + .types + .iter() + .map(|ty| { + if let Some(ty) = ty.as_struct() { + AggregateFields::Struct(ty.fields.iter().map(|field| Self::storage_size(field.storage)).collect()) + } else if let Some(ty) = ty.as_array() { + AggregateFields::Array(Self::storage_size(ty.field.storage)) + } else { + AggregateFields::Other + } + }) + .collect(); Self { signatures, functions, @@ -177,7 +195,7 @@ impl ModuleMetadata { memories: memory_sizes, tables: table_sizes, tags: tag_types, - types: types.types.to_vec(), + aggregate_fields, } } @@ -230,26 +248,30 @@ impl ModuleMetadata { } } - fn struct_fields(&self, idx: u32) -> Result<&[tinywasm_types::FieldType]> { - self.types + fn struct_fields(&self, idx: u32) -> Result<&[ValueLane]> { + self.aggregate_fields .get(idx as usize) - .and_then(SubType::as_struct) - .map(|ty| ty.fields.as_ref()) + .and_then(|fields| match fields { + AggregateFields::Struct(fields) => Some(fields.as_ref()), + AggregateFields::Other | AggregateFields::Array(_) => None, + }) .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a struct type: {idx}"))) } - fn struct_field(&self, type_index: u32, field_index: u32) -> Result<tinywasm_types::FieldType> { + fn struct_field(&self, type_index: u32, field_index: u32) -> Result<ValueLane> { self.struct_fields(type_index)? .get(field_index as usize) .copied() .ok_or_else(|| crate::ParseError::Other("struct field index out of bounds".into())) } - fn array_field(&self, idx: u32) -> Result<tinywasm_types::FieldType> { - self.types + fn array_field(&self, idx: u32) -> Result<ValueLane> { + self.aggregate_fields .get(idx as usize) - .and_then(SubType::as_array) - .map(|ty| ty.field) + .and_then(|fields| match fields { + AggregateFields::Array(field) => Some(*field), + AggregateFields::Other | AggregateFields::Struct(_) => None, + }) .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not an array type: {idx}"))) } } @@ -490,13 +512,14 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_struct_new(&mut self, type_index: u32) -> Self::Output { - let inputs = self - .metadata - .struct_fields(type_index)? - .iter() - .map(|field| ModuleMetadata::storage_size(field.storage)) - .collect::<Vec<_>>(); - self.emit(&inputs, &[ValueLane::S32], Instruction::StructNew(type_index)) + let field_count = self.metadata.struct_fields(type_index)?.len(); + for field_index in (0..field_count).rev() { + let size = self.metadata.struct_field(type_index, field_index as u32)?; + self.pop_expect(size)?; + } + self.push_sizes(&[ValueLane::S32])?; + self.instructions.push(Instruction::StructNew(type_index)); + Ok(()) } fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { @@ -512,12 +535,12 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { - let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + let size = self.metadata.struct_field(type_index, field_index)?; self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { - let size = ModuleMetadata::storage_size(self.metadata.array_field(type_index)?.storage); + let size = self.metadata.array_field(type_index)?; for _ in 0..array_size { self.pop_expect(size)?; } |
