summaryrefslogtreecommitdiff
path: root/crates/parser/src/module.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/parser/src/module.rs')
-rw-r--r--crates/parser/src/module.rs282
1 files changed, 182 insertions, 100 deletions
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index c2199f3..03c725c 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -1,11 +1,15 @@
use crate::log::debug;
-use crate::{ParseError, ParserOptions, Result, conversion::*, optimize};
-use alloc::{boxed::Box, format, string::ToString, sync::Arc, vec::Vec};
+#[cfg(parallel_parser)]
+use crate::validation::{FuncToValidate, ValidatorResources};
+use crate::validation::{FuncValidatorAllocations, Validator};
+use crate::{ParseError, ParserOptions, Result, conversion::*};
+use alloc::{boxed::Box, format, string::ToString, vec::Vec};
use core::marker::PhantomData;
use core::ops::Range;
use tinywasm_types::*;
-use wasmparser::{FuncValidatorAllocations, OperatorsReaderAllocations, Payload, Validator};
+use wasmparser::{OperatorsReaderAllocations, Payload};
+/// Final bytecode and metadata produced by streaming function lowering.
pub(crate) struct FunctionCode {
pub instructions: Vec<Instruction>,
pub data: WasmFunctionData,
@@ -13,52 +17,33 @@ pub(crate) struct FunctionCode {
pub uses_local_memory: bool,
}
-pub(crate) fn optimize_function_code(
- mut code: FunctionCode,
- options: &ParserOptions,
- function_results: ValueCounts,
- self_func_addr: u32,
- imported_memory_count: u32,
-) -> Result<FunctionCode> {
- let optimized = optimize::optimize_instructions(
- code.instructions,
- &mut code.data,
- options,
- function_results,
- self_func_addr,
- imported_memory_count,
- )?;
-
- code.instructions = optimized.instructions;
- code.uses_local_memory = optimized.uses_local_memory;
- Ok(code)
-}
-
#[derive(Default)]
pub(crate) struct ModuleReader<'a> {
func_validator_allocations: Option<FuncValidatorAllocations>,
operators_reader_allocations: Option<OperatorsReaderAllocations>,
- translation_metadata: Option<Arc<crate::visit::ModuleMetadata>>,
+ translation_metadata: Option<crate::visit::ModuleMetadata>,
has_code_section: bool,
+ has_type_section: bool,
marker: PhantomData<&'a [u8]>,
pub(crate) version: Option<u16>,
pub(crate) start_func: Option<u32>,
- pub(crate) func_types: Box<[FuncType]>,
+ pub(crate) types: TypeSection,
pub(crate) code_type_addrs: Box<[u32]>,
code_results: Box<[ValueCounts]>,
- pub(crate) exports: Arc<[Export]>,
+ pub(crate) exports: Shared<[Export]>,
pub(crate) code: Vec<FunctionCode>,
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]>,
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>>>,
@@ -67,23 +52,24 @@ pub(crate) struct ModuleReader<'a> {
impl<'a> ModuleReader<'a> {
fn translation_metadata(&mut self) -> &crate::visit::ModuleMetadata {
if self.translation_metadata.is_none() {
- self.translation_metadata = Some(Arc::new(crate::visit::ModuleMetadata::new(
- &self.func_types,
+ self.translation_metadata = Some(crate::visit::ModuleMetadata::new(
+ &self.types,
&self.code_type_addrs,
&self.imports,
&self.globals,
&self.memory_types,
&self.tables,
- )));
+ &self.tags,
+ ));
}
- self.translation_metadata.as_deref().unwrap()
+ self.translation_metadata.as_ref().unwrap()
}
- pub(crate) fn process_payload(
- &mut self,
- payload: Payload<'_>,
- mut validator: Option<&mut Validator>,
- ) -> Result<()> {
+ pub(crate) fn process_payload(&mut self, payload: Payload<'_>, validator: Option<&mut Validator>) -> Result<()> {
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+ #[cfg(not(feature = "validate"))]
+ let _ = validator;
fn check_section(section: &str, duplicate: bool) -> Result<()> {
debug!("found {section} section");
if duplicate {
@@ -94,9 +80,12 @@ impl<'a> ModuleReader<'a> {
match payload {
Payload::Version { num, encoding, range } => {
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.version(num, encoding, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = range;
self.version = Some(num);
if let wasmparser::Encoding::Component = encoding {
return Err(ParseError::InvalidEncoding(encoding));
@@ -104,27 +93,46 @@ impl<'a> ModuleReader<'a> {
}
Payload::StartSection { func, range } => {
check_section("start", self.start_func.is_some())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.start_section(func, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = range;
self.start_func = Some(func);
}
Payload::TypeSection(reader) => {
- check_section("type", !self.func_types.is_empty())?;
+ check_section("type", self.has_type_section)?;
+ self.has_type_section = true;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.type_section(&reader)?;
}
- self.func_types = reader.into_iter().map(|t| convert_module_type(t?)).collect::<Result<_>>()?;
+ let mut types = Vec::with_capacity(reader.count() as usize);
+ let mut rec_group_lengths = Vec::with_capacity(reader.count() as usize);
+ for group in reader {
+ let group = group?;
+ let group_start = u32::try_from(types.len())
+ .map_err(|_| ParseError::Other("type section is too large".into()))?;
+ let group_len = convert_rec_group(group, group_start, &mut types)?;
+ rec_group_lengths.push(group_len);
+ }
+ self.types = TypeSection {
+ types: types.into_boxed_slice(),
+ rec_group_lengths: rec_group_lengths.into_boxed_slice(),
+ };
}
Payload::GlobalSection(reader) => {
check_section("global", !self.globals.is_empty())?;
+ #[cfg(feature = "validate")]
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())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.table_section(&reader)?;
}
@@ -140,7 +148,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 });
@@ -149,38 +157,69 @@ impl<'a> ModuleReader<'a> {
}
Payload::MemorySection(reader) => {
check_section("memory", !self.memory_types.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.memory_section(&reader)?;
}
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")]
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())?;
+ #[cfg(feature = "validate")]
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");
if !self.data.is_empty() {
return Err(ParseError::UnsupportedSection("Data count section after data section".into()));
}
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.data_count_section(count, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = (count, range);
}
Payload::FunctionSection(reader) => {
check_section("function", !self.code_type_addrs.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.function_section(&reader)?;
}
@@ -188,10 +227,9 @@ impl<'a> ModuleReader<'a> {
let mut results = Vec::with_capacity(reader.count() as usize);
for ty_idx in reader {
let ty_idx = ty_idx?;
- let ty = self
- .func_types
- .get(ty_idx as usize)
- .ok_or_else(|| ParseError::Other(format!("function type index out of bounds: {ty_idx}")))?;
+ let ty = self.types.get(ty_idx).and_then(SubType::as_func).ok_or_else(|| {
+ ParseError::Other(format!("function type index does not reference a function: {ty_idx}"))
+ })?;
type_addrs.push(ty_idx);
results.push(ValueCounts::from_iter(ty.results()));
}
@@ -200,6 +238,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::ImportSection(reader) => {
check_section("import", !self.imports.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.import_section(&reader)?;
}
@@ -207,8 +246,29 @@ impl<'a> ModuleReader<'a> {
for import in reader.into_imports() {
let import = convert_module_import(import?)?;
match import.kind {
- ImportKind::Function(_) => self.imported_func_count += 1,
- ImportKind::Memory(_) => self.imported_memory_count += 1,
+ ImportKind::Function(type_idx) => {
+ if self.types.get(type_idx).and_then(SubType::as_func).is_none() {
+ return Err(ParseError::Other(format!(
+ "function import type index does not reference a function: {type_idx}"
+ )));
+ }
+ self.imported_func_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!(
+ "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);
@@ -217,6 +277,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::ExportSection(reader) => {
check_section("export", !self.exports.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.export_section(&reader)?;
}
@@ -228,9 +289,12 @@ impl<'a> ModuleReader<'a> {
return Err(ParseError::DuplicateSection("End section".into()));
}
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.end(offset)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = offset;
self.end_reached = true;
}
Payload::CustomSection(_reader) => {
@@ -250,7 +314,7 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn begin_code_section(
&mut self,
count: u32,
- range: Range<usize>,
+ range: Range<u64>,
size: u32,
validator: Option<&mut Validator>,
options: &ParserOptions,
@@ -262,9 +326,12 @@ impl<'a> ModuleReader<'a> {
self.has_code_section = true;
self.code.reserve(count as usize);
+ #[cfg(feature = "validate")]
if let Some(validator) = validator {
validator.code_section_start(&range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = (range, validator);
#[cfg(parallel_parser)]
{
@@ -294,28 +361,37 @@ impl<'a> ModuleReader<'a> {
let func_validator_allocs = self.func_validator_allocations.take();
let operators_reader_allocs = self.operators_reader_allocations.take().unwrap_or_default();
+ #[cfg(feature = "validate")]
let func_validator = validator
.map(|validator| validator.code_section_entry(&function))
.transpose()?
.map(|func| func.into_validator(func_validator_allocs.unwrap_or_default()));
+ #[cfg(not(feature = "validate"))]
+ let func_validator = {
+ let _ = (validator, func_validator_allocs);
+ None
+ };
let ordinal = self.code.len();
let ty_idx = *self
.code_type_addrs
.get(ordinal)
.ok_or_else(|| ParseError::Other("code entry has no function signature".into()))?;
+ let context = FunctionLoweringContext {
+ ty_idx,
+ self_func_addr: self
+ .imported_func_count
+ .checked_add(ordinal)
+ .and_then(|idx| u32::try_from(idx).ok())
+ .ok_or_else(|| ParseError::Other("function index is too large".into()))?,
+ function_results: self.code_results[ordinal],
+ };
let metadata = self.translation_metadata();
let (code, func_validator_allocs, operators_reader_allocs) =
- convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx)?;
+ convert_module_code(function, func_validator, operators_reader_allocs, metadata, context, options)?;
- self.code.push(optimize_function_code(
- code,
- options,
- self.code_results[self.code.len()],
- (self.imported_func_count + self.code.len()) as u32,
- self.imported_memory_count,
- )?);
+ self.code.push(code);
self.func_validator_allocations = func_validator_allocs;
self.operators_reader_allocations = Some(operators_reader_allocs);
@@ -332,7 +408,10 @@ impl<'a> ModuleReader<'a> {
#[cfg(parallel_parser)]
if self.pending_functions.is_some() {
+ #[cfg(feature = "validate")]
let func_to_validate = validator.map(|validator| validator.code_section_entry(&function)).transpose()?;
+ #[cfg(not(feature = "validate"))]
+ let func_to_validate = None;
return self.queue_function(crate::parallel::FunctionBodyInput::Borrowed(function), func_to_validate);
}
@@ -343,21 +422,31 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn queue_owned_code_section(
&mut self,
count: u32,
- body_offset: usize,
- section_bytes: Arc<[u8]>,
- mut validator: Option<&mut Validator>,
+ body_offset: u64,
+ section_bytes: Shared<[u8]>,
+ validator: Option<&mut Validator>,
) -> Result<()> {
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+ #[cfg(not(feature = "validate"))]
+ let _ = validator;
let mut reader = wasmparser::BinaryReader::new(&section_bytes, body_offset);
for _ in 0..count {
let body_reader = reader.read_reader()?;
let body_range = body_reader.range();
- let function = wasmparser::FunctionBody::new(body_reader);
- let func_to_validate =
- validator.as_mut().map(|validator| validator.code_section_entry(&function)).transpose()?;
+ let body_start = (body_range.start - body_offset) as usize;
+ let body_end = (body_range.end - body_offset) as usize;
+ #[cfg(feature = "validate")]
+ let func_to_validate = {
+ let function = wasmparser::FunctionBody::new(body_reader);
+ validator.as_mut().map(|validator| validator.code_section_entry(&function)).transpose()?
+ };
+ #[cfg(not(feature = "validate"))]
+ let func_to_validate = None;
self.queue_function(
crate::parallel::FunctionBodyInput::Owned(crate::parallel::OwnedFunctionBody {
section_bytes: section_bytes.clone(),
- body_range: (body_range.start - body_offset)..(body_range.end - body_offset),
+ body_range: body_start..body_end,
body_offset: body_range.start,
}),
func_to_validate,
@@ -378,7 +467,7 @@ impl<'a> ModuleReader<'a> {
fn queue_function(
&mut self,
body: crate::parallel::FunctionBodyInput<'a>,
- func_to_validate: Option<wasmparser::FuncToValidate<wasmparser::ValidatorResources>>,
+ func_to_validate: Option<FuncToValidate<ValidatorResources>>,
) -> Result<()> {
let ordinal = self.code.len() + self.pending_functions.as_ref().map_or(0, Vec::len);
let results = *self
@@ -404,10 +493,8 @@ impl<'a> ModuleReader<'a> {
};
let imported_func_count = self.imported_func_count;
- let imported_memory_count = self.imported_memory_count;
let metadata = self.translation_metadata();
- let code =
- crate::parallel::process_pending(pending, metadata, options, imported_func_count, imported_memory_count)?;
+ let code = crate::parallel::process_pending(pending, metadata, options, imported_func_count)?;
self.code.extend(code);
Ok(())
}
@@ -417,7 +504,7 @@ impl<'a> ModuleReader<'a> {
Ok(())
}
- pub(crate) fn into_module(self, options: &ParserOptions) -> Result<Module> {
+ pub(crate) fn into_module(self) -> Result<Module> {
if !self.end_reached {
return Err(ParseError::EndNotReached);
}
@@ -426,24 +513,6 @@ impl<'a> ModuleReader<'a> {
return Err(ParseError::Other("Code and code type address count mismatch".to_string()));
}
- let import_mem_count = self.imported_memory_count;
- let has_local_mem_export =
- self.exports.iter().any(|export| export.kind == ExternalKind::Memory && export.index >= import_mem_count);
- let has_active_data_segment_on_local_memory = self.data.iter().any(|data| match &data.kind {
- DataKind::Active { mem, .. } => *mem >= import_mem_count,
- DataKind::Passive => false,
- });
- let optimize_local_memory_allocation = options.optimize_local_memory_allocation();
- let mut local_memory_allocation = if self.memory_types.is_empty() {
- LocalMemoryAllocation::Skip
- } else if !optimize_local_memory_allocation || has_active_data_segment_on_local_memory {
- LocalMemoryAllocation::Eager
- } else if has_local_mem_export {
- LocalMemoryAllocation::Lazy
- } else {
- LocalMemoryAllocation::Skip
- };
-
let func_type_idxs = self
.imports
.iter()
@@ -454,31 +523,43 @@ impl<'a> ModuleReader<'a> {
.chain(self.code_type_addrs.iter().copied())
.collect();
+ let imported_memory_count =
+ self.imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count();
+ let uses_local_memory = self.code.iter().any(|code| code.uses_local_memory);
+ let exports_local_memory = self
+ .exports
+ .iter()
+ .any(|export| export.kind == ExternalKind::Memory && export.index as usize >= imported_memory_count);
+ let initializes_local_memory = self
+ .data
+ .iter()
+ .any(|data| matches!(data.kind, DataKind::Active { mem, .. } if mem as usize >= imported_memory_count));
+ let skip_local_memory_allocation =
+ !self.memory_types.is_empty() && !uses_local_memory && !exports_local_memory && !initializes_local_memory;
+
let funcs = self
.code
.into_iter()
.zip(self.code_type_addrs)
.zip(self.code_results)
- .map(|((code, ty_idx), results)| {
- let ty = self.func_types.get(ty_idx as usize).expect("function type was checked while parsing").clone();
+ .map(|((code, ty_idx), results)| -> Result<_> {
+ let ty =
+ self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing");
let params = ValueCounts::from_iter(ty.params());
- if code.uses_local_memory {
- local_memory_allocation = LocalMemoryAllocation::Eager;
- }
- Arc::new(WasmFunction {
- instructions: code.instructions.into(),
+ Ok(Shared::new(WasmFunction {
+ instructions: code.instructions.into_boxed_slice(),
data: code.data,
locals: code.locals,
params,
results,
- })
+ }))
})
- .collect();
+ .collect::<Result<_>>()?;
Ok(ModuleInner {
funcs,
- func_types: self.func_types,
+ types: self.types,
func_type_idxs,
globals: self.globals,
tables: self.tables,
@@ -488,7 +569,8 @@ impl<'a> ModuleReader<'a> {
exports: self.exports,
elements: self.elements,
memory_types: self.memory_types,
- local_memory_allocation,
+ skip_local_memory_allocation,
+ tags: self.tags,
}
.into())
}