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