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