1 use crate::component::matching::InstanceType;
2 use crate::component::types;
3 use crate::component::InstanceExportLookup;
4 use crate::prelude::*;
5 use crate::runtime::vm::component::ComponentRuntimeInfo;
6 #[cfg(feature = "std")]
7 use crate::runtime::vm::open_file_for_mmap;
8 use crate::runtime::vm::{
9     CompiledModuleId, VMArrayCallFunction, VMFuncRef, VMFunctionBody, VMWasmCallFunction,
10 };
11 use crate::{
12     code::CodeObject, code_memory::CodeMemory, type_registry::TypeCollection, Engine, Module,
13     ResourcesRequired,
14 };
15 use crate::{FuncType, ValType};
16 use alloc::sync::Arc;
17 use core::any::Any;
18 use core::ops::Range;
19 use core::ptr::NonNull;
20 #[cfg(feature = "std")]
21 use std::path::Path;
22 use wasmtime_environ::component::{
23     AllCallFunc, CompiledComponentInfo, ComponentArtifacts, ComponentTypes, Export, ExportIndex,
24     GlobalInitializer, InstantiateModule, NameMapNoIntern, StaticModuleIndex, TrampolineIndex,
25     TypeComponentIndex, TypeDef, VMComponentOffsets,
26 };
27 use wasmtime_environ::{FunctionLoc, HostPtr, ObjectKind, PrimaryMap};
28 
29 /// A compiled WebAssembly Component.
30 ///
31 /// This structure represents a compiled component that is ready to be
32 /// instantiated. This owns a region of virtual memory which contains executable
33 /// code compiled from a WebAssembly binary originally. This is the analog of
34 /// [`Module`](crate::Module) in the component embedding API.
35 ///
36 /// A [`Component`] can be turned into an
37 /// [`Instance`](crate::component::Instance) through a
38 /// [`Linker`](crate::component::Linker). [`Component`]s are safe to share
39 /// across threads. The compilation model of a component is the same as that of
40 /// [a module](crate::Module) which is to say:
41 ///
42 /// * Compilation happens synchronously during [`Component::new`].
43 /// * The result of compilation can be saved into storage with
44 ///   [`Component::serialize`].
45 /// * A previously compiled artifact can be parsed with
46 ///   [`Component::deserialize`].
47 /// * No compilation happens at runtime for a component — everything is done
48 ///   by the time [`Component::new`] returns.
49 ///
50 /// ## Components and `Clone`
51 ///
52 /// Using `clone` on a `Component` is a cheap operation. It will not create an
53 /// entirely new component, but rather just a new reference to the existing
54 /// component. In other words it's a shallow copy, not a deep copy.
55 ///
56 /// ## Examples
57 ///
58 /// For example usage see the documentation of [`Module`](crate::Module) as
59 /// [`Component`] has the same high-level API.
60 #[derive(Clone)]
61 pub struct Component {
62     inner: Arc<ComponentInner>,
63 }
64 
65 struct ComponentInner {
66     /// Unique id for this component within this process.
67     ///
68     /// Note that this is repurposing ids for modules intentionally as there
69     /// shouldn't be an issue overlapping them.
70     id: CompiledModuleId,
71 
72     /// The engine that this component belongs to.
73     engine: Engine,
74 
75     /// Component type index
76     ty: TypeComponentIndex,
77 
78     /// Core wasm modules that the component defined internally, indexed by the
79     /// compile-time-assigned `ModuleUpvarIndex`.
80     static_modules: PrimaryMap<StaticModuleIndex, Module>,
81 
82     /// Code-related information such as the compiled artifact, type
83     /// information, etc.
84     ///
85     /// Note that the `Arc` here is used to share this allocation with internal
86     /// modules.
87     code: Arc<CodeObject>,
88 
89     /// Metadata produced during compilation.
90     info: CompiledComponentInfo,
91 
92     /// A cached handle to the `wasmtime::FuncType` for the canonical ABI's
93     /// `realloc`, to avoid the need to look up types in the registry and take
94     /// locks when calling `realloc` via `TypedFunc::call_raw`.
95     realloc_func_type: Arc<dyn Any + Send + Sync>,
96 }
97 
98 pub(crate) struct AllCallFuncPointers {
99     pub wasm_call: NonNull<VMWasmCallFunction>,
100     pub array_call: NonNull<VMArrayCallFunction>,
101 }
102 
103 impl Component {
104     /// Compiles a new WebAssembly component from the in-memory list of bytes
105     /// provided.
106     ///
107     /// The `bytes` provided can either be the binary or text format of a
108     /// [WebAssembly component]. Note that the text format requires the `wat`
109     /// feature of this crate to be enabled. This API does not support
110     /// streaming compilation.
111     ///
112     /// This function will synchronously validate the entire component,
113     /// including all core modules, and then compile all components, modules,
114     /// etc., found within the provided bytes.
115     ///
116     /// [WebAssembly component]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md
117     ///
118     /// # Errors
119     ///
120     /// This function may fail and return an error. Errors may include
121     /// situations such as:
122     ///
123     /// * The binary provided could not be decoded because it's not a valid
124     ///   WebAssembly binary
125     /// * The WebAssembly binary may not validate (e.g. contains type errors)
126     /// * Implementation-specific limits were exceeded with a valid binary (for
127     ///   example too many locals)
128     /// * The wasm binary may use features that are not enabled in the
129     ///   configuration of `engine`
130     /// * If the `wat` feature is enabled and the input is text, then it may be
131     ///   rejected if it fails to parse.
132     ///
133     /// The error returned should contain full information about why compilation
134     /// failed.
135     ///
136     /// # Examples
137     ///
138     /// The `new` function can be invoked with a in-memory array of bytes:
139     ///
140     /// ```no_run
141     /// # use wasmtime::*;
142     /// # use wasmtime::component::Component;
143     /// # fn main() -> anyhow::Result<()> {
144     /// # let engine = Engine::default();
145     /// # let wasm_bytes: Vec<u8> = Vec::new();
146     /// let component = Component::new(&engine, &wasm_bytes)?;
147     /// # Ok(())
148     /// # }
149     /// ```
150     ///
151     /// Or you can also pass in a string to be parsed as the wasm text
152     /// format:
153     ///
154     /// ```
155     /// # use wasmtime::*;
156     /// # use wasmtime::component::Component;
157     /// # fn main() -> anyhow::Result<()> {
158     /// # let engine = Engine::default();
159     /// let component = Component::new(&engine, "(component (core module))")?;
160     /// # Ok(())
161     /// # }
162     #[cfg(any(feature = "cranelift", feature = "winch"))]
163     pub fn new(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> {
164         crate::CodeBuilder::new(engine)
165             .wasm_binary_or_text(bytes.as_ref(), None)?
166             .compile_component()
167     }
168 
169     /// Compiles a new WebAssembly component from a wasm file on disk pointed
170     /// to by `file`.
171     ///
172     /// This is a convenience function for reading the contents of `file` on
173     /// disk and then calling [`Component::new`].
174     #[cfg(all(feature = "std", any(feature = "cranelift", feature = "winch")))]
175     pub fn from_file(engine: &Engine, file: impl AsRef<Path>) -> Result<Component> {
176         crate::CodeBuilder::new(engine)
177             .wasm_binary_or_text_file(file.as_ref())?
178             .compile_component()
179     }
180 
181     /// Compiles a new WebAssembly component from the in-memory wasm image
182     /// provided.
183     ///
184     /// This function is the same as [`Component::new`] except that it does not
185     /// accept the text format of WebAssembly. Even if the `wat` feature
186     /// is enabled an error will be returned here if `binary` is the text
187     /// format.
188     ///
189     /// For more information on semantics and errors see [`Component::new`].
190     #[cfg(any(feature = "cranelift", feature = "winch"))]
191     pub fn from_binary(engine: &Engine, binary: &[u8]) -> Result<Component> {
192         crate::CodeBuilder::new(engine)
193             .wasm_binary(binary, None)?
194             .compile_component()
195     }
196 
197     /// Same as [`Module::deserialize`], but for components.
198     ///
199     /// Note that the bytes referenced here must contain contents previously
200     /// produced by [`Engine::precompile_component`] or
201     /// [`Component::serialize`].
202     ///
203     /// For more information see the [`Module::deserialize`] method.
204     ///
205     /// # Unsafety
206     ///
207     /// The unsafety of this method is the same as that of the
208     /// [`Module::deserialize`] method.
209     ///
210     /// [`Module::deserialize`]: crate::Module::deserialize
211     pub unsafe fn deserialize(engine: &Engine, bytes: impl AsRef<[u8]>) -> Result<Component> {
212         let code = engine.load_code_bytes(bytes.as_ref(), ObjectKind::Component)?;
213         Component::from_parts(engine, code, None)
214     }
215 
216     /// Same as [`Module::deserialize_file`], but for components.
217     ///
218     /// Note that the file referenced here must contain contents previously
219     /// produced by [`Engine::precompile_component`] or
220     /// [`Component::serialize`].
221     ///
222     /// For more information see the [`Module::deserialize_file`] method.
223     ///
224     /// # Unsafety
225     ///
226     /// The unsafety of this method is the same as that of the
227     /// [`Module::deserialize_file`] method.
228     ///
229     /// [`Module::deserialize_file`]: crate::Module::deserialize_file
230     #[cfg(feature = "std")]
231     pub unsafe fn deserialize_file(engine: &Engine, path: impl AsRef<Path>) -> Result<Component> {
232         let file = open_file_for_mmap(path.as_ref())?;
233         let code = engine
234             .load_code_file(file, ObjectKind::Component)
235             .with_context(|| format!("failed to load code for: {}", path.as_ref().display()))?;
236         Component::from_parts(engine, code, None)
237     }
238 
239     /// Returns the type of this component as a [`types::Component`].
240     ///
241     /// This method enables runtime introspection of the type of a component
242     /// before instantiation, if necessary.
243     ///
244     /// ## Component types and Resources
245     ///
246     /// An important point to note here is that the precise type of imports and
247     /// exports of a component change when it is instantiated with respect to
248     /// resources. For example a [`Component`] represents an un-instantiated
249     /// component meaning that its imported resources are represented as abstract
250     /// resource types. These abstract types are not equal to any other
251     /// component's types.
252     ///
253     /// For example:
254     ///
255     /// ```
256     /// # use wasmtime::Engine;
257     /// # use wasmtime::component::Component;
258     /// # use wasmtime::component::types::ComponentItem;
259     /// # fn main() -> wasmtime::Result<()> {
260     /// # let engine = Engine::default();
261     /// let a = Component::new(&engine, r#"
262     ///     (component (import "x" (type (sub resource))))
263     /// "#)?;
264     /// let b = Component::new(&engine, r#"
265     ///     (component (import "x" (type (sub resource))))
266     /// "#)?;
267     ///
268     /// let (_, a_ty) = a.component_type().imports(&engine).next().unwrap();
269     /// let (_, b_ty) = b.component_type().imports(&engine).next().unwrap();
270     ///
271     /// let a_ty = match a_ty {
272     ///     ComponentItem::Resource(ty) => ty,
273     ///     _ => unreachable!(),
274     /// };
275     /// let b_ty = match b_ty {
276     ///     ComponentItem::Resource(ty) => ty,
277     ///     _ => unreachable!(),
278     /// };
279     /// assert!(a_ty != b_ty);
280     /// # Ok(())
281     /// # }
282     /// ```
283     ///
284     /// Additionally, however, these abstract types are "substituted" during
285     /// instantiation meaning that a component type will appear to have changed
286     /// once it is instantiated.
287     ///
288     /// ```
289     /// # use wasmtime::{Engine, Store};
290     /// # use wasmtime::component::{Component, Linker, ResourceType};
291     /// # use wasmtime::component::types::ComponentItem;
292     /// # fn main() -> wasmtime::Result<()> {
293     /// # let engine = Engine::default();
294     /// // Here this component imports a resource and then exports it as-is
295     /// // which means that the export is equal to the import.
296     /// let a = Component::new(&engine, r#"
297     ///     (component
298     ///         (import "x" (type $x (sub resource)))
299     ///         (export "x" (type $x))
300     ///     )
301     /// "#)?;
302     ///
303     /// let (_, import) = a.component_type().imports(&engine).next().unwrap();
304     /// let (_, export) = a.component_type().exports(&engine).next().unwrap();
305     ///
306     /// let import = match import {
307     ///     ComponentItem::Resource(ty) => ty,
308     ///     _ => unreachable!(),
309     /// };
310     /// let export = match export {
311     ///     ComponentItem::Resource(ty) => ty,
312     ///     _ => unreachable!(),
313     /// };
314     /// assert_eq!(import, export);
315     ///
316     /// // However after instantiation the resource type "changes"
317     /// let mut store = Store::new(&engine, ());
318     /// let mut linker = Linker::new(&engine);
319     /// linker.root().resource("x", ResourceType::host::<()>(), |_, _| Ok(()))?;
320     /// let instance = linker.instantiate(&mut store, &a)?;
321     /// let instance_ty = instance.get_resource(&mut store, "x").unwrap();
322     ///
323     /// // Here `instance_ty` is not the same as either `import` or `export`,
324     /// // but it is equal to what we provided as an import.
325     /// assert!(instance_ty != import);
326     /// assert!(instance_ty != export);
327     /// assert!(instance_ty == ResourceType::host::<()>());
328     /// # Ok(())
329     /// # }
330     /// ```
331     ///
332     /// Finally, each instantiation of an exported resource from a component is
333     /// considered "fresh" for all instantiations meaning that different
334     /// instantiations will have different exported resource types:
335     ///
336     /// ```
337     /// # use wasmtime::{Engine, Store};
338     /// # use wasmtime::component::{Component, Linker};
339     /// # fn main() -> wasmtime::Result<()> {
340     /// # let engine = Engine::default();
341     /// let a = Component::new(&engine, r#"
342     ///     (component
343     ///         (type $x (resource (rep i32)))
344     ///         (export "x" (type $x))
345     ///     )
346     /// "#)?;
347     ///
348     /// let mut store = Store::new(&engine, ());
349     /// let linker = Linker::new(&engine);
350     /// let instance1 = linker.instantiate(&mut store, &a)?;
351     /// let instance2 = linker.instantiate(&mut store, &a)?;
352     ///
353     /// let x1 = instance1.get_resource(&mut store, "x").unwrap();
354     /// let x2 = instance2.get_resource(&mut store, "x").unwrap();
355     ///
356     /// // Despite these two resources being the same export of the same
357     /// // component they come from two different instances meaning that their
358     /// // types will be unique.
359     /// assert!(x1 != x2);
360     /// # Ok(())
361     /// # }
362     /// ```
363     pub fn component_type(&self) -> types::Component {
364         self.with_uninstantiated_instance_type(|ty| types::Component::from(self.inner.ty, ty))
365     }
366 
367     fn with_uninstantiated_instance_type<R>(&self, f: impl FnOnce(&InstanceType<'_>) -> R) -> R {
368         let resources = Arc::new(PrimaryMap::new());
369         f(&InstanceType {
370             types: self.types(),
371             resources: &resources,
372         })
373     }
374 
375     /// Final assembly step for a component from its in-memory representation.
376     ///
377     /// If the `artifacts` are specified as `None` here then they will be
378     /// deserialized from `code_memory`.
379     pub(crate) fn from_parts(
380         engine: &Engine,
381         code_memory: Arc<CodeMemory>,
382         artifacts: Option<ComponentArtifacts>,
383     ) -> Result<Component> {
384         let ComponentArtifacts {
385             ty,
386             info,
387             types,
388             static_modules,
389         } = match artifacts {
390             Some(artifacts) => artifacts,
391             None => postcard::from_bytes(code_memory.wasmtime_info()).err2anyhow()?,
392         };
393 
394         // Validate that the component can be used with the current instance
395         // allocator.
396         engine.allocator().validate_component(
397             &info.component,
398             &VMComponentOffsets::new(HostPtr, &info.component),
399             &|module_index| &static_modules[module_index].module,
400         )?;
401 
402         // Create a signature registration with the `Engine` for all trampolines
403         // and core wasm types found within this component, both for the
404         // component and for all included core wasm modules.
405         let signatures = TypeCollection::new_for_module(engine, types.module_types());
406 
407         // Assemble the `CodeObject` artifact which is shared by all core wasm
408         // modules as well as the final component.
409         let types = Arc::new(types);
410         let code = Arc::new(CodeObject::new(code_memory, signatures, types.into()));
411 
412         // Convert all information about static core wasm modules into actual
413         // `Module` instances by converting each `CompiledModuleInfo`, the
414         // `types` type information, and the code memory to a runtime object.
415         let static_modules = static_modules
416             .into_iter()
417             .map(|(_, info)| Module::from_parts_raw(engine, code.clone(), info, false))
418             .collect::<Result<_>>()?;
419 
420         let realloc_func_type = Arc::new(FuncType::new(
421             engine,
422             [ValType::I32, ValType::I32, ValType::I32, ValType::I32],
423             [ValType::I32],
424         )) as _;
425 
426         Ok(Component {
427             inner: Arc::new(ComponentInner {
428                 id: CompiledModuleId::new(),
429                 engine: engine.clone(),
430                 ty,
431                 static_modules,
432                 code,
433                 info,
434                 realloc_func_type,
435             }),
436         })
437     }
438 
439     pub(crate) fn ty(&self) -> TypeComponentIndex {
440         self.inner.ty
441     }
442 
443     pub(crate) fn env_component(&self) -> &wasmtime_environ::component::Component {
444         &self.inner.info.component
445     }
446 
447     pub(crate) fn static_module(&self, idx: StaticModuleIndex) -> &Module {
448         &self.inner.static_modules[idx]
449     }
450 
451     #[inline]
452     pub(crate) fn types(&self) -> &Arc<ComponentTypes> {
453         self.inner.component_types()
454     }
455 
456     pub(crate) fn signatures(&self) -> &TypeCollection {
457         self.inner.code.signatures()
458     }
459 
460     pub(crate) fn text(&self) -> &[u8] {
461         self.inner.code.code_memory().text()
462     }
463 
464     pub(crate) fn trampoline_ptrs(&self, index: TrampolineIndex) -> AllCallFuncPointers {
465         let AllCallFunc {
466             wasm_call,
467             array_call,
468         } = &self.inner.info.trampolines[index];
469         AllCallFuncPointers {
470             wasm_call: self.func(wasm_call).cast(),
471             array_call: self.func(array_call).cast(),
472         }
473     }
474 
475     fn func(&self, loc: &FunctionLoc) -> NonNull<VMFunctionBody> {
476         let text = self.text();
477         let trampoline = &text[loc.start as usize..][..loc.length as usize];
478         NonNull::new(trampoline.as_ptr() as *mut VMFunctionBody).unwrap()
479     }
480 
481     pub(crate) fn code_object(&self) -> &Arc<CodeObject> {
482         &self.inner.code
483     }
484 
485     /// Same as [`Module::serialize`], except for a component.
486     ///
487     /// Note that the artifact produced here must be passed to
488     /// [`Component::deserialize`] and is not compatible for use with
489     /// [`Module`].
490     ///
491     /// [`Module::serialize`]: crate::Module::serialize
492     /// [`Module`]: crate::Module
493     pub fn serialize(&self) -> Result<Vec<u8>> {
494         Ok(self.code_object().code_memory().mmap().to_vec())
495     }
496 
497     pub(crate) fn runtime_info(&self) -> Arc<dyn ComponentRuntimeInfo> {
498         self.inner.clone()
499     }
500 
501     /// Creates a new `VMFuncRef` with all fields filled out for the destructor
502     /// specified.
503     ///
504     /// The `dtor`'s own `VMFuncRef` won't have `wasm_call` filled out but this
505     /// component may have `resource_drop_wasm_to_native_trampoline` filled out
506     /// if necessary in which case it's filled in here.
507     pub(crate) fn resource_drop_func_ref(&self, dtor: &crate::func::HostFunc) -> VMFuncRef {
508         // Host functions never have their `wasm_call` filled in at this time.
509         assert!(dtor.func_ref().wasm_call.is_none());
510 
511         // Note that if `resource_drop_wasm_to_native_trampoline` is not present
512         // then this can't be called by the component, so it's ok to leave it
513         // blank.
514         let wasm_call = self
515             .inner
516             .info
517             .resource_drop_wasm_to_array_trampoline
518             .as_ref()
519             .map(|i| self.func(i).cast());
520         VMFuncRef {
521             wasm_call,
522             ..*dtor.func_ref()
523         }
524     }
525 
526     /// Returns a summary of the resources required to instantiate this
527     /// [`Component`][crate::component::Component].
528     ///
529     /// Note that when a component imports and instantiates another component or
530     /// core module, we cannot determine ahead of time how many resources
531     /// instantiating this component will require, and therefore this method
532     /// will return `None` in these scenarios.
533     ///
534     /// Potential uses of the returned information:
535     ///
536     /// * Determining whether your pooling allocator configuration supports
537     ///   instantiating this component.
538     ///
539     /// * Deciding how many of which `Component` you want to instantiate within
540     ///   a fixed amount of resources, e.g. determining whether to create 5
541     ///   instances of component X or 10 instances of component Y.
542     ///
543     /// # Example
544     ///
545     /// ```
546     /// # fn main() -> wasmtime::Result<()> {
547     /// use wasmtime::{Config, Engine, component::Component};
548     ///
549     /// let mut config = Config::new();
550     /// config.wasm_multi_memory(true);
551     /// config.wasm_component_model(true);
552     /// let engine = Engine::new(&config)?;
553     ///
554     /// let component = Component::new(&engine, &r#"
555     ///     (component
556     ///         ;; Define a core module that uses two memories.
557     ///         (core module $m
558     ///             (memory 1)
559     ///             (memory 6)
560     ///         )
561     ///
562     ///         ;; Instantiate that core module three times.
563     ///         (core instance $i1 (instantiate (module $m)))
564     ///         (core instance $i2 (instantiate (module $m)))
565     ///         (core instance $i3 (instantiate (module $m)))
566     ///     )
567     /// "#)?;
568     ///
569     /// let resources = component.resources_required()
570     ///     .expect("this component does not import any core modules or instances");
571     ///
572     /// // Instantiating the component will require allocating two memories per
573     /// // core instance, and there are three instances, so six total memories.
574     /// assert_eq!(resources.num_memories, 6);
575     /// assert_eq!(resources.max_initial_memory_size, Some(6));
576     ///
577     /// // The component doesn't need any tables.
578     /// assert_eq!(resources.num_tables, 0);
579     /// assert_eq!(resources.max_initial_table_size, None);
580     /// # Ok(()) }
581     /// ```
582     pub fn resources_required(&self) -> Option<ResourcesRequired> {
583         let mut resources = ResourcesRequired {
584             num_memories: 0,
585             max_initial_memory_size: None,
586             num_tables: 0,
587             max_initial_table_size: None,
588         };
589         for init in &self.env_component().initializers {
590             match init {
591                 GlobalInitializer::InstantiateModule(inst) => match inst {
592                     InstantiateModule::Static(index, _) => {
593                         let module = self.static_module(*index);
594                         resources.add(&module.resources_required());
595                     }
596                     InstantiateModule::Import(_, _) => {
597                         // We can't statically determine the resources required
598                         // to instantiate this component.
599                         return None;
600                     }
601                 },
602                 GlobalInitializer::LowerImport { .. }
603                 | GlobalInitializer::ExtractMemory(_)
604                 | GlobalInitializer::ExtractRealloc(_)
605                 | GlobalInitializer::ExtractPostReturn(_)
606                 | GlobalInitializer::Resource(_) => {}
607             }
608         }
609         Some(resources)
610     }
611 
612     /// Returns the range, in the host's address space, that this module's
613     /// compiled code resides at.
614     ///
615     /// For more information see
616     /// [`Module::image_range`](crate::Module::image_range).
617     pub fn image_range(&self) -> Range<*const u8> {
618         self.inner.code.code_memory().mmap().image_range()
619     }
620 
621     /// Force initialization of copy-on-write images to happen here-and-now
622     /// instead of when they're requested during first instantiation.
623     ///
624     /// When [copy-on-write memory
625     /// initialization](crate::Config::memory_init_cow) is enabled then Wasmtime
626     /// will lazily create the initialization image for a component. This method
627     /// can be used to explicitly dictate when this initialization happens.
628     ///
629     /// Note that this largely only matters on Linux when memfd is used.
630     /// Otherwise the copy-on-write image typically comes from disk and in that
631     /// situation the creation of the image is trivial as the image is always
632     /// sourced from disk. On Linux, though, when memfd is used a memfd is
633     /// created and the initialization image is written to it.
634     ///
635     /// Also note that this method is not required to be called, it's available
636     /// as a performance optimization if required but is otherwise handled
637     /// automatically.
638     pub fn initialize_copy_on_write_image(&self) -> Result<()> {
639         for (_, module) in self.inner.static_modules.iter() {
640             module.initialize_copy_on_write_image()?;
641         }
642         Ok(())
643     }
644 
645     /// Looks up a specific export of this component by `name` optionally nested
646     /// within the `instance` provided.
647     ///
648     /// This method is primarily used to acquire a [`ComponentExportIndex`]
649     /// which can be used with [`Instance`](crate::component::Instance) when
650     /// looking up exports. Export lookup with [`ComponentExportIndex`] can
651     /// skip string lookups at runtime and instead use a more efficient
652     /// index-based lookup.
653     ///
654     /// This method takes a few arguments:
655     ///
656     /// * `engine` - the engine that was used to compile this component.
657     /// * `instance` - an optional "parent instance" for the export being looked
658     ///   up. If this is `None` then the export is looked up on the root of the
659     ///   component itself, and otherwise the export is looked up on the
660     ///   `instance` specified. Note that `instance` must have come from a
661     ///   previous invocation of this method.
662     /// * `name` - the name of the export that's being looked up.
663     ///
664     /// If the export is located then two values are returned: a
665     /// [`types::ComponentItem`] which enables introspection about the type of
666     /// the export and a [`ComponentExportIndex`]. The index returned notably
667     /// implements the [`InstanceExportLookup`] trait which enables using it
668     /// with [`Instance::get_func`](crate::component::Instance::get_func) for
669     /// example.
670     ///
671     /// # Examples
672     ///
673     /// ```
674     /// use wasmtime::{Engine, Store};
675     /// use wasmtime::component::{Component, Linker};
676     /// use wasmtime::component::types::ComponentItem;
677     ///
678     /// # fn main() -> wasmtime::Result<()> {
679     /// let engine = Engine::default();
680     /// let component = Component::new(
681     ///     &engine,
682     ///     r#"
683     ///         (component
684     ///             (core module $m
685     ///                 (func (export "f"))
686     ///             )
687     ///             (core instance $i (instantiate $m))
688     ///             (func (export "f")
689     ///                 (canon lift (core func $i "f")))
690     ///         )
691     ///     "#,
692     /// )?;
693     ///
694     /// // Perform a lookup of the function "f" before instantiaton.
695     /// let (ty, export) = component.export_index(None, "f").unwrap();
696     /// assert!(matches!(ty, ComponentItem::ComponentFunc(_)));
697     ///
698     /// // After instantiation use `export` to lookup the function in question
699     /// // which notably does not do a string lookup at runtime.
700     /// let mut store = Store::new(&engine, ());
701     /// let instance = Linker::new(&engine).instantiate(&mut store, &component)?;
702     /// let func = instance.get_typed_func::<(), ()>(&mut store, &export)?;
703     /// // ...
704     /// # Ok(())
705     /// # }
706     /// ```
707     pub fn export_index(
708         &self,
709         instance: Option<&ComponentExportIndex>,
710         name: &str,
711     ) -> Option<(types::ComponentItem, ComponentExportIndex)> {
712         let info = self.env_component();
713         let index = self.lookup_export_index(instance, name)?;
714         let ty = match info.export_items[index] {
715             Export::Instance { ty, .. } => TypeDef::ComponentInstance(ty),
716             Export::LiftedFunction { ty, .. } => TypeDef::ComponentFunc(ty),
717             Export::ModuleStatic { ty, .. } | Export::ModuleImport { ty, .. } => {
718                 TypeDef::Module(ty)
719             }
720             Export::Type(ty) => ty,
721         };
722         let item = self.with_uninstantiated_instance_type(|instance| {
723             types::ComponentItem::from(&self.inner.engine, &ty, instance)
724         });
725         Some((
726             item,
727             ComponentExportIndex {
728                 id: self.inner.id,
729                 index,
730             },
731         ))
732     }
733 
734     pub(crate) fn lookup_export_index(
735         &self,
736         instance: Option<&ComponentExportIndex>,
737         name: &str,
738     ) -> Option<ExportIndex> {
739         let info = self.env_component();
740         let exports = match instance {
741             Some(idx) => {
742                 if idx.id != self.inner.id {
743                     return None;
744                 }
745                 match &info.export_items[idx.index] {
746                     Export::Instance { exports, .. } => exports,
747                     _ => return None,
748                 }
749             }
750             None => &info.exports,
751         };
752         exports.get(name, &NameMapNoIntern).copied()
753     }
754 
755     pub(crate) fn id(&self) -> CompiledModuleId {
756         self.inner.id
757     }
758 
759     /// Returns the [`Engine`] that this [`Component`] was compiled by.
760     pub fn engine(&self) -> &Engine {
761         &self.inner.engine
762     }
763 }
764 
765 /// A value which represents a known export of a component.
766 ///
767 /// This is the return value of [`Component::export_index`] and implements the
768 /// [`InstanceExportLookup`] trait to work with lookups like
769 /// [`Instance::get_func`](crate::component::Instance::get_func).
770 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
771 pub struct ComponentExportIndex {
772     pub(crate) id: CompiledModuleId,
773     pub(crate) index: ExportIndex,
774 }
775 
776 impl InstanceExportLookup for ComponentExportIndex {
777     fn lookup(&self, component: &Component) -> Option<ExportIndex> {
778         if component.inner.id == self.id {
779             Some(self.index)
780         } else {
781             None
782         }
783     }
784 }
785 
786 impl ComponentRuntimeInfo for ComponentInner {
787     fn component(&self) -> &wasmtime_environ::component::Component {
788         &self.info.component
789     }
790 
791     fn component_types(&self) -> &Arc<ComponentTypes> {
792         match self.code.types() {
793             crate::code::Types::Component(types) => types,
794             // The only creator of a `Component` is itself which uses the other
795             // variant, so this shouldn't be possible.
796             crate::code::Types::Module(_) => unreachable!(),
797         }
798     }
799 
800     fn realloc_func_type(&self) -> &Arc<dyn Any + Send + Sync> {
801         &self.realloc_func_type
802     }
803 }
804 
805 #[cfg(test)]
806 mod tests {
807     use crate::component::Component;
808     use crate::{Config, Engine};
809     use wasmtime_environ::MemoryInitialization;
810 
811     #[test]
812     fn cow_on_by_default() {
813         let mut config = Config::new();
814         config.wasm_component_model(true);
815         let engine = Engine::new(&config).unwrap();
816         let component = Component::new(
817             &engine,
818             r#"
819                 (component
820                     (core module
821                         (memory 1)
822                         (data (i32.const 100) "abcd")
823                     )
824                 )
825             "#,
826         )
827         .unwrap();
828 
829         for (_, module) in component.inner.static_modules.iter() {
830             let init = &module.env_module().memory_initialization;
831             assert!(matches!(init, MemoryInitialization::Static { .. }));
832         }
833     }
834 }
835