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