Skip to main content

wasmtime/
engine.rs

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