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