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 = "gc-copying")]
130pub use crate::runtime::vm::vmcontext::VMCopyingHeapData;
131#[cfg(feature = "gc-drc")]
132pub use crate::runtime::vm::vmcontext::VMDrcHeapData;
133#[cfg(feature = "component-model-async")]
134pub use crate::runtime::vm::vmcontext::VMLazyThread;
135#[cfg(feature = "gc-null")]
136pub use crate::runtime::vm::vmcontext::VMNullHeapData;
137pub use crate::runtime::vm::vmcontext::{
138 VMArrayCallHostFuncContext, VMCommonStackInformation, VMContRef, VMContext, VMFuncRef,
139 VMFunctionImport, VMGlobalDefinition, VMGlobalImport, VMGlobalKind, VMHostArray,
140 VMMemoryDefinition, VMMemoryImport, VMOpaqueContext, VMStackLimits, VMStoreContext,
141 VMTableImport, VMTagImport, VMWasmCallFunction, ValRaw,
142};
143#[cfg(has_custom_sync)]
144pub(crate) use sys::capi;
145
146pub use send_sync_ptr::SendSyncPtr;
147pub use wasmtime_unwinder::Unwind;
148
149#[cfg(has_host_compiler_backend)]
150pub use wasmtime_unwinder::{UnwindHost, get_stack_pointer};
151
152mod module_id;
153pub use module_id::CompiledModuleId;
154
155#[cfg(has_virtual_memory)]
156mod byte_count;
157#[cfg(has_virtual_memory)]
158mod cow;
159#[cfg(not(has_virtual_memory))]
160mod cow_disabled;
161#[cfg(has_virtual_memory)]
162mod mmap;
163
164#[allow(unused, reason = "hard to cfg on/off, weird feature interactions")]
165mod send_sync_unsafe_cell;
166#[allow(unused, reason = "hard to cfg on/off, weird feature interactions")]
167pub use send_sync_unsafe_cell::SendSyncUnsafeCell;
168
169cfg_select! {
170 has_virtual_memory => {
171 pub use crate::runtime::vm::byte_count::*;
172 pub use crate::runtime::vm::mmap::{Mmap, MmapOffset};
173 pub use self::cow::{MemoryImage, MemoryImageSlot, ModuleMemoryImages};
174 }
175 _ => {
176 pub use self::cow_disabled::{MemoryImage, MemoryImageSlot, ModuleMemoryImages};
177 }
178}
179
180pub trait ModuleMemoryImageSource: Send + Sync + 'static {
182 fn wasm_data(&self) -> &[u8];
185
186 fn mmap(&self) -> Option<&MmapVec>;
189}
190
191pub unsafe trait VMStore: 'static {
212 fn store_opaque(&self) -> &StoreOpaque;
214
215 fn store_opaque_mut(&mut self) -> &mut StoreOpaque;
217
218 fn resource_limiter_and_store_opaque(
221 &mut self,
222 ) -> (Option<StoreResourceLimiter<'_>>, &mut StoreOpaque);
223
224 #[cfg(feature = "call-hook")]
227 fn call_hook(&mut self, s: crate::CallHook) -> Result<()>;
228
229 #[cfg(target_has_atomic = "64")]
233 fn new_epoch_updated_deadline(&mut self) -> Result<crate::UpdateDeadline>;
234
235 #[cfg(feature = "component-model-async")]
236 fn component_async_store(
237 &mut self,
238 ) -> &mut dyn crate::runtime::component::VMComponentAsyncStore;
239
240 #[cfg(feature = "debug")]
242 fn block_on_debug_handler(&mut self, event: crate::DebugEvent) -> crate::Result<()>;
243}
244
245impl Deref for dyn VMStore + '_ {
246 type Target = StoreOpaque;
247
248 fn deref(&self) -> &Self::Target {
249 self.store_opaque()
250 }
251}
252
253impl DerefMut for dyn VMStore + '_ {
254 fn deref_mut(&mut self) -> &mut Self::Target {
255 self.store_opaque_mut()
256 }
257}
258
259impl dyn VMStore + '_ {
260 pub(crate) unsafe fn unchecked_context_mut<T>(&mut self) -> StoreContextMut<'_, T> {
268 unsafe { StoreContextMut(&mut *(self as *mut dyn VMStore as *mut StoreInner<T>)) }
269 }
270}
271
272#[derive(Copy, Clone)]
287#[repr(transparent)]
288struct VMStoreRawPtr(pub NonNull<dyn VMStore>);
289
290unsafe impl Send for VMStoreRawPtr {}
293unsafe impl Sync for VMStoreRawPtr {}
294
295#[derive(Clone)]
298pub enum ModuleRuntimeInfo {
299 Module(crate::Module),
300 Bare(Arc<BareModuleInfo>),
301}
302
303pub struct BareModuleInfo {
308 module: Arc<wasmtime_environ::Module>,
309 offsets: VMOffsets<HostPtr>,
310 _registered_types: TryVec<RegisteredType>,
311}
312
313impl ModuleRuntimeInfo {
314 pub(crate) fn bare(module: Arc<wasmtime_environ::Module>) -> Result<Self, OutOfMemory> {
315 ModuleRuntimeInfo::new_bare(module, TryVec::new())
316 }
317
318 pub(crate) fn bare_with_registered_types(
326 module: Arc<wasmtime_environ::Module>,
327 engine: &crate::Engine,
328 registered_types: impl IntoIterator<Item = RegisteredType>,
329 ) -> Result<Self> {
330 let mut types = TryVec::new();
331 for ty in registered_types {
332 crate::ensure!(
333 crate::Engine::same(engine, ty.engine()),
334 "type used with wrong engine"
335 );
336 types.push(ty)?;
337 }
338 Ok(ModuleRuntimeInfo::new_bare(module, types)?)
339 }
340
341 fn new_bare(
342 module: Arc<wasmtime_environ::Module>,
343 registered_types: TryVec<RegisteredType>,
344 ) -> Result<Self, OutOfMemory> {
345 let info = try_new(BareModuleInfo {
346 offsets: VMOffsets::new(HostPtr, &module),
347 module,
348 _registered_types: registered_types,
349 })?;
350 Ok(ModuleRuntimeInfo::Bare(info))
351 }
352
353 pub(crate) fn env_module(&self) -> &Arc<wasmtime_environ::Module> {
355 match self {
356 ModuleRuntimeInfo::Module(m) => m.env_module(),
357 ModuleRuntimeInfo::Bare(b) => &b.module,
358 }
359 }
360
361 #[cfg(feature = "gc")]
364 fn engine_type_index(&self, module_index: ModuleInternedTypeIndex) -> VMSharedTypeIndex {
365 match self {
366 ModuleRuntimeInfo::Module(m) => m
367 .engine_code()
368 .signatures()
369 .shared_type(module_index)
370 .expect("bad module-level interned type index"),
371 ModuleRuntimeInfo::Bare(_) => unreachable!(),
372 }
373 }
374
375 fn memory_image(&self, memory: DefinedMemoryIndex) -> crate::Result<Option<&Arc<MemoryImage>>> {
378 match self {
379 ModuleRuntimeInfo::Module(m) => {
380 let images = m.memory_images()?;
381 Ok(images.and_then(|images| images.get_memory_image(memory)))
382 }
383 ModuleRuntimeInfo::Bare(_) => Ok(None),
384 }
385 }
386
387 #[cfg(feature = "pooling-allocator")]
391 fn unique_id(&self) -> Option<CompiledModuleId> {
392 match self {
393 ModuleRuntimeInfo::Module(m) => Some(m.id()),
394 ModuleRuntimeInfo::Bare(_) => None,
395 }
396 }
397
398 fn wasm_data(&self) -> &[u8] {
400 match self {
401 ModuleRuntimeInfo::Module(m) => m.engine_code().wasm_data(),
402 ModuleRuntimeInfo::Bare(_) => &[],
403 }
404 }
405
406 fn type_ids(&self) -> &[VMSharedTypeIndex] {
409 match self {
410 ModuleRuntimeInfo::Module(m) => m
411 .engine_code()
412 .signatures()
413 .as_module_map()
414 .values()
415 .as_slice(),
416 ModuleRuntimeInfo::Bare(_) => &[],
417 }
418 }
419
420 pub(crate) fn offsets(&self) -> &VMOffsets<HostPtr> {
422 match self {
423 ModuleRuntimeInfo::Module(m) => m.offsets(),
424 ModuleRuntimeInfo::Bare(b) => &b.offsets,
425 }
426 }
427}
428
429#[cfg(has_virtual_memory)]
431pub fn host_page_size() -> usize {
432 static PAGE_SIZE: AtomicUsize = AtomicUsize::new(0);
435
436 return match PAGE_SIZE.load(Ordering::Relaxed) {
437 0 => {
438 let size = sys::vm::get_page_size();
439 assert!(size != 0);
440 PAGE_SIZE.store(size, Ordering::Relaxed);
441 size
442 }
443 n => n,
444 };
445}
446
447#[derive(Copy, Clone, PartialEq, Eq, Debug)]
449pub enum WaitResult {
450 Ok = 0,
453 Mismatch = 1,
456 TimedOut = 2,
459}
460
461#[derive(Debug)]
463pub struct WasmFault {
464 pub memory_size: usize,
466 pub wasm_address: u64,
468}
469
470impl fmt::Display for WasmFault {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 write!(
473 f,
474 "memory fault at wasm address 0x{:x} in linear memory of size 0x{:x}",
475 self.wasm_address, self.memory_size,
476 )
477 }
478}
479
480pub fn assert_ready<F: Future>(f: F) -> F::Output {
499 one_poll(f).unwrap()
500}
501
502fn one_poll<F: Future>(f: F) -> Option<F::Output> {
514 let mut context = Context::from_waker(&Waker::noop());
515 match pin!(f).poll(&mut context) {
516 Poll::Ready(output) => Some(output),
517 Poll::Pending => None,
518 }
519}