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