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