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