A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Respect type ascriptions on component exports (#14865)
Randolf J.d23440d83f7f
diff --git a/crates/environ/src/component/translate.rs b/crates/environ/src/component/translate.rsindex 3d8b194ca9..baf49ccc5c 100644--- a/crates/environ/src/component/translate.rs+++ b/crates/environ/src/component/translate.rs@@ -353,10 +353,7 @@ enum LocalInitializer<'data> {HashMap<&'data str, ComponentItem>,ComponentInstanceTypeId,),- ComponentSynthetic(- HashMap<&'data str, (ComponentItem, wasmparser::ComponentExternName<'data>)>,- ComponentInstanceTypeId,- ),+ ComponentSynthetic(HashMap<&'data str, ComponentItem>, ComponentInstanceTypeId),// alias sectionAliasExportFunc(ModuleInstanceIndex, &'data str),@@ -1625,7 +1622,7 @@ impl<'a, 'data> Translator<'a, 'data> {let mut map = HashMap::with_capacity(exports.len());for export in exports {let idx = self.kind_to_item(export.kind, export.index)?;- map.insert(export.name.name, (idx, export.name));+ map.insert(export.name.name, idx);}Ok(LocalInitializer::ComponentSynthetic(map, ty))diff --git a/crates/environ/src/component/translate/inline.rs b/crates/environ/src/component/translate/inline.rsindex 4f3d7d2566..1b611797b3 100644--- a/crates/environ/src/component/translate/inline.rs+++ b/crates/environ/src/component/translate/inline.rs@@ -137,8 +137,8 @@ pub(super) fn run(assert!(frames.is_empty());let mut export_map = Default::default();- for (name, (def, data)) in exports {- let data = ComponentExternData::new(data);+ for (name, def) in exports {+ let data = ComponentExternData::new(result.exports[name].1);inliner.record_export(name, def, data, types, &mut export_map)?;}inliner.result.exports = export_map;@@ -350,7 +350,7 @@ enum ComponentInstanceDef<'a> {// FIXME: same as the issue on `ComponentClosure` where this is cloned a lot// and may need `Rc`.Items(- IndexMap<&'a str, (ComponentItemDef<'a>, wasmparser::ComponentExternName<'a>)>,+ IndexMap<&'a str, ComponentItemDef<'a>>,TypeComponentInstanceIndex,),}@@ -380,8 +380,7 @@ impl<'a> Inliner<'a> {&mut self,types: &mut ComponentTypesBuilder,frames: &mut Vec<(InlinerFrame<'a>, ResourcesBuilder)>,- ) -> Result<IndexMap<&'a str, (ComponentItemDef<'a>, wasmparser::ComponentExternName<'a>)>>- {+ ) -> Result<IndexMap<&'a str, ComponentItemDef<'a>>> {// This loop represents the execution of the instantiation of a// component. This is an iterative process which is finished once all// initializers are processed. Currently this is modeled as an infinite@@ -408,11 +407,36 @@ impl<'a> Inliner<'a> {// parent frame, if any, as a new component instance or they're// returned from this function for the root set of exports.None => {+ let types_ref = frame.translation.types_ref();let exports = frame.translation.exports.iter()- .map(|(name, (item, data))| Ok((*name, (frame.item(*item, types)?, *data))))+ .map(|(name, (item, _))| {+ let mut def = frame.item(*item, types)?;+ // For the root component+ // (`frame.instance_ty.is_none()`) re-ascribe+ // exported instances with whatever type wasmparser+ // recorded for that instance. If the component+ // ascribed the type then it might be a subset of+ // the exports that the instance actually exports.+ //+ // Only instances are handled here. Other items can+ // be ascribed too, but that doesn't change what the+ // host sees: function and value types must match+ // exactly, and ascribed types and resources must+ // refer to existing ones. Ascriptions of modules+ // and components aren't reflected, but the host+ // can only inspect those, not instantiate them.+ if frame.instance_ty.is_none()+ && let ComponentEntityType::Instance(ty) =+ types_ref.component_item_for_export(name).unwrap().ty+ {+ let ty = types.convert_instance(types_ref, ty)?;+ def = def.with_instance_type(ty);+ }+ Ok((*name, def))+ }).collect::<Result<_>>()?;let instance_ty = frame.instance_ty;let (_, snapshot) = frames.pop().unwrap();@@ -1306,7 +1330,7 @@ impl<'a> Inliner<'a> {ComponentSynthetic(map, ty) => {let items = map.iter()- .map(|(name, (index, data))| Ok((*name, (frame.item(*index, types)?, *data))))+ .map(|(name, index)| Ok((*name, frame.item(*index, types)?))).collect::<Result<_>>()?;let types_ref = frame.translation.types_ref();let ty = types.convert_instance(types_ref, *ty)?;@@ -1421,7 +1445,7 @@ impl<'a> Inliner<'a> {// through instantiation of a component or through a// synthetic renaming of items we just schlep around the// definitions of various items here.- ComponentInstanceDef::Items(map, _) => frame.push_item(map[*name].0.clone()),+ ComponentInstanceDef::Items(map, _) => frame.push_item(map[*name].clone()),}}@@ -1690,10 +1714,19 @@ impl<'a> Inliner<'a> {// An exported instance which is itself a bag of items is// translated recursively here to our `exports` map which is// the bag of items we're exporting.+ //+ // Note that `ty` may be a supertype of the items in `map`,+ // for example due to an export's type ascription, so `ty`+ // determines which items are exported and with which+ // attributes.ComponentInstanceDef::Items(map, ty) => {- for (name, (def, data)) in map {- let data = ComponentExternData::new(data);- self.record_export(name, def, data.clone(), types, &mut exports)?;+ for (name, export) in types[ty].exports.iter() {+ let mut def = map[name.as_str()].clone();+ if let TypeDef::ComponentInstance(instance_ty) = export.ty {+ def = def.with_instance_type(instance_ty);+ }+ let data = export.data.clone();+ self.record_export(name, def, data, types, &mut exports)?;}dfg::Export::Instance { ty, exports }}@@ -1844,7 +1877,7 @@ impl<'a> InlinerFrame<'a> {/// and which component instantiated it.fn finish_instantiate(&mut self,- exports: IndexMap<&'a str, (ComponentItemDef<'a>, wasmparser::ComponentExternName<'a>)>,+ exports: IndexMap<&'a str, ComponentItemDef<'a>>,ty: ComponentInstanceTypeId,types: &mut ComponentTypesBuilder,) -> Result<()> {@@ -1858,7 +1891,7 @@ impl<'a> InlinerFrame<'a> {&mut path,&mut |path| match path {[] => unreachable!(),- [name, rest @ ..] => exports[name].0.lookup_resource(rest, types),+ [name, rest @ ..] => exports[name].lookup_resource(rest, types),},);}@@ -1902,6 +1935,25 @@ impl<'a> ComponentItemDef<'a> {Ok(item)}+ /// Returns this instance as seen through `ty`, a supertype of its own+ /// type, which determines which of its exports are visible and what+ /// attributes they have.+ ///+ /// # Panics+ ///+ /// Panics if `self` isn't an instance.+ fn with_instance_type(self, ty: TypeComponentInstanceIndex) -> ComponentItemDef<'a> {+ match self {+ ComponentItemDef::Instance(ComponentInstanceDef::Items(map, _)) => {+ ComponentItemDef::Instance(ComponentInstanceDef::Items(map, ty))+ }+ ComponentItemDef::Instance(ComponentInstanceDef::Import(path, _)) => {+ ComponentItemDef::Instance(ComponentInstanceDef::Import(path, ty))+ }+ _ => panic!("only instances have an instance type"),+ }+ }+/// Walks the `path` within `self` to find a resource at that path.////// This method is used when resources are found within wasmparser's type@@ -1922,7 +1974,7 @@ impl<'a> ComponentItemDef<'a> {cur = match instance {// If this instance is a "bag of things" then this is as easy as// looking up the name in the bag of names.- ComponentInstanceDef::Items(names, _) => names[element].0.clone(),+ ComponentInstanceDef::Items(names, _) => names[element].clone(),// If, however, this instance is an imported instance then this// is a further projection within the import with one more pathdiff --git a/tests/all/component_model/aot.rs b/tests/all/component_model/aot.rsindex 6898ad98b1..687c64bbd0 100644--- a/tests/all/component_model/aot.rs+++ b/tests/all/component_model/aot.rs@@ -1,5 +1,5 @@use wasmtime::Result;-use wasmtime::component::types::ComponentItem;+use wasmtime::component::types::{ComponentExtern, ComponentInstance, ComponentItem};use wasmtime::component::{Component, Linker, Type};use wasmtime::{Config, Engine, Module, Precompiled, Store};@@ -298,6 +298,64 @@ fn external_id_shows_up() -> Result<()> {Ok(())}+#[test]+#[cfg_attr(miri, ignore)]+fn attributes_from_export_ascription() -> Result<()> {+ let mut config = Config::new();+ config.wasm_component_model_implements(true);+ let engine = Engine::new(&config)?;+ let component = Component::new(+ &engine,+ r#"+ (component+ (instance $n)+ (instance $b (export "n" (implements "x:y/z") (instance $n)))+ (export "out" (instance $b) (instance+ (export "n" (implements "a:b/c") (external-id "asc") (instance))+ ))++ (component $c+ (instance $n)+ (instance $b (export "n" (implements "x:y/z") (instance $n)))+ (export "x" (instance $b) (instance+ (export "n" (implements "a:b/c") (external-id "asc") (instance))+ ))+ )+ (instance $c (instantiate $c))+ (export "whole" (instance $c))+ (export "alias" (instance $c "x"))+ )+ "#,+ )?;++ fn instance(item: ComponentExtern<'_>) -> ComponentInstance {+ match item.ty {+ ComponentItem::ComponentInstance(i) => i,+ _ => panic!("expected an instance"),+ }+ }++ let assert_reflection = |component: &Component| {+ let ty = component.component_type();+ let out = instance(ty.get_export(&engine, "out").unwrap());+ let whole = instance(ty.get_export(&engine, "whole").unwrap());+ let whole = instance(whole.get_export(&engine, "x").unwrap());+ let alias = instance(ty.get_export(&engine, "alias").unwrap());+ for i in [out, whole, alias] {+ let n = i.get_export(&engine, "n").unwrap();+ assert_eq!(n.implements, Some("a:b/c"));+ assert_eq!(n.external_id, Some("asc"));+ }+ };++ assert_reflection(&component);+ let bytes = component.serialize()?;+ let component = unsafe { Component::deserialize(&engine, &bytes)? };+ assert_reflection(&component);++ Ok(())+}+#[test]#[cfg_attr(miri, ignore)]fn issue_13540_resources_in_adapter_no_concurrency() -> Result<()> {diff --git a/tests/all/component_model/instance.rs b/tests/all/component_model/instance.rsindex ad7b6d3f23..e7ad1c3c6c 100644--- a/tests/all/component_model/instance.rs+++ b/tests/all/component_model/instance.rs@@ -180,3 +180,51 @@ fn export_missing_get_max() -> Result<()> {Ok(())}++#[test]+#[cfg_attr(miri, ignore)]+fn export_type_ascription_hides_exports() -> Result<()> {+ let engine = super::engine();+ let component = r#"+ (component+ (core module $m+ (func (export "f") (result i32) i32.const 1)+ (func (export "g") (result i32) i32.const 2))+ (core instance $i (instantiate $m))+ (func $f (result u32) (canon lift (core func $i "f")))+ (func $g (result u32) (canon lift (core func $i "g")))+ (instance $inst (export "f" (func $f)) (export "g" (func $g)))+ (export "hidden" (instance $inst) (instance (export "f" (func (result u32)))))+ )+ "#;+ let component = Component::new(&engine, component)?;++ let ty = component.component_type();+ let (_, hidden) = ty.exports(&engine).next().unwrap();+ let types::ComponentItem::ComponentInstance(hidden) = hidden.ty else {+ panic!("expected an instance export");+ };+ let names = hidden.exports(&engine).map(|(n, _)| n).collect::<Vec<_>>();+ assert_eq!(names, ["f"]);++ let hidden = component.get_export_index(None, "hidden").unwrap();+ assert!(component.get_export_index(Some(&hidden), "g").is_none());++ let mut store = Store::new(&engine, ());+ let instance = Linker::new(&engine).instantiate(&mut store, &component)?;+ let hidden = instance+ .get_export_index(&mut store, None, "hidden")+ .unwrap();+ assert!(+ instance+ .get_export_index(&mut store, Some(&hidden), "g")+ .is_none()+ );+ let f = instance+ .get_export_index(&mut store, Some(&hidden), "f")+ .unwrap();+ let f = instance.get_typed_func::<(), (u32,)>(&mut store, &f)?;+ assert_eq!(f.call(&mut store, ())?, (1,));++ Ok(())+}diff --git a/tests/all/component_model/nested.rs b/tests/all/component_model/nested.rsindex dea7f6a5c0..83245b0f0b 100644--- a/tests/all/component_model/nested.rs+++ b/tests/all/component_model/nested.rs@@ -3,7 +3,7 @@use super::REALLOC_AND_FREE;use wasmtime::Result;use wasmtime::component::*;-use wasmtime::{Module, Store};+use wasmtime::{Config, Engine, Module, Store};#[test]fn top_level_instance_two_level() -> Result<()> {@@ -163,3 +163,81 @@ fn issue_14506_long_reexport_chain_compiles_quickly() -> Result<()> {Component::new(&engine, wat)?;Ok(())}++#[test]+fn instance_passed_to_nested_component_has_declared_type() -> Result<()> {+ let component = r#"+(component+ (import "host" (instance $host+ (export "n" (implements "p:q/r") (instance))+ (export "extra" (func (result u32)))+ ))++ (core module $m (func (export "f") (result i32) i32.const 7))+ (core instance $i (instantiate $m))+ (func $f (result u32) (canon lift (core func $i "f")))+ (instance $n)+ (instance $arg+ (export "n" (implements "p:q/r") (instance $n))+ (export "extra" (func $f))+ )++ (component $inner+ (import "x" (instance $x (export "n" (implements "x:y/z") (instance))))+ (export "y" (instance $x))+ )+ (instance $a (instantiate $inner (with "x" (instance $arg))))+ (instance $b (instantiate $inner (with "x" (instance $host))))+ (export "a" (instance $a "y"))+ (export "b" (instance $b "y"))+ (export "c" (instance $a))+)+ "#;+ let mut config = Config::new();+ config.wasm_component_model_implements(true);+ let engine = Engine::new(&config)?;+ let component = Component::new(&engine, component)?;++ // The instances exported by `$inner` have the type that `$inner` declared+ // for its import, not the type of the instances passed to it.+ let instance = |item: Option<types::ComponentExtern<'_>>| match item.unwrap().ty {+ types::ComponentItem::ComponentInstance(i) => i,+ _ => panic!("expected an instance"),+ };+ let ty = component.component_type();+ let c = instance(ty.get_export(&engine, "c"));+ for i in [+ instance(ty.get_export(&engine, "a")),+ instance(ty.get_export(&engine, "b")),+ instance(c.get_export(&engine, "y")),+ ] {+ let exports = i+ .exports(&engine)+ .map(|(name, e)| (name, e.implements))+ .collect::<Vec<_>>();+ assert_eq!(exports, [("n", Some("x:y/z"))]);+ }++ let mut store = Store::new(&engine, ());+ let mut linker = Linker::new(&engine);+ let mut host = linker.instance("host")?;+ host.instance("n")?;+ host.func_wrap("extra", |_, ()| Ok((1u32,)))?;+ let instance = linker.instantiate(&mut store, &component)?;+ let c = instance.get_export_index(&mut store, None, "c").unwrap();+ for (parent, name) in [(None, "a"), (None, "b"), (Some(&c), "y")] {+ let i = instance.get_export_index(&mut store, parent, name).unwrap();+ assert!(+ instance+ .get_export_index(&mut store, Some(&i), "n")+ .is_some()+ );+ assert!(+ instance+ .get_export_index(&mut store, Some(&i), "extra")+ .is_none()+ );+ }++ Ok(())+}