Skip to content

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

wizer: Remove the `wizer-initialize` component export (#11897)

Alex Crichtonb8ae7427a524
diff --git a/crates/wizer/src/component/rewrite.rs b/crates/wizer/src/component/rewrite.rs
index 6a674982be..2666218a41 100644
--- a/crates/wizer/src/component/rewrite.rs
+++ b/crates/wizer/src/component/rewrite.rs
@@ -2,6 +2,7 @@ use crate::component::ComponentContext;
use crate::component::info::RawSection;
use crate::component::snapshot::ComponentSnapshot;
use crate::{FuncRenames, Wizer};
+use wasm_encoder::reencode::{Reencode, ReencodeComponent};
impl Wizer {
/// Helper method which is the equivalent of [`Wizer::rewrite`], but for
@@ -15,6 +16,11 @@ impl Wizer {
snapshot: &ComponentSnapshot,
) -> Vec<u8> {
let mut encoder = wasm_encoder::Component::new();
+ let mut reencoder = Reencoder {
+ funcs: 0,
+ removed_func: None,
+ wizer: self,
+ };
let mut module_index = 0;
for section in component.sections.iter_mut() {
@@ -51,7 +57,7 @@ impl Wizer {
}
}
RawSection::Raw(s) => {
- encoder.section(s);
+ reencoder.raw_section(&mut encoder, s);
}
}
}
@@ -59,3 +65,182 @@ impl Wizer {
encoder.finish()
}
}
+
+struct Reencoder<'a> {
+ /// Number of defined functions encountered so far.
+ funcs: u32,
+ /// Index of the start function that's being removed, used to renumber all
+ /// other functions.
+ removed_func: Option<u32>,
+ /// Wizer configuration.
+ wizer: &'a Wizer,
+}
+
+impl Reencoder<'_> {
+ fn raw_section(
+ &mut self,
+ encoder: &mut wasm_encoder::Component,
+ section: &wasm_encoder::RawSection,
+ ) {
+ match section.id {
+ // These can't define component functions so the sections are
+ // plumbed as-is.
+ id if id == wasm_encoder::ComponentSectionId::CoreCustom as u8
+ || id == wasm_encoder::ComponentSectionId::CoreInstance as u8
+ || id == wasm_encoder::ComponentSectionId::CoreType as u8
+ || id == wasm_encoder::ComponentSectionId::Component as u8
+ || id == wasm_encoder::ComponentSectionId::Type as u8 =>
+ {
+ encoder.section(section);
+ }
+
+ id if id == wasm_encoder::ComponentSectionId::CoreModule as u8 => {
+ panic!("should happen in caller");
+ }
+ id if id == wasm_encoder::ComponentSectionId::Start as u8 => {
+ // Component start sections aren't supported yet anyway
+ todo!()
+ }
+
+ // These sections all might affect or refer to component function
+ // indices so they're reencoded here, optionally updating function
+ // indices in case the index is higher than the one that we're
+ // removing.
+ id if id == wasm_encoder::ComponentSectionId::Instance as u8 => {
+ self.rewrite(encoder, section.data, Self::parse_instance_section);
+ }
+ id if id == wasm_encoder::ComponentSectionId::Alias as u8 => {
+ self.rewrite(encoder, section.data, Self::parse_component_alias_section);
+ }
+ id if id == wasm_encoder::ComponentSectionId::CanonicalFunction as u8 => {
+ self.rewrite(
+ encoder,
+ section.data,
+ Self::parse_component_canonical_section,
+ );
+ }
+ id if id == wasm_encoder::ComponentSectionId::Import as u8 => {
+ self.rewrite(encoder, section.data, Self::parse_component_import_section);
+ }
+ id if id == wasm_encoder::ComponentSectionId::Export as u8 => {
+ self.rewrite(encoder, section.data, Self::parse_component_export_section);
+ }
+ other => panic!("unexpected component section id: {other}"),
+ }
+ }
+
+ fn rewrite<'a, T, S>(
+ &mut self,
+ encoder: &mut wasm_encoder::Component,
+ data: &'a [u8],
+ f: fn(&mut Self, dst: &mut S, wasmparser::SectionLimited<'a, T>) -> Result<(), Error>,
+ ) where
+ T: wasmparser::FromReader<'a>,
+ S: Default + wasm_encoder::ComponentSection,
+ {
+ let mut section = S::default();
+ f(
+ self,
+ &mut section,
+ wasmparser::SectionLimited::new(wasmparser::BinaryReader::new(data, 0)).unwrap(),
+ )
+ .unwrap();
+ encoder.section(&section);
+ }
+}
+
+impl Reencode for Reencoder<'_> {
+ type Error = std::convert::Infallible;
+}
+type Error = wasm_encoder::reencode::Error<std::convert::Infallible>;
+
+impl ReencodeComponent for Reencoder<'_> {
+ fn component_func_index(&mut self, original_index: u32) -> u32 {
+ match self.removed_func {
+ None => original_index,
+ Some(removed) => {
+ if original_index < removed {
+ original_index
+ } else if original_index == removed {
+ panic!("referenced removed function")
+ } else {
+ original_index - 1
+ }
+ }
+ }
+ }
+
+ fn parse_component_alias_section(
+ &mut self,
+ aliases: &mut wasm_encoder::ComponentAliasSection,
+ section: wasmparser::ComponentAliasSectionReader<'_>,
+ ) -> Result<(), Error> {
+ for alias in section.clone() {
+ let alias = alias?;
+ if let wasmparser::ComponentAlias::InstanceExport {
+ kind: wasmparser::ComponentExternalKind::Func,
+ ..
+ } = alias
+ {
+ self.funcs += 1;
+ }
+ }
+
+ wasm_encoder::reencode::component_utils::parse_component_alias_section(
+ self, aliases, section,
+ )
+ }
+
+ fn parse_component_canonical_section(
+ &mut self,
+ canonicals: &mut wasm_encoder::CanonicalFunctionSection,
+ section: wasmparser::ComponentCanonicalSectionReader<'_>,
+ ) -> Result<(), Error> {
+ for canonical in section.clone() {
+ let canonical = canonical?;
+ if let wasmparser::CanonicalFunction::Lift { .. } = canonical {
+ self.funcs += 1;
+ }
+ }
+
+ wasm_encoder::reencode::component_utils::parse_component_canonical_section(
+ self, canonicals, section,
+ )
+ }
+
+ fn parse_component_import_section(
+ &mut self,
+ imports: &mut wasm_encoder::ComponentImportSection,
+ section: wasmparser::ComponentImportSectionReader<'_>,
+ ) -> Result<(), Error> {
+ for import in section.clone() {
+ let import = import?;
+ if let wasmparser::ComponentExternalKind::Func = import.ty.kind() {
+ self.funcs += 1;
+ }
+ }
+
+ wasm_encoder::reencode::component_utils::parse_component_import_section(
+ self, imports, section,
+ )
+ }
+
+ fn parse_component_export_section(
+ &mut self,
+ exports: &mut wasm_encoder::ComponentExportSection,
+ section: wasmparser::ComponentExportSectionReader<'_>,
+ ) -> Result<(), Error> {
+ for export in section {
+ let export = export?;
+ if !self.wizer.get_keep_init_func() && export.name.0 == self.wizer.get_init_func() {
+ self.removed_func = Some(self.funcs);
+ } else {
+ if export.kind == wasmparser::ComponentExternalKind::Func {
+ self.funcs += 1;
+ }
+ self.parse_component_export(exports, export)?;
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/wizer/test.wasm b/crates/wizer/test.wasm
index 4abd7bd1ff..6635aa9328 100644
Binary files a/crates/wizer/test.wasm and b/crates/wizer/test.wasm differ
diff --git a/crates/wizer/tests/all/component.rs b/crates/wizer/tests/all/component.rs
index c844bccaba..c793dff2fc 100644
--- a/crates/wizer/tests/all/component.rs
+++ b/crates/wizer/tests/all/component.rs
@@ -93,12 +93,12 @@ fn store() -> Result<Store<()>> {
}
async fn instantiate(store: &mut Store<()>, component: &Component) -> Result<Instance> {
- Linker::new(store.engine())
- .instantiate_async(store, component)
- .await
+ let mut linker = Linker::new(store.engine());
+ linker.define_unknown_imports_as_traps(component)?;
+ linker.instantiate_async(store, component).await
}
-async fn wizen_and_run_wasm(expected: u32, wat: &str) -> Result<()> {
+async fn wizen(wat: &str) -> Result<Vec<u8>> {
let _ = env_logger::try_init();
let wasm = wat::parse_str(wat)?;
@@ -122,6 +122,13 @@ async fn wizen_and_run_wasm(expected: u32, wat: &str) -> Result<()> {
std::fs::write("test.wasm", &wasm).unwrap();
}
+ Ok(wasm)
+}
+
+async fn wizen_and_run_wasm(expected: u32, wat: &str) -> Result<()> {
+ let wasm = wizen(wat).await?;
+
+ let mut store = store()?;
let module =
Component::new(store.engine(), wasm).context("Wasm test case failed to compile")?;
@@ -404,3 +411,131 @@ async fn multiple_modules() -> Result<()> {
Ok(())
}
+
+#[tokio::test]
+async fn export_is_removed() -> Result<()> {
+ let wasm = wizen(
+ r#"(component
+ (core module $a
+ (func (export "init"))
+ )
+ (core instance $a (instantiate $a))
+ (func $a (canon lift (core func $a "init")))
+ (export "wizer-initialize" (func $a))
+ )"#,
+ )
+ .await?;
+
+ let names = exports(&wasm);
+ assert!(names.is_empty());
+
+ let wasm = wizen(
+ r#"(component
+ (core module $a
+ (func (export "init"))
+ )
+ (core instance $a (instantiate $a))
+ (func $a (canon lift (core func $a "init")))
+ (export "other" (func $a))
+ (export "wizer-initialize" (func $a))
+ )"#,
+ )
+ .await?;
+ let names = exports(&wasm);
+ assert_eq!(names, ["other"]);
+
+ let wasm = wizen(
+ r#"(component
+ (core module $a
+ (func (export "init"))
+ )
+ (core instance $a (instantiate $a))
+ (func $a (canon lift (core func $a "init")))
+ (export "other1" (func $a))
+ (export "wizer-initialize" (func $a))
+ (export "other2" (func $a))
+ )"#,
+ )
+ .await?;
+ let names = exports(&wasm);
+ assert_eq!(names, ["other1", "other2"]);
+
+ let wasm = wizen(
+ r#"(component
+ (core module $a
+ (func (export "init"))
+ )
+ (core instance $a (instantiate $a))
+ (func $a (canon lift (core func $a "init")))
+ (export "other1" (func $a))
+ (export "other2" (func $a))
+ (export "wizer-initialize" (func $a))
+ )"#,
+ )
+ .await?;
+ let names = exports(&wasm);
+ assert_eq!(names, ["other1", "other2"]);
+
+ let wasm = wizen(
+ r#"(component
+ (core module $a
+ (func (export "init"))
+ )
+ (core instance $a (instantiate $a))
+ (func $a (canon lift (core func $a "init")))
+ (export "wizer-initialize" (func $a))
+ (export "other1" (func $a))
+ (export "other2" (func $a))
+ )"#,
+ )
+ .await?;
+ let names = exports(&wasm);
+ assert_eq!(names, ["other1", "other2"]);
+
+ let wasm = wizen(
+ r#"(component
+ (core module $a
+ (func (export "init"))
+ )
+ (core instance $a (instantiate $a))
+ (func $a (canon lift (core func $a "init")))
+ (export $x "other1" (func $a))
+ (export "wizer-initialize" (func $a))
+ (export "other2" (func $x))
+ )"#,
+ )
+ .await?;
+ let names = exports(&wasm);
+ assert_eq!(names, ["other1", "other2"]);
+
+ let wasm = wizen(
+ r#"(component
+ (import "x" (func))
+ (core module $a
+ (func (export "init"))
+ )
+ (core instance $a (instantiate $a))
+ (func $a (canon lift (core func $a "init")))
+ (export $x "other1" (func $a))
+ (export "wizer-initialize" (func $a))
+ (export "other2" (func $x))
+ )"#,
+ )
+ .await?;
+ let names = exports(&wasm);
+ assert_eq!(names, ["other1", "other2"]);
+
+ return Ok(());
+
+ fn exports(wasm: &[u8]) -> Vec<&str> {
+ wasmparser::Parser::new(0)
+ .parse_all(&wasm)
+ .filter_map(|r| r.ok())
+ .filter_map(|payload| match payload {
+ wasmparser::Payload::ComponentExportSection(s) => Some(s),
+ _ => None,
+ })
+ .flat_map(|section| section.into_iter().map(|e| e.unwrap().name.0))
+ .collect()
+ }
+}