Skip to main content

wasmtime/runtime/
linker.rs

1use crate::error::OutOfMemory;
2use crate::func::HostFunc;
3use crate::instance::InstancePre;
4use crate::store::StoreOpaque;
5use crate::{
6    AsContext, AsContextMut, Caller, Engine, Extern, ExternType, Func, FuncType, ImportType,
7    Instance, IntoFunc, Module, Result, StoreContextMut, Val, ValRaw, prelude::*,
8};
9use alloc::sync::Arc;
10use core::fmt::{self, Debug};
11#[cfg(feature = "async")]
12use core::future::Future;
13use core::marker;
14use core::mem::MaybeUninit;
15use log::warn;
16use wasmtime_environ::{Atom, PanicOnOom, StringPool};
17
18/// Structure used to link wasm modules/instances together.
19///
20/// This structure is used to assist in instantiating a [`Module`]. A [`Linker`]
21/// is a way of performing name resolution to make instantiating a module easier
22/// than specifying positional imports to [`Instance::new`]. [`Linker`] is a
23/// name-based resolver where names are dynamically defined and then used to
24/// instantiate a [`Module`].
25///
26/// An important method is [`Linker::instantiate`] which takes a module to
27/// instantiate into the provided store. This method will automatically select
28/// all the right imports for the [`Module`] to be instantiated, and will
29/// otherwise return an error if an import isn't satisfied.
30///
31/// ## Name Resolution
32///
33/// As mentioned previously, `Linker` is a form of name resolver. It will be
34/// using the string-based names of imports on a module to attempt to select a
35/// matching item to hook up to it. This name resolution has two-levels of
36/// namespaces, a module level and a name level. Each item is defined within a
37/// module and then has its own name. This basically follows the wasm standard
38/// for modularization.
39///
40/// Names in a `Linker` cannot be defined twice, but allowing duplicates by
41/// shadowing the previous definition can be controlled with the
42/// [`Linker::allow_shadowing`] method.
43///
44/// ## Commands and Reactors
45///
46/// The [`Linker`] type provides conveniences for working with WASI Commands and
47/// Reactors through the [`Linker::module`] method. This will automatically
48/// handle instantiation and calling `_start` and such as appropriate
49/// depending on the inferred type of module.
50///
51/// ## Type parameter `T`
52///
53/// It's worth pointing out that the type parameter `T` on [`Linker<T>`] does
54/// not represent that `T` is stored within a [`Linker`]. Rather the `T` is used
55/// to ensure that linker-defined functions and stores instantiated into all use
56/// the same matching `T` as host state.
57///
58/// ## Multiple `Store`s
59///
60/// The [`Linker`] type is designed to be compatible, in some scenarios, with
61/// instantiation in multiple [`Store`]s. Specifically host-defined functions
62/// created in [`Linker`] with [`Linker::func_new`], [`Linker::func_wrap`], and
63/// their async versions are compatible to instantiate into any [`Store`]. This
64/// enables programs which want to instantiate lots of modules to create one
65/// [`Linker`] value at program start up and use that continuously for each
66/// [`Store`] created over the lifetime of the program.
67///
68/// Note that once [`Store`]-owned items, such as [`Global`], are defined within
69/// a [`Linker`] then it is no longer compatible with any [`Store`]. At that
70/// point only the [`Store`] that owns the [`Global`] can be used to instantiate
71/// modules.
72///
73/// After that [`Store`] is dropped the [`Linker`] should no longer be used to
74/// instantiate modules which import its items. The type-checking of such
75/// imports may panic or erroneously succeed, but instantiating them in any
76/// other [`Store`] will always return an error.
77///
78/// ## Multiple `Engine`s
79///
80/// The [`Linker`] type is not compatible with usage between multiple [`Engine`]
81/// values. An [`Engine`] is provided when a [`Linker`] is created and only
82/// stores and items which originate from that [`Engine`] can be used with this
83/// [`Linker`]. Instantiating a [`Module`] from another [`Engine`] returns an
84/// error, and mixing engines in other ways may cause a panic at runtime,
85/// similar to how if a [`Func`] is used with the wrong [`Store`] that can also
86/// panic at runtime.
87///
88/// [`Store`]: crate::Store
89/// [`Global`]: crate::Global
90pub struct Linker<T> {
91    engine: Engine,
92    pool: StringPool,
93    map: TryHashMap<ImportKey, Definition>,
94    allow_shadowing: bool,
95    allow_unknown_exports: bool,
96    _marker: marker::PhantomData<fn() -> T>,
97}
98
99impl<T> Debug for Linker<T> {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.debug_struct("Linker").finish_non_exhaustive()
102    }
103}
104
105impl<T> Clone for Linker<T> {
106    fn clone(&self) -> Linker<T> {
107        Linker {
108            engine: self.engine.clone(),
109            pool: self.pool.clone_panic_on_oom(),
110            map: self.map.clone_panic_on_oom(),
111            allow_shadowing: self.allow_shadowing,
112            allow_unknown_exports: self.allow_unknown_exports,
113            _marker: self._marker,
114        }
115    }
116}
117
118#[derive(Copy, Clone, Hash, PartialEq, Eq)]
119struct ImportKey {
120    module: Atom,
121    name: Atom,
122}
123
124impl TryClone for ImportKey {
125    #[inline]
126    fn try_clone(&self) -> Result<Self, OutOfMemory> {
127        Ok(*self)
128    }
129}
130
131#[derive(Clone)]
132pub(crate) enum Definition {
133    Extern {
134        item: Extern,
135        ty: DefinitionType,
136        /// The engine of the store that `item` was taken from, which is the
137        /// engine that assigned any type indices within `ty`.
138        engine: Engine,
139    },
140    HostFunc(Arc<HostFunc>),
141}
142
143impl TryClone for Definition {
144    fn try_clone(&self) -> core::result::Result<Self, OutOfMemory> {
145        Ok(self.clone())
146    }
147}
148
149/// This is a sort of slimmed down `ExternType` which notably doesn't have a
150/// `FuncType`, which is an allocation, and additionally retains the current
151/// size of the table/memory.
152#[derive(Clone, Copy, Debug)]
153pub(crate) enum DefinitionType {
154    Func(wasmtime_environ::VMSharedTypeIndex),
155    Global(wasmtime_environ::Global),
156    // Note that tables and memories store not only the original type
157    // information but additionally the current size of the table/memory, as
158    // this is used during linking since the min size specified in the type may
159    // no longer be the current size of the table/memory.
160    Table(wasmtime_environ::Table, u64),
161    Memory(wasmtime_environ::Memory, u64),
162    Tag(wasmtime_environ::Tag),
163}
164
165impl<T> Linker<T> {
166    /// Creates a new [`Linker`].
167    ///
168    /// The linker will define functions within the context of the `engine`
169    /// provided and can only instantiate modules for a [`Store`][crate::Store]
170    /// that is also defined within the same [`Engine`]. Usage of stores with
171    /// different [`Engine`]s may cause a panic when used with this [`Linker`].
172    pub fn new(engine: &Engine) -> Linker<T> {
173        Linker {
174            engine: engine.clone(),
175            map: TryHashMap::new(),
176            pool: StringPool::new(),
177            allow_shadowing: false,
178            allow_unknown_exports: false,
179            _marker: marker::PhantomData,
180        }
181    }
182
183    /// Returns the [`Engine`] this is connected to.
184    pub fn engine(&self) -> &Engine {
185        &self.engine
186    }
187
188    /// Configures whether this [`Linker`] will shadow previous duplicate
189    /// definitions of the same signature.
190    ///
191    /// By default a [`Linker`] will disallow duplicate definitions of the same
192    /// signature. This method, however, can be used to instead allow duplicates
193    /// and have the latest definition take precedence when linking modules.
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// # use wasmtime::*;
199    /// # fn main() -> Result<()> {
200    /// # let engine = Engine::default();
201    /// let mut linker = Linker::<()>::new(&engine);
202    /// linker.func_wrap("", "", || {})?;
203    ///
204    /// // by default, duplicates are disallowed
205    /// assert!(linker.func_wrap("", "", || {}).is_err());
206    ///
207    /// // but shadowing can be configured to be allowed as well
208    /// linker.allow_shadowing(true);
209    /// linker.func_wrap("", "", || {})?;
210    /// # Ok(())
211    /// # }
212    /// ```
213    pub fn allow_shadowing(&mut self, allow: bool) -> &mut Self {
214        self.allow_shadowing = allow;
215        self
216    }
217
218    /// Configures whether this [`Linker`] will allow unknown exports from
219    /// command modules.
220    ///
221    /// By default a [`Linker`] will error when unknown exports are encountered
222    /// in a command module while using [`Linker::module`].
223    ///
224    /// This method can be used to allow unknown exports from command modules.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// # use wasmtime::*;
230    /// # fn main() -> Result<()> {
231    /// # let engine = Engine::default();
232    /// # let module = Module::new(&engine, "(module)")?;
233    /// # let mut store = Store::new(&engine, ());
234    /// let mut linker = Linker::new(&engine);
235    /// linker.allow_unknown_exports(true);
236    /// linker.module(&mut store, "mod", &module)?;
237    /// # Ok(())
238    /// # }
239    /// ```
240    pub fn allow_unknown_exports(&mut self, allow: bool) -> &mut Self {
241        self.allow_unknown_exports = allow;
242        self
243    }
244
245    /// Implement any imports of the given [`Module`] with a function which traps.
246    ///
247    /// By default a [`Linker`] will error when unknown imports are encountered
248    /// in a command module while using [`Linker::module`].
249    ///
250    /// This method can be used to allow unknown imports from command modules.
251    ///
252    /// # Examples
253    ///
254    /// ```
255    /// # use wasmtime::*;
256    /// # fn main() -> Result<()> {
257    /// # let engine = Engine::default();
258    /// # let module = Module::new(&engine, "(module (import \"unknown\" \"import\" (func)))")?;
259    /// # let mut store = Store::new(&engine, ());
260    /// let mut linker = Linker::new(&engine);
261    /// linker.define_unknown_imports_as_traps(&module)?;
262    /// linker.instantiate(&mut store, &module)?;
263    /// # Ok(())
264    /// # }
265    /// ```
266    pub fn define_unknown_imports_as_traps(&mut self, module: &Module) -> Result<()>
267    where
268        T: 'static,
269    {
270        for import in module.imports() {
271            if let Err(import_err) = self._get_by_import(&import) {
272                if let ExternType::Func(func_ty) = import_err.ty() {
273                    self.func_new(import.module(), import.name(), func_ty, move |_, _, _| {
274                        bail!(import_err.clone());
275                    })?;
276                }
277            }
278        }
279        Ok(())
280    }
281
282    /// Implement any function imports of the [`Module`] with a function that
283    /// ignores its arguments and returns default values.
284    ///
285    /// Default values are either zero or null, depending on the value type.
286    ///
287    /// This method can be used to allow unknown imports from command modules.
288    ///
289    /// # Example
290    ///
291    /// ```
292    /// # use wasmtime::*;
293    /// # fn main() -> Result<()> {
294    /// # let engine = Engine::default();
295    /// # let module = Module::new(&engine, "(module (import \"unknown\" \"import\" (func)))")?;
296    /// # let mut store = Store::new(&engine, ());
297    /// let mut linker = Linker::new(&engine);
298    /// linker.define_unknown_imports_as_default_values(&mut store, &module)?;
299    /// linker.instantiate(&mut store, &module)?;
300    /// # Ok(())
301    /// # }
302    /// ```
303    pub fn define_unknown_imports_as_default_values(
304        &mut self,
305        mut store: impl AsContextMut<Data = T>,
306        module: &Module,
307    ) -> Result<()>
308    where
309        T: 'static,
310    {
311        let mut store = store.as_context_mut();
312        for import in module.imports() {
313            if let Err(import_err) = self._get_by_import(&import) {
314                let default_extern =
315                    import_err.ty().default_value(&mut store).with_context(|| {
316                        format_err!(
317                            "no default value exists for `{}::{}` with type `{:?}`",
318                            import.module(),
319                            import.name(),
320                            import_err.ty(),
321                        )
322                    })?;
323                self.define(
324                    store.as_context(),
325                    import.module(),
326                    import.name(),
327                    default_extern,
328                )?;
329            }
330        }
331        Ok(())
332    }
333
334    /// Defines a new item in this [`Linker`].
335    ///
336    /// This method will add a new definition, by name, to this instance of
337    /// [`Linker`]. The `module` and `name` provided are what to name the
338    /// `item`.
339    ///
340    /// # Errors
341    ///
342    /// Returns an error if the `module` and `name` already identify an item
343    /// of the same type as the `item` provided and if shadowing is disallowed.
344    /// For more information see the documentation on [`Linker`].
345    ///
346    /// # Examples
347    ///
348    /// ```
349    /// # use wasmtime::*;
350    /// # fn main() -> Result<()> {
351    /// # let engine = Engine::default();
352    /// # let mut store = Store::new(&engine, ());
353    /// let mut linker = Linker::new(&engine);
354    /// let ty = GlobalType::new(ValType::I32, Mutability::Const);
355    /// let global = Global::new(&mut store, ty, Val::I32(0x1234))?;
356    /// linker.define(&store, "host", "offset", global)?;
357    ///
358    /// let wat = r#"
359    ///     (module
360    ///         (import "host" "offset" (global i32))
361    ///         (memory 1)
362    ///         (data (global.get 0) "foo")
363    ///     )
364    /// "#;
365    /// let module = Module::new(&engine, wat)?;
366    /// linker.instantiate(&mut store, &module)?;
367    /// # Ok(())
368    /// # }
369    /// ```
370    ///
371    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
372    /// memory allocation fails. See the `OutOfMemory` type's documentation for
373    /// details on Wasmtime's out-of-memory handling.
374    pub fn define(
375        &mut self,
376        store: impl AsContext<Data = T>,
377        module: &str,
378        name: &str,
379        item: impl Into<Extern>,
380    ) -> Result<&mut Self>
381    where
382        T: 'static,
383    {
384        let store = store.as_context();
385        let key = self.import_key(module, name)?;
386        self.insert(key, Definition::new(store.0, item.into()))?;
387        Ok(self)
388    }
389
390    fn func_insert(&mut self, module: &str, name: &str, func: HostFunc) -> Result<&mut Self>
391    where
392        T: 'static,
393    {
394        let key = self.import_key(module, name)?;
395        self.insert(key, Definition::HostFunc(try_new(func)?))?;
396        Ok(self)
397    }
398
399    /// Creates a [`Func::new`]-style function named in this linker.
400    ///
401    /// For more information see [`Linker::func_wrap`].
402    ///
403    /// # Panics
404    ///
405    /// Panics if the given function type is not associated with the same engine
406    /// as this linker.
407    ///
408    /// # Errors
409    ///
410    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
411    /// memory allocation fails. See the `OutOfMemory` type's documentation for
412    /// details on Wasmtime's out-of-memory handling.
413    pub fn func_new(
414        &mut self,
415        module: &str,
416        name: &str,
417        ty: FuncType,
418        func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
419    ) -> Result<&mut Self>
420    where
421        T: 'static,
422    {
423        self.func_insert(module, name, HostFunc::new(&self.engine, ty, func)?)
424    }
425
426    /// Creates a [`Func::new_unchecked`]-style function named in this linker.
427    ///
428    /// For more information see [`Linker::func_wrap`].
429    ///
430    /// # Panics
431    ///
432    /// Panics if the given function type is not associated with the same engine
433    /// as this linker.
434    ///
435    /// # Safety
436    ///
437    /// See [`Func::new_unchecked`] for more safety information.
438    pub unsafe fn func_new_unchecked(
439        &mut self,
440        module: &str,
441        name: &str,
442        ty: FuncType,
443        func: impl Fn(Caller<'_, T>, &mut [MaybeUninit<ValRaw>]) -> Result<()> + Send + Sync + 'static,
444    ) -> Result<&mut Self>
445    where
446        T: 'static,
447    {
448        // SAFETY: the contract of this function is the same as `new_unchecked`.
449        let func = unsafe { HostFunc::new_unchecked(&self.engine, ty, func)? };
450        self.func_insert(module, name, func)
451    }
452
453    /// Creates a [`Func::new_async`]-style function named in this linker.
454    ///
455    /// For more information see [`Linker::func_wrap`].
456    ///
457    /// # Panics
458    ///
459    /// This method panics in the following situations:
460    ///
461    /// * If the given function type is not associated with the same engine as
462    ///   this linker.
463    #[cfg(feature = "async")]
464    pub fn func_new_async<F>(
465        &mut self,
466        module: &str,
467        name: &str,
468        ty: FuncType,
469        func: F,
470    ) -> Result<&mut Self>
471    where
472        F: for<'a> Fn(
473                Caller<'a, T>,
474                &'a [Val],
475                &'a mut [Val],
476            ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
477            + Send
478            + Sync
479            + 'static,
480        T: Send + 'static,
481    {
482        self.func_insert(module, name, HostFunc::new_async(&self.engine, ty, func)?)
483    }
484
485    /// Define a host function within this linker.
486    ///
487    /// For information about how the host function operates, see
488    /// [`Func::wrap`]. That includes information about translating Rust types
489    /// to WebAssembly native types.
490    ///
491    /// This method creates a host-provided function in this linker under the
492    /// provided name. This method is distinct in its capability to create a
493    /// [`Store`](crate::Store)-independent function. This means that the
494    /// function defined here can be used to instantiate instances in multiple
495    /// different stores, or in other words the function can be loaded into
496    /// different stores.
497    ///
498    /// Note that the capability mentioned here applies to all other
499    /// host-function-defining-methods on [`Linker`] as well. All of them can be
500    /// used to create instances of [`Func`] within multiple stores. In a
501    /// multithreaded program, for example, this means that the host functions
502    /// could be called concurrently if different stores are executing on
503    /// different threads.
504    ///
505    /// # Errors
506    ///
507    /// Returns an error if the `module` and `name` already identify an item
508    /// of the same type as the `item` provided and if shadowing is disallowed.
509    /// For more information see the documentation on [`Linker`].
510    ///
511    /// # Examples
512    ///
513    /// ```
514    /// # use wasmtime::*;
515    /// # fn main() -> Result<()> {
516    /// # let engine = Engine::default();
517    /// let mut linker = Linker::new(&engine);
518    /// linker.func_wrap("host", "double", |x: i32| x * 2)?;
519    /// linker.func_wrap("host", "log_i32", |x: i32| println!("{}", x))?;
520    /// linker.func_wrap("host", "log_str", |caller: Caller<'_, ()>, ptr: i32, len: i32| {
521    ///     // ...
522    /// })?;
523    ///
524    /// let wat = r#"
525    ///     (module
526    ///         (import "host" "double" (func (param i32) (result i32)))
527    ///         (import "host" "log_i32" (func (param i32)))
528    ///         (import "host" "log_str" (func (param i32 i32)))
529    ///     )
530    /// "#;
531    /// let module = Module::new(&engine, wat)?;
532    ///
533    /// // instantiate in multiple different stores
534    /// for _ in 0..10 {
535    ///     let mut store = Store::new(&engine, ());
536    ///     linker.instantiate(&mut store, &module)?;
537    /// }
538    /// # Ok(())
539    /// # }
540    /// ```
541    ///
542    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
543    /// memory allocation fails. See the `OutOfMemory` type's documentation for
544    /// details on Wasmtime's out-of-memory handling.
545    pub fn func_wrap<Params, Args>(
546        &mut self,
547        module: &str,
548        name: &str,
549        func: impl IntoFunc<T, Params, Args>,
550    ) -> Result<&mut Self>
551    where
552        T: 'static,
553    {
554        self.func_insert(module, name, func.into_func(&self.engine)?)
555    }
556
557    /// Asynchronous analog of [`Linker::func_wrap`].
558    #[cfg(feature = "async")]
559    pub fn func_wrap_async<F, Params: crate::WasmTyList, Args: crate::WasmRet>(
560        &mut self,
561        module: &str,
562        name: &str,
563        func: F,
564    ) -> Result<&mut Self>
565    where
566        F: for<'a> Fn(Caller<'a, T>, Params) -> Box<dyn Future<Output = Args> + Send + 'a>
567            + Send
568            + Sync
569            + 'static,
570        T: Send + 'static,
571    {
572        self.func_insert(module, name, HostFunc::wrap_async(&self.engine, func)?)
573    }
574
575    /// Convenience wrapper to define an entire [`Instance`] in this linker.
576    ///
577    /// This function is a convenience wrapper around [`Linker::define`] which
578    /// will define all exports on `instance` into this linker. The module name
579    /// for each export is `module_name`, and the name for each export is the
580    /// name in the instance itself.
581    ///
582    /// Note that when this API is used the [`Linker`] is no longer compatible
583    /// with multi-[`Store`][crate::Store] instantiation because the items
584    /// defined within this store will belong to the `store` provided, and only
585    /// the `store` provided.
586    ///
587    /// # Errors
588    ///
589    /// Returns an error if the any item is redefined twice in this linker (for
590    /// example the same `module_name` was already defined) and shadowing is
591    /// disallowed, or if `instance` comes from a different
592    /// [`Store`](crate::Store) than this [`Linker`] originally was created
593    /// with.
594    ///
595    /// # Panics
596    ///
597    /// Panics if `instance` does not belong to `store`.
598    ///
599    /// # Examples
600    ///
601    /// ```
602    /// # use wasmtime::*;
603    /// # fn main() -> Result<()> {
604    /// # let engine = Engine::default();
605    /// # let mut store = Store::new(&engine, ());
606    /// let mut linker = Linker::new(&engine);
607    ///
608    /// // Instantiate a small instance...
609    /// let wat = r#"(module (func (export "run") ))"#;
610    /// let module = Module::new(&engine, wat)?;
611    /// let instance = linker.instantiate(&mut store, &module)?;
612    ///
613    /// // ... and inform the linker that the name of this instance is
614    /// // `instance1`. This defines the `instance1::run` name for our next
615    /// // module to use.
616    /// linker.instance(&mut store, "instance1", instance)?;
617    ///
618    /// let wat = r#"
619    ///     (module
620    ///         (import "instance1" "run" (func $instance1_run))
621    ///         (func (export "run")
622    ///             call $instance1_run
623    ///         )
624    ///     )
625    /// "#;
626    /// let module = Module::new(&engine, wat)?;
627    /// let instance = linker.instantiate(&mut store, &module)?;
628    /// # Ok(())
629    /// # }
630    /// ```
631    ///
632    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
633    /// memory allocation fails. See the `OutOfMemory` type's documentation for
634    /// details on Wasmtime's out-of-memory handling.
635    pub fn instance(
636        &mut self,
637        mut store: impl AsContextMut<Data = T>,
638        module_name: &str,
639        instance: Instance,
640    ) -> Result<&mut Self>
641    where
642        T: 'static,
643    {
644        let mut store = store.as_context_mut();
645        let exports: TryVec<_> = instance
646            .exports(&mut store)
647            .map(|e| Ok((self.import_key(module_name, e.name())?, e.into_extern())))
648            .try_collect::<_, Error>()?;
649        for (key, export) in exports {
650            self.insert(key, Definition::new(store.0, export))?;
651        }
652        Ok(self)
653    }
654
655    /// Define automatic instantiations of a [`Module`] in this linker.
656    ///
657    /// This automatically handles [Commands and Reactors] instantiation and
658    /// initialization.
659    ///
660    /// Exported functions of a Command module may be called directly, however
661    /// instead of having a single instance which is reused for each call,
662    /// each call creates a new instance, which lives for the duration of the
663    /// call. The imports of the Command are resolved once, and reused for
664    /// each instantiation, so all dependencies need to be present at the time
665    /// when `Linker::module` is called.
666    ///
667    /// For Reactors, a single instance is created, and an initialization
668    /// function is called, and then its exports may be called.
669    ///
670    /// Ordinary modules which don't declare themselves to be either Commands
671    /// or Reactors are treated as Reactors without any initialization calls.
672    ///
673    /// [Commands and Reactors]: https://github.com/WebAssembly/WASI/blob/main/legacy/application-abi.md#current-unstable-abi
674    ///
675    /// # Errors
676    ///
677    /// Returns an error if the any item is redefined twice in this linker (for
678    /// example the same `module_name` was already defined) and shadowing is
679    /// disallowed, if `instance` comes from a different
680    /// [`Store`](crate::Store) than this [`Linker`] originally was created
681    /// with, or if a Reactor initialization function traps.
682    ///
683    /// # Panics
684    ///
685    /// Panics if any item used to instantiate the provided [`Module`] is not
686    /// owned by `store`, or if the `store` provided comes from a different
687    /// [`Engine`] than this [`Linker`].
688    ///
689    /// # Examples
690    ///
691    /// ```
692    /// # use wasmtime::*;
693    /// # fn main() -> Result<()> {
694    /// # let engine = Engine::default();
695    /// # let mut store = Store::new(&engine, ());
696    /// let mut linker = Linker::new(&engine);
697    ///
698    /// // Instantiate a small instance and inform the linker that the name of
699    /// // this instance is `instance1`. This defines the `instance1::run` name
700    /// // for our next module to use.
701    /// let wat = r#"(module (func (export "run") ))"#;
702    /// let module = Module::new(&engine, wat)?;
703    /// linker.module(&mut store, "instance1", &module)?;
704    ///
705    /// let wat = r#"
706    ///     (module
707    ///         (import "instance1" "run" (func $instance1_run))
708    ///         (func (export "run")
709    ///             call $instance1_run
710    ///         )
711    ///     )
712    /// "#;
713    /// let module = Module::new(&engine, wat)?;
714    /// let instance = linker.instantiate(&mut store, &module)?;
715    /// # Ok(())
716    /// # }
717    /// ```
718    ///
719    /// For a Command, a new instance is created for each call.
720    ///
721    /// ```
722    /// # use wasmtime::*;
723    /// # fn main() -> Result<()> {
724    /// # let engine = Engine::default();
725    /// # let mut store = Store::new(&engine, ());
726    /// let mut linker = Linker::new(&engine);
727    ///
728    /// // Create a Command that attempts to count the number of times it is run, but is
729    /// // foiled by each call getting a new instance.
730    /// let wat = r#"
731    ///     (module
732    ///         (global $counter (mut i32) (i32.const 0))
733    ///         (func (export "_start")
734    ///             (global.set $counter (i32.add (global.get $counter) (i32.const 1)))
735    ///         )
736    ///         (func (export "read_counter") (result i32)
737    ///             (global.get $counter)
738    ///         )
739    ///     )
740    /// "#;
741    /// let module = Module::new(&engine, wat)?;
742    /// linker.module(&mut store, "commander", &module)?;
743    /// let run = linker.get_default(&mut store, "")?
744    ///     .typed::<(), ()>(&store)?
745    ///     .clone();
746    /// run.call(&mut store, ())?;
747    /// run.call(&mut store, ())?;
748    /// run.call(&mut store, ())?;
749    ///
750    /// let wat = r#"
751    ///     (module
752    ///         (import "commander" "_start" (func $commander_start))
753    ///         (import "commander" "read_counter" (func $commander_read_counter (result i32)))
754    ///         (func (export "run") (result i32)
755    ///             call $commander_start
756    ///             call $commander_start
757    ///             call $commander_start
758    ///             call $commander_read_counter
759    ///         )
760    ///     )
761    /// "#;
762    /// let module = Module::new(&engine, wat)?;
763    /// linker.module(&mut store, "", &module)?;
764    /// let run = linker.get(&mut store, "", "run").unwrap().into_func().unwrap();
765    /// let count = run.typed::<(), i32>(&store)?.call(&mut store, ())?;
766    /// assert_eq!(count, 0, "a Command should get a fresh instance on each invocation");
767    ///
768    /// # Ok(())
769    /// # }
770    /// ```
771    pub fn module(
772        &mut self,
773        mut store: impl AsContextMut<Data = T>,
774        module_name: &str,
775        module: &Module,
776    ) -> Result<&mut Self>
777    where
778        T: 'static,
779    {
780        // NB: this is intended to function the same as `Linker::module_async`,
781        // they should be kept in sync.
782
783        // This assert isn't strictly necessary since it'll bottom out in the
784        // `HostFunc::to_func` method anyway. This is placed earlier for this
785        // function though to prevent the functions created here from delaying
786        // the panic until they're called.
787        assert!(
788            Engine::same(&self.engine, store.as_context().engine()),
789            "different engines for this linker and the store provided"
790        );
791        match ModuleKind::categorize(module)? {
792            ModuleKind::Command => {
793                self.command(
794                    store,
795                    module_name,
796                    module,
797                    |store, func_ty, export_name, instance_pre| {
798                        Func::new(
799                            store,
800                            func_ty.clone(),
801                            move |mut caller, params, results| {
802                                // Create a new instance for this command execution.
803                                let instance = instance_pre.instantiate(&mut caller)?;
804
805                                // `unwrap()` everything here because we know the instance contains a
806                                // function export with the given name and signature because we're
807                                // iterating over the module it was instantiated from.
808                                instance
809                                    .get_export(&mut caller, &export_name)
810                                    .unwrap()
811                                    .into_func()
812                                    .unwrap()
813                                    .call(&mut caller, params, results)?;
814
815                                Ok(())
816                            },
817                        )
818                    },
819                )
820            }
821            ModuleKind::Reactor => {
822                let instance = self.instantiate(&mut store, &module)?;
823
824                if let Some(export) = instance.get_export(&mut store, "_initialize") {
825                    if let Extern::Func(func) = export {
826                        func.typed::<(), ()>(&store)
827                            .and_then(|f| f.call(&mut store, ()))
828                            .context("calling the Reactor initialization function")?;
829                    }
830                }
831
832                self.instance(store, module_name, instance)
833            }
834        }
835    }
836
837    /// Define automatic instantiations of a [`Module`] in this linker.
838    ///
839    /// This is the same as [`Linker::module`], except for async `Store`s.
840    ///
841    /// # Errors
842    ///
843    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
844    /// memory allocation fails. See the `OutOfMemory` type's documentation for
845    /// details on Wasmtime's out-of-memory handling.
846    #[cfg(feature = "async")]
847    pub async fn module_async(
848        &mut self,
849        mut store: impl AsContextMut<Data = T>,
850        module_name: &str,
851        module: &Module,
852    ) -> Result<&mut Self>
853    where
854        T: Send + 'static,
855    {
856        // NB: this is intended to function the same as `Linker::module`, they
857        // should be kept in sync.
858        assert!(
859            Engine::same(&self.engine, store.as_context().engine()),
860            "different engines for this linker and the store provided"
861        );
862        match ModuleKind::categorize(module)? {
863            ModuleKind::Command => self.command(
864                store,
865                module_name,
866                module,
867                |store, func_ty, export_name, instance_pre| {
868                    let upvars = Arc::new((instance_pre, export_name));
869                    Func::new_async(
870                        store,
871                        func_ty.clone(),
872                        move |mut caller, params, results| {
873                            let upvars = upvars.clone();
874                            Box::new(async move {
875                                let (instance_pre, export_name) = &*upvars;
876                                let instance = instance_pre.instantiate_async(&mut caller).await?;
877
878                                instance
879                                    .get_export(&mut caller, &export_name)
880                                    .unwrap()
881                                    .into_func()
882                                    .unwrap()
883                                    .call_async(&mut caller, params, results)
884                                    .await?;
885                                Ok(())
886                            })
887                        },
888                    )
889                },
890            ),
891            ModuleKind::Reactor => {
892                let instance = self.instantiate_async(&mut store, &module).await?;
893
894                if let Some(export) = instance.get_export(&mut store, "_initialize") {
895                    if let Extern::Func(func) = export {
896                        let func = func
897                            .typed::<(), ()>(&store)
898                            .context("loading the Reactor initialization function")?;
899                        func.call_async(&mut store, ())
900                            .await
901                            .context("calling the Reactor initialization function")?;
902                    }
903                }
904
905                self.instance(store, module_name, instance)
906            }
907        }
908    }
909
910    fn command(
911        &mut self,
912        mut store: impl AsContextMut<Data = T>,
913        module_name: &str,
914        module: &Module,
915        mk_func: impl Fn(&mut StoreContextMut<T>, &FuncType, String, InstancePre<T>) -> Func,
916    ) -> Result<&mut Self>
917    where
918        T: 'static,
919    {
920        let mut store = store.as_context_mut();
921        for export in module.exports() {
922            if let Some(func_ty) = export.ty().func() {
923                let instance_pre = self.instantiate_pre(module)?;
924                let export_name = export.name().to_owned();
925                let func = mk_func(&mut store, func_ty, export_name, instance_pre);
926                let key = self.import_key(module_name, export.name())?;
927                self.insert(key, Definition::new(store.0, func.into()))?;
928            } else if export.name() == "memory" && export.ty().memory().is_some() {
929                // Allow an exported "memory" memory for now.
930            } else if export.name() == "__indirect_function_table" && export.ty().table().is_some()
931            {
932                // Allow an exported "__indirect_function_table" table for now.
933            } else if export.name() == "table" && export.ty().table().is_some() {
934                // Allow an exported "table" table for now.
935            } else if export.name() == "__data_end" && export.ty().global().is_some() {
936                // Allow an exported "__data_end" memory for compatibility with toolchains
937                // which use --export-dynamic, which unfortunately doesn't work the way
938                // we want it to.
939                warn!("command module exporting '__data_end' is deprecated");
940            } else if export.name() == "__heap_base" && export.ty().global().is_some() {
941                // Allow an exported "__data_end" memory for compatibility with toolchains
942                // which use --export-dynamic, which unfortunately doesn't work the way
943                // we want it to.
944                warn!("command module exporting '__heap_base' is deprecated");
945            } else if export.name() == "__dso_handle" && export.ty().global().is_some() {
946                // Allow an exported "__dso_handle" memory for compatibility with toolchains
947                // which use --export-dynamic, which unfortunately doesn't work the way
948                // we want it to.
949                warn!("command module exporting '__dso_handle' is deprecated")
950            } else if export.name() == "__rtti_base" && export.ty().global().is_some() {
951                // Allow an exported "__rtti_base" memory for compatibility with
952                // AssemblyScript.
953                warn!(
954                    "command module exporting '__rtti_base' is deprecated; pass `--runtime half` to the AssemblyScript compiler"
955                );
956            } else if !self.allow_unknown_exports {
957                bail!("command export '{}' is not a function", export.name());
958            }
959        }
960
961        Ok(self)
962    }
963
964    /// Aliases one item's name as another.
965    ///
966    /// This method will alias an item with the specified `module` and `name`
967    /// under a new name of `as_module` and `as_name`.
968    ///
969    /// # Errors
970    ///
971    /// Returns an error if any shadowing violations happen while defining new
972    /// items, or if the original item wasn't defined.
973    ///
974    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
975    /// memory allocation fails. See the `OutOfMemory` type's documentation for
976    /// details on Wasmtime's out-of-memory handling.
977    pub fn alias(
978        &mut self,
979        module: &str,
980        name: &str,
981        as_module: &str,
982        as_name: &str,
983    ) -> Result<&mut Self> {
984        let src = self.import_key(module, name)?;
985        let dst = self.import_key(as_module, as_name)?;
986        match self.map.get(&src).cloned() {
987            Some(item) => self.insert(dst, item)?,
988            None => bail!("no item named `{module}::{name}` defined"),
989        }
990        Ok(self)
991    }
992
993    /// Aliases one module's name as another.
994    ///
995    /// This method will alias all currently defined under `module` to also be
996    /// defined under the name `as_module` too.
997    ///
998    /// # Errors
999    ///
1000    /// Returns an error if any shadowing violations happen while defining new
1001    /// items.
1002    ///
1003    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1004    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1005    /// details on Wasmtime's out-of-memory handling.
1006    pub fn alias_module(&mut self, module: &str, as_module: &str) -> Result<()> {
1007        let module = self.pool.insert(module)?;
1008        let as_module = self.pool.insert(as_module)?;
1009        let items: TryVec<_> = self
1010            .map
1011            .iter()
1012            .filter(|(key, _def)| key.module == module)
1013            .map(|(key, def)| Ok((key.name, def.clone())))
1014            .try_collect::<_, Error>()?;
1015        for (name, item) in items {
1016            self.insert(
1017                ImportKey {
1018                    module: as_module,
1019                    name,
1020                },
1021                item,
1022            )?;
1023        }
1024        Ok(())
1025    }
1026
1027    fn insert(&mut self, key: ImportKey, item: Definition) -> Result<()> {
1028        if !self.allow_shadowing && self.map.contains_key(&key) {
1029            let module = &self.pool[key.module];
1030            let name = &self.pool[key.name];
1031            bail!("import of `{module}::{name}` defined twice");
1032        }
1033
1034        self.map.insert(key, item)?;
1035        Ok(())
1036    }
1037
1038    fn import_key(&mut self, module: &str, name: &str) -> Result<ImportKey, OutOfMemory> {
1039        Ok(ImportKey {
1040            module: self.pool.insert(module)?,
1041            name: self.pool.insert(name)?,
1042        })
1043    }
1044
1045    /// Attempts to instantiate the `module` provided.
1046    ///
1047    /// This method will attempt to assemble a list of imports that correspond
1048    /// to the imports required by the [`Module`] provided. This list
1049    /// of imports is then passed to [`Instance::new`] to continue the
1050    /// instantiation process.
1051    ///
1052    /// Each import of `module` will be looked up in this [`Linker`] and must
1053    /// have previously been defined. If it was previously defined with an
1054    /// incorrect signature or if it was not previously defined then an error
1055    /// will be returned because the import can not be satisfied.
1056    ///
1057    /// Per the WebAssembly spec, instantiation includes running the module's
1058    /// start function, if it has one (not to be confused with the `_start`
1059    /// function, which is not run).
1060    ///
1061    /// # Errors
1062    ///
1063    /// This method can fail because an import may not be found, or because
1064    /// instantiation itself may fail. For information on instantiation
1065    /// failures see [`Instance::new`]. If an import is not found, the error
1066    /// may be downcast to an [`UnknownImportError`].
1067    ///
1068    ///
1069    /// # Panics
1070    ///
1071    /// Panics if any item used to instantiate `module` is not owned by
1072    /// `store`. Additionally this will panic if the [`Engine`] that the `store`
1073    /// belongs to is different than this [`Linker`].
1074    ///
1075    /// # Examples
1076    ///
1077    /// ```
1078    /// # use wasmtime::*;
1079    /// # fn main() -> Result<()> {
1080    /// # let engine = Engine::default();
1081    /// # let mut store = Store::new(&engine, ());
1082    /// let mut linker = Linker::new(&engine);
1083    /// linker.func_wrap("host", "double", |x: i32| x * 2)?;
1084    ///
1085    /// let wat = r#"
1086    ///     (module
1087    ///         (import "host" "double" (func (param i32) (result i32)))
1088    ///     )
1089    /// "#;
1090    /// let module = Module::new(&engine, wat)?;
1091    /// linker.instantiate(&mut store, &module)?;
1092    /// # Ok(())
1093    /// # }
1094    /// ```
1095    pub fn instantiate(
1096        &self,
1097        mut store: impl AsContextMut<Data = T>,
1098        module: &Module,
1099    ) -> Result<Instance>
1100    where
1101        T: 'static,
1102    {
1103        self._instantiate_pre(module, Some(store.as_context_mut().0))?
1104            .instantiate(store)
1105    }
1106
1107    /// Attempts to instantiate the `module` provided. This is the same as
1108    /// [`Linker::instantiate`], except for async `Store`s.
1109    ///
1110    /// # Errors
1111    ///
1112    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1113    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1114    /// details on Wasmtime's out-of-memory handling.
1115    #[cfg(feature = "async")]
1116    pub async fn instantiate_async(
1117        &self,
1118        mut store: impl AsContextMut<Data = T>,
1119        module: &Module,
1120    ) -> Result<Instance>
1121    where
1122        T: Send + 'static,
1123    {
1124        self._instantiate_pre(module, Some(store.as_context_mut().0))?
1125            .instantiate_async(store)
1126            .await
1127    }
1128
1129    /// Performs all checks necessary for instantiating `module` with this
1130    /// linker, except that instantiation doesn't actually finish.
1131    ///
1132    /// This method is used for front-loading type-checking information as well
1133    /// as collecting the imports to use to instantiate a module with. The
1134    /// returned [`InstancePre`] represents a ready-to-be-instantiated module,
1135    /// which can also be instantiated multiple times if desired.
1136    ///
1137    /// # Errors
1138    ///
1139    /// Returns an error which may be downcast to an [`UnknownImportError`] if
1140    /// the module has any unresolvable imports.
1141    ///
1142    /// # Panics
1143    ///
1144    /// May panic if `module` imports an item defined in this linker whose
1145    /// [`Store`](crate::Store) has been dropped. See the [`Linker`]
1146    /// documentation for more information.
1147    ///
1148    /// # Examples
1149    ///
1150    /// ```
1151    /// # use wasmtime::*;
1152    /// # fn main() -> Result<()> {
1153    /// # let engine = Engine::default();
1154    /// # let mut store = Store::new(&engine, ());
1155    /// let mut linker = Linker::new(&engine);
1156    /// linker.func_wrap("host", "double", |x: i32| x * 2)?;
1157    ///
1158    /// let wat = r#"
1159    ///     (module
1160    ///         (import "host" "double" (func (param i32) (result i32)))
1161    ///     )
1162    /// "#;
1163    /// let module = Module::new(&engine, wat)?;
1164    /// let instance_pre = linker.instantiate_pre(&module)?;
1165    ///
1166    /// // Finish instantiation after the type-checking has all completed...
1167    /// let instance = instance_pre.instantiate(&mut store)?;
1168    ///
1169    /// // ... and we can even continue to keep instantiating if desired!
1170    /// instance_pre.instantiate(&mut store)?;
1171    /// instance_pre.instantiate(&mut store)?;
1172    ///
1173    /// // Note that functions defined in a linker with `func_wrap` and similar
1174    /// // constructors are not owned by any particular `Store`, so we can also
1175    /// // instantiate our `instance_pre` in other stores because no imports
1176    /// // belong to the original store.
1177    /// let mut new_store = Store::new(&engine, ());
1178    /// instance_pre.instantiate(&mut new_store)?;
1179    /// # Ok(())
1180    /// # }
1181    /// ```
1182    ///
1183    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1184    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1185    /// details on Wasmtime's out-of-memory handling.
1186    pub fn instantiate_pre(&self, module: &Module) -> Result<InstancePre<T>>
1187    where
1188        T: 'static,
1189    {
1190        self._instantiate_pre(module, None)
1191    }
1192
1193    /// This is split out to optionally take a `store` so that when the
1194    /// `.instantiate` API is used we can get fresh up-to-date type information
1195    /// for memories and their current size, if necessary.
1196    ///
1197    /// Note that providing a `store` here is not required for correctness
1198    /// per-se. If one is not provided, such as the with the `instantiate_pre`
1199    /// API, then the type information used for memories and tables will reflect
1200    /// their size when inserted into the linker rather than their current size.
1201    /// This isn't expected to be much of a problem though since
1202    /// per-store-`Linker` types are likely using `.instantiate(..)` and
1203    /// per-`Engine` linkers don't have memories/tables in them.
1204    fn _instantiate_pre(
1205        &self,
1206        module: &Module,
1207        store: Option<&StoreOpaque>,
1208    ) -> Result<InstancePre<T>>
1209    where
1210        T: 'static,
1211    {
1212        ensure!(
1213            Engine::same(&self.engine, module.engine()),
1214            "cross-`Engine` instantiation is not currently supported"
1215        );
1216        let mut imports: TryVec<_> = module
1217            .imports()
1218            .map(|import| Ok(self._get_by_import(&import)?))
1219            .try_collect::<_, Error>()?;
1220        if let Some(store) = store {
1221            for import in imports.iter_mut() {
1222                import.update_size(store);
1223            }
1224        }
1225        unsafe { InstancePre::new(&self.engine, module, imports) }
1226    }
1227
1228    /// Returns an iterator over all items defined in this `Linker`, in
1229    /// arbitrary order.
1230    ///
1231    /// The iterator returned will yield 3-tuples where the first two elements
1232    /// are the module name and item name for the external item, and the third
1233    /// item is the item itself that is defined.
1234    ///
1235    /// Note that multiple `Extern` items may be defined for the same
1236    /// module/name pair.
1237    ///
1238    /// # Panics
1239    ///
1240    /// This function will panic if the `store` provided does not come from the
1241    /// same [`Engine`] that this linker was created with.
1242    pub fn iter<'a: 'p, 'p>(
1243        &'a self,
1244        mut store: impl AsContextMut<Data = T> + 'p,
1245    ) -> impl Iterator<Item = (&'a str, &'a str, Extern)> + 'p
1246    where
1247        T: 'static,
1248    {
1249        self.map.iter().map(move |(key, item)| {
1250            let store = store.as_context_mut();
1251            (
1252                &self.pool[key.module],
1253                &self.pool[key.name],
1254                // Should be safe since `T` is connecting the linker and store
1255                unsafe { item.to_extern(store.0).panic_on_oom() },
1256            )
1257        })
1258    }
1259
1260    /// Looks up a previously defined value in this [`Linker`], identified by
1261    /// the names provided.
1262    ///
1263    /// Returns an error if this name was not previously defined in this
1264    /// [`Linker`].
1265    ///
1266    /// # Panics
1267    ///
1268    /// This function will panic if the `store` provided does not come from the
1269    /// same [`Engine`] that this linker was created with.
1270    ///
1271    /// # Errors
1272    ///
1273    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1274    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1275    /// details on Wasmtime's out-of-memory handling.
1276    pub fn get(
1277        &self,
1278        mut store: impl AsContextMut<Data = T>,
1279        module: &str,
1280        name: &str,
1281    ) -> Result<Extern>
1282    where
1283        T: 'static,
1284    {
1285        let store = store.as_context_mut().0;
1286        match self._get(module, name) {
1287            // Safety: `T` is connecting the linker and store.
1288            Some(def) => Ok(unsafe { def.to_extern(store)? }),
1289            None => bail!("missing definition for `{module}::{name}`"),
1290        }
1291    }
1292
1293    fn _get(&self, module: &str, name: &str) -> Option<&Definition> {
1294        let key = ImportKey {
1295            module: self.pool.get_atom(module)?,
1296            name: self.pool.get_atom(name)?,
1297        };
1298        self.map.get(&key)
1299    }
1300
1301    /// Looks up a value in this `Linker` which matches the `import` type
1302    /// provided.
1303    ///
1304    /// Returns `None` if no match was found.
1305    ///
1306    /// # Panics
1307    ///
1308    /// This function will panic if the `store` provided does not come from the
1309    /// same [`Engine`] that this linker was created with.
1310    pub fn get_by_import(
1311        &self,
1312        store: impl AsContextMut<Data = T>,
1313        import: &ImportType,
1314    ) -> Option<Extern>
1315    where
1316        T: 'static,
1317    {
1318        self.try_get_by_import(store, import)
1319            .expect("out of memory")
1320    }
1321
1322    /// Same as [`Linker::get_by_import`] but returns an error instead of
1323    /// panicking on allocation failure.
1324    ///
1325    /// # Errors
1326    ///
1327    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1328    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1329    /// details on Wasmtime's out-of-memory handling.
1330    pub fn try_get_by_import(
1331        &self,
1332        mut store: impl AsContextMut<Data = T>,
1333        import: &ImportType,
1334    ) -> Result<Option<Extern>>
1335    where
1336        T: 'static,
1337    {
1338        let store = store.as_context_mut().0;
1339        match self._get_by_import(import) {
1340            // Should be safe since `T` is connecting the linker and store
1341            Ok(def) => Ok(Some(unsafe { def.to_extern(store)? })),
1342            Err(_) => Ok(None),
1343        }
1344    }
1345
1346    fn _get_by_import(&self, import: &ImportType) -> Result<Definition, UnknownImportError> {
1347        match self._get(import.module(), import.name()) {
1348            Some(item) => Ok(item.clone()),
1349            None => Err(UnknownImportError::new(import)),
1350        }
1351    }
1352
1353    /// Returns the "default export" of a module.
1354    ///
1355    /// An export with an empty string is considered to be a "default export".
1356    /// "_start" is also recognized for compatibility.
1357    ///
1358    /// # Panics
1359    ///
1360    /// Panics if the default function found is not owned by `store`. This
1361    /// function will also panic if the `store` provided does not come from the
1362    /// same [`Engine`] that this linker was created with.
1363    ///
1364    /// # Errors
1365    ///
1366    /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
1367    /// memory allocation fails. See the `OutOfMemory` type's documentation for
1368    /// details on Wasmtime's out-of-memory handling.
1369    pub fn get_default(&self, mut store: impl AsContextMut<Data = T>, module: &str) -> Result<Func>
1370    where
1371        T: 'static,
1372    {
1373        if let Some(external) = self.get(&mut store, module, "").map(Some).or_else(|e| {
1374            if e.is::<OutOfMemory>() {
1375                Err(e)
1376            } else {
1377                Ok(None)
1378            }
1379        })? {
1380            if let Extern::Func(func) = external {
1381                return Ok(func);
1382            }
1383            bail!("default export in '{module}' is not a function");
1384        }
1385
1386        // For compatibility, also recognize "_start".
1387        if let Some(external) = self
1388            .get(&mut store, module, "_start")
1389            .map(Some)
1390            .or_else(|e| {
1391                if e.is::<OutOfMemory>() {
1392                    Err(e)
1393                } else {
1394                    Ok(None)
1395                }
1396            })?
1397        {
1398            if let Extern::Func(func) = external {
1399                return Ok(func);
1400            }
1401            bail!("`_start` in '{module}' is not a function");
1402        }
1403
1404        // Otherwise return a no-op function.
1405        Ok(Func::wrap(store, || {}))
1406    }
1407}
1408
1409impl<T: 'static> Default for Linker<T> {
1410    fn default() -> Linker<T> {
1411        Linker::new(&Engine::default())
1412    }
1413}
1414
1415impl Definition {
1416    fn new(store: &StoreOpaque, item: Extern) -> Definition {
1417        let ty = DefinitionType::from(store, &item);
1418        Definition::Extern {
1419            item,
1420            ty,
1421            engine: store.engine().clone(),
1422        }
1423    }
1424
1425    pub(crate) fn ty(&self) -> DefinitionType {
1426        match self {
1427            Definition::Extern { ty, .. } => *ty,
1428            Definition::HostFunc(func) => DefinitionType::Func(func.sig_index()),
1429        }
1430    }
1431
1432    /// The engine that assigned the type indices within this definition's
1433    /// [`Definition::ty`].
1434    pub(crate) fn engine(&self) -> &Engine {
1435        match self {
1436            Definition::Extern { engine, .. } => engine,
1437            Definition::HostFunc(func) => func.engine(),
1438        }
1439    }
1440
1441    /// Inserts this definition into the `store` provided.
1442    ///
1443    /// # Safety
1444    ///
1445    /// Note the unsafety here is due to calling `HostFunc::to_func`. The
1446    /// requirement here is that the `T` that was originally used to create the
1447    /// `HostFunc` matches the `T` on the store.
1448    pub(crate) unsafe fn to_extern(&self, store: &mut StoreOpaque) -> Result<Extern, OutOfMemory> {
1449        match self {
1450            Definition::Extern { item, .. } => Ok(item.clone()),
1451            // SAFETY: the contract of this function is the same as what's
1452            // required of `to_func`, that `T` of the store matches the `T` of
1453            // this original definition.
1454            Definition::HostFunc(func) => unsafe { Ok(func.to_func(store)?.into()) },
1455        }
1456    }
1457
1458    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
1459        match self {
1460            Definition::Extern { item, .. } => item.comes_from_same_store(store),
1461            Definition::HostFunc(_func) => true,
1462        }
1463    }
1464
1465    fn update_size(&mut self, store: &StoreOpaque) {
1466        match self {
1467            Definition::Extern {
1468                item: Extern::Memory(m),
1469                ty: DefinitionType::Memory(_, size),
1470                ..
1471            } => {
1472                *size = m.internal_size(store);
1473            }
1474            Definition::Extern {
1475                item: Extern::SharedMemory(m),
1476                ty: DefinitionType::Memory(_, size),
1477                ..
1478            } => {
1479                *size = m.size();
1480            }
1481            Definition::Extern {
1482                item: Extern::Table(m),
1483                ty: DefinitionType::Table(_, size),
1484                ..
1485            } => {
1486                *size = m.size_(store);
1487            }
1488            _ => {}
1489        }
1490    }
1491}
1492
1493impl DefinitionType {
1494    pub(crate) fn from(store: &StoreOpaque, item: &Extern) -> DefinitionType {
1495        match item {
1496            Extern::Func(f) => DefinitionType::Func(f.type_index(store)),
1497            Extern::Table(t) => DefinitionType::Table(*t.wasmtime_ty(store), t.size_(store)),
1498            Extern::Global(t) => DefinitionType::Global(*t.wasmtime_ty(store)),
1499            Extern::Memory(t) => {
1500                DefinitionType::Memory(*t.wasmtime_ty(store), t.internal_size(store))
1501            }
1502            Extern::SharedMemory(t) => DefinitionType::Memory(*t.ty().wasmtime_memory(), t.size()),
1503            Extern::Tag(t) => DefinitionType::Tag(*t.wasmtime_ty(store)),
1504        }
1505    }
1506
1507    pub(crate) fn desc(&self) -> &'static str {
1508        match self {
1509            DefinitionType::Func(_) => "function",
1510            DefinitionType::Table(..) => "table",
1511            DefinitionType::Memory(..) => "memory",
1512            DefinitionType::Global(_) => "global",
1513            DefinitionType::Tag(_) => "tag",
1514        }
1515    }
1516}
1517
1518/// Modules can be interpreted either as Commands or Reactors.
1519enum ModuleKind {
1520    /// The instance is a Command, meaning an instance is created for each
1521    /// exported function and lives for the duration of the function call.
1522    Command,
1523
1524    /// The instance is a Reactor, meaning one instance is created which
1525    /// may live across multiple calls.
1526    Reactor,
1527}
1528
1529impl ModuleKind {
1530    /// Determine whether the given module is a Command or a Reactor.
1531    fn categorize(module: &Module) -> Result<ModuleKind> {
1532        let command_start = module.get_export("_start");
1533        let reactor_start = module.get_export("_initialize");
1534        match (command_start, reactor_start) {
1535            (Some(command_start), None) => {
1536                if let Some(_) = command_start.func() {
1537                    Ok(ModuleKind::Command)
1538                } else {
1539                    bail!("`_start` must be a function")
1540                }
1541            }
1542            (None, Some(reactor_start)) => {
1543                if let Some(_) = reactor_start.func() {
1544                    Ok(ModuleKind::Reactor)
1545                } else {
1546                    bail!("`_initialize` must be a function")
1547                }
1548            }
1549            (None, None) => {
1550                // Module declares neither of the recognized functions, so treat
1551                // it as a reactor with no initialization function.
1552                Ok(ModuleKind::Reactor)
1553            }
1554            (Some(_), Some(_)) => {
1555                // Module declares itself to be both a Command and a Reactor.
1556                bail!("Program cannot be both a Command and a Reactor")
1557            }
1558        }
1559    }
1560}
1561
1562/// Error for an unresolvable import.
1563///
1564/// Returned - wrapped in an [`Error`][crate::Error] - by
1565/// [`Linker::instantiate`] and related methods for modules with unresolvable
1566/// imports.
1567#[derive(Clone, Debug)]
1568pub struct UnknownImportError {
1569    module: String,
1570    name: String,
1571    ty: ExternType,
1572}
1573
1574impl UnknownImportError {
1575    fn new(import: &ImportType) -> Self {
1576        Self {
1577            module: import.module().to_string(),
1578            name: import.name().to_string(),
1579            ty: import.ty(),
1580        }
1581    }
1582
1583    /// Returns the module name that the unknown import was expected to come from.
1584    pub fn module(&self) -> &str {
1585        &self.module
1586    }
1587
1588    /// Returns the field name of the module that the unknown import was expected to come from.
1589    pub fn name(&self) -> &str {
1590        &self.name
1591    }
1592
1593    /// Returns the type of the unknown import.
1594    pub fn ty(&self) -> ExternType {
1595        self.ty.clone()
1596    }
1597}
1598
1599impl fmt::Display for UnknownImportError {
1600    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1601        write!(
1602            f,
1603            "unknown import: `{}::{}` has not been defined",
1604            self.module, self.name,
1605        )
1606    }
1607}
1608
1609impl core::error::Error for UnknownImportError {}