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