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