Skip to main content

wasmtime/runtime/
vm.rs

1//! Runtime library support for Wasmtime.
2
3#![deny(missing_docs)]
4// See documentation in crates/wasmtime/src/runtime.rs for why this is
5// selectively enabled here.
6#![warn(clippy::cast_sign_loss)]
7
8// Polyfill `std::simd::i8x16` etc. until they're stable.
9#[cfg(all(target_arch = "x86_64", target_feature = "sse"))]
10#[expect(non_camel_case_types, reason = "matching wasm conventions")]
11pub(crate) type i8x16 = core::arch::x86_64::__m128i;
12#[cfg(all(target_arch = "x86_64", target_feature = "sse"))]
13#[expect(non_camel_case_types, reason = "matching wasm conventions")]
14pub(crate) type f32x4 = core::arch::x86_64::__m128;
15#[cfg(all(target_arch = "x86_64", target_feature = "sse"))]
16#[expect(non_camel_case_types, reason = "matching wasm conventions")]
17pub(crate) type f64x2 = core::arch::x86_64::__m128d;
18
19// On platforms other than x86_64, define i8x16 to a non-constructible type;
20// we need a type because we have a lot of macros for defining builtin
21// functions that are awkward to make conditional on the target, but it
22// doesn't need to actually be constructible unless we're on x86_64.
23#[cfg(not(all(target_arch = "x86_64", target_feature = "sse")))]
24#[expect(non_camel_case_types, reason = "matching wasm conventions")]
25#[derive(Copy, Clone)]
26pub(crate) struct i8x16(core::convert::Infallible);
27#[cfg(not(all(target_arch = "x86_64", target_feature = "sse")))]
28#[expect(non_camel_case_types, reason = "matching wasm conventions")]
29#[derive(Copy, Clone)]
30pub(crate) struct f32x4(core::convert::Infallible);
31#[cfg(not(all(target_arch = "x86_64", target_feature = "sse")))]
32#[expect(non_camel_case_types, reason = "matching wasm conventions")]
33#[derive(Copy, Clone)]
34pub(crate) struct f64x2(core::convert::Infallible);
35
36use crate::StoreContextMut;
37use crate::prelude::*;
38use crate::store::{StoreInner, StoreOpaque, StoreResourceLimiter};
39use crate::type_registry::RegisteredType;
40use alloc::sync::Arc;
41use core::fmt;
42use core::ops::{Deref, DerefMut};
43use core::pin::pin;
44use core::ptr::NonNull;
45use core::sync::atomic::{AtomicUsize, Ordering};
46use core::task::{Context, Poll, Waker};
47use wasmtime_environ::error::OutOfMemory;
48use wasmtime_environ::{DefinedMemoryIndex, HostPtr, VMOffsets, VMSharedTypeIndex};
49
50#[cfg(feature = "gc")]
51use wasmtime_environ::ModuleInternedTypeIndex;
52
53mod always_mut;
54#[cfg(feature = "component-model")]
55pub mod component;
56mod export;
57mod gc;
58mod imports;
59mod instance;
60mod memory;
61mod mmap_vec;
62#[cfg(has_virtual_memory)]
63mod pagemap_disabled;
64mod provenance;
65mod send_sync_ptr;
66mod stack_switching;
67mod store_box;
68mod sys;
69mod table;
70#[cfg(feature = "gc")]
71mod throw;
72mod traphandlers;
73mod vmcontext;
74
75#[cfg(feature = "threads")]
76mod parking_spot;
77
78// Note that `debug_builtins` here is disabled with a feature or a lack of a
79// native compilation backend because it's only here to assist in debugging
80// natively compiled code.
81#[cfg(all(has_host_compiler_backend, feature = "debug-builtins"))]
82pub mod debug_builtins;
83pub mod libcalls;
84pub mod mpk;
85
86#[cfg(feature = "pulley")]
87pub(crate) mod interpreter;
88#[cfg(not(feature = "pulley"))]
89pub(crate) mod interpreter_disabled;
90#[cfg(not(feature = "pulley"))]
91pub(crate) use interpreter_disabled as interpreter;
92
93#[cfg(feature = "debug-builtins")]
94pub use wasmtime_jit_debug::gdb_jit_int::GdbJitImageRegistration;
95
96pub use crate::runtime::vm::always_mut::*;
97pub use crate::runtime::vm::export::*;
98pub use crate::runtime::vm::gc::*;
99pub use crate::runtime::vm::imports::Imports;
100pub use crate::runtime::vm::instance::{
101    GcHeapAllocationIndex, Instance, InstanceAllocationRequest, InstanceAllocator, InstanceHandle,
102    MemoryAllocationIndex, OnDemandInstanceAllocator, TableAllocationIndex,
103};
104#[cfg(feature = "pooling-allocator")]
105pub use crate::runtime::vm::instance::{
106    InstanceLimits, PoolConcurrencyLimitError, PoolingAllocatorMetrics, PoolingInstanceAllocator,
107    PoolingInstanceAllocatorConfig,
108};
109pub use crate::runtime::vm::interpreter::*;
110pub use crate::runtime::vm::memory::{
111    Memory, MemoryBase, RuntimeLinearMemory, RuntimeMemoryCreator, SharedMemory,
112};
113pub use crate::runtime::vm::mmap_vec::MmapVec;
114pub use crate::runtime::vm::provenance::*;
115pub use crate::runtime::vm::stack_switching::*;
116pub use crate::runtime::vm::store_box::*;
117#[cfg(feature = "std")]
118pub use crate::runtime::vm::sys::mmap::open_file_for_mmap;
119#[cfg(has_host_compiler_backend)]
120pub use crate::runtime::vm::sys::unwind::UnwindRegistration;
121pub use crate::runtime::vm::table::{Table, TableElementType};
122#[cfg(feature = "gc")]
123pub use crate::runtime::vm::throw::*;
124pub use crate::runtime::vm::traphandlers::*;
125#[cfg(feature = "component-model")]
126pub use crate::runtime::vm::vmcontext::VMArrayCallFunction;
127pub use crate::runtime::vm::vmcontext::{
128    VMArrayCallHostFuncContext, VMContext, VMFuncRef, VMFunctionImport, VMGlobalDefinition,
129    VMGlobalImport, VMGlobalKind, VMMemoryDefinition, VMMemoryImport, VMOpaqueContext,
130    VMStoreContext, VMTableImport, VMTagImport, VMWasmCallFunction, ValRaw,
131};
132#[cfg(has_custom_sync)]
133pub(crate) use sys::capi;
134
135pub use send_sync_ptr::SendSyncPtr;
136pub use wasmtime_unwinder::Unwind;
137
138#[cfg(has_host_compiler_backend)]
139pub use wasmtime_unwinder::{UnwindHost, get_stack_pointer};
140
141mod module_id;
142pub use module_id::CompiledModuleId;
143
144#[cfg(has_virtual_memory)]
145mod byte_count;
146#[cfg(has_virtual_memory)]
147mod cow;
148#[cfg(not(has_virtual_memory))]
149mod cow_disabled;
150#[cfg(has_virtual_memory)]
151mod mmap;
152
153#[allow(unused, reason = "hard to cfg on/off, weird feature interactions")]
154mod send_sync_unsafe_cell;
155#[allow(unused, reason = "hard to cfg on/off, weird feature interactions")]
156pub use send_sync_unsafe_cell::SendSyncUnsafeCell;
157
158cfg_if::cfg_if! {
159    if #[cfg(has_virtual_memory)] {
160        pub use crate::runtime::vm::byte_count::*;
161        pub use crate::runtime::vm::mmap::{Mmap, MmapOffset};
162        pub use self::cow::{MemoryImage, MemoryImageSlot, ModuleMemoryImages};
163    } else {
164        pub use self::cow_disabled::{MemoryImage, MemoryImageSlot, ModuleMemoryImages};
165    }
166}
167
168/// Source of data used for [`MemoryImage`]
169pub trait ModuleMemoryImageSource: Send + Sync + 'static {
170    /// Returns this image's slice of all wasm data for a module which is then
171    /// further sub-sliced for a particular initialization segment.
172    fn wasm_data(&self) -> &[u8];
173
174    /// Optionally returns the backing mmap. Used for using the backing mmap's
175    /// file to perform other mmaps, for example.
176    fn mmap(&self) -> Option<&MmapVec>;
177}
178
179/// Dynamic runtime functionality needed by this crate throughout the execution
180/// of a wasm instance.
181///
182/// This trait is used to store a raw pointer trait object within each
183/// `VMContext`. This raw pointer trait object points back to the
184/// `wasmtime::Store` internally but is type-erased to avoid needing to
185/// monomorphize the entire runtime on the `T` in `Store<T>`
186///
187/// # Safety
188///
189/// This trait should be implemented by nothing other than `StoreInner<T>` in
190/// this crate. It's not sound to implement it for anything else due to
191/// `unchecked_context_mut` below.
192///
193/// It's also worth nothing that there are various locations where a `*mut dyn
194/// VMStore` is asserted to be both `Send` and `Sync` which disregards the `T`
195/// that's actually stored in the store itself. It's assume that the high-level
196/// APIs using `Store<T>` are correctly inferring send/sync on the returned
197/// values (e.g. futures) and that internally in the runtime we aren't doing
198/// anything "weird" with threads for example.
199pub unsafe trait VMStore: 'static {
200    /// Get a shared borrow of this store's `StoreOpaque`.
201    fn store_opaque(&self) -> &StoreOpaque;
202
203    /// Get an exclusive borrow of this store's `StoreOpaque`.
204    fn store_opaque_mut(&mut self) -> &mut StoreOpaque;
205
206    /// Returns a split borrow to the limiter plus `StoreOpaque` at the same
207    /// time.
208    fn resource_limiter_and_store_opaque(
209        &mut self,
210    ) -> (Option<StoreResourceLimiter<'_>>, &mut StoreOpaque);
211
212    /// Callback invoked whenever an instance observes a new epoch
213    /// number. Cannot fail; cooperative epoch-based yielding is
214    /// completely semantically transparent. Returns the new deadline.
215    #[cfg(target_has_atomic = "64")]
216    fn new_epoch_updated_deadline(&mut self) -> Result<crate::UpdateDeadline>;
217
218    /// Metadata required for resources for the component model.
219    #[cfg(feature = "component-model")]
220    fn component_task_state_mut(&mut self) -> &mut crate::component::store::ComponentTaskState;
221
222    #[cfg(feature = "component-model-async")]
223    fn component_async_store(
224        &mut self,
225    ) -> &mut dyn crate::runtime::component::VMComponentAsyncStore;
226
227    /// Invoke a debug handler, if present, at a debug event.
228    #[cfg(feature = "debug")]
229    fn block_on_debug_handler(&mut self, event: crate::DebugEvent) -> crate::Result<()>;
230}
231
232impl Deref for dyn VMStore + '_ {
233    type Target = StoreOpaque;
234
235    fn deref(&self) -> &Self::Target {
236        self.store_opaque()
237    }
238}
239
240impl DerefMut for dyn VMStore + '_ {
241    fn deref_mut(&mut self) -> &mut Self::Target {
242        self.store_opaque_mut()
243    }
244}
245
246impl dyn VMStore + '_ {
247    /// Asserts that this `VMStore` was originally paired with `StoreInner<T>`
248    /// and then casts to the `StoreContextMut` type.
249    ///
250    /// # Unsafety
251    ///
252    /// This method is not safe as there's no static guarantee that `T` is
253    /// correct for this store.
254    pub(crate) unsafe fn unchecked_context_mut<T>(&mut self) -> StoreContextMut<'_, T> {
255        unsafe { StoreContextMut(&mut *(self as *mut dyn VMStore as *mut StoreInner<T>)) }
256    }
257}
258
259/// A newtype wrapper around `NonNull<dyn VMStore>` intended to be a
260/// self-pointer back to the `Store<T>` within raw data structures like
261/// `VMContext`.
262///
263/// This type exists to manually, and unsafely, implement `Send` and `Sync`.
264/// The `VMStore` trait doesn't require `Send` or `Sync` which means this isn't
265/// naturally either trait (e.g. with `SendSyncPtr` instead). Note that this
266/// means that `Instance` is, for example, mistakenly considered
267/// unconditionally `Send` and `Sync`. This is hopefully ok for now though
268/// because from a user perspective the only type that matters is `Store<T>`.
269/// That type is `Send + Sync` if `T: Send + Sync` already so the internal
270/// storage of `Instance` shouldn't matter as the final result is the same.
271/// Note though that this means we need to be extra vigilant about cross-thread
272/// usage of `Instance` and `ComponentInstance` for example.
273#[derive(Copy, Clone)]
274#[repr(transparent)]
275struct VMStoreRawPtr(pub NonNull<dyn VMStore>);
276
277// SAFETY: this is the purpose of `VMStoreRawPtr`, see docs above about safe
278// usage.
279unsafe impl Send for VMStoreRawPtr {}
280unsafe impl Sync for VMStoreRawPtr {}
281
282/// Functionality required by this crate for a particular module. This is
283/// chiefly needed for lazy initialization of various bits of instance state.
284#[derive(Clone)]
285pub enum ModuleRuntimeInfo {
286    Module(crate::Module),
287    Bare(Arc<BareModuleInfo>),
288}
289
290/// A barebones implementation of ModuleRuntimeInfo that is useful for
291/// cases where a purpose-built environ::Module is used and a full
292/// CompiledModule does not exist (for example, for tests or for the
293/// default-callee instance).
294#[derive(Clone)]
295pub struct BareModuleInfo {
296    module: Arc<wasmtime_environ::Module>,
297    offsets: VMOffsets<HostPtr>,
298    _registered_type: Option<RegisteredType>,
299}
300
301impl ModuleRuntimeInfo {
302    pub(crate) fn bare(module: Arc<wasmtime_environ::Module>) -> Result<Self, OutOfMemory> {
303        ModuleRuntimeInfo::bare_with_registered_type(module, None)
304    }
305
306    pub(crate) fn bare_with_registered_type(
307        module: Arc<wasmtime_environ::Module>,
308        registered_type: Option<RegisteredType>,
309    ) -> Result<Self, OutOfMemory> {
310        let info = try_new(BareModuleInfo {
311            offsets: VMOffsets::new(HostPtr, &module),
312            module,
313            _registered_type: registered_type,
314        })?;
315        Ok(ModuleRuntimeInfo::Bare(info))
316    }
317
318    /// The underlying Module.
319    pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
320        match self {
321            ModuleRuntimeInfo::Module(m) => m.env_module(),
322            ModuleRuntimeInfo::Bare(b) => &b.module,
323        }
324    }
325
326    /// Translate a module-level interned type index into an engine-level
327    /// interned type index.
328    #[cfg(feature = "gc")]
329    fn engine_type_index(&self, module_index: ModuleInternedTypeIndex) -> VMSharedTypeIndex {
330        match self {
331            ModuleRuntimeInfo::Module(m) => m
332                .engine_code()
333                .signatures()
334                .shared_type(module_index)
335                .expect("bad module-level interned type index"),
336            ModuleRuntimeInfo::Bare(_) => unreachable!(),
337        }
338    }
339
340    /// Returns the `MemoryImage` structure used for copy-on-write
341    /// initialization of the memory, if it's applicable.
342    fn memory_image(&self, memory: DefinedMemoryIndex) -> crate::Result<Option<&Arc<MemoryImage>>> {
343        match self {
344            ModuleRuntimeInfo::Module(m) => {
345                let images = m.memory_images()?;
346                Ok(images.and_then(|images| images.get_memory_image(memory)))
347            }
348            ModuleRuntimeInfo::Bare(_) => Ok(None),
349        }
350    }
351
352    /// A unique ID for this particular module. This can be used to
353    /// allow for fastpaths to optimize a "re-instantiate the same
354    /// module again" case.
355    #[cfg(feature = "pooling-allocator")]
356    fn unique_id(&self) -> Option<CompiledModuleId> {
357        match self {
358            ModuleRuntimeInfo::Module(m) => Some(m.id()),
359            ModuleRuntimeInfo::Bare(_) => None,
360        }
361    }
362
363    /// A slice pointing to all data that is referenced by this instance.
364    fn wasm_data(&self) -> &[u8] {
365        match self {
366            ModuleRuntimeInfo::Module(m) => m.engine_code().wasm_data(),
367            ModuleRuntimeInfo::Bare(_) => &[],
368        }
369    }
370
371    /// Returns an array, indexed by `ModuleInternedTypeIndex` of all
372    /// `VMSharedSignatureIndex` entries corresponding to the `SignatureIndex`.
373    fn type_ids(&self) -> &[VMSharedTypeIndex] {
374        match self {
375            ModuleRuntimeInfo::Module(m) => m
376                .engine_code()
377                .signatures()
378                .as_module_map()
379                .values()
380                .as_slice(),
381            ModuleRuntimeInfo::Bare(_) => &[],
382        }
383    }
384
385    /// Offset information for the current host.
386    pub(crate) fn offsets(&self) -> &VMOffsets<HostPtr> {
387        match self {
388            ModuleRuntimeInfo::Module(m) => m.offsets(),
389            ModuleRuntimeInfo::Bare(b) => &b.offsets,
390        }
391    }
392}
393
394/// Returns the host OS page size, in bytes.
395#[cfg(has_virtual_memory)]
396pub fn host_page_size() -> usize {
397    // NB: this function is duplicated in `crates/fiber/src/unix.rs` so if this
398    // changes that should probably get updated as well.
399    static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
400
401    return match PAGE_SIZE.load(Ordering::Relaxed) {
402        0 => {
403            let size = sys::vm::get_page_size();
404            assert!(size != 0);
405            PAGE_SIZE.store(size, Ordering::Relaxed);
406            size
407        }
408        n => n,
409    };
410}
411
412/// Result of `Memory::atomic_wait32` and `Memory::atomic_wait64`
413#[derive(Copy, Clone, PartialEq, Eq, Debug)]
414pub enum WaitResult {
415    /// Indicates that a `wait` completed by being awoken by a different thread.
416    /// This means the thread went to sleep and didn't time out.
417    Ok = 0,
418    /// Indicates that `wait` did not complete and instead returned due to the
419    /// value in memory not matching the expected value.
420    Mismatch = 1,
421    /// Indicates that `wait` completed with a timeout, meaning that the
422    /// original value matched as expected but nothing ever called `notify`.
423    TimedOut = 2,
424}
425
426/// Description about a fault that occurred in WebAssembly.
427#[derive(Debug)]
428pub struct WasmFault {
429    /// The size of memory, in bytes, at the time of the fault.
430    pub memory_size: usize,
431    /// The WebAssembly address at which the fault occurred.
432    pub wasm_address: u64,
433}
434
435impl fmt::Display for WasmFault {
436    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437        write!(
438            f,
439            "memory fault at wasm address 0x{:x} in linear memory of size 0x{:x}",
440            self.wasm_address, self.memory_size,
441        )
442    }
443}
444
445/// Asserts that the future `f` is ready and returns its output.
446///
447/// This function is intended to be used with `Store::validate_sync_call`.
448/// Internals of Wasmtime are generally `async` when they optionally can be,
449/// meaning that synchronous entrypoints will invoke this function after
450/// invoking the asynchronous internals. The `validate_sync_call` method
451/// ensures that during this `async` function call there won't actually be any
452/// yield points. If a yield point could possibly happen, then
453/// `validate_sync_call` will fail.
454///
455/// If `validate_sync_call` passes, then this function is an extra assert that
456/// yes, indeed, we coded everything correctly in Wasmtime and there shouldn't
457/// be any yield points in the future provided, so its result should be ready
458/// immediately.
459///
460/// # Panics
461///
462/// Panics if `f` is not yet ready.
463pub fn assert_ready<F: Future>(f: F) -> F::Output {
464    one_poll(f).unwrap()
465}
466
467/// Attempts one poll of `f` to see if its output is available.
468///
469/// This function is intended for a few minor entrypoints into the Wasmtime API
470/// where a synchronous function is documented to work even when `async_support`
471/// is enabled. For example growing a `Memory` can be done with a synchronous
472/// function, but it's documented to panic with an async resource limiter.
473///
474/// This function provides the opportunity to poll `f` once to see if its output
475/// is available. If it isn't then `None` is returned and an appropriate panic
476/// message should be generated recommending to use an async function (e.g.
477/// `grow_async` instead of `grow`).
478fn one_poll<F: Future>(f: F) -> Option<F::Output> {
479    let mut context = Context::from_waker(&Waker::noop());
480    match pin!(f).poll(&mut context) {
481        Poll::Ready(output) => Some(output),
482        Poll::Pending => None,
483    }
484}