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