summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md1
-rw-r--r--README.md5
-rw-r--r--crates/cli/Cargo.toml1
-rw-r--r--crates/parser/Cargo.toml5
-rw-r--r--crates/parser/README.md3
-rw-r--r--crates/parser/src/conversion.rs77
-rw-r--r--crates/parser/src/lib.rs70
-rw-r--r--crates/parser/src/macros.rs22
-rw-r--r--crates/parser/src/module.rs66
-rw-r--r--crates/parser/src/parallel.rs11
-rw-r--r--crates/parser/src/validation.rs15
-rw-r--r--crates/parser/src/visit.rs58
-rw-r--r--crates/tinywasm/Cargo.toml7
-rw-r--r--crates/tinywasm/src/lib.rs3
-rw-r--r--examples/rust/Cargo.toml3
15 files changed, 262 insertions, 85 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 79fb6b0..b58768f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added support for the WebAssembly function-references proposal
- Added `WasmValue::ty` and `WasmValue::matches_type`
+- Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules.
### Changed
diff --git a/README.md b/README.md
index 77ade90..6ded672 100644
--- a/README.md
+++ b/README.md
@@ -44,10 +44,11 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin
- **`std`:** Enables `std` and parsing from files and streams. Enabled by default.
- **`log`:** Enables integration with the `log` crate. Enabled by default.
- **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default.
+- **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`.
- **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default.
- **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default.
- **`debug`:** Derives `Debug` for runtime types. Enabled by default.
-- **`parallel-parser`:** Parallelizes function parsing and validation when `std` is enabled. Enabled by default.
+- **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default.
- **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`).
- **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally.
@@ -65,7 +66,7 @@ TinyWasm also has its own internal bytecode format, `twasm`. WebAssembly modules
## Safety
-TinyWasm only uses safe Rust by default. The optional `simd-x86` feature enables x86-specific SIMD intrinsics and uses `unsafe` internally. WebAssembly input is validated by default and runs inside a sandbox: untrusted Wasm should not be able to access host memory, escape the sandbox, or cause undefined behavior in the runtime. Validation should only be disabled for trusted input.
+TinyWasm only uses safe Rust by default. The optional `simd-x86` feature enables x86-specific SIMD intrinsics and uses `unsafe` internally. WebAssembly input is validated by default through the `validate` feature. Disabling validation should not let Wasm access host memory or escape the sandbox, but malformed input may panic or otherwise crash the process, so only disable it for trusted input.
The internal `twasm` bytecode format is not currently validated as an untrusted input format. Malformed `twasm` may panic, but should not compromise memory safety or allow sandbox escape. Only run trusted `twasm` bytecode, or generate it through TinyWasm from Wasm input.
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index 7dbd4d2..17b56e6 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -37,6 +37,7 @@ tinywasm = { workspace = true, features = [
"parallel-parser",
"parser",
"std",
+ "validate",
] }
wast = { workspace = true, optional = true }
wat = { workspace = true, optional = true }
diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml
index 3e71403..561ac45 100644
--- a/crates/parser/Cargo.toml
+++ b/crates/parser/Cargo.toml
@@ -13,10 +13,11 @@ categories.workspace = true
[dependencies]
log = { workspace = true, optional = true }
tinywasm-types = { workspace = true }
-wasmparser = { workspace = true, features = ["features", "simd", "validate"] }
+wasmparser = { workspace = true, features = ["simd"] }
[features]
-default = ["log", "parallel", "std"]
+default = ["log", "parallel", "std", "validate"]
log = ["dep:log"]
parallel = ["std"]
std = ["tinywasm-types/std", "wasmparser/std"]
+validate = ["wasmparser/features", "wasmparser/validate"]
diff --git a/crates/parser/README.md b/crates/parser/README.md
index 91145f1..05c2af2 100644
--- a/crates/parser/README.md
+++ b/crates/parser/README.md
@@ -6,7 +6,8 @@ This crate provides the parser and lowering pipeline that converts WebAssembly b
- `std`: Enables the use of `std` and `std::io` for parsing from files and streams.
- `log`: Enables logging of the parsing process using the `log` crate.
-- `parallel`: Enables multithreaded parsing and validation when `std` is available.
+- `parallel`: Enables multithreaded function parsing. Requires `std`.
+- `validate`: Enables `wasmparser` validation. Enabled by default and configurable through `ParserOptions`.
## Usage
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index db8d2aa..600976a 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -1,10 +1,10 @@
-use crate::{Result, module::FunctionCode, visit::process_operators_and_validate};
+use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources};
+#[cfg(feature = "validate")]
+use crate::visit::process_operators_and_validate;
+use crate::{Result, module::FunctionCode, visit::process_operators};
use alloc::{boxed::Box, format, string::ToString, vec::Vec};
use tinywasm_types::*;
-use wasmparser::{
- CompositeInnerType, FuncValidator, FuncValidatorAllocations, OperatorsReader, OperatorsReaderAllocations,
- ValidatorResources,
-};
+use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations};
pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> {
let kind = match element.kind {
@@ -116,28 +116,48 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex
Ok(Export { index: export.index, name: Box::from(export.name), kind })
}
+fn extend_local_types(
+ local_types: &mut Vec<crate::visit::OperandSize>,
+ count: u32,
+ ty: wasmparser::ValType,
+) -> Result<()> {
+ let size = crate::visit::OperandSize::from(ty);
+ let count =
+ usize::try_from(count).map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?;
+ local_types.reserve(count);
+ local_types.extend(core::iter::repeat_n(size, count));
+ Ok(())
+}
+
pub(crate) fn convert_module_code(
func: wasmparser::FunctionBody<'_>,
- mut validator: Option<FuncValidator<ValidatorResources>>,
+ validator: Option<FuncValidator<ValidatorResources>>,
reader_allocs: OperatorsReaderAllocations,
metadata: &crate::visit::ModuleMetadata,
ty_idx: u32,
) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
let locals_reader = func.get_locals_reader()?;
- let pos = locals_reader.original_position();
+ #[cfg(feature = "validate")]
+ let locals_position = locals_reader.original_position();
let signature = metadata.signature(ty_idx)?.clone();
let mut local_types = signature.params.clone();
- for (i, local) in locals_reader.into_iter().enumerate() {
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+
+ #[cfg(feature = "validate")]
+ for (local_index, local) in locals_reader.into_iter().enumerate() {
let local = local?;
if let Some(validator) = validator.as_mut() {
- validator.define_locals(pos + i, local.0, local.1)?;
+ validator.define_locals(locals_position + local_index, local.0, local.1)?;
}
- let size = crate::visit::OperandSize::from(local.1);
- let count = usize::try_from(local.0)
- .map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?;
- local_types.reserve(count);
- local_types.extend(core::iter::repeat_n(size, count));
+ extend_local_types(&mut local_types, local.0, local.1)?;
+ }
+
+ #[cfg(not(feature = "validate"))]
+ for local in locals_reader {
+ let local = local?;
+ extend_local_types(&mut local_types, local.0, local.1)?;
}
// maps a local's address to the index in the type's locals array
@@ -154,8 +174,33 @@ pub(crate) fn convert_module_code(
*count = count.checked_add(1).ok_or_else(|| crate::ParseError::Other(error.into()))?;
}
- let (body, data, validator_allocs, reader_allocs) =
- process_operators_and_validate(validator, func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?;
+ #[cfg(feature = "validate")]
+ let (body, data, validator_allocs, reader_allocs) = match validator {
+ Some(validator) => {
+ let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate(
+ validator,
+ func,
+ local_types,
+ local_addr_map,
+ metadata,
+ ty_idx,
+ reader_allocs,
+ )?;
+ (body, data, Some(validator_allocs), reader_allocs)
+ }
+ None => {
+ let (body, data, reader_allocs) =
+ process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?;
+ (body, data, None, reader_allocs)
+ }
+ };
+ #[cfg(not(feature = "validate"))]
+ let (body, data, validator_allocs, reader_allocs) = {
+ let _ = validator;
+ let (body, data, reader_allocs) =
+ process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?;
+ (body, data, None, reader_allocs)
+ };
Ok((
FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false },
validator_allocs,
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index aa5e0b0..6efc112 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -34,6 +34,7 @@ mod error;
mod macros;
mod module;
mod optimize;
+mod validation;
mod visit;
#[cfg(parallel_parser)]
@@ -41,7 +42,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,7 +53,10 @@ 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.
@@ -73,7 +80,7 @@ pub struct ParserOptions {
impl Default for ParserOptions {
fn default() -> Self {
Self {
- validation: true,
+ validation: cfg!(feature = "validate"),
optimize_local_memory_allocation: true,
optimize_rewrite: true,
#[cfg(parallel_parser)]
@@ -85,9 +92,12 @@ impl Default for ParserOptions {
impl ParserOptions {
/// 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
}
@@ -157,27 +167,35 @@ 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::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;
+ 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")]
@@ -194,7 +212,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) {
@@ -228,7 +246,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);
diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs
index 723f691..4ce23bb 100644
--- a/crates/parser/src/macros.rs
+++ b/crates/parser/src/macros.rs
@@ -1,26 +1,24 @@
pub(crate) mod visit {
+ #[cfg(feature = "validate")]
macro_rules! validate_then_visit {
($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {$(
fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output {
- if let Some(validator) = self.validator.as_mut() {
- if let Err(e) = validator.visitor(self.position).$visit($($($arg.clone()),*)?) {
- core::hint::cold_path();
- return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
- }
+ if let Err(e) = self.validator.visitor(self.position).$visit($($($arg.clone()),*)?) {
+ core::hint::cold_path();
+ return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
}
self.builder.$visit($($($arg),*)?)
}
)*};
}
+ #[cfg(feature = "validate")]
macro_rules! validate_then_visit_simd {
($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {$(
fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output {
- if let Some(validator) = self.validator.as_mut() {
- if let Err(e) = validator.simd_visitor(self.position).$visit($($($arg.clone()),*)?) {
- core::hint::cold_path();
- return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
- }
+ if let Err(e) = self.validator.simd_visitor(self.position).$visit($($($arg.clone()),*)?) {
+ core::hint::cold_path();
+ return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
}
self.builder.$visit($($($arg),*)?)
}
@@ -138,7 +136,9 @@ pub(crate) mod visit {
};
}
- pub(crate) use {impl_visit_operator, lowering_ops, validate_then_visit, validate_then_visit_simd};
+ pub(crate) use {impl_visit_operator, lowering_ops};
+ #[cfg(feature = "validate")]
+ pub(crate) use {validate_then_visit, validate_then_visit_simd};
}
pub(crate) mod optimize {
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index c2199f3..a269141 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -1,10 +1,13 @@
use crate::log::debug;
+#[cfg(parallel_parser)]
+use crate::validation::{FuncToValidate, ValidatorResources};
+use crate::validation::{FuncValidatorAllocations, Validator};
use crate::{ParseError, ParserOptions, Result, conversion::*, optimize};
use alloc::{boxed::Box, format, string::ToString, sync::Arc, vec::Vec};
use core::marker::PhantomData;
use core::ops::Range;
use tinywasm_types::*;
-use wasmparser::{FuncValidatorAllocations, OperatorsReaderAllocations, Payload, Validator};
+use wasmparser::{OperatorsReaderAllocations, Payload};
pub(crate) struct FunctionCode {
pub instructions: Vec<Instruction>,
@@ -79,11 +82,11 @@ impl<'a> ModuleReader<'a> {
self.translation_metadata.as_deref().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 +97,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,13 +110,17 @@ 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())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.type_section(&reader)?;
}
@@ -118,6 +128,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::GlobalSection(reader) => {
check_section("global", !self.globals.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.global_section(&reader)?;
}
@@ -125,6 +136,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::TableSection(reader) => {
check_section("table", !self.tables.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.table_section(&reader)?;
}
@@ -149,6 +161,7 @@ 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)?;
}
@@ -157,6 +170,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::ElementSection(reader) => {
debug!("Found element section");
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.element_section(&reader)?;
}
@@ -165,6 +179,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::DataSection(reader) => {
check_section("data", !self.data.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.data_section(&reader)?;
}
@@ -175,12 +190,16 @@ impl<'a> ModuleReader<'a> {
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)?;
}
@@ -200,6 +219,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)?;
}
@@ -217,6 +237,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 +249,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) => {
@@ -262,9 +286,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,10 +321,16 @@ 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
@@ -332,7 +365,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);
}
@@ -345,15 +381,23 @@ impl<'a> ModuleReader<'a> {
count: u32,
body_offset: usize,
section_bytes: Arc<[u8]>,
- mut validator: Option<&mut Validator>,
+ 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()?;
+ #[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(),
@@ -378,7 +422,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
diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs
index 88d1035..e0e3858 100644
--- a/crates/parser/src/parallel.rs
+++ b/crates/parser/src/parallel.rs
@@ -1,10 +1,11 @@
use crate::module::{FunctionCode, optimize_function_code};
+use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources};
use crate::{ParseError, ParserOptions, Result, conversion};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::ops::Range;
use tinywasm_types::ValueCounts;
-use wasmparser::{FuncValidatorAllocations, OperatorsReaderAllocations, ValidatorResources};
+use wasmparser::OperatorsReaderAllocations;
pub(crate) enum FunctionBodyInput<'a> {
Borrowed(wasmparser::FunctionBody<'a>),
@@ -22,7 +23,7 @@ pub(crate) struct OwnedFunctionBody {
pub(crate) struct PendingFunction<'a> {
pub ordinal: usize,
pub results: ValueCounts,
- pub func_to_validate: Option<wasmparser::FuncToValidate<ValidatorResources>>,
+ pub func_to_validate: Option<FuncToValidate<ValidatorResources>>,
pub ty_idx: u32,
pub body: FunctionBodyInput<'a>,
}
@@ -64,7 +65,13 @@ fn process_function_job(
validator_allocs: Option<FuncValidatorAllocations>,
reader_allocs: OperatorsReaderAllocations,
) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
+ #[cfg(feature = "validate")]
let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default()));
+ #[cfg(not(feature = "validate"))]
+ let validator = {
+ let _ = (job.func_to_validate, validator_allocs);
+ None
+ };
let (code, validator_allocs, reader_allocs) = match job.body {
FunctionBodyInput::Borrowed(func) => {
conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)?
diff --git a/crates/parser/src/validation.rs b/crates/parser/src/validation.rs
new file mode 100644
index 0000000..b2bb084
--- /dev/null
+++ b/crates/parser/src/validation.rs
@@ -0,0 +1,15 @@
+#[cfg(all(feature = "validate", parallel_parser))]
+pub(crate) use wasmparser::FuncToValidate;
+#[cfg(feature = "validate")]
+pub(crate) use wasmparser::{FuncValidator, FuncValidatorAllocations, Validator, ValidatorResources};
+
+#[cfg(all(not(feature = "validate"), parallel_parser))]
+pub(crate) type FuncToValidate<T> = core::marker::PhantomData<T>;
+#[cfg(not(feature = "validate"))]
+pub(crate) type FuncValidator<T> = core::marker::PhantomData<T>;
+#[cfg(not(feature = "validate"))]
+pub(crate) type FuncValidatorAllocations = ();
+#[cfg(not(feature = "validate"))]
+pub(crate) type Validator = ();
+#[cfg(not(feature = "validate"))]
+pub(crate) type ValidatorResources = ();
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index d0e970b..67651f9 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -5,10 +5,10 @@ use tinywasm_types::{
FuncType, Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, TableDefinition, ValueCounts,
WasmFunctionData, WasmType,
};
-use wasmparser::{
- FuncValidator, FuncValidatorAllocations, FunctionBody, OperatorsReader, OperatorsReaderAllocations,
- ValidatorResources, VisitOperator, VisitSimdOperator,
-};
+use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator};
+
+#[cfg(feature = "validate")]
+use wasmparser::{FuncValidator, FuncValidatorAllocations, ValidatorResources, VisitOperator};
#[derive(Debug, Clone, Copy)]
enum BlockKind {
@@ -142,8 +142,9 @@ impl<'a> FunctionBuilder<'a> {
}
}
+#[cfg(feature = "validate")]
struct ValidateThenVisit<'a, 'm> {
- validator: Option<&'a mut FuncValidator<ValidatorResources>>,
+ validator: &'a mut FuncValidator<ValidatorResources>,
builder: &'a mut FunctionBuilder<'m>,
position: usize,
}
@@ -220,6 +221,7 @@ impl ModuleMetadata {
}
}
+#[cfg(feature = "validate")]
impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> {
type Output = Result<()>;
@@ -230,19 +232,19 @@ impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> {
}
}
+#[cfg(feature = "validate")]
impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> {
wasmparser::for_each_visit_simd_operator!(validate_then_visit_simd);
}
-pub(crate) fn process_operators_and_validate(
- mut validator: Option<FuncValidator<ValidatorResources>>,
+pub(crate) fn process_operators(
body: FunctionBody<'_>,
local_types: Vec<OperandSize>,
local_addr_map: Vec<u16>,
metadata: &ModuleMetadata,
ty_idx: u32,
allocs: OperatorsReaderAllocations,
-) -> Result<(Vec<Instruction>, WasmFunctionData, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
+) -> Result<(Vec<Instruction>, WasmFunctionData, OperatorsReaderAllocations)> {
let body_size = body.as_bytes().len();
let reader = body.get_binary_reader_for_operators()?;
let mut reader = OperatorsReader::new_with_allocs(reader, allocs);
@@ -252,7 +254,7 @@ pub(crate) fn process_operators_and_validate(
while !reader.eof() {
let position = reader.original_position();
let res = reader
- .visit_operator(&mut ValidateThenVisit { validator: validator.as_mut(), builder: &mut builder, position })
+ .visit_operator(&mut builder)
.map_err(|e| crate::ParseError::ParseError { message: e.to_string(), offset: position });
if let Err(e) = res.flatten() {
@@ -262,13 +264,47 @@ pub(crate) fn process_operators_and_validate(
}
reader.finish()?;
+ let data = WasmFunctionData {
+ v128_constants: builder.data.v128_constants.into_boxed_slice(),
+ branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(),
+ };
+ Ok((builder.instructions, data, reader.into_allocations()))
+}
- let validator_allocations = validator.map(FuncValidator::into_allocations);
+#[cfg(feature = "validate")]
+pub(crate) fn process_operators_and_validate(
+ mut validator: FuncValidator<ValidatorResources>,
+ body: FunctionBody<'_>,
+ local_types: Vec<OperandSize>,
+ local_addr_map: Vec<u16>,
+ metadata: &ModuleMetadata,
+ ty_idx: u32,
+ allocs: OperatorsReaderAllocations,
+) -> Result<(Vec<Instruction>, WasmFunctionData, FuncValidatorAllocations, OperatorsReaderAllocations)> {
+ let body_size = body.as_bytes().len();
+ let reader = body.get_binary_reader_for_operators()?;
+ let mut reader = OperatorsReader::new_with_allocs(reader, allocs);
+ let signature = metadata.signature(ty_idx)?.clone();
+ let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size);
+
+ while !reader.eof() {
+ let position = reader.original_position();
+ let res = reader
+ .visit_operator(&mut ValidateThenVisit { validator: &mut validator, builder: &mut builder, position })
+ .map_err(|e| crate::ParseError::ParseError { message: e.to_string(), offset: position });
+
+ if let Err(e) = res.flatten() {
+ core::hint::cold_path();
+ return Err(e);
+ }
+ }
+
+ reader.finish()?;
let data = WasmFunctionData {
v128_constants: builder.data.v128_constants.into_boxed_slice(),
branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(),
};
- Ok((builder.instructions, data, validator_allocations, reader.into_allocations()))
+ Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations()))
}
impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml
index aecebeb..d1c387b 100644
--- a/crates/tinywasm/Cargo.toml
+++ b/crates/tinywasm/Cargo.toml
@@ -13,6 +13,7 @@ categories.workspace = true
[package.metadata.docs.rs]
features = [
"std",
+ "validate",
"parser",
"archive",
"log",
@@ -160,7 +161,8 @@ default = [
"log",
"parallel-parser",
"parser",
- "std"
+ "std",
+ "validate"
]
log = ["dep:log", "tinywasm-parser?/log", "tinywasm-types/log"]
@@ -169,6 +171,9 @@ std = ["tinywasm-parser?/std", "tinywasm-types/std"]
# support for parsing WebAssembly
parser = ["dep:tinywasm-parser"]
+# validate WebAssembly while parsing
+validate = ["parser", "tinywasm-parser/validate"]
+
# parallelize function parsing/validation across threads (requires std)
parallel-parser = ["parser", "tinywasm-parser?/parallel"]
diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs
index 908f33b..1c2bcb4 100644
--- a/crates/tinywasm/src/lib.rs
+++ b/crates/tinywasm/src/lib.rs
@@ -64,10 +64,11 @@
//! - **`std`:** Enables `std` and parsing from files and streams. Enabled by default.
//! - **`log`:** Enables integration with the `log` crate. Enabled by default.
//! - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default.
+//! - **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`.
//! - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default.
//! - **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default.
//! - **`debug`:** Derives `Debug` for runtime types. Enabled by default.
-//! - **`parallel-parser`:** Parallelizes function parsing and validation when `std` is enabled. Enabled by default.
+//! - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default.
//! - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`).
//! - **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally.
//!
diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml
index efce27a..0ae646c 100644
--- a/examples/rust/Cargo.toml
+++ b/examples/rust/Cargo.toml
@@ -39,7 +39,8 @@ argon2 = { version = "0.5" }
dlmalloc = { version = "0.2", features = ["global"] }
tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [
"archive",
- "parser"
+ "parser",
+ "validate"
] }
[features]