wasmtime/engine.rs
1use crate::prelude::*;
2#[cfg(feature = "runtime")]
3pub use crate::runtime::code_memory::CustomCodeMemory;
4#[cfg(feature = "runtime")]
5use crate::runtime::type_registry::TypeRegistry;
6#[cfg(feature = "runtime")]
7use crate::runtime::vm::{GcRuntime, ModuleRuntimeInfo};
8use crate::{Config, RRConfig};
9use alloc::sync::Arc;
10use core::ptr::NonNull;
11#[cfg(target_has_atomic = "64")]
12use core::sync::atomic::{AtomicU64, Ordering};
13#[cfg(any(feature = "cranelift", feature = "winch"))]
14use object::write::{Object, StandardSegment};
15#[cfg(feature = "std")]
16use std::{fs::File, path::Path};
17use wasmparser::WasmFeatures;
18use wasmtime_environ::{FlagValue, ObjectKind, TripleExt, Tunables};
19
20mod serialization;
21
22/// An `Engine` which is a global context for compilation and management of wasm
23/// modules.
24///
25/// An engine can be safely shared across threads and is a cheap cloneable
26/// handle to the actual engine. The engine itself will be deallocated once all
27/// references to it have gone away.
28///
29/// Engines store global configuration preferences such as compilation settings,
30/// enabled features, etc. You'll likely only need at most one of these for a
31/// program.
32///
33/// ## Engines and `Clone`
34///
35/// Using `clone` on an `Engine` is a cheap operation. It will not create an
36/// entirely new engine, but rather just a new reference to the existing engine.
37/// In other words it's a shallow copy, not a deep copy.
38///
39/// ## Engines and `Default`
40///
41/// You can create an engine with default configuration settings using
42/// `Engine::default()`. Be sure to consult the documentation of [`Config`] for
43/// default settings.
44#[derive(Clone)]
45pub struct Engine {
46 inner: Arc<EngineInner>,
47}
48
49// These impls are strictly not necessary but they're currently serving the
50// purpose of the reducing the recursion limit necessary to prove
51// types/futures/etc are `Send` in Wasmtime. This is related to
52// rust-lang/rust#159228.
53//
54// SAFETY: we're re-stating what rustc itself is already going to infer. The
55// `_assert_send_sync` function beneath this is intended to serve as a
56// double-assertion that this actually holds.
57unsafe impl Send for Engine {}
58unsafe impl Sync for Engine {}
59
60fn _assert_send_sync(e: &Engine) {
61 fn _assert<T: Send + Sync>(_: &T) {}
62 let Engine { inner } = e;
63 _assert(e);
64 _assert(inner);
65}
66
67struct EngineInner {
68 config: Config,
69 features: WasmFeatures,
70 tunables: Tunables,
71 #[cfg(any(feature = "cranelift", feature = "winch"))]
72 compiler: Option<Box<dyn wasmtime_environ::Compiler>>,
73 #[cfg(feature = "runtime")]
74 allocator: Box<dyn crate::runtime::vm::InstanceAllocator + Send + Sync>,
75 #[cfg(feature = "runtime")]
76 gc_runtime: Option<Arc<dyn GcRuntime>>,
77 #[cfg(feature = "runtime")]
78 profiler: Box<dyn crate::profiling_agent::ProfilingAgent>,
79 #[cfg(feature = "runtime")]
80 signatures: TypeRegistry,
81 #[cfg(all(feature = "runtime", target_has_atomic = "64"))]
82 epoch: AtomicU64,
83
84 /// One-time check of whether the compiler's settings, if present, are
85 /// compatible with the native host.
86 compatible_with_native_host: crate::sync::OnceLock<Result<(), String>>,
87
88 /// The canonical empty `ModuleRuntimeInfo`, so that each store doesn't need
89 /// allocate its own copy when creating its default caller instance or GC
90 /// heap.
91 #[cfg(feature = "runtime")]
92 empty_module_runtime_info: ModuleRuntimeInfo,
93}
94
95impl core::fmt::Debug for Engine {
96 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
97 f.debug_tuple("Engine")
98 .field(&Arc::as_ptr(&self.inner))
99 .finish()
100 }
101}
102
103impl Default for Engine {
104 fn default() -> Engine {
105 Engine::new(&Config::default()).unwrap()
106 }
107}
108
109impl Engine {
110 /// Creates a new [`Engine`] with the specified compilation and
111 /// configuration settings.
112 ///
113 /// # Errors
114 ///
115 /// This method can fail if the `config` is invalid or some
116 /// configurations are incompatible.
117 ///
118 /// For example, feature `reference_types` will need to set
119 /// the compiler setting `unwind_info` to `true`, but explicitly
120 /// disable these two compiler settings will cause errors.
121 ///
122 /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when
123 /// memory allocation fails. See the `OutOfMemory` type's documentation for
124 /// details on Wasmtime's out-of-memory handling.
125 pub fn new(config: &Config) -> Result<Engine> {
126 let config = config.clone();
127 let (mut tunables, features) = config.validate()?;
128
129 #[cfg(feature = "runtime")]
130 if tunables.signals_based_traps {
131 // Ensure that crate::runtime::vm's signal handlers are
132 // configured. This is the per-program initialization required for
133 // handling traps, such as configuring signals, vectored exception
134 // handlers, etc.
135 #[cfg(has_native_signals)]
136 crate::runtime::vm::init_traps(config.macos_use_mach_ports);
137 if !cfg!(miri) {
138 #[cfg(all(has_host_compiler_backend, feature = "debug-builtins"))]
139 crate::runtime::vm::debug_builtins::init();
140 }
141 }
142
143 #[cfg(any(feature = "cranelift", feature = "winch"))]
144 let (config, compiler) = if config.has_compiler() {
145 let (config, compiler) = config.build_compiler(&mut tunables, features)?;
146 (config, Some(compiler))
147 } else {
148 (config.clone(), None)
149 };
150 #[cfg(not(any(feature = "cranelift", feature = "winch")))]
151 let _ = &mut tunables;
152
153 #[cfg(feature = "runtime")]
154 let empty_module_runtime_info = ModuleRuntimeInfo::bare(try_new(
155 wasmtime_environ::Module::new(wasmtime_environ::StaticModuleIndex::from_u32(0)),
156 )?)?;
157
158 Ok(Engine {
159 inner: try_new::<Arc<_>>(EngineInner {
160 #[cfg(any(feature = "cranelift", feature = "winch"))]
161 compiler,
162 #[cfg(feature = "runtime")]
163 allocator: {
164 let allocator = config.build_allocator(&tunables)?;
165 #[cfg(feature = "gc")]
166 {
167 let mem_ty = tunables.gc_heap_memory_type();
168 allocator.validate_memory(&mem_ty).context(
169 "instance allocator cannot support configured GC heap memory",
170 )?;
171 }
172 allocator
173 },
174 #[cfg(feature = "runtime")]
175 gc_runtime: config.build_gc_runtime()?,
176 #[cfg(feature = "runtime")]
177 profiler: config.build_profiler()?,
178 #[cfg(feature = "runtime")]
179 signatures: TypeRegistry::new(),
180 #[cfg(all(feature = "runtime", target_has_atomic = "64"))]
181 epoch: AtomicU64::new(0),
182 compatible_with_native_host: Default::default(),
183 config,
184 tunables,
185 features,
186 #[cfg(feature = "runtime")]
187 empty_module_runtime_info,
188 })?,
189 })
190 }
191
192 /// Returns the configuration settings that this engine is using.
193 #[inline]
194 pub fn config(&self) -> &Config {
195 &self.inner.config
196 }
197
198 #[inline]
199 pub(crate) fn features(&self) -> WasmFeatures {
200 self.inner.features
201 }
202
203 pub(crate) fn run_maybe_parallel<
204 A: Send,
205 B: Send,
206 E: Send,
207 F: Fn(A) -> Result<B, E> + Send + Sync,
208 >(
209 &self,
210 input: Vec<A>,
211 f: F,
212 ) -> Result<Vec<B>, E> {
213 if self.config().parallel_compilation {
214 #[cfg(feature = "parallel-compilation")]
215 {
216 use rayon::prelude::*;
217 // If we collect into Result<Vec<B>, E> directly, the returned error is not
218 // deterministic, because any error could be returned early. So we first materialize
219 // all results in order and then return the first error deterministically, or Ok(_).
220 return input
221 .into_par_iter()
222 .map(|a| f(a))
223 .collect::<Vec<Result<B, E>>>()
224 .into_iter()
225 .collect::<Result<Vec<B>, E>>();
226 }
227 }
228
229 // In case the parallel-compilation feature is disabled or the parallel_compilation config
230 // was turned off dynamically fallback to the non-parallel version.
231 input
232 .into_iter()
233 .map(|a| f(a))
234 .collect::<Result<Vec<B>, E>>()
235 }
236
237 #[cfg(any(feature = "cranelift", feature = "winch"))]
238 pub(crate) fn run_maybe_parallel_mut<
239 T: Send,
240 E: Send,
241 F: Fn(&mut T) -> Result<(), E> + Send + Sync,
242 >(
243 &self,
244 input: &mut [T],
245 f: F,
246 ) -> Result<(), E> {
247 if self.config().parallel_compilation {
248 #[cfg(feature = "parallel-compilation")]
249 {
250 use rayon::prelude::*;
251 // If we collect into `Result<(), E>` directly, the returned
252 // error is not deterministic, because any error could be
253 // returned early. So we first materialize all results in order
254 // and then return the first error deterministically, or
255 // `Ok(_)`.
256 return input
257 .into_par_iter()
258 .map(|a| f(a))
259 .collect::<Vec<Result<(), E>>>()
260 .into_iter()
261 .collect::<Result<(), E>>();
262 }
263 }
264
265 // In case the parallel-compilation feature is disabled or the
266 // parallel_compilation config was turned off dynamically fallback to
267 // the non-parallel version.
268 input.into_iter().map(|a| f(a)).collect::<Result<(), E>>()
269 }
270
271 /// Take a weak reference to this engine.
272 pub fn weak(&self) -> EngineWeak {
273 EngineWeak {
274 inner: Arc::downgrade(&self.inner),
275 }
276 }
277
278 #[inline]
279 pub(crate) fn tunables(&self) -> &Tunables {
280 &self.inner.tunables
281 }
282
283 /// Returns whether the engine `a` and `b` refer to the same configuration.
284 #[inline]
285 pub fn same(a: &Engine, b: &Engine) -> bool {
286 Arc::ptr_eq(&a.inner, &b.inner)
287 }
288
289 /// Returns whether the engine is configured to support execution recording
290 #[inline]
291 pub fn is_recording(&self) -> bool {
292 match self.config().rr_config {
293 #[cfg(feature = "rr")]
294 RRConfig::Recording => true,
295 #[cfg(feature = "rr")]
296 RRConfig::Replaying => false,
297 RRConfig::None => false,
298 }
299 }
300
301 /// Returns whether the engine is configured to support execution replaying
302 #[inline]
303 pub fn is_replaying(&self) -> bool {
304 match self.config().rr_config {
305 #[cfg(feature = "rr")]
306 RRConfig::Replaying => true,
307 #[cfg(feature = "rr")]
308 RRConfig::Recording => false,
309 RRConfig::None => false,
310 }
311 }
312
313 /// Detects whether the bytes provided are a precompiled object produced by
314 /// Wasmtime.
315 ///
316 /// This function will inspect the header of `bytes` to determine if it
317 /// looks like a precompiled core wasm module or a precompiled component.
318 /// This does not validate the full structure or guarantee that
319 /// deserialization will succeed, instead it helps higher-levels of the
320 /// stack make a decision about what to do next when presented with the
321 /// `bytes` as an input module.
322 ///
323 /// If the `bytes` looks like a precompiled object previously produced by
324 /// [`Module::serialize`](crate::Module::serialize),
325 /// [`Component::serialize`](crate::component::Component::serialize),
326 /// [`Engine::precompile_module`], or [`Engine::precompile_component`], then
327 /// this will return `Some(...)` indicating so. Otherwise `None` is
328 /// returned.
329 pub fn detect_precompiled(bytes: &[u8]) -> Option<Precompiled> {
330 serialization::detect_precompiled_bytes(bytes)
331 }
332
333 /// Like [`Engine::detect_precompiled`], but performs the detection on a file.
334 #[cfg(feature = "std")]
335 pub fn detect_precompiled_file(path: impl AsRef<Path>) -> Result<Option<Precompiled>> {
336 serialization::detect_precompiled_file(path)
337 }
338
339 /// Returns the target triple which this engine is compiling code for
340 /// and/or running code for.
341 pub(crate) fn target(&self) -> target_lexicon::Triple {
342 return self.config().compiler_target();
343 }
344
345 /// Verify that this engine's configuration is compatible with loading
346 /// modules onto the native host platform.
347 ///
348 /// This method is used as part of `Module::new` to ensure that this
349 /// engine can indeed load modules for the configured compiler (if any).
350 /// Note that if cranelift is disabled this trivially returns `Ok` because
351 /// loaded serialized modules are checked separately.
352 pub(crate) fn check_compatible_with_native_host(&self) -> Result<()> {
353 self.inner
354 .compatible_with_native_host
355 .get_or_init(|| self._check_compatible_with_native_host())
356 .clone()
357 .map_err(crate::Error::msg)
358 }
359
360 fn _check_compatible_with_native_host(&self) -> Result<(), String> {
361 use target_lexicon::Triple;
362
363 let host = Triple::host();
364 let target = self.config().compiler_target();
365
366 let target_matches_host = || {
367 // If the host target and target triple match, then it's valid
368 // to run results of compilation on this host.
369 if host == target {
370 return true;
371 }
372
373 // If there's a mismatch and the target is a compatible pulley
374 // target, then that's also ok to run.
375 if cfg!(feature = "pulley")
376 && target.is_pulley()
377 && target.pointer_width() == host.pointer_width()
378 && target.endianness() == host.endianness()
379 {
380 return true;
381 }
382
383 // ... otherwise everything else is considered not a match.
384 false
385 };
386
387 if !target_matches_host() {
388 return Err(format!(
389 "target '{target}' specified in the configuration does not match the host"
390 ));
391 }
392
393 #[cfg(any(feature = "cranelift", feature = "winch"))]
394 {
395 if let Some(compiler) = self.compiler() {
396 // Also double-check all compiler settings
397 for (key, value) in compiler.flags().iter() {
398 self.check_compatible_with_shared_flag(key, value)?;
399 }
400 for (key, value) in compiler.isa_flags().iter() {
401 self.check_compatible_with_isa_flag(key, value)?;
402 }
403 }
404 }
405
406 // Double-check that this configuration isn't requesting capabilities
407 // that this build of Wasmtime doesn't support.
408 if !cfg!(has_native_signals) && self.tunables().signals_based_traps {
409 return Err("signals-based-traps disabled at compile time -- cannot be enabled".into());
410 }
411
412 if self.tunables().mmu_interruption {
413 if !cfg!(has_mmu_interruption_runtime) {
414 return Err("MMU interruption runtime support was disabled at compile time".into());
415 }
416 }
417
418 if !cfg!(has_virtual_memory) && self.tunables().memory_init_cow {
419 return Err("virtual memory disabled at compile time -- cannot enable CoW".into());
420 }
421 if !cfg!(target_has_atomic = "64") && self.tunables().epoch_interruption {
422 return Err("epochs currently require 64-bit atomics".into());
423 }
424
425 // Double-check that the host's float ABI matches Cranelift's float ABI.
426 // See `Config::x86_float_abi_ok` for some more
427 // information.
428 if target == target_lexicon::triple!("x86_64-unknown-none")
429 && self.config().x86_float_abi_ok != Some(true)
430 {
431 return Err("\
432the x86_64-unknown-none target by default uses a soft-float ABI that is \
433incompatible with Cranelift and Wasmtime -- use \
434`Config::x86_float_abi_ok` to disable this check and see more \
435information about this check\
436"
437 .into());
438 }
439
440 // Use of asan compatible codegen required in an asan build, optional
441 // otherwise.
442 if cfg!(asan) && !self.tunables().asan_stack_switching {
443 return Err("asan enabled at compile time: asan stack switching required".into());
444 }
445
446 Ok(())
447 }
448
449 /// Checks to see whether the "shared flag", something enabled for
450 /// individual compilers, is compatible with the native host platform.
451 ///
452 /// This is used both when validating an engine's compilation settings are
453 /// compatible with the host as well as when deserializing modules from
454 /// disk to ensure they're compatible with the current host.
455 ///
456 /// Note that most of the settings here are not configured by users that
457 /// often. While theoretically possible via `Config` methods the more
458 /// interesting flags are the ISA ones below. Typically the values here
459 /// represent global configuration for wasm features. Settings here
460 /// currently rely on the compiler informing us of all settings, including
461 /// those disabled. Settings then fall in a few buckets:
462 ///
463 /// * Some settings must be enabled, such as `preserve_frame_pointers`.
464 /// * Some settings must have a particular value, such as
465 /// `libcall_call_conv`.
466 /// * Some settings do not matter as to their value, such as `opt_level`.
467 pub(crate) fn check_compatible_with_shared_flag(
468 &self,
469 flag: &str,
470 value: &FlagValue,
471 ) -> Result<(), String> {
472 let target = self.target();
473 let ok = match flag {
474 // These settings must all have be enabled, since their value
475 // can affect the way the generated code performs or behaves at
476 // runtime.
477 "libcall_call_conv" => *value == FlagValue::Enum("isa_default"),
478 "preserve_frame_pointers" => *value == FlagValue::Bool(true),
479 "enable_probestack" => *value == FlagValue::Bool(true),
480 "probestack_strategy" => *value == FlagValue::Enum("inline"),
481 "enable_multi_ret_implicit_sret" => *value == FlagValue::Bool(true),
482
483 // Features wasmtime doesn't use should all be disabled, since
484 // otherwise if they are enabled it could change the behavior of
485 // generated code.
486 "enable_llvm_abi_extensions" => *value == FlagValue::Bool(false),
487 "enable_pinned_reg" => *value == FlagValue::Bool(false),
488 "use_colocated_libcalls" => *value == FlagValue::Bool(false),
489 "use_pinned_reg_as_heap_base" => *value == FlagValue::Bool(false),
490
491 // Windows requires unwind info as part of its ABI.
492 "unwind_info" => {
493 if target.operating_system == target_lexicon::OperatingSystem::Windows {
494 *value == FlagValue::Bool(true)
495 } else {
496 return Ok(())
497 }
498 }
499
500 // stack switch model must match the current OS
501 "stack_switch_model" => {
502 if self.features().contains(WasmFeatures::STACK_SWITCHING) {
503 use target_lexicon::OperatingSystem;
504 let expected =
505 match target.operating_system {
506 OperatingSystem::Windows => "update_windows_tib",
507 OperatingSystem::Linux
508 | OperatingSystem::MacOSX(_)
509 | OperatingSystem::Darwin(_) => "basic",
510 _ => { return Err(String::from("stack-switching feature not supported on this platform")); }
511 };
512 *value == FlagValue::Enum(expected)
513 } else {
514 return Ok(())
515 }
516 }
517
518 // These settings don't affect the interface or functionality of
519 // the module itself, so their configuration values shouldn't
520 // matter.
521 "enable_heap_access_spectre_mitigation"
522 | "enable_table_access_spectre_mitigation"
523 | "enable_nan_canonicalization"
524 | "enable_float"
525 | "enable_verifier"
526 | "regalloc_checker"
527 | "regalloc_verbose_logs"
528 | "regalloc_algorithm"
529 | "is_pic"
530 | "bb_padding_log2_minus_one"
531 | "log2_min_function_alignment"
532 | "enable_compact_unwind_abi"
533 | "machine_code_cfg_info"
534 | "tls_model" // wasmtime doesn't use tls right now
535 | "opt_level" // opt level doesn't change semantics
536 | "enable_alias_analysis" // alias analysis-based opts don't change semantics
537 | "probestack_size_log2" // probestack above asserted disabled
538 | "regalloc" // shouldn't change semantics
539 | "enable_incremental_compilation_cache_checks" // shouldn't change semantics
540 | "enable_atomics" => return Ok(()),
541
542 // Everything else is unknown and needs to be added somewhere to
543 // this list if encountered.
544 _ => {
545 return Err(format!("unknown shared setting {flag:?} configured to {value:?}"))
546 }
547 };
548
549 if !ok {
550 return Err(format!(
551 "setting {flag:?} is configured to {value:?} which is not supported",
552 ));
553 }
554 Ok(())
555 }
556
557 /// Same as `check_compatible_with_native_host` except used for ISA-specific
558 /// flags. This is used to test whether a configured ISA flag is indeed
559 /// available on the host platform itself.
560 pub(crate) fn check_compatible_with_isa_flag(
561 &self,
562 flag: &str,
563 value: &FlagValue,
564 ) -> Result<(), String> {
565 match value {
566 // ISA flags are used for things like CPU features, so if they're
567 // disabled then it's compatible with the native host.
568 FlagValue::Bool(false) => return Ok(()),
569
570 // Fall through below where we test at runtime that features are
571 // available.
572 FlagValue::Bool(true) => {}
573
574 // Pulley's pointer_width must match the host.
575 FlagValue::Enum("pointer32") => {
576 return if cfg!(target_pointer_width = "32") {
577 Ok(())
578 } else {
579 Err("wrong host pointer width".to_string())
580 };
581 }
582 FlagValue::Enum("pointer64") => {
583 return if cfg!(target_pointer_width = "64") {
584 Ok(())
585 } else {
586 Err("wrong host pointer width".to_string())
587 };
588 }
589
590 // Only `bool` values are supported right now, other settings would
591 // need more support here.
592 _ => {
593 return Err(format!(
594 "isa-specific feature {flag:?} configured to unknown value {value:?}"
595 ));
596 }
597 }
598
599 let host_feature = match flag {
600 // aarch64 features to detect
601 "has_lse" => "lse",
602 "has_pauth" => "paca",
603 "has_fp16" => "fp16",
604 "has_dotprod" => "dotprod",
605 "has_i8mm" => "i8mm",
606
607 // aarch64 features which don't need detection
608 // No effect on its own.
609 "sign_return_address_all" => return Ok(()),
610 // The pointer authentication instructions act as a `NOP` when
611 // unsupported, so it is safe to enable them.
612 "sign_return_address" => return Ok(()),
613 // No effect on its own.
614 "sign_return_address_with_bkey" => return Ok(()),
615 // The `BTI` instruction acts as a `NOP` when unsupported, so it
616 // is safe to enable it regardless of whether the host supports it
617 // or not.
618 "use_bti" => return Ok(()),
619
620 // s390x features to detect
621 "has_vxrs_ext2" => "vxrs_ext2",
622 "has_vxrs_ext3" => "vxrs_ext3",
623 "has_mie3" => "mie3",
624 "has_mie4" => "mie4",
625
626 // x64 features to detect
627 "has_cmpxchg16b" => "cmpxchg16b",
628 "has_sse3" => "sse3",
629 "has_ssse3" => "ssse3",
630 "has_sse41" => "sse4.1",
631 "has_sse42" => "sse4.2",
632 "has_popcnt" => "popcnt",
633 "has_avx" => "avx",
634 "has_avx2" => "avx2",
635 "has_fma" => "fma",
636 "has_avx_vnni" => "avxvnni",
637 "has_bmi1" => "bmi1",
638 "has_bmi2" => "bmi2",
639 "has_avx512bitalg" => "avx512bitalg",
640 "has_avx512dq" => "avx512dq",
641 "has_avx512f" => "avx512f",
642 "has_avx512vl" => "avx512vl",
643 "has_avx512vbmi" => "avx512vbmi",
644 "has_avx512vnni" => "avx512vnni",
645 "has_lzcnt" => "lzcnt",
646
647 // pulley features
648 "big_endian" if cfg!(target_endian = "big") => return Ok(()),
649 "big_endian" if cfg!(target_endian = "little") => {
650 return Err("wrong host endianness".to_string());
651 }
652
653 _ => {
654 // FIXME: should enumerate risc-v features and plumb them
655 // through to the `detect_host_feature` function.
656 if cfg!(target_arch = "riscv64") && flag != "not_a_flag" {
657 return Ok(());
658 }
659 return Err(format!(
660 "don't know how to test for target-specific flag {flag:?} at runtime"
661 ));
662 }
663 };
664
665 let detect = match self.config().detect_host_feature {
666 Some(detect) => detect,
667 None => {
668 return Err(format!(
669 "cannot determine if host feature {host_feature:?} is \
670 available at runtime, configure a probing function with \
671 `Config::detect_host_feature`"
672 ));
673 }
674 };
675
676 match detect(host_feature) {
677 Some(true) => Ok(()),
678 Some(false) => Err(format!(
679 "compilation setting {flag:?} is enabled, but not \
680 available on the host",
681 )),
682 None => Err(format!(
683 "failed to detect if target-specific flag {host_feature:?} is \
684 available at runtime (compile setting {flag:?})"
685 )),
686 }
687 }
688
689 /// Returns whether this [`Engine`] is configured to execute with Pulley,
690 /// Wasmtime's interpreter.
691 ///
692 /// Note that Pulley is the default for host platforms that do not have a
693 /// Cranelift backend to support them. For example at the time of this
694 /// writing 32-bit x86 is not supported in Cranelift so the
695 /// `i686-unknown-linux-gnu` target would by default return `true` here.
696 pub fn is_pulley(&self) -> bool {
697 self.target().is_pulley()
698 }
699
700 #[cfg(feature = "runtime")]
701 pub(crate) fn empty_module_runtime_info(&self) -> &ModuleRuntimeInfo {
702 &self.inner.empty_module_runtime_info
703 }
704}
705
706#[cfg(any(feature = "cranelift", feature = "winch"))]
707impl Engine {
708 pub(crate) fn compiler(&self) -> Option<&dyn wasmtime_environ::Compiler> {
709 self.inner.compiler.as_deref()
710 }
711
712 pub(crate) fn try_compiler(&self) -> Result<&dyn wasmtime_environ::Compiler> {
713 self.compiler()
714 .ok_or_else(|| format_err!("Engine was not configured with a compiler"))
715 }
716
717 /// Ahead-of-time (AOT) compiles a WebAssembly module.
718 ///
719 /// The `bytes` provided must be in one of two formats:
720 ///
721 /// * A [binary-encoded][binary] WebAssembly module. This is always supported.
722 /// * A [text-encoded][text] instance of the WebAssembly text format.
723 /// This is only supported when the `wat` feature of this crate is enabled.
724 /// If this is supplied then the text format will be parsed before validation.
725 /// Note that the `wat` feature is enabled by default.
726 ///
727 /// This method may be used to compile a module for use with a different target
728 /// host. The output of this method may be used with
729 /// [`Module::deserialize`](crate::Module::deserialize) on hosts compatible
730 /// with the [`Config`](crate::Config) associated with this [`Engine`].
731 ///
732 /// The output of this method is safe to send to another host machine for later
733 /// execution. As the output is already a compiled module, translation and code
734 /// generation will be skipped and this will improve the performance of constructing
735 /// a [`Module`](crate::Module) from the output of this method.
736 ///
737 /// [binary]: https://webassembly.github.io/spec/core/binary/index.html
738 /// [text]: https://webassembly.github.io/spec/core/text/index.html
739 pub fn precompile_module(&self, bytes: &[u8]) -> Result<Vec<u8>> {
740 crate::CodeBuilder::new(self)
741 .wasm_binary_or_text(bytes, None)?
742 .compile_module_serialized()
743 }
744
745 /// Same as [`Engine::precompile_module`] except for a
746 /// [`Component`](crate::component::Component)
747 #[cfg(feature = "component-model")]
748 pub fn precompile_component(&self, bytes: &[u8]) -> Result<Vec<u8>> {
749 crate::CodeBuilder::new(self)
750 .wasm_binary_or_text(bytes, None)?
751 .compile_component_serialized()
752 }
753
754 /// Produces a blob of bytes by serializing the `engine`'s configuration data to
755 /// be checked, perhaps in a different process, with the `check_compatible`
756 /// method below.
757 ///
758 /// The blob of bytes is inserted into the object file specified to become part
759 /// of the final compiled artifact.
760 pub(crate) fn append_compiler_info(&self, obj: &mut Object<'_>) -> Result<()> {
761 serialization::append_compiler_info(self, obj, &serialization::Metadata::new(&self)?);
762 Ok(())
763 }
764
765 #[cfg(any(feature = "cranelift", feature = "winch"))]
766 pub(crate) fn append_bti(&self, obj: &mut Object<'_>) {
767 let section = obj.add_section(
768 obj.segment_name(StandardSegment::Data).to_vec(),
769 wasmtime_environ::obj::ELF_WASM_BTI.as_bytes().to_vec(),
770 object::SectionKind::ReadOnlyData,
771 );
772 let contents = if self
773 .compiler()
774 .is_some_and(|c| c.is_branch_protection_enabled())
775 {
776 1
777 } else {
778 0
779 };
780 obj.append_section_data(section, &[contents], 1);
781 }
782}
783
784/// Return value from the [`Engine::detect_precompiled`] API.
785#[derive(PartialEq, Eq, Copy, Clone, Debug)]
786pub enum Precompiled {
787 /// The input bytes look like a precompiled core wasm module.
788 Module,
789 /// The input bytes look like a precompiled wasm component.
790 Component,
791}
792
793#[cfg(feature = "runtime")]
794impl Engine {
795 /// Eagerly initialize thread-local functionality shared by all [`Engine`]s.
796 ///
797 /// Wasmtime's implementation on some platforms may involve per-thread
798 /// setup that needs to happen whenever WebAssembly is invoked. This setup
799 /// can take on the order of a few hundred microseconds, whereas the
800 /// overhead of calling WebAssembly is otherwise on the order of a few
801 /// nanoseconds. This setup cost is paid once per-OS-thread. If your
802 /// application is sensitive to the latencies of WebAssembly function
803 /// calls, even those that happen first on a thread, then this function
804 /// can be used to improve the consistency of each call into WebAssembly
805 /// by explicitly frontloading the cost of the one-time setup per-thread.
806 ///
807 /// Note that this function is not required to be called in any embedding.
808 /// Wasmtime will automatically initialize thread-local-state as necessary
809 /// on calls into WebAssembly. This is provided for use cases where the
810 /// latency of WebAssembly calls are extra-important, which is not
811 /// necessarily true of all embeddings.
812 pub fn tls_eager_initialize() {
813 crate::runtime::vm::tls_eager_initialize();
814 }
815
816 /// Returns a [`PoolingAllocatorMetrics`](crate::PoolingAllocatorMetrics) if
817 /// this engine was configured with
818 /// [`InstanceAllocationStrategy::Pooling`](crate::InstanceAllocationStrategy::Pooling).
819 #[cfg(feature = "pooling-allocator")]
820 pub fn pooling_allocator_metrics(&self) -> Option<crate::vm::PoolingAllocatorMetrics> {
821 crate::runtime::vm::PoolingAllocatorMetrics::new(self)
822 }
823
824 /// Releases memory the pooling allocator is keeping resident for slots
825 /// that are not currently in use, returning how many bytes were released.
826 ///
827 /// [`PoolingAllocationConfig::linear_memory_keep_resident`] keeps memory
828 /// resident after an instance slot is freed, in order to enable faster
829 /// instantiation on the next use of the same module. This increases
830 /// resident memory size. If an embedder knows that load has decreased and
831 /// wishes to free up memory, it might wish to purge these "warm slots".
832 ///
833 /// This method releases all resident memory held by warm but unused
834 /// slots. The tradeoff is that the next instantiation of any given module
835 /// may be slower, because no cached memory mappings are present anymore.
836 ///
837 /// Note that while this method is running the warm slots it is releasing
838 /// are unavailable for allocation. Instantiations running concurrently
839 /// with this method may therefore fail with a "maximum concurrent limit
840 /// reached" error, even if few instances are live, when the pool's other
841 /// free slots are exhausted.
842 ///
843 /// Returns 0 if this engine is not using the pooling allocator, or if
844 /// nothing was resident to release.
845 ///
846 /// [`PoolingAllocationConfig::linear_memory_keep_resident`]: crate::PoolingAllocationConfig::linear_memory_keep_resident
847 ///
848 /// # Example
849 ///
850 /// ```
851 /// # use wasmtime::{Config, Engine, InstanceAllocationStrategy};
852 /// # fn main() -> wasmtime::Result<()> {
853 /// let mut config = Config::new();
854 /// config.allocation_strategy(InstanceAllocationStrategy::pooling());
855 /// let engine = Engine::new(&config)?;
856 ///
857 /// // ... once the embedder knows load has decreased ...
858 /// let _bytes = engine.release_idle_pool_memory();
859 /// # Ok(())
860 /// # }
861 /// ```
862 #[cfg(feature = "pooling-allocator")]
863 pub fn release_idle_pool_memory(&self) -> usize {
864 match self.allocator().as_pooling() {
865 Some(pool) => pool.release_resident_unused_memory(),
866 None => 0,
867 }
868 }
869
870 pub(crate) fn allocator(&self) -> &dyn crate::runtime::vm::InstanceAllocator {
871 let r: &(dyn crate::runtime::vm::InstanceAllocator + Send + Sync) =
872 self.inner.allocator.as_ref();
873 &*r
874 }
875
876 pub(crate) fn gc_runtime(&self) -> Option<&Arc<dyn GcRuntime>> {
877 self.inner.gc_runtime.as_ref()
878 }
879
880 pub(crate) fn profiler(&self) -> &dyn crate::profiling_agent::ProfilingAgent {
881 self.inner.profiler.as_ref()
882 }
883
884 #[cfg(all(feature = "cache", any(feature = "cranelift", feature = "winch")))]
885 pub(crate) fn cache(&self) -> Option<&wasmtime_cache::Cache> {
886 self.config().cache.as_ref()
887 }
888
889 pub(crate) fn signatures(&self) -> &TypeRegistry {
890 &self.inner.signatures
891 }
892
893 #[cfg(feature = "runtime")]
894 pub(crate) fn custom_code_memory(&self) -> Option<&Arc<dyn CustomCodeMemory>> {
895 self.config().custom_code_memory.as_ref()
896 }
897
898 #[cfg(target_has_atomic = "64")]
899 pub(crate) fn epoch_counter(&self) -> &AtomicU64 {
900 &self.inner.epoch
901 }
902
903 #[cfg(target_has_atomic = "64")]
904 pub(crate) fn current_epoch(&self) -> u64 {
905 self.epoch_counter().load(Ordering::Relaxed)
906 }
907
908 /// Increments the epoch.
909 ///
910 /// When using epoch-based interruption, currently-executing Wasm
911 /// code within this engine will trap or yield "soon" when the
912 /// epoch deadline is reached or exceeded. (The configuration, and
913 /// the deadline, are set on the `Store`.) The intent of the
914 /// design is for this method to be called by the embedder at some
915 /// regular cadence, for example by a thread that wakes up at some
916 /// interval, or by a signal handler.
917 ///
918 /// See [`Config::epoch_interruption`](crate::Config::epoch_interruption)
919 /// for an introduction to epoch-based interruption and pointers
920 /// to the other relevant methods.
921 ///
922 /// When performing `increment_epoch` in a separate thread, consider using
923 /// [`Engine::weak`] to hold an [`EngineWeak`](crate::EngineWeak) and
924 /// performing [`EngineWeak::upgrade`](crate::EngineWeak::upgrade) on each
925 /// tick, so that the epoch ticking thread does not keep an [`Engine`] alive
926 /// longer than any of its consumers.
927 ///
928 /// ## Signal Safety
929 ///
930 /// This method is signal-safe: it does not make any syscalls, and
931 /// performs only an atomic increment to the epoch value in
932 /// memory.
933 #[cfg(target_has_atomic = "64")]
934 pub fn increment_epoch(&self) {
935 self.inner.epoch.fetch_add(1, Ordering::Relaxed);
936 }
937
938 /// Returns a [`std::hash::Hash`] that can be used to check precompiled WebAssembly compatibility.
939 ///
940 /// The outputs of [`Engine::precompile_module`] and [`Engine::precompile_component`]
941 /// are compatible with a different [`Engine`] instance only if the two engines use
942 /// compatible [`Config`]s. If this Hash matches between two [`Engine`]s then binaries
943 /// from one are guaranteed to deserialize in the other.
944 #[cfg(any(feature = "cranelift", feature = "winch"))]
945 pub fn precompile_compatibility_hash(&self) -> impl std::hash::Hash + '_ {
946 crate::compile::HashedEngineCompileEnv(self)
947 }
948
949 /// Returns the required alignment for a code image, if we
950 /// allocate in a way that is not a system `mmap()` that naturally
951 /// aligns it.
952 fn required_code_alignment(&self) -> usize {
953 self.custom_code_memory()
954 .map(|c| c.required_alignment())
955 .unwrap_or(1)
956 }
957
958 /// Loads a `CodeMemory` from the specified in-memory slice, copying it to a
959 /// uniquely owned mmap.
960 ///
961 /// The `expected` marker here is whether the bytes are expected to be a
962 /// precompiled module or a component.
963 pub(crate) fn load_code_bytes(
964 &self,
965 bytes: &[u8],
966 expected: ObjectKind,
967 ) -> Result<Arc<crate::CodeMemory>> {
968 self.load_code(
969 crate::runtime::vm::MmapVec::from_slice_with_alignment(
970 bytes,
971 self.required_code_alignment(),
972 )?,
973 expected,
974 )
975 }
976
977 /// Loads a `CodeMemory` from the specified memory region without copying
978 ///
979 /// The `expected` marker here is whether the bytes are expected to be
980 /// a precompiled module or a component. The `memory` provided is expected
981 /// to be a serialized module (.cwasm) generated by `[Module::serialize]`
982 /// or [`Engine::precompile_module] or their `Component` counterparts
983 /// [`Component::serialize`] or `[Engine::precompile_component]`.
984 ///
985 /// The memory provided is guaranteed to only be immutably by the runtime.
986 ///
987 /// # Safety
988 ///
989 /// As there is no copy here, the runtime will be making direct readonly use
990 /// of the provided memory. As such, outside writes to this memory region
991 /// will result in undefined and likely very undesirable behavior.
992 pub(crate) unsafe fn load_code_raw(
993 &self,
994 memory: NonNull<[u8]>,
995 expected: ObjectKind,
996 ) -> Result<Arc<crate::CodeMemory>> {
997 // SAFETY: the contract of this function is the same as that of
998 // `from_raw`.
999 unsafe { self.load_code(crate::runtime::vm::MmapVec::from_raw(memory)?, expected) }
1000 }
1001
1002 /// Like `load_code_bytes`, but creates a mmap from a file on disk.
1003 #[cfg(feature = "std")]
1004 pub(crate) fn load_code_file(
1005 &self,
1006 file: File,
1007 expected: ObjectKind,
1008 ) -> Result<Arc<crate::CodeMemory>> {
1009 self.load_code(
1010 crate::runtime::vm::MmapVec::from_file(file)
1011 .with_context(|| "Failed to create file mapping".to_string())?,
1012 expected,
1013 )
1014 }
1015
1016 pub(crate) fn load_code(
1017 &self,
1018 mmap: crate::runtime::vm::MmapVec,
1019 expected: ObjectKind,
1020 ) -> Result<Arc<crate::CodeMemory>> {
1021 self.check_compatible_with_native_host()
1022 .context("compilation settings are not compatible with the native host")?;
1023
1024 serialization::check_compatible(self, &mmap, expected)?;
1025 let mut code = crate::CodeMemory::new(self, mmap)?;
1026 code.publish()?;
1027 Ok(try_new(code)?)
1028 }
1029
1030 /// Unload process-related trap/signal handlers and destroy this engine.
1031 ///
1032 /// This method is not safe and is not widely applicable. It is not required
1033 /// to be called and is intended for use cases such as unloading a dynamic
1034 /// library from a process. It is difficult to invoke this method correctly
1035 /// and it requires careful coordination to do so.
1036 ///
1037 /// # Panics
1038 ///
1039 /// This method will panic if this `Engine` handle is not the last remaining
1040 /// engine handle.
1041 ///
1042 /// # Aborts
1043 ///
1044 /// This method will abort the process on some platforms in some situations
1045 /// where unloading the handler cannot be performed and an unrecoverable
1046 /// state is reached. For example on Unix platforms with signal handling
1047 /// the process will be aborted if the current signal handlers are not
1048 /// Wasmtime's.
1049 ///
1050 /// # Unsafety
1051 ///
1052 /// This method is not generally safe to call and has a number of
1053 /// preconditions that must be met to even possibly be safe. Even with these
1054 /// known preconditions met there may be other unknown invariants to uphold
1055 /// as well.
1056 ///
1057 /// * There must be no other instances of `Engine` elsewhere in the process.
1058 /// Note that this isn't just copies of this `Engine` but it's any other
1059 /// `Engine` at all. This unloads global state that is used by all
1060 /// `Engine`s so this instance must be the last.
1061 ///
1062 /// * On Unix platforms no other signal handlers could have been installed
1063 /// for signals that Wasmtime catches. In this situation Wasmtime won't
1064 /// know how to restore signal handlers that Wasmtime possibly overwrote
1065 /// when Wasmtime was initially loaded. If possible initialize other
1066 /// libraries first and then initialize Wasmtime last (e.g. defer creating
1067 /// an `Engine`).
1068 ///
1069 /// * All existing threads which have used this DLL or copy of Wasmtime may
1070 /// no longer use this copy of Wasmtime. Per-thread state is not iterated
1071 /// and destroyed. Only future threads may use future instances of this
1072 /// Wasmtime itself.
1073 ///
1074 /// If other crashes are seen from using this method please feel free to
1075 /// file an issue to update the documentation here with more preconditions
1076 /// that must be met.
1077 #[cfg(has_native_signals)]
1078 pub unsafe fn unload_process_handlers(self) {
1079 assert_eq!(Arc::weak_count(&self.inner), 0);
1080 assert_eq!(Arc::strong_count(&self.inner), 1);
1081
1082 // SAFETY: the contract of this function is the same as `deinit_traps`.
1083 #[cfg(not(miri))]
1084 unsafe {
1085 crate::runtime::vm::deinit_traps();
1086 }
1087 }
1088}
1089
1090/// A weak reference to an [`Engine`].
1091#[derive(Clone, Default)]
1092pub struct EngineWeak {
1093 inner: alloc::sync::Weak<EngineInner>,
1094}
1095
1096impl EngineWeak {
1097 /// Upgrade this weak reference into an [`Engine`]. Returns `None` if
1098 /// strong references (the [`Engine`] type itself) no longer exist.
1099 pub fn upgrade(&self) -> Option<Engine> {
1100 alloc::sync::Weak::upgrade(&self.inner).map(|inner| Engine { inner })
1101 }
1102}