summaryrefslogtreecommitdiff
path: root/crates/parser/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/parser/src/lib.rs')
-rw-r--r--crates/parser/src/lib.rs179
1 files changed, 98 insertions, 81 deletions
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index aa5e0b0..019e027 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -30,10 +30,12 @@ pub(crate) mod log {
}
mod conversion;
+mod emitter;
mod error;
mod macros;
mod module;
-mod optimize;
+mod selection;
+mod validation;
mod visit;
#[cfg(parallel_parser)]
@@ -41,7 +43,10 @@ mod parallel;
pub use error::*;
use module::ModuleReader;
-use wasmparser::{Validator, WasmFeatures};
+use validation::Validator;
+
+#[cfg(feature = "validate")]
+use wasmparser::WasmFeatures;
pub use tinywasm_types::Module;
@@ -49,15 +54,20 @@ pub use tinywasm_types::Module;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ParserOptions {
- /// Whether to validate modules while parsing. Enabled by default.
+ /// Whether to validate modules while parsing. Enabled by default when the
+ /// `validate` feature is enabled.
+ ///
+ /// Requires the `validate` feature to have any effect.
///
/// Disable this only for trusted input. Parsing without validation may produce
/// a module that violates runtime assumptions.
pub validation: bool,
- /// Whether to optimize local memory allocation by skipping allocation of unused local memories.
- pub optimize_local_memory_allocation: bool,
- /// Whether to run the peephole rewrite optimizer.
- pub optimize_rewrite: bool,
+
+ /// Whether to enable some of the optimizations during lowering, such as bounded instruction selection.
+ pub optimize: bool,
+
+ /// Whether to deduplicate immutable function operands while parsing.
+ pub deduplicate_operands: bool,
#[cfg(parallel_parser)]
/// Number of threads to use for parallel parsing.
@@ -67,27 +77,35 @@ pub struct ParserOptions {
/// - `None`: auto-detect based on available parallelism
/// - `Some(1)`: force single-threaded
/// - `Some(n)`: use up to `n` workers
- pub parser_threads: Option<usize>,
+ pub threads: Option<usize>,
}
impl Default for ParserOptions {
fn default() -> Self {
Self {
- validation: true,
- optimize_local_memory_allocation: true,
- optimize_rewrite: true,
+ validation: cfg!(feature = "validate"),
+ optimize: true,
+ deduplicate_operands: true,
#[cfg(parallel_parser)]
- parser_threads: None,
+ threads: None,
}
}
}
impl ParserOptions {
+ /// Create parser options with default settings.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
/// Enable or disable WebAssembly validation.
///
+ /// Requires the `validate` feature to have any effect.
+ ///
/// Disable this only for trusted input. Parsing without validation may produce
/// a module that violates runtime assumptions.
pub const fn with_validation(mut self, enabled: bool) -> Self {
+ assert!(!enabled || cfg!(feature = "validate"), "validation requires the `validate` feature");
self.validation = enabled;
self
}
@@ -97,41 +115,41 @@ impl ParserOptions {
self.validation
}
- /// Enable or disable the optimization that skips allocating unused local memories.
- pub const fn with_local_memory_allocation_optimization(mut self, enabled: bool) -> Self {
- self.optimize_local_memory_allocation = enabled;
+ /// Enable or disable some of the optimizations during lowering, such as bounded instruction selection.
+ pub const fn with_optimize(mut self, enabled: bool) -> Self {
+ self.optimize = enabled;
self
}
- /// Returns whether unused local memory allocation optimization is enabled.
- pub const fn optimize_local_memory_allocation(&self) -> bool {
- self.optimize_local_memory_allocation
+ /// Returns whether some of the optimizations during lowering, such as bounded instruction selection, are enabled.
+ pub const fn optimize(&self) -> bool {
+ self.optimize
}
- /// Enable or disable the peephole rewrite optimizer.
- pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self {
- self.optimize_rewrite = enabled;
+ /// Enable or disable parse-time deduplication of immutable function operands.
+ pub const fn with_operand_deduplication(mut self, enabled: bool) -> Self {
+ self.deduplicate_operands = enabled;
self
}
- /// Returns whether the peephole rewrite optimizer is enabled.
- pub const fn optimize_rewrite(&self) -> bool {
- self.optimize_rewrite
+ /// Returns whether immutable function operands are deduplicated while parsing.
+ pub const fn deduplicate_operands(&self) -> bool {
+ self.deduplicate_operands
}
#[cfg(parallel_parser)]
/// Set the number of threads for parallel parsing.
///
/// Requires the `parallel` feature to have any effect.
- pub const fn with_parser_threads(mut self, threads: usize) -> Self {
- self.parser_threads = Some(threads);
+ pub const fn with_threads(mut self, threads: usize) -> Self {
+ self.threads = Some(threads);
self
}
#[cfg(parallel_parser)]
/// Returns the configured parser thread count, or `None` for auto-detect.
- pub const fn parser_threads(&self) -> Option<usize> {
- self.parser_threads
+ pub const fn threads(&self) -> Option<usize> {
+ self.threads
}
}
@@ -142,13 +160,8 @@ pub struct Parser {
}
impl Parser {
- /// Create a new parser instance
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Create a new parser with explicit options.
- pub fn with_options(options: ParserOptions) -> Self {
+ /// Create a parser with the given options.
+ pub const fn new(options: ParserOptions) -> Self {
Self { options }
}
@@ -157,36 +170,44 @@ impl Parser {
&self.options
}
- fn create_validator(_options: ParserOptions) -> Validator {
- let features = WasmFeatures::CALL_INDIRECT_OVERLONG
- | WasmFeatures::BULK_MEMORY_OPT
- | WasmFeatures::RELAXED_SIMD
- | WasmFeatures::GC_TYPES
- | WasmFeatures::REFERENCE_TYPES
- | WasmFeatures::MUTABLE_GLOBAL
- | WasmFeatures::MULTI_VALUE
- | WasmFeatures::FLOATS
- | WasmFeatures::BULK_MEMORY
- | WasmFeatures::SATURATING_FLOAT_TO_INT
- | WasmFeatures::SIGN_EXTENSION
- | WasmFeatures::EXTENDED_CONST
- | WasmFeatures::FUNCTION_REFERENCES
- | WasmFeatures::TAIL_CALL
- | WasmFeatures::MULTI_MEMORY
- | WasmFeatures::SIMD
- | WasmFeatures::MEMORY64
- | WasmFeatures::CUSTOM_PAGE_SIZES
- | WasmFeatures::WIDE_ARITHMETIC;
- Validator::new_with_features(features)
+ fn validator(&self) -> Option<Validator> {
+ #[cfg(feature = "validate")]
+ {
+ let features = WasmFeatures::WASM3
+ .difference(WasmFeatures::THREADS)
+ .union(WasmFeatures::CUSTOM_PAGE_SIZES)
+ .union(WasmFeatures::WIDE_ARITHMETIC)
+ .union(WasmFeatures::COMPACT_IMPORTS);
+ self.options.validation().then(|| Validator::new_with_features(features))
+ }
+ #[cfg(not(feature = "validate"))]
+ {
+ assert!(!self.options.validation(), "validation requires the `validate` feature");
+ None
+ }
}
#[cfg(feature = "std")]
fn read_more(stream: &mut impl std::io::Read, buffer: &mut alloc::vec::Vec<u8>, hint: usize) -> Result<usize> {
let len = buffer.len();
- buffer.resize(len + hint, 0);
- let read_bytes = stream
- .read(&mut buffer[len..])
- .map_err(|e| ParseError::Other(alloc::format!("Error reading from stream: {e}")))?;
+ // Size hints can come from untrusted section lengths.
+ let increment = hint.clamp(1, 64 * 1024);
+ let new_len =
+ len.checked_add(increment).ok_or_else(|| ParseError::Other("stream buffer is too large".into()))?;
+ buffer
+ .try_reserve(increment)
+ .map_err(|e| ParseError::Other(alloc::format!("Error reserving stream buffer: {e}")))?;
+ buffer.resize(new_len, 0);
+ let read_bytes = loop {
+ match stream.read(&mut buffer[len..]) {
+ Ok(read_bytes) => break read_bytes,
+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(e) => {
+ buffer.truncate(len);
+ return Err(ParseError::Other(alloc::format!("Error reading from stream: {e}")));
+ }
+ }
+ };
buffer.truncate(len + read_bytes);
Ok(read_bytes)
}
@@ -194,7 +215,7 @@ impl Parser {
/// Parse a [`Module`] from bytes
pub fn parse_module_bytes(&self, wasm: impl AsRef<[u8]>) -> Result<Module> {
let wasm = wasm.as_ref();
- let mut validator = self.options.validation().then(|| Self::create_validator(self.options.clone()));
+ let mut validator = self.validator();
let mut reader = ModuleReader::default();
for payload in wasmparser::Parser::new(0).parse_all(wasm) {
@@ -214,7 +235,7 @@ impl Parser {
}
reader.process_pending_functions(&self.options)?;
- reader.into_module(&self.options)
+ reader.into_module()
}
#[cfg(feature = "std")]
@@ -228,7 +249,7 @@ impl Parser {
#[cfg(feature = "std")]
/// Parse a [`Module`] from a stream. Requires `std` feature.
pub fn parse_module_stream(&self, mut stream: impl std::io::Read) -> Result<Module> {
- let mut validator = self.options.validation().then(|| Self::create_validator(self.options.clone()));
+ let mut validator = self.validator();
let mut reader = ModuleReader::default();
let mut buffer = alloc::vec::Vec::new();
let mut parser = wasmparser::Parser::new(0);
@@ -243,7 +264,7 @@ impl Parser {
buffer.truncate(buffer.len() - buffer_offset);
buffer_offset = 0;
}
- let read_bytes = Self::read_more(&mut stream, &mut buffer, hint as usize)?;
+ let read_bytes = Self::read_more(&mut stream, &mut buffer, hint)?;
eof = read_bytes == 0;
}
wasmparser::Chunk::Parsed { consumed, payload } => {
@@ -252,17 +273,12 @@ impl Parser {
match payload {
wasmparser::Payload::CodeSectionStart { count, range, size } => {
- let defer = reader.begin_code_section(
- count,
- range.clone(),
- size,
- validator.as_mut(),
- &self.options,
- )?;
+ let defer =
+ reader.begin_code_section(count, range, size, validator.as_mut(), &self.options)?;
#[cfg(parallel_parser)]
if defer {
- deferred_code_section = Some((count, range.end - size as usize, size as usize));
+ deferred_code_section = Some((count, size as usize));
}
#[cfg(not(parallel_parser))]
@@ -278,21 +294,22 @@ impl Parser {
buffer_offset += consumed;
#[cfg(parallel_parser)]
- if let Some((count, body_offset, section_size)) = deferred_code_section {
+ if let Some((count, section_size)) = deferred_code_section {
while buffer.len() - buffer_offset < section_size {
let remaining = section_size - (buffer.len() - buffer_offset);
let read_bytes = Self::read_more(&mut stream, &mut buffer, remaining)?;
if read_bytes == 0 {
return Err(ParseError::ParseError {
message: "unexpected end-of-file".into(),
- offset: body_offset + buffer.len() - buffer_offset,
+ offset: parser.offset() + (buffer.len() - buffer_offset) as u64,
});
}
}
let section_end = buffer_offset + section_size;
- let section_bytes = alloc::sync::Arc::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
- reader.queue_owned_code_section(count, body_offset, section_bytes, validator.as_mut())?;
+ let section_bytes =
+ tinywasm_types::Shared::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
+ reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?;
parser.skip_section();
buffer_offset = section_end;
continue;
@@ -315,7 +332,7 @@ impl Parser {
if reader.end_reached || eof {
reader.process_pending_functions(&self.options)?;
- return reader.into_module(&self.options);
+ return reader.into_module();
}
}
};
@@ -327,23 +344,23 @@ impl TryFrom<ModuleReader<'_>> for Module {
type Error = ParseError;
fn try_from(reader: ModuleReader<'_>) -> Result<Self> {
- reader.into_module(&ParserOptions::default())
+ reader.into_module()
}
}
/// Parse a module from bytes
pub fn parse_bytes(wasm: &[u8]) -> Result<Module> {
- Parser::new().parse_module_bytes(wasm)
+ Parser::default().parse_module_bytes(wasm)
}
#[cfg(feature = "std")]
/// Parse a module from a file. Requires the `std` feature.
pub fn parse_file(path: impl AsRef<crate::std::path::Path> + Clone) -> Result<Module> {
- Parser::new().parse_module_file(path)
+ Parser::default().parse_module_file(path)
}
#[cfg(feature = "std")]
/// Parse a module from a stream. Requires the `std` feature.
pub fn parse_stream(stream: impl crate::std::io::Read) -> Result<Module> {
- Parser::new().parse_module_stream(stream)
+ Parser::default().parse_module_stream(stream)
}