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<()> {
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<()> {
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                     table.set_(&mut store, i, element.ref_().unwrap()).unwrap();
972                 }
973             }
974         }
975 
976         Ok(())
977     }
978 
979     /// Drop an element.
980     pub(crate) fn elem_drop(self: Pin<&mut Self>, elem_index: ElemIndex) {
981         // https://webassembly.github.io/reference-types/core/exec/instructions.html#exec-elem-drop
982 
983         self.dropped_elements_mut().insert(elem_index);
984 
985         // Note that we don't check that we actually removed a segment because
986         // dropping a non-passive segment is a no-op (not a trap).
987     }
988 
989     /// Get a locally-defined memory.
990     pub fn get_defined_memory_mut(self: Pin<&mut Self>, index: DefinedMemoryIndex) -> &mut Memory {
991         &mut self.memories_mut()[index].1
992     }
993 
994     /// Get a locally-defined memory.
995     pub fn get_defined_memory(&self, index: DefinedMemoryIndex) -> &Memory {
996         &self.memories[index].1
997     }
998 
999     /// Do a `memory.copy`
1000     ///
1001     /// # Errors
1002     ///
1003     /// Returns a `Trap` error when the source or destination ranges are out of
1004     /// bounds.
1005     pub(crate) fn memory_copy(
1006         self: Pin<&mut Self>,
1007         dst_index: MemoryIndex,
1008         dst: u64,
1009         src_index: MemoryIndex,
1010         src: u64,
1011         len: u64,
1012     ) -> Result<(), Trap> {
1013         // https://webassembly.github.io/reference-types/core/exec/instructions.html#exec-memory-copy
1014 
1015         let src_mem = self.get_memory(src_index);
1016         let dst_mem = self.get_memory(dst_index);
1017 
1018         let src = self.validate_inbounds(src_mem.current_length(), src, len)?;
1019         let dst = self.validate_inbounds(dst_mem.current_length(), dst, len)?;
1020         let len = usize::try_from(len).unwrap();
1021 
1022         // Bounds and casts are checked above, by this point we know that
1023         // everything is safe.
1024         unsafe {
1025             let dst = dst_mem.base.as_ptr().add(dst);
1026             let src = src_mem.base.as_ptr().add(src);
1027             // FIXME audit whether this is safe in the presence of shared memory
1028             // (https://github.com/bytecodealliance/wasmtime/issues/4203).
1029             ptr::copy(src, dst, len);
1030         }
1031 
1032         Ok(())
1033     }
1034 
1035     fn validate_inbounds(&self, max: usize, ptr: u64, len: u64) -> Result<usize, Trap> {
1036         let oob = || Trap::MemoryOutOfBounds;
1037         let end = ptr
1038             .checked_add(len)
1039             .and_then(|i| usize::try_from(i).ok())
1040             .ok_or_else(oob)?;
1041         if end > max {
1042             Err(oob())
1043         } else {
1044             Ok(ptr.try_into().unwrap())
1045         }
1046     }
1047 
1048     /// Perform the `memory.fill` operation on a locally defined memory.
1049     ///
1050     /// # Errors
1051     ///
1052     /// Returns a `Trap` error if the memory range is out of bounds.
1053     pub(crate) fn memory_fill(
1054         self: Pin<&mut Self>,
1055         memory_index: DefinedMemoryIndex,
1056         dst: u64,
1057         val: u8,
1058         len: u64,
1059     ) -> Result<(), Trap> {
1060         let memory_index = self.env_module().memory_index(memory_index);
1061         let memory = self.get_memory(memory_index);
1062         let dst = self.validate_inbounds(memory.current_length(), dst, len)?;
1063         let len = usize::try_from(len).unwrap();
1064 
1065         // Bounds and casts are checked above, by this point we know that
1066         // everything is safe.
1067         unsafe {
1068             let dst = memory.base.as_ptr().add(dst);
1069             // FIXME audit whether this is safe in the presence of shared memory
1070             // (https://github.com/bytecodealliance/wasmtime/issues/4203).
1071             ptr::write_bytes(dst, val, len);
1072         }
1073 
1074         Ok(())
1075     }
1076 
1077     /// Get the internal storage range of a particular Wasm data segment.
1078     pub(crate) fn wasm_data_range(&self, index: DataIndex) -> Range<u32> {
1079         match self.env_module().passive_data_map.get(&index) {
1080             Some(range) if !self.dropped_data.contains(index) => range.clone(),
1081             _ => 0..0,
1082         }
1083     }
1084 
1085     /// Given an internal storage range of a Wasm data segment (or subset of a
1086     /// Wasm data segment), get the data's raw bytes.
1087     pub(crate) fn wasm_data(&self, range: Range<u32>) -> &[u8] {
1088         let start = usize::try_from(range.start).unwrap();
1089         let end = usize::try_from(range.end).unwrap();
1090         &self.runtime_info.wasm_data()[start..end]
1091     }
1092 
1093     /// Performs the `memory.init` operation.
1094     ///
1095     /// # Errors
1096     ///
1097     /// Returns a `Trap` error if the destination range is out of this module's
1098     /// memory's bounds or if the source range is outside the data segment's
1099     /// bounds.
1100     pub(crate) fn memory_init(
1101         self: Pin<&mut Self>,
1102         memory_index: MemoryIndex,
1103         data_index: DataIndex,
1104         dst: u64,
1105         src: u32,
1106         len: u32,
1107     ) -> Result<(), Trap> {
1108         let range = self.wasm_data_range(data_index);
1109         self.memory_init_segment(memory_index, range, dst, src, len)
1110     }
1111 
1112     pub(crate) fn memory_init_segment(
1113         self: Pin<&mut Self>,
1114         memory_index: MemoryIndex,
1115         range: Range<u32>,
1116         dst: u64,
1117         src: u32,
1118         len: u32,
1119     ) -> Result<(), Trap> {
1120         // https://webassembly.github.io/bulk-memory-operations/core/exec/instructions.html#exec-memory-init
1121 
1122         let memory = self.get_memory(memory_index);
1123         let data = self.wasm_data(range);
1124         let dst = self.validate_inbounds(memory.current_length(), dst, len.into())?;
1125         let src = self.validate_inbounds(data.len(), src.into(), len.into())?;
1126         let len = len as usize;
1127 
1128         unsafe {
1129             let src_start = data.as_ptr().add(src);
1130             let dst_start = memory.base.as_ptr().add(dst);
1131             // FIXME audit whether this is safe in the presence of shared memory
1132             // (https://github.com/bytecodealliance/wasmtime/issues/4203).
1133             ptr::copy_nonoverlapping(src_start, dst_start, len);
1134         }
1135 
1136         Ok(())
1137     }
1138 
1139     /// Drop the given data segment, truncating its length to zero.
1140     pub(crate) fn data_drop(self: Pin<&mut Self>, data_index: DataIndex) {
1141         self.dropped_data_mut().insert(data_index);
1142 
1143         // Note that we don't check that we actually removed a segment because
1144         // dropping a non-passive segment is a no-op (not a trap).
1145     }
1146 
1147     /// Get a table by index regardless of whether it is locally-defined
1148     /// or an imported, foreign table. Ensure that the given range of
1149     /// elements in the table is lazily initialized.  We define this
1150     /// operation all-in-one for safety, to ensure the lazy-init
1151     /// happens.
1152     ///
1153     /// Takes an `Iterator` for the index-range to lazy-initialize,
1154     /// for flexibility. This can be a range, single item, or empty
1155     /// sequence, for example. The iterator should return indices in
1156     /// increasing order, so that the break-at-out-of-bounds behavior
1157     /// works correctly.
1158     pub(crate) fn get_table_with_lazy_init(
1159         self: Pin<&mut Self>,
1160         table_index: TableIndex,
1161         range: impl Iterator<Item = u64>,
1162     ) -> &mut Table {
1163         let (idx, instance) = self.defined_table_index_and_instance(table_index);
1164         instance.get_defined_table_with_lazy_init(idx, range)
1165     }
1166 
1167     /// Gets the raw runtime table data structure owned by this instance
1168     /// given the provided `idx`.
1169     ///
1170     /// The `range` specified is eagerly initialized for funcref tables.
1171     pub fn get_defined_table_with_lazy_init(
1172         mut self: Pin<&mut Self>,
1173         idx: DefinedTableIndex,
1174         range: impl IntoIterator<Item = u64>,
1175     ) -> &mut Table {
1176         let elt_ty = self.tables[idx].1.element_type();
1177 
1178         if elt_ty == TableElementType::Func {
1179             for i in range {
1180                 match self.tables[idx].1.get_func_maybe_init(i) {
1181                     // Uninitialized table element.
1182                     Ok(None) => {}
1183                     // Initialized table element, move on to the next.
1184                     Ok(Some(_)) => continue,
1185                     // Out-of-bounds; caller will handle by likely
1186                     // throwing a trap. No work to do to lazy-init
1187                     // beyond the end.
1188                     Err(_) => break,
1189                 };
1190 
1191                 // The table element `i` is uninitialized and is now being
1192                 // initialized. This must imply that a `precompiled` list of
1193                 // function indices is available for this table. The precompiled
1194                 // list is extracted and then it is consulted with `i` to
1195                 // determine the function that is going to be initialized. Note
1196                 // that `i` may be outside the limits of the static
1197                 // initialization so it's a fallible `get` instead of an index.
1198                 let module = self.env_module();
1199                 let precomputed = match &module.table_initialization.initial_values[idx] {
1200                     TableInitialValue::Null { precomputed } => precomputed,
1201                     TableInitialValue::Expr(_) => unreachable!(),
1202                 };
1203                 // Panicking here helps catch bugs rather than silently truncating by accident.
1204                 let func_index = precomputed.get(usize::try_from(i).unwrap()).cloned();
1205                 let func_ref =
1206                     func_index.and_then(|func_index| self.as_mut().get_func_ref(func_index));
1207                 self.as_mut().tables_mut()[idx]
1208                     .1
1209                     .set_func(i, func_ref)
1210                     .expect("Table type should match and index should be in-bounds");
1211             }
1212         }
1213 
1214         self.get_defined_table(idx)
1215     }
1216 
1217     /// Get a table by index regardless of whether it is locally-defined or an
1218     /// imported, foreign table.
1219     pub(crate) fn get_table(self: Pin<&mut Self>, table_index: TableIndex) -> &mut Table {
1220         let (idx, instance) = self.defined_table_index_and_instance(table_index);
1221         instance.get_defined_table(idx)
1222     }
1223 
1224     /// Get a locally-defined table.
1225     pub(crate) fn get_defined_table(self: Pin<&mut Self>, index: DefinedTableIndex) -> &mut Table {
1226         &mut self.tables_mut()[index].1
1227     }
1228 
1229     pub(crate) fn defined_table_index_and_instance<'a>(
1230         self: Pin<&'a mut Self>,
1231         index: TableIndex,
1232     ) -> (DefinedTableIndex, Pin<&'a mut Instance>) {
1233         if let Some(defined_table_index) = self.env_module().defined_table_index(index) {
1234             (defined_table_index, self)
1235         } else {
1236             let import = self.imported_table(index);
1237             let index = import.index;
1238             let vmctx = import.vmctx.as_non_null();
1239             // SAFETY: the validity of `self` means that the reachable instances
1240             // should also all be owned by the same store and fully initialized,
1241             // so it's safe to laterally move from a mutable borrow of this
1242             // instance to a mutable borrow of a sibling instance.
1243             let foreign_instance = unsafe { self.sibling_vmctx_mut(vmctx) };
1244             (index, foreign_instance)
1245         }
1246     }
1247 
1248     /// Initialize the VMContext data associated with this Instance.
1249     ///
1250     /// The `VMContext` memory is assumed to be uninitialized; any field
1251     /// that we need in a certain state will be explicitly written by this
1252     /// function.
1253     unsafe fn initialize_vmctx(
1254         mut self: Pin<&mut Self>,
1255         module: &Module,
1256         offsets: &VMOffsets<HostPtr>,
1257         store: &StoreOpaque,
1258         imports: Imports,
1259     ) {
1260         assert!(ptr::eq(module, self.env_module().as_ref()));
1261 
1262         // SAFETY: the type of the magic field is indeed `u32` and this function
1263         // is initializing its value.
1264         unsafe {
1265             self.vmctx_plus_offset_raw::<u32>(offsets.ptr.vmctx_magic())
1266                 .write(VMCONTEXT_MAGIC);
1267         }
1268 
1269         // SAFETY: it's up to the caller to provide a valid store pointer here.
1270         unsafe {
1271             self.as_mut().set_store(store);
1272         }
1273 
1274         // Initialize shared types
1275         //
1276         // SAFETY: validity of the vmctx means it should be safe to write to it
1277         // here.
1278         unsafe {
1279             let types = NonNull::from(self.runtime_info.type_ids());
1280             self.type_ids_array().write(types.cast().into());
1281         }
1282 
1283         // Initialize the built-in functions
1284         //
1285         // SAFETY: the type of the builtin functions field is indeed a pointer
1286         // and the pointer being filled in here, plus the vmctx is valid to
1287         // write to during initialization.
1288         unsafe {
1289             static BUILTINS: VMBuiltinFunctionsArray = VMBuiltinFunctionsArray::INIT;
1290             let ptr = BUILTINS.expose_provenance();
1291             self.vmctx_plus_offset_raw(offsets.ptr.vmctx_builtin_functions())
1292                 .write(VmPtr::from(ptr));
1293         }
1294 
1295         // Initialize the imports
1296         //
1297         // SAFETY: the vmctx is safe to initialize during this function and
1298         // validity of each item itself is a contract the caller must uphold.
1299         debug_assert_eq!(imports.functions.len(), module.num_imported_funcs);
1300         unsafe {
1301             ptr::copy_nonoverlapping(
1302                 imports.functions.as_ptr(),
1303                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_functions_begin())
1304                     .as_ptr(),
1305                 imports.functions.len(),
1306             );
1307             debug_assert_eq!(imports.tables.len(), module.num_imported_tables);
1308             ptr::copy_nonoverlapping(
1309                 imports.tables.as_ptr(),
1310                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_tables_begin())
1311                     .as_ptr(),
1312                 imports.tables.len(),
1313             );
1314             debug_assert_eq!(imports.memories.len(), module.num_imported_memories);
1315             ptr::copy_nonoverlapping(
1316                 imports.memories.as_ptr(),
1317                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_memories_begin())
1318                     .as_ptr(),
1319                 imports.memories.len(),
1320             );
1321             debug_assert_eq!(imports.globals.len(), module.num_imported_globals);
1322             ptr::copy_nonoverlapping(
1323                 imports.globals.as_ptr(),
1324                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_globals_begin())
1325                     .as_ptr(),
1326                 imports.globals.len(),
1327             );
1328             debug_assert_eq!(imports.tags.len(), module.num_imported_tags);
1329             ptr::copy_nonoverlapping(
1330                 imports.tags.as_ptr(),
1331                 self.vmctx_plus_offset_raw(offsets.vmctx_imported_tags_begin())
1332                     .as_ptr(),
1333                 imports.tags.len(),
1334             );
1335         }
1336 
1337         // N.B.: there is no need to initialize the funcrefs array because we
1338         // eagerly construct each element in it whenever asked for a reference
1339         // to that element. In other words, there is no state needed to track
1340         // the lazy-init, so we don't need to initialize any state now.
1341 
1342         // Initialize the defined tables
1343         //
1344         // SAFETY: it's safe to initialize these tables during initialization
1345         // here and the various types of pointers and such here should all be
1346         // valid.
1347         unsafe {
1348             let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_tables_begin());
1349             let tables = self.as_mut().tables_mut();
1350             for i in 0..module.num_defined_tables() {
1351                 ptr.write(tables[DefinedTableIndex::new(i)].1.vmtable());
1352                 ptr = ptr.add(1);
1353             }
1354         }
1355 
1356         // Initialize the defined memories. This fills in both the
1357         // `defined_memories` table and the `owned_memories` table at the same
1358         // time. Entries in `defined_memories` hold a pointer to a definition
1359         // (all memories) whereas the `owned_memories` hold the actual
1360         // definitions of memories owned (not shared) in the module.
1361         //
1362         // SAFETY: it's safe to initialize these memories during initialization
1363         // here and the various types of pointers and such here should all be
1364         // valid.
1365         unsafe {
1366             let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_memories_begin());
1367             let mut owned_ptr = self.vmctx_plus_offset_raw(offsets.vmctx_owned_memories_begin());
1368             let memories = self.as_mut().memories_mut();
1369             for i in 0..module.num_defined_memories() {
1370                 let defined_memory_index = DefinedMemoryIndex::new(i);
1371                 let memory_index = module.memory_index(defined_memory_index);
1372                 if module.memories[memory_index].shared {
1373                     let def_ptr = memories[defined_memory_index]
1374                         .1
1375                         .as_shared_memory()
1376                         .unwrap()
1377                         .vmmemory_ptr();
1378                     ptr.write(VmPtr::from(def_ptr));
1379                 } else {
1380                     owned_ptr.write(memories[defined_memory_index].1.vmmemory());
1381                     ptr.write(VmPtr::from(owned_ptr));
1382                     owned_ptr = owned_ptr.add(1);
1383                 }
1384                 ptr = ptr.add(1);
1385             }
1386         }
1387 
1388         // Zero-initialize the globals so that nothing is uninitialized memory
1389         // after this function returns. The globals are actually initialized
1390         // with their const expression initializers after the instance is fully
1391         // allocated.
1392         //
1393         // SAFETY: it's safe to initialize globals during initialization
1394         // here. Note that while the value being written is not valid for all
1395         // types of globals it's initializing the memory to zero instead of
1396         // being in an undefined state. So it's still unsafe to access globals
1397         // after this, but if it's read then it'd hopefully crash faster than
1398         // leaving this undefined.
1399         unsafe {
1400             for (index, _init) in module.global_initializers.iter() {
1401                 self.global_ptr(index).write(VMGlobalDefinition::new());
1402             }
1403         }
1404 
1405         // Initialize the defined tags
1406         //
1407         // SAFETY: it's safe to initialize these tags during initialization
1408         // here and the various types of pointers and such here should all be
1409         // valid.
1410         unsafe {
1411             let mut ptr = self.vmctx_plus_offset_raw(offsets.vmctx_tags_begin());
1412             for i in 0..module.num_defined_tags() {
1413                 let defined_index = DefinedTagIndex::new(i);
1414                 let tag_index = module.tag_index(defined_index);
1415                 let tag = module.tags[tag_index];
1416                 ptr.write(VMTagDefinition::new(
1417                     tag.signature.unwrap_engine_type_index(),
1418                 ));
1419                 ptr = ptr.add(1);
1420             }
1421         }
1422     }
1423 
1424     /// Attempts to convert from the host `addr` specified to a WebAssembly
1425     /// based address recorded in `WasmFault`.
1426     ///
1427     /// This method will check all linear memories that this instance contains
1428     /// to see if any of them contain `addr`. If one does then `Some` is
1429     /// returned with metadata about the wasm fault. Otherwise `None` is
1430     /// returned and `addr` doesn't belong to this instance.
1431     pub fn wasm_fault(&self, addr: usize) -> Option<WasmFault> {
1432         let mut fault = None;
1433         for (_, (_, memory)) in self.memories.iter() {
1434             let accessible = memory.wasm_accessible();
1435             if accessible.start <= addr && addr < accessible.end {
1436                 // All linear memories should be disjoint so assert that no
1437                 // prior fault has been found.
1438                 assert!(fault.is_none());
1439                 fault = Some(WasmFault {
1440                     memory_size: memory.byte_size(),
1441                     wasm_address: u64::try_from(addr - accessible.start).unwrap(),
1442                 });
1443             }
1444         }
1445         fault
1446     }
1447 
1448     /// Returns the id, within this instance's store, that it's assigned.
1449     pub fn id(&self) -> InstanceId {
1450         self.id
1451     }
1452 
1453     /// Get all memories within this instance.
1454     ///
1455     /// Returns both import and defined memories.
1456     ///
1457     /// Returns both exported and non-exported memories.
1458     ///
1459     /// Gives access to the full memories space.
1460     pub fn all_memories(
1461         &self,
1462         store: StoreId,
1463     ) -> impl ExactSizeIterator<Item = (MemoryIndex, crate::Memory)> + '_ {
1464         self.env_module()
1465             .memories
1466             .iter()
1467             .map(move |(i, _)| (i, self.get_exported_memory(store, i)))
1468     }
1469 
1470     /// Return the memories defined in this instance (not imported).
1471     pub fn defined_memories<'a>(
1472         &'a self,
1473         store: StoreId,
1474     ) -> impl ExactSizeIterator<Item = crate::Memory> + 'a {
1475         let num_imported = self.env_module().num_imported_memories;
1476         self.all_memories(store)
1477             .skip(num_imported)
1478             .map(|(_i, memory)| memory)
1479     }
1480 
1481     /// Lookup an item with the given index.
1482     ///
1483     /// # Panics
1484     ///
1485     /// Panics if `export` is not valid for this instance.
1486     ///
1487     /// # Safety
1488     ///
1489     /// This function requires that `store` is the correct store which owns this
1490     /// instance.
1491     pub unsafe fn get_export_by_index_mut(
1492         self: Pin<&mut Self>,
1493         store: StoreId,
1494         export: EntityIndex,
1495     ) -> Export {
1496         match export {
1497             // SAFETY: the contract of `store` owning the this instance is a
1498             // safety requirement of this function itself.
1499             EntityIndex::Function(i) => {
1500                 Export::Function(unsafe { self.get_exported_func(store, i) })
1501             }
1502             EntityIndex::Global(i) => Export::Global(self.get_exported_global(store, i)),
1503             EntityIndex::Table(i) => Export::Table(self.get_exported_table(store, i)),
1504             EntityIndex::Memory(i) => Export::Memory {
1505                 memory: self.get_exported_memory(store, i),
1506                 shared: self.env_module().memories[i].shared,
1507             },
1508             EntityIndex::Tag(i) => Export::Tag(self.get_exported_tag(store, i)),
1509         }
1510     }
1511 
1512     fn store_mut(self: Pin<&mut Self>) -> &mut Option<VMStoreRawPtr> {
1513         // SAFETY: this is a pin-projection to get a mutable reference to an
1514         // internal field and is safe so long as the `&mut Self` temporarily
1515         // created is not overwritten, which it isn't here.
1516         unsafe { &mut self.get_unchecked_mut().store }
1517     }
1518 
1519     fn dropped_elements_mut(self: Pin<&mut Self>) -> &mut EntitySet<ElemIndex> {
1520         // SAFETY: see `store_mut` above.
1521         unsafe { &mut self.get_unchecked_mut().dropped_elements }
1522     }
1523 
1524     fn dropped_data_mut(self: Pin<&mut Self>) -> &mut EntitySet<DataIndex> {
1525         // SAFETY: see `store_mut` above.
1526         unsafe { &mut self.get_unchecked_mut().dropped_data }
1527     }
1528 
1529     fn memories_mut(
1530         self: Pin<&mut Self>,
1531     ) -> &mut PrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)> {
1532         // SAFETY: see `store_mut` above.
1533         unsafe { &mut self.get_unchecked_mut().memories }
1534     }
1535 
1536     pub(crate) fn tables_mut(
1537         self: Pin<&mut Self>,
1538     ) -> &mut PrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)> {
1539         // SAFETY: see `store_mut` above.
1540         unsafe { &mut self.get_unchecked_mut().tables }
1541     }
1542 
1543     #[cfg(feature = "wmemcheck")]
1544     pub(super) fn wmemcheck_state_mut(self: Pin<&mut Self>) -> &mut Option<Wmemcheck> {
1545         // SAFETY: see `store_mut` above.
1546         unsafe { &mut self.get_unchecked_mut().wmemcheck_state }
1547     }
1548 }
1549 
1550 // SAFETY: `layout` should describe this accurately and `OwnedVMContext` is the
1551 // last field of `ComponentInstance`.
1552 unsafe impl InstanceLayout for Instance {
1553     const INIT_ZEROED: bool = false;
1554     type VMContext = VMContext;
1555 
1556     fn layout(&self) -> Layout {
1557         Self::alloc_layout(self.runtime_info.offsets())
1558     }
1559 
1560     fn owned_vmctx(&self) -> &OwnedVMContext<VMContext> {
1561         &self.vmctx
1562     }
1563 
1564     fn owned_vmctx_mut(&mut self) -> &mut OwnedVMContext<VMContext> {
1565         &mut self.vmctx
1566     }
1567 }
1568 
1569 pub type InstanceHandle = OwnedInstance<Instance>;
1570 
1571 /// A handle holding an `Instance` of a WebAssembly module.
1572 ///
1573 /// This structure is an owning handle of the `instance` contained internally.
1574 /// When this value goes out of scope it will deallocate the `Instance` and all
1575 /// memory associated with it.
1576 ///
1577 /// Note that this lives within a `StoreOpaque` on a list of instances that a
1578 /// store is keeping alive.
1579 #[derive(Debug)]
1580 #[repr(transparent)] // guarantee this is a zero-cost wrapper
1581 pub struct OwnedInstance<T: InstanceLayout> {
1582     /// The raw pointer to the instance that was allocated.
1583     ///
1584     /// Note that this is not equivalent to `Box<Instance>` because the
1585     /// allocation here has a `VMContext` trailing after it. Thus the custom
1586     /// destructor to invoke the `dealloc` function with the appropriate
1587     /// layout.
1588     instance: SendSyncPtr<T>,
1589     _marker: marker::PhantomData<Box<(T, OwnedVMContext<T::VMContext>)>>,
1590 }
1591 
1592 /// Structure that must be placed at the end of a type implementing
1593 /// `InstanceLayout`.
1594 #[repr(align(16))] // match the alignment of VMContext
1595 pub struct OwnedVMContext<T> {
1596     /// A pointer to the `vmctx` field at the end of the `structure`.
1597     ///
1598     /// If you're looking at this a reasonable question would be "why do we need
1599     /// a pointer to ourselves?" because after all the pointer's value is
1600     /// trivially derivable from any `&Instance` pointer. The rationale for this
1601     /// field's existence is subtle, but it's required for correctness. The
1602     /// short version is "this makes miri happy".
1603     ///
1604     /// The long version of why this field exists is that the rules that MIRI
1605     /// uses to ensure pointers are used correctly have various conditions on
1606     /// them depend on how pointers are used. More specifically if `*mut T` is
1607     /// derived from `&mut T`, then that invalidates all prior pointers drived
1608     /// from the `&mut T`. This means that while we liberally want to re-acquire
1609     /// a `*mut VMContext` throughout the implementation of `Instance` the
1610     /// trivial way, a function `fn vmctx(Pin<&mut Instance>) -> *mut VMContext`
1611     /// would effectively invalidate all prior `*mut VMContext` pointers
1612     /// acquired. The purpose of this field is to serve as a sort of
1613     /// source-of-truth for where `*mut VMContext` pointers come from.
1614     ///
1615     /// This field is initialized when the `Instance` is created with the
1616     /// original allocation's pointer. That means that the provenance of this
1617     /// pointer contains the entire allocation (both instance and `VMContext`).
1618     /// This provenance bit is then "carried through" where `fn vmctx` will base
1619     /// all returned pointers on this pointer itself. This provides the means of
1620     /// never invalidating this pointer throughout MIRI and additionally being
1621     /// able to still temporarily have `Pin<&mut Instance>` methods and such.
1622     ///
1623     /// It's important to note, though, that this is not here purely for MIRI.
1624     /// The careful construction of the `fn vmctx` method has ramifications on
1625     /// the LLVM IR generated, for example. A historical CVE on Wasmtime,
1626     /// GHSA-ch89-5g45-qwc7, was caused due to relying on undefined behavior. By
1627     /// deriving VMContext pointers from this pointer it specifically hints to
1628     /// LLVM that trickery is afoot and it properly informs `noalias` and such
1629     /// annotations and analysis. More-or-less this pointer is actually loaded
1630     /// in LLVM IR which helps defeat otherwise present aliasing optimizations,
1631     /// which we want, since writes to this should basically never be optimized
1632     /// out.
1633     ///
1634     /// As a final note it's worth pointing out that the machine code generated
1635     /// for accessing `fn vmctx` is still as one would expect. This member isn't
1636     /// actually ever loaded at runtime (or at least shouldn't be). Perhaps in
1637     /// the future if the memory consumption of this field is a problem we could
1638     /// shrink it slightly, but for now one extra pointer per wasm instance
1639     /// seems not too bad.
1640     vmctx_self_reference: SendSyncPtr<T>,
1641 
1642     /// This field ensures that going from `Pin<&mut T>` to `&mut T` is not a
1643     /// safe operation.
1644     _marker: core::marker::PhantomPinned,
1645 }
1646 
1647 impl<T> OwnedVMContext<T> {
1648     /// Creates a new blank vmctx to place at the end of an instance.
1649     pub fn new() -> OwnedVMContext<T> {
1650         OwnedVMContext {
1651             vmctx_self_reference: SendSyncPtr::new(NonNull::dangling()),
1652             _marker: core::marker::PhantomPinned,
1653         }
1654     }
1655 }
1656 
1657 /// Helper trait to plumb both core instances and component instances into
1658 /// `OwnedInstance` below.
1659 ///
1660 /// # Safety
1661 ///
1662 /// This trait requires `layout` to correctly describe `Self` and appropriately
1663 /// allocate space for `Self::VMContext` afterwards. Additionally the field
1664 /// returned by `owned_vmctx()` must be the last field in the structure.
1665 pub unsafe trait InstanceLayout {
1666     /// Whether or not to allocate this instance with `alloc_zeroed` or `alloc`.
1667     const INIT_ZEROED: bool;
1668 
1669     /// The trailing `VMContext` type at the end of this instance.
1670     type VMContext;
1671 
1672     /// The memory layout to use to allocate and deallocate this instance.
1673     fn layout(&self) -> Layout;
1674 
1675     fn owned_vmctx(&self) -> &OwnedVMContext<Self::VMContext>;
1676     fn owned_vmctx_mut(&mut self) -> &mut OwnedVMContext<Self::VMContext>;
1677 
1678     /// Returns the `vmctx_self_reference` set above.
1679     #[inline]
1680     fn vmctx(&self) -> NonNull<Self::VMContext> {
1681         // The definition of this method is subtle but intentional. The goal
1682         // here is that effectively this should return `&mut self.vmctx`, but
1683         // it's not quite so simple. Some more documentation is available on the
1684         // `vmctx_self_reference` field, but the general idea is that we're
1685         // creating a pointer to return with proper provenance. Provenance is
1686         // still in the works in Rust at the time of this writing but the load
1687         // of the `self.vmctx_self_reference` field is important here as it
1688         // affects how LLVM thinks about aliasing with respect to the returned
1689         // pointer.
1690         //
1691         // The intention of this method is to codegen to machine code as `&mut
1692         // self.vmctx`, however. While it doesn't show up like this in LLVM IR
1693         // (there's an actual load of the field) it does look like that by the
1694         // time the backend runs. (that's magic to me, the backend removing
1695         // loads...)
1696         let owned_vmctx = self.owned_vmctx();
1697         let owned_vmctx_raw = NonNull::from(owned_vmctx);
1698         // SAFETY: it's part of the contract of `InstanceLayout` and the usage
1699         // with `OwnedInstance` that this indeed points to the vmctx.
1700         let addr = unsafe { owned_vmctx_raw.add(1) };
1701         owned_vmctx
1702             .vmctx_self_reference
1703             .as_non_null()
1704             .with_addr(addr.addr())
1705     }
1706 
1707     /// Helper function to access various locations offset from our `*mut
1708     /// VMContext` object.
1709     ///
1710     /// Note that this method takes `&self` as an argument but returns
1711     /// `NonNull<T>` which is frequently used to mutate said memory. This is an
1712     /// intentional design decision where the safety of the modification of
1713     /// memory is placed as a burden onto the caller. The implementation of this
1714     /// method explicitly does not require `&mut self` to acquire mutable
1715     /// provenance to update the `VMContext` region. Instead all pointers into
1716     /// the `VMContext` area have provenance/permissions to write.
1717     ///
1718     /// Also note though that care must be taken to ensure that reads/writes of
1719     /// memory must only happen where appropriate, for example a non-atomic
1720     /// write (as most are) should never happen concurrently with another read
1721     /// or write. It's generally on the burden of the caller to adhere to this.
1722     ///
1723     /// Also of note is that most of the time the usage of this method falls
1724     /// into one of:
1725     ///
1726     /// * Something in the VMContext is being read or written. In that case use
1727     ///   `vmctx_plus_offset` or `vmctx_plus_offset_mut` if possible due to
1728     ///   that having a safer lifetime.
1729     ///
1730     /// * A pointer is being created to pass to other VM* data structures. In
1731     ///   that situation the lifetime of all VM data structures are typically
1732     ///   tied to the `Store<T>` which is what provides the guarantees around
1733     ///   concurrency/etc.
1734     ///
1735     /// There's quite a lot of unsafety riding on this method, especially
1736     /// related to the ascription `T` of the byte `offset`. It's hoped that in
1737     /// the future we're able to settle on an in theory safer design.
1738     ///
1739     /// # Safety
1740     ///
1741     /// This method is unsafe because the `offset` must be within bounds of the
1742     /// `VMContext` object trailing this instance. Additionally `T` must be a
1743     /// valid ascription of the value that resides at that location.
1744     unsafe fn vmctx_plus_offset_raw<T: VmSafe>(&self, offset: impl Into<u32>) -> NonNull<T> {
1745         // SAFETY: the safety requirements of `byte_add` are forwarded to this
1746         // method's caller.
1747         unsafe {
1748             self.vmctx()
1749                 .byte_add(usize::try_from(offset.into()).unwrap())
1750                 .cast()
1751         }
1752     }
1753 
1754     /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of
1755     /// `&self` to the returned reference `&T`.
1756     ///
1757     /// # Safety
1758     ///
1759     /// See the safety documentation of `vmctx_plus_offset_raw`.
1760     unsafe fn vmctx_plus_offset<T: VmSafe>(&self, offset: impl Into<u32>) -> &T {
1761         // SAFETY: this method has the same safety requirements as
1762         // `vmctx_plus_offset_raw`.
1763         unsafe { self.vmctx_plus_offset_raw(offset).as_ref() }
1764     }
1765 
1766     /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of
1767     /// `&mut self` to the returned reference `&mut T`.
1768     ///
1769     /// # Safety
1770     ///
1771     /// See the safety documentation of `vmctx_plus_offset_raw`.
1772     unsafe fn vmctx_plus_offset_mut<T: VmSafe>(
1773         self: Pin<&mut Self>,
1774         offset: impl Into<u32>,
1775     ) -> &mut T {
1776         // SAFETY: this method has the same safety requirements as
1777         // `vmctx_plus_offset_raw`.
1778         unsafe { self.vmctx_plus_offset_raw(offset).as_mut() }
1779     }
1780 }
1781 
1782 impl<T: InstanceLayout> OwnedInstance<T> {
1783     /// Allocates a new `OwnedInstance` and places `instance` inside of it.
1784     ///
1785     /// This will `instance`
1786     pub(super) fn new(mut instance: T) -> OwnedInstance<T> {
1787         let layout = instance.layout();
1788         debug_assert!(layout.size() >= size_of_val(&instance));
1789         debug_assert!(layout.align() >= align_of_val(&instance));
1790 
1791         // SAFETY: it's up to us to assert that `layout` has a non-zero size,
1792         // which is asserted here.
1793         let ptr = unsafe {
1794             assert!(layout.size() > 0);
1795             if T::INIT_ZEROED {
1796                 alloc::alloc::alloc_zeroed(layout)
1797             } else {
1798                 alloc::alloc::alloc(layout)
1799             }
1800         };
1801         if ptr.is_null() {
1802             alloc::alloc::handle_alloc_error(layout);
1803         }
1804         let instance_ptr = NonNull::new(ptr.cast::<T>()).unwrap();
1805 
1806         // SAFETY: it's part of the unsafe contract of `InstanceLayout` that the
1807         // `add` here is appropriate for the layout allocated.
1808         let vmctx_self_reference = unsafe { instance_ptr.add(1).cast() };
1809         instance.owned_vmctx_mut().vmctx_self_reference = vmctx_self_reference.into();
1810 
1811         // SAFETY: we allocated above and it's an unsafe contract of
1812         // `InstanceLayout` that the layout is suitable for writing the
1813         // instance.
1814         unsafe {
1815             instance_ptr.write(instance);
1816         }
1817 
1818         let ret = OwnedInstance {
1819             instance: SendSyncPtr::new(instance_ptr),
1820             _marker: marker::PhantomData,
1821         };
1822 
1823         // Double-check various vmctx calculations are correct.
1824         debug_assert_eq!(
1825             vmctx_self_reference.addr(),
1826             // SAFETY: `InstanceLayout` should guarantee it's safe to add 1 to
1827             // the last field to get a pointer to 1-byte-past-the-end of an
1828             // object, which should be valid.
1829             unsafe { NonNull::from(ret.get().owned_vmctx()).add(1).addr() }
1830         );
1831         debug_assert_eq!(vmctx_self_reference.addr(), ret.get().vmctx().addr());
1832 
1833         ret
1834     }
1835 
1836     /// Gets the raw underlying `&Instance` from this handle.
1837     pub fn get(&self) -> &T {
1838         // SAFETY: this is an owned instance handle that retains exclusive
1839         // ownership of the `Instance` inside. With `&self` given we know
1840         // this pointer is valid valid and the returned lifetime is connected
1841         // to `self` so that should also be valid.
1842         unsafe { self.instance.as_non_null().as_ref() }
1843     }
1844 
1845     /// Same as [`Self::get`] except for mutability.
1846     pub fn get_mut(&mut self) -> Pin<&mut T> {
1847         // SAFETY: The lifetime concerns here are the same as `get` above.
1848         // Otherwise `new_unchecked` is used here to uphold the contract that
1849         // instances are always pinned in memory.
1850         unsafe { Pin::new_unchecked(self.instance.as_non_null().as_mut()) }
1851     }
1852 }
1853 
1854 impl<T: InstanceLayout> Drop for OwnedInstance<T> {
1855     fn drop(&mut self) {
1856         unsafe {
1857             let layout = self.get().layout();
1858             ptr::drop_in_place(self.instance.as_ptr());
1859             alloc::alloc::dealloc(self.instance.as_ptr().cast(), layout);
1860         }
1861     }
1862 }
1863