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