wasmtime/runtime/
linker.rs

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