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