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