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