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