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