1#![deny(missing_docs)]
4#![warn(clippy::cast_sign_loss)]
7
8#[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#[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#[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 = "component-model-async")]
94pub(crate) use sys::{component_async_tls_get, component_async_tls_set};
95
96#[cfg(feature = "debug-builtins")]
97pub use wasmtime_jit_debug::gdb_jit_int::GdbJitImageRegistration;
98
99pub use crate::runtime::vm::always_mut::*;
100pub use crate::runtime::vm::export::*;
101pub use crate::runtime::vm::gc::*;
102pub use crate::runtime::vm::imports::Imports;
103pub use crate::runtime::vm::instance::{
104 GcHeapAllocationIndex, Instance, InstanceAllocationRequest, InstanceAllocator, InstanceHandle,
105 MemoryAllocationIndex, OnDemandInstanceAllocator, TableAllocationIndex,
106};
107#[cfg(feature = "pooling-allocator")]
108pub use crate::runtime::vm::instance::{
109 PoolConcurrencyLimitError, PoolingAllocatorMetrics, PoolingInstanceAllocator,
110};
111pub use crate::runtime::vm::interpreter::*;
112pub use crate::runtime::vm::memory::{
113 Memory, MemoryBase, RuntimeLinearMemory, RuntimeMemoryCreator, SharedMemory,
114};
115pub use crate::runtime::vm::mmap_vec::MmapVec;
116pub use crate::runtime::vm::provenance::*;
117pub use crate::runtime::vm::stack_switching::*;
118pub use crate::runtime::vm::store_box::*;
119#[cfg(feature = "std")]
120pub use crate::runtime::vm::sys::mmap::open_file_for_mmap;
121#[cfg(has_host_compiler_backend)]
122pub use crate::runtime::vm::sys::unwind::UnwindRegistration;
123pub use crate::runtime::vm::table::{Table, TableElementType};
124#[cfg(feature = "gc")]
125pub use crate::runtime::vm::throw::*;
126pub use crate::runtime::vm::traphandlers::*;
127#[cfg(feature = "component-model")]
128pub use crate::runtime::vm::vmcontext::VMArrayCallFunction;
129#[cfg(feature = "component-model-async")]
130pub use crate::runtime::vm::vmcontext::VMLazyThread;
131pub use crate::runtime::vm::vmcontext::{
132 VMArrayCallHostFuncContext, VMContext, VMFuncRef, VMFunctionImport, VMGlobalDefinition,
133 VMGlobalImport, VMGlobalKind, VMMemoryDefinition, VMMemoryImport, VMOpaqueContext,
134 VMStoreContext, VMTableImport, VMTagImport, VMWasmCallFunction, ValRaw,
135};
136#[cfg(has_custom_sync)]
137pub(crate) use sys::capi;
138
139pub use send_sync_ptr::SendSyncPtr;
140pub use wasmtime_unwinder::Unwind;
141
142#[cfg(has_host_compiler_backend)]
143pub use wasmtime_unwinder::{UnwindHost, get_stack_pointer};
144
145mod module_id;
146pub use module_id::CompiledModuleId;
147
148#[cfg(has_virtual_memory)]
149mod byte_count;
150#[cfg(has_virtual_memory)]
151mod cow;
152#[cfg(not(has_virtual_memory))]
153mod cow_disabled;
154#[cfg(has_virtual_memory)]
155mod mmap;
156
157#[allow(unused, reason = "hard to cfg on/off, weird feature interactions")]
158mod send_sync_unsafe_cell;
159#[allow(unused, reason = "hard to cfg on/off, weird feature interactions")]
160pub use send_sync_unsafe_cell::SendSyncUnsafeCell;
161
162cfg_select! {
163 has_virtual_memory => {
164 pub use crate::runtime::vm::byte_count::*;
165 pub use crate::runtime::vm::mmap::{Mmap, MmapOffset};
166 pub use self::cow::{MemoryImage, MemoryImageSlot, ModuleMemoryImages};
167 }
168 _ => {
169 pub use self::cow_disabled::{MemoryImage, MemoryImageSlot, ModuleMemoryImages};
170 }
171}
172
173pub trait ModuleMemoryImageSource: Send + Sync + 'static {
175 fn wasm_data(&self) -> &[u8];
178
179 fn mmap(&self) -> Option<&MmapVec>;
182}
183
184pub unsafe trait VMStore: 'static {
205 fn store_opaque(&self) -> &StoreOpaque;
207
208 fn store_opaque_mut(&mut self) -> &mut StoreOpaque;
210
211 fn resource_limiter_and_store_opaque(
214 &mut self,
215 ) -> (Option<StoreResourceLimiter<'_>>, &mut StoreOpaque);
216
217 #[cfg(feature = "call-hook")]
220 fn call_hook(&mut self, s: crate::CallHook) -> Result<()>;
221
222 #[cfg(target_has_atomic = "64")]
226 fn new_epoch_updated_deadline(&mut self) -> Result<crate::UpdateDeadline>;
227
228 #[cfg(feature = "component-model-async")]
229 fn component_async_store(
230 &mut self,
231 ) -> &mut dyn crate::runtime::component::VMComponentAsyncStore;
232
233 #[cfg(feature = "debug")]
235 fn block_on_debug_handler(&mut self, event: crate::DebugEvent) -> crate::Result<()>;
236}
237
238impl Deref for dyn VMStore + '_ {
239 type Target = StoreOpaque;
240
241 fn deref(&self) -> &Self::Target {
242 self.store_opaque()
243 }
244}
245
246impl DerefMut for dyn VMStore + '_ {
247 fn deref_mut(&mut self) -> &mut Self::Target {
248 self.store_opaque_mut()
249 }
250}
251
252impl dyn VMStore + '_ {
253 pub(crate) unsafe fn unchecked_context_mut<T>(&mut self) -> StoreContextMut<'_, T> {
261 unsafe { StoreContextMut(&mut *(self as *mut dyn VMStore as *mut StoreInner<T>)) }
262 }
263}
264
265#[derive(Copy, Clone)]
280#[repr(transparent)]
281struct VMStoreRawPtr(pub NonNull<dyn VMStore>);
282
283unsafe impl Send for VMStoreRawPtr {}
286unsafe impl Sync for VMStoreRawPtr {}
287
288#[derive(Clone)]
291pub enum ModuleRuntimeInfo {
292 Module(crate::Module),
293 Bare(Arc<BareModuleInfo>),
294}
295
296pub struct BareModuleInfo {
301 module: Arc<wasmtime_environ::Module>,
302 offsets: VMOffsets<HostPtr>,
303 _registered_types: TryVec<RegisteredType>,
304}
305
306impl ModuleRuntimeInfo {
307 pub(crate) fn bare(module: Arc<wasmtime_environ::Module>) -> Result<Self, OutOfMemory> {
308 ModuleRuntimeInfo::bare_with_registered_types(module, None)
309 }
310
311 pub(crate) fn bare_with_registered_types(
312 module: Arc<wasmtime_environ::Module>,
313 registered_types: impl IntoIterator<Item = RegisteredType>,
314 ) -> Result<Self, OutOfMemory> {
315 let info = try_new(BareModuleInfo {
316 offsets: VMOffsets::new(HostPtr, &module),
317 module,
318 _registered_types: registered_types.into_iter().try_collect()?,
319 })?;
320 Ok(ModuleRuntimeInfo::Bare(info))
321 }
322
323 pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
325 match self {
326 ModuleRuntimeInfo::Module(m) => m.env_module(),
327 ModuleRuntimeInfo::Bare(b) => &b.module,
328 }
329 }
330
331 #[cfg(feature = "gc")]
334 fn engine_type_index(&self, module_index: ModuleInternedTypeIndex) -> VMSharedTypeIndex {
335 match self {
336 ModuleRuntimeInfo::Module(m) => m
337 .engine_code()
338 .signatures()
339 .shared_type(module_index)
340 .expect("bad module-level interned type index"),
341 ModuleRuntimeInfo::Bare(_) => unreachable!(),
342 }
343 }
344
345 fn memory_image(&self, memory: DefinedMemoryIndex) -> crate::Result<Option<&Arc<MemoryImage>>> {
348 match self {
349 ModuleRuntimeInfo::Module(m) => {
350 let images = m.memory_images()?;
351 Ok(images.and_then(|images| images.get_memory_image(memory)))
352 }
353 ModuleRuntimeInfo::Bare(_) => Ok(None),
354 }
355 }
356
357 #[cfg(feature = "pooling-allocator")]
361 fn unique_id(&self) -> Option<CompiledModuleId> {
362 match self {
363 ModuleRuntimeInfo::Module(m) => Some(m.id()),
364 ModuleRuntimeInfo::Bare(_) => None,
365 }
366 }
367
368 fn wasm_data(&self) -> &[u8] {
370 match self {
371 ModuleRuntimeInfo::Module(m) => m.engine_code().wasm_data(),
372 ModuleRuntimeInfo::Bare(_) => &[],
373 }
374 }
375
376 fn type_ids(&self) -> &[VMSharedTypeIndex] {
379 match self {
380 ModuleRuntimeInfo::Module(m) => m
381 .engine_code()
382 .signatures()
383 .as_module_map()
384 .values()
385 .as_slice(),
386 ModuleRuntimeInfo::Bare(_) => &[],
387 }
388 }
389
390 pub(crate) fn offsets(&self) -> &VMOffsets<HostPtr> {
392 match self {
393 ModuleRuntimeInfo::Module(m) => m.offsets(),
394 ModuleRuntimeInfo::Bare(b) => &b.offsets,
395 }
396 }
397}
398
399#[cfg(has_virtual_memory)]
401pub fn host_page_size() -> usize {
402 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
405
406 return match PAGE_SIZE.load(Ordering::Relaxed) {
407 0 => {
408 let size = sys::vm::get_page_size();
409 assert!(size != 0);
410 PAGE_SIZE.store(size, Ordering::Relaxed);
411 size
412 }
413 n => n,
414 };
415}
416
417#[derive(Copy, Clone, PartialEq, Eq, Debug)]
419pub enum WaitResult {
420 Ok = 0,
423 Mismatch = 1,
426 TimedOut = 2,
429}
430
431#[derive(Debug)]
433pub struct WasmFault {
434 pub memory_size: usize,
436 pub wasm_address: u64,
438}
439
440impl fmt::Display for WasmFault {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 write!(
443 f,
444 "memory fault at wasm address 0x{:x} in linear memory of size 0x{:x}",
445 self.wasm_address, self.memory_size,
446 )
447 }
448}
449
450pub fn assert_ready<F: Future>(f: F) -> F::Output {
469 one_poll(f).unwrap()
470}
471
472fn one_poll<F: Future>(f: F) -> Option<F::Output> {
484 let mut context = Context::from_waker(&Waker::noop());
485 match pin!(f).poll(&mut context) {
486 Poll::Ready(output) => Some(output),
487 Poll::Pending => None,
488 }
489}