Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Remove more module linking support from Wizer (#11855)

Alex Crichton41a695f27cb1
diff --git a/crates/wizer/src/info.rs b/crates/wizer/src/info.rs
index c2b4ea1b05..05df36a9da 100644
--- a/crates/wizer/src/info.rs
+++ b/crates/wizer/src/info.rs
@@ -1,65 +1,5 @@
use std::convert::TryFrom;
use std::ops::Range;
-use types_interner::{EntityType, TypeId, TypesInterner};
-use wasm_encoder::SectionId;
-
-pub mod types_interner;
-
-/// A collection of info about modules within a module linking bundle.
-pub struct ModuleContext<'a> {
- arena: Vec<ModuleInfo<'a>>,
- types: TypesInterner,
-}
-
-impl<'a> ModuleContext<'a> {
- /// Construct a new `ModuleContext`, pre-populated with an empty root
- /// module.
- pub(crate) fn new() -> Self {
- Self {
- arena: vec![ModuleInfo::Defined(DefinedModuleInfo::default())],
- types: TypesInterner::default(),
- }
- }
-
- /// Get the root module.
- pub(crate) fn root(&self) -> Module {
- Module { id: 0 }
- }
-
- /// Get the interned types set for this module context.
- pub(crate) fn types(&self) -> &TypesInterner {
- &self.types
- }
-
- /// Get a shared reference to the `DefinedModuleInfo` for this module,
- /// following through aliases.
- fn defined(&self, module: Module) -> &DefinedModuleInfo<'a> {
- match &self.arena[module.id] {
- ModuleInfo::Defined(d) => return d,
- }
- }
-
- /// Get an exclusive reference to the `DefinedModuleInfo` for this module.
- ///
- /// Does not resolve through aliases, because you shouldn't ever mutate
- /// aliased modules.
- fn defined_mut(&mut self, module: Module) -> &mut DefinedModuleInfo<'a> {
- match &mut self.arena[module.id] {
- ModuleInfo::Defined(d) => d,
- }
- }
-
- pub(crate) fn has_wasi_initialize(&self, module: Module) -> bool {
- self.defined(module)
- .exports
- .iter()
- .any(|e| e.name == "_initialize")
- }
-}
-
-enum ModuleInfo<'a> {
- Defined(DefinedModuleInfo<'a>),
-}
/// Info that we keep track of on a per module-within-a-module-linking-bundle
/// basis.
@@ -67,16 +7,10 @@ enum ModuleInfo<'a> {
/// These are created during during our `parse` pass and then used throughout
/// our later passes.
#[derive(Default)]
-struct DefinedModuleInfo<'a> {
+pub struct ModuleContext<'a> {
/// The raw sections from the original Wasm input.
raw_sections: Vec<wasm_encoder::RawSection<'a>>,
- /// Types available in this module.
- ///
- /// We keep track of these for determining how many things we need to
- /// re-export for new instantiations and for inner module's aliases.
- types: Vec<TypeId>,
-
/// Imports made by this module.
imports: Vec<wasmparser::Import<'a>>,
@@ -100,8 +34,8 @@ struct DefinedModuleInfo<'a> {
exports: Vec<wasmparser::Export<'a>>,
/// Maps from function index to the function's type index for all functions
- /// defined, imported, and aliased in this module.
- functions: Vec<TypeId>,
+ /// defined and imported in this module.
+ functions: Vec<u32>,
/// Maps from table index to the table's type for all tables defined,
/// imported, and aliased in this module.
@@ -118,110 +52,70 @@ struct DefinedModuleInfo<'a> {
defined_memories_index: Option<u32>,
}
-/// A module inside a module linking bundle.
-///
-/// This is a small, copy-able type that essentially just indexes into a
-/// `ModuleContext`.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub(crate) struct Module {
- /// This module's id, aka its pre-order traversal index, aka its index in
- /// `Modules::arena`.
- id: usize,
-}
-
-impl Module {
- /// Translate the given `wasmparser` entity type into its interned
- /// representation using this module's types space.
- pub fn entity_type(self, cx: &ModuleContext<'_>, ty: wasmparser::TypeRef) -> EntityType {
- cx.types().entity_type(ty, &cx.defined(self).types)
- }
-
+impl<'a> ModuleContext<'a> {
/// Add a new raw section to this module info during parsing.
- pub fn add_raw_section<'a>(
- self,
- cx: &mut ModuleContext<'a>,
- id: SectionId,
- range: Range<usize>,
- full_wasm: &'a [u8],
- ) {
- cx.defined_mut(self)
- .raw_sections
- .push(wasm_encoder::RawSection {
- id: id as u8,
- data: &full_wasm[range.start..range.end],
- })
- }
-
- /// Push a new type into this module's types space.
- pub fn push_type<'a>(self, cx: &mut ModuleContext<'a>, ty: wasmparser::CompositeType) {
- let types_space = match &cx.arena[self.id] {
- ModuleInfo::Defined(d) => &d.types,
- };
- let ty = cx.types.insert_wasmparser(ty, types_space);
- cx.defined_mut(self).types.push(ty);
+ pub(crate) fn add_raw_section(&mut self, id: u8, range: Range<usize>, full_wasm: &'a [u8]) {
+ self.raw_sections.push(wasm_encoder::RawSection {
+ id,
+ data: &full_wasm[range.start..range.end],
+ })
}
/// Push a new imported memory into this module's memory index space.
- pub fn push_imported_memory(self, cx: &mut ModuleContext, memory_type: wasmparser::MemoryType) {
- let info = cx.defined_mut(self);
- assert!(info.defined_memories_index.is_none());
- info.memories.push(memory_type);
+ pub(crate) fn push_imported_memory(&mut self, memory_type: wasmparser::MemoryType) {
+ assert!(self.defined_memories_index.is_none());
+ self.memories.push(memory_type);
}
/// Push a new defined memory into this module's memory index space.
- pub fn push_defined_memory(self, cx: &mut ModuleContext, memory_type: wasmparser::MemoryType) {
- let info = cx.defined_mut(self);
- if info.defined_memories_index.is_none() {
- info.defined_memories_index = Some(u32::try_from(info.memories.len()).unwrap());
+ pub(crate) fn push_defined_memory(&mut self, memory_type: wasmparser::MemoryType) {
+ if self.defined_memories_index.is_none() {
+ self.defined_memories_index = Some(u32::try_from(self.memories.len()).unwrap());
}
- info.memories.push(memory_type);
+ self.memories.push(memory_type);
}
/// Push a new imported global into this module's global index space.
- pub fn push_imported_global(self, cx: &mut ModuleContext, global_type: wasmparser::GlobalType) {
- let info = cx.defined_mut(self);
- assert!(info.defined_globals_index.is_none());
- info.globals.push(global_type);
+ pub(crate) fn push_imported_global(&mut self, global_type: wasmparser::GlobalType) {
+ assert!(self.defined_globals_index.is_none());
+ self.globals.push(global_type);
}
/// Push a new defined global into this module's global index space.
- pub fn push_defined_global(self, cx: &mut ModuleContext, global_type: wasmparser::GlobalType) {
- let info = cx.defined_mut(self);
- if info.defined_globals_index.is_none() {
- info.defined_globals_index = Some(u32::try_from(info.globals.len()).unwrap());
+ pub(crate) fn push_defined_global(&mut self, global_type: wasmparser::GlobalType) {
+ if self.defined_globals_index.is_none() {
+ self.defined_globals_index = Some(u32::try_from(self.globals.len()).unwrap());
}
- info.globals.push(global_type);
+ self.globals.push(global_type);
}
/// Push a new function into this module's function index space.
- pub fn push_function(self, cx: &mut ModuleContext, func_type: TypeId) {
- assert!(cx.types.get(func_type).is_func());
- cx.defined_mut(self).functions.push(func_type);
+ pub(crate) fn push_function(&mut self, func_type: u32) {
+ self.functions.push(func_type);
}
/// Push a new table into this module's table index space.
- pub fn push_table(self, cx: &mut ModuleContext, table_type: wasmparser::TableType) {
- cx.defined_mut(self).tables.push(table_type);
+ pub(crate) fn push_table(&mut self, table_type: wasmparser::TableType) {
+ self.tables.push(table_type);
}
/// Push a new import into this module.
- pub fn push_import<'a>(self, cx: &mut ModuleContext<'a>, import: wasmparser::Import<'a>) {
- cx.defined_mut(self).imports.push(import);
+ pub(crate) fn push_import(&mut self, import: wasmparser::Import<'a>) {
+ self.imports.push(import);
// Add the import to the appropriate index space for our current module.
match import.ty {
wasmparser::TypeRef::Memory(ty) => {
- self.push_imported_memory(cx, ty);
+ self.push_imported_memory(ty);
}
wasmparser::TypeRef::Global(ty) => {
- self.push_imported_global(cx, ty);
+ self.push_imported_global(ty);
}
wasmparser::TypeRef::Func(ty_idx) => {
- let ty = self.type_id_at(cx, ty_idx);
- self.push_function(cx, ty);
+ self.push_function(ty_idx);
}
wasmparser::TypeRef::Table(ty) => {
- self.push_table(cx, ty);
+ self.push_table(ty);
}
wasmparser::TypeRef::Tag(_) => {
unreachable!("exceptions are unsupported; checked in validation")
@@ -230,81 +124,65 @@ impl Module {
}
/// Push an export into this module.
- pub fn push_export<'a>(self, cx: &mut ModuleContext<'a>, export: wasmparser::Export<'a>) {
- cx.defined_mut(self).exports.push(export);
- }
-
- /// Is this the root of the module linking bundle?
- pub fn is_root(self) -> bool {
- self.id == 0
+ pub(crate) fn push_export(&mut self, export: wasmparser::Export<'a>) {
+ self.exports.push(export);
}
/// The number of defined memories in this module.
- pub fn defined_memories_len(self, cx: &ModuleContext) -> usize {
- let info = cx.defined(self);
- info.defined_memories_index.map_or(0, |n| {
+ pub(crate) fn defined_memories_len(&self) -> usize {
+ self.defined_memories_index.map_or(0, |n| {
let n = usize::try_from(n).unwrap();
- assert!(info.memories.len() > n);
- info.memories.len() - n
+ assert!(self.memories.len() > n);
+ self.memories.len() - n
})
}
/// Iterate over the defined memories in this module.
- pub fn defined_memories<'b>(
- self,
- cx: &'b ModuleContext<'_>,
- ) -> impl Iterator<Item = (u32, wasmparser::MemoryType)> + 'b {
- let info = cx.defined(self);
- info.memories
+ pub(crate) fn defined_memories(
+ &self,
+ ) -> impl Iterator<Item = (u32, wasmparser::MemoryType)> + '_ {
+ self.memories
.iter()
.copied()
.enumerate()
.skip(
- info.defined_memories_index
- .map_or(info.memories.len(), |i| usize::try_from(i).unwrap()),
+ self.defined_memories_index
+ .map_or(self.memories.len(), |i| usize::try_from(i).unwrap()),
)
.map(|(i, m)| (u32::try_from(i).unwrap(), m))
}
/// Iterate over the defined globals in this module.
- pub fn defined_globals<'b>(
- self,
- cx: &'b ModuleContext<'_>,
- ) -> impl Iterator<Item = (u32, wasmparser::GlobalType)> + 'b {
- let info = cx.defined(self);
- info.globals
+ pub(crate) fn defined_globals(
+ &self,
+ ) -> impl Iterator<Item = (u32, wasmparser::GlobalType)> + '_ {
+ self.globals
.iter()
.copied()
.enumerate()
.skip(
- info.defined_globals_index
- .map_or(info.globals.len(), |i| usize::try_from(i).unwrap()),
+ self.defined_globals_index
+ .map_or(self.globals.len(), |i| usize::try_from(i).unwrap()),
)
.map(|(i, g)| (u32::try_from(i).unwrap(), g))
}
/// Get a slice of this module's original raw sections.
- pub fn raw_sections<'a, 'b>(
- self,
- cx: &'b ModuleContext<'a>,
- ) -> &'b [wasm_encoder::RawSection<'a>] {
- &cx.defined(self).raw_sections
+ pub(crate) fn raw_sections(&self) -> &[wasm_encoder::RawSection<'a>] {
+ &self.raw_sections
}
- /// Get a slice of this module's exports.
- pub fn exports<'a, 'b>(self, cx: &'b ModuleContext<'a>) -> &'b [wasmparser::Export<'a>] {
- &cx.defined(self).exports
+ /// Get a slice of this module's imports.
+ pub(crate) fn imports(&self) -> &[wasmparser::Import<'a>] {
+ &self.imports
}
- /// Get the full types index space for this module.
- pub fn types<'a, 'b>(self, cx: &'b ModuleContext<'a>) -> &'b [TypeId] {
- &cx.defined(self).types
+ /// Get a slice of this module's exports.
+ pub(crate) fn exports(&self) -> &[wasmparser::Export<'a>] {
+ &self.exports
}
- /// Get the type at the given index.
- ///
- /// Panics if the types index space does not contain the given index.
- pub fn type_id_at(self, cx: &ModuleContext<'_>, type_index: u32) -> TypeId {
- cx.defined(self).types[usize::try_from(type_index).unwrap()]
+ pub(crate) fn has_wasi_initialize(&self) -> bool {
+ self.exports.iter().any(|e| e.name == "_initialize")
}
}
diff --git a/crates/wizer/src/info/types_interner.rs b/crates/wizer/src/info/types_interner.rs
deleted file mode 100644
index 748a835bdd..0000000000
--- a/crates/wizer/src/info/types_interner.rs
+++ /dev/null
@@ -1,107 +0,0 @@
-use std::{collections::HashMap, convert::TryFrom, rc::Rc};
-
-/// A de-duplicated set of type definitions.
-///
-/// We insert new entries via hash consing, to de-duplicate entries.
-///
-/// This is shared across all modules in a module linking bundle.
-///
-/// We assign and track a unique index for each type we insert. These end up
-/// being the indices of each type in the root Wasm module. All nested modules
-/// refer to these types, and pull them into their nested types index space, via
-/// outer type aliases.
-#[derive(Default)]
-pub struct TypesInterner {
- /// The interned types.
- types: Vec<Rc<Type>>,
-
- /// An map from a type to its index in `self.types`.
- type_to_index: HashMap<Rc<Type>, u32>,
-}
-
-/// An interned Wasm type definition.
-#[derive(PartialEq, Eq, Hash)]
-pub enum Type {
- Func(wasmparser::FuncType),
-}
-
-impl Type {
- pub fn is_func(&self) -> bool {
- matches!(self, Type::Func(_))
- }
-}
-
-/// An interned type for some kind of Wasm entity.
-#[derive(PartialEq, Eq, Hash)]
-pub enum EntityType {
- Function(TypeId),
- Table(wasmparser::TableType),
- Memory(wasmparser::MemoryType),
- Global(wasmparser::GlobalType),
-}
-
-/// An id of a type in a `TypesInterner` type set.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub struct TypeId {
- index: u32,
-}
-
-impl TypesInterner {
- /// Get a type by id.
- pub fn get(&self, id: TypeId) -> &Type {
- &*self.types[usize::try_from(id.index).unwrap()]
- }
-
- /// Intern a `wasmparser` type into this type set and get its id.
- ///
- /// The provided `types_space` must be a slice of the defining module's
- /// types index space.
- ///
- /// If the type has already been inserted and assigned an id before, then
- /// that entry and its id are reused.
- pub fn insert_wasmparser(
- &mut self,
- ty: wasmparser::CompositeType,
- _types_space: &[TypeId],
- ) -> TypeId {
- match ty.inner {
- wasmparser::CompositeInnerType::Func(func_ty) => self.insert(Type::Func(func_ty)),
- wasmparser::CompositeInnerType::Array(_) => todo!(),
- wasmparser::CompositeInnerType::Struct(_) => todo!(),
- wasmparser::CompositeInnerType::Cont(_) => todo!(),
- }
- }
-
- /// Insert a new type into this type set and get its id.
- ///
- /// If the type has already been inserted and assigned an id before, then
- /// that entry and its id are reused.
- pub fn insert(&mut self, ty: Type) -> TypeId {
- if let Some(index) = self.type_to_index.get(&ty).copied() {
- return TypeId { index };
- }
-
- let index = u32::try_from(self.types.len()).unwrap();
- let ty = Rc::new(ty);
- self.type_to_index.insert(ty.clone(), index);
- self.types.push(ty);
- TypeId { index }
- }
-
- /// Convert a `wasmparser::EntityType` into an interned
- /// `EntityType`.
- ///
- /// The provided `types_space` must be a slice of the defining module's
- /// types index space.
- pub fn entity_type(&self, ty: wasmparser::TypeRef, types_space: &[TypeId]) -> EntityType {
- match ty {
- wasmparser::TypeRef::Func(idx) => {
- EntityType::Function(types_space[usize::try_from(idx).unwrap()])
- }
- wasmparser::TypeRef::Table(ty) => EntityType::Table(ty),
- wasmparser::TypeRef::Memory(ty) => EntityType::Memory(ty),
- wasmparser::TypeRef::Global(ty) => EntityType::Global(ty),
- wasmparser::TypeRef::Tag(_) => unreachable!(),
- }
- }
-}
diff --git a/crates/wizer/src/instrument.rs b/crates/wizer/src/instrument.rs
index b63b14bf57..de6aab24de 100644
--- a/crates/wizer/src/instrument.rs
+++ b/crates/wizer/src/instrument.rs
@@ -58,13 +58,12 @@ use wasm_encoder::reencode::{Reencode, RoundtripReencoder};
/// export their memories and globals individually, that would disturb the
/// modules locally defined memoryies' and globals' indices, which would require
/// rewriting the code section, which would break debug info offsets.
-pub(crate) fn instrument(cx: &ModuleContext<'_>) -> Vec<u8> {
+pub(crate) fn instrument(module: &ModuleContext<'_>) -> Vec<u8> {
log::debug!("Instrumenting the input Wasm");
- let module = cx.root();
let mut encoder = wasm_encoder::Module::new();
- for section in module.raw_sections(cx) {
+ for section in module.raw_sections() {
match section.id {
// For the exports section, we need to transitively export internal
// state so that we can read the initialized state after we call the
@@ -73,7 +72,7 @@ pub(crate) fn instrument(cx: &ModuleContext<'_>) -> Vec<u8> {
let mut exports = wasm_encoder::ExportSection::new();
// First, copy over all the original exports.
- for export in module.exports(cx) {
+ for export in module.exports() {
RoundtripReencoder
.parse_export(&mut exports, *export)
.unwrap();
@@ -82,11 +81,11 @@ pub(crate) fn instrument(cx: &ModuleContext<'_>) -> Vec<u8> {
// Now export all of this module's defined globals, memories,
// and instantiations under well-known names so we can inspect
// them after initialization.
- for (i, (j, _)) in module.defined_globals(cx).enumerate() {
+ for (i, (j, _)) in module.defined_globals().enumerate() {
let name = format!("__wizer_global_{i}");
exports.export(&name, wasm_encoder::ExportKind::Global, j);
}
- for (i, (j, _)) in module.defined_memories(cx).enumerate() {
+ for (i, (j, _)) in module.defined_memories().enumerate() {
let name = format!("__wizer_memory_{i}");
exports.export(&name, wasm_encoder::ExportKind::Memory, j);
}
diff --git a/crates/wizer/src/lib.rs b/crates/wizer/src/lib.rs
index dd8733932e..3db74939db 100644
--- a/crates/wizer/src/lib.rs
+++ b/crates/wizer/src/lib.rs
@@ -9,7 +9,6 @@ mod instrument;
mod parse;
mod rewrite;
mod snapshot;
-mod stack_ext;
/// Re-export wasmtime so users can align with our version. This is
/// especially useful when providing a custom Linker.
@@ -205,6 +204,25 @@ impl Wizer {
self.wasm_validate(&wasm)?;
let cx = parse::parse(wasm)?;
+
+ // When wizening core modules directly some imports aren't supported,
+ // so check for those here.
+ for import in cx.imports() {
+ match import.ty {
+ wasmparser::TypeRef::Global(_) => {
+ anyhow::bail!("imported globals are not supported")
+ }
+ wasmparser::TypeRef::Table(_) => {
+ anyhow::bail!("imported tables are not supported")
+ }
+ wasmparser::TypeRef::Memory(_) => {
+ anyhow::bail!("imported memories are not supported")
+ }
+ wasmparser::TypeRef::Func(_) => {}
+ wasmparser::TypeRef::Tag(_) => {}
+ }
+ }
+
let instrumented_wasm = instrument::instrument(&cx);
if cfg!(debug_assertions) {
@@ -256,6 +274,10 @@ impl Wizer {
fn wasm_validate(&self, wasm: &[u8]) -> anyhow::Result<()> {
log::debug!("Validating input Wasm");
+ wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
+ .validate_all(wasm)
+ .context("wasm validation failed")?;
+
// Reject bulk memory stuff that manipulates state we don't
// snapshot. See the comment inside `wasm_features`.
let mut wasm = wasm;
diff --git a/crates/wizer/src/parse.rs b/crates/wizer/src/parse.rs
index 666629cd61..dfad0c2bb5 100644
--- a/crates/wizer/src/parse.rs
+++ b/crates/wizer/src/parse.rs
@@ -1,164 +1,40 @@
-use crate::info::{
- Module, ModuleContext,
- types_interner::{EntityType, TypeId},
-};
-use crate::stack_ext::StackExt;
-use anyhow::{Context, Result};
-use std::convert::TryFrom;
-use wasm_encoder::SectionId;
-
-struct StackEntry {
- parser: wasmparser::Parser,
- module: Module,
-}
+use crate::info::ModuleContext;
+use anyhow::Context;
+use wasmparser::Parser;
/// Parse the given Wasm bytes into a `ModuleInfo` tree.
pub(crate) fn parse<'a>(full_wasm: &'a [u8]) -> anyhow::Result<ModuleContext<'a>> {
log::debug!("Parsing the input Wasm");
- let mut cx = ModuleContext::new();
-
- // The wasm we are currently parsing. This is advanced as the parser
- // consumes input.
- let mut wasm = full_wasm;
-
- let mut stack = vec![StackEntry {
- parser: wasmparser::Parser::new(0),
- module: cx.root(),
- }];
-
- loop {
- let (payload, consumed) = match stack
- .top_mut()
- .parser
- .parse(wasm, true)
- .context("failed to parse Wasm")?
- {
- wasmparser::Chunk::NeedMoreData(_) => unreachable!(),
- wasmparser::Chunk::Parsed { payload, consumed } => (payload, consumed),
- };
- wasm = &wasm[consumed..];
+ let mut module = ModuleContext::default();
+ for payload in Parser::new(0).parse_all(full_wasm) {
use wasmparser::Payload::*;
- match payload {
- Version { .. } => {}
- TypeSection(types) => type_section(&mut cx, &mut stack, full_wasm, types)?,
- ImportSection(imports) => import_section(&mut cx, &mut stack, full_wasm, imports)?,
- FunctionSection(funcs) => function_section(&mut cx, &mut stack, full_wasm, funcs)?,
- TableSection(tables) => table_section(&mut cx, &mut stack, full_wasm, tables)?,
- MemorySection(mems) => memory_section(&mut cx, &mut stack, full_wasm, mems)?,
- GlobalSection(globals) => global_section(&mut cx, &mut stack, full_wasm, globals)?,
- ExportSection(exports) => export_section(&mut cx, &mut stack, full_wasm, exports)?,
- StartSection { func: _, range } => {
- stack
- .top_mut()
- .module
- .add_raw_section(&mut cx, SectionId::Start, range, full_wasm)
- }
- ElementSection(elems) => stack.top_mut().module.add_raw_section(
- &mut cx,
- SectionId::Element,
- elems.range(),
- full_wasm,
- ),
- DataCountSection { range, .. } => stack.top_mut().module.add_raw_section(
- &mut cx,
- SectionId::DataCount,
- range,
- full_wasm,
- ),
- DataSection(data) => stack.top_mut().module.add_raw_section(
- &mut cx,
- SectionId::Data,
- data.range(),
- full_wasm,
- ),
- CustomSection(c) => stack.top_mut().module.add_raw_section(
- &mut cx,
- SectionId::Custom,
- c.range(),
- full_wasm,
- ),
- CodeSectionStart {
- range,
- count: _,
- size,
- } => {
- wasm = &wasm[usize::try_from(size).unwrap()..];
- let entry = stack.top_mut();
- entry.parser.skip_section();
- entry
- .module
- .add_raw_section(&mut cx, SectionId::Code, range, full_wasm)
- }
- CodeSectionEntry(_) => unreachable!(),
- UnknownSection { .. } => anyhow::bail!("unknown section"),
- TagSection(_) => anyhow::bail!("exceptions are not supported yet"),
- End(_) => {
- let entry = stack.pop().unwrap();
- // If we finished parsing the root Wasm module, then we're done.
- assert!(entry.module.is_root());
- assert!(stack.is_empty());
- return Ok(cx);
- }
- ComponentTypeSection(_)
- | ComponentImportSection(_)
- | ComponentExportSection(_)
- | ComponentStartSection { .. }
- | ComponentAliasSection(_)
- | CoreTypeSection(_)
- | InstanceSection(_)
- | ComponentInstanceSection(_)
- | ComponentCanonicalSection(_)
- | ModuleSection { .. }
- | ComponentSection { .. } => {
- unreachable!()
- }
- _ => anyhow::bail!("unsupported wasmparser payload"),
- }
- }
-}
+ let payload = payload.context("failed to parse Wasm")?;
-fn type_section<'a>(
- cx: &mut ModuleContext<'a>,
- stack: &mut Vec<StackEntry>,
- full_wasm: &'a [u8],
- types: wasmparser::TypeSectionReader<'a>,
-) -> anyhow::Result<()> {
- let module = stack.top().module;
- module.add_raw_section(cx, SectionId::Type, types.range(), full_wasm);
+ if let Some((id, range)) = payload.as_section() {
+ module.add_raw_section(id, range, full_wasm);
+ }
- // Parse out types, as we will need them later when processing
- // instance imports.
- for group in types {
- for ty in group?.into_types() {
- match ty.composite_type.inner {
- wasmparser::CompositeInnerType::Func(_) => {
- module.push_type(cx, ty.composite_type);
- }
- wasmparser::CompositeInnerType::Array(_) => todo!(),
- wasmparser::CompositeInnerType::Struct(_) => todo!(),
- wasmparser::CompositeInnerType::Cont(_) => todo!(),
- }
+ match payload {
+ ImportSection(imports) => import_section(&mut module, imports)?,
+ FunctionSection(funcs) => function_section(&mut module, funcs)?,
+ TableSection(tables) => table_section(&mut module, tables)?,
+ MemorySection(mems) => memory_section(&mut module, mems)?,
+ GlobalSection(globals) => global_section(&mut module, globals)?,
+ ExportSection(exports) => export_section(&mut module, exports)?,
+ _ => {}
}
}
- Ok(())
+ Ok(module)
}
fn import_section<'a>(
- cx: &mut ModuleContext<'a>,
- stack: &mut Vec<StackEntry>,
- full_wasm: &'a [u8],
+ module: &mut ModuleContext<'a>,
imports: wasmparser::ImportSectionReader<'a>,
) -> anyhow::Result<()> {
- let module = stack.top().module;
- stack
- .top_mut()
- .module
- .add_raw_section(cx, SectionId::Import, imports.range(), full_wasm);
-
// Check that we can properly handle all imports.
for imp in imports {
let imp = imp?;
@@ -169,120 +45,55 @@ fn import_section<'a>(
);
}
- check_import_type(
- cx,
- stack.top().module.types(cx),
- stack.top().module.is_root(),
- &module.entity_type(cx, imp.ty),
- )?;
- module.push_import(cx, imp);
+ module.push_import(imp);
}
Ok(())
}
-fn check_import_type(
- _cx: &ModuleContext,
- _types: &[TypeId],
- is_root: bool,
- ty: &EntityType,
-) -> Result<()> {
- match ty {
- EntityType::Function(_) => Ok(()),
- EntityType::Memory(mem_ty) => {
- anyhow::ensure!(
- !mem_ty.shared,
- "shared memories are not supported by Wizer yet"
- );
- anyhow::ensure!(
- !mem_ty.memory64,
- "the memory64 proposal is not supported by Wizer yet"
- );
- anyhow::ensure!(
- !is_root,
- "memory imports are not allowed in the root Wasm module"
- );
- Ok(())
- }
- EntityType::Table(_) | EntityType::Global(_) => {
- anyhow::ensure!(
- !is_root,
- "table and global imports are not allowed in the root Wasm module"
- );
- Ok(())
- }
- }
-}
-
fn function_section<'a>(
- cx: &mut ModuleContext<'a>,
- stack: &mut Vec<StackEntry>,
- full_wasm: &'a [u8],
+ module: &mut ModuleContext<'a>,
funcs: wasmparser::FunctionSectionReader<'a>,
) -> anyhow::Result<()> {
- let module = stack.top().module;
- module.add_raw_section(cx, SectionId::Function, funcs.range(), full_wasm);
-
for ty_idx in funcs {
- let ty = module.type_id_at(cx, ty_idx?);
- module.push_function(cx, ty);
+ module.push_function(ty_idx?);
}
Ok(())
}
fn table_section<'a>(
- cx: &mut ModuleContext<'a>,
- stack: &mut Vec<StackEntry>,
- full_wasm: &'a [u8],
+ module: &mut ModuleContext<'a>,
tables: wasmparser::TableSectionReader<'a>,
) -> anyhow::Result<()> {
- let module = stack.top().module;
- module.add_raw_section(cx, SectionId::Table, tables.range(), full_wasm);
-
for table in tables {
- module.push_table(cx, table?.ty);
+ module.push_table(table?.ty);
}
Ok(())
}
fn memory_section<'a>(
- cx: &mut ModuleContext<'a>,
- stack: &mut Vec<StackEntry>,
- full_wasm: &'a [u8],
+ module: &mut ModuleContext<'a>,
mems: wasmparser::MemorySectionReader<'a>,
) -> anyhow::Result<()> {
- let module = stack.top().module;
- module.add_raw_section(cx, SectionId::Memory, mems.range(), full_wasm);
-
for m in mems {
- module.push_defined_memory(cx, m?);
+ module.push_defined_memory(m?);
}
Ok(())
}
fn global_section<'a>(
- cx: &mut ModuleContext<'a>,
- stack: &mut Vec<StackEntry>,
- full_wasm: &'a [u8],
+ module: &mut ModuleContext<'a>,
globals: wasmparser::GlobalSectionReader<'a>,
) -> anyhow::Result<()> {
- let module = stack.top().module;
- module.add_raw_section(cx, SectionId::Global, globals.range(), full_wasm);
-
for g in globals {
- module.push_defined_global(cx, g?.ty);
+ module.push_defined_global(g?.ty);
}
Ok(())
}
fn export_section<'a>(
- cx: &mut ModuleContext<'a>,
- stack: &mut Vec<StackEntry>,
- full_wasm: &'a [u8],
+ module: &mut ModuleContext<'a>,
exports: wasmparser::ExportSectionReader<'a>,
) -> anyhow::Result<()> {
- let module = stack.top().module;
- module.add_raw_section(cx, SectionId::Export, exports.range(), full_wasm);
-
for export in exports {
let export = export?;
@@ -293,14 +104,12 @@ fn export_section<'a>(
}
match export.kind {
- wasmparser::ExternalKind::Tag => {
- unreachable!("checked in validation")
- }
- wasmparser::ExternalKind::Func
+ wasmparser::ExternalKind::Tag
+ | wasmparser::ExternalKind::Func
| wasmparser::ExternalKind::Table
| wasmparser::ExternalKind::Memory
| wasmparser::ExternalKind::Global => {
- module.push_export(cx, export);
+ module.push_export(export);
}
}
}
diff --git a/crates/wizer/src/rewrite.rs b/crates/wizer/src/rewrite.rs
index bc5cad66d9..af2a4d2ff7 100644
--- a/crates/wizer/src/rewrite.rs
+++ b/crates/wizer/src/rewrite.rs
@@ -11,7 +11,7 @@ impl Wizer {
///
pub(crate) fn rewrite<T>(
&self,
- cx: &mut ModuleContext<'_>,
+ module: &mut ModuleContext<'_>,
store: &wasmtime::Store<T>,
snapshot: &Snapshot,
renames: &FuncRenames,
@@ -19,8 +19,7 @@ impl Wizer {
log::debug!("Rewriting input Wasm to pre-initialized state");
let mut encoder = wasm_encoder::Module::new();
- let module = cx.root();
- let has_wasi_initialize = cx.has_wasi_initialize(module);
+ let has_wasi_initialize = module.has_wasi_initialize();
// Encode the initialized data segments from the snapshot rather
// than the original, uninitialized data segments.
@@ -50,7 +49,7 @@ impl Wizer {
}
};
- for section in module.raw_sections(cx) {
+ for section in module.raw_sections() {
match section {
// Some tools expect the name custom section to come last, even
// though custom sections are allowed in any order. Therefore,
@@ -65,9 +64,9 @@ impl Wizer {
// memory.
s if s.id == u8::from(SectionId::Memory) => {
let mut memories = wasm_encoder::MemorySection::new();
- assert_eq!(module.defined_memories_len(cx), snapshot.memory_mins.len());
+ assert_eq!(module.defined_memories_len(), snapshot.memory_mins.len());
for ((_, mem), new_min) in module
- .defined_memories(cx)
+ .defined_memories()
.zip(snapshot.memory_mins.iter().copied())
{
let mut mem = RoundtripReencoder.memory_type(mem).unwrap();
@@ -81,8 +80,7 @@ impl Wizer {
// rather than the original values.
s if s.id == u8::from(SectionId::Global) => {
let mut globals = wasm_encoder::GlobalSection::new();
- for ((_, glob_ty), val) in
- module.defined_globals(cx).zip(snapshot.globals.iter())
+ for ((_, glob_ty), val) in module.defined_globals().zip(snapshot.globals.iter())
{
let glob_ty = RoundtripReencoder.global_type(glob_ty).unwrap();
globals.global(
@@ -111,7 +109,7 @@ impl Wizer {
// then perform any requested renames.
s if s.id == u8::from(SectionId::Export) => {
let mut exports = wasm_encoder::ExportSection::new();
- for export in module.exports(cx) {
+ for export in module.exports() {
if (export.name == self.init_func && !self.get_keep_init_func())
|| (has_wasi_initialize && export.name == "_initialize")
{
diff --git a/crates/wizer/src/stack_ext.rs b/crates/wizer/src/stack_ext.rs
deleted file mode 100644
index e5ec5a0382..0000000000
--- a/crates/wizer/src/stack_ext.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-/// An extension trait for getting the top element on a stack with an implicit
-/// unwrap for if the stack is empty.
-pub(crate) trait StackExt<T> {
- fn top(&self) -> &T;
- fn top_mut(&mut self) -> &mut T;
-}
-
-impl<T> StackExt<T> for Vec<T> {
- fn top(&self) -> &T {
- self.last().unwrap()
- }
-
- fn top_mut(&mut self) -> &mut T {
- self.last_mut().unwrap()
- }
-}