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