1 //! An `Instance` contains all the runtime state used by execution of a
2 //! wasm module (except its callstack and register state). An
3 //! `InstanceHandle` is a reference-counting handle for an `Instance`.
4 
5 use crate::OpaqueRootScope;
6 use crate::prelude::*;
7 use crate::runtime::vm::const_expr::{ConstEvalContext, ConstExprEvaluator};
8 use crate::runtime::vm::export::Export;
9 use crate::runtime::vm::memory::{Memory, RuntimeMemoryCreator};
10 use crate::runtime::vm::table::{Table, TableElementType};
11 use crate::runtime::vm::vmcontext::{
12     VMBuiltinFunctionsArray, VMContext, VMFuncRef, VMFunctionImport, VMGlobalDefinition,
13     VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMOpaqueContext, VMStoreContext,
14     VMTableDefinition, VMTableImport, VMTagDefinition, VMTagImport,
15 };
16 use crate::runtime::vm::{
17     GcStore, HostResult, Imports, ModuleRuntimeInfo, SendSyncPtr, VMGlobalKind, VMStore,
18     VMStoreRawPtr, VmPtr, VmSafe, WasmFault, catch_unwind_and_record_trap,
19 };
20 use crate::store::{InstanceId, StoreId, StoreInstanceId, StoreOpaque, StoreResourceLimiter};
21 use alloc::sync::Arc;
22 use core::alloc::Layout;
23 use core::marker;
24 use core::ops::Range;
25 use core::pin::Pin;
26 use core::ptr::NonNull;
27 #[cfg(target_has_atomic = "64")]
28 use core::sync::atomic::AtomicU64;
29 use core::{mem, ptr};
30 #[cfg(feature = "gc")]
31 use wasmtime_environ::ModuleInternedTypeIndex;
32 use wasmtime_environ::{
33     DataIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex, DefinedTagIndex,
34     ElemIndex, EntityIndex, EntityRef, EntitySet, FuncIndex, GlobalIndex, HostPtr, MemoryIndex,
35     Module, PrimaryMap, PtrSize, TableIndex, TableInitialValue, TableSegmentElements, TagIndex,
36     Trap, VMCONTEXT_MAGIC, VMOffsets, VMSharedTypeIndex, packed_option::ReservedValue,
37 };
38 #[cfg(feature = "wmemcheck")]
39 use wasmtime_wmemcheck::Wmemcheck;
40 
41 mod allocator;
42 pub use allocator::*;
43 
44 /// A type that roughly corresponds to a WebAssembly instance, but is also used
45 /// for host-defined objects.
46 ///
47 /// Instances here can correspond to actual instantiated modules, but it's also
48 /// used ubiquitously for host-defined objects. For example creating a
49 /// host-defined memory will have a `module` that looks like it exports a single
50 /// memory (and similar for other constructs).
51 ///
52 /// This `Instance` type is used as a ubiquitous representation for WebAssembly
53 /// values, whether or not they were created on the host or through a module.
54 ///
55 /// # Ownership
56 ///
57 /// This structure is never allocated directly but is instead managed through
58 /// an `InstanceHandle`. This structure ends with a `VMContext` which has a
59 /// dynamic size corresponding to the `module` configured within. Memory
60 /// management of this structure is always done through `InstanceHandle` as the
61 /// sole owner of an instance.
62 ///
63 /// # `Instance` and `Pin`
64 ///
65 /// Given an instance it is accompanied with trailing memory for the
66 /// appropriate `VMContext`. The `Instance` also holds `runtime_info` and other
67 /// information pointing to relevant offsets for the `VMContext`. Thus it is
68 /// not sound to mutate `runtime_info` after an instance is created. More
69 /// generally it's also not safe to "swap" instances, for example given two
70 /// `&mut Instance` values it's not sound to swap them as then the `VMContext`
71 /// values are inaccurately described.
72 ///
73 /// To encapsulate this guarantee this type is only ever mutated through Rust's
74 /// `Pin` type. All mutable methods here take `self: Pin<&mut Self>` which
75 /// statically disallows safe access to `&mut Instance`. There are assorted
76 /// "projection methods" to go from `Pin<&mut Instance>` to `&mut T` for
77 /// individual fields, for example `memories_mut`. More methods can be added as
78 /// necessary or methods may also be added to project multiple fields at a time
79 /// if necessary to. The precise ergonomics around getting mutable access to
80 /// some fields (but notably not `runtime_info`) is probably going to evolve
81 /// over time.
82 ///
83 /// Note that is is not sound to basically ever pass around `&mut Instance`.
84 /// That should always instead be `Pin<&mut Instance>`. All usage of
85 /// `Pin::new_unchecked` should be here in this module in just a few `unsafe`
86 /// locations and it's recommended to use existing helpers if you can.
87 #[repr(C)] // ensure that the vmctx field is last.
88 pub struct Instance {
89     /// The index, within a `Store` that this instance lives at
90     id: InstanceId,
91 
92     /// The runtime info (corresponding to the "compiled module"
93     /// abstraction in higher layers) that is retained and needed for
94     /// lazy initialization. This provides access to the underlying
95     /// Wasm module entities, the compiled JIT code, metadata about
96     /// functions, lazy initialization state, etc.
97     runtime_info: ModuleRuntimeInfo,
98 
99     /// WebAssembly linear memory data.
100     ///
101     /// This is where all runtime information about defined linear memories in
102     /// this module lives.
103     ///
104     /// The `MemoryAllocationIndex` was given from our `InstanceAllocator` and
105     /// must be given back to the instance allocator when deallocating each
106     /// memory.
107     memories: PrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)>,
108 
109     /// WebAssembly table data.
110     ///
111     /// Like memories, this is only for defined tables in the module and
112     /// contains all of their runtime state.
113     ///
114     /// The `TableAllocationIndex` was given from our `InstanceAllocator` and
115     /// must be given back to the instance allocator when deallocating each
116     /// table.
117     tables: PrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)>,
118 
119     /// Stores the dropped passive element segments in this instantiation by index.
120     /// If the index is present in the set, the segment has been dropped.
121     dropped_elements: EntitySet<ElemIndex>,
122 
123     /// Stores the dropped passive data segments in this instantiation by index.
124     /// If the index is present in the set, the segment has been dropped.
125     dropped_data: EntitySet<DataIndex>,
126 
127     // TODO: add support for multiple memories; `wmemcheck_state` corresponds to
128     // memory 0.
129     #[cfg(feature = "wmemcheck")]
130     pub(crate) wmemcheck_state: Option<Wmemcheck>,
131 
132     /// Self-pointer back to `Store<T>` and its functions. Not present for
133     /// the brief time that `Store<T>` is itself being created. Also not
134     /// present for some niche uses that are disconnected from stores (e.g.
135     /// cross-thread stuff used in `InstancePre`)
136     store: Option<VMStoreRawPtr>,
137 
138     /// Additional context used by compiled wasm code. This field is last, and
139     /// represents a dynamically-sized array that extends beyond the nominal
140     /// end of the struct (similar to a flexible array member).
141     vmctx: OwnedVMContext<VMContext>,
142 }
143 
144 impl Instance {
145     /// Create an instance at the given memory address.
146     ///
147     /// It is assumed the memory was properly aligned and the
148     /// allocation was `alloc_size` in bytes.
149     ///
150     /// # Safety
151     ///
152     /// The `req.imports` field must be appropriately sized/typed for the module
153     /// being allocated according to `req.runtime_info`. Additionally `memories`
154     /// and `tables` must have been allocated for `req.store`.
155     unsafe fn new(
156         req: InstanceAllocationRequest,
157         memories: PrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)>,
158         tables: PrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)>,
159         memory_tys: &PrimaryMap<MemoryIndex, wasmtime_environ::Memory>,
160     ) -> InstanceHandle {
161         let module = req.runtime_info.env_module();
162         let dropped_elements = EntitySet::with_capacity(module.passive_elements.len());
163         let dropped_data = EntitySet::with_capacity(module.passive_data_map.len());
164 
165         #[cfg(not(feature = "wmemcheck"))]
166         let _ = memory_tys;
167 
168         let mut ret = OwnedInstance::new(Instance {
169             id: req.id,
170             runtime_info: req.runtime_info.clone(),
171             memories,
172             tables,
173             dropped_elements,
174             dropped_data,
175             #[cfg(feature = "wmemcheck")]
176             wmemcheck_state: {
177                 if req.store.engine().config().wmemcheck {
178                     let size = memory_tys
179                         .iter()
180                         .next()
181                         .map(|memory| memory.1.limits.min)
182                         .unwrap_or(0)
183                         * 64
184                         * 1024;
185                     Some(Wmemcheck::new(size.try_into().unwrap()))
186                 } else {
187                     None
188                 }
189             },
190             store: None,
191             vmctx: OwnedVMContext::new(),
192         });
193 
194         // SAFETY: this vmctx was allocated with the same layout above, so it
195         // should be safe to initialize with the same values here.
196         unsafe {
197             ret.get_mut().initialize_vmctx(
198                 module,
199                 req.runtime_info.offsets(),
200                 req.store,
201                 req.imports,
202             );
203         }
204         ret
205     }
206 
207     /// Encapsulated entrypoint to the host from WebAssembly, converting a raw
208     /// `VMContext` pointer into a `VMStore` plus an `InstanceId`.
209     ///
210     /// This is an entrypoint for core wasm entering back into the host. This is
211     /// used for both host functions and libcalls for example. This will execute
212     /// the closure `f` with safer Internal types than a raw `VMContext`
213     /// pointer.
214     ///
215     /// The closure `f` will have its errors caught, handled, and translated to
216     /// an ABI-safe return value to give back to wasm. This includes both normal
217     /// errors such as traps as well as panics.
218     ///
219     /// # Safety
220     ///
221     /// Callers must ensure that `vmctx` is a valid allocation and is safe to
222     /// dereference at this time. That's generally only true when it's a
223     /// wasm-provided value and this is the first function called after entering
224     /// the host. Otherwise this could unsafely alias the store with a mutable
225     /// pointer, for example.
226     #[inline]
227     pub(crate) unsafe fn enter_host_from_wasm<R>(
228         vmctx: NonNull<VMContext>,
229         f: impl FnOnce(&mut dyn VMStore, InstanceId) -> R,
230     ) -> R::Abi
231     where
232         R: HostResult,
233     {
234         // SAFETY: The validity of this `byte_sub` relies on `vmctx` being a
235         // valid allocation which is itself a contract of this function.
236         // Additionally `as_mut` requires that the pointer is valid, which is
237         // also a contract of this function. The lifetime of the reference will
238         // be constrained by the closure `f` provided to this function which
239         // inherently can't have the pointer escape, so the lifetime is scoped
240         // here.
241         let (store, instance) = unsafe {
242             let instance = vmctx
243                 .byte_sub(mem::size_of::<Instance>())
244                 .cast::<Instance>()
245                 .as_mut();
246             let store = &mut *instance.store.unwrap().0.as_ptr();
247             (store, instance.id)
248         };
249 
250         // Thread the `store` and `instance` through panic/trap infrastructure
251         // back into `f`.
252         catch_unwind_and_record_trap(store, |store| f(store, instance))
253     }
254 
255     /// Converts the provided `*mut VMContext` to an `Instance` pointer and
256     /// returns it with the same lifetime as `self`.
257     ///
258     /// This function can be used when traversing a `VMContext` to reach into
259     /// the context needed for imports, optionally.
260     ///
261     /// # Safety
262     ///
263     /// This function requires that the `vmctx` pointer is indeed valid and
264     /// from the store that `self` belongs to.
265     #[inline]
266     unsafe fn sibling_vmctx<'a>(&'a self, vmctx: NonNull<VMContext>) -> &'a Instance {
267         // SAFETY: it's a contract of this function itself that `vmctx` is a
268         // valid pointer such that this pointer arithmetic is valid.
269         let ptr = unsafe {
270             vmctx
271                 .byte_sub(mem::size_of::<Instance>())
272                 .cast::<Instance>()
273         };
274         // SAFETY: it's a contract of this function itself that `vmctx` is a
275         // valid pointer to dereference. Additionally the lifetime of the return
276         // value is constrained to be the same as `self` to avoid granting a
277         // too-long lifetime.
278         unsafe { ptr.as_ref() }
279     }
280 
281     /// Same as [`Self::sibling_vmctx`], but the mutable version.
282     ///
283     /// # Safety
284     ///
285     /// This function requires that the `vmctx` pointer is indeed valid and
286     /// from the store that `self` belongs to.
287     ///
288     /// (Note that it is *NOT* required that `vmctx` be distinct from this
289     /// instance's `vmctx`, or that usage of the resulting instance is limited
290     /// to its defined items! The returned borrow has the same lifetime as
291     /// `self`, which means that this instance cannot be used while the
292     /// resulting instance is in use, and we therefore do not need to worry
293     /// about mutable aliasing between this instance and the resulting
294     /// instance.)
295     #[inline]
296     unsafe fn sibling_vmctx_mut<'a>(
297         self: Pin<&'a mut Self>,
298         vmctx: NonNull<VMContext>,
299     ) -> Pin<&'a mut Instance> {
300         // SAFETY: it's a contract of this function itself that `vmctx` is a
301         // valid pointer such that this pointer arithmetic is valid.
302         let mut ptr = unsafe {
303             vmctx
304                 .byte_sub(mem::size_of::<Instance>())
305                 .cast::<Instance>()
306         };
307 
308         // SAFETY: it's a contract of this function itself that `vmctx` is a
309         // valid pointer to dereference. Additionally the lifetime of the return
310         // value is constrained to be the same as `self` to avoid granting a
311         // too-long lifetime. Finally mutable references to an instance are
312         // always through `Pin`, so it's safe to create a pin-pointer here.
313         unsafe { Pin::new_unchecked(ptr.as_mut()) }
314     }
315 
316     /// Accessor from a raw `vmctx` to `&vm::Instance`, given a store.
317     ///
318     /// This is like the above `sibling_vmctx{,_mut}` accessors, but
319     /// takes the store explicitly rather than inferring it from an
320     /// existing instance in the store.
321     ///
322     /// # Safety
323     ///
324     /// The `vmctx` pointer must be a valid vmctx from an active
325     /// instance that belongs to the given `store`.
326     #[inline]
327     pub unsafe fn from_vmctx<'a>(
328         _store: &'a StoreOpaque,
329         vmctx: NonNull<VMContext>,
330     ) -> &'a Instance {
331         // SAFETY: The validity of this `byte_sub` relies on `vmctx`
332         // being a valid allocation which is itself a contract of this
333         // function. Likewise, the `.as_ref()` converts a valid `*mut
334         // Instance` to a `&Instance`.
335         unsafe {
336             vmctx
337                 .byte_sub(mem::size_of::<Instance>())
338                 .cast::<Instance>()
339                 .as_ref()
340         }
341     }
342 
343     pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
344         self.runtime_info.env_module()
345     }
346 
347     #[cfg(feature = "gc")]
348     pub(crate) fn runtime_module(&self) -> Option<&crate::Module> {
349         match &self.runtime_info {
350             ModuleRuntimeInfo::Module(m) => Some(m),
351             ModuleRuntimeInfo::Bare(_) => None,
352         }
353     }
354 
355     /// Translate a module-level interned type index into an engine-level
356     /// interned type index.
357     #[cfg(feature = "gc")]
358     pub fn engine_type_index(&self, module_index: ModuleInternedTypeIndex) -> VMSharedTypeIndex {
359         self.runtime_info.engine_type_index(module_index)
360     }
361 
362     #[inline]
363     fn offsets(&self) -> &VMOffsets<HostPtr> {
364         self.runtime_info.offsets()
365     }
366 
367     /// Return the indexed `VMFunctionImport`.
368     fn imported_function(&self, index: FuncIndex) -> &VMFunctionImport {
369         unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmfunction_import(index)) }
370     }
371 
372     /// Return the index `VMTableImport`.
373     fn imported_table(&self, index: TableIndex) -> &VMTableImport {
374         unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmtable_import(index)) }
375     }
376 
377     /// Return the indexed `VMMemoryImport`.
378     fn imported_memory(&self, index: MemoryIndex) -> &VMMemoryImport {
379         unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmmemory_import(index)) }
380     }
381 
382     /// Return the indexed `VMGlobalImport`.
383     fn imported_global(&self, index: GlobalIndex) -> &VMGlobalImport {
384         unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmglobal_import(index)) }
385     }
386 
387     /// Return the indexed `VMTagImport`.
388     fn imported_tag(&self, index: TagIndex) -> &VMTagImport {
389         unsafe { self.vmctx_plus_offset(self.offsets().vmctx_vmtag_import(index)) }
390     }
391 
392     /// Return the indexed `VMTagDefinition`.
393     pub fn tag_ptr(&self, index: DefinedTagIndex) -> NonNull<VMTagDefinition> {
394         unsafe { self.vmctx_plus_offset_raw(self.offsets().vmctx_vmtag_definition(index)) }
395     }
396 
397     /// Return the indexed `VMTableDefinition`.
398     pub fn table(&self, index: DefinedTableIndex) -> VMTableDefinition {
399         unsafe { self.table_ptr(index).read() }
400     }
401 
402     /// Updates the value for a defined table to `VMTableDefinition`.
403     fn set_table(self: Pin<&mut Self>, index: DefinedTableIndex, table: VMTableDefinition) {
404         unsafe {
405             self.table_ptr(index).write(table);
406         }
407     }
408 
409     /// Return a pointer to the `index`'th table within this instance, stored
410     /// in vmctx memory.
411     pub fn table_ptr(&self, index: DefinedTableIndex) -> NonNull<VMTableDefinition> {
412         unsafe { self.vmctx_plus_offset_raw(self.offsets().vmctx_vmtable_definition(index)) }
413     }
414 
415     /// Get a locally defined or imported memory.
416     pub(crate) fn get_memory(&self, index: MemoryIndex) -> VMMemoryDefinition {
417         if let Some(defined_index) = self.env_module().defined_memory_index(index) {
418             self.memory(defined_index)
419         } else {
420             let import = self.imported_memory(index);
421             unsafe { VMMemoryDefinition::load(import.from.as_ptr()) }
422         }
423     }
424 
425     /// Return the indexed `VMMemoryDefinition`, loaded from vmctx memory
426     /// already.
427     #[inline]
428     pub fn memory(&self, index: DefinedMemoryIndex) -> VMMemoryDefinition {
429         unsafe { VMMemoryDefinition::load(self.memory_ptr(index).as_ptr()) }
430     }
431 
432     /// Set the indexed memory to `VMMemoryDefinition`.
433     fn set_memory(&self, index: DefinedMemoryIndex, mem: VMMemoryDefinition) {
434         unsafe {
435             self.memory_ptr(index).write(mem);
436         }
437     }
438 
439     /// Return the address of the specified memory at `index` within this vmctx.
440     ///
441     /// Note that the returned pointer resides in wasm-code-readable-memory in
442     /// the vmctx.
443     #[inline]
444     pub fn memory_ptr(&self, index: DefinedMemoryIndex) -> NonNull<VMMemoryDefinition> {
445         unsafe {
446             self.vmctx_plus_offset::<VmPtr<_>>(self.offsets().vmctx_vmmemory_pointer(index))
447                 .as_non_null()
448         }
449     }
450 
451     /// Return the indexed `VMGlobalDefinition`.
452     pub fn global_ptr(&self, index: DefinedGlobalIndex) -> NonNull<VMGlobalDefinition> {
453         unsafe { self.vmctx_plus_offset_raw(self.offsets().vmctx_vmglobal_definition(index)) }
454     }
455 
456     /// Get all globals within this instance.
457     ///
458     /// Returns both import and defined globals.
459     ///
460     /// Returns both exported and non-exported globals.
461     ///
462     /// Gives access to the full globals space.
463     pub fn all_globals(
464         &self,
465         store: StoreId,
466     ) -> impl ExactSizeIterator<Item = (GlobalIndex, crate::Global)> + '_ {
467         let module = self.env_module();
468         module
469             .globals
470             .keys()
471             .map(move |idx| (idx, self.get_exported_global(store, idx)))
472     }
473 
474     /// Get the globals defined in this instance (not imported).
475     pub fn defined_globals(
476         &self,
477         store: StoreId,
478     ) -> impl ExactSizeIterator<Item = (DefinedGlobalIndex, crate::Global)> + '_ {
479         let module = self.env_module();
480         self.all_globals(store)
481             .skip(module.num_imported_globals)
482             .map(move |(i, global)| (module.defined_global_index(i).unwrap(), global))
483     }
484 
485     /// Return a pointer to the interrupts structure
486     #[inline]
487     pub fn vm_store_context(&self) -> NonNull<Option<VmPtr<VMStoreContext>>> {
488         unsafe { self.vmctx_plus_offset_raw(self.offsets().ptr.vmctx_store_context()) }
489     }
490 
491     /// Return a pointer to the global epoch counter used by this instance.
492     #[cfg(target_has_atomic = "64")]
493     pub fn epoch_ptr(self: Pin<&mut Self>) -> &mut Option<VmPtr<AtomicU64>> {
494         let offset = self.offsets().ptr.vmctx_epoch_ptr();
495         unsafe { self.vmctx_plus_offset_mut(offset) }
496     }
497 
498     /// Return a pointer to the collector-specific heap data.
499     pub fn gc_heap_data(self: Pin<&mut Self>) -> &mut Option<VmPtr<u8>> {
500         let offset = self.offsets().ptr.vmctx_gc_heap_data();
501         unsafe { self.vmctx_plus_offset_mut(offset) }
502     }
503 
504     pub(crate) unsafe fn set_store(mut self: Pin<&mut Self>, store: &StoreOpaque) {
505         // FIXME: should be more targeted ideally with the `unsafe` than just
506         // throwing this entire function in a large `unsafe` block.
507         unsafe {
508             *self.as_mut().store_mut() = Some(VMStoreRawPtr(store.traitobj()));
509             self.vm_store_context()
510                 .write(Some(store.vm_store_context_ptr().into()));
511             #[cfg(target_has_atomic = "64")]
512             {
513                 *self.as_mut().epoch_ptr() =
514                     Some(NonNull::from(store.engine().epoch_counter()).into());
515             }
516 
517             if self.env_module().needs_gc_heap {
518                 self.as_mut().set_gc_heap(Some(store.unwrap_gc_store()));
519             } else {
520                 self.as_mut().set_gc_heap(None);
521             }
522         }
523     }
524 
525     unsafe fn set_gc_heap(self: Pin<&mut Self>, gc_store: Option<&GcStore>) {
526         if let Some(gc_store) = gc_store {
527             *self.gc_heap_data() = Some(unsafe { gc_store.gc_heap.vmctx_gc_heap_data().into() });
528         } else {
529             *self.gc_heap_data() = None;
530         }
531     }
532 
533     /// Return a reference to the vmctx used by compiled wasm code.
534     #[inline]
535     pub fn vmctx(&self) -> NonNull<VMContext> {
536         InstanceLayout::vmctx(self)
537     }
538 
539     /// Lookup a function by index.
540     ///
541     /// # Panics
542     ///
543     /// Panics if `index` is out of bounds for this instance.
544     ///
545     /// # Safety
546     ///
547     /// The `store` parameter must be the store that owns this instance and the
548     /// functions that this instance can reference.
549     pub unsafe fn get_exported_func(
550         self: Pin<&mut Self>,
551         store: StoreId,
552         index: FuncIndex,
553     ) -> crate::Func {
554         let func_ref = self.get_func_ref(index).unwrap();
555 
556         // SAFETY: the validity of `func_ref` is guaranteed by the validity of
557         // `self`, and the contract that `store` must own `func_ref` is a
558         // contract of this function itself.
559         unsafe { crate::Func::from_vm_func_ref(store, func_ref) }
560     }
561 
562     /// Lookup a table by index.
563     ///
564     /// # Panics
565     ///
566     /// Panics if `index` is out of bounds for this instance.
567     pub fn get_exported_table(&self, store: StoreId, index: TableIndex) -> crate::Table {
568         let (id, def_index) = if let Some(def_index) = self.env_module().defined_table_index(index)
569         {
570             (self.id, def_index)
571         } else {
572             let import = self.imported_table(index);
573             // SAFETY: validity of this `Instance` guarantees validity of the
574             // `vmctx` pointer being read here to find the transitive
575             // `InstanceId` that the import is associated with.
576             let id = unsafe { self.sibling_vmctx(import.vmctx.as_non_null()).id };
577             (id, import.index)
578         };
579         crate::Table::from_raw(StoreInstanceId::new(store, id), def_index)
580     }
581 
582     /// Lookup a memory by index.
583     ///
584     /// # Panics
585     ///
586     /// Panics if `index` is out-of-bounds for this instance.
587     pub fn get_exported_memory(&self, store: StoreId, index: MemoryIndex) -> crate::Memory {
588         let (id, def_index) = if let Some(def_index) = self.env_module().defined_memory_index(index)
589         {
590             (self.id, def_index)
591         } else {
592             let import = self.imported_memory(index);
593             // SAFETY: validity of this `Instance` guarantees validity of the
594             // `vmctx` pointer being read here to find the transitive
595             // `InstanceId` that the import is associated with.
596             let id = unsafe { self.sibling_vmctx(import.vmctx.as_non_null()).id };
597             (id, import.index)
598         };
599         crate::Memory::from_raw(StoreInstanceId::new(store, id), def_index)
600     }
601 
602     /// Lookup a global by index.
603     ///
604     /// # Panics
605     ///
606     /// Panics if `index` is out-of-bounds for this instance.
607     pub(crate) fn get_exported_global(&self, store: StoreId, index: GlobalIndex) -> crate::Global {
608         // If this global is defined within this instance, then that's easy to
609         // calculate the `Global`.
610         if let Some(def_index) = self.env_module().defined_global_index(index) {
611             let instance = StoreInstanceId::new(store, self.id);
612             return crate::Global::from_core(instance, def_index);
613         }
614 
615         // For imported globals it's required to match on the `kind` to
616         // determine which `Global` constructor is going to be invoked.
617         let import = self.imported_global(index);
618         match import.kind {
619             VMGlobalKind::Host(index) => crate::Global::from_host(store, index),
620             VMGlobalKind::Instance(index) => {
621                 // SAFETY: validity of this `&Instance` means validity of its
622                 // imports meaning we can read the id of the vmctx within.
623                 let id = unsafe {
624                     let vmctx = VMContext::from_opaque(import.vmctx.unwrap().as_non_null());
625                     self.sibling_vmctx(vmctx).id
626                 };
627                 crate::Global::from_core(StoreInstanceId::new(store, id), index)
628             }
629             #[cfg(feature = "component-model")]
630             VMGlobalKind::ComponentFlags(index) => {
631                 // SAFETY: validity of this `&Instance` means validity of its
632                 // imports meaning we can read the id of the vmctx within.
633                 let id = unsafe {
634                     let vmctx = super::component::VMComponentContext::from_opaque(
635                         import.vmctx.unwrap().as_non_null(),
636                     );
637                     super::component::ComponentInstance::vmctx_instance_id(vmctx)
638                 };
639                 crate::Global::from_component_flags(
640                     crate::component::store::StoreComponentInstanceId::new(store, id),
641                     index,
642                 )
643             }
644         }
645     }
646 
647     /// Get an exported tag by index.
648     ///
649     /// # Panics
650     ///
651     /// Panics if the index is out-of-range.
652     pub fn get_exported_tag(&self, store: StoreId, index: TagIndex) -> crate::Tag {
653         let (id, def_index) = if let Some(def_index) = self.env_module().defined_tag_index(index) {
654             (self.id, def_index)
655         } else {
656             let import = self.imported_tag(index);
657             // SAFETY: validity of this `Instance` guarantees validity of the
658             // `vmctx` pointer being read here to find the transitive
659             // `InstanceId` that the import is associated with.
660             let id = unsafe { self.sibling_vmctx(import.vmctx.as_non_null()).id };
661             (id, import.index)
662         };
663         crate::Tag::from_raw(StoreInstanceId::new(store, id), def_index)
664     }
665 
666     /// Return an iterator over the exports of this instance.
667     ///
668     /// Specifically, it provides access to the key-value pairs, where the keys
669     /// are export names, and the values are export declarations which can be
670     /// resolved `lookup_by_declaration`.
671     pub fn exports(&self) -> wasmparser::collections::index_map::Iter<'_, String, EntityIndex> {
672         self.env_module().exports.iter()
673     }
674 
675     /// Grow memory by the specified amount of pages.
676     ///
677     /// Returns `None` if memory can't be grown by the specified amount
678     /// of pages. Returns `Some` with the old size in bytes if growth was
679     /// successful.
680     pub(crate) async fn memory_grow(
681         mut self: Pin<&mut Self>,
682         limiter: Option<&mut StoreResourceLimiter<'_>>,
683         idx: DefinedMemoryIndex,
684         delta: u64,
685     ) -> Result<Option<usize>, Error> {
686         let memory = &mut self.as_mut().memories_mut()[idx].1;
687 
688         // SAFETY: this is the safe wrapper around `Memory::grow` because it
689         // automatically updates the `VMMemoryDefinition` in this instance after
690         // a growth operation below.
691         let result = unsafe { memory.grow(delta, limiter).await };
692 
693         // Update the state used by a non-shared Wasm memory in case the base
694         // pointer and/or the length changed.
695         if memory.as_shared_memory().is_none() {
696             let vmmemory = memory.vmmemory();
697             self.set_memory(idx, vmmemory);
698         }
699 
700         result
701     }
702 
703     pub(crate) fn table_element_type(
704         self: Pin<&mut Self>,
705         table_index: TableIndex,
706     ) -> TableElementType {
707         self.get_table(table_index).element_type()
708     }
709 
710     /// Performs a grow operation on the `table_index` specified using `grow`.
711     ///
712     /// This will handle updating the VMTableDefinition internally as necessary.
713     pub(crate) async fn defined_table_grow(
714         mut self: Pin<&mut Self>,
715         table_index: DefinedTableIndex,
716         grow: impl AsyncFnOnce(&mut Table) -> Result<Option<usize>>,
717     ) -> Result<Option<usize>> {
718         let table = self.as_mut().get_defined_table(table_index);
719         let result = grow(table).await;
720         let element = table.vmtable();
721         self.set_table(table_index, element);
722         result
723     }
724 
725     fn alloc_layout(offsets: &VMOffsets<HostPtr>) -> Layout {
726         let size = mem::size_of::<Self>()
727             .checked_add(usize::try_from(offsets.size_of_vmctx()).unwrap())
728             .unwrap();
729         let align = mem::align_of::<Self>();
730         Layout::from_size_align(size, align).unwrap()
731     }
732 
733     fn type_ids_array(&self) -> NonNull<VmPtr<VMSharedTypeIndex>> {
734         unsafe { self.vmctx_plus_offset_raw(self.offsets().ptr.vmctx_type_ids_array()) }
735     }
736 
737     /// Construct a new VMFuncRef for the given function
738     /// (imported or defined in this module) and store into the given
739     /// location. Used during lazy initialization.
740     ///
741     /// Note that our current lazy-init scheme actually calls this every
742     /// time the funcref pointer is fetched; this turns out to be better
743     /// than tracking state related to whether it's been initialized
744     /// before, because resetting that state on (re)instantiation is
745     /// very expensive if there are many funcrefs.
746     ///
747     /// # Safety
748     ///
749     /// This functions requires that `into` is a valid pointer.
750     unsafe fn construct_func_ref(
751         self: Pin<&mut Self>,
752         index: FuncIndex,
753         type_index: VMSharedTypeIndex,
754         into: *mut VMFuncRef,
755     ) {
756         let func_ref = if let Some(def_index) = self.env_module().defined_func_index(index) {
757             VMFuncRef {
758                 array_call: self
759                     .runtime_info
760                     .array_to_wasm_trampoline(def_index)
761                     .expect("should have array-to-Wasm trampoline for escaping function")
762                     .into(),
763                 wasm_call: Some(self.runtime_info.function(def_index).into()),
764                 vmctx: VMOpaqueContext::from_vmcontext(self.vmctx()).into(),
765                 type_index,
766             }
767         } else {
768             let import = self.imported_function(index);
769             VMFuncRef {
770                 array_call: import.array_call,
771                 wasm_call: Some(import.wasm_call),
772                 vmctx: import.vmctx,
773                 type_index,
774             }
775         };
776 
777         // SAFETY: the unsafe contract here is forwarded to callers of this
778         // function.
779         unsafe {
780             ptr::write(into, func_ref);
781         }
782     }
783 
784     /// Get a `&VMFuncRef` for the given `FuncIndex`.
785     ///
786     /// Returns `None` if the index is the reserved index value.
787     ///
788     /// The returned reference is a stable reference that won't be moved and can
789     /// be passed into JIT code.
790     pub(crate) fn get_func_ref(
791         self: Pin<&mut Self>,
792         index: FuncIndex,
793     ) -> Option<NonNull<VMFuncRef>> {
794         if index == FuncIndex::reserved_value() {
795             return None;
796         }
797 
798         // For now, we eagerly initialize an funcref struct in-place
799         // whenever asked for a reference to it. This is mostly
800         // fine, because in practice each funcref is unlikely to be
801         // requested more than a few times: once-ish for funcref
802         // tables used for call_indirect (the usual compilation
803         // strategy places each function in the table at most once),
804         // and once or a few times when fetching exports via API.
805         // Note that for any case driven by table accesses, the lazy
806         // table init behaves like a higher-level cache layer that
807         // protects this initialization from happening multiple
808         // times, via that particular table at least.
809         //
810         // When `ref.func` becomes more commonly used or if we
811         // otherwise see a use-case where this becomes a hotpath,
812         // we can reconsider by using some state to track
813         // "uninitialized" explicitly, for example by zeroing the
814         // funcrefs (perhaps together with other
815         // zeroed-at-instantiate-time state) or using a separate
816         // is-initialized bitmap.
817         //
818         // We arrived at this design because zeroing memory is
819         // expensive, so it's better for instantiation performance
820         // if we don't have to track "is-initialized" state at
821         // all!
822         let func = &self.env_module().functions[index];
823         let sig = func.signature.unwrap_engine_type_index();
824 
825         // SAFETY: the offset calculated here should be correct with
826         // `self.offsets`
827         let func_ref = unsafe {
828             self.vmctx_plus_offset_raw::<VMFuncRef>(self.offsets().vmctx_func_ref(func.func_ref))
829         };
830 
831         // SAFETY: the `func_ref` ptr should be valid as it's within our
832         // `VMContext` area.
833         unsafe {
834             self.construct_func_ref(index, sig, func_ref.as_ptr());
835         }
836 
837         Some(func_ref)
838     }
839 
840     /// Get the passive elements segment at the given index.
841     ///
842     /// Returns an empty segment if the index is out of bounds or if the segment
843     /// has been dropped.
844     ///
845     /// The `storage` parameter should always be `None`; it is a bit of a hack
846     /// to work around lifetime issues.
847     pub(crate) fn passive_element_segment<'a>(
848         &self,
849         storage: &'a mut Option<(Arc<wasmtime_environ::Module>, TableSegmentElements)>,
850         elem_index: ElemIndex,
851     ) -> &'a TableSegmentElements {
852         debug_assert!(storage.is_none());
853         *storage = Some((
854             // TODO: this `clone()` shouldn't be necessary but is used for now to
855             // inform `rustc` that the lifetime of the elements here are
856             // disconnected from the lifetime of `self`.
857             self.env_module().clone(),
858             // NB: fall back to an expressions-based list of elements which
859             // doesn't have static type information (as opposed to
860             // `TableSegmentElements::Functions`) since we don't know what type
861             // is needed in the caller's context. Let the type be inferred by
862             // how they use the segment.
863             TableSegmentElements::Expressions(Box::new([])),
864         ));
865         let (module, empty) = storage.as_ref().unwrap();
866 
867         match module.passive_elements_map.get(&elem_index) {
868             Some(index) if !self.dropped_elements.contains(elem_index) => {
869                 &module.passive_elements[*index]
870             }
871             _ => empty,
872         }
873     }
874 
875     /// The `table.init` operation: initializes a portion of a table with a
876     /// passive element.
877     ///
878     /// # Errors
879     ///
880     /// Returns a `Trap` error when the range within the table is out of bounds
881     /// or the range within the passive element is out of bounds.
882     pub(crate) async fn table_init(
883         store: &mut StoreOpaque,
884         limiter: Option<&mut StoreResourceLimiter<'_>>,
885         instance: InstanceId,
886         table_index: TableIndex,
887         elem_index: ElemIndex,
888         dst: u64,
889         src: u64,
890         len: u64,
891     ) -> Result<(), Trap> {
892         let mut storage = None;
893         let elements = store
894             .instance(instance)
895             .passive_element_segment(&mut storage, elem_index);
896         let mut const_evaluator = ConstExprEvaluator::default();
897         Self::table_init_segment(
898             store,
899             limiter,
900             instance,
901             &mut const_evaluator,
902             table_index,
903             elements,
904             dst,
905             src,
906             len,
907         )
908         .await
909     }
910 
911     pub(crate) async fn table_init_segment(
912         store: &mut StoreOpaque,
913         mut limiter: Option<&mut StoreResourceLimiter<'_>>,
914         elements_instance_id: InstanceId,
915         const_evaluator: &mut ConstExprEvaluator,
916         table_index: TableIndex,
917         elements: &TableSegmentElements,
918         dst: u64,
919         src: u64,
920         len: u64,
921     ) -> Result<(), Trap> {
922         // https://webassembly.github.io/bulk-memory-operations/core/exec/instructions.html#exec-table-init
923 
924         let store_id = store.id();
925         let elements_instance = store.instance_mut(elements_instance_id);
926         let table = elements_instance.get_exported_table(store_id, table_index);
927         let table_size = table._size(store);
928 
929         // Perform a bounds check on the table being written to. This is done by
930         // ensuring that `dst + len <= table.size()` via checked arithmetic.
931         //
932         // Note that the bounds check for the element segment happens below when
933         // the original segment is sliced via `src` and `len`.
934         table_size
935             .checked_sub(dst)
936             .and_then(|i| i.checked_sub(len))
937             .ok_or(Trap::TableOutOfBounds)?;
938 
939         let src = usize::try_from(src).map_err(|_| Trap::TableOutOfBounds)?;
940         let len = usize::try_from(len).map_err(|_| Trap::TableOutOfBounds)?;
941 
942         let positions = dst..dst + u64::try_from(len).unwrap();
943         match elements {
944             TableSegmentElements::Functions(funcs) => {
945                 let elements = funcs
946                     .get(src..)
947                     .and_then(|s| s.get(..len))
948                     .ok_or(Trap::TableOutOfBounds)?;
949                 for (i, func_idx) in positions.zip(elements) {
950                     // SAFETY: the `store_id` passed to `get_exported_func` is
951                     // indeed the store that owns the function.
952                     let func = unsafe {
953                         store
954                             .instance_mut(elements_instance_id)
955                             .get_exported_func(store_id, *func_idx)
956                     };
957                     table.set_(store, i, func.into()).unwrap();
958                 }
959             }
960             TableSegmentElements::Expressions(exprs) => {
961                 let mut store = OpaqueRootScope::new(store);
962                 let exprs = exprs
963                     .get(src..)
964                     .and_then(|s| s.get(..len))
965                     .ok_or(Trap::TableOutOfBounds)?;
966                 let mut context = ConstEvalContext::new(elements_instance_id);
967                 for (i, expr) in positions.zip(exprs) {
968                     let element = const_evaluator
969                         .eval(&mut store, limiter.as_deref_mut(), &mut context, expr)
970                         .await
971                         .expect("const expr should be valid");
972                     table.set_(&mut store, i, element.ref_().unwrap()).unwrap();
973                 }
974             }
975         }
976 
977         Ok(())
978     }
979 
980     /// Drop an element.
981     pub(crate) fn elem_drop(self: Pin<&mut Self>, elem_index: ElemIndex) {
982         // https://webassembly.github.io/reference-types/core/exec/instructions.html#exec-elem-drop
983 
984         self.dropped_elements_mut().insert(elem_index);
985 
986         // Note that we don't check that we actually removed a segment because
987         // dropping a non-passive segment is a no-op (not a trap).
988     }
989 
990     /// Get a locally-defined memory.
991     pub fn get_defined_memory_mut(self: Pin<&mut Self>, index: DefinedMemoryIndex) -> &mut Memory {
992         &mut self.memories_mut()[index].1
993     }
994 
995     /// Get a locally-defined memory.
996     pub fn get_defined_memory(&self, index: DefinedMemoryIndex) -> &Memory {
997         &self.memories[index].1
998     }
999 
1000     /// Do a `memory.copy`
1001     ///
1002     /// # Errors
1003     ///
1004     /// Returns a `Trap` error when the source or destination ranges are out of
1005     /// bounds.
1006     pub(crate) fn memory_copy(
1007         self: Pin<&mut Self>,
1008         dst_index: MemoryIndex,
1009         dst: u64,
1010         src_index: MemoryIndex,
1011         src: u64,
1012         len: u64,
1013     ) -> Result<(), Trap> {
1014         // https://webassembly.github.io/reference-types/core/exec/instructions.html#exec-memory-copy
1015 
1016         let src_mem = self.get_memory(src_index);
1017         let dst_mem = self.get_memory(dst_index);
1018 
1019         let src = self.validate_inbounds(src_mem.current_length(), src, len)?;
1020         let dst = self.validate_inbounds(dst_mem.current_length(), dst, len)?;
1021         let len = usize::try_from(len).unwrap();
1022 
1023         // Bounds and casts are checked above, by this point we know that
1024         // everything is safe.
1025         unsafe {
1026             let dst = dst_mem.base.as_ptr().add(dst);
1027             let src = src_mem.base.as_ptr().add(src);
1028             // FIXME audit whether this is safe in the presence of shared memory
1029             // (https://github.com/bytecodealliance/wasmtime/issues/4203).
1030             ptr::copy(src, dst, len);
1031         }
1032 
1033         Ok(())
1034     }
1035 
1036     fn validate_inbounds(&self, max: usize, ptr: u64, len: u64) -> Result<usize, Trap> {
1037         let oob = || Trap::MemoryOutOfBounds;
1038         let end = ptr
1039             .checked_add(len)
1040             .and_then(|i| usize::try_from(i).ok())
1041             .ok_or_else(oob)?;
1042         if end > max {
1043             Err(oob())
1044         } else {
1045             Ok(ptr.try_into().unwrap())
1046         }
1047     }
1048 
1049     /// Perform the `memory.fill` operation on a locally defined memory.
1050     ///
1051     /// # Errors
1052     ///
1053     /// Returns a `Trap` error if the memory range is out of bounds.
1054     pub(crate) fn memory_fill(
1055         self: Pin<&mut Self>,
1056         memory_index: DefinedMemoryIndex,
1057         dst: u64,
1058         val: u8,
1059         len: u64,
1060     ) -> Result<(), Trap> {
1061         let memory_index = self.env_module().memory_index(memory_index);
1062         let memory = self.get_memory(memory_index);
1063         let dst = self.validate_inbounds(memory.current_length(), dst, len)?;
1064         let len = usize::try_from(len).unwrap();
1065 
1066         // Bounds and casts are checked above, by this point we know that
1067         // everything is safe.
1068         unsafe {
1069             let dst = memory.base.as_ptr().add(dst);
1070             // FIXME audit whether this is safe in the presence of shared memory
1071             // (https://github.com/bytecodealliance/wasmtime/issues/4203).
1072             ptr::write_bytes(dst, val, len);
1073         }
1074 
1075         Ok(())
1076     }
1077 
1078     /// Get the internal storage range of a particular Wasm data segment.
1079     pub(crate) fn wasm_data_range(&self, index: DataIndex) -> Range<u32> {
1080         match self.env_module().passive_data_map.get(&index) {
1081             Some(range) if !self.dropped_data.contains(index) => range.clone(),
1082             _ => 0..0,
1083         }
1084     }
1085 
1086     /// Given an internal storage range of a Wasm data segment (or subset of a
1087     /// Wasm data segment), get the data's raw bytes.
1088     pub(crate) fn wasm_data(&self, range: Range<u32>) -> &[u8] {
1089         let start = usize::try_from(range.start).unwrap();
1090         let end = usize::try_from(range.end).unwrap();
1091         &self.runtime_info.wasm_data()[start..end]
1092     }
1093 
1094     /// Performs the `memory.init` operation.
1095     ///
1096     /// # Errors
1097     ///
1098     /// Returns a `Trap` error if the destination range is out of this module's
1099     /// memory's bounds or if the source range is outside the data segment's
1100     /// bounds.
1101     pub(crate) fn memory_init(
1102         self: Pin<&mut Self>,
1103         memory_index: MemoryIndex,
1104         data_index: DataIndex,
1105         dst: u64,
1106         src: u32,
1107         len: u32,
1108     ) -> Result<(), Trap> {
1109         let range = self.wasm_data_range(data_index);
1110         self.memory_init_segment(memory_index, range, dst, src, len)
1111     }
1112 
1113     pub(crate) fn memory_init_segment(
1114         self: Pin<&mut Self>,
1115         memory_index: MemoryIndex,
1116         range: Range<u32>,
1117         dst: u64,
1118         src: u32,
1119         len: u32,
1120     ) -> Result<(), Trap> {
1121         // https://webassembly.github.io/bulk-memory-operations/core/exec/instructions.html#exec-memory-init
1122 
1123         let memory = self.get_memory(memory_index);
1124         let data = self.wasm_data(range);
1125         let dst = self.validate_inbounds(memory.current_length(), dst, len.into())?;
1126         let src = self.validate_inbounds(data.len(), src.into(), len.into())?;
1127         let len = len as usize;
1128 
1129         unsafe {
1130             let src_start = data.as_ptr().add(src);
1131             let dst_start = memory.base.as_ptr().add(dst);
1132             // FIXME audit whether this is safe in the presence of shared memory
1133             // (https://github.com/bytecodealliance/wasmtime/issues/4203).
1134             ptr::copy_nonoverlapping(src_start, dst_start, len);
1135         }
1136 
1137         Ok(())
1138     }
1139 
1140     /// Drop the given data segment, truncating its length to zero.
1141     pub(crate) fn data_drop(self: Pin<&mut Self>, data_index: DataIndex) {
1142         self.dropped_data_mut().insert(data_index);
1143 
1144         // Note that we don't check that we actually removed a segment because
1145         // dropping a non-passive segment is a no-op (not a trap).
1146     }
1147 
1148     /// Get a table by index regardless of whether it is locally-defined
1149     /// or an imported, foreign table. Ensure that the given range of
1150     /// elements in the table is lazily initialized.  We define this
1151     /// operation all-in-one for safety, to ensure the lazy-init
1152     /// happens.
1153     ///
1154     /// Takes an `Iterator` for the index-range to lazy-initialize,
1155     /// for flexibility. This can be a range, single item, or empty
1156     /// sequence, for example. The iterator should return indices in
1157     /// increasing order, so that the break-at-out-of-bounds behavior
1158     /// works correctly.
1159     pub(crate) fn get_table_with_lazy_init(
1160         self: Pin<&mut Self>,
1161         table_index: TableIndex,
1162         range: impl Iterator<Item = u64>,
1163     ) -> &mut Table {
1164         let (idx, instance) = self.defined_table_index_and_instance(table_index);
1165         instance.get_defined_table_with_lazy_init(idx, range)
1166     }
1167 
1168     /// Gets the raw runtime table data structure owned by this instance
1169     /// given the provided `idx`.
1170     ///
1171     /// The `range` specified is eagerly initialized for funcref tables.
1172     pub fn get_defined_table_with_lazy_init(
1173         mut self: Pin<&mut Self>,
1174         idx: DefinedTableIndex,
1175         range: impl IntoIterator<Item = u64>,
1176     ) -> &mut Table {
1177         let elt_ty = self.tables[idx].1.element_type();
1178 
1179         if elt_ty == TableElementType::Func {
1180             for i in range {
1181                 match self.tables[idx].1.get_func_maybe_init(i) {
1182                     // Uninitialized table element.
1183                     Ok(None) => {}
1184                     // Initialized table element, move on to the next.
1185                     Ok(Some(_)) => continue,
1186                     // Out-of-bounds; caller will handle by likely
1187                     // throwing a trap. No work to do to lazy-init
1188                     // beyond the end.
1189                     Err(_) => break,
1190                 };
1191 
1192                 // The table element `i` is uninitialized and is now being
1193                 // initialized. This must imply that a `precompiled` list of
1194                 // function indices is available for this table. The precompiled
1195                 // list is extracted and then it is consulted with `i` to
1196                 // determine the function that is going to be initialized. Note
1197                 // that `i` may be outside the limits of the static
1198                 // initialization so it's a fallible `get` instead of an index.
1199                 let module = self.env_module();
1200                 let precomputed = match &module.table_initialization.initial_values[idx] {
1201                     TableInitialValue::Null { precomputed } => precomputed,
1202                     TableInitialValue::Expr(_) => unreachable!(),
1203                 };
1204                 // Panicking here helps catch bugs rather than silently truncating by accident.
1205                 let func_index = precomputed.get(usize::try_from(i).unwrap()).cloned();
1206                 let func_ref =
1207                     func_index.and_then(|func_index| self.as_mut().get_func_ref(func_index));
1208                 self.as_mut().tables_mut()[idx]
1209                     .1
1210                     .set_func(i, func_ref)
1211                     .expect("Table type should match and index should be in-bounds");
1212             }
1213         }
1214 
1215         self.get_defined_table(idx)
1216     }
1217 
1218     /// Get a table by index regardless of whether it is locally-defined or an
1219     /// imported, foreign table.
1220     pub(crate) fn get_table(self: Pin<&mut Self>, table_index: TableIndex) -> &mut Table {
1221         let (idx, instance) = self.defined_table_index_and_instance(table_index);
1222         instance.get_defined_table(idx)
1223     }
1224 
1225     /// Get a locally-defined table.
1226     pub(crate) fn get_defined_table(self: Pin<&mut Self>, index: DefinedTableIndex) -> &mut Table {
1227         &mut self.tables_mut()[index].1
1228     }
1229 
1230     pub(crate) fn defined_table_index_and_instance<'a>(
1231         self: Pin<&'a mut Self>,
1232         index: TableIndex,
1233     ) -> (DefinedTableIndex, Pin<&'a mut Instance>) {
1234         if let Some(defined_table_index) = self.env_module().defined_table_index(index) {
1235             (defined_table_index, self)
1236         } else {
1237             let import = self.imported_table(index);
1238             let index = import.index;
1239             let vmctx = import.vmctx.as_non_null();
1240             // SAFETY: the validity of `self` means that the reachable instances
1241             // should also all be owned by the same store and fully initialized,
1242             // so it's safe to laterally move from a mutable borrow of this
1243             // instance to a mutable borrow of a sibling instance.
1244             let foreign_instance = unsafe { self.sibling_vmctx_mut(vmctx) };
1245             (index, foreign_instance)
1246         }
1247     }
1248 
1249     /// Initialize the VMContext data associated with this Instance.
1250     ///
1251     /// The `VMContext` memory is assumed to be uninitialized; any field
1252     /// that we need in a certain state will be explicitly written by this
1253     /// function.
1254     unsafe fn initialize_vmctx(
1255         mut self: Pin<&mut Self>,
1256         module: &Module,
1257         offsets: &VMOffsets<HostPtr>,
1258         store: &StoreOpaque,
1259         imports: Imports,
1260     ) {
1261         assert!(ptr::eq(module, self.env_module().as_ref()));
1262 
1263         // SAFETY: the type of the magic field is indeed `u32` and this function
1264         // is initializing its value.
1265         unsafe {
1266             self.vmctx_plus_offset_raw::<u32>(offsets.ptr.vmctx_magic())
1267                 .write(VMCONTEXT_MAGIC);
1268         }
1269 
1270         // SAFETY: it's up to the caller to provide a valid store pointer here.
1271         unsafe {
1272             self.as_mut().set_store(store);
1273         }
1274 
1275         // Initialize shared types
1276         //
1277         // SAFETY: validity of the vmctx means it should be safe to write to it
1278         // here.
1279         unsafe {
1280             let types = NonNull::from(self.runtime_info.type_ids());
1281             self.type_ids_array().write(types.cast().into());
1282         }
1283 
1284         // Initialize the built-in functions
1285         //
1286         // SAFETY: the type of the builtin functions field is indeed a pointer
1287         // and the pointer being filled in here, plus the vmctx is valid to
1288         // write to during initialization.
1289         unsafe {
1290             static BUILTINS: VMBuiltinFunctionsArray = VMBuiltinFunctionsArray::INIT;
1291             let ptr = BUILTINS.expose_provenance();
1292             self.vmctx_plus_offset_raw(offsets.ptr.vmctx_builtin_functions())
1293                 .write(VmPtr::from(ptr));
1294         }
1295 
1296         // Initialize the imports
1297         //
1298         // SAFETY: the vmctx is safe to initialize during this function and
1299         // validity of each item itself is a contract the caller must uphold.
1300         debug_assert_eq!(imports.functions.len(), module.num_imported_funcs);
1301         unsafe {
1302             ptr::copy_nonoverlapping(
1303                 imports.functions.as_ptr(),
1304                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_functions_begin())
1305                     .as_ptr(),
1306                 imports.functions.len(),
1307             );
1308             debug_assert_eq!(imports.tables.len(), module.num_imported_tables);
1309             ptr::copy_nonoverlapping(
1310                 imports.tables.as_ptr(),
1311                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_tables_begin())
1312                     .as_ptr(),
1313                 imports.tables.len(),
1314             );
1315             debug_assert_eq!(imports.memories.len(), module.num_imported_memories);
1316             ptr::copy_nonoverlapping(
1317                 imports.memories.as_ptr(),
1318                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_memories_begin())
1319                     .as_ptr(),
1320                 imports.memories.len(),
1321             );
1322             debug_assert_eq!(imports.globals.len(), module.num_imported_globals);
1323             ptr::copy_nonoverlapping(
1324                 imports.globals.as_ptr(),
1325                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_globals_begin())
1326                     .as_ptr(),
1327                 imports.globals.len(),
1328             );
1329             debug_assert_eq!(imports.tags.len(), module.num_imported_tags);
1330             ptr::copy_nonoverlapping(
1331                 imports.tags.as_ptr(),
1332                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_tags_begin())
1333                     .as_ptr(),
1334                 imports.tags.len(),
1335             );
1336         }
1337 
1338         // N.B.: there is no need to initialize the funcrefs array because we
1339         // eagerly construct each element in it whenever asked for a reference
1340         // to that element. In other words, there is no state needed to track
1341         // the lazy-init, so we don't need to initialize any state now.
1342 
1343         // Initialize the defined tables
1344         //
1345         // SAFETY: it's safe to initialize these tables during initialization
1346         // here and the various types of pointers and such here should all be
1347         // valid.
1348         unsafe {
1349             let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_tables_begin());
1350             let tables = self.as_mut().tables_mut();
1351             for i in 0..module.num_defined_tables() {
1352                 ptr.write(tables[DefinedTableIndex::new(i)].1.vmtable());
1353                 ptr = ptr.add(1);
1354             }
1355         }
1356 
1357         // Initialize the defined memories. This fills in both the
1358         // `defined_memories` table and the `owned_memories` table at the same
1359         // time. Entries in `defined_memories` hold a pointer to a definition
1360         // (all memories) whereas the `owned_memories` hold the actual
1361         // definitions of memories owned (not shared) in the module.
1362         //
1363         // SAFETY: it's safe to initialize these memories during initialization
1364         // here and the various types of pointers and such here should all be
1365         // valid.
1366         unsafe {
1367             let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_memories_begin());
1368             let mut owned_ptr = self.vmctx_plus_offset_raw(offsets.vmctx_owned_memories_begin());
1369             let memories = self.as_mut().memories_mut();
1370             for i in 0..module.num_defined_memories() {
1371                 let defined_memory_index = DefinedMemoryIndex::new(i);
1372                 let memory_index = module.memory_index(defined_memory_index);
1373                 if module.memories[memory_index].shared {
1374                     let def_ptr = memories[defined_memory_index]
1375                         .1
1376                         .as_shared_memory()
1377                         .unwrap()
1378                         .vmmemory_ptr();
1379                     ptr.write(VmPtr::from(def_ptr));
1380                 } else {
1381                     owned_ptr.write(memories[defined_memory_index].1.vmmemory());
1382                     ptr.write(VmPtr::from(owned_ptr));
1383                     owned_ptr = owned_ptr.add(1);
1384                 }
1385                 ptr = ptr.add(1);
1386             }
1387         }
1388 
1389         // Zero-initialize the globals so that nothing is uninitialized memory
1390         // after this function returns. The globals are actually initialized
1391         // with their const expression initializers after the instance is fully
1392         // allocated.
1393         //
1394         // SAFETY: it's safe to initialize globals during initialization
1395         // here. Note that while the value being written is not valid for all
1396         // types of globals it's initializing the memory to zero instead of
1397         // being in an undefined state. So it's still unsafe to access globals
1398         // after this, but if it's read then it'd hopefully crash faster than
1399         // leaving this undefined.
1400         unsafe {
1401             for (index, _init) in module.global_initializers.iter() {
1402                 self.global_ptr(index).write(VMGlobalDefinition::new());
1403             }
1404         }
1405 
1406         // Initialize the defined tags
1407         //
1408         // SAFETY: it's safe to initialize these tags during initialization
1409         // here and the various types of pointers and such here should all be
1410         // valid.
1411         unsafe {
1412             let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_tags_begin());
1413             for i in 0..module.num_defined_tags() {
1414                 let defined_index = DefinedTagIndex::new(i);
1415                 let tag_index = module.tag_index(defined_index);
1416                 let tag = module.tags[tag_index];
1417                 ptr.write(VMTagDefinition::new(
1418                     tag.signature.unwrap_engine_type_index(),
1419                 ));
1420                 ptr = ptr.add(1);
1421             }
1422         }
1423     }
1424 
1425     /// Attempts to convert from the host `addr` specified to a WebAssembly
1426     /// based address recorded in `WasmFault`.
1427     ///
1428     /// This method will check all linear memories that this instance contains
1429     /// to see if any of them contain `addr`. If one does then `Some` is
1430     /// returned with metadata about the wasm fault. Otherwise `None` is
1431     /// returned and `addr` doesn't belong to this instance.
1432     pub fn wasm_fault(&self, addr: usize) -> Option<WasmFault> {
1433         let mut fault = None;
1434         for (_, (_, memory)) in self.memories.iter() {
1435             let accessible = memory.wasm_accessible();
1436             if accessible.start <= addr && addr < accessible.end {
1437                 // All linear memories should be disjoint so assert that no
1438                 // prior fault has been found.
1439                 assert!(fault.is_none());
1440                 fault = Some(WasmFault {
1441                     memory_size: memory.byte_size(),
1442                     wasm_address: u64::try_from(addr - accessible.start).unwrap(),
1443                 });
1444             }
1445         }
1446         fault
1447     }
1448 
1449     /// Returns the id, within this instance's store, that it's assigned.
1450     pub fn id(&self) -> InstanceId {
1451         self.id
1452     }
1453 
1454     /// Get all memories within this instance.
1455     ///
1456     /// Returns both import and defined memories.
1457     ///
1458     /// Returns both exported and non-exported memories.
1459     ///
1460     /// Gives access to the full memories space.
1461     pub fn all_memories(
1462         &self,
1463         store: StoreId,
1464     ) -> impl ExactSizeIterator<Item = (MemoryIndex, crate::Memory)> + '_ {
1465         self.env_module()
1466             .memories
1467             .iter()
1468             .map(move |(i, _)| (i, self.get_exported_memory(store, i)))
1469     }
1470 
1471     /// Return the memories defined in this instance (not imported).
1472     pub fn defined_memories<'a>(
1473         &'a self,
1474         store: StoreId,
1475     ) -> impl ExactSizeIterator<Item = crate::Memory> + 'a {
1476         let num_imported = self.env_module().num_imported_memories;
1477         self.all_memories(store)
1478             .skip(num_imported)
1479             .map(|(_i, memory)| memory)
1480     }
1481 
1482     /// Lookup an item with the given index.
1483     ///
1484     /// # Panics
1485     ///
1486     /// Panics if `export` is not valid for this instance.
1487     ///
1488     /// # Safety
1489     ///
1490     /// This function requires that `store` is the correct store which owns this
1491     /// instance.
1492     pub unsafe fn get_export_by_index_mut(
1493         self: Pin<&mut Self>,
1494         store: StoreId,
1495         export: EntityIndex,
1496     ) -> Export {
1497         match export {
1498             // SAFETY: the contract of `store` owning the this instance is a
1499             // safety requirement of this function itself.
1500             EntityIndex::Function(i) => {
1501                 Export::Function(unsafe { self.get_exported_func(store, i) })
1502             }
1503             EntityIndex::Global(i) => Export::Global(self.get_exported_global(store, i)),
1504             EntityIndex::Table(i) => Export::Table(self.get_exported_table(store, i)),
1505             EntityIndex::Memory(i) => Export::Memory {
1506                 memory: self.get_exported_memory(store, i),
1507                 shared: self.env_module().memories[i].shared,
1508             },
1509             EntityIndex::Tag(i) => Export::Tag(self.get_exported_tag(store, i)),
1510         }
1511     }
1512 
1513     fn store_mut(self: Pin<&mut Self>) -> &mut Option<VMStoreRawPtr> {
1514         // SAFETY: this is a pin-projection to get a mutable reference to an
1515         // internal field and is safe so long as the `&mut Self` temporarily
1516         // created is not overwritten, which it isn't here.
1517         unsafe { &mut self.get_unchecked_mut().store }
1518     }
1519 
1520     fn dropped_elements_mut(self: Pin<&mut Self>) -> &mut EntitySet<ElemIndex> {
1521         // SAFETY: see `store_mut` above.
1522         unsafe { &mut self.get_unchecked_mut().dropped_elements }
1523     }
1524 
1525     fn dropped_data_mut(self: Pin<&mut Self>) -> &mut EntitySet<DataIndex> {
1526         // SAFETY: see `store_mut` above.
1527         unsafe { &mut self.get_unchecked_mut().dropped_data }
1528     }
1529 
1530     fn memories_mut(
1531         self: Pin<&mut Self>,
1532     ) -> &mut PrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)> {
1533         // SAFETY: see `store_mut` above.
1534         unsafe { &mut self.get_unchecked_mut().memories }
1535     }
1536 
1537     pub(crate) fn tables_mut(
1538         self: Pin<&mut Self>,
1539     ) -> &mut PrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)> {
1540         // SAFETY: see `store_mut` above.
1541         unsafe { &mut self.get_unchecked_mut().tables }
1542     }
1543 
1544     #[cfg(feature = "wmemcheck")]
1545     pub(super) fn wmemcheck_state_mut(self: Pin<&mut Self>) -> &mut Option<Wmemcheck> {
1546         // SAFETY: see `store_mut` above.
1547         unsafe { &mut self.get_unchecked_mut().wmemcheck_state }
1548     }
1549 }
1550 
1551 // SAFETY: `layout` should describe this accurately and `OwnedVMContext` is the
1552 // last field of `ComponentInstance`.
1553 unsafe impl InstanceLayout for Instance {
1554     const INIT_ZEROED: bool = false;
1555     type VMContext = VMContext;
1556 
1557     fn layout(&self) -> Layout {
1558         Self::alloc_layout(self.runtime_info.offsets())
1559     }
1560 
1561     fn owned_vmctx(&self) -> &OwnedVMContext<VMContext> {
1562         &self.vmctx
1563     }
1564 
1565     fn owned_vmctx_mut(&mut self) -> &mut OwnedVMContext<VMContext> {
1566         &mut self.vmctx
1567     }
1568 }
1569 
1570 pub type InstanceHandle = OwnedInstance<Instance>;
1571 
1572 /// A handle holding an `Instance` of a WebAssembly module.
1573 ///
1574 /// This structure is an owning handle of the `instance` contained internally.
1575 /// When this value goes out of scope it will deallocate the `Instance` and all
1576 /// memory associated with it.
1577 ///
1578 /// Note that this lives within a `StoreOpaque` on a list of instances that a
1579 /// store is keeping alive.
1580 #[derive(Debug)]
1581 #[repr(transparent)] // guarantee this is a zero-cost wrapper
1582 pub struct OwnedInstance<T: InstanceLayout> {
1583     /// The raw pointer to the instance that was allocated.
1584     ///
1585     /// Note that this is not equivalent to `Box<Instance>` because the
1586     /// allocation here has a `VMContext` trailing after it. Thus the custom
1587     /// destructor to invoke the `dealloc` function with the appropriate
1588     /// layout.
1589     instance: SendSyncPtr<T>,
1590     _marker: marker::PhantomData<Box<(T, OwnedVMContext<T::VMContext>)>>,
1591 }
1592 
1593 /// Structure that must be placed at the end of a type implementing
1594 /// `InstanceLayout`.
1595 #[repr(align(16))] // match the alignment of VMContext
1596 pub struct OwnedVMContext<T> {
1597     /// A pointer to the `vmctx` field at the end of the `structure`.
1598     ///
1599     /// If you're looking at this a reasonable question would be "why do we need
1600     /// a pointer to ourselves?" because after all the pointer's value is
1601     /// trivially derivable from any `&Instance` pointer. The rationale for this
1602     /// field's existence is subtle, but it's required for correctness. The
1603     /// short version is "this makes miri happy".
1604     ///
1605     /// The long version of why this field exists is that the rules that MIRI
1606     /// uses to ensure pointers are used correctly have various conditions on
1607     /// them depend on how pointers are used. More specifically if `*mut T` is
1608     /// derived from `&mut T`, then that invalidates all prior pointers drived
1609     /// from the `&mut T`. This means that while we liberally want to re-acquire
1610     /// a `*mut VMContext` throughout the implementation of `Instance` the
1611     /// trivial way, a function `fn vmctx(Pin<&mut Instance>) -> *mut VMContext`
1612     /// would effectively invalidate all prior `*mut VMContext` pointers
1613     /// acquired. The purpose of this field is to serve as a sort of
1614     /// source-of-truth for where `*mut VMContext` pointers come from.
1615     ///
1616     /// This field is initialized when the `Instance` is created with the
1617     /// original allocation's pointer. That means that the provenance of this
1618     /// pointer contains the entire allocation (both instance and `VMContext`).
1619     /// This provenance bit is then "carried through" where `fn vmctx` will base
1620     /// all returned pointers on this pointer itself. This provides the means of
1621     /// never invalidating this pointer throughout MIRI and additionally being
1622     /// able to still temporarily have `Pin<&mut Instance>` methods and such.
1623     ///
1624     /// It's important to note, though, that this is not here purely for MIRI.
1625     /// The careful construction of the `fn vmctx` method has ramifications on
1626     /// the LLVM IR generated, for example. A historical CVE on Wasmtime,
1627     /// GHSA-ch89-5g45-qwc7, was caused due to relying on undefined behavior. By
1628     /// deriving VMContext pointers from this pointer it specifically hints to
1629     /// LLVM that trickery is afoot and it properly informs `noalias` and such
1630     /// annotations and analysis. More-or-less this pointer is actually loaded
1631     /// in LLVM IR which helps defeat otherwise present aliasing optimizations,
1632     /// which we want, since writes to this should basically never be optimized
1633     /// out.
1634     ///
1635     /// As a final note it's worth pointing out that the machine code generated
1636     /// for accessing `fn vmctx` is still as one would expect. This member isn't
1637     /// actually ever loaded at runtime (or at least shouldn't be). Perhaps in
1638     /// the future if the memory consumption of this field is a problem we could
1639     /// shrink it slightly, but for now one extra pointer per wasm instance
1640     /// seems not too bad.
1641     vmctx_self_reference: SendSyncPtr<T>,
1642 
1643     /// This field ensures that going from `Pin<&mut T>` to `&mut T` is not a
1644     /// safe operation.
1645     _marker: core::marker::PhantomPinned,
1646 }
1647 
1648 impl<T> OwnedVMContext<T> {
1649     /// Creates a new blank vmctx to place at the end of an instance.
1650     pub fn new() -> OwnedVMContext<T> {
1651         OwnedVMContext {
1652             vmctx_self_reference: SendSyncPtr::new(NonNull::dangling()),
1653             _marker: core::marker::PhantomPinned,
1654         }
1655     }
1656 }
1657 
1658 /// Helper trait to plumb both core instances and component instances into
1659 /// `OwnedInstance` below.
1660 ///
1661 /// # Safety
1662 ///
1663 /// This trait requires `layout` to correctly describe `Self` and appropriately
1664 /// allocate space for `Self::VMContext` afterwards. Additionally the field
1665 /// returned by `owned_vmctx()` must be the last field in the structure.
1666 pub unsafe trait InstanceLayout {
1667     /// Whether or not to allocate this instance with `alloc_zeroed` or `alloc`.
1668     const INIT_ZEROED: bool;
1669 
1670     /// The trailing `VMContext` type at the end of this instance.
1671     type VMContext;
1672 
1673     /// The memory layout to use to allocate and deallocate this instance.
1674     fn layout(&self) -> Layout;
1675 
1676     fn owned_vmctx(&self) -> &OwnedVMContext<Self::VMContext>;
1677     fn owned_vmctx_mut(&mut self) -> &mut OwnedVMContext<Self::VMContext>;
1678 
1679     /// Returns the `vmctx_self_reference` set above.
1680     #[inline]
1681     fn vmctx(&self) -> NonNull<Self::VMContext> {
1682         // The definition of this method is subtle but intentional. The goal
1683         // here is that effectively this should return `&mut self.vmctx`, but
1684         // it's not quite so simple. Some more documentation is available on the
1685         // `vmctx_self_reference` field, but the general idea is that we're
1686         // creating a pointer to return with proper provenance. Provenance is
1687         // still in the works in Rust at the time of this writing but the load
1688         // of the `self.vmctx_self_reference` field is important here as it
1689         // affects how LLVM thinks about aliasing with respect to the returned
1690         // pointer.
1691         //
1692         // The intention of this method is to codegen to machine code as `&mut
1693         // self.vmctx`, however. While it doesn't show up like this in LLVM IR
1694         // (there's an actual load of the field) it does look like that by the
1695         // time the backend runs. (that's magic to me, the backend removing
1696         // loads...)
1697         let owned_vmctx = self.owned_vmctx();
1698         let owned_vmctx_raw = NonNull::from(owned_vmctx);
1699         // SAFETY: it's part of the contract of `InstanceLayout` and the usage
1700         // with `OwnedInstance` that this indeed points to the vmctx.
1701         let addr = unsafe { owned_vmctx_raw.add(1) };
1702         owned_vmctx
1703             .vmctx_self_reference
1704             .as_non_null()
1705             .with_addr(addr.addr())
1706     }
1707 
1708     /// Helper function to access various locations offset from our `*mut
1709     /// VMContext` object.
1710     ///
1711     /// Note that this method takes `&self` as an argument but returns
1712     /// `NonNull<T>` which is frequently used to mutate said memory. This is an
1713     /// intentional design decision where the safety of the modification of
1714     /// memory is placed as a burden onto the caller. The implementation of this
1715     /// method explicitly does not require `&mut self` to acquire mutable
1716     /// provenance to update the `VMContext` region. Instead all pointers into
1717     /// the `VMContext` area have provenance/permissions to write.
1718     ///
1719     /// Also note though that care must be taken to ensure that reads/writes of
1720     /// memory must only happen where appropriate, for example a non-atomic
1721     /// write (as most are) should never happen concurrently with another read
1722     /// or write. It's generally on the burden of the caller to adhere to this.
1723     ///
1724     /// Also of note is that most of the time the usage of this method falls
1725     /// into one of:
1726     ///
1727     /// * Something in the VMContext is being read or written. In that case use
1728     ///   `vmctx_plus_offset` or `vmctx_plus_offset_mut` if possible due to
1729     ///   that having a safer lifetime.
1730     ///
1731     /// * A pointer is being created to pass to other VM* data structures. In
1732     ///   that situation the lifetime of all VM data structures are typically
1733     ///   tied to the `Store<T>` which is what provides the guarantees around
1734     ///   concurrency/etc.
1735     ///
1736     /// There's quite a lot of unsafety riding on this method, especially
1737     /// related to the ascription `T` of the byte `offset`. It's hoped that in
1738     /// the future we're able to settle on an in theory safer design.
1739     ///
1740     /// # Safety
1741     ///
1742     /// This method is unsafe because the `offset` must be within bounds of the
1743     /// `VMContext` object trailing this instance. Additionally `T` must be a
1744     /// valid ascription of the value that resides at that location.
1745     unsafe fn vmctx_plus_offset_raw<T: VmSafe>(&self, offset: impl Into<u32>) -> NonNull<T> {
1746         // SAFETY: the safety requirements of `byte_add` are forwarded to this
1747         // method's caller.
1748         unsafe {
1749             self.vmctx()
1750                 .byte_add(usize::try_from(offset.into()).unwrap())
1751                 .cast()
1752         }
1753     }
1754 
1755     /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of
1756     /// `&self` to the returned reference `&T`.
1757     ///
1758     /// # Safety
1759     ///
1760     /// See the safety documentation of `vmctx_plus_offset_raw`.
1761     unsafe fn vmctx_plus_offset<T: VmSafe>(&self, offset: impl Into<u32>) -> &T {
1762         // SAFETY: this method has the same safety requirements as
1763         // `vmctx_plus_offset_raw`.
1764         unsafe { self.vmctx_plus_offset_raw(offset).as_ref() }
1765     }
1766 
1767     /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of
1768     /// `&mut self` to the returned reference `&mut T`.
1769     ///
1770     /// # Safety
1771     ///
1772     /// See the safety documentation of `vmctx_plus_offset_raw`.
1773     unsafe fn vmctx_plus_offset_mut<T: VmSafe>(
1774         self: Pin<&mut Self>,
1775         offset: impl Into<u32>,
1776     ) -> &mut T {
1777         // SAFETY: this method has the same safety requirements as
1778         // `vmctx_plus_offset_raw`.
1779         unsafe { self.vmctx_plus_offset_raw(offset).as_mut() }
1780     }
1781 }
1782 
1783 impl<T: InstanceLayout> OwnedInstance<T> {
1784     /// Allocates a new `OwnedInstance` and places `instance` inside of it.
1785     ///
1786     /// This will `instance`
1787     pub(super) fn new(mut instance: T) -> OwnedInstance<T> {
1788         let layout = instance.layout();
1789         debug_assert!(layout.size() >= size_of_val(&instance));
1790         debug_assert!(layout.align() >= align_of_val(&instance));
1791 
1792         // SAFETY: it's up to us to assert that `layout` has a non-zero size,
1793         // which is asserted here.
1794         let ptr = unsafe {
1795             assert!(layout.size() > 0);
1796             if T::INIT_ZEROED {
1797                 alloc::alloc::alloc_zeroed(layout)
1798             } else {
1799                 alloc::alloc::alloc(layout)
1800             }
1801         };
1802         if ptr.is_null() {
1803             alloc::alloc::handle_alloc_error(layout);
1804         }
1805         let instance_ptr = NonNull::new(ptr.cast::<T>()).unwrap();
1806 
1807         // SAFETY: it's part of the unsafe contract of `InstanceLayout` that the
1808         // `add` here is appropriate for the layout allocated.
1809         let vmctx_self_reference = unsafe { instance_ptr.add(1).cast() };
1810         instance.owned_vmctx_mut().vmctx_self_reference = vmctx_self_reference.into();
1811 
1812         // SAFETY: we allocated above and it's an unsafe contract of
1813         // `InstanceLayout` that the layout is suitable for writing the
1814         // instance.
1815         unsafe {
1816             instance_ptr.write(instance);
1817         }
1818 
1819         let ret = OwnedInstance {
1820             instance: SendSyncPtr::new(instance_ptr),
1821             _marker: marker::PhantomData,
1822         };
1823 
1824         // Double-check various vmctx calculations are correct.
1825         debug_assert_eq!(
1826             vmctx_self_reference.addr(),
1827             // SAFETY: `InstanceLayout` should guarantee it's safe to add 1 to
1828             // the last field to get a pointer to 1-byte-past-the-end of an
1829             // object, which should be valid.
1830             unsafe { NonNull::from(ret.get().owned_vmctx()).add(1).addr() }
1831         );
1832         debug_assert_eq!(vmctx_self_reference.addr(), ret.get().vmctx().addr());
1833 
1834         ret
1835     }
1836 
1837     /// Gets the raw underlying `&Instance` from this handle.
1838     pub fn get(&self) -> &T {
1839         // SAFETY: this is an owned instance handle that retains exclusive
1840         // ownership of the `Instance` inside. With `&self` given we know
1841         // this pointer is valid valid and the returned lifetime is connected
1842         // to `self` so that should also be valid.
1843         unsafe { self.instance.as_non_null().as_ref() }
1844     }
1845 
1846     /// Same as [`Self::get`] except for mutability.
1847     pub fn get_mut(&mut self) -> Pin<&mut T> {
1848         // SAFETY: The lifetime concerns here are the same as `get` above.
1849         // Otherwise `new_unchecked` is used here to uphold the contract that
1850         // instances are always pinned in memory.
1851         unsafe { Pin::new_unchecked(self.instance.as_non_null().as_mut()) }
1852     }
1853 }
1854 
1855 impl<T: InstanceLayout> Drop for OwnedInstance<T> {
1856     fn drop(&mut self) {
1857         unsafe {
1858             let layout = self.get().layout();
1859             ptr::drop_in_place(self.instance.as_ptr());
1860             alloc::alloc::dealloc(self.instance.as_ptr().cast(), layout);
1861         }
1862     }
1863 }
1864