1 use crate::prelude::*;
2 #[cfg(feature = "runtime")]
3 pub use crate::runtime::code_memory::CustomCodeMemory;
4 #[cfg(feature = "runtime")]
5 use crate::runtime::type_registry::TypeRegistry;
6 #[cfg(feature = "runtime")]
7 use crate::runtime::vm::GcRuntime;
8 use crate::Config;
9 use alloc::sync::Arc;
10 use core::ptr::NonNull;
11 #[cfg(target_has_atomic = "64")]
12 use core::sync::atomic::{AtomicU64, Ordering};
13 #[cfg(any(feature = "cranelift", feature = "winch"))]
14 use object::write::{Object, StandardSegment};
15 #[cfg(feature = "std")]
16 use std::{fs::File, path::Path};
17 use wasmparser::WasmFeatures;
18 use wasmtime_environ::{FlagValue, ObjectKind, TripleExt, Tunables};
19 
20 mod 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)]
45 pub struct Engine {
46     inner: Arc<EngineInner>,
47 }
48 
49 struct 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 
72 impl 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 
80 impl Default for Engine {
81     fn default() -> Engine {
82         Engine::new(&Config::default()).unwrap()
83     }
84 }
85 
86 impl 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(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(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             | "log2_min_function_alignment"
396             | "machine_code_cfg_info"
397             | "tls_model" // wasmtime doesn't use tls right now
398             | "stack_switch_model" // wasmtime doesn't use stack switching right now
399             | "opt_level" // opt level doesn't change semantics
400             | "enable_alias_analysis" // alias analysis-based opts don't change semantics
401             | "probestack_size_log2" // probestack above asserted disabled
402             | "regalloc" // shouldn't change semantics
403             | "enable_incremental_compilation_cache_checks" // shouldn't change semantics
404             | "enable_atomics" => return Ok(()),
405 
406             // Everything else is unknown and needs to be added somewhere to
407             // this list if encountered.
408             _ => {
409                 return Err(format!("unknown shared setting {flag:?} configured to {value:?}"))
410             }
411         };
412 
413         if !ok {
414             return Err(format!(
415                 "setting {flag:?} is configured to {value:?} which is not supported",
416             ));
417         }
418         Ok(())
419     }
420 
421     /// Same as `check_compatible_with_native_host` except used for ISA-specific
422     /// flags. This is used to test whether a configured ISA flag is indeed
423     /// available on the host platform itself.
424     pub(crate) fn check_compatible_with_isa_flag(
425         &self,
426         flag: &str,
427         value: &FlagValue,
428     ) -> Result<(), String> {
429         match value {
430             // ISA flags are used for things like CPU features, so if they're
431             // disabled then it's compatible with the native host.
432             FlagValue::Bool(false) => return Ok(()),
433 
434             // Fall through below where we test at runtime that features are
435             // available.
436             FlagValue::Bool(true) => {}
437 
438             // Pulley's pointer_width must match the host.
439             FlagValue::Enum("pointer32") => {
440                 return if cfg!(target_pointer_width = "32") {
441                     Ok(())
442                 } else {
443                     Err("wrong host pointer width".to_string())
444                 }
445             }
446             FlagValue::Enum("pointer64") => {
447                 return if cfg!(target_pointer_width = "64") {
448                     Ok(())
449                 } else {
450                     Err("wrong host pointer width".to_string())
451                 }
452             }
453 
454             // Only `bool` values are supported right now, other settings would
455             // need more support here.
456             _ => {
457                 return Err(format!(
458                     "isa-specific feature {flag:?} configured to unknown value {value:?}"
459                 ))
460             }
461         }
462 
463         let host_feature = match flag {
464             // aarch64 features to detect
465             "has_lse" => "lse",
466             "has_pauth" => "paca",
467             "has_fp16" => "fp16",
468 
469             // aarch64 features which don't need detection
470             // No effect on its own.
471             "sign_return_address_all" => return Ok(()),
472             // The pointer authentication instructions act as a `NOP` when
473             // unsupported, so it is safe to enable them.
474             "sign_return_address" => return Ok(()),
475             // No effect on its own.
476             "sign_return_address_with_bkey" => return Ok(()),
477             // The `BTI` instruction acts as a `NOP` when unsupported, so it
478             // is safe to enable it regardless of whether the host supports it
479             // or not.
480             "use_bti" => return Ok(()),
481 
482             // s390x features to detect
483             "has_vxrs_ext2" => "vxrs_ext2",
484             "has_mie2" => "mie2",
485 
486             // x64 features to detect
487             "has_cmpxchg16b" => "cmpxchg16b",
488             "has_sse3" => "sse3",
489             "has_ssse3" => "ssse3",
490             "has_sse41" => "sse4.1",
491             "has_sse42" => "sse4.2",
492             "has_popcnt" => "popcnt",
493             "has_avx" => "avx",
494             "has_avx2" => "avx2",
495             "has_fma" => "fma",
496             "has_bmi1" => "bmi1",
497             "has_bmi2" => "bmi2",
498             "has_avx512bitalg" => "avx512bitalg",
499             "has_avx512dq" => "avx512dq",
500             "has_avx512f" => "avx512f",
501             "has_avx512vl" => "avx512vl",
502             "has_avx512vbmi" => "avx512vbmi",
503             "has_lzcnt" => "lzcnt",
504 
505             // pulley features
506             "big_endian" if cfg!(target_endian = "big") => return Ok(()),
507             "big_endian" if cfg!(target_endian = "little") => {
508                 return Err("wrong host endianness".to_string())
509             }
510 
511             _ => {
512                 // FIXME: should enumerate risc-v features and plumb them
513                 // through to the `detect_host_feature` function.
514                 if cfg!(target_arch = "riscv64") && flag != "not_a_flag" {
515                     return Ok(());
516                 }
517                 return Err(format!(
518                     "don't know how to test for target-specific flag {flag:?} at runtime"
519                 ));
520             }
521         };
522 
523         let detect = match self.config().detect_host_feature {
524             Some(detect) => detect,
525             None => {
526                 return Err(format!(
527                     "cannot determine if host feature {host_feature:?} is \
528                      available at runtime, configure a probing function with \
529                      `Config::detect_host_feature`"
530                 ))
531             }
532         };
533 
534         match detect(host_feature) {
535             Some(true) => Ok(()),
536             Some(false) => Err(format!(
537                 "compilation setting {flag:?} is enabled, but not \
538                  available on the host",
539             )),
540             None => Err(format!(
541                 "failed to detect if target-specific flag {flag:?} is \
542                  available at runtime"
543             )),
544         }
545     }
546 
547     /// Returns whether this [`Engine`] is configured to execute with Pulley,
548     /// Wasmtime's interpreter.
549     ///
550     /// Note that Pulley is the default for host platforms that do not have a
551     /// Cranelift backend to support them. For example at the time of this
552     /// writing 32-bit x86 is not supported in Cranelift so the
553     /// `i686-unknown-linux-gnu` target would by default return `true` here.
554     pub fn is_pulley(&self) -> bool {
555         self.target().is_pulley()
556     }
557 }
558 
559 #[cfg(any(feature = "cranelift", feature = "winch"))]
560 impl Engine {
561     pub(crate) fn compiler(&self) -> &dyn wasmtime_environ::Compiler {
562         &*self.inner.compiler
563     }
564 
565     /// Ahead-of-time (AOT) compiles a WebAssembly module.
566     ///
567     /// The `bytes` provided must be in one of two formats:
568     ///
569     /// * A [binary-encoded][binary] WebAssembly module. This is always supported.
570     /// * A [text-encoded][text] instance of the WebAssembly text format.
571     ///   This is only supported when the `wat` feature of this crate is enabled.
572     ///   If this is supplied then the text format will be parsed before validation.
573     ///   Note that the `wat` feature is enabled by default.
574     ///
575     /// This method may be used to compile a module for use with a different target
576     /// host. The output of this method may be used with
577     /// [`Module::deserialize`](crate::Module::deserialize) on hosts compatible
578     /// with the [`Config`](crate::Config) associated with this [`Engine`].
579     ///
580     /// The output of this method is safe to send to another host machine for later
581     /// execution. As the output is already a compiled module, translation and code
582     /// generation will be skipped and this will improve the performance of constructing
583     /// a [`Module`](crate::Module) from the output of this method.
584     ///
585     /// [binary]: https://webassembly.github.io/spec/core/binary/index.html
586     /// [text]: https://webassembly.github.io/spec/core/text/index.html
587     pub fn precompile_module(&self, bytes: &[u8]) -> Result<Vec<u8>> {
588         crate::CodeBuilder::new(self)
589             .wasm_binary_or_text(bytes, None)?
590             .compile_module_serialized()
591     }
592 
593     /// Same as [`Engine::precompile_module`] except for a
594     /// [`Component`](crate::component::Component)
595     #[cfg(feature = "component-model")]
596     pub fn precompile_component(&self, bytes: &[u8]) -> Result<Vec<u8>> {
597         crate::CodeBuilder::new(self)
598             .wasm_binary_or_text(bytes, None)?
599             .compile_component_serialized()
600     }
601 
602     /// Produces a blob of bytes by serializing the `engine`'s configuration data to
603     /// be checked, perhaps in a different process, with the `check_compatible`
604     /// method below.
605     ///
606     /// The blob of bytes is inserted into the object file specified to become part
607     /// of the final compiled artifact.
608     pub(crate) fn append_compiler_info(&self, obj: &mut Object<'_>) {
609         serialization::append_compiler_info(self, obj, &serialization::Metadata::new(&self))
610     }
611 
612     #[cfg(any(feature = "cranelift", feature = "winch"))]
613     pub(crate) fn append_bti(&self, obj: &mut Object<'_>) {
614         let section = obj.add_section(
615             obj.segment_name(StandardSegment::Data).to_vec(),
616             wasmtime_environ::obj::ELF_WASM_BTI.as_bytes().to_vec(),
617             object::SectionKind::ReadOnlyData,
618         );
619         let contents = if self.compiler().is_branch_protection_enabled() {
620             1
621         } else {
622             0
623         };
624         obj.append_section_data(section, &[contents], 1);
625     }
626 }
627 
628 /// Return value from the [`Engine::detect_precompiled`] API.
629 #[derive(PartialEq, Eq, Copy, Clone, Debug)]
630 pub enum Precompiled {
631     /// The input bytes look like a precompiled core wasm module.
632     Module,
633     /// The input bytes look like a precompiled wasm component.
634     Component,
635 }
636 
637 #[cfg(feature = "runtime")]
638 impl Engine {
639     /// Eagerly initialize thread-local functionality shared by all [`Engine`]s.
640     ///
641     /// Wasmtime's implementation on some platforms may involve per-thread
642     /// setup that needs to happen whenever WebAssembly is invoked. This setup
643     /// can take on the order of a few hundred microseconds, whereas the
644     /// overhead of calling WebAssembly is otherwise on the order of a few
645     /// nanoseconds. This setup cost is paid once per-OS-thread. If your
646     /// application is sensitive to the latencies of WebAssembly function
647     /// calls, even those that happen first on a thread, then this function
648     /// can be used to improve the consistency of each call into WebAssembly
649     /// by explicitly frontloading the cost of the one-time setup per-thread.
650     ///
651     /// Note that this function is not required to be called in any embedding.
652     /// Wasmtime will automatically initialize thread-local-state as necessary
653     /// on calls into WebAssembly. This is provided for use cases where the
654     /// latency of WebAssembly calls are extra-important, which is not
655     /// necessarily true of all embeddings.
656     pub fn tls_eager_initialize() {
657         crate::runtime::vm::tls_eager_initialize();
658     }
659 
660     pub(crate) fn allocator(&self) -> &dyn crate::runtime::vm::InstanceAllocator {
661         self.inner.allocator.as_ref()
662     }
663 
664     pub(crate) fn gc_runtime(&self) -> Result<&Arc<dyn GcRuntime>> {
665         if let Some(rt) = &self.inner.gc_runtime {
666             Ok(rt)
667         } else {
668             bail!("no GC runtime: GC disabled at compile time or configuration time")
669         }
670     }
671 
672     pub(crate) fn profiler(&self) -> &dyn crate::profiling_agent::ProfilingAgent {
673         self.inner.profiler.as_ref()
674     }
675 
676     #[cfg(all(feature = "cache", any(feature = "cranelift", feature = "winch")))]
677     pub(crate) fn cache_config(&self) -> &wasmtime_cache::CacheConfig {
678         &self.config().cache_config
679     }
680 
681     pub(crate) fn signatures(&self) -> &TypeRegistry {
682         &self.inner.signatures
683     }
684 
685     #[cfg(feature = "runtime")]
686     pub(crate) fn custom_code_memory(&self) -> Option<&Arc<dyn CustomCodeMemory>> {
687         self.config().custom_code_memory.as_ref()
688     }
689 
690     #[cfg(target_has_atomic = "64")]
691     pub(crate) fn epoch_counter(&self) -> &AtomicU64 {
692         &self.inner.epoch
693     }
694 
695     #[cfg(target_has_atomic = "64")]
696     pub(crate) fn current_epoch(&self) -> u64 {
697         self.epoch_counter().load(Ordering::Relaxed)
698     }
699 
700     /// Increments the epoch.
701     ///
702     /// When using epoch-based interruption, currently-executing Wasm
703     /// code within this engine will trap or yield "soon" when the
704     /// epoch deadline is reached or exceeded. (The configuration, and
705     /// the deadline, are set on the `Store`.) The intent of the
706     /// design is for this method to be called by the embedder at some
707     /// regular cadence, for example by a thread that wakes up at some
708     /// interval, or by a signal handler.
709     ///
710     /// See [`Config::epoch_interruption`](crate::Config::epoch_interruption)
711     /// for an introduction to epoch-based interruption and pointers
712     /// to the other relevant methods.
713     ///
714     /// When performing `increment_epoch` in a separate thread, consider using
715     /// [`Engine::weak`] to hold an [`EngineWeak`](crate::EngineWeak) and
716     /// performing [`EngineWeak::upgrade`](crate::EngineWeak::upgrade) on each
717     /// tick, so that the epoch ticking thread does not keep an [`Engine`] alive
718     /// longer than any of its consumers.
719     ///
720     /// ## Signal Safety
721     ///
722     /// This method is signal-safe: it does not make any syscalls, and
723     /// performs only an atomic increment to the epoch value in
724     /// memory.
725     #[cfg(target_has_atomic = "64")]
726     pub fn increment_epoch(&self) {
727         self.inner.epoch.fetch_add(1, Ordering::Relaxed);
728     }
729 
730     /// Returns a [`std::hash::Hash`] that can be used to check precompiled WebAssembly compatibility.
731     ///
732     /// The outputs of [`Engine::precompile_module`] and [`Engine::precompile_component`]
733     /// are compatible with a different [`Engine`] instance only if the two engines use
734     /// compatible [`Config`]s. If this Hash matches between two [`Engine`]s then binaries
735     /// from one are guaranteed to deserialize in the other.
736     #[cfg(any(feature = "cranelift", feature = "winch"))]
737     pub fn precompile_compatibility_hash(&self) -> impl std::hash::Hash + '_ {
738         crate::compile::HashedEngineCompileEnv(self)
739     }
740 
741     /// Executes `f1` and `f2` in parallel if parallel compilation is enabled at
742     /// both runtime and compile time, otherwise runs them synchronously.
743     #[allow(dead_code)] // only used for the component-model feature right now
744     pub(crate) fn join_maybe_parallel<T, U>(
745         &self,
746         f1: impl FnOnce() -> T + Send,
747         f2: impl FnOnce() -> U + Send,
748     ) -> (T, U)
749     where
750         T: Send,
751         U: Send,
752     {
753         if self.config().parallel_compilation {
754             #[cfg(feature = "parallel-compilation")]
755             return rayon::join(f1, f2);
756         }
757         (f1(), f2())
758     }
759 
760     /// Returns the required alignment for a code image, if we
761     /// allocate in a way that is not a system `mmap()` that naturally
762     /// aligns it.
763     fn required_code_alignment(&self) -> usize {
764         self.custom_code_memory()
765             .map(|c| c.required_alignment())
766             .unwrap_or(1)
767     }
768 
769     /// Loads a `CodeMemory` from the specified in-memory slice, copying it to a
770     /// uniquely owned mmap.
771     ///
772     /// The `expected` marker here is whether the bytes are expected to be a
773     /// precompiled module or a component.
774     pub(crate) fn load_code_bytes(
775         &self,
776         bytes: &[u8],
777         expected: ObjectKind,
778     ) -> Result<Arc<crate::CodeMemory>> {
779         self.load_code(
780             crate::runtime::vm::MmapVec::from_slice_with_alignment(
781                 bytes,
782                 self.required_code_alignment(),
783             )?,
784             expected,
785         )
786     }
787 
788     /// Loads a `CodeMemory` from the specified memory region without copying
789     ///
790     /// The `expected` marker here is whether the bytes are expected to be
791     /// a precompiled module or a component.  The `memory` provided is expected
792     /// to be a serialized module (.cwasm) generated by `[Module::serialize]`
793     /// or [`Engine::precompile_module] or their `Component` counterparts
794     /// [`Component::serialize`] or `[Engine::precompile_component]`.
795     ///
796     /// The memory provided is guaranteed to only be immutably by the runtime.
797     ///
798     /// # Safety
799     ///
800     /// As there is no copy here, the runtime will be making direct readonly use
801     /// of the provided memory. As such, outside writes to this memory region
802     /// will result in undefined and likely very undesirable behavior.
803     pub(crate) unsafe fn load_code_raw(
804         &self,
805         memory: NonNull<[u8]>,
806         expected: ObjectKind,
807     ) -> Result<Arc<crate::CodeMemory>> {
808         self.load_code(crate::runtime::vm::MmapVec::from_raw(memory)?, expected)
809     }
810 
811     /// Like `load_code_bytes`, but creates a mmap from a file on disk.
812     #[cfg(feature = "std")]
813     pub(crate) fn load_code_file(
814         &self,
815         file: File,
816         expected: ObjectKind,
817     ) -> Result<Arc<crate::CodeMemory>> {
818         self.load_code(
819             crate::runtime::vm::MmapVec::from_file(file)
820                 .with_context(|| "Failed to create file mapping".to_string())?,
821             expected,
822         )
823     }
824 
825     pub(crate) fn load_code(
826         &self,
827         mmap: crate::runtime::vm::MmapVec,
828         expected: ObjectKind,
829     ) -> Result<Arc<crate::CodeMemory>> {
830         serialization::check_compatible(self, &mmap, expected)?;
831         let mut code = crate::CodeMemory::new(self, mmap)?;
832         code.publish()?;
833         Ok(Arc::new(code))
834     }
835 
836     /// Unload process-related trap/signal handlers and destroy this engine.
837     ///
838     /// This method is not safe and is not widely applicable. It is not required
839     /// to be called and is intended for use cases such as unloading a dynamic
840     /// library from a process. It is difficult to invoke this method correctly
841     /// and it requires careful coordination to do so.
842     ///
843     /// # Panics
844     ///
845     /// This method will panic if this `Engine` handle is not the last remaining
846     /// engine handle.
847     ///
848     /// # Aborts
849     ///
850     /// This method will abort the process on some platforms in some situations
851     /// where unloading the handler cannot be performed and an unrecoverable
852     /// state is reached. For example on Unix platforms with signal handling
853     /// the process will be aborted if the current signal handlers are not
854     /// Wasmtime's.
855     ///
856     /// # Unsafety
857     ///
858     /// This method is not generally safe to call and has a number of
859     /// preconditions that must be met to even possibly be safe. Even with these
860     /// known preconditions met there may be other unknown invariants to uphold
861     /// as well.
862     ///
863     /// * There must be no other instances of `Engine` elsewhere in the process.
864     ///   Note that this isn't just copies of this `Engine` but it's any other
865     ///   `Engine` at all. This unloads global state that is used by all
866     ///   `Engine`s so this instance must be the last.
867     ///
868     /// * On Unix platforms no other signal handlers could have been installed
869     ///   for signals that Wasmtime catches. In this situation Wasmtime won't
870     ///   know how to restore signal handlers that Wasmtime possibly overwrote
871     ///   when Wasmtime was initially loaded. If possible initialize other
872     ///   libraries first and then initialize Wasmtime last (e.g. defer creating
873     ///   an `Engine`).
874     ///
875     /// * All existing threads which have used this DLL or copy of Wasmtime may
876     ///   no longer use this copy of Wasmtime. Per-thread state is not iterated
877     ///   and destroyed. Only future threads may use future instances of this
878     ///   Wasmtime itself.
879     ///
880     /// If other crashes are seen from using this method please feel free to
881     /// file an issue to update the documentation here with more preconditions
882     /// that must be met.
883     #[cfg(has_native_signals)]
884     pub unsafe fn unload_process_handlers(self) {
885         assert_eq!(Arc::weak_count(&self.inner), 0);
886         assert_eq!(Arc::strong_count(&self.inner), 1);
887 
888         #[cfg(not(miri))]
889         crate::runtime::vm::deinit_traps();
890     }
891 }
892 
893 /// A weak reference to an [`Engine`].
894 #[derive(Clone)]
895 pub struct EngineWeak {
896     inner: alloc::sync::Weak<EngineInner>,
897 }
898 
899 impl EngineWeak {
900     /// Upgrade this weak reference into an [`Engine`]. Returns `None` if
901     /// strong references (the [`Engine`] type itself) no longer exist.
902     pub fn upgrade(&self) -> Option<Engine> {
903         alloc::sync::Weak::upgrade(&self.inner).map(|inner| Engine { inner })
904     }
905 }
906