wasmtime/runtime/vm/instance.rs
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
5use crate::code::ModuleWithCode;
6use crate::module::ModuleRegistry;
7use crate::prelude::*;
8use crate::runtime::vm::export::{Export, ExportMemory};
9use crate::runtime::vm::memory::{Memory, RuntimeMemoryCreator};
10use crate::runtime::vm::table::{Table, TableElementType};
11use crate::runtime::vm::vmcontext::{
12 VMBuiltinFunctionsArray, VMContext, VMFuncRef, VMFunctionImport, VMGlobalDefinition,
13 VMGlobalImport, VMMemoryDefinition, VMMemoryImport, VMOpaqueContext, VMStoreContext,
14 VMTableDefinition, VMTableImport, VMTagDefinition, VMTagImport,
15};
16use crate::runtime::vm::{
17 GcStore, HostResult, Imports, ModuleRuntimeInfo, SendSyncPtr, UncaughtException, VMGcRef,
18 VMGlobalKind, VMStore, VMStoreRawPtr, VmPtr, VmSafe, WasmFault, catch_unwind_and_record_trap,
19};
20use crate::store::{InstanceId, StoreId, StoreInstanceId, StoreOpaque, StoreResourceLimiter};
21use crate::vm::{VMWasmCallFunction, ValRaw};
22use alloc::sync::Arc;
23use core::alloc::Layout;
24use core::marker;
25use core::ops::Range;
26use core::pin::Pin;
27use core::ptr::NonNull;
28#[cfg(target_has_atomic = "64")]
29use core::sync::atomic::AtomicU64;
30use core::{mem, ptr};
31#[cfg(feature = "gc")]
32use wasmtime_environ::ModuleInternedTypeIndex;
33use wasmtime_environ::error::OutOfMemory;
34use wasmtime_environ::{
35 Abi, DefinedFuncIndex, DefinedGlobalIndex, DefinedMemoryIndex, DefinedTableIndex,
36 DefinedTagIndex, EntityIndex, EntityRef, FuncIndex, FuncKey, GlobalConstValue, GlobalIndex,
37 HostPtr, MemoryIndex, MemoryInitialization, ModuleStartup, PassiveElemIndex, PtrSize,
38 RuntimeDataIndex, TableIndex, TagIndex, VMCONTEXT_MAGIC, VMOffsets, VMSharedTypeIndex,
39 WasmRefType, packed_option::ReservedValue,
40};
41#[cfg(feature = "wmemcheck")]
42use wasmtime_wmemcheck::Wmemcheck;
43
44mod allocator;
45pub use allocator::*;
46
47/// A type that roughly corresponds to a WebAssembly instance, but is also used
48/// for host-defined objects.
49///
50/// Instances here can correspond to actual instantiated modules, but it's also
51/// used ubiquitously for host-defined objects. For example creating a
52/// host-defined memory will have a `module` that looks like it exports a single
53/// memory (and similar for other constructs).
54///
55/// This `Instance` type is used as a ubiquitous representation for WebAssembly
56/// values, whether or not they were created on the host or through a module.
57///
58/// # Ownership
59///
60/// This structure is never allocated directly but is instead managed through
61/// an `InstanceHandle`. This structure ends with a `VMContext` which has a
62/// dynamic size corresponding to the `module` configured within. Memory
63/// management of this structure is always done through `InstanceHandle` as the
64/// sole owner of an instance.
65///
66/// # `Instance` and `Pin`
67///
68/// Given an instance it is accompanied with trailing memory for the
69/// appropriate `VMContext`. The `Instance` also holds `runtime_info` and other
70/// information pointing to relevant offsets for the `VMContext`. Thus it is
71/// not sound to mutate `runtime_info` after an instance is created. More
72/// generally it's also not safe to "swap" instances, for example given two
73/// `&mut Instance` values it's not sound to swap them as then the `VMContext`
74/// values are inaccurately described.
75///
76/// To encapsulate this guarantee this type is only ever mutated through Rust's
77/// `Pin` type. All mutable methods here take `self: Pin<&mut Self>` which
78/// statically disallows safe access to `&mut Instance`. There are assorted
79/// "projection methods" to go from `Pin<&mut Instance>` to `&mut T` for
80/// individual fields, for example `memories_mut`. More methods can be added as
81/// necessary or methods may also be added to project multiple fields at a time
82/// if necessary to. The precise ergonomics around getting mutable access to
83/// some fields (but notably not `runtime_info`) is probably going to evolve
84/// over time.
85///
86/// Note that is is not sound to basically ever pass around `&mut Instance`.
87/// That should always instead be `Pin<&mut Instance>`. All usage of
88/// `Pin::new_unchecked` should be here in this module in just a few `unsafe`
89/// locations and it's recommended to use existing helpers if you can.
90#[repr(C)] // ensure that the vmctx field is last.
91pub struct Instance {
92 /// The index, within a `Store` that this instance lives at
93 id: InstanceId,
94
95 /// The runtime info (corresponding to the "compiled module"
96 /// abstraction in higher layers) that is retained and needed for
97 /// lazy initialization. This provides access to the underlying
98 /// Wasm module entities, the compiled JIT code, metadata about
99 /// functions, lazy initialization state, etc.
100 //
101 // SAFETY: this field cannot be overwritten after an instance is created. It
102 // must contain this exact same value for the entire lifetime of this
103 // instance. This enables borrowing the info's `Module` and this instance at
104 // the same time (instance mutably, module not). Additionally it enables
105 // borrowing a store mutably at the same time as a contained instance.
106 runtime_info: ModuleRuntimeInfo,
107
108 /// WebAssembly linear memory data.
109 ///
110 /// This is where all runtime information about defined linear memories in
111 /// this module lives.
112 ///
113 /// The `MemoryAllocationIndex` was given from our `InstanceAllocator` and
114 /// must be given back to the instance allocator when deallocating each
115 /// memory.
116 memories: TryPrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)>,
117
118 /// WebAssembly table data.
119 ///
120 /// Like memories, this is only for defined tables in the module and
121 /// contains all of their runtime state.
122 ///
123 /// The `TableAllocationIndex` was given from our `InstanceAllocator` and
124 /// must be given back to the instance allocator when deallocating each
125 /// table.
126 tables: TryPrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)>,
127
128 /// Evaluated passive element segments.
129 ///
130 /// If an entry is none, then it has been dropped.
131 //
132 // TODO(#12621): This should be a `TrySecondaryMap<PassiveElemIndex, _>`
133 // but that type is currently footgun-y / isn't actually OOM-safe yet.
134 passive_elements: TryVec<PassiveElementSegment>,
135
136 // TODO: add support for multiple memories; `wmemcheck_state` corresponds to
137 // memory 0.
138 #[cfg(feature = "wmemcheck")]
139 pub(crate) wmemcheck_state: Option<Wmemcheck>,
140
141 /// Self-pointer back to `Store<T>` and its functions. Not present for
142 /// the brief time that `Store<T>` is itself being created. Also not
143 /// present for some niche uses that are disconnected from stores (e.g.
144 /// cross-thread stuff used in `InstancePre`)
145 store: Option<VMStoreRawPtr>,
146
147 /// Additional context used by compiled wasm code. This field is last, and
148 /// represents a dynamically-sized array that extends beyond the nominal
149 /// end of the struct (similar to a flexible array member).
150 vmctx: OwnedVMContext<VMContext>,
151}
152
153impl Instance {
154 /// Creates a new owned instance handle from `req`.
155 ///
156 /// The runtime memory/table data structures must have been previously
157 /// allocated and are present within `memories` and `tables`. These values
158 /// are `mem::take`n upon allocation success of an instance, and if the
159 /// instance allocation fails then these are otherwise left in place. This
160 /// enable the pooling allocator to run custom deallocation code for them,
161 /// for example.
162 ///
163 /// # Safety
164 ///
165 /// The `req.imports` field must be appropriately sized/typed for the module
166 /// being allocated according to `req.runtime_info`. Additionally `memories`
167 /// and `tables` must have been allocated for `req.store`.
168 unsafe fn new(
169 req: InstanceAllocationRequest,
170 memories: &mut TryPrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)>,
171 tables: &mut TryPrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)>,
172 ) -> Result<InstanceHandle, OutOfMemory> {
173 let module = req.runtime_info.env_module();
174 let memory_tys = &module.memories;
175 let mut passive_elements = TryVec::with_capacity(module.passive_elements.len())?;
176
177 #[cfg(feature = "wmemcheck")]
178 let wmemcheck_state = if req.store.engine().config().wmemcheck {
179 let size = memory_tys
180 .iter()
181 .next()
182 .map(|memory| memory.1.limits.min)
183 .unwrap_or(0)
184 * 64
185 * 1024;
186 Some(Wmemcheck::new(size.try_into().unwrap()))
187 } else {
188 None
189 };
190 #[cfg(not(feature = "wmemcheck"))]
191 let _ = memory_tys;
192
193 for (_, (ty, len)) in req.runtime_info.env_module().passive_elements.iter() {
194 let len = usize::try_from(*len).unwrap();
195 passive_elements.push(PassiveElementSegment::new(*ty, len)?)?;
196 }
197
198 // Allocate the instance and its `VMContext` with empty memory and table
199 // maps. This is the final fallible allocation in this function; only
200 // after it succeeds do we transfer ownership of the pool-allocated
201 // `memories`/`tables` into the instance (below), so that a failure here
202 // leaves them in the caller's deallocation guard to be freed.
203 let mut ret = OwnedInstance::new(Instance {
204 id: req.id,
205 runtime_info: req.runtime_info.clone(),
206 memories: TryPrimaryMap::default(),
207 tables: TryPrimaryMap::default(),
208 passive_elements,
209 #[cfg(feature = "wmemcheck")]
210 wmemcheck_state,
211 store: None,
212 vmctx: OwnedVMContext::new(),
213 })?;
214
215 // Can't fail any more, so transfer ownership of `memories` and `tables`
216 // to this instance.
217 *ret.get_mut().memories_mut() = mem::take(memories);
218 *ret.get_mut().tables_mut() = mem::take(tables);
219
220 // SAFETY: this vmctx was allocated with the same layout above, so it
221 // should be safe to initialize with the same values here.
222 unsafe {
223 ret.get_mut().initialize_vmctx(req.store, req.imports);
224 }
225
226 Ok(ret)
227 }
228
229 /// Trace element segment GC roots inside this `Instance`.
230 ///
231 /// # Safety
232 ///
233 /// This instance must live for the duration of the associated GC cycle.
234 #[cfg(feature = "gc")]
235 pub(crate) unsafe fn trace_element_segment_roots(
236 self: Pin<&mut Self>,
237 gc_roots: &mut crate::vm::GcRootsList,
238 ) {
239 for segment in self.passive_elements_mut().iter_mut() {
240 if segment.needs_gc_rooting {
241 for e in segment.elements_mut() {
242 if e.get_vmgcref().is_none() {
243 continue;
244 }
245
246 let root: SendSyncPtr<ValRaw> = e.into();
247
248 // Safety: We know this is a type that needs GC rooting and
249 // the lifetime is implied by our safety contract.
250 unsafe {
251 gc_roots.add_val_raw_root(root, "passive element segment");
252 }
253 }
254 }
255 }
256 }
257
258 /// Converts a raw `VMContext` pointer into a raw `Instance` pointer.
259 ///
260 /// # Safety
261 ///
262 /// Calling this function safely requires that `vmctx` is a valid allocation
263 /// of a `VMContext` which is derived from `Instance::new`. To safely
264 /// convert the returned raw pointer into a safe instance pointer callers
265 /// will also want to uphold guarantees such as:
266 ///
267 /// * The instance should not be in use elsewhere. For example you can't
268 /// call this function twice, turn both raw pointers into safe pointers,
269 /// and then use both safe pointers.
270 /// * There should be no other active mutable borrow to any other instance
271 /// within the same store. Note that this is not restricted to just this
272 /// instance pointer, but to all instances in a store. Instances can
273 /// safely traverse to other instances "laterally" meaning that a mutable
274 /// borrow on one is a mutable borrow on all.
275 /// * There should be no active mutable borrow on the store accessible at
276 /// the same time the instance is turned. Instances are owned by a store
277 /// and a store can be used to acquire a safe instance borrow at any time.
278 /// * The lifetime of the usage of the instance should not be unnecessarily
279 /// long, for example it cannot be `'static`.
280 ///
281 /// Other entrypoints exist for converting from a raw `VMContext` to a safe
282 /// pointer such as:
283 ///
284 /// * `Instance::enter_host_from_wasm`
285 /// * `Instance::sibling_vmctx{,_mut}`
286 ///
287 /// These place further restrictions on the API signature to satisfy some of
288 /// the above points.
289 #[inline]
290 pub(crate) unsafe fn from_vmctx(vmctx: NonNull<VMContext>) -> NonNull<Instance> {
291 // SAFETY: The validity of `byte_sub` relies on `vmctx` being a valid
292 // allocation.
293 unsafe {
294 vmctx
295 .byte_sub(mem::size_of::<Instance>())
296 .cast::<Instance>()
297 }
298 }
299
300 /// Encapsulated entrypoint to the host from WebAssembly, converting a raw
301 /// `VMContext` pointer into a `VMStore` plus an `InstanceId`.
302 ///
303 /// This is an entrypoint for core wasm entering back into the host. This is
304 /// used for both host functions and libcalls for example. This will execute
305 /// the closure `f` with safer Internal types than a raw `VMContext`
306 /// pointer.
307 ///
308 /// The closure `f` will have its errors caught, handled, and translated to
309 /// an ABI-safe return value to give back to wasm. This includes both normal
310 /// errors such as traps as well as panics.
311 ///
312 /// # Safety
313 ///
314 /// Callers must ensure that `vmctx` is a valid allocation and is safe to
315 /// dereference at this time. That's generally only true when it's a
316 /// wasm-provided value and this is the first function called after entering
317 /// the host. Otherwise this could unsafely alias the store with a mutable
318 /// pointer, for example.
319 #[inline]
320 pub(crate) unsafe fn enter_host_from_wasm<R>(
321 vmctx: NonNull<VMContext>,
322 f: impl FnOnce(&mut dyn VMStore, InstanceId) -> R,
323 ) -> R::Abi
324 where
325 R: HostResult,
326 {
327 // SAFETY: It's a contract of this function that `vmctx` is a valid
328 // pointer with neither the store nor other instances actively in use
329 // when this is called, so it should be safe to acquire a mutable
330 // pointer to the store and read the instance pointer.
331 let (store, instance) = unsafe {
332 let instance = Instance::from_vmctx(vmctx);
333 let instance = instance.as_ref();
334 let store = &mut *instance.store.unwrap().0.as_ptr();
335 (store, instance.id)
336 };
337
338 // Thread the `store` and `instance` through panic/trap infrastructure
339 // back into `f`.
340 catch_unwind_and_record_trap(store, UncaughtException::Propagate, |store| {
341 f(store, instance)
342 })
343 }
344
345 /// Converts the provided `*mut VMContext` to an `Instance` pointer and
346 /// returns it with the same lifetime as `self`.
347 ///
348 /// This function can be used when traversing a `VMContext` to reach into
349 /// the context needed for imports, optionally.
350 ///
351 /// # Safety
352 ///
353 /// This function requires that the `vmctx` pointer is indeed valid and
354 /// from the store that `self` belongs to.
355 #[inline]
356 unsafe fn sibling_vmctx<'a>(&'a self, vmctx: NonNull<VMContext>) -> &'a Instance {
357 // SAFETY: it's a contract of this function itself that `vmctx` is a
358 // valid pointer. Additionally with `self` being a
359 let ptr = unsafe { Instance::from_vmctx(vmctx) };
360 // SAFETY: it's a contract of this function itself that `vmctx` is a
361 // valid pointer to dereference. Additionally the lifetime of the return
362 // value is constrained to be the same as `self` to avoid granting a
363 // too-long lifetime.
364 unsafe { ptr.as_ref() }
365 }
366
367 /// Same as [`Self::sibling_vmctx`], but the mutable version.
368 ///
369 /// # Safety
370 ///
371 /// This function requires that the `vmctx` pointer is indeed valid and
372 /// from the store that `self` belongs to.
373 ///
374 /// (Note that it is *NOT* required that `vmctx` be distinct from this
375 /// instance's `vmctx`, or that usage of the resulting instance is limited
376 /// to its defined items! The returned borrow has the same lifetime as
377 /// `self`, which means that this instance cannot be used while the
378 /// resulting instance is in use, and we therefore do not need to worry
379 /// about mutable aliasing between this instance and the resulting
380 /// instance.)
381 #[inline]
382 unsafe fn sibling_vmctx_mut<'a>(
383 self: Pin<&'a mut Self>,
384 vmctx: NonNull<VMContext>,
385 ) -> Pin<&'a mut Instance> {
386 // SAFETY: it's a contract of this function itself that `vmctx` is a
387 // valid pointer such that this pointer arithmetic is valid.
388 let mut ptr = unsafe { Instance::from_vmctx(vmctx) };
389
390 // SAFETY: it's a contract of this function itself that `vmctx` is a
391 // valid pointer to dereference. Additionally the lifetime of the return
392 // value is constrained to be the same as `self` to avoid granting a
393 // too-long lifetime. Finally mutable references to an instance are
394 // always through `Pin`, so it's safe to create a pin-pointer here.
395 unsafe { Pin::new_unchecked(ptr.as_mut()) }
396 }
397
398 pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
399 self.runtime_info.env_module()
400 }
401
402 pub(crate) fn runtime_module(&self) -> Option<&crate::Module> {
403 match &self.runtime_info {
404 ModuleRuntimeInfo::Module(m) => Some(m),
405 ModuleRuntimeInfo::Bare(_) => None,
406 }
407 }
408
409 /// Translate a module-level interned type index into an engine-level
410 /// interned type index.
411 #[cfg(feature = "gc")]
412 pub fn engine_type_index(&self, module_index: ModuleInternedTypeIndex) -> VMSharedTypeIndex {
413 self.runtime_info.engine_type_index(module_index)
414 }
415
416 #[inline]
417 fn offsets(&self) -> &VMOffsets<HostPtr> {
418 self.runtime_info.offsets()
419 }
420
421 /// Return the indexed `VMFunctionImport`.
422 fn imported_function(&self, index: FuncIndex) -> &VMFunctionImport {
423 unsafe { self.vmctx_plus_offset(self.offsets().imported_functions().at(index)) }
424 }
425
426 /// Return the index `VMTableImport`.
427 fn imported_table(&self, index: TableIndex) -> &VMTableImport {
428 unsafe { self.vmctx_plus_offset(self.offsets().imported_tables().at(index)) }
429 }
430
431 /// Return the indexed `VMMemoryImport`.
432 fn imported_memory(&self, index: MemoryIndex) -> &VMMemoryImport {
433 unsafe { self.vmctx_plus_offset(self.offsets().imported_memories().at(index)) }
434 }
435
436 /// Return the indexed `VMGlobalImport`.
437 fn imported_global(&self, index: GlobalIndex) -> &VMGlobalImport {
438 unsafe { self.vmctx_plus_offset(self.offsets().imported_globals().at(index)) }
439 }
440
441 /// Return the indexed `VMTagImport`.
442 fn imported_tag(&self, index: TagIndex) -> &VMTagImport {
443 unsafe { self.vmctx_plus_offset(self.offsets().imported_tags().at(index)) }
444 }
445
446 /// Return the indexed `VMTagDefinition`.
447 pub fn tag_ptr(&self, index: DefinedTagIndex) -> NonNull<VMTagDefinition> {
448 unsafe { self.vmctx_plus_offset_raw(self.offsets().tags().at(index)) }
449 }
450
451 /// Return the indexed `VMTableDefinition`.
452 pub fn table(&self, index: DefinedTableIndex) -> VMTableDefinition {
453 unsafe { self.table_ptr(index).read() }
454 }
455
456 /// Updates the value for a defined table to `VMTableDefinition`.
457 fn set_table(self: Pin<&mut Self>, index: DefinedTableIndex, table: VMTableDefinition) {
458 unsafe {
459 self.table_ptr(index).write(table);
460 }
461 }
462
463 /// Return a pointer to the `index`'th table within this instance, stored
464 /// in vmctx memory.
465 pub fn table_ptr(&self, index: DefinedTableIndex) -> NonNull<VMTableDefinition> {
466 unsafe { self.vmctx_plus_offset_raw(self.offsets().tables().at(index)) }
467 }
468
469 /// Get a locally defined or imported memory.
470 #[cfg(all(has_host_compiler_backend, feature = "debug-builtins"))]
471 pub(crate) fn get_memory(&self, index: MemoryIndex) -> VMMemoryDefinition {
472 if let Some(defined_index) = self.env_module().defined_memory_index(index) {
473 self.memory(defined_index)
474 } else {
475 let import = self.imported_memory(index);
476 unsafe { VMMemoryDefinition::load(import.from.as_ptr()) }
477 }
478 }
479
480 /// Return the indexed `VMMemoryDefinition`, loaded from vmctx memory
481 /// already.
482 #[inline]
483 pub fn memory(&self, index: DefinedMemoryIndex) -> VMMemoryDefinition {
484 unsafe { VMMemoryDefinition::load(self.memory_ptr(index).as_ptr()) }
485 }
486
487 /// Set the indexed memory to `VMMemoryDefinition`.
488 fn set_memory(&self, index: DefinedMemoryIndex, mem: VMMemoryDefinition) {
489 unsafe {
490 self.memory_ptr(index).write(mem);
491 }
492 }
493
494 /// Return the address of the specified memory at `index` within this vmctx.
495 ///
496 /// Note that the returned pointer resides in wasm-code-readable-memory in
497 /// the vmctx.
498 #[inline]
499 pub fn memory_ptr(&self, index: DefinedMemoryIndex) -> NonNull<VMMemoryDefinition> {
500 unsafe {
501 self.vmctx_plus_offset::<VmPtr<_>>(self.offsets().memories().at(index))
502 .as_non_null()
503 }
504 }
505
506 /// Return the indexed `VMGlobalDefinition`.
507 pub fn global_ptr(&self, index: DefinedGlobalIndex) -> NonNull<VMGlobalDefinition> {
508 unsafe { self.vmctx_plus_offset_raw(self.offsets().globals().at(index)) }
509 }
510
511 /// Get all globals within this instance.
512 ///
513 /// Returns both import and defined globals.
514 ///
515 /// Returns both exported and non-exported globals.
516 ///
517 /// Gives access to the full globals space.
518 pub fn all_globals(
519 &self,
520 store: StoreId,
521 ) -> impl ExactSizeIterator<Item = (GlobalIndex, crate::Global)> + '_ {
522 let module = self.env_module();
523 module
524 .globals
525 .keys()
526 .map(move |idx| (idx, self.get_exported_global(store, idx)))
527 }
528
529 /// Get the globals defined in this instance (not imported).
530 pub fn defined_globals(
531 &self,
532 store: StoreId,
533 ) -> impl ExactSizeIterator<Item = (DefinedGlobalIndex, crate::Global)> + '_ {
534 let module = self.env_module();
535 self.all_globals(store)
536 .skip(module.num_imported_globals)
537 .map(move |(i, global)| (module.defined_global_index(i).unwrap(), global))
538 }
539
540 /// Return a pointer to the interrupts structure
541 #[inline]
542 pub fn vm_store_context(&self) -> NonNull<Option<VmPtr<VMStoreContext>>> {
543 unsafe { self.vmctx_plus_offset_raw(self.offsets().ptr.vmctx().store_context()) }
544 }
545
546 /// Return a pointer to the global epoch counter used by this instance.
547 #[cfg(target_has_atomic = "64")]
548 pub fn epoch_ptr(self: Pin<&mut Self>) -> &mut Option<VmPtr<AtomicU64>> {
549 let offset = self.offsets().ptr.vmctx().epoch_ptr();
550 unsafe { self.vmctx_plus_offset_mut(offset) }
551 }
552
553 /// Return a pointer to the collector-specific heap data.
554 pub fn gc_heap_data(self: Pin<&mut Self>) -> &mut Option<VmPtr<u8>> {
555 let offset = self.offsets().ptr.vmctx().gc_heap_data();
556 unsafe { self.vmctx_plus_offset_mut(offset) }
557 }
558
559 pub(crate) unsafe fn set_store(mut self: Pin<&mut Self>, store: &StoreOpaque) {
560 // FIXME: should be more targeted ideally with the `unsafe` than just
561 // throwing this entire function in a large `unsafe` block.
562 unsafe {
563 *self.as_mut().store_mut() = Some(VMStoreRawPtr(store.traitobj()));
564 self.vm_store_context()
565 .write(Some(store.vm_store_context_ptr().into()));
566 #[cfg(target_has_atomic = "64")]
567 {
568 *self.as_mut().epoch_ptr() =
569 Some(NonNull::from(store.engine().epoch_counter()).into());
570 }
571
572 if self.env_module().needs_gc_heap {
573 self.as_mut().set_gc_heap(Some(store.unwrap_gc_store()));
574 } else {
575 self.as_mut().set_gc_heap(None);
576 }
577 }
578 }
579
580 unsafe fn set_gc_heap(self: Pin<&mut Self>, gc_store: Option<&GcStore>) {
581 if let Some(gc_store) = gc_store {
582 *self.gc_heap_data() = Some(unsafe { gc_store.gc_heap.vmctx_gc_heap_data().into() });
583 } else {
584 *self.gc_heap_data() = None;
585 }
586 }
587
588 /// Return a reference to the vmctx used by compiled wasm code.
589 #[inline]
590 pub fn vmctx(&self) -> NonNull<VMContext> {
591 InstanceLayout::vmctx(self)
592 }
593
594 /// Lookup a function by index.
595 ///
596 /// # Panics
597 ///
598 /// Panics if `index` is out of bounds for this instance.
599 ///
600 /// # Safety
601 ///
602 /// The `store` parameter must be the store that owns this instance and the
603 /// functions that this instance can reference.
604 pub unsafe fn get_exported_func(
605 self: Pin<&mut Self>,
606 registry: &ModuleRegistry,
607 store: StoreId,
608 index: FuncIndex,
609 ) -> crate::Func {
610 let func_ref = self.get_func_ref(registry, index).unwrap();
611
612 // SAFETY: the validity of `func_ref` is guaranteed by the validity of
613 // `self`, and the contract that `store` must own `func_ref` is a
614 // contract of this function itself.
615 unsafe { crate::Func::from_vm_func_ref(store, func_ref) }
616 }
617
618 /// Returns a `Func` corresponding to the startup function for this
619 /// instance, if generated at compile time.
620 ///
621 /// # Safety
622 ///
623 /// The `store` parameter must be the store that owns this instance and the
624 /// functions that this instance can reference.
625 pub unsafe fn get_startup_func(
626 self: Pin<&mut Self>,
627 registry: &ModuleRegistry,
628 store: StoreId,
629 ) -> Option<crate::Func> {
630 let func_ref = self.get_start_func_ref(registry)?;
631
632 // SAFETY: the validity of `func_ref` is guaranteed by the validity of
633 // `self`, and the contract that `store` must own `func_ref` is a
634 // contract of this function itself.
635 Some(unsafe { crate::Func::from_vm_func_ref(store, func_ref) })
636 }
637
638 /// Lookup a table by index.
639 ///
640 /// # Panics
641 ///
642 /// Panics if `index` is out of bounds for this instance.
643 pub fn get_exported_table(&self, store: StoreId, index: TableIndex) -> crate::Table {
644 let (id, def_index) = if let Some(def_index) = self.env_module().defined_table_index(index)
645 {
646 (self.id, def_index)
647 } else {
648 let import = self.imported_table(index);
649 // SAFETY: validity of this `Instance` guarantees validity of the
650 // `vmctx` pointer being read here to find the transitive
651 // `InstanceId` that the import is associated with.
652 let id = unsafe { self.sibling_vmctx(import.vmctx.as_non_null()).id };
653 (id, import.index)
654 };
655 crate::Table::from_raw(StoreInstanceId::new(store, id), def_index)
656 }
657
658 /// Lookup a memory by index.
659 ///
660 /// # Panics
661 ///
662 /// Panics if `index` is out-of-bounds for this instance.
663 #[cfg_attr(
664 not(feature = "threads"),
665 expect(unused_variables, reason = "definitions cfg'd to dummy",)
666 )]
667 pub fn get_exported_memory(&self, store: StoreId, index: MemoryIndex) -> ExportMemory {
668 let module = self.env_module();
669 if module.memories[index].shared {
670 let (memory, import) =
671 if let Some(def_index) = self.env_module().defined_memory_index(index) {
672 (
673 self.get_defined_memory(def_index),
674 self.get_defined_memory_vmimport(def_index),
675 )
676 } else {
677 let import = self.imported_memory(index);
678 // SAFETY: validity of this `Instance` guarantees validity of
679 // the `vmctx` pointer being read here to find the transitive
680 // `InstanceId` that the import is associated with.
681 let instance = unsafe { self.sibling_vmctx(import.vmctx.as_non_null()) };
682 (instance.get_defined_memory(import.index), *import)
683 };
684
685 let vm = memory.as_shared_memory().unwrap().clone();
686 ExportMemory::Shared(vm, import)
687 } else {
688 let (id, def_index) =
689 if let Some(def_index) = self.env_module().defined_memory_index(index) {
690 (self.id, def_index)
691 } else {
692 let import = self.imported_memory(index);
693 // SAFETY: validity of this `Instance` guarantees validity of the
694 // `vmctx` pointer being read here to find the transitive
695 // `InstanceId` that the import is associated with.
696 let id = unsafe { self.sibling_vmctx(import.vmctx.as_non_null()).id };
697 (id, import.index)
698 };
699
700 // SAFETY: `from_raw` requires that the memory is not shared, which
701 // was tested above in this if/else.
702 let store_id = StoreInstanceId::new(store, id);
703 ExportMemory::Unshared(unsafe { crate::Memory::from_raw(store_id, def_index) })
704 }
705 }
706
707 /// Lookup a global by index.
708 ///
709 /// # Panics
710 ///
711 /// Panics if `index` is out-of-bounds for this instance.
712 pub(crate) fn get_exported_global(&self, store: StoreId, index: GlobalIndex) -> crate::Global {
713 // If this global is defined within this instance, then that's easy to
714 // calculate the `Global`.
715 if let Some(def_index) = self.env_module().defined_global_index(index) {
716 let instance = StoreInstanceId::new(store, self.id);
717 return crate::Global::from_core(instance, def_index);
718 }
719
720 // For imported globals it's required to match on the `kind` to
721 // determine which `Global` constructor is going to be invoked.
722 let import = self.imported_global(index);
723 match import.kind {
724 VMGlobalKind::Host(index) => crate::Global::from_host(store, index),
725 VMGlobalKind::Instance(index) => {
726 // SAFETY: validity of this `&Instance` means validity of its
727 // imports meaning we can read the id of the vmctx within.
728 let id = unsafe {
729 let vmctx = VMContext::from_opaque(import.vmctx.unwrap().as_non_null());
730 self.sibling_vmctx(vmctx).id
731 };
732 crate::Global::from_core(StoreInstanceId::new(store, id), index)
733 }
734 #[cfg(feature = "component-model")]
735 VMGlobalKind::ComponentFlags(index) => {
736 // SAFETY: validity of this `&Instance` means validity of its
737 // imports meaning we can read the id of the vmctx within.
738 let id = unsafe {
739 let vmctx = super::component::VMComponentContext::from_opaque(
740 import.vmctx.unwrap().as_non_null(),
741 );
742 super::component::ComponentInstance::vmctx_instance_id(vmctx)
743 };
744 crate::Global::from_component_flags(
745 crate::component::store::StoreComponentInstanceId::new(store, id),
746 index,
747 )
748 }
749 }
750 }
751
752 /// Get an exported tag by index.
753 ///
754 /// # Panics
755 ///
756 /// Panics if the index is out-of-range.
757 pub fn get_exported_tag(&self, store: StoreId, index: TagIndex) -> crate::Tag {
758 let (id, def_index) = if let Some(def_index) = self.env_module().defined_tag_index(index) {
759 (self.id, def_index)
760 } else {
761 let import = self.imported_tag(index);
762 // SAFETY: validity of this `Instance` guarantees validity of the
763 // `vmctx` pointer being read here to find the transitive
764 // `InstanceId` that the import is associated with.
765 let id = unsafe { self.sibling_vmctx(import.vmctx.as_non_null()).id };
766 (id, import.index)
767 };
768 crate::Tag::from_raw(StoreInstanceId::new(store, id), def_index)
769 }
770
771 /// Grow memory by the specified amount of pages.
772 ///
773 /// Returns `None` if memory can't be grown by the specified amount
774 /// of pages. Returns `Some` with the old size in bytes if growth was
775 /// successful.
776 pub(crate) async fn memory_grow(
777 mut self: Pin<&mut Self>,
778 limiter: Option<&mut StoreResourceLimiter<'_>>,
779 idx: DefinedMemoryIndex,
780 delta: u64,
781 ) -> Result<Option<usize>, Error> {
782 let memory = &mut self.as_mut().memories_mut()[idx].1;
783
784 // SAFETY: this is the safe wrapper around `Memory::grow` because it
785 // automatically updates the `VMMemoryDefinition` in this instance after
786 // a growth operation below.
787 let result = unsafe { memory.grow(delta, limiter).await };
788
789 // Update the state used by a non-shared Wasm memory in case the base
790 // pointer and/or the length changed.
791 if memory.as_shared_memory().is_none() {
792 let vmmemory = memory.vmmemory();
793 self.set_memory(idx, vmmemory);
794 }
795
796 result
797 }
798
799 /// Performs a grow operation on the `table_index` specified using `grow`.
800 ///
801 /// This will handle updating the VMTableDefinition internally as necessary.
802 ///
803 /// # Safety
804 ///
805 /// This function requires that the caller, on success, fills in the table
806 /// elements with an appropriately typed value.
807 pub(crate) async unsafe fn defined_table_grow(
808 mut self: Pin<&mut Self>,
809 table_index: DefinedTableIndex,
810 limiter: Option<&mut StoreResourceLimiter<'_>>,
811 amt: u64,
812 ) -> Result<Option<usize>> {
813 let table = self.as_mut().get_defined_table(table_index);
814 // SAFETY: updating the `VMContext` table pointers and such is done
815 // below, and the responsibility of filling in the new table elements
816 // is forwarded to the caller.
817 let result = unsafe { table.grow(limiter, amt).await? };
818 let element = table.vmtable();
819 self.set_table(table_index, element);
820 Ok(result)
821 }
822
823 fn alloc_layout(offsets: &VMOffsets<HostPtr>) -> Layout {
824 let size = mem::size_of::<Self>()
825 .checked_add(usize::try_from(offsets.size_of_vmctx()).unwrap())
826 .unwrap();
827 let align = mem::align_of::<Self>();
828 Layout::from_size_align(size, align).unwrap()
829 }
830
831 fn type_ids_array(&self) -> NonNull<VmPtr<VMSharedTypeIndex>> {
832 unsafe { self.vmctx_plus_offset_raw(self.offsets().ptr.vmctx().type_ids()) }
833 }
834
835 /// Get a `&VMFuncRef` for the given `FuncIndex`.
836 ///
837 /// Returns `None` if the index is the reserved index value.
838 ///
839 /// The returned reference is a stable reference that won't be moved and can
840 /// be passed into JIT code.
841 pub(crate) fn get_func_ref(
842 self: Pin<&mut Self>,
843 registry: &ModuleRegistry,
844 index: FuncIndex,
845 ) -> Option<NonNull<VMFuncRef>> {
846 if index == FuncIndex::reserved_value() {
847 return None;
848 }
849
850 match self.env_module().defined_func_index(index) {
851 Some(index) => self.initialize_defined_funcref(registry, index),
852 None => {
853 debug_assert!(self.env_module().is_imported_function(index));
854 Some(self.imported_function(index).as_func_ref().into())
855 }
856 }
857 }
858
859 /// Initializes a defined function's `VMFuncRef` in-place and then returns a
860 /// pointer to that location.
861 fn initialize_defined_funcref(
862 self: Pin<&mut Self>,
863 registry: &ModuleRegistry,
864 def_index: DefinedFuncIndex,
865 ) -> Option<NonNull<VMFuncRef>> {
866 let module = self.env_module();
867 let index = module.func_index(def_index);
868 let func = &module.functions[index];
869 let type_index = func.signature.unwrap_engine_type_index();
870 let vmctx_offset = self.offsets().func_refs().at(func.func_ref);
871 let array_to_wasm_key = FuncKey::ArrayToWasmTrampoline(module.module_index, def_index);
872 let wasm_key = FuncKey::DefinedWasmFunction(module.module_index, def_index);
873 // SAFETY: the type/offset/keys here are all valid for the defined
874 // function at `def_index`.
875 unsafe {
876 self.initialize_and_return_funcref(
877 registry,
878 type_index,
879 vmctx_offset,
880 array_to_wasm_key,
881 wasm_key,
882 )
883 }
884 }
885
886 fn get_start_func_ref(
887 self: Pin<&mut Self>,
888 registry: &ModuleRegistry,
889 ) -> Option<NonNull<VMFuncRef>> {
890 let module = self.env_module();
891 let type_index = match module.startup {
892 ModuleStartup::None => return None,
893 ModuleStartup::Always(t) | ModuleStartup::IfMemoriesNeedInit(t) => {
894 t.unwrap_engine_type_index()
895 }
896 };
897 let vmctx_offset = self.offsets().startup_func_ref();
898 let array_to_wasm_key = FuncKey::ModuleStartup(Abi::Array, module.module_index);
899 let wasm_key = FuncKey::ModuleStartup(Abi::Wasm, module.module_index);
900 // SAFETY: the type/offset/keys here are all valid for the module
901 // startup function.
902 unsafe {
903 self.initialize_and_return_funcref(
904 registry,
905 type_index,
906 vmctx_offset,
907 array_to_wasm_key,
908 wasm_key,
909 )
910 }
911 }
912
913 /// Common implementation of initializing a `VMFuncRef` stored within this
914 /// instance's `VMContext`.
915 ///
916 /// # Safety
917 ///
918 /// This function requires that `type_index` accurately describes this
919 /// function and `vmctx_offset` is indeed the correct offset for the
920 /// functions here. Effectively all the arguments here must be "logically
921 /// correct" for the `VMFuncRef` being initialized.
922 unsafe fn initialize_and_return_funcref(
923 self: Pin<&mut Self>,
924 registry: &ModuleRegistry,
925 type_index: VMSharedTypeIndex,
926 vmctx_offset: u32,
927 array_to_wasm_key: FuncKey,
928 wasm_key: FuncKey,
929 ) -> Option<NonNull<VMFuncRef>> {
930 // For now, we eagerly initialize an funcref struct in-place whenever
931 // asked for a reference to it. This is mostly fine, because in practice
932 // each funcref is unlikely to be requested more than a few times:
933 // once-ish for funcref tables used for call_indirect (the usual
934 // compilation strategy places each function in the table at most once),
935 // and once or a few times when fetching exports via API. Note that for
936 // any case driven by table accesses, the lazy table init behaves like a
937 // higher-level cache layer that protects this initialization from
938 // happening multiple times, via that particular table at least.
939 //
940 // When `ref.func` becomes more commonly used or if we otherwise see a
941 // use-case where this becomes a hotpath, we can reconsider by using
942 // some state to track "uninitialized" explicitly, for example by
943 // zeroing the funcrefs (perhaps together with other
944 // zeroed-at-instantiate-time state) or using a separate is-initialized
945 // bitmap.
946 //
947 // We arrived at this design because zeroing memory is expensive, so
948 // it's better for instantiation performance if we don't have to track
949 // "is-initialized" state at all!
950
951 let module_with_code = ModuleWithCode::in_store(
952 registry,
953 self.runtime_module()
954 .expect("funcref impossible in fake module"),
955 )
956 .expect("module not in store");
957
958 let array_call =
959 VmPtr::from(NonNull::from(module_with_code.function(array_to_wasm_key)).cast());
960
961 let wasm_call = Some(VmPtr::from(
962 NonNull::new(
963 module_with_code
964 .function(wasm_key)
965 .as_ptr()
966 .cast::<VMWasmCallFunction>()
967 .cast_mut(),
968 )
969 .unwrap(),
970 ));
971
972 let vmctx = VMOpaqueContext::from_vmcontext(self.vmctx()).into();
973
974 // SAFETY: the offset calculated here should be correct with
975 // `self.offsets`
976 let func_ref_ptr = unsafe { self.vmctx_plus_offset_raw::<VMFuncRef>(vmctx_offset) };
977
978 // SAFETY: the `func_ref_ptr` should be valid as it's within our
979 // `VMContext` area.
980 unsafe {
981 func_ref_ptr.write(VMFuncRef {
982 array_call,
983 wasm_call,
984 vmctx,
985 type_index,
986 });
987 }
988
989 Some(func_ref_ptr)
990 }
991
992 /// Get the passive elements segment at the given index.
993 pub(crate) fn passive_element_segment(
994 self: Pin<&mut Self>,
995 passive: PassiveElemIndex,
996 ) -> &mut [ValRaw] {
997 self.passive_elements_mut()[passive.index()].elements_mut()
998 }
999
1000 pub(crate) fn passive_elements_mut(self: Pin<&mut Self>) -> &mut TryVec<PassiveElementSegment> {
1001 // SAFETY: Not moving data out of `self`.
1002 &mut unsafe { self.get_unchecked_mut() }.passive_elements
1003 }
1004
1005 /// Drop an element.
1006 pub(crate) fn passive_elem_drop(
1007 self: Pin<&mut Self>,
1008 gc_store: Option<&mut GcStore>,
1009 passive_index: PassiveElemIndex,
1010 ) -> Result<(), OutOfMemory> {
1011 self.passive_elements_mut()[passive_index.index()].clear(gc_store);
1012 Ok(())
1013 }
1014
1015 /// Get a locally-defined memory.
1016 pub fn get_defined_memory_mut(self: Pin<&mut Self>, index: DefinedMemoryIndex) -> &mut Memory {
1017 &mut self.memories_mut()[index].1
1018 }
1019
1020 /// Get a locally-defined memory.
1021 pub fn get_defined_memory(&self, index: DefinedMemoryIndex) -> &Memory {
1022 &self.memories[index].1
1023 }
1024
1025 pub fn get_defined_memory_vmimport(&self, index: DefinedMemoryIndex) -> VMMemoryImport {
1026 crate::runtime::vm::VMMemoryImport {
1027 from: self.memory_ptr(index).into(),
1028 vmctx: self.vmctx().into(),
1029 index,
1030 }
1031 }
1032
1033 /// Given an internal storage range of a Wasm data segment (or subset of a
1034 /// Wasm data segment), get the data's raw bytes.
1035 pub(crate) fn wasm_data(&self, range: Range<u32>) -> &[u8] {
1036 let start = usize::try_from(range.start).unwrap();
1037 let end = usize::try_from(range.end).unwrap();
1038 &self.runtime_info.wasm_data()[start..end]
1039 }
1040
1041 /// Returns the data for the runtime segment identified by `index`
1042 ///
1043 /// Does not take into account the dynamic size of the data pointed to by
1044 /// `index`, always returns the raw data from the module itself.
1045 ///
1046 /// # Panics
1047 ///
1048 /// Panics if `index` is out-of-bounds.
1049 fn runtime_data(&self, index: RuntimeDataIndex) -> &[u8] {
1050 let range = self.env_module().runtime_data[index].clone();
1051 self.wasm_data(range)
1052 }
1053
1054 /// Get a table by index regardless of whether it is locally-defined
1055 /// or an imported, foreign table. Ensure that the given range of
1056 /// elements in the table is lazily initialized. We define this
1057 /// operation all-in-one for safety, to ensure the lazy-init
1058 /// happens.
1059 ///
1060 /// Takes an `Iterator` for the index-range to lazy-initialize,
1061 /// for flexibility. This can be a range, single item, or empty
1062 /// sequence, for example. The iterator should return indices in
1063 /// increasing order, so that the break-at-out-of-bounds behavior
1064 /// works correctly.
1065 pub(crate) fn get_table_with_lazy_init(
1066 self: Pin<&mut Self>,
1067 registry: &ModuleRegistry,
1068 table_index: TableIndex,
1069 range: impl Iterator<Item = u64>,
1070 ) -> &mut Table {
1071 let (idx, instance) = self.defined_table_index_and_instance(table_index);
1072 instance.get_defined_table_with_lazy_init(registry, idx, range)
1073 }
1074
1075 /// Gets the raw runtime table data structure owned by this instance
1076 /// given the provided `idx`.
1077 ///
1078 /// The `range` specified is eagerly initialized for funcref tables.
1079 pub fn get_defined_table_with_lazy_init(
1080 mut self: Pin<&mut Self>,
1081 registry: &ModuleRegistry,
1082 idx: DefinedTableIndex,
1083 range: impl IntoIterator<Item = u64>,
1084 ) -> &mut Table {
1085 let elt_ty = self.tables[idx].1.element_type();
1086
1087 if elt_ty == TableElementType::Func {
1088 for i in range {
1089 match self.tables[idx].1.get_func_maybe_init(i) {
1090 // Uninitialized table element.
1091 Ok(None) => {}
1092 // Initialized table element, move on to the next.
1093 Ok(Some(_)) => continue,
1094 // Out-of-bounds; caller will handle by likely
1095 // throwing a trap. No work to do to lazy-init
1096 // beyond the end.
1097 Err(_) => break,
1098 };
1099
1100 // The table element `i` is uninitialized and is now being
1101 // initialized. This must imply that a `precompiled` list of
1102 // function indices is available for this table. The precompiled
1103 // list is extracted and then it is consulted with `i` to
1104 // determine the function that is going to be initialized. Note
1105 // that `i` may be outside the limits of the static
1106 // initialization so it's a fallible `get` instead of an index.
1107 let module = self.env_module();
1108 let precomputed = &module.table_initialization[idx];
1109 // Panicking here helps catch bugs rather than silently truncating by accident.
1110 let func_index = precomputed.get(usize::try_from(i).unwrap()).cloned();
1111 let func_ref = func_index
1112 .and_then(|func_index| self.as_mut().get_func_ref(registry, func_index));
1113 self.as_mut().tables_mut()[idx]
1114 .1
1115 .set_func(i, func_ref)
1116 .expect("Table type should match and index should be in-bounds");
1117 }
1118 }
1119
1120 self.get_defined_table(idx)
1121 }
1122
1123 /// Get a locally-defined table.
1124 pub(crate) fn get_defined_table(self: Pin<&mut Self>, index: DefinedTableIndex) -> &mut Table {
1125 &mut self.tables_mut()[index].1
1126 }
1127
1128 pub(crate) fn defined_table_index_and_instance<'a>(
1129 self: Pin<&'a mut Self>,
1130 index: TableIndex,
1131 ) -> (DefinedTableIndex, Pin<&'a mut Instance>) {
1132 if let Some(defined_table_index) = self.env_module().defined_table_index(index) {
1133 (defined_table_index, self)
1134 } else {
1135 let import = self.imported_table(index);
1136 let index = import.index;
1137 let vmctx = import.vmctx.as_non_null();
1138 // SAFETY: the validity of `self` means that the reachable instances
1139 // should also all be owned by the same store and fully initialized,
1140 // so it's safe to laterally move from a mutable borrow of this
1141 // instance to a mutable borrow of a sibling instance.
1142 let foreign_instance = unsafe { self.sibling_vmctx_mut(vmctx) };
1143 (index, foreign_instance)
1144 }
1145 }
1146
1147 /// Same as `self.runtime_info.env_module()` but additionally returns the
1148 /// `Pin<&mut Self>` with the same original lifetime.
1149 pub fn module_and_self(self: Pin<&mut Self>) -> (&wasmtime_environ::Module, Pin<&mut Self>) {
1150 // SAFETY: this function is projecting both `&Module` and the same
1151 // pointer both connected to the same lifetime. This is safe because
1152 // it's a contract of `Pin<&mut Self>` that the `runtime_info` field is
1153 // never written, meaning it's effectively unsafe to have `&mut Module`
1154 // projected from `Pin<&mut Self>`. Consequently it's safe to have a
1155 // read-only view of the field while still retaining mutable access to
1156 // all other fields.
1157 let module = self.runtime_info.env_module();
1158 let module = &raw const *module;
1159 let module = unsafe { &*module };
1160 (module, self)
1161 }
1162
1163 /// Initialize the VMContext data associated with this Instance.
1164 ///
1165 /// The `VMContext` memory is assumed to be uninitialized; any field
1166 /// that we need in a certain state will be explicitly written by this
1167 /// function.
1168 unsafe fn initialize_vmctx(self: Pin<&mut Self>, store: &StoreOpaque, imports: Imports) {
1169 let (module, mut instance) = self.module_and_self();
1170
1171 // SAFETY: the type of the magic field is indeed `u32` and this function
1172 // is initializing its value.
1173 unsafe {
1174 let offsets = instance.runtime_info.offsets();
1175 instance
1176 .vmctx_plus_offset_raw::<u32>(offsets.ptr.vmctx().magic())
1177 .write(VMCONTEXT_MAGIC);
1178 }
1179
1180 // SAFETY: it's up to the caller to provide a valid store pointer here.
1181 unsafe {
1182 instance.as_mut().set_store(store);
1183 }
1184
1185 // Initialize shared types
1186 //
1187 // SAFETY: validity of the vmctx means it should be safe to write to it
1188 // here.
1189 unsafe {
1190 let types = NonNull::from(instance.runtime_info.type_ids());
1191 instance.type_ids_array().write(types.cast().into());
1192 }
1193
1194 // Initialize the built-in functions
1195 //
1196 // SAFETY: the type of the builtin functions field is indeed a pointer
1197 // and the pointer being filled in here, plus the vmctx is valid to
1198 // write to during initialization.
1199 unsafe {
1200 static BUILTINS: VMBuiltinFunctionsArray = VMBuiltinFunctionsArray::INIT;
1201 let ptr = BUILTINS.expose_provenance();
1202 let offsets = instance.runtime_info.offsets();
1203 instance
1204 .vmctx_plus_offset_raw(offsets.ptr.vmctx().builtin_functions())
1205 .write(VmPtr::from(ptr));
1206 }
1207
1208 // Initialize the imports
1209 //
1210 // SAFETY: the vmctx is safe to initialize during this function and
1211 // validity of each item itself is a contract the caller must uphold.
1212 debug_assert_eq!(imports.functions.len(), module.num_imported_funcs);
1213 unsafe {
1214 let offsets = instance.runtime_info.offsets();
1215 ptr::copy_nonoverlapping(
1216 imports.functions.as_ptr(),
1217 instance
1218 .vmctx_plus_offset_raw(offsets.imported_functions().begin())
1219 .as_ptr(),
1220 imports.functions.len(),
1221 );
1222 debug_assert_eq!(imports.tables.len(), module.num_imported_tables);
1223 ptr::copy_nonoverlapping(
1224 imports.tables.as_ptr(),
1225 instance
1226 .vmctx_plus_offset_raw(offsets.imported_tables().begin())
1227 .as_ptr(),
1228 imports.tables.len(),
1229 );
1230 debug_assert_eq!(imports.memories.len(), module.num_imported_memories);
1231 ptr::copy_nonoverlapping(
1232 imports.memories.as_ptr(),
1233 instance
1234 .vmctx_plus_offset_raw(offsets.imported_memories().begin())
1235 .as_ptr(),
1236 imports.memories.len(),
1237 );
1238 debug_assert_eq!(imports.globals.len(), module.num_imported_globals);
1239 ptr::copy_nonoverlapping(
1240 imports.globals.as_ptr(),
1241 instance
1242 .vmctx_plus_offset_raw(offsets.imported_globals().begin())
1243 .as_ptr(),
1244 imports.globals.len(),
1245 );
1246 debug_assert_eq!(imports.tags.len(), module.num_imported_tags);
1247 ptr::copy_nonoverlapping(
1248 imports.tags.as_ptr(),
1249 instance
1250 .vmctx_plus_offset_raw(offsets.imported_tags().begin())
1251 .as_ptr(),
1252 imports.tags.len(),
1253 );
1254 }
1255
1256 // N.B.: there is no need to initialize the funcrefs array because we
1257 // eagerly construct each element in it whenever asked for a reference
1258 // to that element. In other words, there is no state needed to track
1259 // the lazy-init, so we don't need to initialize any state now.
1260
1261 // Initialize the defined tables
1262 //
1263 // SAFETY: it's safe to initialize these tables during initialization
1264 // here and the various types of pointers and such here should all be
1265 // valid.
1266 unsafe {
1267 let offsets = instance.runtime_info.offsets();
1268 let mut ptr = instance.vmctx_plus_offset_raw(offsets.tables().begin());
1269 let tables = instance.as_mut().tables_mut();
1270 for i in 0..module.num_defined_tables() {
1271 ptr.write(tables[DefinedTableIndex::new(i)].1.vmtable());
1272 ptr = ptr.add(1);
1273 }
1274 }
1275
1276 // Initialize the defined memories. This fills in both the
1277 // `defined_memories` table and the `owned_memories` table at the same
1278 // time. Entries in `defined_memories` hold a pointer to a definition
1279 // (all memories) whereas the `owned_memories` hold the actual
1280 // definitions of memories owned (not shared) in the module.
1281 //
1282 // SAFETY: it's safe to initialize these memories during initialization
1283 // here and the various types of pointers and such here should all be
1284 // valid.
1285 unsafe {
1286 let offsets = instance.runtime_info.offsets();
1287 let mut ptr = instance.vmctx_plus_offset_raw(offsets.memories().begin());
1288 let mut owned_ptr = instance.vmctx_plus_offset_raw(offsets.owned_memories().begin());
1289 let memories = instance.as_mut().memories_mut();
1290 for i in 0..module.num_defined_memories() {
1291 let defined_memory_index = DefinedMemoryIndex::new(i);
1292 let memory_index = module.memory_index(defined_memory_index);
1293 if module.memories[memory_index].shared {
1294 let def_ptr = memories[defined_memory_index]
1295 .1
1296 .as_shared_memory()
1297 .unwrap()
1298 .vmmemory_ptr();
1299 ptr.write(VmPtr::from(def_ptr));
1300 } else {
1301 owned_ptr.write(memories[defined_memory_index].1.vmmemory());
1302 ptr.write(VmPtr::from(owned_ptr));
1303 owned_ptr = owned_ptr.add(1);
1304 }
1305 ptr = ptr.add(1);
1306 }
1307 }
1308
1309 // Zero-initialize the globals so that nothing is uninitialized memory
1310 // after this function returns. The globals are actually initialized
1311 // with their const expression initializers after the instance is fully
1312 // allocated.
1313 //
1314 // SAFETY: it's safe to initialize globals during initialization
1315 // here. Note that while the value being written is not valid for all
1316 // types of globals it's initializing the memory to zero instead of
1317 // being in an undefined state. So it's still unsafe to access globals
1318 // after this, but if it's read then it'd hopefully crash faster than
1319 // leaving this undefined.
1320 unsafe {
1321 for i in 0..module.num_defined_globals() {
1322 let index = DefinedGlobalIndex::new(i);
1323 instance.global_ptr(index).write(VMGlobalDefinition::new());
1324 }
1325 for (index, val) in module.global_initializers.iter() {
1326 let mut def = VMGlobalDefinition::new();
1327 match val {
1328 GlobalConstValue::I32(i) => def.set_i32(*i),
1329 GlobalConstValue::I64(i) => def.set_i64(*i),
1330 GlobalConstValue::F32(i) => def.set_f32_bits(*i),
1331 GlobalConstValue::F64(i) => def.set_f64_bits(*i),
1332 GlobalConstValue::V128(i) => def.set_u128(*i),
1333 }
1334 instance.global_ptr(*index).write(def);
1335 }
1336 }
1337
1338 // Initialize the defined tags
1339 //
1340 // SAFETY: it's safe to initialize these tags during initialization
1341 // here and the various types of pointers and such here should all be
1342 // valid.
1343 unsafe {
1344 let offsets = instance.runtime_info.offsets();
1345 let mut ptr = instance.vmctx_plus_offset_raw(offsets.tags().begin());
1346 for i in 0..module.num_defined_tags() {
1347 let defined_index = DefinedTagIndex::new(i);
1348 let tag_index = module.tag_index(defined_index);
1349 let tag = module.tags[tag_index];
1350 ptr.write(VMTagDefinition::new(
1351 tag.signature.unwrap_engine_type_index(),
1352 ));
1353 ptr = ptr.add(1);
1354 }
1355 }
1356
1357 // Initialize the lengths of runtime data segments.
1358 //
1359 // SAFETY: it's safe to initialize these lengths during initialization
1360 // here and the various types of pointers and such here should all be
1361 // valid.
1362 unsafe {
1363 let offsets = instance.runtime_info.offsets();
1364 let mut lengths =
1365 instance.vmctx_plus_offset_raw(offsets.runtime_data_lengths().begin());
1366 let mut bases = instance.vmctx_plus_offset_raw(offsets.runtime_data_bases().begin());
1367 for i in module.runtime_data.keys() {
1368 let data = instance.runtime_data(i);
1369 lengths.write(u32::try_from(data.len()).unwrap());
1370 lengths = lengths.add(1);
1371 bases.write(VmPtr::from(NonNull::from(data).cast::<u8>()));
1372 bases = bases.add(1);
1373 }
1374 }
1375
1376 // This is the half of the strategy of implementing memory-init-cow data
1377 // segments. Notably the compiled startup function, if present, will
1378 // skip data segments that have a null pointer. Here each linear memory
1379 // is tested to see if it needs initialization. If it does, then the
1380 // data segment is left in-place (and the startup function will
1381 // initialize linear memory). Otherwise the data segment is null'd out.
1382 // If the startup function runs (e.g. something else in the module needs
1383 // it), then the corresponding data segment's initialization will be
1384 // skipped.
1385 if let MemoryInitialization::Static { map } = &module.memory_initialization {
1386 for (memory, init) in map {
1387 let Some(memory) = module.defined_memory_index(memory) else {
1388 continue;
1389 };
1390 if instance.memories[memory].1.needs_init() {
1391 continue;
1392 }
1393 if let Some((_offset, data)) = init {
1394 let offsets = instance.runtime_info.offsets();
1395 unsafe {
1396 instance
1397 .vmctx_plus_offset_raw(offsets.runtime_data_lengths().at(*data))
1398 .write(0u32);
1399 instance
1400 .vmctx_plus_offset_raw(offsets.runtime_data_bases().at(*data))
1401 .write(0usize);
1402 }
1403 }
1404 }
1405 }
1406 }
1407
1408 /// Attempts to convert from the host `addr` specified to a WebAssembly
1409 /// based address recorded in `WasmFault`.
1410 ///
1411 /// This method will check all linear memories that this instance contains
1412 /// to see if any of them contain `addr`. If one does then `Some` is
1413 /// returned with metadata about the wasm fault. Otherwise `None` is
1414 /// returned and `addr` doesn't belong to this instance.
1415 pub fn wasm_fault(&self, addr: usize) -> Option<WasmFault> {
1416 let mut fault = None;
1417 for (_, (_, memory)) in self.memories.iter() {
1418 let accessible = memory.wasm_accessible();
1419 if accessible.start <= addr && addr < accessible.end {
1420 // All linear memories should be disjoint so assert that no
1421 // prior fault has been found.
1422 assert!(fault.is_none());
1423 fault = Some(WasmFault {
1424 memory_size: memory.byte_size(),
1425 wasm_address: u64::try_from(addr - accessible.start).unwrap(),
1426 });
1427 }
1428 }
1429 fault
1430 }
1431
1432 /// Returns the id, within this instance's store, that it's assigned.
1433 pub fn id(&self) -> InstanceId {
1434 self.id
1435 }
1436
1437 /// Get all memories within this instance.
1438 ///
1439 /// Returns both import and defined memories.
1440 ///
1441 /// Returns both exported and non-exported memories.
1442 ///
1443 /// Gives access to the full memories space.
1444 pub fn all_memories(
1445 &self,
1446 store: StoreId,
1447 ) -> impl ExactSizeIterator<Item = (MemoryIndex, ExportMemory)> + '_ {
1448 self.env_module()
1449 .memories
1450 .iter()
1451 .map(move |(i, _)| (i, self.get_exported_memory(store, i)))
1452 }
1453
1454 /// Return the memories defined in this instance (not imported).
1455 pub fn defined_memories<'a>(
1456 &'a self,
1457 store: StoreId,
1458 ) -> impl ExactSizeIterator<Item = ExportMemory> + 'a {
1459 let num_imported = self.env_module().num_imported_memories;
1460 self.all_memories(store)
1461 .skip(num_imported)
1462 .map(|(_i, memory)| memory)
1463 }
1464
1465 /// Lookup an item with the given index.
1466 ///
1467 /// # Panics
1468 ///
1469 /// Panics if `export` is not valid for this instance.
1470 ///
1471 /// # Safety
1472 ///
1473 /// This function requires that `store` is the correct store which owns this
1474 /// instance.
1475 pub unsafe fn get_export_by_index_mut(
1476 self: Pin<&mut Self>,
1477 registry: &ModuleRegistry,
1478 store: StoreId,
1479 export: EntityIndex,
1480 ) -> Export {
1481 match export {
1482 // SAFETY: the contract of `store` owning the this instance is a
1483 // safety requirement of this function itself.
1484 EntityIndex::Function(i) => {
1485 Export::Function(unsafe { self.get_exported_func(registry, store, i) })
1486 }
1487 EntityIndex::Global(i) => Export::Global(self.get_exported_global(store, i)),
1488 EntityIndex::Table(i) => Export::Table(self.get_exported_table(store, i)),
1489 EntityIndex::Memory(i) => match self.get_exported_memory(store, i) {
1490 ExportMemory::Unshared(m) => Export::Memory(m),
1491 ExportMemory::Shared(m, i) => Export::SharedMemory(m, i),
1492 },
1493 EntityIndex::Tag(i) => Export::Tag(self.get_exported_tag(store, i)),
1494 }
1495 }
1496
1497 fn store_mut(self: Pin<&mut Self>) -> &mut Option<VMStoreRawPtr> {
1498 // SAFETY: this is a pin-projection to get a mutable reference to an
1499 // internal field and is safe so long as the `&mut Self` temporarily
1500 // created is not overwritten, which it isn't here.
1501 unsafe { &mut self.get_unchecked_mut().store }
1502 }
1503
1504 fn memories_mut(
1505 self: Pin<&mut Self>,
1506 ) -> &mut TryPrimaryMap<DefinedMemoryIndex, (MemoryAllocationIndex, Memory)> {
1507 // SAFETY: see `store_mut` above.
1508 unsafe { &mut self.get_unchecked_mut().memories }
1509 }
1510
1511 pub(crate) fn tables_mut(
1512 self: Pin<&mut Self>,
1513 ) -> &mut TryPrimaryMap<DefinedTableIndex, (TableAllocationIndex, Table)> {
1514 // SAFETY: see `store_mut` above.
1515 unsafe { &mut self.get_unchecked_mut().tables }
1516 }
1517
1518 #[cfg(feature = "wmemcheck")]
1519 pub(super) fn wmemcheck_state_mut(self: Pin<&mut Self>) -> &mut Option<Wmemcheck> {
1520 // SAFETY: see `store_mut` above.
1521 unsafe { &mut self.get_unchecked_mut().wmemcheck_state }
1522 }
1523
1524 pub(crate) fn needs_startup(&self) -> bool {
1525 match self.env_module().startup {
1526 ModuleStartup::None => false,
1527 ModuleStartup::Always(_) => true,
1528 ModuleStartup::IfMemoriesNeedInit(_) => self
1529 .memories
1530 .iter()
1531 .any(|(_, (_, memory))| memory.needs_init()),
1532 }
1533 }
1534}
1535
1536// SAFETY: `layout` should describe this accurately and `OwnedVMContext` is the
1537// last field of `ComponentInstance`.
1538unsafe impl InstanceLayout for Instance {
1539 const INIT_ZEROED: bool = false;
1540 type VMContext = VMContext;
1541
1542 fn layout(&self) -> Layout {
1543 Self::alloc_layout(self.runtime_info.offsets())
1544 }
1545
1546 fn owned_vmctx(&self) -> &OwnedVMContext<VMContext> {
1547 &self.vmctx
1548 }
1549
1550 fn owned_vmctx_mut(&mut self) -> &mut OwnedVMContext<VMContext> {
1551 &mut self.vmctx
1552 }
1553}
1554
1555pub type InstanceHandle = OwnedInstance<Instance>;
1556
1557/// A handle holding an `Instance` of a WebAssembly module.
1558///
1559/// This structure is an owning handle of the `instance` contained internally.
1560/// When this value goes out of scope it will deallocate the `Instance` and all
1561/// memory associated with it.
1562///
1563/// Note that this lives within a `StoreOpaque` on a list of instances that a
1564/// store is keeping alive.
1565#[derive(Debug)]
1566#[repr(transparent)] // guarantee this is a zero-cost wrapper
1567pub struct OwnedInstance<T: InstanceLayout> {
1568 /// The raw pointer to the instance that was allocated.
1569 ///
1570 /// Note that this is not equivalent to `Box<Instance>` because the
1571 /// allocation here has a `VMContext` trailing after it. Thus the custom
1572 /// destructor to invoke the `dealloc` function with the appropriate
1573 /// layout.
1574 instance: SendSyncPtr<T>,
1575 _marker: marker::PhantomData<Box<(T, OwnedVMContext<T::VMContext>)>>,
1576}
1577
1578/// Structure that must be placed at the end of a type implementing
1579/// `InstanceLayout`.
1580#[repr(align(16))] // match the alignment of VMContext
1581pub struct OwnedVMContext<T> {
1582 /// A pointer to the `vmctx` field at the end of the `structure`.
1583 ///
1584 /// If you're looking at this a reasonable question would be "why do we need
1585 /// a pointer to ourselves?" because after all the pointer's value is
1586 /// trivially derivable from any `&Instance` pointer. The rationale for this
1587 /// field's existence is subtle, but it's required for correctness. The
1588 /// short version is "this makes miri happy".
1589 ///
1590 /// The long version of why this field exists is that the rules that MIRI
1591 /// uses to ensure pointers are used correctly have various conditions on
1592 /// them depend on how pointers are used. More specifically if `*mut T` is
1593 /// derived from `&mut T`, then that invalidates all prior pointers derived
1594 /// from the `&mut T`. This means that while we liberally want to re-acquire
1595 /// a `*mut VMContext` throughout the implementation of `Instance` the
1596 /// trivial way, a function `fn vmctx(Pin<&mut Instance>) -> *mut VMContext`
1597 /// would effectively invalidate all prior `*mut VMContext` pointers
1598 /// acquired. The purpose of this field is to serve as a sort of
1599 /// source-of-truth for where `*mut VMContext` pointers come from.
1600 ///
1601 /// This field is initialized when the `Instance` is created with the
1602 /// original allocation's pointer. That means that the provenance of this
1603 /// pointer contains the entire allocation (both instance and `VMContext`).
1604 /// This provenance bit is then "carried through" where `fn vmctx` will base
1605 /// all returned pointers on this pointer itself. This provides the means of
1606 /// never invalidating this pointer throughout MIRI and additionally being
1607 /// able to still temporarily have `Pin<&mut Instance>` methods and such.
1608 ///
1609 /// It's important to note, though, that this is not here purely for MIRI.
1610 /// The careful construction of the `fn vmctx` method has ramifications on
1611 /// the LLVM IR generated, for example. A historical CVE on Wasmtime,
1612 /// GHSA-ch89-5g45-qwc7, was caused due to relying on undefined behavior. By
1613 /// deriving VMContext pointers from this pointer it specifically hints to
1614 /// LLVM that trickery is afoot and it properly informs `noalias` and such
1615 /// annotations and analysis. More-or-less this pointer is actually loaded
1616 /// in LLVM IR which helps defeat otherwise present aliasing optimizations,
1617 /// which we want, since writes to this should basically never be optimized
1618 /// out.
1619 ///
1620 /// As a final note it's worth pointing out that the machine code generated
1621 /// for accessing `fn vmctx` is still as one would expect. This member isn't
1622 /// actually ever loaded at runtime (or at least shouldn't be). Perhaps in
1623 /// the future if the memory consumption of this field is a problem we could
1624 /// shrink it slightly, but for now one extra pointer per wasm instance
1625 /// seems not too bad.
1626 vmctx_self_reference: SendSyncPtr<T>,
1627
1628 /// This field ensures that going from `Pin<&mut T>` to `&mut T` is not a
1629 /// safe operation.
1630 _marker: core::marker::PhantomPinned,
1631}
1632
1633impl<T> OwnedVMContext<T> {
1634 /// Creates a new blank vmctx to place at the end of an instance.
1635 pub fn new() -> OwnedVMContext<T> {
1636 OwnedVMContext {
1637 vmctx_self_reference: SendSyncPtr::new(NonNull::dangling()),
1638 _marker: core::marker::PhantomPinned,
1639 }
1640 }
1641}
1642
1643/// Helper trait to plumb both core instances and component instances into
1644/// `OwnedInstance` below.
1645///
1646/// # Safety
1647///
1648/// This trait requires `layout` to correctly describe `Self` and appropriately
1649/// allocate space for `Self::VMContext` afterwards. Additionally the field
1650/// returned by `owned_vmctx()` must be the last field in the structure.
1651pub unsafe trait InstanceLayout {
1652 /// Whether or not to allocate this instance with `alloc_zeroed` or `alloc`.
1653 const INIT_ZEROED: bool;
1654
1655 /// The trailing `VMContext` type at the end of this instance.
1656 type VMContext;
1657
1658 /// The memory layout to use to allocate and deallocate this instance.
1659 fn layout(&self) -> Layout;
1660
1661 fn owned_vmctx(&self) -> &OwnedVMContext<Self::VMContext>;
1662 fn owned_vmctx_mut(&mut self) -> &mut OwnedVMContext<Self::VMContext>;
1663
1664 /// Returns the `vmctx_self_reference` set above.
1665 #[inline]
1666 fn vmctx(&self) -> NonNull<Self::VMContext> {
1667 // The definition of this method is subtle but intentional. The goal
1668 // here is that effectively this should return `&mut self.vmctx`, but
1669 // it's not quite so simple. Some more documentation is available on the
1670 // `vmctx_self_reference` field, but the general idea is that we're
1671 // creating a pointer to return with proper provenance. Provenance is
1672 // still in the works in Rust at the time of this writing but the load
1673 // of the `self.vmctx_self_reference` field is important here as it
1674 // affects how LLVM thinks about aliasing with respect to the returned
1675 // pointer.
1676 //
1677 // The intention of this method is to codegen to machine code as `&mut
1678 // self.vmctx`, however. While it doesn't show up like this in LLVM IR
1679 // (there's an actual load of the field) it does look like that by the
1680 // time the backend runs. (that's magic to me, the backend removing
1681 // loads...)
1682 let owned_vmctx = self.owned_vmctx();
1683 let owned_vmctx_raw = NonNull::from(owned_vmctx);
1684 // SAFETY: it's part of the contract of `InstanceLayout` and the usage
1685 // with `OwnedInstance` that this indeed points to the vmctx.
1686 let addr = unsafe { owned_vmctx_raw.add(1) };
1687 owned_vmctx
1688 .vmctx_self_reference
1689 .as_non_null()
1690 .with_addr(addr.addr())
1691 }
1692
1693 /// Helper function to access various locations offset from our `*mut
1694 /// VMContext` object.
1695 ///
1696 /// Note that this method takes `&self` as an argument but returns
1697 /// `NonNull<T>` which is frequently used to mutate said memory. This is an
1698 /// intentional design decision where the safety of the modification of
1699 /// memory is placed as a burden onto the caller. The implementation of this
1700 /// method explicitly does not require `&mut self` to acquire mutable
1701 /// provenance to update the `VMContext` region. Instead all pointers into
1702 /// the `VMContext` area have provenance/permissions to write.
1703 ///
1704 /// Also note though that care must be taken to ensure that reads/writes of
1705 /// memory must only happen where appropriate, for example a non-atomic
1706 /// write (as most are) should never happen concurrently with another read
1707 /// or write. It's generally on the burden of the caller to adhere to this.
1708 ///
1709 /// Also of note is that most of the time the usage of this method falls
1710 /// into one of:
1711 ///
1712 /// * Something in the VMContext is being read or written. In that case use
1713 /// `vmctx_plus_offset` or `vmctx_plus_offset_mut` if possible due to
1714 /// that having a safer lifetime.
1715 ///
1716 /// * A pointer is being created to pass to other VM* data structures. In
1717 /// that situation the lifetime of all VM data structures are typically
1718 /// tied to the `Store<T>` which is what provides the guarantees around
1719 /// concurrency/etc.
1720 ///
1721 /// There's quite a lot of unsafety riding on this method, especially
1722 /// related to the ascription `T` of the byte `offset`. It's hoped that in
1723 /// the future we're able to settle on an in theory safer design.
1724 ///
1725 /// # Safety
1726 ///
1727 /// This method is unsafe because the `offset` must be within bounds of the
1728 /// `VMContext` object trailing this instance. Additionally `T` must be a
1729 /// valid ascription of the value that resides at that location.
1730 unsafe fn vmctx_plus_offset_raw<T: VmSafe>(&self, offset: impl Into<u32>) -> NonNull<T> {
1731 // SAFETY: the safety requirements of `byte_add` are forwarded to this
1732 // method's caller.
1733 unsafe {
1734 self.vmctx()
1735 .byte_add(usize::try_from(offset.into()).unwrap())
1736 .cast()
1737 }
1738 }
1739
1740 /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of
1741 /// `&self` to the returned reference `&T`.
1742 ///
1743 /// # Safety
1744 ///
1745 /// See the safety documentation of `vmctx_plus_offset_raw`.
1746 unsafe fn vmctx_plus_offset<T: VmSafe>(&self, offset: impl Into<u32>) -> &T {
1747 // SAFETY: this method has the same safety requirements as
1748 // `vmctx_plus_offset_raw`.
1749 unsafe { self.vmctx_plus_offset_raw(offset).as_ref() }
1750 }
1751
1752 /// Helper above `vmctx_plus_offset_raw` which transfers the lifetime of
1753 /// `&mut self` to the returned reference `&mut T`.
1754 ///
1755 /// # Safety
1756 ///
1757 /// See the safety documentation of `vmctx_plus_offset_raw`.
1758 unsafe fn vmctx_plus_offset_mut<T: VmSafe>(
1759 self: Pin<&mut Self>,
1760 offset: impl Into<u32>,
1761 ) -> &mut T {
1762 // SAFETY: this method has the same safety requirements as
1763 // `vmctx_plus_offset_raw`.
1764 unsafe { self.vmctx_plus_offset_raw(offset).as_mut() }
1765 }
1766}
1767
1768impl<T: InstanceLayout> OwnedInstance<T> {
1769 /// Allocates a new `OwnedInstance` and places `instance` inside of it.
1770 ///
1771 /// This will `instance`
1772 pub(super) fn new(mut instance: T) -> Result<OwnedInstance<T>, OutOfMemory> {
1773 let layout = instance.layout();
1774 debug_assert!(layout.size() >= size_of_val(&instance));
1775 debug_assert!(layout.align() >= align_of_val(&instance));
1776
1777 // SAFETY: it's up to us to assert that `layout` has a non-zero size,
1778 // which is asserted here.
1779 let ptr = unsafe {
1780 assert!(layout.size() > 0);
1781 if T::INIT_ZEROED {
1782 alloc::alloc::alloc_zeroed(layout)
1783 } else {
1784 alloc::alloc::alloc(layout)
1785 }
1786 };
1787 let Some(instance_ptr) = NonNull::new(ptr.cast::<T>()) else {
1788 return Err(OutOfMemory::new(layout.size()));
1789 };
1790
1791 // SAFETY: it's part of the unsafe contract of `InstanceLayout` that the
1792 // `add` here is appropriate for the layout allocated.
1793 let vmctx_self_reference = unsafe { instance_ptr.add(1).cast() };
1794 instance.owned_vmctx_mut().vmctx_self_reference = vmctx_self_reference.into();
1795
1796 // SAFETY: we allocated above and it's an unsafe contract of
1797 // `InstanceLayout` that the layout is suitable for writing the
1798 // instance.
1799 unsafe {
1800 instance_ptr.write(instance);
1801 }
1802
1803 let ret = OwnedInstance {
1804 instance: SendSyncPtr::new(instance_ptr),
1805 _marker: marker::PhantomData,
1806 };
1807
1808 // Double-check various vmctx calculations are correct.
1809 debug_assert_eq!(
1810 vmctx_self_reference.addr(),
1811 // SAFETY: `InstanceLayout` should guarantee it's safe to add 1 to
1812 // the last field to get a pointer to 1-byte-past-the-end of an
1813 // object, which should be valid.
1814 unsafe { NonNull::from(ret.get().owned_vmctx()).add(1).addr() }
1815 );
1816 debug_assert_eq!(vmctx_self_reference.addr(), ret.get().vmctx().addr());
1817
1818 Ok(ret)
1819 }
1820
1821 /// Gets the raw underlying `&Instance` from this handle.
1822 pub fn get(&self) -> &T {
1823 // SAFETY: this is an owned instance handle that retains exclusive
1824 // ownership of the `Instance` inside. With `&self` given we know
1825 // this pointer is valid valid and the returned lifetime is connected
1826 // to `self` so that should also be valid.
1827 unsafe { self.instance.as_non_null().as_ref() }
1828 }
1829
1830 /// Same as [`Self::get`] except for mutability.
1831 pub fn get_mut(&mut self) -> Pin<&mut T> {
1832 // SAFETY: The lifetime concerns here are the same as `get` above.
1833 // Otherwise `new_unchecked` is used here to uphold the contract that
1834 // instances are always pinned in memory.
1835 unsafe { Pin::new_unchecked(self.instance.as_non_null().as_mut()) }
1836 }
1837}
1838
1839impl<T: InstanceLayout> Drop for OwnedInstance<T> {
1840 fn drop(&mut self) {
1841 unsafe {
1842 let layout = self.get().layout();
1843 ptr::drop_in_place(self.instance.as_ptr());
1844 alloc::alloc::dealloc(self.instance.as_ptr().cast(), layout);
1845 }
1846 }
1847}
1848
1849#[derive(Debug)]
1850pub(crate) struct PassiveElementSegment {
1851 needs_gc_rooting: bool,
1852 elements: TryVec<ValRaw>,
1853}
1854
1855impl PassiveElementSegment {
1856 /// Create a new passive element segment with the given capacity.
1857 pub(crate) fn new(ty: WasmRefType, capacity: usize) -> Result<Self, OutOfMemory> {
1858 let mut elements = TryVec::with_capacity(capacity)?;
1859 elements.resize_with(capacity, || ValRaw::null())?;
1860 Ok(Self {
1861 needs_gc_rooting: ty.is_vmgcref_type_and_not_i31(),
1862 elements,
1863 })
1864 }
1865
1866 /// Clear this segment's elements.
1867 pub(crate) fn clear(&mut self, mut gc_store: Option<&mut GcStore>) {
1868 let elements = mem::take(&mut self.elements);
1869 if !self.needs_gc_rooting {
1870 return;
1871 }
1872 for val in elements {
1873 // Like above, `anyref` accessors are used here even if this
1874 // element segment has a different type because all of the vmgcref
1875 // types are treated the same way.
1876 let gc_ref = val.get_anyref();
1877 debug_assert_eq!(gc_ref, val.get_exnref());
1878 debug_assert_eq!(gc_ref, val.get_externref());
1879 if let Some(gc_ref) = VMGcRef::from_raw_u32(gc_ref) {
1880 if let Some(gc_store) = gc_store.as_deref_mut() {
1881 let _ = gc_store.drop_gc_ref(gc_ref);
1882 }
1883 }
1884 }
1885 }
1886
1887 /// The elements of this segment.
1888 pub(crate) fn elements_mut(&mut self) -> &mut [ValRaw] {
1889 &mut self.elements
1890 }
1891}