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(crate::uninhabited::Uninhabited);
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(crate::uninhabited::Uninhabited);
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(crate::uninhabited::Uninhabited);
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::{
48 DefinedFuncIndex, DefinedMemoryIndex, HostPtr, VMOffsets, VMSharedTypeIndex,
49};
50
51#[cfg(feature = "gc")]
52use wasmtime_environ::ModuleInternedTypeIndex;
53
54mod always_mut;
55#[cfg(feature = "component-model")]
56pub mod component;
57mod const_expr;
58mod export;
59mod gc;
60mod imports;
61mod instance;
62mod memory;
63mod mmap_vec;
64#[cfg(has_virtual_memory)]
65mod pagemap_disabled;
66mod provenance;
67mod send_sync_ptr;
68mod stack_switching;
69mod store_box;
70mod sys;
71mod table;
72#[cfg(feature = "gc")]
73mod throw;
74mod traphandlers;
75mod vmcontext;
76
77#[cfg(feature = "threads")]
78mod parking_spot;
79
80#[cfg(all(has_host_compiler_backend, feature = "debug-builtins"))]
84pub mod debug_builtins;
85pub mod libcalls;
86pub mod mpk;
87
88#[cfg(feature = "pulley")]
89pub(crate) mod interpreter;
90#[cfg(not(feature = "pulley"))]
91pub(crate) mod interpreter_disabled;
92#[cfg(not(feature = "pulley"))]
93pub(crate) use interpreter_disabled as interpreter;
94
95#[cfg(feature = "debug-builtins")]
96pub use wasmtime_jit_debug::gdb_jit_int::GdbJitImageRegistration;
97
98pub use crate::runtime::vm::always_mut::*;
99pub use crate::runtime::vm::export::*;
100pub use crate::runtime::vm::gc::*;
101pub use crate::runtime::vm::imports::Imports;
102pub use crate::runtime::vm::instance::{
103 GcHeapAllocationIndex, Instance, InstanceAllocationRequest, InstanceAllocator, InstanceHandle,
104 MemoryAllocationIndex, OnDemandInstanceAllocator, TableAllocationIndex, initialize_instance,
105};
106#[cfg(feature = "pooling-allocator")]
107pub use crate::runtime::vm::instance::{
108 InstanceLimits, PoolConcurrencyLimitError, PoolingAllocatorMetrics, PoolingInstanceAllocator,
109 PoolingInstanceAllocatorConfig,
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::*;
127pub use crate::runtime::vm::vmcontext::{
128 VMArrayCallFunction, VMArrayCallHostFuncContext, VMContext, VMFuncRef, VMFunctionImport,
129 VMGlobalDefinition, VMGlobalImport, VMGlobalKind, VMMemoryDefinition, VMMemoryImport,
130 VMOpaqueContext, 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#[cfg(feature = "async")]
154mod async_yield;
155#[cfg(feature = "async")]
156pub use crate::runtime::vm::async_yield::*;
157
158#[cfg(feature = "gc-null")]
159mod send_sync_unsafe_cell;
160#[cfg(feature = "gc-null")]
161pub use send_sync_unsafe_cell::SendSyncUnsafeCell;
162
163cfg_if::cfg_if! {
164 if #[cfg(has_virtual_memory)] {
165 pub use crate::runtime::vm::byte_count::*;
166 pub use crate::runtime::vm::mmap::{Mmap, MmapOffset};
167 pub use self::cow::{MemoryImage, MemoryImageSlot, ModuleMemoryImages};
168 } else {
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(target_has_atomic = "64")]
221 fn new_epoch_updated_deadline(&mut self) -> Result<crate::UpdateDeadline>;
222
223 #[cfg(feature = "component-model")]
225 fn component_calls(&mut self) -> &mut component::CallContexts;
226
227 #[cfg(feature = "component-model-async")]
228 fn component_async_store(
229 &mut self,
230 ) -> &mut dyn crate::runtime::component::VMComponentAsyncStore;
231
232 #[cfg(feature = "debug")]
234 fn block_on_debug_handler(&mut self, event: crate::DebugEvent) -> anyhow::Result<()>;
235}
236
237impl Deref for dyn VMStore + '_ {
238 type Target = StoreOpaque;
239
240 fn deref(&self) -> &Self::Target {
241 self.store_opaque()
242 }
243}
244
245impl DerefMut for dyn VMStore + '_ {
246 fn deref_mut(&mut self) -> &mut Self::Target {
247 self.store_opaque_mut()
248 }
249}
250
251impl dyn VMStore + '_ {
252 pub(crate) unsafe fn unchecked_context_mut<T>(&mut self) -> StoreContextMut<'_, T> {
260 unsafe { StoreContextMut(&mut *(self as *mut dyn VMStore as *mut StoreInner<T>)) }
261 }
262}
263
264#[derive(Copy, Clone)]
279#[repr(transparent)]
280struct VMStoreRawPtr(pub NonNull<dyn VMStore>);
281
282unsafe impl Send for VMStoreRawPtr {}
285unsafe impl Sync for VMStoreRawPtr {}
286
287#[derive(Clone)]
301pub enum ModuleRuntimeInfo {
302 Module(crate::Module),
303 Bare(Box<BareModuleInfo>),
304}
305
306#[derive(Clone)]
311pub struct BareModuleInfo {
312 module: Arc<wasmtime_environ::Module>,
313 offsets: VMOffsets<HostPtr>,
314 _registered_type: Option<RegisteredType>,
315}
316
317impl ModuleRuntimeInfo {
318 pub(crate) fn bare(module: Arc<wasmtime_environ::Module>) -> Self {
319 ModuleRuntimeInfo::bare_with_registered_type(module, None)
320 }
321
322 pub(crate) fn bare_with_registered_type(
323 module: Arc<wasmtime_environ::Module>,
324 registered_type: Option<RegisteredType>,
325 ) -> Self {
326 ModuleRuntimeInfo::Bare(Box::new(BareModuleInfo {
327 offsets: VMOffsets::new(HostPtr, &module),
328 module,
329 _registered_type: registered_type,
330 }))
331 }
332
333 pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
335 match self {
336 ModuleRuntimeInfo::Module(m) => m.env_module(),
337 ModuleRuntimeInfo::Bare(b) => &b.module,
338 }
339 }
340
341 #[cfg(feature = "gc")]
344 fn engine_type_index(&self, module_index: ModuleInternedTypeIndex) -> VMSharedTypeIndex {
345 match self {
346 ModuleRuntimeInfo::Module(m) => m
347 .code_object()
348 .signatures()
349 .shared_type(module_index)
350 .expect("bad module-level interned type index"),
351 ModuleRuntimeInfo::Bare(_) => unreachable!(),
352 }
353 }
354
355 fn function(&self, index: DefinedFuncIndex) -> NonNull<VMWasmCallFunction> {
357 let module = match self {
358 ModuleRuntimeInfo::Module(m) => m,
359 ModuleRuntimeInfo::Bare(_) => unreachable!(),
360 };
361 let ptr = module
362 .compiled_module()
363 .finished_function(index)
364 .as_ptr()
365 .cast::<VMWasmCallFunction>()
366 .cast_mut();
367 NonNull::new(ptr).unwrap()
368 }
369
370 fn array_to_wasm_trampoline(
376 &self,
377 index: DefinedFuncIndex,
378 ) -> Option<NonNull<VMArrayCallFunction>> {
379 let m = match self {
380 ModuleRuntimeInfo::Module(m) => m,
381 ModuleRuntimeInfo::Bare(_) => unreachable!(),
382 };
383 let ptr = NonNull::from(m.compiled_module().array_to_wasm_trampoline(index)?);
384 Some(ptr.cast())
385 }
386
387 fn memory_image(
390 &self,
391 memory: DefinedMemoryIndex,
392 ) -> anyhow::Result<Option<&Arc<MemoryImage>>> {
393 match self {
394 ModuleRuntimeInfo::Module(m) => {
395 let images = m.memory_images()?;
396 Ok(images.and_then(|images| images.get_memory_image(memory)))
397 }
398 ModuleRuntimeInfo::Bare(_) => Ok(None),
399 }
400 }
401
402 #[cfg(feature = "pooling-allocator")]
406 fn unique_id(&self) -> Option<CompiledModuleId> {
407 match self {
408 ModuleRuntimeInfo::Module(m) => Some(m.id()),
409 ModuleRuntimeInfo::Bare(_) => None,
410 }
411 }
412
413 fn wasm_data(&self) -> &[u8] {
415 match self {
416 ModuleRuntimeInfo::Module(m) => m.compiled_module().code_memory().wasm_data(),
417 ModuleRuntimeInfo::Bare(_) => &[],
418 }
419 }
420
421 fn type_ids(&self) -> &[VMSharedTypeIndex] {
424 match self {
425 ModuleRuntimeInfo::Module(m) => m
426 .code_object()
427 .signatures()
428 .as_module_map()
429 .values()
430 .as_slice(),
431 ModuleRuntimeInfo::Bare(_) => &[],
432 }
433 }
434
435 pub(crate) fn offsets(&self) -> &VMOffsets<HostPtr> {
437 match self {
438 ModuleRuntimeInfo::Module(m) => m.offsets(),
439 ModuleRuntimeInfo::Bare(b) => &b.offsets,
440 }
441 }
442}
443
444#[cfg(has_virtual_memory)]
446pub fn host_page_size() -> usize {
447 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
450
451 return match PAGE_SIZE.load(Ordering::Relaxed) {
452 0 => {
453 let size = sys::vm::get_page_size();
454 assert!(size != 0);
455 PAGE_SIZE.store(size, Ordering::Relaxed);
456 size
457 }
458 n => n,
459 };
460}
461
462#[derive(Copy, Clone, PartialEq, Eq, Debug)]
464pub enum WaitResult {
465 Ok = 0,
468 Mismatch = 1,
471 TimedOut = 2,
474}
475
476#[derive(Debug)]
478pub struct WasmFault {
479 pub memory_size: usize,
481 pub wasm_address: u64,
483}
484
485impl fmt::Display for WasmFault {
486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487 write!(
488 f,
489 "memory fault at wasm address 0x{:x} in linear memory of size 0x{:x}",
490 self.wasm_address, self.memory_size,
491 )
492 }
493}
494
495pub fn assert_ready<F: Future>(f: F) -> F::Output {
508 one_poll(f).unwrap()
509}
510
511pub fn one_poll<F: Future>(f: F) -> Option<F::Output> {
523 let mut context = Context::from_waker(&Waker::noop());
524 match pin!(f).poll(&mut context) {
525 Poll::Ready(output) => Some(output),
526 Poll::Pending => None,
527 }
528}