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