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