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