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