Skip to main content

wasmtime/runtime/
instance.rs

1use crate::linker::{Definition, DefinitionType};
2use crate::prelude::*;
3use crate::runtime::vm::{
4    self, Imports, ModuleRuntimeInfo, VMFuncRef, VMFunctionImport, VMGlobalImport, VMMemoryImport,
5    VMStore, VMTableImport, VMTagImport,
6};
7use crate::store::{
8    AllocateInstanceKind, Asyncness, InstanceId, StoreInstanceId, StoreOpaque, StoreResourceLimiter,
9};
10use crate::types::matching;
11use crate::{
12    AsContextMut, Engine, Export, Extern, Func, Global, Memory, Module, ModuleExport, SharedMemory,
13    StoreContext, StoreContextMut, Table, Tag, TypedFunc,
14};
15use alloc::sync::Arc;
16use core::ptr::NonNull;
17use wasmtime_environ::{
18    EntityIndex, EntityType, FuncIndex, GlobalIndex, MemoryIndex, TableIndex, TagIndex, 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, PartialEq, Eq)]
35#[repr(C)]
36pub struct Instance {
37    pub(crate) id: StoreInstanceId,
38}
39
40// Double-check that the C representation in `instance.h` matches our in-Rust
41// representation here in terms of size/alignment/etc.
42const _: () = {
43    #[repr(C)]
44    struct C(u64, usize);
45    assert!(core::mem::size_of::<C>() == core::mem::size_of::<Instance>());
46    assert!(core::mem::align_of::<C>() == core::mem::align_of::<Instance>());
47    assert!(core::mem::offset_of!(Instance, id) == 0);
48};
49
50impl Instance {
51    /// Creates a new [`Instance`] from the previously compiled [`Module`] and
52    /// list of `imports` specified.
53    ///
54    /// This method instantiates the `module` provided with the `imports`,
55    /// following the procedure in the [core specification][inst] to
56    /// instantiate. Instantiation can fail for a number of reasons (many
57    /// specified below), but if successful the `start` function will be
58    /// automatically run (if specified in the `module`) and then the
59    /// [`Instance`] will be returned.
60    ///
61    /// Per the WebAssembly spec, instantiation includes running the module's
62    /// start function, if it has one (not to be confused with the `_start`
63    /// function, which is not run).
64    ///
65    /// Note that this is a low-level function that just performs an
66    /// instantiation. See the [`Linker`](crate::Linker) struct for an API which
67    /// provides a convenient way to link imports and provides automatic Command
68    /// and Reactor behavior.
69    ///
70    /// ## Providing Imports
71    ///
72    /// The entries in the list of `imports` are intended to correspond 1:1
73    /// with the list of imports returned by [`Module::imports`]. Before
74    /// calling [`Instance::new`] you'll want to inspect the return value of
75    /// [`Module::imports`] and, for each import type, create an [`Extern`]
76    /// which corresponds to that type.  These [`Extern`] values are all then
77    /// collected into a list and passed to this function.
78    ///
79    /// Note that this function is intentionally relatively low level. For an
80    /// easier time passing imports by doing name-based resolution it's
81    /// recommended to instead use the [`Linker`](crate::Linker) type.
82    ///
83    /// ## Errors
84    ///
85    /// This function can fail for a number of reasons, including, but not
86    /// limited to:
87    ///
88    /// * The number of `imports` provided doesn't match the number of imports
89    ///   returned by the `module`'s [`Module::imports`] method.
90    /// * The type of any [`Extern`] doesn't match the corresponding
91    ///   [`ExternType`] entry that it maps to.
92    /// * The `start` function in the instance, if present, traps.
93    /// * Module/instance resource limits are exceeded.
94    /// * The `store` provided requires the use of [`Instance::new_async`]
95    ///   instead, such as if epochs or fuel are configured.
96    ///
97    /// When instantiation fails it's recommended to inspect the return value to
98    /// see why it failed, or bubble it upwards. If you'd like to specifically
99    /// check for trap errors, you can use `error.downcast::<Trap>()`. For more
100    /// about error handling see the [`Trap`] documentation.
101    ///
102    /// [`Trap`]: crate::Trap
103    ///
104    /// # Panics
105    ///
106    /// This function will panic if any [`Extern`] supplied is not owned by
107    /// `store`.
108    ///
109    /// [inst]: https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation
110    /// [`ExternType`]: crate::ExternType
111    ///
112    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
113    /// memory allocation fails. See the `OutOfMemory` type's documentation for
114    /// details on Wasmtime's out-of-memory handling.
115    pub fn new(
116        mut store: impl AsContextMut,
117        module: &Module,
118        imports: &[Extern],
119    ) -> Result<Instance> {
120        let mut store = store.as_context_mut();
121        store.0.validate_sync_call()?;
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        vm::assert_ready(unsafe {
127            Instance::new_started(&mut store, module, imports.as_ref(), Asyncness::No)
128        })
129    }
130
131    /// Same as [`Instance::new`], except for usage in [asynchronous stores].
132    ///
133    /// For more details about this function see the documentation on
134    /// [`Instance::new`]. The only difference between these two methods is that
135    /// this one will asynchronously invoke the wasm start function in case it
136    /// calls any imported function which is an asynchronous host function (e.g.
137    /// created with [`Func::new_async`](crate::Func::new_async).
138    ///
139    /// # Panics
140    ///
141    /// This function will panic, like [`Instance::new`], if any [`Extern`]
142    /// specified does not belong to `store`.
143    ///
144    /// # Examples
145    ///
146    /// An example of using this function:
147    ///
148    /// ```
149    /// use wasmtime::{Result, Store, Engine, Module, Instance};
150    ///
151    /// #[tokio::main]
152    /// async fn main() -> Result<()> {
153    ///     let engine = Engine::default();
154    ///
155    ///     // For this example, a module with no imports is being used hence
156    ///     // the empty array to `Instance::new_async`.
157    ///     let module = Module::new(&engine, "(module)")?;
158    ///     let mut store = Store::new(&engine, ());
159    ///     let instance = Instance::new_async(&mut store, &module, &[]).await?;
160    ///
161    ///     // ... use `instance` and exports and such ...
162    ///
163    ///     Ok(())
164    /// }
165    /// ```
166    ///
167    /// Note, though, that the future returned from this function is only
168    /// `Send` if the store's own data is `Send` meaning that this does not
169    /// compile for example:
170    ///
171    /// ```compile_fail
172    /// use wasmtime::{Result, Store, Engine, Module, Instance};
173    /// use std::rc::Rc;
174    ///
175    /// #[tokio::main]
176    /// async fn main() -> Result<()> {
177    ///     let engine = Engine::default();
178    ///
179    ///     let module = Module::new(&engine, "(module)")?;
180    ///
181    ///     // Note that `Rc<()>` is NOT `Send`, which is what many future
182    ///     // runtimes require and below will cause a failure.
183    ///     let mut store = Store::new(&engine, Rc::new(()));
184    ///
185    ///     // Compile failure because `Store<Rc<()>>` is not `Send`
186    ///     assert_send(Instance::new_async(&mut store, &module, &[])).await?;
187    ///
188    ///     Ok(())
189    /// }
190    ///
191    /// fn assert_send<T: Send>(t: T) -> T { t }
192    /// ```
193    ///
194    /// # Errors
195    ///
196    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
197    /// memory allocation fails. See the `OutOfMemory` type's documentation for
198    /// details on Wasmtime's out-of-memory handling.
199    #[cfg(feature = "async")]
200    pub async fn new_async(
201        mut store: impl AsContextMut,
202        module: &Module,
203        imports: &[Extern],
204    ) -> Result<Instance> {
205        let mut store = store.as_context_mut();
206        let imports = Instance::typecheck_externs(store.0, module, imports)?;
207        // See `new` for notes on this unsafety
208        unsafe { Instance::new_started(&mut store, module, imports.as_ref(), Asyncness::Yes).await }
209    }
210
211    fn typecheck_externs(
212        store: &mut StoreOpaque,
213        module: &Module,
214        imports: &[Extern],
215    ) -> Result<OwnedImports> {
216        for import in imports {
217            if !import.comes_from_same_store(store) {
218                bail!("cross-`Store` instantiation is not currently supported");
219            }
220        }
221
222        typecheck(store.engine(), module, imports, |cx, ty, item| {
223            let item = DefinitionType::from(store, item);
224            cx.definition(ty, &item)
225        })?;
226
227        // When pushing functions into `OwnedImports` it's required that their
228        // `wasm_call` fields are all filled out. This `module` is guaranteed
229        // to have any trampolines necessary for functions so register the
230        // module with the store and then attempt to fill out any outstanding
231        // holes.
232        //
233        // Note that under normal operation this shouldn't do much as the list
234        // of funcs-with-holes should generally be empty. As a result the
235        // process of filling this out is not super optimized at this point.
236        let (modules, engine, breakpoints) = store.modules_and_engine_and_breakpoints_mut();
237        modules.register_module(module, engine, breakpoints)?;
238        let (funcrefs, modules) = store.func_refs_and_modules();
239        funcrefs.fill(modules);
240
241        let mut owned_imports = OwnedImports::new(module)?;
242        for import in imports {
243            owned_imports.push(import, store)?;
244        }
245        Ok(owned_imports)
246    }
247
248    /// Internal function to create an instance and run the start function.
249    ///
250    /// This function's unsafety is the same as `Instance::new_raw`.
251    pub(crate) async unsafe fn new_started<T>(
252        store: &mut StoreContextMut<'_, T>,
253        module: &Module,
254        imports: Imports<'_>,
255        asyncness: Asyncness,
256    ) -> Result<Instance> {
257        let (instance, needs_startup) = {
258            let (mut limiter, store) = store.0.resource_limiter_and_store_opaque();
259            // SAFETY: the safety contract of `new_raw` is the same as this
260            // function.
261            unsafe { Instance::new_raw(store, limiter.as_mut(), module, imports).await? }
262        };
263
264        // If this instance requires startup, which is a dynamic decision made
265        // at this point in conjunction with analysis at compile time, the
266        // instance gets started. Note that this isn't just the wasm start
267        // function itself, but it's finalization of initialization of this
268        // instance, for example for complicated global initialization
269        // expressions.
270        if needs_startup {
271            if asyncness == Asyncness::No {
272                instance.start_raw(store)?;
273            } else {
274                #[cfg(feature = "async")]
275                {
276                    store.on_fiber(|store| instance.start_raw(store)).await??;
277                }
278                #[cfg(not(feature = "async"))]
279                unreachable!();
280            }
281        }
282        Ok(instance)
283    }
284
285    /// Internal function to create an instance which doesn't have its `start`
286    /// function run yet.
287    ///
288    /// # Unsafety
289    ///
290    /// This method is unsafe because it does not type-check the `imports`
291    /// provided. The `imports` provided must be suitable for the module
292    /// provided as well.
293    pub(crate) async unsafe fn new_raw(
294        store: &mut StoreOpaque,
295        mut limiter: Option<&mut StoreResourceLimiter<'_>>,
296        module: &Module,
297        imports: Imports<'_>,
298    ) -> Result<(Instance, bool)> {
299        if !Engine::same(store.engine(), module.engine()) {
300            bail!("cross-`Engine` instantiation is not currently supported");
301        }
302        store.bump_resource_counts(module)?;
303
304        // Allocate the GC heap, if necessary.
305        if module.env_module().needs_gc_heap {
306            store.ensure_gc_store(limiter.as_deref_mut()).await?;
307        }
308
309        // Register the module just before instantiation to ensure we keep the module
310        // properly referenced while in use by the store.
311        let (modules, engine, breakpoints) = store.modules_and_engine_and_breakpoints_mut();
312        let module_id = modules.register_module(module, engine, breakpoints)?;
313
314        // The first thing we do is issue an instance allocation request
315        // to the instance allocator. This, on success, will give us an
316        // instance handle.
317        //
318        // SAFETY: this module, by construction, was already validated within
319        // the store.
320        let id = unsafe {
321            store
322                .allocate_instance(
323                    limiter.as_deref_mut(),
324                    AllocateInstanceKind::Module(module_id),
325                    &ModuleRuntimeInfo::Module(module.clone()),
326                    imports,
327                )
328                .await?
329        };
330
331        let instance = Instance::from_wasmtime(id, store);
332
333        let needs_startup = instance.id.get_mut(store).needs_startup();
334
335        // At this point the instance is created and stored within the store,
336        // but it's also not quite usable just yet. Initialization hasn't
337        // completed (e.g. active data/element segments) and the `start`
338        // function additionally has not yet been invoked. That's the
339        // responsibility of the caller to handle, however.
340        Ok((instance, needs_startup))
341    }
342
343    pub(crate) fn from_wasmtime(id: InstanceId, store: &mut StoreOpaque) -> Instance {
344        Instance {
345            id: StoreInstanceId::new(store.id(), id),
346        }
347    }
348
349    pub(crate) fn start_raw<T>(&self, store: &mut StoreContextMut<'_, T>) -> Result<()> {
350        // If a start function is present, invoke it. Make sure we use all the
351        // trap-handling configuration in `store` as well.
352        let store_id = store.0.id();
353        let (mut instance, registry) = self.id.get_mut_and_module_registry(store.0);
354        // SAFETY: the `store_id` is the id of the store that owns this
355        // instance and any function stored within the instance.
356        let f = unsafe {
357            instance
358                .as_mut()
359                .get_startup_func(registry, store_id)
360                .expect("should have a startup function")
361        };
362        let caller_vmctx = instance.vmctx();
363        unsafe {
364            let funcref = f.vm_func_ref(store.0);
365            super::func::invoke_wasm_and_catch_traps(store, |_default_caller, vm| {
366                VMFuncRef::array_call(funcref, vm, caller_vmctx, NonNull::from(&mut []))
367            })?;
368        }
369        Ok(())
370    }
371
372    /// Get this instance's module.
373    pub fn module<'a, T: 'static>(&self, store: impl Into<StoreContext<'a, T>>) -> &'a Module {
374        self._module(store.into().0)
375    }
376
377    pub(crate) fn _module<'a>(&self, store: &'a StoreOpaque) -> &'a Module {
378        store.module_for_instance(self.id).unwrap()
379    }
380
381    /// Returns the list of exported items from this [`Instance`].
382    ///
383    /// # Panics
384    ///
385    /// Panics if `store` does not own this instance, or if memory allocation
386    /// fails.
387    pub fn exports<'a, T: 'static>(
388        &'a self,
389        store: impl Into<StoreContextMut<'a, T>>,
390    ) -> impl ExactSizeIterator<Item = Export<'a>> + 'a {
391        let store = store.into().0;
392        let store_id = store.id();
393        let engine = store.engine().clone();
394
395        let (instance, registry) = store.instance_and_module_registry_mut(self.id());
396        let (module, mut instance) = instance.module_and_self();
397        module.exports.iter().map(move |(name, entity)| {
398            // SAFETY: the `store_id` owns this instance and all exports
399            // contained within.
400            let export = unsafe {
401                instance
402                    .as_mut()
403                    .get_export_by_index_mut(registry, store_id, *entity)
404            };
405
406            let ext = Extern::from_wasmtime_export(export, &engine);
407            Export::new(&module.strings[name], ext)
408        })
409    }
410
411    /// Looks up an exported [`Extern`] value by name.
412    ///
413    /// This method will search the module for an export named `name` and return
414    /// the value, if found.
415    ///
416    /// Returns `None` if there was no export named `name`.
417    ///
418    /// # Panics
419    ///
420    /// Panics if `store` does not own this instance.
421    ///
422    /// # Why does `get_export` take a mutable context?
423    ///
424    /// This method requires a mutable context because an instance's exports are
425    /// lazily populated, and we cache them as they are accessed. This makes
426    /// instantiating a module faster, but also means this method requires a
427    /// mutable context.
428    pub fn get_export(&self, mut store: impl AsContextMut, name: &str) -> Option<Extern> {
429        let store = store.as_context_mut().0;
430        let module = store[self.id].env_module();
431        let name = module.strings.get_atom(name)?;
432        let entity = *module.exports.get(&name)?;
433        Some(self._get_export(store, entity))
434    }
435
436    /// Looks up an exported [`Extern`] value by a [`ModuleExport`] value.
437    ///
438    /// This is similar to [`Instance::get_export`] but uses a [`ModuleExport`] value to avoid
439    /// string lookups where possible. [`ModuleExport`]s can be obtained by calling
440    /// [`Module::get_export_index`] on the [`Module`] that this instance was instantiated with.
441    ///
442    /// This method will search the module for an export with a matching entity index and return
443    /// the value, if found.
444    ///
445    /// Returns `None` if there was no export with a matching entity index.
446    ///
447    /// # Panics
448    ///
449    /// Panics if `store` does not own this instance.
450    pub fn get_module_export(
451        &self,
452        mut store: impl AsContextMut,
453        export: &ModuleExport,
454    ) -> Option<Extern> {
455        let store = store.as_context_mut().0;
456
457        // Verify the `ModuleExport` matches the module used in this instance.
458        if self._module(store).id() != export.module {
459            return None;
460        }
461
462        Some(self._get_export(store, export.entity))
463    }
464
465    fn _get_export(&self, store: &mut StoreOpaque, entity: EntityIndex) -> Extern {
466        let id = store.id();
467        // SAFETY: the store `id` owns this instance and all exports contained
468        // within.
469        let export = unsafe {
470            let (instance, registry) = self.id.get_mut_and_module_registry(store);
471            instance.get_export_by_index_mut(registry, id, entity)
472        };
473        Extern::from_wasmtime_export(export, store.engine())
474    }
475
476    /// Looks up an exported [`Func`] value by name.
477    ///
478    /// Returns `None` if there was no export named `name`, or if there was but
479    /// it wasn't a function.
480    ///
481    /// # Panics
482    ///
483    /// Panics if `store` does not own this instance.
484    pub fn get_func(&self, store: impl AsContextMut, name: &str) -> Option<Func> {
485        self.get_export(store, name)?.into_func()
486    }
487
488    /// Looks up an exported [`Func`] value by name and with its type.
489    ///
490    /// This function is a convenience wrapper over [`Instance::get_func`] and
491    /// [`Func::typed`]. For more information see the linked documentation.
492    ///
493    /// Returns an error if `name` isn't a function export or if the export's
494    /// type did not match `Params` or `Results`
495    ///
496    /// # Panics
497    ///
498    /// Panics if `store` does not own this instance.
499    ///
500    /// # Errors
501    ///
502    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
503    /// memory allocation fails. See the `OutOfMemory` type's documentation for
504    /// details on Wasmtime's out-of-memory handling.
505    pub fn get_typed_func<Params, Results>(
506        &self,
507        mut store: impl AsContextMut,
508        name: &str,
509    ) -> Result<TypedFunc<Params, Results>>
510    where
511        Params: crate::WasmParams,
512        Results: crate::WasmResults,
513    {
514        let f = self
515            .get_export(store.as_context_mut(), name)
516            .and_then(|f| f.into_func())
517            .ok_or_else(|| format_err!("failed to find function export `{name}`"))?;
518        Ok(f.typed::<Params, Results>(store)
519            .with_context(|| format!("failed to convert function `{name}` to given type"))?)
520    }
521
522    /// Looks up an exported [`Table`] value by name.
523    ///
524    /// Returns `None` if there was no export named `name`, or if there was but
525    /// it wasn't a table.
526    ///
527    /// # Panics
528    ///
529    /// Panics if `store` does not own this instance.
530    pub fn get_table(&self, store: impl AsContextMut, name: &str) -> Option<Table> {
531        self.get_export(store, name)?.into_table()
532    }
533
534    /// Looks up an exported [`Memory`] value by name.
535    ///
536    /// Returns `None` if there was no export named `name`, or if there was but
537    /// it wasn't a memory.
538    ///
539    /// # Panics
540    ///
541    /// Panics if `store` does not own this instance.
542    pub fn get_memory(&self, store: impl AsContextMut, name: &str) -> Option<Memory> {
543        self.get_export(store, name)?.into_memory()
544    }
545
546    /// Looks up an exported [`SharedMemory`] value by name.
547    ///
548    /// Returns `None` if there was no export named `name`, or if there was but
549    /// it wasn't a shared memory.
550    ///
551    /// # Panics
552    ///
553    /// Panics if `store` does not own this instance.
554    pub fn get_shared_memory(
555        &self,
556        mut store: impl AsContextMut,
557        name: &str,
558    ) -> Option<SharedMemory> {
559        let mut store = store.as_context_mut();
560        self.get_export(&mut store, name)?.into_shared_memory()
561    }
562
563    /// Looks up an exported [`Global`] value by name.
564    ///
565    /// Returns `None` if there was no export named `name`, or if there was but
566    /// it wasn't a global.
567    ///
568    /// # Panics
569    ///
570    /// Panics if `store` does not own this instance.
571    pub fn get_global(&self, store: impl AsContextMut, name: &str) -> Option<Global> {
572        self.get_export(store, name)?.into_global()
573    }
574
575    /// Looks up a tag [`Tag`] by name.
576    ///
577    /// Returns `None` if there was no export named `name`, or if there was but
578    /// it wasn't a tag.
579    ///
580    /// # Panics
581    ///
582    /// Panics if `store` does not own this instance.
583    pub fn get_tag(&self, store: impl AsContextMut, name: &str) -> Option<Tag> {
584        self.get_export(store, name)?.into_tag()
585    }
586
587    #[allow(
588        dead_code,
589        reason = "c-api crate does not yet support exnrefs and causes this method to be dead."
590    )]
591    pub(crate) fn id(&self) -> InstanceId {
592        self.id.instance()
593    }
594
595    /// Return a unique-within-Store index for this `Instance`.
596    ///
597    /// Allows distinguishing instance identities when introspecting
598    /// the `Store`, e.g. via debug APIs.
599    ///
600    /// This index will match the instance's position in the sequence
601    /// returned by `Store::debug_all_instances()`.
602    #[cfg(feature = "debug")]
603    pub fn debug_index_in_store(&self) -> u32 {
604        self.id.instance().as_u32()
605    }
606
607    /// Get all globals within this instance.
608    ///
609    /// Returns both import and defined globals.
610    ///
611    /// Returns both exported and non-exported globals.
612    ///
613    /// Gives access to the full globals space.
614    #[cfg(feature = "coredump")]
615    pub(crate) fn all_globals<'a>(
616        &'a self,
617        store: &'a mut StoreOpaque,
618    ) -> impl ExactSizeIterator<Item = (GlobalIndex, Global)> + 'a {
619        let store_id = store.id();
620        store[self.id].all_globals(store_id)
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    #[cfg(feature = "coredump")]
631    pub(crate) fn all_memories<'a>(
632        &'a self,
633        store: &'a StoreOpaque,
634    ) -> impl ExactSizeIterator<Item = (MemoryIndex, vm::ExportMemory)> + 'a {
635        let store_id = store.id();
636        store[self.id].all_memories(store_id)
637    }
638}
639
640pub(crate) struct OwnedImports {
641    functions: TryPrimaryMap<FuncIndex, VMFunctionImport>,
642    tables: TryPrimaryMap<TableIndex, VMTableImport>,
643    memories: TryPrimaryMap<MemoryIndex, VMMemoryImport>,
644    globals: TryPrimaryMap<GlobalIndex, VMGlobalImport>,
645    tags: TryPrimaryMap<TagIndex, VMTagImport>,
646}
647
648impl OwnedImports {
649    fn new(module: &Module) -> Result<OwnedImports, OutOfMemory> {
650        let mut ret = OwnedImports::empty();
651        ret.reserve(module)?;
652        Ok(ret)
653    }
654
655    pub(crate) fn empty() -> OwnedImports {
656        OwnedImports {
657            functions: TryPrimaryMap::new(),
658            tables: TryPrimaryMap::new(),
659            memories: TryPrimaryMap::new(),
660            globals: TryPrimaryMap::new(),
661            tags: TryPrimaryMap::new(),
662        }
663    }
664
665    pub(crate) fn reserve(&mut self, module: &Module) -> Result<(), OutOfMemory> {
666        let raw = module.compiled_module().module();
667        self.functions.reserve(raw.num_imported_funcs)?;
668        self.tables.reserve(raw.num_imported_tables)?;
669        self.memories.reserve(raw.num_imported_memories)?;
670        self.globals.reserve(raw.num_imported_globals)?;
671        self.tags.reserve(raw.num_imported_tags)?;
672        Ok(())
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        self.tags.clear();
682    }
683
684    fn push(&mut self, item: &Extern, store: &mut StoreOpaque) -> Result<(), OutOfMemory> {
685        match item {
686            Extern::Func(i) => {
687                self.functions.push(i.vmimport(store))?;
688            }
689            Extern::Global(i) => {
690                self.globals.push(i.vmimport(store))?;
691            }
692            Extern::Table(i) => {
693                self.tables.push(i.vmimport(store))?;
694            }
695            Extern::Memory(i) => {
696                self.memories.push(i.vmimport(store))?;
697            }
698            Extern::SharedMemory(i) => {
699                self.memories.push(i.vmimport(store))?;
700            }
701            Extern::Tag(i) => {
702                self.tags.push(i.vmimport(store))?;
703            }
704        }
705        Ok(())
706    }
707
708    /// Note that this is unsafe as the validity of `item` is not verified and
709    /// it contains a bunch of raw pointers.
710    #[cfg(feature = "component-model")]
711    pub(crate) fn push_export(
712        &mut self,
713        store: &StoreOpaque,
714        item: &crate::runtime::vm::Export,
715    ) -> Result<(), OutOfMemory> {
716        match item {
717            crate::runtime::vm::Export::Function(f) => {
718                self.functions.push(f.vmimport(store))?;
719            }
720            crate::runtime::vm::Export::Global(g) => {
721                self.globals.push(g.vmimport(store))?;
722            }
723            crate::runtime::vm::Export::Table(t) => {
724                self.tables.push(t.vmimport(store))?;
725            }
726            crate::runtime::vm::Export::Memory(m) => {
727                self.memories.push(m.vmimport(store))?;
728            }
729            crate::runtime::vm::Export::SharedMemory(_, vmimport) => {
730                self.memories.push(*vmimport)?;
731            }
732            crate::runtime::vm::Export::Tag(t) => {
733                self.tags.push(t.vmimport(store))?;
734            }
735        }
736        Ok(())
737    }
738
739    pub(crate) fn as_ref(&self) -> Imports<'_> {
740        Imports {
741            tables: self.tables.values().as_slice(),
742            globals: self.globals.values().as_slice(),
743            memories: self.memories.values().as_slice(),
744            functions: self.functions.values().as_slice(),
745            tags: self.tags.values().as_slice(),
746        }
747    }
748}
749
750/// An instance, pre-instantiation, that is ready to be instantiated.
751///
752/// This structure represents an instance *just before* it was instantiated,
753/// after all type-checking and imports have been resolved. The only thing left
754/// to do for this instance is to actually run the process of instantiation.
755///
756/// Note that an `InstancePre` may not be tied to any particular [`Store`] if
757/// none of the imports it closed over are tied to any particular [`Store`].
758///
759/// This structure is created through the [`Linker::instantiate_pre`] method,
760/// which also has some more information and examples.
761///
762/// [`Store`]: crate::Store
763/// [`Linker::instantiate_pre`]: crate::Linker::instantiate_pre
764pub struct InstancePre<T> {
765    module: Module,
766
767    /// The items which this `InstancePre` use to instantiate the `module`
768    /// provided, passed to `Instance::new_started` after inserting them into a
769    /// `Store`.
770    ///
771    /// Note that this is stored as an `Arc` to quickly move a strong reference
772    /// to everything internally into a `Store<T>` without having to clone each
773    /// individual item.
774    items: Arc<TryVec<Definition>>,
775
776    /// A count of `Definition::HostFunc` entries in `items` above to
777    /// preallocate space in a `Store` up front for all entries to be inserted.
778    host_funcs: usize,
779
780    /// The `VMFuncRef`s for the functions in `items` that do not
781    /// have a `wasm_call` trampoline. We pre-allocate and pre-patch these
782    /// `VMFuncRef`s so that we don't have to do it at
783    /// instantiation time.
784    ///
785    /// This is an `Arc` for the same reason as `items`.
786    func_refs: Arc<TryVec<VMFuncRef>>,
787
788    /// Whether or not any import in `items` is flagged as needing async.
789    ///
790    /// This is used to update stores during instantiation as to whether they
791    /// require async entrypoints.
792    asyncness: Asyncness,
793
794    _marker: core::marker::PhantomData<fn() -> T>,
795}
796
797/// InstancePre's clone does not require T: Clone
798impl<T> Clone for InstancePre<T> {
799    fn clone(&self) -> Self {
800        Self {
801            module: self.module.clone(),
802            items: self.items.clone(),
803            host_funcs: self.host_funcs,
804            func_refs: self.func_refs.clone(),
805            asyncness: self.asyncness,
806            _marker: self._marker,
807        }
808    }
809}
810
811impl<T: 'static> InstancePre<T> {
812    /// Creates a new `InstancePre` which type-checks the `items` provided and
813    /// on success is ready to instantiate a new instance.
814    ///
815    /// `engine` is the engine that `items` belong to, and this returns an error
816    /// if that is not also `module`'s engine. This also returns an error if an
817    /// individual item within `items` reports an engine of its own that is not
818    /// `engine`, which happens when that item was taken from a store belonging
819    /// to a different engine than the linker it was defined in.
820    ///
821    /// # Unsafety
822    ///
823    /// This method is unsafe as the `T` of the `InstancePre<T>` is not
824    /// guaranteed to be the same as the `T` within the `Store`, the caller must
825    /// verify that.
826    pub(crate) unsafe fn new(
827        engine: &Engine,
828        module: &Module,
829        items: TryVec<Definition>,
830    ) -> Result<InstancePre<T>> {
831        typecheck(engine, module, &items, |cx, ty, item| {
832            cx.definition(ty, &item.ty())
833        })?;
834
835        let mut func_refs = TryVec::with_capacity(items.len())?;
836        let mut host_funcs = 0;
837        let mut asyncness = Asyncness::No;
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                        func_refs.push(VMFuncRef {
845                            wasm_call: module
846                                .wasm_to_array_trampoline(f.sig_index())
847                                .map(|f| f.into()),
848                            ..*f.func_ref()
849                        })?;
850                    }
851                    asyncness = asyncness | f.asyncness();
852                }
853            }
854        }
855
856        Ok(InstancePre {
857            module: module.clone(),
858            items: try_new::<Arc<_>>(items)?,
859            host_funcs,
860            func_refs: try_new::<Arc<_>>(func_refs)?,
861            asyncness,
862            _marker: core::marker::PhantomData,
863        })
864    }
865
866    /// Returns a reference to the module that this [`InstancePre`] will be
867    /// instantiating.
868    pub fn module(&self) -> &Module {
869        &self.module
870    }
871
872    /// Instantiates this instance, creating a new instance within the provided
873    /// `store`.
874    ///
875    /// This function will run the actual process of instantiation to
876    /// completion. This will use all of the previously-closed-over items as
877    /// imports to instantiate the module that this was originally created with.
878    ///
879    /// For more information about instantiation see [`Instance::new`].
880    ///
881    /// # Panics
882    ///
883    /// Panics if any import closed over by this [`InstancePre`] isn't owned by
884    /// `store`, or if `store` has async support enabled. Additionally this
885    /// function will panic if the `store` provided comes from a different
886    /// [`Engine`] than the [`InstancePre`] originally came from.
887    ///
888    /// # Errors
889    ///
890    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
891    /// memory allocation fails. See the `OutOfMemory` type's documentation for
892    /// details on Wasmtime's out-of-memory handling.
893    pub fn instantiate(&self, mut store: impl AsContextMut<Data = T>) -> Result<Instance> {
894        let mut store = store.as_context_mut();
895        let imports = pre_instantiate_raw(
896            &mut store.0,
897            &self.module,
898            &self.items,
899            self.host_funcs,
900            &self.func_refs,
901            self.asyncness,
902        )?;
903
904        // Note that this is specifically done after `pre_instantiate_raw` to
905        // handle the case that if any imports in this `InstancePre` require
906        // async that it's flagged in the store by that point which will reject
907        // this instantiation to say "use `instantiate_async` instead".
908        store.0.validate_sync_call()?;
909
910        // This unsafety should be handled by the type-checking performed by the
911        // constructor of `InstancePre` to assert that all the imports we're passing
912        // in match the module we're instantiating.
913        vm::assert_ready(unsafe {
914            Instance::new_started(&mut store, &self.module, imports.as_ref(), Asyncness::No)
915        })
916    }
917
918    /// Creates a new instance, running the start function asynchronously
919    /// instead of inline.
920    ///
921    /// For more information about asynchronous instantiation see the
922    /// documentation on [`Instance::new_async`].
923    ///
924    /// # Panics
925    ///
926    /// Panics if any import closed over by this [`InstancePre`] isn't owned by
927    /// `store`, or if `store` does not have async support enabled.
928    ///
929    /// # Errors
930    ///
931    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
932    /// memory allocation fails. See the `OutOfMemory` type's documentation for
933    /// details on Wasmtime's out-of-memory handling.
934    #[cfg(feature = "async")]
935    pub async fn instantiate_async(
936        &self,
937        mut store: impl AsContextMut<Data = T>,
938    ) -> Result<Instance> {
939        let mut store = store.as_context_mut();
940        let imports = pre_instantiate_raw(
941            &mut store.0,
942            &self.module,
943            &self.items,
944            self.host_funcs,
945            &self.func_refs,
946            self.asyncness,
947        )?;
948
949        // This unsafety should be handled by the type-checking performed by the
950        // constructor of `InstancePre` to assert that all the imports we're passing
951        // in match the module we're instantiating.
952        unsafe {
953            Instance::new_started(&mut store, &self.module, imports.as_ref(), Asyncness::Yes).await
954        }
955    }
956}
957
958/// Helper function shared between
959/// `InstancePre::{instantiate,instantiate_async}`
960///
961/// This is an out-of-line function to avoid the generic on `InstancePre` and
962/// get this compiled into the `wasmtime` crate to avoid having it monomorphized
963/// elsewhere.
964fn pre_instantiate_raw(
965    store: &mut StoreOpaque,
966    module: &Module,
967    items: &Arc<TryVec<Definition>>,
968    host_funcs: usize,
969    func_refs: &Arc<TryVec<VMFuncRef>>,
970    asyncness: Asyncness,
971) -> Result<OwnedImports> {
972    // Register this module and use it to fill out any funcref wasm_call holes
973    // we can. For more comments on this see `typecheck_externs`.
974    let (modules, engine, breakpoints) = store.modules_and_engine_and_breakpoints_mut();
975    modules.register_module(module, engine, breakpoints)?;
976    let (funcrefs, modules) = store.func_refs_and_modules();
977    funcrefs.fill(modules);
978
979    if host_funcs > 0 {
980        // Any linker-defined function of the `Definition::HostFunc` variant
981        // will insert a function into the store automatically as part of
982        // instantiation, so reserve space here to make insertion more efficient
983        // as it won't have to realloc during the instantiation.
984        funcrefs.reserve_storage(host_funcs)?;
985
986        // The usage of `to_extern_store_rooted` requires that the items are
987        // rooted via another means, which happens here by cloning the list of
988        // items into the store once. This avoids cloning each individual item
989        // below.
990        funcrefs.push_instance_pre_definitions(items.clone())?;
991        funcrefs.push_instance_pre_func_refs(func_refs.clone())?;
992    }
993
994    store.set_async_required(asyncness);
995
996    let mut func_refs = func_refs.iter().map(|f| NonNull::from(f));
997    let mut imports = OwnedImports::new(module)?;
998    for import in items.iter() {
999        if !import.comes_from_same_store(store) {
1000            bail!("cross-`Store` instantiation is not currently supported");
1001        }
1002        // This unsafety should be encapsulated in the constructor of
1003        // `InstancePre` where the `T` of the original item should match the
1004        // `T` of the store. Additionally the rooting necessary has happened
1005        // above.
1006        let item = match import {
1007            Definition::Extern { item, .. } => item.clone(),
1008            Definition::HostFunc(func) => unsafe {
1009                func.to_func_store_rooted(
1010                    store,
1011                    if func.func_ref().wasm_call.is_none() {
1012                        Some(func_refs.next().unwrap())
1013                    } else {
1014                        None
1015                    },
1016                )
1017                .into()
1018            },
1019        };
1020        imports.push(&item, store)?;
1021    }
1022
1023    Ok(imports)
1024}
1025
1026/// An item that can be supplied as an import argument during instantiation.
1027///
1028/// # Safety
1029///
1030/// Implementations must return an associated engine if they own a handle to
1031/// one. Failure to do so may allow cross-`Engine` type confusion.
1032///
1033/// (Items that are just identifiers indexing into a store, for example
1034/// `Extern::Global(wasmtime::Global)`, do not have their own handle to an
1035/// engine. Their engine is the engine of the store they belong to, and it is
1036/// the store, not them, that holds an owning handle to the engine.)
1037unsafe trait ImportArg {
1038    fn engine(&self) -> Option<&Engine>;
1039}
1040
1041// SAFETY: `Extern::SharedMemory` is the only variant with an `Engine` handle.
1042unsafe impl ImportArg for Extern {
1043    fn engine(&self) -> Option<&Engine> {
1044        match self {
1045            Extern::SharedMemory(m) => Some(m.engine()),
1046            Extern::Func(_)
1047            | Extern::Global(_)
1048            | Extern::Table(_)
1049            | Extern::Memory(_)
1050            | Extern::Tag(_) => None,
1051        }
1052    }
1053}
1054
1055// SAFETY: `Definition::engine` is complete.
1056unsafe impl ImportArg for Definition {
1057    fn engine(&self) -> Option<&Engine> {
1058        Some(Definition::engine(self))
1059    }
1060}
1061
1062/// Type check the `import_args` against the imports that `module` declares.
1063///
1064/// `engine` is the engine that the `import_args` belong to. It must be the same
1065/// engine as `module`'s: entity types are compared by `VMSharedTypeIndex`, which
1066/// only means anything within the engine that assigned it, so checking one
1067/// engine's items against another engine's module would compare unrelated types
1068/// and consider them equal.
1069fn typecheck<I>(
1070    engine: &Engine,
1071    module: &Module,
1072    import_args: &[I],
1073    check: impl Fn(&matching::MatchCx<'_>, &EntityType, &I) -> Result<()>,
1074) -> Result<()>
1075where
1076    I: ImportArg,
1077{
1078    ensure!(
1079        Engine::same(engine, module.engine()),
1080        "cross-`Engine` instantiation is not currently supported"
1081    );
1082    let env_module = module.compiled_module().module();
1083    let expected_len = env_module.imports().count();
1084    let actual_len = import_args.len();
1085    if expected_len != actual_len {
1086        bail!("expected {expected_len} imports, found {actual_len}");
1087    }
1088    let cx = matching::MatchCx::new(module.engine());
1089    for ((name, field, expected_ty), actual) in env_module.imports().zip(import_args) {
1090        debug_assert!(expected_ty.is_canonicalized_for_runtime_usage());
1091        if let Some(actual_engine) = actual.engine() {
1092            ensure!(
1093                Engine::same(actual_engine, engine),
1094                "cross-`Engine` instantiation is not currently supported: \
1095                 the item provided for `{name}::{field}` belongs to a \
1096                 different engine than the module being instantiated"
1097            );
1098        }
1099        check(&cx, &expected_ty, actual)
1100            .with_context(|| format!("incompatible import type for `{name}::{field}`"))?;
1101    }
1102    Ok(())
1103}