Skip to main content

wasmtime/
engine.rs

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