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