1 use crate::linker::{Definition, DefinitionType};
2 use crate::prelude::*;
3 use crate::runtime::vm::{
4     Imports, InstanceAllocationRequest, ModuleRuntimeInfo, StorePtr, VMFuncRef, VMFunctionImport,
5     VMGlobalImport, VMMemoryImport, VMOpaqueContext, VMTable, VMTagImport,
6 };
7 use crate::store::{InstanceId, StoreOpaque, Stored};
8 use crate::types::matching;
9 use crate::{
10     AsContextMut, Engine, Export, Extern, Func, Global, Memory, Module, ModuleExport, SharedMemory,
11     StoreContext, StoreContextMut, Table, Tag, TypedFunc,
12 };
13 use alloc::sync::Arc;
14 use core::ptr::NonNull;
15 use wasmparser::WasmFeatures;
16 use wasmtime_environ::{
17     EntityIndex, EntityType, FuncIndex, GlobalIndex, MemoryIndex, PrimaryMap, TableIndex, TagIndex,
18     TypeTrace,
19 };
20 
21 /// An instantiated WebAssembly module.
22 ///
23 /// This type represents the instantiation of a [`Module`]. Once instantiated
24 /// you can access the [`exports`](Instance::exports) which are of type
25 /// [`Extern`] and provide the ability to call functions, set globals, read
26 /// memory, etc. When interacting with any wasm code you'll want to make an
27 /// [`Instance`] to call any code or execute anything.
28 ///
29 /// Instances are owned by a [`Store`](crate::Store) which is passed in at
30 /// creation time. It's recommended to create instances with
31 /// [`Linker::instantiate`](crate::Linker::instantiate) or similar
32 /// [`Linker`](crate::Linker) methods, but a more low-level constructor is also
33 /// available as [`Instance::new`].
34 #[derive(Copy, Clone, Debug)]
35 #[repr(transparent)]
36 pub struct Instance(Stored<InstanceData>);
37 
38 pub(crate) struct InstanceData {
39     /// The id of the instance within the store, used to find the original
40     /// `InstanceHandle`.
41     id: InstanceId,
42     /// A lazily-populated list of exports of this instance. The order of
43     /// exports here matches the order of the exports in the original
44     /// module.
45     exports: Vec<Option<Extern>>,
46 }
47 
48 impl InstanceData {
49     pub fn from_id(id: InstanceId) -> InstanceData {
50         InstanceData {
51             id,
52             exports: vec![],
53         }
54     }
55 }
56 
57 impl Instance {
58     /// Creates a new [`Instance`] from the previously compiled [`Module`] and
59     /// list of `imports` specified.
60     ///
61     /// This method instantiates the `module` provided with the `imports`,
62     /// following the procedure in the [core specification][inst] to
63     /// instantiate. Instantiation can fail for a number of reasons (many
64     /// specified below), but if successful the `start` function will be
65     /// automatically run (if specified in the `module`) and then the
66     /// [`Instance`] will be returned.
67     ///
68     /// Per the WebAssembly spec, instantiation includes running the module's
69     /// start function, if it has one (not to be confused with the `_start`
70     /// function, which is not run).
71     ///
72     /// Note that this is a low-level function that just performs an
73     /// instantiation. See the [`Linker`](crate::Linker) struct for an API which
74     /// provides a convenient way to link imports and provides automatic Command
75     /// and Reactor behavior.
76     ///
77     /// ## Providing Imports
78     ///
79     /// The entries in the list of `imports` are intended to correspond 1:1
80     /// with the list of imports returned by [`Module::imports`]. Before
81     /// calling [`Instance::new`] you'll want to inspect the return value of
82     /// [`Module::imports`] and, for each import type, create an [`Extern`]
83     /// which corresponds to that type.  These [`Extern`] values are all then
84     /// collected into a list and passed to this function.
85     ///
86     /// Note that this function is intentionally relatively low level. For an
87     /// easier time passing imports by doing name-based resolution it's
88     /// recommended to instead use the [`Linker`](crate::Linker) type.
89     ///
90     /// ## Errors
91     ///
92     /// This function can fail for a number of reasons, including, but not
93     /// limited to:
94     ///
95     /// * The number of `imports` provided doesn't match the number of imports
96     ///   returned by the `module`'s [`Module::imports`] method.
97     /// * The type of any [`Extern`] doesn't match the corresponding
98     ///   [`ExternType`] entry that it maps to.
99     /// * The `start` function in the instance, if present, traps.
100     /// * Module/instance resource limits are exceeded.
101     ///
102     /// When instantiation fails it's recommended to inspect the return value to
103     /// see why it failed, or bubble it upwards. If you'd like to specifically
104     /// check for trap errors, you can use `error.downcast::<Trap>()`. For more
105     /// about error handling see the [`Trap`] documentation.
106     ///
107     /// [`Trap`]: crate::Trap
108     ///
109     /// # Panics
110     ///
111     /// This function will panic if called with a store associated with a
112     /// [`asynchronous config`](crate::Config::async_support). This function
113     /// will also panic if any [`Extern`] supplied is not owned by `store`.
114     ///
115     /// [inst]: https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation
116     /// [`ExternType`]: crate::ExternType
117     pub fn new(
118         mut store: impl AsContextMut,
119         module: &Module,
120         imports: &[Extern],
121     ) -> Result<Instance> {
122         let mut store = store.as_context_mut();
123         let imports = Instance::typecheck_externs(store.0, module, imports)?;
124         // Note that the unsafety here should be satisfied by the call to
125         // `typecheck_externs` above which satisfies the condition that all
126         // the imports are valid for this module.
127         unsafe { Instance::new_started(&mut store, module, imports.as_ref()) }
128     }
129 
130     /// Same as [`Instance::new`], except for usage in [asynchronous stores].
131     ///
132     /// For more details about this function see the documentation on
133     /// [`Instance::new`]. The only difference between these two methods is that
134     /// this one will asynchronously invoke the wasm start function in case it
135     /// calls any imported function which is an asynchronous host function (e.g.
136     /// created with [`Func::new_async`](crate::Func::new_async).
137     ///
138     /// # Panics
139     ///
140     /// This function will panic if called with a store associated with a
141     /// [`synchronous config`](crate::Config::new). This is only compatible with
142     /// stores associated with an [`asynchronous
143     /// config`](crate::Config::async_support).
144     ///
145     /// This function will also panic, like [`Instance::new`], if any [`Extern`]
146     /// specified does not belong to `store`.
147     #[cfg(feature = "async")]
148     pub async fn new_async(
149         mut store: impl AsContextMut<Data: Send>,
150         module: &Module,
151         imports: &[Extern],
152     ) -> Result<Instance> {
153         let mut store = store.as_context_mut();
154         let imports = Instance::typecheck_externs(store.0, module, imports)?;
155         // See `new` for notes on this unsafety
156         unsafe { Instance::new_started_async(&mut store, module, imports.as_ref()).await }
157     }
158 
159     fn typecheck_externs(
160         store: &mut StoreOpaque,
161         module: &Module,
162         imports: &[Extern],
163     ) -> Result<OwnedImports> {
164         for import in imports {
165             if !import.comes_from_same_store(store) {
166                 bail!("cross-`Store` instantiation is not currently supported");
167             }
168         }
169         typecheck(module, imports, |cx, ty, item| {
170             let item = DefinitionType::from(store, item);
171             cx.definition(ty, &item)
172         })?;
173         let mut owned_imports = OwnedImports::new(module);
174         for import in imports {
175             owned_imports.push(import, store, module);
176         }
177         Ok(owned_imports)
178     }
179 
180     /// Internal function to create an instance and run the start function.
181     ///
182     /// This function's unsafety is the same as `Instance::new_raw`.
183     pub(crate) unsafe fn new_started<T>(
184         store: &mut StoreContextMut<'_, T>,
185         module: &Module,
186         imports: Imports<'_>,
187     ) -> Result<Instance> {
188         assert!(
189             !store.0.async_support(),
190             "must use async instantiation when async support is enabled",
191         );
192         Self::new_started_impl(store, module, imports)
193     }
194 
195     /// Internal function to create an instance and run the start function.
196     ///
197     /// ONLY CALL THIS IF YOU HAVE ALREADY CHECKED FOR ASYNCNESS AND HANDLED
198     /// THE FIBER NONSENSE
199     pub(crate) unsafe fn new_started_impl<T>(
200         store: &mut StoreContextMut<'_, T>,
201         module: &Module,
202         imports: Imports<'_>,
203     ) -> Result<Instance> {
204         let (instance, start) = Instance::new_raw(store.0, module, imports)?;
205         if let Some(start) = start {
206             instance.start_raw(store, start)?;
207         }
208         Ok(instance)
209     }
210 
211     /// Internal function to create an instance and run the start function.
212     ///
213     /// This function's unsafety is the same as `Instance::new_raw`.
214     #[cfg(feature = "async")]
215     async unsafe fn new_started_async<T>(
216         store: &mut StoreContextMut<'_, T>,
217         module: &Module,
218         imports: Imports<'_>,
219     ) -> Result<Instance>
220     where
221         T: Send + 'static,
222     {
223         assert!(
224             store.0.async_support(),
225             "must use sync instantiation when async support is disabled",
226         );
227 
228         store
229             .on_fiber(|store| Self::new_started_impl(store, module, imports))
230             .await?
231     }
232 
233     /// Internal function to create an instance which doesn't have its `start`
234     /// function run yet.
235     ///
236     /// This is not intended to be exposed from Wasmtime, it's intended to
237     /// refactor out common code from `new_started` and `new_started_async`.
238     ///
239     /// Note that this step needs to be run on a fiber in async mode even
240     /// though it doesn't do any blocking work because an async resource
241     /// limiter may need to yield.
242     ///
243     /// # Unsafety
244     ///
245     /// This method is unsafe because it does not type-check the `imports`
246     /// provided. The `imports` provided must be suitable for the module
247     /// provided as well.
248     unsafe fn new_raw(
249         store: &mut StoreOpaque,
250         module: &Module,
251         imports: Imports<'_>,
252     ) -> Result<(Instance, Option<FuncIndex>)> {
253         if !Engine::same(store.engine(), module.engine()) {
254             bail!("cross-`Engine` instantiation is not currently supported");
255         }
256         store.bump_resource_counts(module)?;
257 
258         // Allocate the GC heap, if necessary.
259         if module.env_module().needs_gc_heap {
260             let _ = store.gc_store_mut()?;
261         }
262 
263         let compiled_module = module.compiled_module();
264 
265         // Register the module just before instantiation to ensure we keep the module
266         // properly referenced while in use by the store.
267         let module_id = store.modules_mut().register_module(module);
268         store.fill_func_refs();
269 
270         // The first thing we do is issue an instance allocation request
271         // to the instance allocator. This, on success, will give us an
272         // instance handle.
273         //
274         // Note that the `host_state` here is a pointer back to the
275         // `Instance` we'll be returning from this function. This is a
276         // circular reference so we can't construct it before we construct
277         // this instance, so we determine what the ID is and then assert
278         // it's the same later when we do actually insert it.
279         let instance_to_be = store.store_data().next_id::<InstanceData>();
280 
281         let mut instance_handle =
282             store
283                 .engine()
284                 .allocator()
285                 .allocate_module(InstanceAllocationRequest {
286                     runtime_info: &ModuleRuntimeInfo::Module(module.clone()),
287                     imports,
288                     host_state: Box::new(Instance(instance_to_be)),
289                     store: StorePtr::new(store.traitobj()),
290                     wmemcheck: store.engine().config().wmemcheck,
291                     pkey: store.get_pkey(),
292                     tunables: store.engine().tunables(),
293                 })?;
294 
295         // The instance still has lots of setup, for example
296         // data/elements/start/etc. This can all fail, but even on failure
297         // the instance may persist some state via previous successful
298         // initialization. For this reason once we have an instance handle
299         // we immediately insert it into the store to keep it alive.
300         //
301         // Note that we `clone` the instance handle just to make easier
302         // working the borrow checker here easier. Technically the `&mut
303         // instance` has somewhat of a borrow on `store` (which
304         // conflicts with the borrow on `store.engine`) but this doesn't
305         // matter in practice since initialization isn't even running any
306         // code here anyway.
307         let id = store.add_instance(instance_handle.clone(), module_id);
308 
309         // Additionally, before we start doing fallible instantiation, we
310         // do one more step which is to insert an `InstanceData`
311         // corresponding to this instance. This `InstanceData` can be used
312         // via `Caller::get_export` if our instance's state "leaks" into
313         // other instances, even if we don't return successfully from this
314         // function.
315         //
316         // We don't actually load all exports from the instance at this
317         // time, instead preferring to lazily load them as they're demanded.
318         // For module/instance exports, though, those aren't actually
319         // stored in the instance handle so we need to immediately handle
320         // those here.
321         let instance = {
322             let exports = vec![None; compiled_module.module().exports.len()];
323             let data = InstanceData { id, exports };
324             Instance::from_wasmtime(data, store)
325         };
326 
327         // double-check our guess of what the new instance's ID would be
328         // was actually correct.
329         assert_eq!(instance.0, instance_to_be);
330 
331         // Now that we've recorded all information we need to about this
332         // instance within a `Store` we can start performing fallible
333         // initialization. Note that we still defer the `start` function to
334         // later since that may need to run asynchronously.
335         //
336         // If this returns an error (or if the start function traps) then
337         // any other initialization which may have succeeded which placed
338         // items from this instance into other instances should be ok when
339         // those items are loaded and run we'll have all the metadata to
340         // look at them.
341         let bulk_memory = store
342             .engine()
343             .features()
344             .contains(WasmFeatures::BULK_MEMORY);
345         instance_handle.initialize(store, compiled_module.module(), bulk_memory)?;
346 
347         Ok((instance, compiled_module.module().start_func))
348     }
349 
350     pub(crate) fn from_wasmtime(handle: InstanceData, store: &mut StoreOpaque) -> Instance {
351         Instance(store.store_data_mut().insert(handle))
352     }
353 
354     fn start_raw<T>(&self, store: &mut StoreContextMut<'_, T>, start: FuncIndex) -> Result<()> {
355         let id = store.0.store_data()[self.0].id;
356         // If a start function is present, invoke it. Make sure we use all the
357         // trap-handling configuration in `store` as well.
358         let instance = store.0.instance_mut(id);
359         let f = instance.get_exported_func(start);
360         let caller_vmctx = instance.vmctx();
361         unsafe {
362             super::func::invoke_wasm_and_catch_traps(store, |_default_caller, vm| {
363                 f.func_ref.as_ref().array_call(
364                     vm,
365                     VMOpaqueContext::from_vmcontext(caller_vmctx),
366                     NonNull::from(&mut []),
367                 )
368             })?;
369         }
370         Ok(())
371     }
372 
373     /// Get this instance's module.
374     pub fn module<'a, T: 'static>(&self, store: impl Into<StoreContext<'a, T>>) -> &'a Module {
375         self._module(store.into().0)
376     }
377 
378     fn _module<'a>(&self, store: &'a StoreOpaque) -> &'a Module {
379         let InstanceData { id, .. } = store[self.0];
380         store.module_for_instance(id).unwrap()
381     }
382 
383     /// Returns the list of exported items from this [`Instance`].
384     ///
385     /// # Panics
386     ///
387     /// Panics if `store` does not own this instance.
388     pub fn exports<'a, T: 'static>(
389         &'a self,
390         store: impl Into<StoreContextMut<'a, T>>,
391     ) -> impl ExactSizeIterator<Item = Export<'a>> + 'a {
392         self._exports(store.into().0)
393     }
394 
395     fn _exports<'a>(
396         &'a self,
397         store: &'a mut StoreOpaque,
398     ) -> impl ExactSizeIterator<Item = Export<'a>> + 'a {
399         // If this is an `Instantiated` instance then all the `exports` may not
400         // be filled in. Fill them all in now if that's the case.
401         let InstanceData { exports, id, .. } = &store[self.0];
402         if exports.iter().any(|e| e.is_none()) {
403             let module = Arc::clone(store.instance(*id).module());
404             let data = &store[self.0];
405             let id = data.id;
406 
407             for name in module.exports.keys() {
408                 let instance = store.instance(id);
409                 if let Some((export_name_index, _, &entity)) =
410                     instance.module().exports.get_full(name)
411                 {
412                     self._get_export(store, entity, export_name_index);
413                 }
414             }
415         }
416 
417         let data = &store.store_data()[self.0];
418         let module = store.instance(data.id).module();
419         module
420             .exports
421             .iter()
422             .zip(&data.exports)
423             .map(|((name, _), export)| Export::new(name, export.clone().unwrap()))
424     }
425 
426     /// Looks up an exported [`Extern`] value by name.
427     ///
428     /// This method will search the module for an export named `name` and return
429     /// the value, if found.
430     ///
431     /// Returns `None` if there was no export named `name`.
432     ///
433     /// # Panics
434     ///
435     /// Panics if `store` does not own this instance.
436     ///
437     /// # Why does `get_export` take a mutable context?
438     ///
439     /// This method requires a mutable context because an instance's exports are
440     /// lazily populated, and we cache them as they are accessed. This makes
441     /// instantiating a module faster, but also means this method requires a
442     /// mutable context.
443     pub fn get_export(&self, mut store: impl AsContextMut, name: &str) -> Option<Extern> {
444         let store = store.as_context_mut().0;
445         let data = &store[self.0];
446         let instance = store.instance(data.id);
447         let (export_name_index, _, &entity) = instance.module().exports.get_full(name)?;
448         self._get_export(store, entity, export_name_index)
449     }
450 
451     /// Looks up an exported [`Extern`] value by a [`ModuleExport`] value.
452     ///
453     /// This is similar to [`Instance::get_export`] but uses a [`ModuleExport`] value to avoid
454     /// string lookups where possible. [`ModuleExport`]s can be obtained by calling
455     /// [`Module::get_export_index`] on the [`Module`] that this instance was instantiated with.
456     ///
457     /// This method will search the module for an export with a matching entity index and return
458     /// the value, if found.
459     ///
460     /// Returns `None` if there was no export with a matching entity index.
461     /// # Panics
462     ///
463     /// Panics if `store` does not own this instance.
464     pub fn get_module_export(
465         &self,
466         mut store: impl AsContextMut,
467         export: &ModuleExport,
468     ) -> Option<Extern> {
469         let store = store.as_context_mut().0;
470 
471         // Verify the `ModuleExport` matches the module used in this instance.
472         if self._module(store).id() != export.module {
473             return None;
474         }
475 
476         self._get_export(store, export.entity, export.export_name_index)
477     }
478 
479     fn _get_export(
480         &self,
481         store: &mut StoreOpaque,
482         entity: EntityIndex,
483         export_name_index: usize,
484     ) -> Option<Extern> {
485         // Instantiated instances will lazily fill in exports, so we process
486         // all that lazy logic here.
487         let data = &store[self.0];
488 
489         if let Some(export) = &data.exports[export_name_index] {
490             return Some(export.clone());
491         }
492 
493         let instance = store.instance_mut(data.id); // Reborrow the &mut InstanceHandle
494         let item =
495             unsafe { Extern::from_wasmtime_export(instance.get_export_by_index(entity), store) };
496         let data = &mut store[self.0];
497         data.exports[export_name_index] = Some(item.clone());
498         Some(item)
499     }
500 
501     /// Looks up an exported [`Func`] value by name.
502     ///
503     /// Returns `None` if there was no export named `name`, or if there was but
504     /// it wasn't a function.
505     ///
506     /// # Panics
507     ///
508     /// Panics if `store` does not own this instance.
509     pub fn get_func(&self, store: impl AsContextMut, name: &str) -> Option<Func> {
510         self.get_export(store, name)?.into_func()
511     }
512 
513     /// Looks up an exported [`Func`] value by name and with its type.
514     ///
515     /// This function is a convenience wrapper over [`Instance::get_func`] and
516     /// [`Func::typed`]. For more information see the linked documentation.
517     ///
518     /// Returns an error if `name` isn't a function export or if the export's
519     /// type did not match `Params` or `Results`
520     ///
521     /// # Panics
522     ///
523     /// Panics if `store` does not own this instance.
524     pub fn get_typed_func<Params, Results>(
525         &self,
526         mut store: impl AsContextMut,
527         name: &str,
528     ) -> Result<TypedFunc<Params, Results>>
529     where
530         Params: crate::WasmParams,
531         Results: crate::WasmResults,
532     {
533         let f = self
534             .get_export(store.as_context_mut(), name)
535             .and_then(|f| f.into_func())
536             .ok_or_else(|| anyhow!("failed to find function export `{}`", name))?;
537         Ok(f.typed::<Params, Results>(store)
538             .with_context(|| format!("failed to convert function `{name}` to given type"))?)
539     }
540 
541     /// Looks up an exported [`Table`] value by name.
542     ///
543     /// Returns `None` if there was no export named `name`, or if there was but
544     /// it wasn't a table.
545     ///
546     /// # Panics
547     ///
548     /// Panics if `store` does not own this instance.
549     pub fn get_table(&self, store: impl AsContextMut, name: &str) -> Option<Table> {
550         self.get_export(store, name)?.into_table()
551     }
552 
553     /// Looks up an exported [`Memory`] value by name.
554     ///
555     /// Returns `None` if there was no export named `name`, or if there was but
556     /// it wasn't a memory.
557     ///
558     /// # Panics
559     ///
560     /// Panics if `store` does not own this instance.
561     pub fn get_memory(&self, store: impl AsContextMut, name: &str) -> Option<Memory> {
562         self.get_export(store, name)?.into_memory()
563     }
564 
565     /// Looks up an exported [`SharedMemory`] value by name.
566     ///
567     /// Returns `None` if there was no export named `name`, or if there was but
568     /// it wasn't a shared memory.
569     ///
570     /// # Panics
571     ///
572     /// Panics if `store` does not own this instance.
573     pub fn get_shared_memory(
574         &self,
575         mut store: impl AsContextMut,
576         name: &str,
577     ) -> Option<SharedMemory> {
578         let mut store = store.as_context_mut();
579         self.get_export(&mut store, name)?.into_shared_memory()
580     }
581 
582     /// Looks up an exported [`Global`] value by name.
583     ///
584     /// Returns `None` if there was no export named `name`, or if there was but
585     /// it wasn't a global.
586     ///
587     /// # Panics
588     ///
589     /// Panics if `store` does not own this instance.
590     pub fn get_global(&self, store: impl AsContextMut, name: &str) -> Option<Global> {
591         self.get_export(store, name)?.into_global()
592     }
593 
594     /// Looks up a tag [`Tag`] by name.
595     ///
596     /// Returns `None` if there was no export named `name`, or if there was but
597     /// it wasn't a tag.
598     ///
599     /// # Panics
600     ///
601     /// Panics if `store` does not own this instance.
602     pub fn get_tag(&self, store: impl AsContextMut, name: &str) -> Option<Tag> {
603         self.get_export(store, name)?.into_tag()
604     }
605 
606     #[cfg(feature = "component-model")]
607     pub(crate) fn id(&self, store: &StoreOpaque) -> InstanceId {
608         store[self.0].id
609     }
610 
611     /// Get all globals within this instance.
612     ///
613     /// Returns both import and defined globals.
614     ///
615     /// Returns both exported and non-exported globals.
616     ///
617     /// Gives access to the full globals space.
618     #[cfg(feature = "coredump")]
619     pub(crate) fn all_globals<'a>(
620         &'a self,
621         store: &'a mut StoreOpaque,
622     ) -> impl ExactSizeIterator<Item = (GlobalIndex, Global)> + 'a {
623         let data = &store[self.0];
624         let instance = store.instance_mut(data.id);
625         instance
626             .all_globals()
627             .collect::<Vec<_>>()
628             .into_iter()
629             .map(|(i, g)| (i, unsafe { Global::from_wasmtime_global(g, store) }))
630     }
631 
632     /// Get all memories within this instance.
633     ///
634     /// Returns both import and defined memories.
635     ///
636     /// Returns both exported and non-exported memories.
637     ///
638     /// Gives access to the full memories space.
639     #[cfg(feature = "coredump")]
640     pub(crate) fn all_memories<'a>(
641         &'a self,
642         store: &'a mut StoreOpaque,
643     ) -> impl ExactSizeIterator<Item = (MemoryIndex, Memory)> + 'a {
644         let data = &store[self.0];
645         let instance = store.instance_mut(data.id);
646         instance
647             .all_memories()
648             .collect::<Vec<_>>()
649             .into_iter()
650             .map(|(i, m)| (i, unsafe { Memory::from_wasmtime_memory(m, store) }))
651     }
652 }
653 
654 pub(crate) struct OwnedImports {
655     functions: PrimaryMap<FuncIndex, VMFunctionImport>,
656     tables: PrimaryMap<TableIndex, VMTable>,
657     memories: PrimaryMap<MemoryIndex, VMMemoryImport>,
658     globals: PrimaryMap<GlobalIndex, VMGlobalImport>,
659     tags: PrimaryMap<TagIndex, VMTagImport>,
660 }
661 
662 impl OwnedImports {
663     fn new(module: &Module) -> OwnedImports {
664         let mut ret = OwnedImports::empty();
665         ret.reserve(module);
666         return ret;
667     }
668 
669     pub(crate) fn empty() -> OwnedImports {
670         OwnedImports {
671             functions: PrimaryMap::new(),
672             tables: PrimaryMap::new(),
673             memories: PrimaryMap::new(),
674             globals: PrimaryMap::new(),
675             tags: PrimaryMap::new(),
676         }
677     }
678 
679     pub(crate) fn reserve(&mut self, module: &Module) {
680         let raw = module.compiled_module().module();
681         self.functions.reserve(raw.num_imported_funcs);
682         self.tables.reserve(raw.num_imported_tables);
683         self.memories.reserve(raw.num_imported_memories);
684         self.globals.reserve(raw.num_imported_globals);
685         self.tags.reserve(raw.num_imported_tags);
686     }
687 
688     #[cfg(feature = "component-model")]
689     pub(crate) fn clear(&mut self) {
690         self.functions.clear();
691         self.tables.clear();
692         self.memories.clear();
693         self.globals.clear();
694         self.tags.clear();
695     }
696 
697     fn push(&mut self, item: &Extern, store: &mut StoreOpaque, module: &Module) {
698         match item {
699             Extern::Func(i) => {
700                 self.functions.push(i.vmimport(store, module));
701             }
702             Extern::Global(i) => {
703                 self.globals.push(i.vmimport(store));
704             }
705             Extern::Table(i) => {
706                 self.tables.push(i.vmimport(store));
707             }
708             Extern::Memory(i) => {
709                 self.memories.push(i.vmimport(store));
710             }
711             Extern::SharedMemory(i) => {
712                 self.memories.push(i.vmimport(store));
713             }
714             Extern::Tag(i) => {
715                 self.tags.push(i.vmimport(store));
716             }
717         }
718     }
719 
720     /// Note that this is unsafe as the validity of `item` is not verified and
721     /// it contains a bunch of raw pointers.
722     #[cfg(feature = "component-model")]
723     pub(crate) unsafe fn push_export(&mut self, item: &crate::runtime::vm::Export) {
724         match item {
725             crate::runtime::vm::Export::Function(f) => {
726                 let f = f.func_ref.as_ref();
727                 self.functions.push(VMFunctionImport {
728                     wasm_call: f.wasm_call.unwrap(),
729                     array_call: f.array_call,
730                     vmctx: f.vmctx,
731                 });
732             }
733             crate::runtime::vm::Export::Global(g) => {
734                 self.globals.push(VMGlobalImport {
735                     from: g.definition.into(),
736                 });
737             }
738             crate::runtime::vm::Export::Table(t) => {
739                 self.tables.push(VMTable {
740                     from: t.definition.into(),
741                     vmctx: t.vmctx.into(),
742                 });
743             }
744             crate::runtime::vm::Export::Memory(m) => {
745                 self.memories.push(VMMemoryImport {
746                     from: m.definition.into(),
747                     vmctx: m.vmctx.into(),
748                     index: m.index,
749                 });
750             }
751             crate::runtime::vm::Export::Tag(t) => {
752                 self.tags.push(VMTagImport {
753                     from: t.definition.into(),
754                 });
755             }
756         }
757     }
758 
759     pub(crate) fn as_ref(&self) -> Imports<'_> {
760         Imports {
761             tables: self.tables.values().as_slice(),
762             globals: self.globals.values().as_slice(),
763             memories: self.memories.values().as_slice(),
764             functions: self.functions.values().as_slice(),
765             tags: self.tags.values().as_slice(),
766         }
767     }
768 }
769 
770 /// An instance, pre-instantiation, that is ready to be instantiated.
771 ///
772 /// This structure represents an instance *just before* it was instantiated,
773 /// after all type-checking and imports have been resolved. The only thing left
774 /// to do for this instance is to actually run the process of instantiation.
775 ///
776 /// Note that an `InstancePre` may not be tied to any particular [`Store`] if
777 /// none of the imports it closed over are tied to any particular [`Store`].
778 ///
779 /// This structure is created through the [`Linker::instantiate_pre`] method,
780 /// which also has some more information and examples.
781 ///
782 /// [`Store`]: crate::Store
783 /// [`Linker::instantiate_pre`]: crate::Linker::instantiate_pre
784 pub struct InstancePre<T> {
785     module: Module,
786 
787     /// The items which this `InstancePre` use to instantiate the `module`
788     /// provided, passed to `Instance::new_started` after inserting them into a
789     /// `Store`.
790     ///
791     /// Note that this is stored as an `Arc<[T]>` to quickly move a strong
792     /// reference to everything internally into a `Store<T>` without having to
793     /// clone each individual item.
794     items: Arc<[Definition]>,
795 
796     /// A count of `Definition::HostFunc` entries in `items` above to
797     /// preallocate space in a `Store` up front for all entries to be inserted.
798     host_funcs: usize,
799 
800     /// The `VMFuncRef`s for the functions in `items` that do not
801     /// have a `wasm_call` trampoline. We pre-allocate and pre-patch these
802     /// `VMFuncRef`s so that we don't have to do it at
803     /// instantiation time.
804     ///
805     /// This is an `Arc<[T]>` for the same reason as `items`.
806     func_refs: Arc<[VMFuncRef]>,
807 
808     _marker: core::marker::PhantomData<fn() -> T>,
809 }
810 
811 /// InstancePre's clone does not require T: Clone
812 impl<T> Clone for InstancePre<T> {
813     fn clone(&self) -> Self {
814         Self {
815             module: self.module.clone(),
816             items: self.items.clone(),
817             host_funcs: self.host_funcs,
818             func_refs: self.func_refs.clone(),
819             _marker: self._marker,
820         }
821     }
822 }
823 
824 impl<T: 'static> InstancePre<T> {
825     /// Creates a new `InstancePre` which type-checks the `items` provided and
826     /// on success is ready to instantiate a new instance.
827     ///
828     /// # Unsafety
829     ///
830     /// This method is unsafe as the `T` of the `InstancePre<T>` is not
831     /// guaranteed to be the same as the `T` within the `Store`, the caller must
832     /// verify that.
833     pub(crate) unsafe fn new(module: &Module, items: Vec<Definition>) -> Result<InstancePre<T>> {
834         typecheck(module, &items, |cx, ty, item| cx.definition(ty, &item.ty()))?;
835 
836         let mut func_refs = vec![];
837         let mut host_funcs = 0;
838         for item in &items {
839             match item {
840                 Definition::Extern(_, _) => {}
841                 Definition::HostFunc(f) => {
842                     host_funcs += 1;
843                     if f.func_ref().wasm_call.is_none() {
844                         // `f` needs its `VMFuncRef::wasm_call` patched with a
845                         // Wasm-to-native trampoline.
846                         debug_assert!(matches!(f.host_ctx(), crate::HostContext::Array(_)));
847                         func_refs.push(VMFuncRef {
848                             wasm_call: module
849                                 .wasm_to_array_trampoline(f.sig_index())
850                                 .map(|f| f.into()),
851                             ..*f.func_ref()
852                         });
853                     }
854                 }
855             }
856         }
857 
858         Ok(InstancePre {
859             module: module.clone(),
860             items: items.into(),
861             host_funcs,
862             func_refs: func_refs.into(),
863             _marker: core::marker::PhantomData,
864         })
865     }
866 
867     /// Returns a reference to the module that this [`InstancePre`] will be
868     /// instantiating.
869     pub fn module(&self) -> &Module {
870         &self.module
871     }
872 
873     /// Instantiates this instance, creating a new instance within the provided
874     /// `store`.
875     ///
876     /// This function will run the actual process of instantiation to
877     /// completion. This will use all of the previously-closed-over items as
878     /// imports to instantiate the module that this was originally created with.
879     ///
880     /// For more information about instantiation see [`Instance::new`].
881     ///
882     /// # Panics
883     ///
884     /// Panics if any import closed over by this [`InstancePre`] isn't owned by
885     /// `store`, or if `store` has async support enabled. Additionally this
886     /// function will panic if the `store` provided comes from a different
887     /// [`Engine`] than the [`InstancePre`] originally came from.
888     pub fn instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> {
889         let mut store = store.as_context_mut();
890         let imports = pre_instantiate_raw(
891             &mut store.0,
892             &self.module,
893             &self.items,
894             self.host_funcs,
895             &self.func_refs,
896         )?;
897 
898         // This unsafety should be handled by the type-checking performed by the
899         // constructor of `InstancePre` to assert that all the imports we're passing
900         // in match the module we're instantiating.
901         unsafe { Instance::new_started(&mut store, &self.module, imports.as_ref()) }
902     }
903 
904     /// Creates a new instance, running the start function asynchronously
905     /// instead of inline.
906     ///
907     /// For more information about asynchronous instantiation see the
908     /// documentation on [`Instance::new_async`].
909     ///
910     /// # Panics
911     ///
912     /// Panics if any import closed over by this [`InstancePre`] isn't owned by
913     /// `store`, or if `store` does not have async support enabled.
914     #[cfg(feature = "async")]
915     pub async fn instantiate_async(
916         &self,
917         mut store: impl AsContextMut<Data: Send>,
918     ) -> Result<Instance> {
919         let mut store = store.as_context_mut();
920         let imports = pre_instantiate_raw(
921             &mut store.0,
922             &self.module,
923             &self.items,
924             self.host_funcs,
925             &self.func_refs,
926         )?;
927 
928         // This unsafety should be handled by the type-checking performed by the
929         // constructor of `InstancePre` to assert that all the imports we're passing
930         // in match the module we're instantiating.
931         unsafe { Instance::new_started_async(&mut store, &self.module, imports.as_ref()).await }
932     }
933 }
934 
935 /// Helper function shared between
936 /// `InstancePre::{instantiate,instantiate_async}`
937 ///
938 /// This is an out-of-line function to avoid the generic on `InstancePre` and
939 /// get this compiled into the `wasmtime` crate to avoid having it monomorphized
940 /// elsewhere.
941 fn pre_instantiate_raw(
942     store: &mut StoreOpaque,
943     module: &Module,
944     items: &Arc<[Definition]>,
945     host_funcs: usize,
946     func_refs: &Arc<[VMFuncRef]>,
947 ) -> Result<OwnedImports> {
948     if host_funcs > 0 {
949         // Any linker-defined function of the `Definition::HostFunc` variant
950         // will insert a function into the store automatically as part of
951         // instantiation, so reserve space here to make insertion more efficient
952         // as it won't have to realloc during the instantiation.
953         store.store_data_mut().reserve_funcs(host_funcs);
954 
955         // The usage of `to_extern_store_rooted` requires that the items are
956         // rooted via another means, which happens here by cloning the list of
957         // items into the store once. This avoids cloning each individual item
958         // below.
959         store.push_rooted_funcs(items.clone());
960         store.push_instance_pre_func_refs(func_refs.clone());
961     }
962 
963     let mut func_refs = func_refs.iter().map(|f| NonNull::from(f));
964     let mut imports = OwnedImports::new(module);
965     for import in items.iter() {
966         if !import.comes_from_same_store(store) {
967             bail!("cross-`Store` instantiation is not currently supported");
968         }
969         // This unsafety should be encapsulated in the constructor of
970         // `InstancePre` where the `T` of the original item should match the
971         // `T` of the store. Additionally the rooting necessary has happened
972         // above.
973         let item = match import {
974             Definition::Extern(e, _) => e.clone(),
975             Definition::HostFunc(func) => unsafe {
976                 func.to_func_store_rooted(
977                     store,
978                     if func.func_ref().wasm_call.is_none() {
979                         Some(func_refs.next().unwrap())
980                     } else {
981                         None
982                     },
983                 )
984                 .into()
985             },
986         };
987         imports.push(&item, store, module);
988     }
989 
990     Ok(imports)
991 }
992 
993 fn typecheck<I>(
994     module: &Module,
995     import_args: &[I],
996     check: impl Fn(&matching::MatchCx<'_>, &EntityType, &I) -> Result<()>,
997 ) -> Result<()> {
998     let env_module = module.compiled_module().module();
999     let expected_len = env_module.imports().count();
1000     let actual_len = import_args.len();
1001     if expected_len != actual_len {
1002         bail!("expected {expected_len} imports, found {actual_len}");
1003     }
1004     let cx = matching::MatchCx::new(module.engine());
1005     for ((name, field, expected_ty), actual) in env_module.imports().zip(import_args) {
1006         debug_assert!(expected_ty.is_canonicalized_for_runtime_usage());
1007         check(&cx, &expected_ty, actual)
1008             .with_context(|| format!("incompatible import type for `{name}::{field}`"))?;
1009     }
1010     Ok(())
1011 }
1012