wasmtime/runtime/linker.rs
1use crate::func::HostFunc;
2use crate::hash_map::{Entry, HashMap};
3use crate::instance::InstancePre;
4use crate::store::StoreOpaque;
5use crate::{prelude::*, IntoFunc};
6use crate::{
7 AsContext, AsContextMut, Caller, Engine, Extern, ExternType, Func, FuncType, ImportType,
8 Instance, Module, StoreContextMut, Val, ValRaw,
9};
10use alloc::sync::Arc;
11use core::fmt::{self, Debug};
12use core::marker;
13#[cfg(feature = "async")]
14use core::{future::Future, pin::Pin};
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 for import in module.imports() {
245 if let Err(import_err) = self._get_by_import(&import) {
246 if let ExternType::Func(func_ty) = import_err.ty() {
247 self.func_new(import.module(), import.name(), func_ty, move |_, _, _| {
248 bail!(import_err.clone());
249 })?;
250 }
251 }
252 }
253 Ok(())
254 }
255
256 /// Implement any function imports of the [`Module`] with a function that
257 /// ignores its arguments and returns default values.
258 ///
259 /// Default values are either zero or null, depending on the value type.
260 ///
261 /// This method can be used to allow unknown imports from command modules.
262 ///
263 /// # Example
264 ///
265 /// ```
266 /// # use wasmtime::*;
267 /// # fn main() -> anyhow::Result<()> {
268 /// # let engine = Engine::default();
269 /// # let module = Module::new(&engine, "(module (import \"unknown\" \"import\" (func)))")?;
270 /// # let mut store = Store::new(&engine, ());
271 /// let mut linker = Linker::new(&engine);
272 /// linker.define_unknown_imports_as_default_values(&mut store, &module)?;
273 /// linker.instantiate(&mut store, &module)?;
274 /// # Ok(())
275 /// # }
276 /// ```
277 pub fn define_unknown_imports_as_default_values(
278 &mut self,
279 store: &mut impl AsContextMut<Data = T>,
280 module: &Module,
281 ) -> anyhow::Result<()> {
282 for import in module.imports() {
283 if let Err(import_err) = self._get_by_import(&import) {
284 let default_extern =
285 import_err
286 .ty()
287 .default_value(&mut *store)
288 .with_context(|| {
289 anyhow!(
290 "no default value exists for `{}::{}` with type `{:?}`",
291 import.module(),
292 import.name(),
293 import_err.ty(),
294 )
295 })?;
296 self.define(
297 store.as_context(),
298 import.module(),
299 import.name(),
300 default_extern,
301 )?;
302 }
303 }
304 Ok(())
305 }
306
307 /// Defines a new item in this [`Linker`].
308 ///
309 /// This method will add a new definition, by name, to this instance of
310 /// [`Linker`]. The `module` and `name` provided are what to name the
311 /// `item`.
312 ///
313 /// # Errors
314 ///
315 /// Returns an error if the `module` and `name` already identify an item
316 /// of the same type as the `item` provided and if shadowing is disallowed.
317 /// For more information see the documentation on [`Linker`].
318 ///
319 /// # Examples
320 ///
321 /// ```
322 /// # use wasmtime::*;
323 /// # fn main() -> anyhow::Result<()> {
324 /// # let engine = Engine::default();
325 /// # let mut store = Store::new(&engine, ());
326 /// let mut linker = Linker::new(&engine);
327 /// let ty = GlobalType::new(ValType::I32, Mutability::Const);
328 /// let global = Global::new(&mut store, ty, Val::I32(0x1234))?;
329 /// linker.define(&store, "host", "offset", global)?;
330 ///
331 /// let wat = r#"
332 /// (module
333 /// (import "host" "offset" (global i32))
334 /// (memory 1)
335 /// (data (global.get 0) "foo")
336 /// )
337 /// "#;
338 /// let module = Module::new(&engine, wat)?;
339 /// linker.instantiate(&mut store, &module)?;
340 /// # Ok(())
341 /// # }
342 /// ```
343 pub fn define(
344 &mut self,
345 store: impl AsContext<Data = T>,
346 module: &str,
347 name: &str,
348 item: impl Into<Extern>,
349 ) -> Result<&mut Self> {
350 let store = store.as_context();
351 let key = self.import_key(module, Some(name));
352 self.insert(key, Definition::new(store.0, item.into()))?;
353 Ok(self)
354 }
355
356 /// Same as [`Linker::define`], except only the name of the import is
357 /// provided, not a module name as well.
358 ///
359 /// This is only relevant when working with the module linking proposal
360 /// where one-level names are allowed (in addition to two-level names).
361 /// Otherwise this method need not be used.
362 pub fn define_name(
363 &mut self,
364 store: impl AsContext<Data = T>,
365 name: &str,
366 item: impl Into<Extern>,
367 ) -> Result<&mut Self> {
368 let store = store.as_context();
369 let key = self.import_key(name, None);
370 self.insert(key, Definition::new(store.0, item.into()))?;
371 Ok(self)
372 }
373
374 /// Creates a [`Func::new`]-style function named in this linker.
375 ///
376 /// For more information see [`Linker::func_wrap`].
377 ///
378 /// # Panics
379 ///
380 /// Panics if the given function type is not associated with the same engine
381 /// as this linker.
382 pub fn func_new(
383 &mut self,
384 module: &str,
385 name: &str,
386 ty: FuncType,
387 func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
388 ) -> Result<&mut Self> {
389 assert!(ty.comes_from_same_engine(self.engine()));
390 let func = HostFunc::new(&self.engine, ty, func);
391 let key = self.import_key(module, Some(name));
392 self.insert(key, Definition::HostFunc(Arc::new(func)))?;
393 Ok(self)
394 }
395
396 /// Creates a [`Func::new_unchecked`]-style function named in this linker.
397 ///
398 /// For more information see [`Linker::func_wrap`].
399 ///
400 /// # Panics
401 ///
402 /// Panics if the given function type is not associated with the same engine
403 /// as this linker.
404 pub unsafe fn func_new_unchecked(
405 &mut self,
406 module: &str,
407 name: &str,
408 ty: FuncType,
409 func: impl Fn(Caller<'_, T>, &mut [ValRaw]) -> Result<()> + Send + Sync + 'static,
410 ) -> Result<&mut Self> {
411 assert!(ty.comes_from_same_engine(self.engine()));
412 let func = HostFunc::new_unchecked(&self.engine, ty, func);
413 let key = self.import_key(module, Some(name));
414 self.insert(key, Definition::HostFunc(Arc::new(func)))?;
415 Ok(self)
416 }
417
418 /// Creates a [`Func::new_async`]-style function named in this linker.
419 ///
420 /// For more information see [`Linker::func_wrap`].
421 ///
422 /// # Panics
423 ///
424 /// This method panics in the following situations:
425 ///
426 /// * This linker is not associated with an [async
427 /// config](crate::Config::async_support).
428 ///
429 /// * If the given function type is not associated with the same engine as
430 /// this linker.
431 #[cfg(all(feature = "async", feature = "cranelift"))]
432 pub fn func_new_async<F>(
433 &mut self,
434 module: &str,
435 name: &str,
436 ty: FuncType,
437 func: F,
438 ) -> Result<&mut Self>
439 where
440 F: for<'a> Fn(
441 Caller<'a, T>,
442 &'a [Val],
443 &'a mut [Val],
444 ) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
445 + Send
446 + Sync
447 + 'static,
448 {
449 assert!(
450 self.engine.config().async_support,
451 "cannot use `func_new_async` without enabling async support in the config"
452 );
453 assert!(ty.comes_from_same_engine(self.engine()));
454 self.func_new(module, name, ty, move |mut caller, params, results| {
455 let async_cx = caller
456 .store
457 .as_context_mut()
458 .0
459 .async_cx()
460 .expect("Attempt to spawn new function on dying fiber");
461 let future = func(caller, params, results);
462 match unsafe { async_cx.block_on(Pin::from(future)) } {
463 Ok(Ok(())) => Ok(()),
464 Ok(Err(trap)) | Err(trap) => Err(trap),
465 }
466 })
467 }
468
469 /// Define a host function within this linker.
470 ///
471 /// For information about how the host function operates, see
472 /// [`Func::wrap`]. That includes information about translating Rust types
473 /// to WebAssembly native types.
474 ///
475 /// This method creates a host-provided function in this linker under the
476 /// provided name. This method is distinct in its capability to create a
477 /// [`Store`](crate::Store)-independent function. This means that the
478 /// function defined here can be used to instantiate instances in multiple
479 /// different stores, or in other words the function can be loaded into
480 /// different stores.
481 ///
482 /// Note that the capability mentioned here applies to all other
483 /// host-function-defining-methods on [`Linker`] as well. All of them can be
484 /// used to create instances of [`Func`] within multiple stores. In a
485 /// multithreaded program, for example, this means that the host functions
486 /// could be called concurrently if different stores are executing on
487 /// different threads.
488 ///
489 /// # Errors
490 ///
491 /// Returns an error if the `module` and `name` already identify an item
492 /// of the same type as the `item` provided and if shadowing is disallowed.
493 /// For more information see the documentation on [`Linker`].
494 ///
495 /// # Examples
496 ///
497 /// ```
498 /// # use wasmtime::*;
499 /// # fn main() -> anyhow::Result<()> {
500 /// # let engine = Engine::default();
501 /// let mut linker = Linker::new(&engine);
502 /// linker.func_wrap("host", "double", |x: i32| x * 2)?;
503 /// linker.func_wrap("host", "log_i32", |x: i32| println!("{}", x))?;
504 /// linker.func_wrap("host", "log_str", |caller: Caller<'_, ()>, ptr: i32, len: i32| {
505 /// // ...
506 /// })?;
507 ///
508 /// let wat = r#"
509 /// (module
510 /// (import "host" "double" (func (param i32) (result i32)))
511 /// (import "host" "log_i32" (func (param i32)))
512 /// (import "host" "log_str" (func (param i32 i32)))
513 /// )
514 /// "#;
515 /// let module = Module::new(&engine, wat)?;
516 ///
517 /// // instantiate in multiple different stores
518 /// for _ in 0..10 {
519 /// let mut store = Store::new(&engine, ());
520 /// linker.instantiate(&mut store, &module)?;
521 /// }
522 /// # Ok(())
523 /// # }
524 /// ```
525 pub fn func_wrap<Params, Args>(
526 &mut self,
527 module: &str,
528 name: &str,
529 func: impl IntoFunc<T, Params, Args>,
530 ) -> Result<&mut Self> {
531 let func = HostFunc::wrap(&self.engine, func);
532 let key = self.import_key(module, Some(name));
533 self.insert(key, Definition::HostFunc(Arc::new(func)))?;
534 Ok(self)
535 }
536
537 /// Asynchronous analog of [`Linker::func_wrap`].
538 #[cfg(feature = "async")]
539 pub fn func_wrap_async<F, Params: crate::WasmTyList, Args: crate::WasmRet>(
540 &mut self,
541 module: &str,
542 name: &str,
543 func: F,
544 ) -> Result<&mut Self>
545 where
546 F: for<'a> Fn(Caller<'a, T>, Params) -> Box<dyn Future<Output = Args> + Send + 'a>
547 + Send
548 + Sync
549 + 'static,
550 {
551 assert!(
552 self.engine.config().async_support,
553 "cannot use `func_wrap_async` without enabling async support on the config",
554 );
555 let func = HostFunc::wrap_inner(
556 &self.engine,
557 move |mut caller: Caller<'_, T>, args: Params| {
558 let async_cx = caller
559 .store
560 .as_context_mut()
561 .0
562 .async_cx()
563 .expect("Attempt to start async function on dying fiber");
564 let future = func(caller, args);
565 match unsafe { async_cx.block_on(Pin::from(future)) } {
566 Ok(ret) => ret.into_fallible(),
567 Err(e) => Args::fallible_from_error(e),
568 }
569 },
570 );
571 let key = self.import_key(module, Some(name));
572 self.insert(key, Definition::HostFunc(Arc::new(func)))?;
573 Ok(self)
574 }
575
576 /// Convenience wrapper to define an entire [`Instance`] in this linker.
577 ///
578 /// This function is a convenience wrapper around [`Linker::define`] which
579 /// will define all exports on `instance` into this linker. The module name
580 /// for each export is `module_name`, and the name for each export is the
581 /// name in the instance itself.
582 ///
583 /// Note that when this API is used the [`Linker`] is no longer compatible
584 /// with multi-[`Store`][crate::Store] instantiation because the items
585 /// defined within this store will belong to the `store` provided, and only
586 /// the `store` provided.
587 ///
588 /// # Errors
589 ///
590 /// Returns an error if the any item is redefined twice in this linker (for
591 /// example the same `module_name` was already defined) and shadowing is
592 /// disallowed, or if `instance` comes from a different
593 /// [`Store`](crate::Store) than this [`Linker`] originally was created
594 /// with.
595 ///
596 /// # Panics
597 ///
598 /// Panics if `instance` does not belong to `store`.
599 ///
600 /// # Examples
601 ///
602 /// ```
603 /// # use wasmtime::*;
604 /// # fn main() -> anyhow::Result<()> {
605 /// # let engine = Engine::default();
606 /// # let mut store = Store::new(&engine, ());
607 /// let mut linker = Linker::new(&engine);
608 ///
609 /// // Instantiate a small instance...
610 /// let wat = r#"(module (func (export "run") ))"#;
611 /// let module = Module::new(&engine, wat)?;
612 /// let instance = linker.instantiate(&mut store, &module)?;
613 ///
614 /// // ... and inform the linker that the name of this instance is
615 /// // `instance1`. This defines the `instance1::run` name for our next
616 /// // module to use.
617 /// linker.instance(&mut store, "instance1", instance)?;
618 ///
619 /// let wat = r#"
620 /// (module
621 /// (import "instance1" "run" (func $instance1_run))
622 /// (func (export "run")
623 /// call $instance1_run
624 /// )
625 /// )
626 /// "#;
627 /// let module = Module::new(&engine, wat)?;
628 /// let instance = linker.instantiate(&mut store, &module)?;
629 /// # Ok(())
630 /// # }
631 /// ```
632 pub fn instance(
633 &mut self,
634 mut store: impl AsContextMut<Data = T>,
635 module_name: &str,
636 instance: Instance,
637 ) -> Result<&mut Self> {
638 let mut store = store.as_context_mut();
639 let exports = instance
640 .exports(&mut store)
641 .map(|e| {
642 (
643 self.import_key(module_name, Some(e.name())),
644 e.into_extern(),
645 )
646 })
647 .collect::<Vec<_>>();
648 for (key, export) in exports {
649 self.insert(key, Definition::new(store.0, export))?;
650 }
651 Ok(self)
652 }
653
654 /// Define automatic instantiations of a [`Module`] in this linker.
655 ///
656 /// This automatically handles [Commands and Reactors] instantiation and
657 /// initialization.
658 ///
659 /// Exported functions of a Command module may be called directly, however
660 /// instead of having a single instance which is reused for each call,
661 /// each call creates a new instance, which lives for the duration of the
662 /// call. The imports of the Command are resolved once, and reused for
663 /// each instantiation, so all dependencies need to be present at the time
664 /// when `Linker::module` is called.
665 ///
666 /// For Reactors, a single instance is created, and an initialization
667 /// function is called, and then its exports may be called.
668 ///
669 /// Ordinary modules which don't declare themselves to be either Commands
670 /// or Reactors are treated as Reactors without any initialization calls.
671 ///
672 /// [Commands and Reactors]: https://github.com/WebAssembly/WASI/blob/main/legacy/application-abi.md#current-unstable-abi
673 ///
674 /// # Errors
675 ///
676 /// Returns an error if the any item is redefined twice in this linker (for
677 /// example the same `module_name` was already defined) and shadowing is
678 /// disallowed, if `instance` comes from a different
679 /// [`Store`](crate::Store) than this [`Linker`] originally was created
680 /// with, or if a Reactor initialization function traps.
681 ///
682 /// # Panics
683 ///
684 /// Panics if any item used to instantiate the provided [`Module`] is not
685 /// owned by `store`, or if the `store` provided comes from a different
686 /// [`Engine`] than this [`Linker`].
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// # use wasmtime::*;
692 /// # fn main() -> anyhow::Result<()> {
693 /// # let engine = Engine::default();
694 /// # let mut store = Store::new(&engine, ());
695 /// let mut linker = Linker::new(&engine);
696 ///
697 /// // Instantiate a small instance and inform the linker that the name of
698 /// // this instance is `instance1`. This defines the `instance1::run` name
699 /// // for our next module to use.
700 /// let wat = r#"(module (func (export "run") ))"#;
701 /// let module = Module::new(&engine, wat)?;
702 /// linker.module(&mut store, "instance1", &module)?;
703 ///
704 /// let wat = r#"
705 /// (module
706 /// (import "instance1" "run" (func $instance1_run))
707 /// (func (export "run")
708 /// call $instance1_run
709 /// )
710 /// )
711 /// "#;
712 /// let module = Module::new(&engine, wat)?;
713 /// let instance = linker.instantiate(&mut store, &module)?;
714 /// # Ok(())
715 /// # }
716 /// ```
717 ///
718 /// For a Command, a new instance is created for each call.
719 ///
720 /// ```
721 /// # use wasmtime::*;
722 /// # fn main() -> anyhow::Result<()> {
723 /// # let engine = Engine::default();
724 /// # let mut store = Store::new(&engine, ());
725 /// let mut linker = Linker::new(&engine);
726 ///
727 /// // Create a Command that attempts to count the number of times it is run, but is
728 /// // foiled by each call getting a new instance.
729 /// let wat = r#"
730 /// (module
731 /// (global $counter (mut i32) (i32.const 0))
732 /// (func (export "_start")
733 /// (global.set $counter (i32.add (global.get $counter) (i32.const 1)))
734 /// )
735 /// (func (export "read_counter") (result i32)
736 /// (global.get $counter)
737 /// )
738 /// )
739 /// "#;
740 /// let module = Module::new(&engine, wat)?;
741 /// linker.module(&mut store, "commander", &module)?;
742 /// let run = linker.get_default(&mut store, "")?
743 /// .typed::<(), ()>(&store)?
744 /// .clone();
745 /// run.call(&mut store, ())?;
746 /// run.call(&mut store, ())?;
747 /// run.call(&mut store, ())?;
748 ///
749 /// let wat = r#"
750 /// (module
751 /// (import "commander" "_start" (func $commander_start))
752 /// (import "commander" "read_counter" (func $commander_read_counter (result i32)))
753 /// (func (export "run") (result i32)
754 /// call $commander_start
755 /// call $commander_start
756 /// call $commander_start
757 /// call $commander_read_counter
758 /// )
759 /// )
760 /// "#;
761 /// let module = Module::new(&engine, wat)?;
762 /// linker.module(&mut store, "", &module)?;
763 /// let run = linker.get(&mut store, "", "run").unwrap().into_func().unwrap();
764 /// let count = run.typed::<(), i32>(&store)?.call(&mut store, ())?;
765 /// assert_eq!(count, 0, "a Command should get a fresh instance on each invocation");
766 ///
767 /// # Ok(())
768 /// # }
769 /// ```
770 pub fn module(
771 &mut self,
772 mut store: impl AsContextMut<Data = T>,
773 module_name: &str,
774 module: &Module,
775 ) -> Result<&mut Self>
776 where
777 T: 'static,
778 {
779 // NB: this is intended to function the same as `Linker::module_async`,
780 // they should be kept in sync.
781
782 // This assert isn't strictly necessary since it'll bottom out in the
783 // `HostFunc::to_func` method anyway. This is placed earlier for this
784 // function though to prevent the functions created here from delaying
785 // the panic until they're called.
786 assert!(
787 Engine::same(&self.engine, store.as_context().engine()),
788 "different engines for this linker and the store provided"
789 );
790 match ModuleKind::categorize(module)? {
791 ModuleKind::Command => {
792 self.command(
793 store,
794 module_name,
795 module,
796 |store, func_ty, export_name, instance_pre| {
797 Func::new(
798 store,
799 func_ty.clone(),
800 move |mut caller, params, results| {
801 // Create a new instance for this command execution.
802 let instance = instance_pre.instantiate(&mut caller)?;
803
804 // `unwrap()` everything here because we know the instance contains a
805 // function export with the given name and signature because we're
806 // iterating over the module it was instantiated from.
807 instance
808 .get_export(&mut caller, &export_name)
809 .unwrap()
810 .into_func()
811 .unwrap()
812 .call(&mut caller, params, results)?;
813
814 Ok(())
815 },
816 )
817 },
818 )
819 }
820 ModuleKind::Reactor => {
821 let instance = self.instantiate(&mut store, &module)?;
822
823 if let Some(export) = instance.get_export(&mut store, "_initialize") {
824 if let Extern::Func(func) = export {
825 func.typed::<(), ()>(&store)
826 .and_then(|f| f.call(&mut store, ()).map_err(Into::into))
827 .context("calling the Reactor initialization function")?;
828 }
829 }
830
831 self.instance(store, module_name, instance)
832 }
833 }
834 }
835
836 /// Define automatic instantiations of a [`Module`] in this linker.
837 ///
838 /// This is the same as [`Linker::module`], except for async `Store`s.
839 #[cfg(all(feature = "async", feature = "cranelift"))]
840 pub async fn module_async(
841 &mut self,
842 mut store: impl AsContextMut<Data = T>,
843 module_name: &str,
844 module: &Module,
845 ) -> Result<&mut Self>
846 where
847 T: Send + 'static,
848 {
849 // NB: this is intended to function the same as `Linker::module`, they
850 // should be kept in sync.
851 assert!(
852 Engine::same(&self.engine, store.as_context().engine()),
853 "different engines for this linker and the store provided"
854 );
855 match ModuleKind::categorize(module)? {
856 ModuleKind::Command => self.command(
857 store,
858 module_name,
859 module,
860 |store, func_ty, export_name, instance_pre| {
861 let upvars = Arc::new((instance_pre, export_name));
862 Func::new_async(
863 store,
864 func_ty.clone(),
865 move |mut caller, params, results| {
866 let upvars = upvars.clone();
867 Box::new(async move {
868 let (instance_pre, export_name) = &*upvars;
869 let instance = instance_pre.instantiate_async(&mut caller).await?;
870
871 instance
872 .get_export(&mut caller, &export_name)
873 .unwrap()
874 .into_func()
875 .unwrap()
876 .call_async(&mut caller, params, results)
877 .await?;
878 Ok(())
879 })
880 },
881 )
882 },
883 ),
884 ModuleKind::Reactor => {
885 let instance = self.instantiate_async(&mut store, &module).await?;
886
887 if let Some(export) = instance.get_export(&mut store, "_initialize") {
888 if let Extern::Func(func) = export {
889 let func = func
890 .typed::<(), ()>(&store)
891 .context("loading the Reactor initialization function")?;
892 func.call_async(&mut store, ())
893 .await
894 .context("calling the Reactor initialization function")?;
895 }
896 }
897
898 self.instance(store, module_name, instance)
899 }
900 }
901 }
902
903 fn command(
904 &mut self,
905 mut store: impl AsContextMut<Data = T>,
906 module_name: &str,
907 module: &Module,
908 mk_func: impl Fn(&mut StoreContextMut<T>, &FuncType, String, InstancePre<T>) -> Func,
909 ) -> Result<&mut Self>
910 where
911 T: 'static,
912 {
913 let mut store = store.as_context_mut();
914 for export in module.exports() {
915 if let Some(func_ty) = export.ty().func() {
916 let instance_pre = self.instantiate_pre(module)?;
917 let export_name = export.name().to_owned();
918 let func = mk_func(&mut store, func_ty, export_name, instance_pre);
919 let key = self.import_key(module_name, Some(export.name()));
920 self.insert(key, Definition::new(store.0, func.into()))?;
921 } else if export.name() == "memory" && export.ty().memory().is_some() {
922 // Allow an exported "memory" memory for now.
923 } else if export.name() == "__indirect_function_table" && export.ty().table().is_some()
924 {
925 // Allow an exported "__indirect_function_table" table for now.
926 } else if export.name() == "table" && export.ty().table().is_some() {
927 // Allow an exported "table" table for now.
928 } else if export.name() == "__data_end" && export.ty().global().is_some() {
929 // Allow an exported "__data_end" memory for compatibility with toolchains
930 // which use --export-dynamic, which unfortunately doesn't work the way
931 // we want it to.
932 warn!("command module exporting '__data_end' is deprecated");
933 } else if export.name() == "__heap_base" && export.ty().global().is_some() {
934 // Allow an exported "__data_end" memory for compatibility with toolchains
935 // which use --export-dynamic, which unfortunately doesn't work the way
936 // we want it to.
937 warn!("command module exporting '__heap_base' is deprecated");
938 } else if export.name() == "__dso_handle" && export.ty().global().is_some() {
939 // Allow an exported "__dso_handle" memory for compatibility with toolchains
940 // which use --export-dynamic, which unfortunately doesn't work the way
941 // we want it to.
942 warn!("command module exporting '__dso_handle' is deprecated")
943 } else if export.name() == "__rtti_base" && export.ty().global().is_some() {
944 // Allow an exported "__rtti_base" memory for compatibility with
945 // AssemblyScript.
946 warn!("command module exporting '__rtti_base' is deprecated; pass `--runtime half` to the AssemblyScript compiler");
947 } else if !self.allow_unknown_exports {
948 bail!("command export '{}' is not a function", export.name());
949 }
950 }
951
952 Ok(self)
953 }
954
955 /// Aliases one item's name as another.
956 ///
957 /// This method will alias an item with the specified `module` and `name`
958 /// under a new name of `as_module` and `as_name`.
959 ///
960 /// # Errors
961 ///
962 /// Returns an error if any shadowing violations happen while defining new
963 /// items, or if the original item wasn't defined.
964 pub fn alias(
965 &mut self,
966 module: &str,
967 name: &str,
968 as_module: &str,
969 as_name: &str,
970 ) -> Result<&mut Self> {
971 let src = self.import_key(module, Some(name));
972 let dst = self.import_key(as_module, Some(as_name));
973 match self.map.get(&src).cloned() {
974 Some(item) => self.insert(dst, item)?,
975 None => bail!("no item named `{}::{}` defined", module, name),
976 }
977 Ok(self)
978 }
979
980 /// Aliases one module's name as another.
981 ///
982 /// This method will alias all currently defined under `module` to also be
983 /// defined under the name `as_module` too.
984 ///
985 /// # Errors
986 ///
987 /// Returns an error if any shadowing violations happen while defining new
988 /// items.
989 pub fn alias_module(&mut self, module: &str, as_module: &str) -> Result<()> {
990 let module = self.intern_str(module);
991 let as_module = self.intern_str(as_module);
992 let items = self
993 .map
994 .iter()
995 .filter(|(key, _def)| key.module == module)
996 .map(|(key, def)| (key.name, def.clone()))
997 .collect::<Vec<_>>();
998 for (name, item) in items {
999 self.insert(
1000 ImportKey {
1001 module: as_module,
1002 name,
1003 },
1004 item,
1005 )?;
1006 }
1007 Ok(())
1008 }
1009
1010 fn insert(&mut self, key: ImportKey, item: Definition) -> Result<()> {
1011 match self.map.entry(key) {
1012 Entry::Occupied(_) if !self.allow_shadowing => {
1013 let module = &self.strings[key.module];
1014 let desc = match self.strings.get(key.name) {
1015 Some(name) => format!("{module}::{name}"),
1016 None => module.to_string(),
1017 };
1018 bail!("import of `{}` defined twice", desc)
1019 }
1020 Entry::Occupied(mut o) => {
1021 o.insert(item);
1022 }
1023 Entry::Vacant(v) => {
1024 v.insert(item);
1025 }
1026 }
1027 Ok(())
1028 }
1029
1030 fn import_key(&mut self, module: &str, name: Option<&str>) -> ImportKey {
1031 ImportKey {
1032 module: self.intern_str(module),
1033 name: name
1034 .map(|name| self.intern_str(name))
1035 .unwrap_or(usize::max_value()),
1036 }
1037 }
1038
1039 fn intern_str(&mut self, string: &str) -> usize {
1040 if let Some(idx) = self.string2idx.get(string) {
1041 return *idx;
1042 }
1043 let string: Arc<str> = string.into();
1044 let idx = self.strings.len();
1045 self.strings.push(string.clone());
1046 self.string2idx.insert(string, idx);
1047 idx
1048 }
1049
1050 /// Attempts to instantiate the `module` provided.
1051 ///
1052 /// This method will attempt to assemble a list of imports that correspond
1053 /// to the imports required by the [`Module`] provided. This list
1054 /// of imports is then passed to [`Instance::new`] to continue the
1055 /// instantiation process.
1056 ///
1057 /// Each import of `module` will be looked up in this [`Linker`] and must
1058 /// have previously been defined. If it was previously defined with an
1059 /// incorrect signature or if it was not previously defined then an error
1060 /// will be returned because the import can not be satisfied.
1061 ///
1062 /// Per the WebAssembly spec, instantiation includes running the module's
1063 /// start function, if it has one (not to be confused with the `_start`
1064 /// function, which is not run).
1065 ///
1066 /// # Errors
1067 ///
1068 /// This method can fail because an import may not be found, or because
1069 /// instantiation itself may fail. For information on instantiation
1070 /// failures see [`Instance::new`]. If an import is not found, the error
1071 /// may be downcast to an [`UnknownImportError`].
1072 ///
1073 ///
1074 /// # Panics
1075 ///
1076 /// Panics if any item used to instantiate `module` is not owned by
1077 /// `store`. Additionally this will panic if the [`Engine`] that the `store`
1078 /// belongs to is different than this [`Linker`].
1079 ///
1080 /// # Examples
1081 ///
1082 /// ```
1083 /// # use wasmtime::*;
1084 /// # fn main() -> anyhow::Result<()> {
1085 /// # let engine = Engine::default();
1086 /// # let mut store = Store::new(&engine, ());
1087 /// let mut linker = Linker::new(&engine);
1088 /// linker.func_wrap("host", "double", |x: i32| x * 2)?;
1089 ///
1090 /// let wat = r#"
1091 /// (module
1092 /// (import "host" "double" (func (param i32) (result i32)))
1093 /// )
1094 /// "#;
1095 /// let module = Module::new(&engine, wat)?;
1096 /// linker.instantiate(&mut store, &module)?;
1097 /// # Ok(())
1098 /// # }
1099 /// ```
1100 pub fn instantiate(
1101 &self,
1102 mut store: impl AsContextMut<Data = T>,
1103 module: &Module,
1104 ) -> Result<Instance> {
1105 self._instantiate_pre(module, Some(store.as_context_mut().0))?
1106 .instantiate(store)
1107 }
1108
1109 /// Attempts to instantiate the `module` provided. This is the same as
1110 /// [`Linker::instantiate`], except for async `Store`s.
1111 #[cfg(feature = "async")]
1112 pub async fn instantiate_async(
1113 &self,
1114 mut store: impl AsContextMut<Data = T>,
1115 module: &Module,
1116 ) -> Result<Instance>
1117 where
1118 T: Send,
1119 {
1120 self._instantiate_pre(module, Some(store.as_context_mut().0))?
1121 .instantiate_async(store)
1122 .await
1123 }
1124
1125 /// Performs all checks necessary for instantiating `module` with this
1126 /// linker, except that instantiation doesn't actually finish.
1127 ///
1128 /// This method is used for front-loading type-checking information as well
1129 /// as collecting the imports to use to instantiate a module with. The
1130 /// returned [`InstancePre`] represents a ready-to-be-instantiated module,
1131 /// which can also be instantiated multiple times if desired.
1132 ///
1133 /// # Errors
1134 ///
1135 /// Returns an error which may be downcast to an [`UnknownImportError`] if
1136 /// the module has any unresolvable imports.
1137 ///
1138 /// # Examples
1139 ///
1140 /// ```
1141 /// # use wasmtime::*;
1142 /// # fn main() -> anyhow::Result<()> {
1143 /// # let engine = Engine::default();
1144 /// # let mut store = Store::new(&engine, ());
1145 /// let mut linker = Linker::new(&engine);
1146 /// linker.func_wrap("host", "double", |x: i32| x * 2)?;
1147 ///
1148 /// let wat = r#"
1149 /// (module
1150 /// (import "host" "double" (func (param i32) (result i32)))
1151 /// )
1152 /// "#;
1153 /// let module = Module::new(&engine, wat)?;
1154 /// let instance_pre = linker.instantiate_pre(&module)?;
1155 ///
1156 /// // Finish instantiation after the type-checking has all completed...
1157 /// let instance = instance_pre.instantiate(&mut store)?;
1158 ///
1159 /// // ... and we can even continue to keep instantiating if desired!
1160 /// instance_pre.instantiate(&mut store)?;
1161 /// instance_pre.instantiate(&mut store)?;
1162 ///
1163 /// // Note that functions defined in a linker with `func_wrap` and similar
1164 /// // constructors are not owned by any particular `Store`, so we can also
1165 /// // instantiate our `instance_pre` in other stores because no imports
1166 /// // belong to the original store.
1167 /// let mut new_store = Store::new(&engine, ());
1168 /// instance_pre.instantiate(&mut new_store)?;
1169 /// # Ok(())
1170 /// # }
1171 /// ```
1172 pub fn instantiate_pre(&self, module: &Module) -> Result<InstancePre<T>> {
1173 self._instantiate_pre(module, None)
1174 }
1175
1176 /// This is split out to optionally take a `store` so that when the
1177 /// `.instantiate` API is used we can get fresh up-to-date type information
1178 /// for memories and their current size, if necessary.
1179 ///
1180 /// Note that providing a `store` here is not required for correctness
1181 /// per-se. If one is not provided, such as the with the `instantiate_pre`
1182 /// API, then the type information used for memories and tables will reflect
1183 /// their size when inserted into the linker rather than their current size.
1184 /// This isn't expected to be much of a problem though since
1185 /// per-store-`Linker` types are likely using `.instantiate(..)` and
1186 /// per-`Engine` linkers don't have memories/tables in them.
1187 fn _instantiate_pre(
1188 &self,
1189 module: &Module,
1190 store: Option<&StoreOpaque>,
1191 ) -> Result<InstancePre<T>> {
1192 let mut imports = module
1193 .imports()
1194 .map(|import| self._get_by_import(&import))
1195 .collect::<Result<Vec<_>, _>>()?;
1196 if let Some(store) = store {
1197 for import in imports.iter_mut() {
1198 import.update_size(store);
1199 }
1200 }
1201 unsafe { InstancePre::new(module, imports) }
1202 }
1203
1204 /// Returns an iterator over all items defined in this `Linker`, in
1205 /// arbitrary order.
1206 ///
1207 /// The iterator returned will yield 3-tuples where the first two elements
1208 /// are the module name and item name for the external item, and the third
1209 /// item is the item itself that is defined.
1210 ///
1211 /// Note that multiple `Extern` items may be defined for the same
1212 /// module/name pair.
1213 ///
1214 /// # Panics
1215 ///
1216 /// This function will panic if the `store` provided does not come from the
1217 /// same [`Engine`] that this linker was created with.
1218 pub fn iter<'a: 'p, 'p>(
1219 &'a self,
1220 mut store: impl AsContextMut<Data = T> + 'p,
1221 ) -> impl Iterator<Item = (&'a str, &'a str, Extern)> + 'p {
1222 self.map.iter().map(move |(key, item)| {
1223 let store = store.as_context_mut();
1224 (
1225 &*self.strings[key.module],
1226 &*self.strings[key.name],
1227 // Should be safe since `T` is connecting the linker and store
1228 unsafe { item.to_extern(store.0) },
1229 )
1230 })
1231 }
1232
1233 /// Looks up a previously defined value in this [`Linker`], identified by
1234 /// the names provided.
1235 ///
1236 /// Returns `None` if this name was not previously defined in this
1237 /// [`Linker`].
1238 ///
1239 /// # Panics
1240 ///
1241 /// This function will panic if the `store` provided does not come from the
1242 /// same [`Engine`] that this linker was created with.
1243 pub fn get(
1244 &self,
1245 mut store: impl AsContextMut<Data = T>,
1246 module: &str,
1247 name: &str,
1248 ) -> Option<Extern> {
1249 let store = store.as_context_mut().0;
1250 // Should be safe since `T` is connecting the linker and store
1251 Some(unsafe { self._get(module, name)?.to_extern(store) })
1252 }
1253
1254 fn _get(&self, module: &str, name: &str) -> Option<&Definition> {
1255 let key = ImportKey {
1256 module: *self.string2idx.get(module)?,
1257 name: *self.string2idx.get(name)?,
1258 };
1259 self.map.get(&key)
1260 }
1261
1262 /// Looks up a value in this `Linker` which matches the `import` type
1263 /// provided.
1264 ///
1265 /// Returns `None` if no match was found.
1266 ///
1267 /// # Panics
1268 ///
1269 /// This function will panic if the `store` provided does not come from the
1270 /// same [`Engine`] that this linker was created with.
1271 pub fn get_by_import(
1272 &self,
1273 mut store: impl AsContextMut<Data = T>,
1274 import: &ImportType,
1275 ) -> Option<Extern> {
1276 let store = store.as_context_mut().0;
1277 // Should be safe since `T` is connecting the linker and store
1278 Some(unsafe { self._get_by_import(import).ok()?.to_extern(store) })
1279 }
1280
1281 fn _get_by_import(&self, import: &ImportType) -> Result<Definition, UnknownImportError> {
1282 match self._get(import.module(), import.name()) {
1283 Some(item) => Ok(item.clone()),
1284 None => Err(UnknownImportError::new(import)),
1285 }
1286 }
1287
1288 /// Returns the "default export" of a module.
1289 ///
1290 /// An export with an empty string is considered to be a "default export".
1291 /// "_start" is also recognized for compatibility.
1292 ///
1293 /// # Panics
1294 ///
1295 /// Panics if the default function found is not owned by `store`. This
1296 /// function will also panic if the `store` provided does not come from the
1297 /// same [`Engine`] that this linker was created with.
1298 pub fn get_default(
1299 &self,
1300 mut store: impl AsContextMut<Data = T>,
1301 module: &str,
1302 ) -> Result<Func> {
1303 if let Some(external) = self.get(&mut store, module, "") {
1304 if let Extern::Func(func) = external {
1305 return Ok(func);
1306 }
1307 bail!("default export in '{}' is not a function", module);
1308 }
1309
1310 // For compatibility, also recognize "_start".
1311 if let Some(external) = self.get(&mut store, module, "_start") {
1312 if let Extern::Func(func) = external {
1313 return Ok(func);
1314 }
1315 bail!("`_start` in '{}' is not a function", module);
1316 }
1317
1318 // Otherwise return a no-op function.
1319 Ok(Func::wrap(store, || {}))
1320 }
1321}
1322
1323impl<T> Default for Linker<T> {
1324 fn default() -> Linker<T> {
1325 Linker::new(&Engine::default())
1326 }
1327}
1328
1329impl Definition {
1330 fn new(store: &StoreOpaque, item: Extern) -> Definition {
1331 let ty = DefinitionType::from(store, &item);
1332 Definition::Extern(item, ty)
1333 }
1334
1335 pub(crate) fn ty(&self) -> DefinitionType {
1336 match self {
1337 Definition::Extern(_, ty) => ty.clone(),
1338 Definition::HostFunc(func) => DefinitionType::Func(func.sig_index()),
1339 }
1340 }
1341
1342 /// Note the unsafety here is due to calling `HostFunc::to_func`. The
1343 /// requirement here is that the `T` that was originally used to create the
1344 /// `HostFunc` matches the `T` on the store.
1345 pub(crate) unsafe fn to_extern(&self, store: &mut StoreOpaque) -> Extern {
1346 match self {
1347 Definition::Extern(e, _) => e.clone(),
1348 Definition::HostFunc(func) => func.to_func(store).into(),
1349 }
1350 }
1351
1352 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
1353 match self {
1354 Definition::Extern(e, _) => e.comes_from_same_store(store),
1355 Definition::HostFunc(_func) => true,
1356 }
1357 }
1358
1359 fn update_size(&mut self, store: &StoreOpaque) {
1360 match self {
1361 Definition::Extern(Extern::Memory(m), DefinitionType::Memory(_, size)) => {
1362 *size = m.internal_size(store);
1363 }
1364 Definition::Extern(Extern::SharedMemory(m), DefinitionType::Memory(_, size)) => {
1365 *size = m.size();
1366 }
1367 Definition::Extern(Extern::Table(m), DefinitionType::Table(_, size)) => {
1368 *size = m.internal_size(store);
1369 }
1370 _ => {}
1371 }
1372 }
1373}
1374
1375impl DefinitionType {
1376 pub(crate) fn from(store: &StoreOpaque, item: &Extern) -> DefinitionType {
1377 let data = store.store_data();
1378 match item {
1379 Extern::Func(f) => DefinitionType::Func(f.type_index(data)),
1380 Extern::Table(t) => DefinitionType::Table(*t.wasmtime_ty(data), t.internal_size(store)),
1381 Extern::Global(t) => DefinitionType::Global(*t.wasmtime_ty(data)),
1382 Extern::Memory(t) => {
1383 DefinitionType::Memory(*t.wasmtime_ty(data), t.internal_size(store))
1384 }
1385 Extern::SharedMemory(t) => DefinitionType::Memory(*t.ty().wasmtime_memory(), t.size()),
1386 Extern::Tag(t) => DefinitionType::Tag(*t.wasmtime_ty(data)),
1387 }
1388 }
1389
1390 pub(crate) fn desc(&self) -> &'static str {
1391 match self {
1392 DefinitionType::Func(_) => "function",
1393 DefinitionType::Table(..) => "table",
1394 DefinitionType::Memory(..) => "memory",
1395 DefinitionType::Global(_) => "global",
1396 DefinitionType::Tag(_) => "tag",
1397 }
1398 }
1399}
1400
1401/// Modules can be interpreted either as Commands or Reactors.
1402enum ModuleKind {
1403 /// The instance is a Command, meaning an instance is created for each
1404 /// exported function and lives for the duration of the function call.
1405 Command,
1406
1407 /// The instance is a Reactor, meaning one instance is created which
1408 /// may live across multiple calls.
1409 Reactor,
1410}
1411
1412impl ModuleKind {
1413 /// Determine whether the given module is a Command or a Reactor.
1414 fn categorize(module: &Module) -> Result<ModuleKind> {
1415 let command_start = module.get_export("_start");
1416 let reactor_start = module.get_export("_initialize");
1417 match (command_start, reactor_start) {
1418 (Some(command_start), None) => {
1419 if let Some(_) = command_start.func() {
1420 Ok(ModuleKind::Command)
1421 } else {
1422 bail!("`_start` must be a function")
1423 }
1424 }
1425 (None, Some(reactor_start)) => {
1426 if let Some(_) = reactor_start.func() {
1427 Ok(ModuleKind::Reactor)
1428 } else {
1429 bail!("`_initialize` must be a function")
1430 }
1431 }
1432 (None, None) => {
1433 // Module declares neither of the recognized functions, so treat
1434 // it as a reactor with no initialization function.
1435 Ok(ModuleKind::Reactor)
1436 }
1437 (Some(_), Some(_)) => {
1438 // Module declares itself to be both a Command and a Reactor.
1439 bail!("Program cannot be both a Command and a Reactor")
1440 }
1441 }
1442 }
1443}
1444
1445/// Error for an unresolvable import.
1446///
1447/// Returned - wrapped in an [`anyhow::Error`] - by [`Linker::instantiate`] and
1448/// related methods for modules with unresolvable imports.
1449#[derive(Clone, Debug)]
1450pub struct UnknownImportError {
1451 module: String,
1452 name: String,
1453 ty: ExternType,
1454}
1455
1456impl UnknownImportError {
1457 fn new(import: &ImportType) -> Self {
1458 Self {
1459 module: import.module().to_string(),
1460 name: import.name().to_string(),
1461 ty: import.ty(),
1462 }
1463 }
1464
1465 /// Returns the module name that the unknown import was expected to come from.
1466 pub fn module(&self) -> &str {
1467 &self.module
1468 }
1469
1470 /// Returns the field name of the module that the unknown import was expected to come from.
1471 pub fn name(&self) -> &str {
1472 &self.name
1473 }
1474
1475 /// Returns the type of the unknown import.
1476 pub fn ty(&self) -> ExternType {
1477 self.ty.clone()
1478 }
1479}
1480
1481impl fmt::Display for UnknownImportError {
1482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1483 write!(
1484 f,
1485 "unknown import: `{}::{}` has not been defined",
1486 self.module, self.name,
1487 )
1488 }
1489}
1490
1491impl core::error::Error for UnknownImportError {}