wasmtime/config.rs
1use crate::Engine;
2use crate::prelude::*;
3use alloc::sync::Arc;
4use bitflags::Flags;
5use core::fmt;
6use core::num::{NonZeroU32, NonZeroUsize};
7use core::str::FromStr;
8#[cfg(any(feature = "cranelift", feature = "winch"))]
9use std::path::Path;
10pub use wasmparser::WasmFeatures;
11#[cfg(any(feature = "cranelift", feature = "winch"))]
12use wasmtime_environ::FlagValue;
13use wasmtime_environ::{ConfigTunables, OperatorCost, OperatorCostStrategy, TripleExt, Tunables};
14
15#[cfg(feature = "runtime")]
16use crate::memory::MemoryCreator;
17#[cfg(feature = "runtime")]
18use crate::profiling_agent::{self, ProfilingAgent};
19#[cfg(feature = "runtime")]
20use crate::runtime::vm::{GcRuntime, InstanceAllocator, OnDemandInstanceAllocator};
21
22#[cfg(feature = "async")]
23use crate::stack::{StackCreator, StackCreatorProxy};
24#[cfg(feature = "async")]
25use wasmtime_fiber::RuntimeFiberStackCreator;
26
27#[cfg(feature = "runtime")]
28pub use crate::runtime::code_memory::CustomCodeMemory;
29#[cfg(feature = "cache")]
30pub use wasmtime_cache::{Cache, CacheConfig};
31#[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
32pub use wasmtime_environ::CacheStore;
33pub use wasmtime_environ::{Inlining, RrConfig};
34
35pub(crate) const DEFAULT_WASM_BACKTRACE_MAX_FRAMES: NonZeroUsize = NonZeroUsize::new(20).unwrap();
36
37/// Represents the module instance allocation strategy to use.
38#[derive(Clone)]
39#[non_exhaustive]
40pub enum InstanceAllocationStrategy {
41 /// The on-demand instance allocation strategy.
42 ///
43 /// Resources related to a module instance are allocated at instantiation time and
44 /// immediately deallocated when the `Store` referencing the instance is dropped.
45 ///
46 /// This is the default allocation strategy for Wasmtime.
47 OnDemand,
48 /// The pooling instance allocation strategy.
49 ///
50 /// A pool of resources is created in advance and module instantiation reuses resources
51 /// from the pool. Resources are returned to the pool when the `Store` referencing the instance
52 /// is dropped.
53 ///
54 /// When GC is enabled, the pooling allocator requires that the GC heap
55 /// configuration matches the linear memory configuration (i.e.,
56 /// `gc_heap_reservation` must equal `memory_reservation`, etc.). By
57 /// default, if no `gc_heap_*` tunables are explicitly configured, they
58 /// automatically inherit the `memory_*` values.
59 #[cfg(feature = "pooling-allocator")]
60 Pooling(PoolingAllocationConfig),
61}
62
63impl InstanceAllocationStrategy {
64 /// The default pooling instance allocation strategy.
65 #[cfg(feature = "pooling-allocator")]
66 pub fn pooling() -> Self {
67 Self::Pooling(Default::default())
68 }
69}
70
71impl Default for InstanceAllocationStrategy {
72 fn default() -> Self {
73 Self::OnDemand
74 }
75}
76
77#[cfg(feature = "pooling-allocator")]
78impl From<PoolingAllocationConfig> for InstanceAllocationStrategy {
79 fn from(cfg: PoolingAllocationConfig) -> InstanceAllocationStrategy {
80 InstanceAllocationStrategy::Pooling(cfg)
81 }
82}
83
84#[derive(Clone)]
85/// Configure the strategy used for versioning in serializing and deserializing [`crate::Module`].
86pub enum ModuleVersionStrategy {
87 /// Use the wasmtime crate's full Cargo package version, including the
88 /// major, minor, and patch components (e.g. `"50.0.1"`).
89 ///
90 /// This means that, by default, modules serialized by one release of
91 /// Wasmtime can only be deserialized by exactly the same release of
92 /// Wasmtime, including patch releases.
93 WasmtimeVersion,
94 /// Use a custom version string. Must be at most 255 bytes.
95 Custom(String),
96 /// Emit no version string in serialization, and accept all version strings in deserialization.
97 None,
98}
99
100impl Default for ModuleVersionStrategy {
101 fn default() -> Self {
102 ModuleVersionStrategy::WasmtimeVersion
103 }
104}
105
106impl core::hash::Hash for ModuleVersionStrategy {
107 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
108 match self {
109 Self::WasmtimeVersion => env!("CARGO_PKG_VERSION").hash(hasher),
110 Self::Custom(s) => s.hash(hasher),
111 Self::None => {}
112 };
113 }
114}
115
116impl ModuleVersionStrategy {
117 /// Get the string-encoding version of the module.
118 pub fn as_str(&self) -> &str {
119 match &self {
120 Self::WasmtimeVersion => env!("CARGO_PKG_VERSION"),
121 Self::Custom(c) => c,
122 Self::None => "",
123 }
124 }
125}
126
127/// Global configuration options used to create an [`Engine`]
128/// and customize its behavior.
129///
130/// This structure exposed a builder-like interface and is primarily consumed by
131/// [`Engine::new()`].
132///
133/// The validation of `Config` is deferred until the engine is being built, thus
134/// a problematic config may cause [`Engine::new`] to fail.
135///
136/// # Defaults
137///
138/// The `Default` trait implementation and the return value from
139/// [`Config::new()`] are the same and represent the default set of
140/// configuration for an engine. The exact set of defaults will differ based on
141/// properties such as enabled Cargo features at compile time and the configured
142/// target (see [`Config::target`]). Configuration options document their
143/// default values and what the conditional value of the default is where
144/// applicable.
145#[derive(Clone)]
146pub struct Config {
147 #[cfg(any(feature = "cranelift", feature = "winch"))]
148 compiler_config: Option<CompilerConfig>,
149 target: Option<target_lexicon::Triple>,
150 #[cfg(feature = "gc")]
151 collector: Collector,
152 profiling_strategy: ProfilingStrategy,
153 tunables: ConfigTunables,
154
155 #[cfg(feature = "cache")]
156 pub(crate) cache: Option<Cache>,
157 #[cfg(feature = "runtime")]
158 pub(crate) mem_creator: Option<Arc<dyn MemoryCreator>>,
159 #[cfg(feature = "runtime")]
160 pub(crate) custom_code_memory: Option<Arc<dyn CustomCodeMemory>>,
161 pub(crate) allocation_strategy: InstanceAllocationStrategy,
162 pub(crate) max_wasm_stack: usize,
163 /// Explicitly enabled features via `Config::wasm_*` methods. This is a
164 /// signal that the embedder specifically wants something turned on
165 /// regardless of the defaults that Wasmtime might otherwise have enabled.
166 ///
167 /// Note that this, and `disabled_features` below, start as the empty set of
168 /// features to only track explicit user requests.
169 pub(crate) enabled_features: WasmFeatures,
170 /// Same as `enabled_features`, but for those that are explicitly disabled.
171 pub(crate) disabled_features: WasmFeatures,
172 pub(crate) wasm_backtrace_details_env_used: bool,
173 pub(crate) wasm_backtrace_max_frames: Option<NonZeroUsize>,
174 pub(crate) native_unwind_info: Option<bool>,
175 pub(crate) async_stack_size: usize,
176 pub(crate) async_stack_zeroing: bool,
177 #[cfg(feature = "async")]
178 pub(crate) stack_creator: Option<Arc<dyn RuntimeFiberStackCreator>>,
179 pub(crate) module_version: ModuleVersionStrategy,
180 pub(crate) parallel_compilation: bool,
181 pub(crate) memory_guaranteed_dense_image_size: u64,
182 pub(crate) force_memory_init_memfd: bool,
183 pub(crate) wmemcheck: bool,
184 #[cfg(feature = "coredump")]
185 pub(crate) coredump_on_trap: bool,
186 pub(crate) macos_use_mach_ports: bool,
187 pub(crate) detect_host_feature: Option<fn(&str) -> Option<bool>>,
188 pub(crate) x86_float_abi_ok: Option<bool>,
189 pub(crate) shared_memory: bool,
190}
191
192/// User-provided configuration for the compiler.
193#[cfg(any(feature = "cranelift", feature = "winch"))]
194#[derive(Debug, Clone)]
195struct CompilerConfig {
196 strategy: Option<Strategy>,
197 settings: crate::hash_map::HashMap<String, (String, UserSpecified)>,
198 flags: crate::hash_map::HashMap<String, UserSpecified>,
199 #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
200 cache_store: Option<Arc<dyn CacheStore>>,
201 clif_dir: Option<std::path::PathBuf>,
202 wmemcheck: bool,
203}
204
205#[cfg(any(feature = "cranelift", feature = "winch"))]
206#[derive(Debug, Clone)]
207enum UserSpecified {
208 Yes,
209 No,
210}
211
212#[cfg(any(feature = "cranelift", feature = "winch"))]
213impl CompilerConfig {
214 fn new() -> Self {
215 Self {
216 strategy: Strategy::Auto.not_auto(),
217 settings: Default::default(),
218 flags: Default::default(),
219 #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
220 cache_store: None,
221 clif_dir: None,
222 wmemcheck: false,
223 }
224 }
225
226 /// Ensures that the key is not set or equals to the given value.
227 /// If the key is not set, it will be set to the given value.
228 ///
229 /// # Returns
230 ///
231 /// Returns true if successfully set or already had the given setting
232 /// value, or false if the setting was explicitly set to something
233 /// else previously.
234 fn ensure_setting_unset_or_given(&mut self, k: &str, v: &str) -> bool {
235 if let Some((value, _)) = self.settings.get(k) {
236 if value != v {
237 return false;
238 }
239 } else {
240 self.settings
241 .insert(k.to_string(), (v.to_string(), UserSpecified::No));
242 }
243 true
244 }
245}
246
247#[cfg(any(feature = "cranelift", feature = "winch"))]
248impl Default for CompilerConfig {
249 fn default() -> Self {
250 Self::new()
251 }
252}
253
254impl Config {
255 /// Creates a new configuration object with the default configuration
256 /// specified.
257 pub fn new() -> Self {
258 let mut ret = Self {
259 tunables: ConfigTunables::default(),
260 #[cfg(any(feature = "cranelift", feature = "winch"))]
261 compiler_config: Some(CompilerConfig::default()),
262 target: None,
263 #[cfg(feature = "gc")]
264 collector: Collector::default(),
265 #[cfg(feature = "cache")]
266 cache: None,
267 profiling_strategy: ProfilingStrategy::None,
268 #[cfg(feature = "runtime")]
269 mem_creator: None,
270 #[cfg(feature = "runtime")]
271 custom_code_memory: None,
272 allocation_strategy: InstanceAllocationStrategy::OnDemand,
273 // 512k of stack -- note that this is chosen currently to not be too
274 // big, not be too small, and be a good default for most platforms.
275 // One platform of particular note is Windows where the stack size
276 // of the main thread seems to, by default, be smaller than that of
277 // Linux and macOS. This 512k value at least lets our current test
278 // suite pass on the main thread of Windows (using `--test-threads
279 // 1` forces this), or at least it passed when this change was
280 // committed.
281 max_wasm_stack: 512 * 1024,
282 wasm_backtrace_details_env_used: false,
283 wasm_backtrace_max_frames: Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES),
284 native_unwind_info: None,
285 enabled_features: WasmFeatures::empty(),
286 disabled_features: WasmFeatures::empty(),
287 async_stack_size: 2 << 20,
288 async_stack_zeroing: false,
289 #[cfg(feature = "async")]
290 stack_creator: None,
291 module_version: ModuleVersionStrategy::default(),
292 parallel_compilation: !cfg!(miri),
293 memory_guaranteed_dense_image_size: 16 << 20,
294 force_memory_init_memfd: false,
295 wmemcheck: false,
296 #[cfg(feature = "coredump")]
297 coredump_on_trap: false,
298 // Disable mach ports on miri since it doesn't emulate those APIs,
299 // and additionally disable it with ASAN by default because
300 // otherwise mach ports routes around signal handlers installed by
301 // ASAN.
302 macos_use_mach_ports: !cfg!(miri) && !cfg!(asan),
303 #[cfg(feature = "std")]
304 detect_host_feature: Some(detect_host_feature),
305 #[cfg(not(feature = "std"))]
306 detect_host_feature: None,
307 x86_float_abi_ok: None,
308 shared_memory: false,
309 };
310 ret.wasm_backtrace_details(WasmBacktraceDetails::Environment);
311 ret
312 }
313
314 #[cfg(any(feature = "cranelift", feature = "winch"))]
315 pub(crate) fn has_compiler(&self) -> bool {
316 self.compiler_config.is_some()
317 }
318
319 #[track_caller]
320 #[cfg(any(feature = "cranelift", feature = "winch"))]
321 fn compiler_config_mut(&mut self) -> &mut CompilerConfig {
322 self.compiler_config.as_mut().expect(
323 "cannot configure compiler settings for `Config`s \
324 created by `Config::without_compiler`",
325 )
326 }
327
328 /// Configure whether Wasm compilation is enabled.
329 ///
330 /// Disabling Wasm compilation will allow you to load and run
331 /// [pre-compiled][Engine::precompile_module] Wasm programs, but not
332 /// to compile and run new Wasm programs that have not already been
333 /// pre-compiled.
334 ///
335 /// Many compilation-related configuration methods will panic if compilation
336 /// has been disabled.
337 ///
338 /// Note that there are two ways to disable Wasm compilation:
339 ///
340 /// 1. Statically, by disabling the `"cranelift"` and `"winch"` cargo
341 /// features when building Wasmtime. These builds of Wasmtime will have
342 /// smaller code size, since they do not include any of the code to
343 /// compile Wasm.
344 ///
345 /// 2. Dynamically, by passing `false` to this method at run-time when
346 /// configuring Wasmtime. The Wasmtime binary will still include the code
347 /// for compiling Wasm, it just won't be executed, so code size is larger
348 /// than with the first approach.
349 ///
350 /// The static approach is better in most cases, however dynamically calling
351 /// `enable_compiler(false)` is useful whenever you create multiple
352 /// [`Engine`]s in the same process, some of which must be able to compile
353 /// Wasm and some of which should never do so. Tests are a common example of
354 /// such a situation, especially when there are multiple Rust binaries in
355 /// the same cargo workspace, and cargo's feature resolution enables the
356 /// `"cranelift"` or `"winch"` features across the whole workspace.
357 #[cfg(any(feature = "cranelift", feature = "winch"))]
358 pub fn enable_compiler(&mut self, enable: bool) -> &mut Self {
359 match (enable, &self.compiler_config) {
360 (true, Some(_)) | (false, None) => {}
361 (true, None) => {
362 self.compiler_config = Some(CompilerConfig::default());
363 }
364 (false, Some(_)) => {
365 self.compiler_config = None;
366 }
367 }
368 self
369 }
370
371 /// Configures the target platform of this [`Config`].
372 ///
373 /// This method is used to configure the output of compilation in an
374 /// [`Engine`]. This can be used, for example, to
375 /// cross-compile from one platform to another. By default, the host target
376 /// triple is used meaning compiled code is suitable to run on the host.
377 ///
378 /// Note that the [`Module`](crate::Module) type can only be created if the
379 /// target configured here matches the host. Otherwise if a cross-compile is
380 /// being performed where the host doesn't match the target then
381 /// [`Engine::precompile_module`] must be used instead.
382 ///
383 /// Target-specific flags (such as CPU features) will not be inferred by
384 /// default for the target when one is provided here. This means that this
385 /// can also be used, for example, with the host architecture to disable all
386 /// host-inferred feature flags. Configuring target-specific flags can be
387 /// done with [`Config::cranelift_flag_set`] and
388 /// [`Config::cranelift_flag_enable`].
389 ///
390 /// # Errors
391 ///
392 /// This method will error if the given target triple is not supported.
393 pub fn target(&mut self, target: &str) -> Result<&mut Self> {
394 self.target =
395 Some(target_lexicon::Triple::from_str(target).map_err(|e| crate::format_err!(e))?);
396
397 Ok(self)
398 }
399
400 /// Enables the incremental compilation cache in Cranelift, using the provided `CacheStore`
401 /// backend for storage.
402 ///
403 /// # Panics
404 ///
405 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
406 #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
407 pub fn enable_incremental_compilation(
408 &mut self,
409 cache_store: Arc<dyn CacheStore>,
410 ) -> Result<&mut Self> {
411 self.compiler_config_mut().cache_store = Some(cache_store);
412 Ok(self)
413 }
414
415 #[doc(hidden)]
416 #[deprecated(note = "no longer has any effect")]
417 #[cfg(feature = "async")]
418 pub fn async_support(&mut self, _enable: bool) -> &mut Self {
419 self
420 }
421
422 /// Configures whether DWARF debug information will be emitted
423 /// during compilation for a native debugger on the Wasmtime
424 /// process to consume.
425 ///
426 /// Note that the `debug-builtins` compile-time Cargo feature must also be
427 /// enabled for native debuggers such as GDB or LLDB to be able to debug
428 /// guest WebAssembly programs.
429 ///
430 /// By default this option is `false`.
431 /// **Note** Enabling this option is not compatible with the Winch compiler.
432 pub fn debug_info(&mut self, enable: bool) -> &mut Self {
433 self.tunables.debug_native = Some(enable);
434 self
435 }
436
437 /// Whether or not symbols are located in generated compiled module
438 /// artifacts.
439 ///
440 /// Wasmtime's currently representation of compiled artifacts is an ELF
441 /// file. ELF files have symbol tables and such and this option enables
442 /// whether symbols are emitted for wasm functions. This utility can be
443 /// useful when profiling wasm modules (many profilers work with
444 /// ELF-in-memory by default without futher configuration), introspection of
445 /// a `*.cwasm` (e.g. the symbol table is what `wasmtime objdump` reads), or
446 /// just general binary analysis of the result ELF file. Large wasm modules
447 /// can have large symbol tables, however, and the symbols serve no purpose
448 /// at runtime meaning that they are pure overhead for minimal module as
449 /// well. This option can be used to disable these symbols which will reduce
450 /// the debuggability of modules but will also reduce their size.
451 ///
452 /// Note that the ELF file representation is considered an implementation
453 /// detail of Wasmtime and embedders should not rely on this format.
454 /// Wasmtime may change the format of artifacts in the future.
455 ///
456 /// This option is `true` by default.
457 ///
458 /// This option is required if [`Config::debug_info`] is enabled.
459 pub fn debug_symbols(&mut self, enable: bool) -> &mut Self {
460 self.tunables.debug_symbols = Some(enable);
461 self
462 }
463
464 /// Configures whether compiled guest code will be instrumented to
465 /// provide debugging at the Wasm VM level.
466 ///
467 /// This is required in order to enable a guest-level debugging
468 /// API that can precisely examine Wasm VM state and (eventually,
469 /// once it is complete) set breakpoints and watchpoints and step
470 /// through code.
471 ///
472 /// Without this enabled, debugging can only be done via a native
473 /// debugger operating on the compiled guest code (see
474 /// [`Config::debug_info`] and is "best-effort": we may be able to
475 /// recover some Wasm locals or operand stack values, but it is
476 /// not guaranteed, even when optimizations are disabled.
477 ///
478 /// When this is enabled, additional instrumentation is inserted
479 /// that directly tracks the Wasm VM state at every step. This has
480 /// some performance impact, but allows perfect debugging
481 /// fidelity.
482 ///
483 /// Breakpoints, watchpoints, and stepping are not yet supported,
484 /// but will be added in a future version of Wasmtime.
485 ///
486 /// This enables use of the [`crate::FrameHandle`] API which is
487 /// provided by [`crate::Caller::debug_exit_frames`] or
488 /// [`crate::Store::debug_exit_frames`].
489 ///
490 /// ***Note*** Enabling this option is not compatible with the
491 /// Winch compiler.
492 #[cfg(feature = "debug")]
493 pub fn guest_debug(&mut self, enable: bool) -> &mut Self {
494 self.tunables.debug_guest = Some(enable);
495 self
496 }
497
498 /// Configures whether [`WasmBacktrace`] will be present in the context of
499 /// errors returned from Wasmtime.
500 ///
501 /// This method is deprecated in favor of
502 /// [`Config::wasm_backtrace_max_frames`]. Calling `wasm_backtrace(false)`
503 /// is equivalent to `wasm_backtrace_max_frames(None)`, and
504 /// `wasm_backtrace(true)` will leave `wasm_backtrace_max_frames` unchanged
505 /// if the value is `Some` and will otherwise restore the default `Some`
506 /// value.
507 ///
508 /// ***Note:*** Wasm backtraces are not yet OOM-safe; see
509 /// [`Config::wasm_backtrace_max_frames`] for details.
510 ///
511 /// [`WasmBacktrace`]: crate::WasmBacktrace
512 #[deprecated = "use `wasm_backtrace_max_frames` instead"]
513 pub fn wasm_backtrace(&mut self, enable: bool) -> &mut Self {
514 match (enable, self.wasm_backtrace_max_frames) {
515 (false, _) => self.wasm_backtrace_max_frames = None,
516 // Wasm backtraces were disabled; enable them with the
517 // default maximum number of frames to capture.
518 (true, None) => {
519 self.wasm_backtrace_max_frames = Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES)
520 }
521 // Wasm backtraces are already enabled; keep the existing
522 // max-frames configuration.
523 (true, Some(_)) => {}
524 }
525 self
526 }
527
528 /// Configures whether backtraces in `Trap` will parse debug info in the wasm file to
529 /// have filename/line number information.
530 ///
531 /// When enabled this will causes modules to retain debugging information
532 /// found in wasm binaries. This debug information will be used when a trap
533 /// happens to symbolicate each stack frame and attempt to print a
534 /// filename/line number for each wasm frame in the stack trace.
535 ///
536 /// By default this option is `WasmBacktraceDetails::Environment`, meaning
537 /// that wasm will read `WASMTIME_BACKTRACE_DETAILS` to indicate whether
538 /// details should be parsed. Note that the `std` feature of this crate must
539 /// be active to read environment variables, otherwise this is disabled by
540 /// default.
541 pub fn wasm_backtrace_details(&mut self, enable: WasmBacktraceDetails) -> &mut Self {
542 self.wasm_backtrace_details_env_used = false;
543 self.tunables.parse_wasm_debuginfo = match enable {
544 WasmBacktraceDetails::Enable => Some(true),
545 WasmBacktraceDetails::Disable => Some(false),
546 WasmBacktraceDetails::Environment => {
547 #[cfg(feature = "std")]
548 {
549 self.wasm_backtrace_details_env_used = true;
550 std::env::var("WASMTIME_BACKTRACE_DETAILS")
551 .map(|s| Some(s == "1"))
552 .unwrap_or(Some(false))
553 }
554 #[cfg(not(feature = "std"))]
555 {
556 Some(false)
557 }
558 }
559 };
560 self
561 }
562
563 /// Configures the maximum number of WebAssembly frames to collect in
564 /// backtraces.
565 ///
566 /// A backtrace may be collected whenever an error is returned from a host
567 /// function call through to WebAssembly or when WebAssembly itself hits a
568 /// trap condition, such as an out-of-bounds memory access. This flag
569 /// indicates, in these conditions, whether the backtrace is collected or
570 /// not and how many frames should be collected.
571 ///
572 /// Currently wasm backtraces are implemented through frame pointer walking.
573 /// This means that collecting a backtrace is expected to be a fast and
574 /// relatively cheap operation. Additionally backtrace collection is
575 /// suitable in concurrent environments since one thread capturing a
576 /// backtrace won't block other threads.
577 ///
578 /// Collected backtraces are attached via
579 /// [`Error::context`](crate::Error::context) to errors returned from host
580 /// functions. The [`WasmBacktrace`] type can be acquired via
581 /// [`Error::downcast_ref`](crate::Error::downcast_ref) to inspect the
582 /// backtrace. When this option is set to `None` then this context is never
583 /// applied to errors coming out of wasm.
584 ///
585 /// The default value is 20.
586 ///
587 /// ***Note:*** Capturing and symbolizing Wasm backtraces is not yet
588 /// OOM-safe: when backtraces are enabled, an allocation failure while
589 /// building a backtrace (for example, when a module with a name section
590 /// traps) may abort the process rather than return an
591 /// [`OutOfMemory`](crate::OutOfMemory) error. Set this option to `None` if
592 /// you rely on Wasmtime's OOM handling for Wasm execution.
593 ///
594 /// [`WasmBacktrace`]: crate::WasmBacktrace
595 pub fn wasm_backtrace_max_frames(&mut self, limit: Option<NonZeroUsize>) -> &mut Self {
596 self.wasm_backtrace_max_frames = limit;
597 self
598 }
599
600 /// Configures whether to generate native unwind information
601 /// (e.g. `.eh_frame` on Linux).
602 ///
603 /// This configuration option only exists to help third-party stack
604 /// capturing mechanisms, such as the system's unwinder or the `backtrace`
605 /// crate, determine how to unwind through Wasm frames. It does not affect
606 /// whether Wasmtime can capture Wasm backtraces or not. The presence of
607 /// [`WasmBacktrace`] is controlled by the
608 /// [`Config::wasm_backtrace_max_frames`] option.
609 ///
610 /// Native unwind information is included:
611 /// - When targeting Windows, since the Windows ABI requires it.
612 /// - By default.
613 ///
614 /// Note that systems loading many modules may wish to disable this
615 /// configuration option instead of leaving it on-by-default. Some platforms
616 /// exhibit quadratic behavior when registering/unregistering unwinding
617 /// information which can greatly slow down the module loading/unloading
618 /// process.
619 ///
620 /// [`WasmBacktrace`]: crate::WasmBacktrace
621 pub fn native_unwind_info(&mut self, enable: bool) -> &mut Self {
622 self.native_unwind_info = Some(enable);
623 self
624 }
625
626 /// Configures whether execution of WebAssembly will "consume fuel" to
627 /// either halt or yield execution as desired.
628 ///
629 /// This can be used to deterministically prevent infinitely-executing
630 /// WebAssembly code by instrumenting generated code to consume fuel as it
631 /// executes. When fuel runs out a trap is raised, however [`Store`] can be
632 /// configured to yield execution periodically via
633 /// [`crate::Store::fuel_async_yield_interval`].
634 ///
635 /// Note that a [`Store`] starts with no fuel, so if you enable this option
636 /// you'll have to be sure to pour some fuel into [`Store`] before
637 /// executing some code.
638 ///
639 /// Fuel accounting is not precise when WebAssembly traps. Each call is
640 /// still bounded by the fuel in the [`Store`], but the amount of fuel
641 /// listed as being consumed when WebAssembly traps may not accurately
642 /// reflect the exact amount that was consumed. This tradeoff enables
643 /// Wasmtime to optimize fuel-consumption primarily while still ensuring
644 /// that non-trapping code is always bounded. Embedders which need precise
645 /// fuel consumption metrics should not reuse a [`Store`] after a trap and
646 /// should not rely on the precise value of [`Store::get_fuel`] in the event
647 /// of a trap.
648 ///
649 /// Some configuration options make the fuel consumed by instantiation
650 /// depend on the host. When [`Config::memory_init_cow`] is enabled, which
651 /// it is by default, initializing linear memory consumes no fuel where the
652 /// initial image can be mapped copy-on-write (on Linux, or for a module
653 /// loaded from a file on other Unix platforms). Elsewhere the image is
654 /// copied instead, and the copy consumes fuel for the image's full size,
655 /// which is rounded up to the host page size. To consume the same fuel on
656 /// every platform, disable [`Config::memory_init_cow`].
657 ///
658 /// By default this option is `false`.
659 ///
660 /// [`Store`]: crate::Store
661 /// [`Store::get_fuel`]: crate::Store::get_fuel
662 pub fn consume_fuel(&mut self, enable: bool) -> &mut Self {
663 self.tunables.consume_fuel = Some(enable);
664 self
665 }
666
667 /// Configures the fuel cost of each WebAssembly operator.
668 ///
669 /// In addition to each operator's flat cost, [`OperatorCost::variable`]
670 /// configures per-byte, per-element, and per-page costs for operators whose
671 /// work depends on a runtime operand.
672 ///
673 /// These costs apply both to operators in function bodies and to operators
674 /// in constant expressions evaluated at instantiation time, such as global
675 /// initializers and element or data segment offsets.
676 ///
677 /// This is only relevant when [`Config::consume_fuel`] is enabled.
678 pub fn operator_cost(&mut self, cost: OperatorCost) -> &mut Self {
679 self.tunables.operator_cost = Some(OperatorCostStrategy::table(cost));
680 self
681 }
682
683 /// Enables epoch-based interruption.
684 ///
685 /// When executing code in async mode, we sometimes want to
686 /// implement a form of cooperative timeslicing: long-running Wasm
687 /// guest code should periodically yield to the executor
688 /// loop. This yielding could be implemented by using "fuel" (see
689 /// [`consume_fuel`](Config::consume_fuel)). However, fuel
690 /// instrumentation is somewhat expensive: it modifies the
691 /// compiled form of the Wasm code so that it maintains a precise
692 /// instruction count, frequently checking this count against the
693 /// remaining fuel. If one does not need this precise count or
694 /// deterministic interruptions and needs only a periodic
695 /// interrupt of some form, then It would be better to have a more
696 /// lightweight mechanism.
697 ///
698 /// Epoch-based interruption is that mechanism. There is a global
699 /// "epoch", which is a counter that divides time into arbitrary
700 /// periods (or epochs). This counter lives on the
701 /// [`Engine`] and can be incremented by calling
702 /// [`Engine::increment_epoch`].
703 /// Epoch-based instrumentation works by setting a "deadline
704 /// epoch". The compiled code knows the deadline, and at certain
705 /// points, checks the current epoch against that deadline. It
706 /// will yield if the deadline has been reached.
707 ///
708 /// The idea is that checking an infrequently-changing counter is
709 /// cheaper than counting and frequently storing a precise metric
710 /// (instructions executed) locally. The interruptions are not
711 /// deterministic, but if the embedder increments the epoch in a
712 /// periodic way (say, every regular timer tick by a thread or
713 /// signal handler), then we can ensure that all async code will
714 /// yield to the executor within a bounded time.
715 ///
716 /// The [`Store`](crate::Store) tracks the deadline, and controls
717 /// what happens when the deadline is reached during
718 /// execution. Several behaviors are possible:
719 ///
720 /// - Trap if code is executing when the epoch deadline is
721 /// met. See
722 /// [`Store::epoch_deadline_trap`](crate::Store::epoch_deadline_trap).
723 ///
724 /// - Call an arbitrary function. This function may chose to trap or
725 /// increment the epoch. See
726 /// [`Store::epoch_deadline_callback`](crate::Store::epoch_deadline_callback).
727 ///
728 /// - Yield to the executor loop, then resume when the future is
729 /// next polled. See
730 /// [`Store::epoch_deadline_async_yield_and_update`](crate::Store::epoch_deadline_async_yield_and_update).
731 ///
732 /// Trapping is the default. The yielding behaviour may be used for
733 /// the timeslicing behavior described above.
734 ///
735 /// This feature is available with or without async support.
736 /// However, without async support, the timeslicing behaviour is
737 /// not available. This means epoch-based interruption can only
738 /// serve as a simple external-interruption mechanism.
739 ///
740 /// An initial deadline must be set before executing code by calling
741 /// [`Store::set_epoch_deadline`](crate::Store::set_epoch_deadline). If this
742 /// deadline is not configured then wasm will immediately trap.
743 ///
744 /// ## Interaction with blocking host calls
745 ///
746 /// Epochs (and fuel) do not assist in handling WebAssembly code blocked in
747 /// a call to the host. For example if the WebAssembly function calls
748 /// `wasi:io/poll.poll` to sleep epochs will not assist in waking this up or
749 /// timing it out. Epochs intentionally only affect running WebAssembly code
750 /// itself and it's left to the embedder to determine how best to wake up
751 /// indefinitely blocking code in the host.
752 ///
753 /// The typical solution for this, however, is to use the `async` variant of
754 /// WASI host functions. This models computation as a Rust `Future` which
755 /// means that when blocking happens the future is only suspended and
756 /// control yields back to the main event loop. This gives the embedder the
757 /// opportunity to use `tokio::time::timeout` for example on a wasm
758 /// computation and have the desired effect of cancelling a blocking
759 /// operation when a timeout expires.
760 ///
761 /// ## Limitations with malicious guests
762 ///
763 /// Epochs are designed to handle malicious WebAssembly guests -- the
764 /// deadline check cannot be avoided by WebAssembly code. It is safe to use
765 /// epoch deadlines to limit the execution time of untrusted code.
766 ///
767 /// Note, though, that a current limitation to this is that
768 /// bulk-data-transfer instructions, such as `memory.copy`, only check the
769 /// epoch once at the start of the operation. These operations can take a
770 /// variable amount of time to complete based on how many bytes are being
771 /// copied. This means that the maximal time slice a guest might take is
772 /// the maximum of the epoch interval and the largest
773 /// memory-copy-style-instruction executed. The size of a copy is bounded
774 /// on the size of linear memory or GC heap size. In the limit, however, a
775 /// guest using a 64-bit linear memory with a 128GiB size could issue a
776 /// 128GiB `memory.copy` which would have no preemption within the
777 /// instruction itself. Hosts which need strict time limits for guests right
778 /// now are recommended to ensure that the store's allocated heap size
779 /// (linear memory + GC heap) are bounded with a
780 /// [`ResourceLimiter`](crate::ResourceLimiter).
781 ///
782 /// ## When to use fuel vs. epochs
783 ///
784 /// In general, epoch-based interruption results in faster
785 /// execution. This difference is sometimes significant: in some
786 /// measurements, up to 2-3x. This is because epoch-based
787 /// interruption does less work: it only watches for a global
788 /// rarely-changing counter to increment, rather than keeping a
789 /// local frequently-changing counter and comparing it to a
790 /// deadline.
791 ///
792 /// Fuel, in contrast, should be used when *deterministic*
793 /// yielding or trapping is needed. For example, if it is required
794 /// that the same function call with the same starting state will
795 /// always either complete or trap with an out-of-fuel error,
796 /// deterministically, then fuel with a fixed bound should be
797 /// used.
798 ///
799 /// **Note** Enabling this option is not compatible with the Winch compiler.
800 ///
801 /// # See Also
802 ///
803 /// - [`Store::set_epoch_deadline`](crate::Store::set_epoch_deadline)
804 /// - [`Store::epoch_deadline_trap`](crate::Store::epoch_deadline_trap)
805 /// - [`Store::epoch_deadline_callback`](crate::Store::epoch_deadline_callback)
806 /// - [`Store::epoch_deadline_async_yield_and_update`](crate::Store::epoch_deadline_async_yield_and_update)
807 pub fn epoch_interruption(&mut self, enable: bool) -> &mut Self {
808 self.tunables.epoch_interruption = Some(enable);
809 self
810 }
811
812 /// XXX: MMU interruption is not yet fully landed; this config flag, not yet
813 /// plumbed through to the CLI, serves as a feature flag that keeps its
814 /// landed portions from kicking in.
815 ///
816 /// Enables MMU-based interruption, a lower-overhead alternative to
817 /// [`Config::epoch_interruption`]. It uses memory-protection faults instead
818 /// of epoch deadline comparisons to prod a running Wasm guest to yield.
819 ///
820 /// # How it works
821 ///
822 /// Cranelift emits, at each loop backedge and function prologue, a load
823 /// from a per-store "interrupt page". To trigger an interruption, the
824 /// embedder marks that page as inaccessible; the resulting SIGSEGV is
825 /// caught by Wasmtime's signal handler, which distinguishes an
826 /// interrupt-check load from an actual crash by consulting a record of each
827 /// such load in the trap table. The signal handler then causes the active
828 /// fiber to yield.
829 ///
830 /// # Compared to `epoch_interruption`
831 ///
832 /// - Faster. Whereas epoch interruption needs to compare, branch, and keep
833 /// a deadline register coherent, MMU interruption does only a single
834 /// (dead) load from a per-store memory page. In the no-interruption case,
835 /// the load completes successfully, and overhead (versus doing nothing)
836 /// is 2.8% on the SpiderMonkey Sightglass benchmark, compared to 14.4%
837 /// for epoch interruption. Factoring in interruptions, the SpiderMonkey
838 /// Markdown-parsing workload, when run under `wasmtime serve`, shows a
839 /// 12% boost in throughput over epoch interruption and a 19% reduction in
840 /// p50 latency.
841 /// - Also non-deterministic. The same guidance in
842 /// [`Config::epoch_interruption`] about fuel vs. epochs applies here.
843 /// - Equally fine-grained. Checks for MMU interruption happen at the same
844 /// points in the compiled Wasm as checks for epoch interruption.
845 /// - Less flexible. Unlike epochs, there is, as of yet, no configurable
846 /// per-store interrupt behavior. When triggered, interruption always
847 /// causes the running fiber to yield; the `Store::epoch_deadline_*`
848 /// callbacks are not consulted.
849 ///
850 /// # Triggering an interruption
851 ///
852 /// Interruptions are triggered from outside the Wasm guest code by an
853 /// [`MmuInterrupter`](crate::MmuInterrupter), which hands each running
854 /// [`Store`] an interrupt page and protects it when that store is due to
855 /// yield. The [`Engine`] owns a single interrupter, shared by all its
856 /// stores. You must provide this interrupter using
857 /// [`Config::with_mmu_interrupter`] before running code.
858 /// [`TimingWheelInterrupter`](crate::TimingWheelInterrupter) is a good
859 /// default implementation; like the epoch counter, it does nothing until
860 /// you tick it.
861 ///
862 /// # Requirements
863 ///
864 /// - **Async.** Since MMU interruption always causes the fiber to yield,
865 /// wasmtime must be built with the `async` feature. Configuring an engine
866 /// with `mmu_interruption()` puts every [`Store`] derived from it into
867 /// async mode automatically.
868 /// - **Cranelift.** Winch does not support it.
869 /// - **Linux on x86_64 or aarch64 target.** Cross-compilation from other
870 /// hosts is fine.
871 /// - **Native signals**, because we depend on a signal handler.
872 /// - **Signals-based traps**, because signal-handler installation (in
873 /// [`Engine::new()`]) is currently gated on this. It should be possible
874 /// to remove this dependency, but the use cases are few, and threading
875 /// the value of `signals_based_traps` into the signal handler may be
876 /// nontrivial.
877 ///
878 /// # Errors
879 ///
880 /// Some requirements are validated after config time: some when an
881 /// [`Engine`] is instantiated (which calls [`Config::validate`] herein) and
882 /// others when code is loaded into the engine. Nothing panics; errors are
883 /// reported via return values.
884 #[doc(hidden)]
885 pub fn mmu_interruption(&mut self, enable: bool) -> &mut Self {
886 self.tunables.mmu_interruption = Some(enable);
887 self
888 }
889
890 /// Whether this build of Wasmtime can run code on this host with
891 /// [`Self::mmu_interruption`] enabled.
892 #[doc(hidden)]
893 pub fn is_mmu_interruption_runtime_available() -> bool {
894 cfg!(has_mmu_interruption_runtime)
895 }
896
897 /// XXX: For internal fuzzing and debugging use only!
898 #[doc(hidden)]
899 pub fn gc_zeal_alloc_counter(&mut self, counter: Option<NonZeroU32>) -> Result<&mut Self> {
900 #[cfg(not(gc_zeal))]
901 {
902 let _ = counter;
903 bail!(
904 "cannot set `gc_zeal_alloc_counter` because Wasmtime was not built with `cfg(gc_zeal)`"
905 );
906 }
907
908 #[cfg(gc_zeal)]
909 {
910 self.tunables.gc_zeal_alloc_counter = Some(counter);
911 Ok(self)
912 }
913 }
914
915 /// Configures the maximum amount of stack space available for
916 /// executing WebAssembly code.
917 ///
918 /// WebAssembly has well-defined semantics on stack overflow. This is
919 /// intended to be a knob which can help configure how much stack space
920 /// wasm execution is allowed to consume. Note that the number here is not
921 /// super-precise, but rather wasm will take at most "pretty close to this
922 /// much" stack space.
923 ///
924 /// If a wasm call (or series of nested wasm calls) take more stack space
925 /// than the `size` specified then a stack overflow trap will be raised.
926 ///
927 /// Caveat: this knob only limits the stack space consumed by wasm code.
928 /// More importantly, it does not ensure that this much stack space is
929 /// available on the calling thread stack. Exhausting the thread stack
930 /// typically leads to an **abort** of the process.
931 ///
932 /// Here are some examples of how that could happen:
933 ///
934 /// - Let's assume this option is set to 2 MiB and then a thread that has
935 /// a stack with 512 KiB left.
936 ///
937 /// If wasm code consumes more than 512 KiB then the process will be aborted.
938 ///
939 /// - Assuming the same conditions, but this time wasm code does not consume
940 /// any stack but calls into a host function. The host function consumes
941 /// more than 512 KiB of stack space. The process will be aborted.
942 ///
943 /// There's another gotcha related to recursive calling into wasm: the stack
944 /// space consumed by a host function is counted towards this limit. The
945 /// host functions are not prevented from consuming more than this limit.
946 /// However, if the host function that used more than this limit and called
947 /// back into wasm, then the execution will trap immediately because of
948 /// stack overflow.
949 ///
950 /// When the `async` feature is enabled, this value cannot exceed the
951 /// `async_stack_size` option. Be careful not to set this value too close
952 /// to `async_stack_size` as doing so may limit how much stack space
953 /// is available for host functions.
954 ///
955 /// By default this option is 512 KiB.
956 ///
957 /// # Errors
958 ///
959 /// The [`Engine::new`] method will fail if the `size` specified here is
960 /// either 0 or larger than the [`Config::async_stack_size`] configuration.
961 pub fn max_wasm_stack(&mut self, size: usize) -> &mut Self {
962 self.max_wasm_stack = size;
963 self
964 }
965
966 /// Configures the size of the stacks used for asynchronous execution.
967 ///
968 /// This setting configures the size of the stacks that are allocated for
969 /// asynchronous execution. The value cannot be less than `max_wasm_stack`.
970 ///
971 /// The amount of stack space guaranteed for host functions is
972 /// `async_stack_size - max_wasm_stack`, so take care not to set these two values
973 /// close to one another; doing so may cause host functions to overflow the
974 /// stack and abort the process.
975 ///
976 /// By default this option is 2 MiB.
977 ///
978 /// # Errors
979 ///
980 /// The [`Engine::new`] method will fail if the value for this option is
981 /// smaller than the [`Config::max_wasm_stack`] option.
982 pub fn async_stack_size(&mut self, size: usize) -> &mut Self {
983 self.async_stack_size = size;
984 self
985 }
986
987 /// Configures whether or not stacks used for async futures are zeroed
988 /// before (re)use.
989 ///
990 /// When the [`call_async`] variant of calling WebAssembly is used
991 /// then Wasmtime will create a separate runtime execution stack for each
992 /// future produced by [`call_async`]. By default upon allocation, depending
993 /// on the platform, these stacks might be filled with uninitialized
994 /// memory. This is safe and correct because, modulo bugs in Wasmtime,
995 /// compiled Wasm code will never read from a stack slot before it
996 /// initializes the stack slot.
997 ///
998 /// However, as a defense-in-depth mechanism, you may configure Wasmtime to
999 /// ensure that these stacks are zeroed before they are used. Notably, if
1000 /// you are using the pooling allocator, stacks can be pooled and reused
1001 /// across different Wasm guests; ensuring that stacks are zeroed can
1002 /// prevent data leakage between Wasm guests even in the face of potential
1003 /// read-of-stack-slot-before-initialization bugs in Wasmtime's compiler.
1004 ///
1005 /// Stack zeroing can be a costly operation in highly concurrent
1006 /// environments due to modifications of the virtual address space requiring
1007 /// process-wide synchronization. It can also be costly in `no-std`
1008 /// environments that must manually zero memory, and cannot rely on an OS
1009 /// and virtual memory to provide zeroed pages.
1010 ///
1011 /// This option defaults to `false`.
1012 ///
1013 /// [`call_async`]: crate::TypedFunc::call_async
1014 pub fn async_stack_zeroing(&mut self, enable: bool) -> &mut Self {
1015 self.async_stack_zeroing = enable;
1016 self
1017 }
1018
1019 /// Explicitly enables (and un-disables) a given set of [`WasmFeatures`].
1020 ///
1021 /// Note: this is a low-level method that does not necessarily imply that
1022 /// wasmtime _supports_ a feature. It should only be used to _disable_
1023 /// features that callers want to be rejected by the parser or _enable_
1024 /// features callers are certain that the current configuration of wasmtime
1025 /// supports.
1026 ///
1027 /// Feature validation is deferred until an engine is being built, thus by
1028 /// enabling features here a caller may cause
1029 /// [`Engine::new`] to fail later, if the feature
1030 /// configuration isn't supported.
1031 pub fn wasm_features(&mut self, flag: WasmFeatures, enable: bool) -> &mut Self {
1032 self.enabled_features.set(flag, enable);
1033 self.disabled_features.set(flag, !enable);
1034 self
1035 }
1036
1037 /// Configures whether the WebAssembly tail calls proposal will be enabled
1038 /// for compilation or not.
1039 ///
1040 /// The [WebAssembly tail calls proposal] introduces the `return_call` and
1041 /// `return_call_indirect` instructions. These instructions allow for Wasm
1042 /// programs to implement some recursive algorithms with *O(1)* stack space
1043 /// usage.
1044 ///
1045 /// This is `true` by default.
1046 ///
1047 /// [WebAssembly tail calls proposal]: https://github.com/WebAssembly/tail-call
1048 pub fn wasm_tail_call(&mut self, enable: bool) -> &mut Self {
1049 self.wasm_features(WasmFeatures::TAIL_CALL, enable);
1050 self
1051 }
1052
1053 /// Configures whether the WebAssembly [branch-hinting] proposal is enabled.
1054 ///
1055 /// When enabled, the `metadata.code.branch_hint` custom section is parsed
1056 /// and used to lay out cold code paths during compilation. The hints are
1057 /// advisory and never affect execution semantics.
1058 ///
1059 /// This is `false` by default until the proposal has been fuzzed.
1060 ///
1061 /// [branch-hinting]: https://github.com/WebAssembly/branch-hinting
1062 pub fn wasm_branch_hinting(&mut self, enable: bool) -> &mut Self {
1063 self.tunables.branch_hinting = Some(enable);
1064 self
1065 }
1066
1067 /// Configures whether the WebAssembly custom-page-sizes proposal will be
1068 /// enabled for compilation or not.
1069 ///
1070 /// The [WebAssembly custom-page-sizes proposal] allows a memory to
1071 /// customize its page sizes. By default, Wasm page sizes are 64KiB
1072 /// large. This proposal allows the memory to opt into smaller page sizes
1073 /// instead, allowing Wasm to run in environments with less than 64KiB RAM
1074 /// available, for example.
1075 ///
1076 /// Note that the page size is part of the memory's type, and because
1077 /// different memories may have different types, they may also have
1078 /// different page sizes.
1079 ///
1080 /// Currently the only valid page sizes are 64KiB (the default) and 1
1081 /// byte. Future extensions may relax this constraint and allow all powers
1082 /// of two.
1083 ///
1084 /// Support for this proposal is disabled by default.
1085 ///
1086 /// [WebAssembly custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
1087 pub fn wasm_custom_page_sizes(&mut self, enable: bool) -> &mut Self {
1088 self.wasm_features(WasmFeatures::CUSTOM_PAGE_SIZES, enable);
1089 self
1090 }
1091
1092 /// Configures whether the WebAssembly compact imports proposal is enabled.
1093 ///
1094 /// The [WebAssembly compact import section proposal]
1095 /// adds two compact encodings for imports:
1096 /// - A module name and a list of `(item name, type)` pairs
1097 /// - A module name, a type, and a list of item names
1098 ///
1099 /// This reduces redundant module and type listings, and can
1100 /// reduce WebAssembly file size, especially in files with many
1101 /// repeated imports.
1102 ///
1103 /// When enabled, compact imports are accepted in binary and text-format inputs.
1104 ///
1105 /// This feature is `false` by default.
1106 ///
1107 /// [WebAssembly compact import section proposal]: https://github.com/WebAssembly/compact-import-section
1108 pub fn wasm_compact_imports(&mut self, enable: bool) -> &mut Self {
1109 self.wasm_features(WasmFeatures::COMPACT_IMPORTS, enable);
1110 self
1111 }
1112
1113 /// Configures whether the WebAssembly [threads] proposal will be enabled
1114 /// for compilation.
1115 ///
1116 /// This feature gates items such as shared memories and atomic
1117 /// instructions. Note that the threads feature depends on the bulk memory
1118 /// feature, which is enabled by default. Additionally note that while the
1119 /// wasm feature is called "threads" it does not actually include the
1120 /// ability to spawn threads. Spawning threads is part of the [wasi-threads]
1121 /// proposal which is a separately gated feature in Wasmtime.
1122 ///
1123 /// Embeddings of Wasmtime are able to build their own custom threading
1124 /// scheme on top of the core wasm threads proposal, however.
1125 ///
1126 /// The default value for this option is whether the `threads`
1127 /// crate feature of Wasmtime is enabled or not. By default this crate
1128 /// feature is enabled.
1129 ///
1130 /// [threads]: https://github.com/webassembly/threads
1131 /// [wasi-threads]: https://github.com/webassembly/wasi-threads
1132 #[cfg(feature = "threads")]
1133 pub fn wasm_threads(&mut self, enable: bool) -> &mut Self {
1134 self.wasm_features(WasmFeatures::THREADS, enable);
1135 self
1136 }
1137
1138 /// Configures whether the [WebAssembly reference types proposal][proposal]
1139 /// will be enabled for compilation.
1140 ///
1141 /// This feature gates items such as the `externref` and `funcref` types as
1142 /// well as allowing a module to define multiple tables.
1143 ///
1144 /// Note that the reference types proposal depends on the bulk memory proposal.
1145 ///
1146 /// This feature is `true` by default.
1147 ///
1148 /// # Errors
1149 ///
1150 /// The validation of this feature are deferred until the engine is being built,
1151 /// and thus may cause [`Engine::new`] fail if the `bulk_memory` feature is disabled.
1152 ///
1153 /// [proposal]: https://github.com/webassembly/reference-types
1154 #[cfg(feature = "gc")]
1155 pub fn wasm_reference_types(&mut self, enable: bool) -> &mut Self {
1156 self.wasm_features(WasmFeatures::REFERENCE_TYPES, enable);
1157 self
1158 }
1159
1160 /// Configures whether the [WebAssembly function references
1161 /// proposal][proposal] will be enabled for compilation.
1162 ///
1163 /// This feature gates non-nullable reference types, function reference
1164 /// types, `call_ref`, `ref.func`, and non-nullable reference related
1165 /// instructions.
1166 ///
1167 /// Note that the function references proposal depends on the reference
1168 /// types proposal.
1169 ///
1170 /// This feature is `true` by default.
1171 ///
1172 /// [proposal]: https://github.com/WebAssembly/function-references
1173 #[cfg(feature = "gc")]
1174 pub fn wasm_function_references(&mut self, enable: bool) -> &mut Self {
1175 self.wasm_features(WasmFeatures::FUNCTION_REFERENCES, enable);
1176 self
1177 }
1178
1179 /// Configures whether the [WebAssembly wide-arithmetic][proposal] will be
1180 /// enabled for compilation.
1181 ///
1182 /// This feature is `true` by default.
1183 ///
1184 /// [proposal]: https://github.com/WebAssembly/wide-arithmetic
1185 pub fn wasm_wide_arithmetic(&mut self, enable: bool) -> &mut Self {
1186 self.wasm_features(WasmFeatures::WIDE_ARITHMETIC, enable);
1187 self
1188 }
1189
1190 /// Configures whether the [WebAssembly Garbage Collection
1191 /// proposal][proposal] will be enabled for compilation.
1192 ///
1193 /// This feature gates `struct` and `array` type definitions and references,
1194 /// the `i31ref` type, and all related instructions.
1195 ///
1196 /// Note that the function references proposal depends on the typed function
1197 /// references proposal.
1198 ///
1199 /// This feature is `true` by default.
1200 ///
1201 /// [proposal]: https://github.com/WebAssembly/gc
1202 pub fn wasm_gc(&mut self, enable: bool) -> &mut Self {
1203 self.wasm_features(WasmFeatures::GC, enable);
1204 self
1205 }
1206
1207 /// Configures whether the WebAssembly SIMD proposal will be
1208 /// enabled for compilation.
1209 ///
1210 /// The [WebAssembly SIMD proposal][proposal]. This feature gates items such
1211 /// as the `v128` type and all of its operators being in a module. Note that
1212 /// this does not enable the [relaxed simd proposal].
1213 ///
1214 /// **Note**
1215 ///
1216 /// On x86_64 platforms the base CPU feature requirement for SIMD
1217 /// is SSE2 for the Cranelift compiler and AVX for the Winch compiler.
1218 ///
1219 /// On riscv64 the Cranelift compiler requires the `has_v` (or
1220 /// `has_zvl128b`) setting for SIMD, which is not detected when
1221 /// [`Config::target`] is used. Without it creating an [`Engine`] fails
1222 /// unless this option and [`Config::wasm_relaxed_simd`] are disabled.
1223 ///
1224 /// This is `true` by default.
1225 ///
1226 /// [proposal]: https://github.com/webassembly/simd
1227 /// [relaxed simd proposal]: https://github.com/WebAssembly/relaxed-simd
1228 pub fn wasm_simd(&mut self, enable: bool) -> &mut Self {
1229 self.wasm_features(WasmFeatures::SIMD, enable);
1230 self
1231 }
1232
1233 /// Configures whether the WebAssembly Relaxed SIMD proposal will be
1234 /// enabled for compilation.
1235 ///
1236 /// The relaxed SIMD proposal adds new instructions to WebAssembly which,
1237 /// for some specific inputs, are allowed to produce different results on
1238 /// different hosts. More-or-less this proposal enables exposing
1239 /// platform-specific semantics of SIMD instructions in a controlled
1240 /// fashion to a WebAssembly program. From an embedder's perspective this
1241 /// means that WebAssembly programs may execute differently depending on
1242 /// whether the host is x86_64 or AArch64, for example.
1243 ///
1244 /// By default Wasmtime lowers relaxed SIMD instructions to the fastest
1245 /// lowering for the platform it's running on. This means that, by default,
1246 /// some relaxed SIMD instructions may have different results for the same
1247 /// inputs across x86_64 and AArch64. This behavior can be disabled through
1248 /// the [`Config::relaxed_simd_deterministic`] option which will force
1249 /// deterministic behavior across all platforms, as classified by the
1250 /// specification, at the cost of performance.
1251 ///
1252 /// On riscv64 the Cranelift compiler requires the `has_v` (or
1253 /// `has_zvl128b`) setting for relaxed SIMD. Without it creating an
1254 /// [`Engine`] fails unless this option is disabled.
1255 ///
1256 /// This is `true` by default.
1257 ///
1258 /// [proposal]: https://github.com/webassembly/relaxed-simd
1259 pub fn wasm_relaxed_simd(&mut self, enable: bool) -> &mut Self {
1260 self.wasm_features(WasmFeatures::RELAXED_SIMD, enable);
1261 self
1262 }
1263
1264 /// This option can be used to control the behavior of the [relaxed SIMD
1265 /// proposal's][proposal] instructions.
1266 ///
1267 /// The relaxed SIMD proposal introduces instructions that are allowed to
1268 /// have different behavior on different architectures, primarily to afford
1269 /// an efficient implementation on all architectures. This means, however,
1270 /// that the same module may execute differently on one host than another,
1271 /// which typically is not otherwise the case. This option is provided to
1272 /// force Wasmtime to generate deterministic code for all relaxed simd
1273 /// instructions, at the cost of performance, for all architectures. When
1274 /// this option is enabled then the deterministic behavior of all
1275 /// instructions in the relaxed SIMD proposal is selected.
1276 ///
1277 /// This is `false` by default.
1278 ///
1279 /// [proposal]: https://github.com/webassembly/relaxed-simd
1280 pub fn relaxed_simd_deterministic(&mut self, enable: bool) -> &mut Self {
1281 self.tunables.relaxed_simd_deterministic = Some(enable);
1282 self
1283 }
1284
1285 /// Configures whether the [WebAssembly bulk memory operations
1286 /// proposal][proposal] will be enabled for compilation.
1287 ///
1288 /// This feature gates items such as the `memory.copy` instruction, passive
1289 /// data/table segments, etc, being in a module.
1290 ///
1291 /// This is `true` by default.
1292 ///
1293 /// Feature `reference_types`, which is also `true` by default, requires
1294 /// this feature to be enabled. Thus disabling this feature must also disable
1295 /// `reference_types` as well using [`wasm_reference_types`](crate::Config::wasm_reference_types).
1296 ///
1297 /// # Errors
1298 ///
1299 /// Disabling this feature without disabling `reference_types` will cause
1300 /// [`Engine::new`] to fail.
1301 ///
1302 /// [proposal]: https://github.com/webassembly/bulk-memory-operations
1303 pub fn wasm_bulk_memory(&mut self, enable: bool) -> &mut Self {
1304 self.wasm_features(WasmFeatures::BULK_MEMORY, enable);
1305 self
1306 }
1307
1308 /// Configures whether the WebAssembly multi-value [proposal] will
1309 /// be enabled for compilation.
1310 ///
1311 /// This feature gates functions and blocks returning multiple values in a
1312 /// module, for example.
1313 ///
1314 /// This is `true` by default.
1315 ///
1316 /// [proposal]: https://github.com/webassembly/multi-value
1317 pub fn wasm_multi_value(&mut self, enable: bool) -> &mut Self {
1318 self.wasm_features(WasmFeatures::MULTI_VALUE, enable);
1319 self
1320 }
1321
1322 /// Configures whether the WebAssembly multi-memory [proposal] will
1323 /// be enabled for compilation.
1324 ///
1325 /// This feature gates modules having more than one linear memory
1326 /// declaration or import.
1327 ///
1328 /// This is `true` by default.
1329 ///
1330 /// [proposal]: https://github.com/webassembly/multi-memory
1331 pub fn wasm_multi_memory(&mut self, enable: bool) -> &mut Self {
1332 self.wasm_features(WasmFeatures::MULTI_MEMORY, enable);
1333 self
1334 }
1335
1336 /// Configures whether the WebAssembly memory64 [proposal] will
1337 /// be enabled for compilation.
1338 ///
1339 /// This is `true` by default.
1340 ///
1341 /// [proposal]: https://github.com/webassembly/memory64
1342 pub fn wasm_memory64(&mut self, enable: bool) -> &mut Self {
1343 self.wasm_features(WasmFeatures::MEMORY64, enable);
1344 self
1345 }
1346
1347 /// Configures whether the WebAssembly extended-const [proposal] will
1348 /// be enabled for compilation.
1349 ///
1350 /// This is `true` by default.
1351 ///
1352 /// [proposal]: https://github.com/webassembly/extended-const
1353 pub fn wasm_extended_const(&mut self, enable: bool) -> &mut Self {
1354 self.wasm_features(WasmFeatures::EXTENDED_CONST, enable);
1355 self
1356 }
1357
1358 /// Configures whether the [WebAssembly stack switching
1359 /// proposal][proposal] will be enabled for compilation.
1360 ///
1361 /// This feature gates the use of control tags.
1362 ///
1363 /// This feature depends on the `function_reference_types` and
1364 /// `exceptions` features.
1365 ///
1366 /// This feature is `false` by default.
1367 ///
1368 /// # Errors
1369 ///
1370 /// [proposal]: https://github.com/webassembly/stack-switching
1371 pub fn wasm_stack_switching(&mut self, enable: bool) -> &mut Self {
1372 self.wasm_features(WasmFeatures::STACK_SWITCHING, enable);
1373 self
1374 }
1375
1376 /// Configures whether the WebAssembly component-model [proposal] will
1377 /// be enabled for compilation.
1378 ///
1379 /// This flag can be used to blanket disable all components within Wasmtime.
1380 /// Otherwise usage of components requires statically using
1381 /// [`Component`](crate::component::Component) instead of
1382 /// [`Module`](crate::Module) for example anyway.
1383 ///
1384 /// The default value for this option is whether the `component-model`
1385 /// crate feature of Wasmtime is enabled or not. By default this crate
1386 /// feature is enabled.
1387 ///
1388 /// [proposal]: https://github.com/webassembly/component-model
1389 #[cfg(feature = "component-model")]
1390 pub fn wasm_component_model(&mut self, enable: bool) -> &mut Self {
1391 self.wasm_features(WasmFeatures::COMPONENT_MODEL, enable);
1392 self
1393 }
1394
1395 /// Configures whether components support the async ABI [proposal] for
1396 /// lifting and lowering functions, as well as `stream`, `future`, and
1397 /// `error-context` types.
1398 ///
1399 /// The default value for this option is whether the `component-model-async`
1400 /// crate feature of Wasmtime is enabled or not. By default this crate
1401 /// feature is enabled. This option is also disabled by default if
1402 /// [`Config::concurrency_support`] is disabled.
1403 ///
1404 /// [proposal]:
1405 /// https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1406 #[cfg(feature = "component-model-async")]
1407 pub fn wasm_component_model_async(&mut self, enable: bool) -> &mut Self {
1408 self.wasm_features(WasmFeatures::CM_ASYNC, enable);
1409 self
1410 }
1411
1412 /// This corresponds to the 🚝 emoji in the component model specification.
1413 ///
1414 /// Please note that Wasmtime's support for this feature is _very_
1415 /// incomplete.
1416 ///
1417 /// [proposal]:
1418 /// https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1419 #[cfg(feature = "component-model-async")]
1420 pub fn wasm_component_model_more_async_builtins(&mut self, enable: bool) -> &mut Self {
1421 self.wasm_features(WasmFeatures::CM_MORE_ASYNC_BUILTINS, enable);
1422 self
1423 }
1424
1425 /// This corresponds to the 🚟 emoji in the component model specification.
1426 ///
1427 /// Please note that Wasmtime's support for this feature is _very_
1428 /// incomplete.
1429 ///
1430 /// [proposal]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1431 #[cfg(feature = "component-model-async")]
1432 pub fn wasm_component_model_async_stackful(&mut self, enable: bool) -> &mut Self {
1433 self.wasm_features(WasmFeatures::CM_ASYNC_STACKFUL, enable);
1434 self
1435 }
1436
1437 /// This corresponds to the 🧵 emoji in the component model specification.
1438 ///
1439 /// Please note that Wasmtime's support for this feature is _very_
1440 /// incomplete.
1441 ///
1442 /// [proposal]:
1443 /// https://github.com/WebAssembly/component-model/pull/557
1444 #[cfg(feature = "component-model-async")]
1445 pub fn wasm_component_model_threading(&mut self, enable: bool) -> &mut Self {
1446 self.wasm_features(WasmFeatures::CM_THREADING, enable);
1447 self
1448 }
1449
1450 /// This corresponds to the 📝 emoji in the component model specification.
1451 ///
1452 /// Please note that Wasmtime's support for this feature is _very_
1453 /// incomplete.
1454 ///
1455 /// [proposal]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1456 #[cfg(feature = "component-model")]
1457 pub fn wasm_component_model_error_context(&mut self, enable: bool) -> &mut Self {
1458 self.wasm_features(WasmFeatures::CM_ERROR_CONTEXT, enable);
1459 self
1460 }
1461
1462 /// Configures whether the [GC extension to the component-model
1463 /// proposal][proposal] is enabled or not.
1464 ///
1465 /// This corresponds to the 🛸 emoji in the component model specification.
1466 ///
1467 /// Please note that Wasmtime's support for this feature is _very_
1468 /// incomplete.
1469 ///
1470 /// [proposal]: https://github.com/WebAssembly/component-model/issues/525
1471 #[cfg(feature = "component-model")]
1472 pub fn wasm_component_model_gc(&mut self, enable: bool) -> &mut Self {
1473 self.wasm_features(WasmFeatures::CM_GC, enable);
1474 self
1475 }
1476
1477 /// Configures whether the component model map type is enabled or not.
1478 ///
1479 /// This corresponds to the 🗺️ emoji in the component model specification
1480 /// and enables the `map<k, v>` type in WIT and the component binary
1481 /// format.
1482 ///
1483 /// The default value for this option is whether the `component-model`
1484 /// crate feature of Wasmtime is enabled or not. By default this crate
1485 /// feature is enabled.
1486 #[cfg(feature = "component-model")]
1487 pub fn wasm_component_model_map(&mut self, enable: bool) -> &mut Self {
1488 self.wasm_features(WasmFeatures::CM_MAP, enable);
1489 self
1490 }
1491
1492 /// Configures whether the component model memory64 support is enabled
1493 ///
1494 /// This corresponds to the 🐘 emoji in the component model specification.
1495 ///
1496 /// Please note that Wasmtime's support for this feature is _very_
1497 /// incomplete.
1498 #[cfg(feature = "component-model")]
1499 pub fn wasm_component_model_memory64(&mut self, enable: bool) -> &mut Self {
1500 self.wasm_features(WasmFeatures::CM64, enable);
1501 self
1502 }
1503
1504 /// This corresponds to the 🔧 emoji in the component model specification.
1505 ///
1506 /// Please note that Wasmtime's support for this feature is _very_
1507 /// incomplete.
1508 #[cfg(feature = "component-model")]
1509 pub fn wasm_component_model_fixed_length_lists(&mut self, enable: bool) -> &mut Self {
1510 self.wasm_features(WasmFeatures::CM_FIXED_LENGTH_LISTS, enable);
1511 self
1512 }
1513
1514 /// Configures whether the component model `(implements "...")` and
1515 /// `(external-id "...")` name annotations are enabled.
1516 ///
1517 /// This corresponds to the 🏷️ emoji in the component model specification.
1518 ///
1519 /// Please note that Wasmtime's support for this feature is a work in
1520 /// progress.
1521 #[cfg(feature = "component-model")]
1522 pub fn wasm_component_model_implements(&mut self, enable: bool) -> &mut Self {
1523 self.wasm_features(WasmFeatures::CM_IMPLEMENTS, enable);
1524 self
1525 }
1526
1527 /// This corresponds to the 🔗 emoji in the component model specification.
1528 ///
1529 /// Please note that Wasmtime's support for this feature is a work in
1530 /// progress.
1531 #[cfg(feature = "component-model")]
1532 pub fn wasm_component_model_canonical_names(&mut self, enable: bool) -> &mut Self {
1533 self.wasm_features(WasmFeatures::CM_CANON_NAMES, enable);
1534 self
1535 }
1536
1537 /// This corresponds to the 📡 emoji in the component model specification.
1538 ///
1539 /// Please note that Wasmtime's support for this feature is a work in
1540 /// progress.
1541 #[cfg(feature = "component-model")]
1542 pub fn wasm_component_model_accessors(&mut self, enable: bool) -> &mut Self {
1543 self.wasm_features(WasmFeatures::CM_ACCESSORS, enable);
1544 self
1545 }
1546
1547 /// Configures whether the [Exception-handling proposal][proposal] is enabled or not.
1548 ///
1549 /// This is `true` by default, except when using [`Strategy::Winch`] where
1550 /// it defaults to `false`.
1551 ///
1552 /// [proposal]: https://github.com/WebAssembly/exception-handling
1553 #[cfg(feature = "gc")]
1554 pub fn wasm_exceptions(&mut self, enable: bool) -> &mut Self {
1555 self.wasm_features(WasmFeatures::EXCEPTIONS, enable);
1556 self
1557 }
1558
1559 #[doc(hidden)] // FIXME(#3427) - if/when implemented then un-hide this
1560 #[deprecated = "This configuration option only exists for internal \
1561 usage with the spec testsuite. It may be removed at \
1562 any time and without warning. Do not rely on it!"]
1563 pub fn wasm_legacy_exceptions(&mut self, enable: bool) -> &mut Self {
1564 self.wasm_features(WasmFeatures::LEGACY_EXCEPTIONS, enable);
1565 self
1566 }
1567
1568 /// Configures which compilation strategy will be used for wasm modules.
1569 ///
1570 /// This method can be used to configure which compiler is used for wasm
1571 /// modules, and for more documentation consult the [`Strategy`] enumeration
1572 /// and its documentation.
1573 ///
1574 /// The default value for this is `Strategy::Auto`.
1575 ///
1576 /// # Panics
1577 ///
1578 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1579 #[cfg(any(feature = "cranelift", feature = "winch"))]
1580 pub fn strategy(&mut self, strategy: Strategy) -> &mut Self {
1581 self.compiler_config_mut().strategy = strategy.not_auto();
1582 self
1583 }
1584
1585 /// Configures which garbage collector will be used for Wasm modules.
1586 ///
1587 /// This method can be used to configure which garbage collector
1588 /// implementation is used for Wasm modules. For more documentation, consult
1589 /// the [`Collector`] enumeration and its documentation.
1590 ///
1591 /// The default value for this is `Collector::Auto`.
1592 #[cfg(feature = "gc")]
1593 pub fn collector(&mut self, collector: Collector) -> &mut Self {
1594 self.collector = collector;
1595 self
1596 }
1597
1598 /// Configures the initial size, in bytes, of each store's GC heap.
1599 ///
1600 /// By default all GC heaps start out at 0 bytes in size and must grow
1601 /// upwards from there. Growth happens incrementally as GC pressure happens
1602 /// and memory runs out. The amount being grown by is additionally a
1603 /// heuristic of the size of the failed allocation. By providing an initial
1604 /// size of a store's GC heap embedders can more tightly control initial
1605 /// parameters to optimize workloads that might have a predictable pattern.
1606 /// For example if workloads frequently have less than a certain threshold
1607 /// of size then that could be configured as the initial size here to avoid
1608 /// growths happening over time.
1609 ///
1610 /// Note that like WebAssembly linear memories the GC heap does not start
1611 /// with committed memory equal to this size. Instead memory is reserved,
1612 /// but then lazily allocated by the OS on access. In other words it should
1613 /// be relatively cheap to increase this value to help amortize initial
1614 /// startup cost of wasm modules.
1615 ///
1616 /// The `bytes` size is rounded up to the GC heap's page size.
1617 ///
1618 /// This only configures the initially-allocated size of the GC heap; the
1619 /// heap can still grow beyond it on demand. It is separate from
1620 /// [`Config::gc_heap_reservation`], which configures the size of the
1621 /// virtual-memory reservation (and therefore how far the heap can grow
1622 /// in place).
1623 ///
1624 /// The default value for this is 0.
1625 pub fn gc_heap_initial_size(&mut self, bytes: u64) -> &mut Self {
1626 self.tunables.gc_heap_initial_size = Some(bytes);
1627 self
1628 }
1629
1630 /// Creates a default profiler based on the profiling strategy chosen.
1631 ///
1632 /// Profiler creation calls the type's default initializer where the purpose is
1633 /// really just to put in place the type used for profiling.
1634 ///
1635 /// Some [`ProfilingStrategy`] require specific platforms or particular feature
1636 /// to be enabled, such as `ProfilingStrategy::JitDump` requires the `jitdump`
1637 /// feature.
1638 ///
1639 /// # Errors
1640 ///
1641 /// The validation of this field is deferred until the engine is being built, and thus may
1642 /// cause [`Engine::new`] fail if the required feature is disabled, or the platform is not
1643 /// supported.
1644 pub fn profiler(&mut self, profile: ProfilingStrategy) -> &mut Self {
1645 self.profiling_strategy = profile;
1646 self
1647 }
1648
1649 /// Configures whether the debug verifier of Cranelift is enabled or not.
1650 ///
1651 /// When Cranelift is used as a code generation backend this will configure
1652 /// it to have the `enable_verifier` flag which will enable a number of debug
1653 /// checks inside of Cranelift. This is largely only useful for the
1654 /// developers of wasmtime itself.
1655 ///
1656 /// The default value for this is `false`
1657 ///
1658 /// # Panics
1659 ///
1660 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1661 #[cfg(any(feature = "cranelift", feature = "winch"))]
1662 pub fn cranelift_debug_verifier(&mut self, enable: bool) -> &mut Self {
1663 let val = if enable { "true" } else { "false" };
1664 self.compiler_config_mut().settings.insert(
1665 "enable_verifier".to_string(),
1666 (val.to_string(), UserSpecified::No),
1667 );
1668 self
1669 }
1670
1671 /// Configures whether extra debug checks are inserted into
1672 /// Wasmtime-generated code by Cranelift.
1673 ///
1674 /// The default value for this is `false`
1675 ///
1676 /// # Panics
1677 ///
1678 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1679 #[cfg(any(feature = "cranelift", feature = "winch"))]
1680 pub fn cranelift_wasmtime_debug_checks(&mut self, enable: bool) -> &mut Self {
1681 unsafe { self.cranelift_flag_set("wasmtime_debug_checks", &enable.to_string()) }
1682 }
1683
1684 /// Configures the Cranelift code generator optimization level.
1685 ///
1686 /// When the Cranelift code generator is used you can configure the
1687 /// optimization level used for generated code in a few various ways. For
1688 /// more information see the documentation of [`OptLevel`].
1689 ///
1690 /// The default value for this is `OptLevel::Speed`.
1691 ///
1692 /// # Panics
1693 ///
1694 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1695 #[cfg(any(feature = "cranelift", feature = "winch"))]
1696 pub fn cranelift_opt_level(&mut self, level: OptLevel) -> &mut Self {
1697 let val = match level {
1698 OptLevel::None => "none",
1699 OptLevel::Speed => "speed",
1700 OptLevel::SpeedAndSize => "speed_and_size",
1701 };
1702 self.compiler_config_mut().settings.insert(
1703 "opt_level".to_string(),
1704 (val.to_string(), UserSpecified::No),
1705 );
1706 self
1707 }
1708
1709 /// Configures the regalloc algorithm used by the Cranelift code generator.
1710 ///
1711 /// Cranelift can select any of several register allocator algorithms. Each
1712 /// of these algorithms generates correct code, but they represent different
1713 /// tradeoffs between compile speed (how expensive the compilation process
1714 /// is) and run-time speed (how fast the generated code runs).
1715 /// For more information see the documentation of [`RegallocAlgorithm`].
1716 ///
1717 /// The default value for this is `RegallocAlgorithm::Backtracking`.
1718 ///
1719 /// # Panics
1720 ///
1721 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1722 #[cfg(any(feature = "cranelift", feature = "winch"))]
1723 pub fn cranelift_regalloc_algorithm(&mut self, algo: RegallocAlgorithm) -> &mut Self {
1724 let val = match algo {
1725 RegallocAlgorithm::Backtracking => "backtracking",
1726 RegallocAlgorithm::SinglePass => "single_pass",
1727 };
1728 self.compiler_config_mut().settings.insert(
1729 "regalloc_algorithm".to_string(),
1730 (val.to_string(), UserSpecified::No),
1731 );
1732 self
1733 }
1734
1735 /// Configures whether Cranelift should perform a NaN-canonicalization pass.
1736 ///
1737 /// When Cranelift is used as a code generation backend this will configure
1738 /// it to replace NaNs with a single canonical value. This is useful for
1739 /// users requiring entirely deterministic WebAssembly computation. This is
1740 /// not required by the WebAssembly spec, so it is not enabled by default.
1741 ///
1742 /// Note that this option affects not only WebAssembly's `f32` and `f64`
1743 /// types but additionally the `v128` type. This option will cause
1744 /// operations using any of these types to have extra checks placed after
1745 /// them to normalize NaN values as needed.
1746 ///
1747 /// The default value for this is `false`
1748 ///
1749 /// # Panics
1750 ///
1751 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1752 #[cfg(any(feature = "cranelift", feature = "winch"))]
1753 pub fn cranelift_nan_canonicalization(&mut self, enable: bool) -> &mut Self {
1754 let val = if enable { "true" } else { "false" };
1755 self.compiler_config_mut().settings.insert(
1756 "enable_nan_canonicalization".to_string(),
1757 (val.to_string(), UserSpecified::No),
1758 );
1759 self
1760 }
1761
1762 /// Allows setting a Cranelift boolean flag or preset. This allows
1763 /// fine-tuning of Cranelift settings.
1764 ///
1765 /// Since Cranelift flags may be unstable, this method should not be considered to be stable
1766 /// either; other `Config` functions should be preferred for stability.
1767 ///
1768 /// # Safety
1769 ///
1770 /// This is marked as unsafe, because setting the wrong flag might break invariants,
1771 /// resulting in execution hazards.
1772 ///
1773 /// # Errors
1774 ///
1775 /// The validation of the flags are deferred until the engine is being built, and thus may
1776 /// cause [`Engine::new`] fail if the flag's name does not exist, or the value is not appropriate
1777 /// for the flag type.
1778 ///
1779 /// # Panics
1780 ///
1781 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1782 #[cfg(any(feature = "cranelift", feature = "winch"))]
1783 pub unsafe fn cranelift_flag_enable(&mut self, flag: &str) -> &mut Self {
1784 self.compiler_config_mut()
1785 .flags
1786 .insert(flag.to_string(), UserSpecified::Yes);
1787 self
1788 }
1789
1790 /// Allows settings another Cranelift flag defined by a flag name and value. This allows
1791 /// fine-tuning of Cranelift settings.
1792 ///
1793 /// Since Cranelift flags may be unstable, this method should not be considered to be stable
1794 /// either; other `Config` functions should be preferred for stability.
1795 ///
1796 /// # Safety
1797 ///
1798 /// This is marked as unsafe, because setting the wrong flag might break invariants,
1799 /// resulting in execution hazards.
1800 ///
1801 /// # Errors
1802 ///
1803 /// The validation of the flags are deferred until the engine is being built, and thus may
1804 /// cause [`Engine::new`] fail if the flag's name does not exist, or incompatible with other
1805 /// settings.
1806 ///
1807 /// For example, feature `wasm_backtrace` will set `unwind_info` to `true`, but if it's
1808 /// manually set to false then it will fail.
1809 ///
1810 /// # Panics
1811 ///
1812 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1813 #[cfg(any(feature = "cranelift", feature = "winch"))]
1814 pub unsafe fn cranelift_flag_set(&mut self, name: &str, value: &str) -> &mut Self {
1815 self.compiler_config_mut()
1816 .settings
1817 .insert(name.to_string(), (value.to_string(), UserSpecified::Yes));
1818 self
1819 }
1820
1821 /// Set a custom [`Cache`].
1822 ///
1823 /// To load a cache configuration from a file, use [`Cache::from_file`]. Otherwise, you can
1824 /// create a new cache config using [`CacheConfig::new`] and passing that to [`Cache::new`].
1825 ///
1826 /// If you want to disable the cache, you can call this method with `None`.
1827 ///
1828 /// By default, new configs do not have caching enabled.
1829 /// Every call to [`Module::new(my_wasm)`][crate::Module::new] will recompile `my_wasm`,
1830 /// even when it is unchanged, unless an enabled `CacheConfig` is provided.
1831 ///
1832 /// This method is only available when the `cache` feature of this crate is
1833 /// enabled.
1834 ///
1835 /// [docs]: https://bytecodealliance.github.io/wasmtime/cli-cache.html
1836 #[cfg(feature = "cache")]
1837 pub fn cache(&mut self, cache: Option<Cache>) -> &mut Self {
1838 self.cache = cache;
1839 self
1840 }
1841
1842 /// Sets a custom memory creator.
1843 ///
1844 /// Custom memory creators are used when creating host `Memory` objects or when
1845 /// creating instance linear memories for the on-demand instance allocation strategy.
1846 #[cfg(feature = "runtime")]
1847 pub fn with_host_memory(&mut self, mem_creator: Arc<dyn MemoryCreator>) -> &mut Self {
1848 self.mem_creator = Some(mem_creator);
1849 self
1850 }
1851
1852 /// Sets a custom stack creator.
1853 ///
1854 /// Custom memory creators are used when creating creating async instance stacks for
1855 /// the on-demand instance allocation strategy.
1856 #[cfg(feature = "async")]
1857 pub fn with_host_stack(&mut self, stack_creator: Arc<dyn StackCreator>) -> &mut Self {
1858 self.stack_creator = Some(Arc::new(StackCreatorProxy(stack_creator)));
1859 self
1860 }
1861
1862 /// Sets a custom executable-memory publisher.
1863 ///
1864 /// Custom executable-memory publishers are hooks that allow
1865 /// Wasmtime to make certain regions of memory executable when
1866 /// loading precompiled modules or compiling new modules
1867 /// in-process. In most modern operating systems, memory allocated
1868 /// for heap usage is readable and writable by default but not
1869 /// executable. To jump to machine code stored in that memory, we
1870 /// need to make it executable. For security reasons, we usually
1871 /// also make it read-only at the same time, so the executing code
1872 /// can't be modified later.
1873 ///
1874 /// By default, Wasmtime will use the appropriate system calls on
1875 /// the host platform for this work. However, it also allows
1876 /// plugging in a custom implementation via this configuration
1877 /// option. This may be useful on custom or `no_std` platforms,
1878 /// for example, especially where virtual memory is not otherwise
1879 /// used by Wasmtime (no `signals-and-traps` feature).
1880 #[cfg(feature = "runtime")]
1881 pub fn with_custom_code_memory(
1882 &mut self,
1883 custom_code_memory: Option<Arc<dyn CustomCodeMemory>>,
1884 ) -> &mut Self {
1885 self.custom_code_memory = custom_code_memory;
1886 self
1887 }
1888
1889 /// Sets the instance allocation strategy to use.
1890 ///
1891 /// This is notably used in conjunction with
1892 /// [`InstanceAllocationStrategy::Pooling`] and [`PoolingAllocationConfig`].
1893 pub fn allocation_strategy(
1894 &mut self,
1895 strategy: impl Into<InstanceAllocationStrategy>,
1896 ) -> &mut Self {
1897 self.allocation_strategy = strategy.into();
1898 self
1899 }
1900
1901 /// Specifies the capacity of linear memories, in bytes, in their initial
1902 /// allocation.
1903 ///
1904 /// > Note: this value has important performance ramifications, be sure to
1905 /// > benchmark when setting this to a non-default value and read over this
1906 /// > documentation.
1907 ///
1908 /// This function will change the size of the initial memory allocation made
1909 /// for linear memories. This setting is only applicable when the initial
1910 /// size of a linear memory is below this threshold. Linear memories are
1911 /// allocated in the virtual address space of the host process with OS APIs
1912 /// such as `mmap` and this setting affects how large the allocation will
1913 /// be.
1914 ///
1915 /// ## Background: WebAssembly Linear Memories
1916 ///
1917 /// WebAssembly linear memories always start with a minimum size and can
1918 /// possibly grow up to a maximum size. The minimum size is always specified
1919 /// in a WebAssembly module itself and the maximum size can either be
1920 /// optionally specified in the module or inherently limited by the index
1921 /// type. For example for this module:
1922 ///
1923 /// ```wasm
1924 /// (module
1925 /// (memory $a 4)
1926 /// (memory $b 4096 4096 (pagesize 1))
1927 /// (memory $c i64 10)
1928 /// )
1929 /// ```
1930 ///
1931 /// * Memory `$a` initially allocates 4 WebAssembly pages (256KiB) and can
1932 /// grow up to 4GiB, the limit of the 32-bit index space.
1933 /// * Memory `$b` initially allocates 4096 WebAssembly pages, but in this
1934 /// case its page size is 1, so it's 4096 bytes. Memory can also grow no
1935 /// further meaning that it will always be 4096 bytes.
1936 /// * Memory `$c` is a 64-bit linear memory which starts with 640KiB of
1937 /// memory and can theoretically grow up to 2^64 bytes, although most
1938 /// hosts will run out of memory long before that.
1939 ///
1940 /// All operations on linear memories done by wasm are required to be
1941 /// in-bounds. Any access beyond the end of a linear memory is considered a
1942 /// trap.
1943 ///
1944 /// ## What this setting affects: Virtual Memory
1945 ///
1946 /// This setting is used to configure the behavior of the size of the linear
1947 /// memory allocation performed for each of these memories. For example the
1948 /// initial linear memory allocation looks like this:
1949 ///
1950 /// ```text
1951 /// memory_reservation
1952 /// |
1953 /// ◄─────────┴────────────────►
1954 /// ┌───────┬─────────┬──────────────────┬───────┐
1955 /// │ guard │ initial │ ... capacity ... │ guard │
1956 /// └───────┴─────────┴──────────────────┴───────┘
1957 /// ◄──┬──► ◄──┬──►
1958 /// │ │
1959 /// │ memory_guard_size
1960 /// │
1961 /// │
1962 /// memory_guard_size (if guard_before_linear_memory)
1963 /// ```
1964 ///
1965 /// Memory in the `initial` range is accessible to the instance and can be
1966 /// read/written by wasm code. Memory in the `guard` regions is never
1967 /// accessible to wasm code and memory in `capacity` is initially
1968 /// inaccessible but may become accessible through `memory.grow` instructions
1969 /// for example.
1970 ///
1971 /// This means that this setting is the size of the initial chunk of virtual
1972 /// memory that a linear memory may grow into.
1973 ///
1974 /// ## What this setting affects: Runtime Speed
1975 ///
1976 /// This is a performance-sensitive setting which is taken into account
1977 /// during the compilation process of a WebAssembly module. For example if a
1978 /// 32-bit WebAssembly linear memory has a `memory_reservation` size of 4GiB
1979 /// then bounds checks can be elided because `capacity` will be guaranteed
1980 /// to be unmapped for all addressable bytes that wasm can access (modulo a
1981 /// few details).
1982 ///
1983 /// If `memory_reservation` was something smaller like 256KiB then that
1984 /// would have a much smaller impact on virtual memory but the compile code
1985 /// would then need to have explicit bounds checks to ensure that
1986 /// loads/stores are in-bounds.
1987 ///
1988 /// The goal of this setting is to enable skipping bounds checks in most
1989 /// modules by default. Some situations which require explicit bounds checks
1990 /// though are:
1991 ///
1992 /// * When `memory_reservation` is smaller than the addressable size of the
1993 /// linear memory. For example if 64-bit linear memories always need
1994 /// bounds checks as they can address the entire virtual address spacce.
1995 /// For 32-bit linear memories a `memory_reservation` minimum size of 4GiB
1996 /// is required to elide bounds checks.
1997 ///
1998 /// * When linear memories have a page size of 1 then bounds checks are
1999 /// required. In this situation virtual memory can't be relied upon
2000 /// because that operates at the host page size granularity where wasm
2001 /// requires a per-byte level granularity.
2002 ///
2003 /// * Configuration settings such as [`Config::signals_based_traps`] can be
2004 /// used to disable the use of signal handlers and virtual memory so
2005 /// explicit bounds checks are required.
2006 ///
2007 /// * When [`Config::memory_guard_size`] is too small a bounds check may be
2008 /// required. For 32-bit wasm addresses are actually 33-bit effective
2009 /// addresses because loads/stores have a 32-bit static offset to add to
2010 /// the dynamic 32-bit address. If the static offset is larger than the
2011 /// size of the guard region then an explicit bounds check is required.
2012 ///
2013 /// ## What this setting affects: Memory Growth Behavior
2014 ///
2015 /// In addition to affecting bounds checks emitted in compiled code this
2016 /// setting also affects how WebAssembly linear memories are grown. The
2017 /// `memory.grow` instruction can be used to make a linear memory larger and
2018 /// this is also affected by APIs such as
2019 /// [`Memory::grow`](crate::Memory::grow).
2020 ///
2021 /// In these situations when the amount being grown is small enough to fit
2022 /// within the remaining capacity then the linear memory doesn't have to be
2023 /// moved at runtime. If the capacity runs out though then a new linear
2024 /// memory allocation must be made and the contents of linear memory is
2025 /// copied over.
2026 ///
2027 /// For example here's a situation where a copy happens:
2028 ///
2029 /// * The `memory_reservation` setting is configured to 128KiB.
2030 /// * A WebAssembly linear memory starts with a single 64KiB page.
2031 /// * This memory can be grown by one page to contain the full 128KiB of
2032 /// memory.
2033 /// * If grown by one more page, though, then a 192KiB allocation must be
2034 /// made and the previous 128KiB of contents are copied into the new
2035 /// allocation.
2036 ///
2037 /// This growth behavior can have a significant performance impact if lots
2038 /// of data needs to be copied on growth. Conversely if memory growth never
2039 /// needs to happen because the capacity will always be large enough then
2040 /// optimizations can be applied to cache the base pointer of linear memory.
2041 ///
2042 /// When memory is grown then the
2043 /// [`Config::memory_reservation_for_growth`] is used for the new
2044 /// memory allocation to have memory to grow into.
2045 ///
2046 /// When using the pooling allocator via [`PoolingAllocationConfig`] then
2047 /// memories are never allowed to move so requests for growth are instead
2048 /// rejected with an error.
2049 ///
2050 /// ## When this setting is not used
2051 ///
2052 /// This setting is ignored and unused when the initial size of linear
2053 /// memory is larger than this threshold. For example if this setting is set
2054 /// to 1MiB but a wasm module requires a 2MiB minimum allocation then this
2055 /// setting is ignored. In this situation the minimum size of memory will be
2056 /// allocated along with [`Config::memory_reservation_for_growth`]
2057 /// after it to grow into.
2058 ///
2059 /// That means that this value can be set to zero. That can be useful in
2060 /// benchmarking to see the overhead of bounds checks for example.
2061 /// Additionally it can be used to minimize the virtual memory allocated by
2062 /// Wasmtime.
2063 ///
2064 /// ## Default Value
2065 ///
2066 /// The default value for this property depends on the host platform. For
2067 /// 64-bit platforms there's lots of address space available, so the default
2068 /// configured here is 4GiB. When coupled with the default size of
2069 /// [`Config::memory_guard_size`] this means that 32-bit WebAssembly linear
2070 /// memories with 64KiB page sizes will skip almost all bounds checks by
2071 /// default.
2072 ///
2073 /// For 32-bit platforms this value defaults to 10MiB. This means that
2074 /// bounds checks will be required on 32-bit platforms.
2075 pub fn memory_reservation(&mut self, bytes: u64) -> &mut Self {
2076 self.tunables.memory_reservation = Some(bytes);
2077 self
2078 }
2079
2080 /// Indicates whether linear memories may relocate their base pointer at
2081 /// runtime.
2082 ///
2083 /// WebAssembly linear memories either have a maximum size that's explicitly
2084 /// listed in the type of a memory or inherently limited by the index type
2085 /// of the memory (e.g. 4GiB for 32-bit linear memories). Depending on how
2086 /// the linear memory is allocated (see [`Config::memory_reservation`]) it
2087 /// may be necessary to move the memory in the host's virtual address space
2088 /// during growth. This option controls whether this movement is allowed or
2089 /// not.
2090 ///
2091 /// An example of a linear memory needing to move is when
2092 /// [`Config::memory_reservation`] is 0 then a linear memory will be
2093 /// allocated as the minimum size of the memory plus
2094 /// [`Config::memory_reservation_for_growth`]. When memory grows beyond the
2095 /// reservation for growth then the memory needs to be relocated.
2096 ///
2097 /// When this option is set to `false` then it can have a number of impacts
2098 /// on how memories work at runtime:
2099 ///
2100 /// * Modules can be compiled with static knowledge the base pointer of
2101 /// linear memory never changes to enable optimizations such as
2102 /// loop invariant code motion (hoisting the base pointer out of a loop).
2103 ///
2104 /// * Memories cannot grow in excess of their original allocation. This
2105 /// means that [`Config::memory_reservation`] and
2106 /// [`Config::memory_reservation_for_growth`] may need tuning to ensure
2107 /// the memory configuration works at runtime.
2108 ///
2109 /// The default value for this option is `true`.
2110 pub fn memory_may_move(&mut self, enable: bool) -> &mut Self {
2111 self.tunables.memory_may_move = Some(enable);
2112 self
2113 }
2114
2115 /// Configures the size, in bytes, of the guard region used at the end of a
2116 /// linear memory's address space reservation.
2117 ///
2118 /// > Note: this value has important performance ramifications, be sure to
2119 /// > understand what this value does before tweaking it and benchmarking.
2120 ///
2121 /// This setting controls how many bytes are guaranteed to be unmapped after
2122 /// the virtual memory allocation of a linear memory. When
2123 /// combined with sufficiently large values of
2124 /// [`Config::memory_reservation`] (e.g. 4GiB for 32-bit linear memories)
2125 /// then a guard region can be used to eliminate bounds checks in generated
2126 /// code.
2127 ///
2128 /// This setting additionally can be used to help deduplicate bounds checks
2129 /// in code that otherwise requires bounds checks. For example with a 4KiB
2130 /// guard region then a 64-bit linear memory which accesses addresses `x+8`
2131 /// and `x+16` only needs to perform a single bounds check on `x`. If that
2132 /// bounds check passes then the offset is guaranteed to either reside in
2133 /// linear memory or the guard region, resulting in deterministic behavior
2134 /// either way.
2135 ///
2136 /// ## How big should the guard be?
2137 ///
2138 /// In general, like with configuring [`Config::memory_reservation`], you
2139 /// probably don't want to change this value from the defaults. Removing
2140 /// bounds checks is dependent on a number of factors where the size of the
2141 /// guard region is only one piece of the equation. Other factors include:
2142 ///
2143 /// * [`Config::memory_reservation`]
2144 /// * The index type of the linear memory (e.g. 32-bit or 64-bit)
2145 /// * The page size of the linear memory
2146 /// * Other settings such as [`Config::signals_based_traps`]
2147 ///
2148 /// Embeddings using virtual memory almost always want at least some guard
2149 /// region, but otherwise changes from the default should be profiled
2150 /// locally to see the performance impact.
2151 ///
2152 /// ## Default
2153 ///
2154 /// The default value for this property is 32MiB on 64-bit platforms. This
2155 /// allows eliminating almost all bounds checks on loads/stores with an
2156 /// immediate offset of less than 32MiB. On 32-bit platforms this defaults
2157 /// to 64KiB.
2158 pub fn memory_guard_size(&mut self, bytes: u64) -> &mut Self {
2159 self.tunables.memory_guard_size = Some(bytes);
2160 self
2161 }
2162
2163 /// Configures the size, in bytes, of the extra virtual memory space
2164 /// reserved after a linear memory is relocated.
2165 ///
2166 /// This setting is used in conjunction with [`Config::memory_reservation`]
2167 /// to configure what happens after a linear memory is relocated in the host
2168 /// address space. If the initial size of a linear memory exceeds
2169 /// [`Config::memory_reservation`] or if it grows beyond that size
2170 /// throughout its lifetime then this setting will be used.
2171 ///
2172 /// When a linear memory is relocated it will initially look like this:
2173 ///
2174 /// ```text
2175 /// memory.size
2176 /// │
2177 /// ◄──────┴─────►
2178 /// ┌───────┬──────────────┬───────┐
2179 /// │ guard │ accessible │ guard │
2180 /// └───────┴──────────────┴───────┘
2181 /// ◄──┬──►
2182 /// │
2183 /// memory_guard_size
2184 /// ```
2185 ///
2186 /// where `accessible` needs to be grown but there's no more memory to grow
2187 /// into. A new region of the virtual address space will be allocated that
2188 /// looks like this:
2189 ///
2190 /// ```text
2191 /// memory_reservation_for_growth
2192 /// │
2193 /// memory.size │
2194 /// │ │
2195 /// ◄──────┴─────► ◄─────────────┴───────────►
2196 /// ┌───────┬──────────────┬───────────────────────────┬───────┐
2197 /// │ guard │ accessible │ .. reserved for growth .. │ guard │
2198 /// └───────┴──────────────┴───────────────────────────┴───────┘
2199 /// ◄──┬──►
2200 /// │
2201 /// memory_guard_size
2202 /// ```
2203 ///
2204 /// This means that up to `memory_reservation_for_growth` bytes can be
2205 /// allocated again before the entire linear memory needs to be moved again
2206 /// when another `memory_reservation_for_growth` bytes will be appended to
2207 /// the size of the allocation.
2208 ///
2209 /// Note that this is a currently simple heuristic for optimizing the growth
2210 /// of dynamic memories, primarily implemented for the memory64 proposal
2211 /// where the maximum size of memory is larger than 4GiB. This setting is
2212 /// unlikely to be a one-size-fits-all style approach and if you're an
2213 /// embedder running into issues with growth and are interested in having
2214 /// other growth strategies available here please feel free to [open an
2215 /// issue on the Wasmtime repository][issue]!
2216 ///
2217 /// [issue]: https://github.com/bytecodealliance/wasmtime/issues/new
2218 ///
2219 /// ## Default
2220 ///
2221 /// For 64-bit platforms this defaults to 2GiB, and for 32-bit platforms
2222 /// this defaults to 1MiB.
2223 pub fn memory_reservation_for_growth(&mut self, bytes: u64) -> &mut Self {
2224 self.tunables.memory_reservation_for_growth = Some(bytes);
2225 self
2226 }
2227
2228 /// Configures the initial size, in bytes, to be allocated for GC heaps.
2229 ///
2230 /// This is similar to [`Config::memory_reservation`] but applies to the GC
2231 /// heap rather than to linear memories. See that method for more details
2232 /// on what "reservation" means and the implications of this setting.
2233 ///
2234 /// ## Default
2235 ///
2236 /// If none of the `gc_heap_*` tunables are explicitly configured, they
2237 /// default to the same values as their `memory_*` counterparts. Otherwise,
2238 /// the default value for this property depends on the host platform: for
2239 /// 64-bit platforms this defaults to 4GiB, and for 32-bit platforms this
2240 /// defaults to 10MiB.
2241 pub fn gc_heap_reservation(&mut self, bytes: u64) -> &mut Self {
2242 self.tunables.gc_heap_reservation = Some(bytes);
2243 self
2244 }
2245
2246 /// Configures the size, in bytes, of the guard page region for GC heaps.
2247 ///
2248 /// This is similar to [`Config::memory_guard_size`] but applies to the GC
2249 /// heap rather than to linear memories. See that method for more details on
2250 /// what guard pages are and the implications of this setting.
2251 ///
2252 /// ## Default
2253 ///
2254 /// If none of the `gc_heap_*` tunables are explicitly configured, they
2255 /// default to the same values as their `memory_*` counterparts. Otherwise,
2256 /// the default value for this property is 32MiB on 64-bit platforms and
2257 /// 64KiB on 32-bit platforms.
2258 pub fn gc_heap_guard_size(&mut self, bytes: u64) -> &mut Self {
2259 self.tunables.gc_heap_guard_size = Some(bytes);
2260 self
2261 }
2262
2263 /// Configures the size, in bytes, of the extra virtual memory space
2264 /// reserved after a GC heap is relocated.
2265 ///
2266 /// This is similar to [`Config::memory_reservation_for_growth`] but applies
2267 /// to the GC heap rather than to linear memories. See that method for more
2268 /// details.
2269 ///
2270 /// ## Default
2271 ///
2272 /// If none of the `gc_heap_*` tunables are explicitly configured, they
2273 /// default to the same values as their `memory_*` counterparts. Otherwise,
2274 /// for 64-bit platforms this defaults to 2GiB, and for 32-bit platforms
2275 /// this defaults to 1MiB.
2276 pub fn gc_heap_reservation_for_growth(&mut self, bytes: u64) -> &mut Self {
2277 self.tunables.gc_heap_reservation_for_growth = Some(bytes);
2278 self
2279 }
2280
2281 /// Indicates whether GC heaps are allowed to be reallocated after initial
2282 /// allocation at runtime.
2283 ///
2284 /// This is similar to [`Config::memory_may_move`] but applies to the GC
2285 /// heap rather than to linear memories. See that method for more details.
2286 ///
2287 /// ## Default
2288 ///
2289 /// If none of the `gc_heap_*` tunables are explicitly configured, they
2290 /// default to the same values as their `memory_*` counterparts. Otherwise,
2291 /// the default value for this option is `true`.
2292 pub fn gc_heap_may_move(&mut self, enable: bool) -> &mut Self {
2293 self.tunables.gc_heap_may_move = Some(enable);
2294 self
2295 }
2296
2297 /// Indicates whether a guard region is present before allocations of
2298 /// linear memory.
2299 ///
2300 /// Guard regions before linear memories are never used during normal
2301 /// operation of WebAssembly modules, even if they have out-of-bounds
2302 /// loads. The only purpose for a preceding guard region in linear memory
2303 /// is extra protection against possible bugs in code generators like
2304 /// Cranelift. This setting does not affect performance in any way, but will
2305 /// result in larger virtual memory reservations for linear memories (it
2306 /// won't actually ever use more memory, just use more of the address
2307 /// space).
2308 ///
2309 /// The size of the guard region before linear memory is the same as the
2310 /// guard size that comes after linear memory, which is configured by
2311 /// [`Config::memory_guard_size`].
2312 ///
2313 /// ## Default
2314 ///
2315 /// This value defaults to `true`.
2316 pub fn guard_before_linear_memory(&mut self, enable: bool) -> &mut Self {
2317 self.tunables.guard_before_linear_memory = Some(enable);
2318 self
2319 }
2320
2321 /// Indicates whether to initialize tables lazily, so that instantiation
2322 /// is fast but indirect calls are a little slower. If false, tables
2323 /// are initialized eagerly during instantiation from any active element
2324 /// segments that apply to them.
2325 ///
2326 /// **Note** Disabling this option is not compatible with the Winch compiler.
2327 ///
2328 /// ## Default
2329 ///
2330 /// This value defaults to `true`.
2331 pub fn table_lazy_init(&mut self, table_lazy_init: bool) -> &mut Self {
2332 self.tunables.table_lazy_init = Some(table_lazy_init);
2333 self
2334 }
2335
2336 /// Configure the version information used in serialized and deserialized [`crate::Module`]s.
2337 /// This effects the behavior of [`crate::Module::serialize()`], as well as
2338 /// [`crate::Module::deserialize()`] and related functions.
2339 ///
2340 /// The default strategy is to use the wasmtime crate's full Cargo package
2341 /// version (major, minor, and patch), so artifacts are only compatible
2342 /// with the exact same release of Wasmtime.
2343 pub fn module_version(&mut self, strategy: ModuleVersionStrategy) -> Result<&mut Self> {
2344 match strategy {
2345 // This case requires special precondition for assertion in SerializedModule::to_bytes
2346 ModuleVersionStrategy::Custom(ref v) => {
2347 if v.as_bytes().len() > 255 {
2348 bail!("custom module version cannot be more than 255 bytes: {v}");
2349 }
2350 }
2351 _ => {}
2352 }
2353 self.module_version = strategy;
2354 Ok(self)
2355 }
2356
2357 /// Configure whether wasmtime should compile a module using multiple
2358 /// threads.
2359 ///
2360 /// Disabling this will result in a single thread being used to compile
2361 /// the wasm bytecode.
2362 ///
2363 /// By default parallel compilation is enabled.
2364 #[cfg(feature = "parallel-compilation")]
2365 pub fn parallel_compilation(&mut self, parallel: bool) -> &mut Self {
2366 self.parallel_compilation = parallel;
2367 self
2368 }
2369
2370 /// Configures whether compiled artifacts will contain information to map
2371 /// native program addresses back to the original wasm module.
2372 ///
2373 /// This configuration option is `true` by default and, if enabled,
2374 /// generates the appropriate tables in compiled modules to map from native
2375 /// address back to wasm source addresses. This is used for displaying wasm
2376 /// program counters in backtraces as well as generating filenames/line
2377 /// numbers if so configured as well (and the original wasm module has DWARF
2378 /// debugging information present).
2379 pub fn generate_address_map(&mut self, generate: bool) -> &mut Self {
2380 self.tunables.generate_address_map = Some(generate);
2381 self
2382 }
2383
2384 /// Configures whether copy-on-write memory-mapped data is used to
2385 /// initialize a linear memory.
2386 ///
2387 /// Initializing linear memory via a copy-on-write mapping can drastically
2388 /// improve instantiation costs of a WebAssembly module because copying
2389 /// memory is deferred. Additionally if a page of memory is only ever read
2390 /// from WebAssembly and never written too then the same underlying page of
2391 /// data will be reused between all instantiations of a module meaning that
2392 /// if a module is instantiated many times this can lower the overall memory
2393 /// required needed to run that module.
2394 ///
2395 /// The main disadvantage of copy-on-write initialization, however, is that
2396 /// it may be possible for highly-parallel scenarios to be less scalable. If
2397 /// a page is read initially by a WebAssembly module then that page will be
2398 /// mapped to a read-only copy shared between all WebAssembly instances. If
2399 /// the same page is then written, however, then a private copy is created
2400 /// and swapped out from the read-only version. This also requires an [IPI],
2401 /// however, which can be a significant bottleneck in high-parallelism
2402 /// situations.
2403 ///
2404 /// This feature is only applicable when a WebAssembly module meets specific
2405 /// criteria to be initialized in this fashion, such as:
2406 ///
2407 /// * Only memories defined in the module can be initialized this way.
2408 /// * Data segments for memory must use statically known offsets.
2409 /// * Data segments for memory must all be in-bounds.
2410 ///
2411 /// Modules which do not meet these criteria will fall back to
2412 /// initialization of linear memory based on copying memory.
2413 ///
2414 /// This feature of Wasmtime is also platform-specific:
2415 ///
2416 /// * Linux - this feature is supported for all instances of [`Module`].
2417 /// Modules backed by an existing mmap (such as those created by
2418 /// [`Module::deserialize_file`]) will reuse that mmap to cow-initialize
2419 /// memory. Other instance of [`Module`] may use the `memfd_create`
2420 /// syscall to create an initialization image to `mmap`.
2421 /// * Unix (not Linux) - this feature is only supported when loading modules
2422 /// from a precompiled file via [`Module::deserialize_file`] where there
2423 /// is a file descriptor to use to map data into the process. Note that
2424 /// the module must have been compiled with this setting enabled as well.
2425 /// * Windows - there is no support for this feature at this time. Memory
2426 /// initialization will always copy bytes.
2427 ///
2428 /// Because of this, with [`Config::consume_fuel`] enabled the fuel consumed
2429 /// by instantiation can differ between platforms while this option is
2430 /// enabled. See [`Config::consume_fuel`] for more details.
2431 ///
2432 /// By default this option is enabled.
2433 ///
2434 /// [`Module::deserialize_file`]: crate::Module::deserialize_file
2435 /// [`Module`]: crate::Module
2436 /// [IPI]: https://en.wikipedia.org/wiki/Inter-processor_interrupt
2437 pub fn memory_init_cow(&mut self, enable: bool) -> &mut Self {
2438 self.tunables.memory_init_cow = Some(enable);
2439 self
2440 }
2441
2442 /// A configuration option to force the usage of `memfd_create` on Linux to
2443 /// be used as the backing source for a module's initial memory image.
2444 ///
2445 /// When [`Config::memory_init_cow`] is enabled, which is enabled by
2446 /// default, module memory initialization images are taken from a module's
2447 /// original mmap if possible. If a precompiled module was loaded from disk
2448 /// this means that the disk's file is used as an mmap source for the
2449 /// initial linear memory contents. This option can be used to force, on
2450 /// Linux, that instead of using the original file on disk a new in-memory
2451 /// file is created with `memfd_create` to hold the contents of the initial
2452 /// image.
2453 ///
2454 /// This option can be used to avoid possibly loading the contents of memory
2455 /// from disk through a page fault. Instead with `memfd_create` the contents
2456 /// of memory are always in RAM, meaning that even page faults which
2457 /// initially populate a wasm linear memory will only work with RAM instead
2458 /// of ever hitting the disk that the original precompiled module is stored
2459 /// on.
2460 ///
2461 /// This option is disabled by default.
2462 pub fn force_memory_init_memfd(&mut self, enable: bool) -> &mut Self {
2463 self.force_memory_init_memfd = enable;
2464 self
2465 }
2466
2467 /// Configures whether or not a coredump should be generated and attached to
2468 /// the [`Error`](crate::Error) when a trap is raised.
2469 ///
2470 /// This option is disabled by default.
2471 #[cfg(feature = "coredump")]
2472 pub fn coredump_on_trap(&mut self, enable: bool) -> &mut Self {
2473 self.coredump_on_trap = enable;
2474 self
2475 }
2476
2477 /// Enables memory error checking for wasm programs.
2478 ///
2479 /// This option is disabled by default.
2480 ///
2481 /// # Panics
2482 ///
2483 /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
2484 #[cfg(any(feature = "cranelift", feature = "winch"))]
2485 pub fn wmemcheck(&mut self, enable: bool) -> &mut Self {
2486 self.wmemcheck = enable;
2487 self.compiler_config_mut().wmemcheck = enable;
2488 self
2489 }
2490
2491 /// Configures the "guaranteed dense image size" for copy-on-write
2492 /// initialized memories.
2493 ///
2494 /// When using the [`Config::memory_init_cow`] feature to initialize memory
2495 /// efficiently (which is enabled by default), compiled modules contain an
2496 /// image of the module's initial heap. If the module has a fairly sparse
2497 /// initial heap, with just a few data segments at very different offsets,
2498 /// this could result in a large region of zero bytes in the image. In
2499 /// other words, it's not very memory-efficient.
2500 ///
2501 /// We normally use a heuristic to avoid this: if less than half
2502 /// of the initialized range (first non-zero to last non-zero
2503 /// byte) of any memory in the module has pages with nonzero
2504 /// bytes, then we avoid creating a memory image for the entire module.
2505 ///
2506 /// However, if the embedder always needs the instantiation-time efficiency
2507 /// of copy-on-write initialization, and is otherwise carefully controlling
2508 /// parameters of the modules (for example, by limiting the maximum heap
2509 /// size of the modules), then it may be desirable to ensure a memory image
2510 /// is created even if this could go against the heuristic above. Thus, we
2511 /// add another condition: there is a size of initialized data region up to
2512 /// which we *always* allow a memory image. The embedder can set this to a
2513 /// known maximum heap size if they desire to always get the benefits of
2514 /// copy-on-write images.
2515 ///
2516 /// In the future we may implement a "best of both worlds"
2517 /// solution where we have a dense image up to some limit, and
2518 /// then support a sparse list of initializers beyond that; this
2519 /// would get most of the benefit of copy-on-write and pay the incremental
2520 /// cost of eager initialization only for those bits of memory
2521 /// that are out-of-bounds. However, for now, an embedder desiring
2522 /// fast instantiation should ensure that this setting is as large
2523 /// as the maximum module initial memory content size.
2524 ///
2525 /// By default this value is 16 MiB.
2526 pub fn memory_guaranteed_dense_image_size(&mut self, size_in_bytes: u64) -> &mut Self {
2527 self.memory_guaranteed_dense_image_size = size_in_bytes;
2528 self
2529 }
2530
2531 /// Whether to enable function inlining during compilation or not.
2532 ///
2533 /// This may result in faster execution at runtime, but adds additional
2534 /// compilation time. Inlining may also enlarge the size of compiled
2535 /// artifacts (for example, the size of the result of
2536 /// [`Engine::precompile_component`]).
2537 ///
2538 /// Inlining is not supported by all of Wasmtime's compilation strategies;
2539 /// currently, it only Cranelift supports it. This setting will be ignored
2540 /// when using a compilation strategy that does not support inlining, like
2541 /// Winch.
2542 ///
2543 /// The default value for this is `Inlining::No`.
2544 pub fn compiler_inlining(&mut self, inlining: Inlining) -> &mut Self {
2545 self.tunables.inlining = Some(inlining);
2546 self
2547 }
2548
2549 /// Returns the set of features that the currently selected compiler backend
2550 /// does not support at all and may panic on.
2551 ///
2552 /// Wasmtime strives to reject unknown modules or unsupported modules with
2553 /// first-class errors instead of panics. Not all compiler backends have the
2554 /// same level of feature support on all platforms as well. This method
2555 /// returns a set of features that the currently selected compiler
2556 /// configuration is known to not support and may panic on. This acts as a
2557 /// first-level filter on incoming wasm modules/configuration to fail-fast
2558 /// instead of panicking later on.
2559 ///
2560 /// Note that if a feature is not returned here it does not mean that the
2561 /// backend fully supports the proposal. Instead that means that the backend
2562 /// doesn't ever panic on the proposal, but errors during compilation may
2563 /// still be returned. This means that features listed here are definitely
2564 /// not supported at all, but features not listed here may still be
2565 /// partially supported. For example at the time of this writing the Winch
2566 /// backend partially supports simd so it's not listed here. Winch doesn't
2567 /// fully support simd but unimplemented instructions just return errors.
2568 fn compiler_panicking_wasm_features(&self) -> WasmFeatures {
2569 // First we compute the set of features that Wasmtime itself knows;
2570 // this is a sort of "maximal set" that we invert to create a set
2571 // of features we _definitely can't support_ because wasmtime
2572 // has never heard of them.
2573 let features_known_to_wasmtime = WasmFeatures::WASM3
2574 | WasmFeatures::COMPONENT_MODEL
2575 | WasmFeatures::CUSTOM_PAGE_SIZES
2576 | WasmFeatures::COMPACT_IMPORTS
2577 | WasmFeatures::STACK_SWITCHING
2578 | WasmFeatures::WIDE_ARITHMETIC
2579 | WasmFeatures::CM_ASYNC
2580 | WasmFeatures::CM_ASYNC_STACKFUL
2581 | WasmFeatures::CM_MORE_ASYNC_BUILTINS
2582 | WasmFeatures::CM_THREADING
2583 | WasmFeatures::CM_ERROR_CONTEXT
2584 | WasmFeatures::CM_GC
2585 | WasmFeatures::CM_MAP
2586 | WasmFeatures::CM64
2587 | WasmFeatures::CM_FIXED_LENGTH_LISTS
2588 | WasmFeatures::CM_IMPLEMENTS
2589 | WasmFeatures::CM_CANON_NAMES
2590 | WasmFeatures::CM_ACCESSORS;
2591
2592 let mut unsupported = !features_known_to_wasmtime;
2593
2594 match self.get_strategy() {
2595 None | Some(Strategy::Cranelift) => {
2596 // Pulley at this time fundamentally doesn't support the
2597 // `threads` proposal, notably shared memory, because Rust can't
2598 // safely implement loads/stores in the face of shared memory.
2599 // Stack switching is not implemented, either.
2600 if self.compiler_target().is_pulley() {
2601 unsupported |= WasmFeatures::THREADS;
2602 unsupported |= WasmFeatures::STACK_SWITCHING;
2603 }
2604
2605 use target_lexicon::*;
2606 match self.compiler_target() {
2607 Triple {
2608 architecture: Architecture::X86_64 | Architecture::X86_64h,
2609 operating_system:
2610 OperatingSystem::Linux
2611 | OperatingSystem::MacOSX(_)
2612 | OperatingSystem::Darwin(_),
2613 ..
2614 } => {
2615 // Stack switching supported on (non-Pulley) Cranelift.
2616 }
2617
2618 _ => {
2619 // On platforms other than x64 Unix-like, we don't
2620 // support stack switching.
2621 unsupported |= WasmFeatures::STACK_SWITCHING;
2622 }
2623 }
2624 }
2625 Some(Strategy::Winch) => {
2626 unsupported |= WasmFeatures::GC
2627 | WasmFeatures::FUNCTION_REFERENCES
2628 | WasmFeatures::RELAXED_SIMD
2629 | WasmFeatures::LEGACY_EXCEPTIONS
2630 | WasmFeatures::STACK_SWITCHING;
2631
2632 match self.compiler_target().architecture {
2633 target_lexicon::Architecture::Aarch64(_) => {
2634 unsupported |= WasmFeatures::THREADS;
2635 }
2636
2637 // Winch doesn't support other non-x64 architectures at this
2638 // time either but will return an first-class error for
2639 // them.
2640 _ => {}
2641 }
2642 }
2643 Some(Strategy::Auto) => unreachable!(),
2644 }
2645 unsupported
2646 }
2647
2648 fn get_strategy(&self) -> Option<Strategy> {
2649 #[cfg(any(feature = "cranelift", feature = "winch"))]
2650 return self.compiler_config.as_ref()?.strategy;
2651 #[cfg(not(any(feature = "cranelift", feature = "winch")))]
2652 return None;
2653 }
2654
2655 /// Calculates the set of features that are enabled for this `Config`.
2656 ///
2657 /// This is a bit of a subtle function which takes into account inputs such
2658 /// as the default set of features Wasmtime has enabled, the currently
2659 /// enabled compiler, the currently enabled target, compile-time crate
2660 /// features, and explicitly configured wasm proposals. This function does
2661 /// not return a fixed set of all proposals in all cases as it's a bit more
2662 /// nuanced than that.
2663 ///
2664 /// This method internally will start with an empty set of features to
2665 /// avoid being tied to wasmparser's defaults. Next Wasmtime's set of
2666 /// default features are added to this set, some of which are conditional
2667 /// depending on crate features. Finally explicitly requested features via
2668 /// `wasm_*` methods on `Config` are applied. Everything is then validated
2669 /// later in `Config::validate`.
2670 ///
2671 /// Note that the validation later on in `Config::validate` is a crucial
2672 /// step here. The returned features here might include features unsupported
2673 /// at compile time or unsupported by the selected compiler. In that case
2674 /// `Config::validate` will present a first-class error message indicating
2675 /// what's going on, and users should in theory be able to understand "ok
2676 /// yeah that's why I can't enable that feature here".
2677 fn features(&self) -> WasmFeatures {
2678 let mut features;
2679
2680 // Next add in all on-by-default features that Wasmtime has which are
2681 // subject to the criteria at
2682 // https://docs.wasmtime.dev/contributing-implementing-wasm-proposals.html
2683 // and https://docs.wasmtime.dev/stability-wasm-proposals.html.
2684 //
2685 // Features here are based on the currently selected compiler. Wasm
2686 // features generally are tightly intertwined with compiler support, and
2687 // just because we want to on-by-default support in one compiler doesn't
2688 // mean we want it for another. Additionally note that each compiler
2689 // here starts with a fixed, unchanging, set of wasm features (e.g.
2690 // `WASM2` or `WASM3`) which insulates this from `wasmparser`'s
2691 // defaults.
2692 //
2693 // Finally, `None` is possible here when compiler support isn't enabled
2694 // at all. In that situation just assume we're using Cranelift's feature
2695 // set.
2696 //
2697 // NB: if you add a feature to a compiler please double-check
2698 // https://docs.wasmtime.dev/stability-wasm-proposals.html
2699 // to ensure all requirements are met and/or update the documentation
2700 // there too.
2701 match self.get_strategy() {
2702 None | Some(Strategy::Cranelift) => {
2703 features = WasmFeatures::WASM3;
2704 features |= WasmFeatures::WIDE_ARITHMETIC;
2705
2706 // features |= WasmFeatures::YOUR_WASM_FEATURE;
2707 // ...
2708 }
2709 Some(Strategy::Winch) => {
2710 features = WasmFeatures::WASM2;
2711 features.remove(WasmFeatures::GC_TYPES);
2712 features |= WasmFeatures::EXTENDED_CONST;
2713 features |= WasmFeatures::MEMORY64;
2714 features |= WasmFeatures::MULTI_MEMORY;
2715 }
2716 Some(Strategy::Auto) => unreachable!(),
2717 }
2718
2719 // Next configure some features further based on compile-time features
2720 // of the wasmtime crate itself. For example if "gc" is disabled then
2721 // `GC_TYPES` are disabled (a wasmparser pseudo-feature) as well as
2722 // exceptions, but reference-types is still available (e.g. new
2723 // encodings/types/etc).
2724 if !cfg!(feature = "gc") {
2725 features.remove(WasmFeatures::GC_TYPES | WasmFeatures::EXCEPTIONS);
2726 }
2727 if !cfg!(feature = "threads") {
2728 features.remove(WasmFeatures::THREADS);
2729 }
2730
2731 // These features aren't included in the base sets above, so explicitly
2732 // enable/disable them there based on compiler features. Note that
2733 // these are pretty much exclusively runtime-related features so there's
2734 // no differentiation here between compilers.
2735 features.set(
2736 WasmFeatures::COMPONENT_MODEL,
2737 cfg!(feature = "component-model"),
2738 );
2739 features.set(WasmFeatures::CM_MAP, cfg!(feature = "component-model"));
2740 features.set(
2741 WasmFeatures::CM_ASYNC,
2742 self.tunables
2743 .concurrency_support
2744 .unwrap_or(cfg!(feature = "component-model-async")),
2745 );
2746
2747 // Next disable any features which the current compiler/target do not
2748 // support. This handles cases where Winch, for example, doesn't
2749 // implement a feature yet but Cranelift does. Or maybe Cranelift only
2750 // supports one particular platform and not others. Things like that.
2751 features = features & !self.compiler_panicking_wasm_features();
2752
2753 // And, finally, process all explicitly enabled/disabled features on
2754 // behalf of the embedder's frobbing `Config::wasm_*`. These have the
2755 // highest priority since they were explicitly requested.
2756 debug_assert!((self.enabled_features & self.disabled_features).is_empty());
2757 features &= !self.disabled_features;
2758 features |= self.enabled_features;
2759
2760 features
2761 }
2762
2763 /// Returns the configured compiler target for this `Config`.
2764 pub(crate) fn compiler_target(&self) -> target_lexicon::Triple {
2765 // If a target is explicitly configured, always use that.
2766 if let Some(target) = self.target.clone() {
2767 return target;
2768 }
2769
2770 // If the `build.rs` script determined that this platform uses pulley by
2771 // default, then use Pulley.
2772 if cfg!(default_target_pulley) {
2773 return target_lexicon::Triple::pulley_host();
2774 }
2775
2776 // And at this point the target is for sure the host.
2777 target_lexicon::Triple::host()
2778 }
2779
2780 /// Returns `true` if any of the `gc_heap_*` tunables have been explicitly
2781 /// configured.
2782 fn any_gc_heap_tunables_configured(&self) -> bool {
2783 self.tunables.gc_heap_reservation.is_some()
2784 || self.tunables.gc_heap_guard_size.is_some()
2785 || self.tunables.gc_heap_reservation_for_growth.is_some()
2786 || self.tunables.gc_heap_may_move.is_some()
2787 }
2788
2789 pub(crate) fn validate(&self) -> Result<(Tunables, WasmFeatures)> {
2790 let features = self.features();
2791
2792 // First validate that the selected compiler backend and configuration
2793 // supports the set of `features` that are enabled. This will help
2794 // provide more first class errors instead of panics about unsupported
2795 // features and configurations.
2796 let unsupported = features & self.compiler_panicking_wasm_features();
2797 if !unsupported.is_empty() {
2798 for flag in WasmFeatures::FLAGS.iter() {
2799 if !unsupported.contains(*flag.value()) {
2800 continue;
2801 }
2802 bail!(
2803 "the wasm_{} feature is not supported on this compiler configuration",
2804 flag.name().to_lowercase()
2805 );
2806 }
2807
2808 panic!("should have returned an error by now")
2809 }
2810
2811 if self.max_wasm_stack > self.async_stack_size {
2812 bail!("max_wasm_stack size cannot exceed the async_stack_size");
2813 }
2814 if self.max_wasm_stack == 0 {
2815 bail!("max_wasm_stack size cannot be zero");
2816 }
2817 if !cfg!(feature = "wmemcheck") && self.wmemcheck {
2818 bail!("wmemcheck (memory checker) was requested but is not enabled in this build");
2819 }
2820
2821 if !cfg!(feature = "gc") && features.gc_types() {
2822 bail!("support for GC was disabled at compile time")
2823 }
2824
2825 if !cfg!(feature = "gc") && features.contains(WasmFeatures::EXCEPTIONS) {
2826 bail!("exceptions support requires garbage collection (GC) to be enabled in the build");
2827 }
2828
2829 if !cfg!(feature = "threads") && features.threads() {
2830 bail!("support for threads was disabled at compile time")
2831 }
2832
2833 if !cfg!(feature = "stack-switching") && features.contains(WasmFeatures::STACK_SWITCHING) {
2834 bail!("support for stack switching was disabled at compile time")
2835 }
2836
2837 let rr = self.tunables.rr.flatten();
2838 if rr.is_some() {
2839 if !cfg!(feature = "rr") {
2840 bail!("support for record/replay was disabled at compile time");
2841 }
2842 self.validate_rr_determinism_conflicts()?;
2843 }
2844
2845 let mut tunables = Tunables::default_for_target(&self.compiler_target())?;
2846
2847 // Stack switching is emitted inline in compiled Wasm. In
2848 // ASan-enabled builds the compiler must arrange the
2849 // corresponding fiber switch handshake around every such
2850 // instruction. This defaults to how Wasmtime itself was built
2851 // but can be overridden with `Config::asan_compatible_code`.
2852 tunables.asan_stack_switching = cfg!(asan);
2853
2854 // By default this is enabled with the Cargo feature, and if the feature
2855 // is missing this is disabled.
2856 tunables.concurrency_support = cfg!(feature = "component-model-async");
2857
2858 // Record/replay requires deterministic relaxed SIMD by default;
2859 // `validate_rr_determinism_conflicts` rejects disabling it.
2860 if rr.is_some() {
2861 tunables.relaxed_simd_deterministic = true;
2862 }
2863
2864 // If no target is explicitly specified then further refine `tunables`
2865 // for the configuration of this host depending on what platform
2866 // features were found available at compile time. This means that anyone
2867 // cross-compiling for a customized host will need to further refine
2868 // compilation options.
2869 if self.target.is_none() {
2870 // If this platform doesn't have native signals then change some
2871 // defaults to account for that. Note that VM guards are turned off
2872 // here because that's primarily a feature of eliding
2873 // bounds-checks.
2874 if !cfg!(has_native_signals) {
2875 tunables.signals_based_traps = cfg!(has_native_signals);
2876 tunables.memory_guard_size = 0;
2877 tunables.gc_heap_guard_size = 0;
2878 }
2879
2880 // When virtual memory is not available use slightly different
2881 // defaults for tunables to be more amenable to `MallocMemory`.
2882 // Note that these can still be overridden by config options.
2883 if !cfg!(has_virtual_memory) {
2884 tunables.memory_reservation = 0;
2885 tunables.memory_reservation_for_growth = 1 << 20; // 1MB
2886 tunables.memory_init_cow = false;
2887 tunables.gc_heap_reservation = 0;
2888 tunables.gc_heap_reservation_for_growth = 1 << 20; // 1MB
2889 }
2890 }
2891
2892 // If guest-debugging is enabled, we must disable
2893 // signals-based traps. Do this before we process the user's
2894 // provided tunables settings so we can detect a conflict with
2895 // an explicit request to use signals-based traps.
2896 #[cfg(feature = "debug")]
2897 if self.tunables.debug_guest == Some(true) {
2898 tunables.signals_based_traps = false;
2899 }
2900
2901 // Inlining currently falls over with the `stack_switch` instruction.
2902 #[cfg(any(feature = "cranelift", feature = "winch"))]
2903 if features.contains(WasmFeatures::STACK_SWITCHING) {
2904 if let Some(inlining) = self.tunables.inlining
2905 && inlining != Inlining::No
2906 {
2907 bail!("cannot enable compiler inlining when stack switching is enabled");
2908 }
2909 tunables.inlining = Inlining::No;
2910 }
2911
2912 self.tunables.configure(&mut tunables);
2913
2914 // Debuggers set watchpoints through linear memories' shadows.
2915 tunables.memory_watchpoints = tunables.debug_guest;
2916
2917 // If no GC heap tunables are explicitly configured, copy the memory
2918 // tunables' configured values so that GC heaps default to the same
2919 // configuration as linear memories.
2920 if !self.any_gc_heap_tunables_configured() {
2921 tunables.gc_heap_reservation = tunables.memory_reservation;
2922 tunables.gc_heap_guard_size = tunables.memory_guard_size;
2923 tunables.gc_heap_reservation_for_growth = tunables.memory_reservation_for_growth;
2924 tunables.gc_heap_may_move = tunables.memory_may_move;
2925 }
2926
2927 // Validate that the configuration of reservation/guards is sensible
2928 // enough to ever possibly actually get allocated. If this doesn't fit
2929 // in the target's address space then there's no hope.
2930 let guard_regions = if tunables.guard_before_linear_memory {
2931 2
2932 } else {
2933 1
2934 };
2935 let max_size = match self.compiler_target().pointer_width() {
2936 Ok(width) if width.bits() < 64 => (1 << width.bits()) - 1,
2937 _ => u64::MAX,
2938 };
2939 for (what, reservation, guard_size) in [
2940 (
2941 "memory",
2942 tunables.memory_reservation,
2943 tunables.memory_guard_size,
2944 ),
2945 (
2946 "gc_heap",
2947 tunables.gc_heap_reservation,
2948 tunables.gc_heap_guard_size,
2949 ),
2950 ] {
2951 if guard_size
2952 .checked_mul(guard_regions)
2953 .and_then(|g| g.checked_add(reservation))
2954 .is_none_or(|size| size > max_size)
2955 {
2956 bail!(
2957 "`{what}_reservation` ({reservation}) plus `{what}_guard_size` \
2958 ({guard_size}) overflows the target's address space"
2959 );
2960 }
2961 }
2962
2963 // If we're going to compile with winch, we must use the winch calling convention.
2964 #[cfg(any(feature = "cranelift", feature = "winch"))]
2965 {
2966 tunables.winch_callable = self
2967 .compiler_config
2968 .as_ref()
2969 .is_some_and(|c| c.strategy == Some(Strategy::Winch));
2970 }
2971
2972 tunables.collector = if features.gc_types() {
2973 #[cfg(feature = "gc")]
2974 {
2975 use wasmtime_environ::Collector as EnvCollector;
2976 Some(match self.collector.try_not_auto()? {
2977 Collector::DeferredReferenceCounting => EnvCollector::DeferredReferenceCounting,
2978 Collector::Null => EnvCollector::Null,
2979 Collector::Copying => EnvCollector::Copying,
2980 Collector::Auto => unreachable!(),
2981 })
2982 }
2983 #[cfg(not(feature = "gc"))]
2984 bail!("cannot use GC types: the `gc` feature was disabled at compile time")
2985 } else {
2986 None
2987 };
2988
2989 if tunables.debug_guest {
2990 ensure!(
2991 cfg!(feature = "debug"),
2992 "debug instrumentation support was disabled at compile time"
2993 );
2994 ensure!(
2995 !tunables.signals_based_traps,
2996 "cannot use signals-based traps with guest debugging enabled"
2997 );
2998 }
2999
3000 if tunables.mmu_interruption {
3001 // Only with signals-based traps can MMU interruption's signal
3002 // handler be installed (at engine creation time).
3003 ensure!(
3004 tunables.signals_based_traps,
3005 "MMU interruption requires signals-based traps"
3006 );
3007 }
3008 // Concurrency support is required for some component model features.
3009 let requires_concurrency = WasmFeatures::CM_ASYNC
3010 | WasmFeatures::CM_MORE_ASYNC_BUILTINS
3011 | WasmFeatures::CM_ASYNC_STACKFUL
3012 | WasmFeatures::CM_THREADING
3013 | WasmFeatures::CM_ERROR_CONTEXT;
3014 if tunables.concurrency_support && !cfg!(feature = "component-model-async") {
3015 bail!(
3016 "concurrency support was requested but was not \
3017 compiled into this build of Wasmtime"
3018 )
3019 }
3020 if !tunables.concurrency_support && features.intersects(requires_concurrency) {
3021 bail!(
3022 "concurrency support must be enabled to use the component \
3023 model async or threading features"
3024 )
3025 }
3026
3027 // Generated adapters between components will use `ref.func` in some
3028 // async-related situations so `component-model-async` requires
3029 // `reference-types`.
3030 if features.contains(WasmFeatures::CM_ASYNC)
3031 && !features.contains(WasmFeatures::REFERENCE_TYPES)
3032 {
3033 bail!("the component-model-async feature requires the wasm reference-types proposal");
3034 }
3035
3036 // If the pooling allocator is used and GC is enabled, check that
3037 // memories and the GC heap are configured identically, since the
3038 // pooling allocator can't support differently-configured heaps.
3039 #[cfg(feature = "pooling-allocator")]
3040 if matches!(
3041 &self.allocation_strategy,
3042 InstanceAllocationStrategy::Pooling(_)
3043 ) && tunables.collector.is_some()
3044 {
3045 if tunables.memory_reservation != tunables.gc_heap_reservation {
3046 bail!(
3047 "when using the pooling allocator with GC, `memory_reservation` ({}) \
3048 and `gc_heap_reservation` ({}) must be the same",
3049 tunables.memory_reservation,
3050 tunables.gc_heap_reservation,
3051 );
3052 }
3053 if tunables.memory_guard_size != tunables.gc_heap_guard_size {
3054 bail!(
3055 "when using the pooling allocator with GC, `memory_guard_size` ({}) \
3056 and `gc_heap_guard_size` ({}) must be the same",
3057 tunables.memory_guard_size,
3058 tunables.gc_heap_guard_size,
3059 );
3060 }
3061 if tunables.memory_reservation_for_growth != tunables.gc_heap_reservation_for_growth {
3062 bail!(
3063 "when using the pooling allocator with GC, \
3064 `memory_reservation_for_growth` ({}) and \
3065 `gc_heap_reservation_for_growth` ({}) must be the same",
3066 tunables.memory_reservation_for_growth,
3067 tunables.gc_heap_reservation_for_growth,
3068 );
3069 }
3070 if tunables.memory_may_move != tunables.gc_heap_may_move {
3071 bail!(
3072 "when using the pooling allocator with GC, `memory_may_move` ({}) \
3073 and `gc_heap_may_move` ({}) must be the same",
3074 tunables.memory_may_move,
3075 tunables.gc_heap_may_move,
3076 );
3077 }
3078 }
3079
3080 if tunables.debug_native && !tunables.debug_symbols {
3081 bail!("cannot enable native debug info while debug symbols are disabled");
3082 }
3083
3084 Ok((tunables, features))
3085 }
3086
3087 #[cfg(feature = "runtime")]
3088 pub(crate) fn build_allocator(
3089 &self,
3090 tunables: &Tunables,
3091 ) -> Result<Box<dyn InstanceAllocator + Send + Sync>> {
3092 let _ = tunables;
3093
3094 match &self.allocation_strategy {
3095 InstanceAllocationStrategy::OnDemand => {
3096 let mut _allocator = try_new::<Box<_>>(OnDemandInstanceAllocator::new(
3097 self.mem_creator.clone(),
3098 self.async_stack_size,
3099 self.async_stack_zeroing,
3100 ))?;
3101 #[cfg(feature = "async")]
3102 if let Some(stack_creator) = &self.stack_creator {
3103 _allocator.set_stack_creator(stack_creator.clone());
3104 }
3105 Ok(_allocator as _)
3106 }
3107 #[cfg(feature = "pooling-allocator")]
3108 InstanceAllocationStrategy::Pooling(config) => {
3109 let mut config = config.clone();
3110 let _ = &mut config;
3111 #[cfg(feature = "async")]
3112 {
3113 config.stack_size = self.async_stack_size;
3114 config.async_stack_zeroing = self.async_stack_zeroing;
3115 }
3116 let allocator = try_new::<Box<_>>(
3117 crate::runtime::vm::PoolingInstanceAllocator::new(&config, tunables)?,
3118 )?;
3119 Ok(allocator as _)
3120 }
3121 }
3122 }
3123
3124 #[cfg(feature = "runtime")]
3125 pub(crate) fn build_gc_runtime(&self) -> Result<Option<Arc<dyn GcRuntime>>> {
3126 if !self.features().gc_types() {
3127 return Ok(None);
3128 }
3129
3130 #[cfg(not(feature = "gc"))]
3131 bail!("cannot create a GC runtime: the `gc` feature was disabled at compile time");
3132
3133 #[cfg(feature = "gc")]
3134 #[cfg_attr(
3135 not(any(feature = "gc-null", feature = "gc-drc", feature = "gc-copying")),
3136 expect(unreachable_code, reason = "definitions known to be dummy")
3137 )]
3138 {
3139 Ok(Some(match self.collector.try_not_auto()? {
3140 #[cfg(feature = "gc-drc")]
3141 Collector::DeferredReferenceCounting => {
3142 try_new::<Arc<_>>(crate::runtime::vm::DrcCollector::default())? as _
3143 }
3144 #[cfg(not(feature = "gc-drc"))]
3145 Collector::DeferredReferenceCounting => unreachable!(),
3146
3147 #[cfg(feature = "gc-null")]
3148 Collector::Null => {
3149 try_new::<Arc<_>>(crate::runtime::vm::NullCollector::default())? as _
3150 }
3151 #[cfg(not(feature = "gc-null"))]
3152 Collector::Null => unreachable!(),
3153
3154 #[cfg(feature = "gc-copying")]
3155 Collector::Copying => {
3156 try_new::<Arc<_>>(crate::runtime::vm::CopyingCollector::default())? as _
3157 }
3158 #[cfg(not(feature = "gc-copying"))]
3159 Collector::Copying => unreachable!(),
3160
3161 Collector::Auto => unreachable!(),
3162 }))
3163 }
3164 }
3165
3166 #[cfg(feature = "runtime")]
3167 pub(crate) fn build_profiler(&self) -> Result<Box<dyn ProfilingAgent>> {
3168 Ok(match self.profiling_strategy {
3169 ProfilingStrategy::PerfMap => profiling_agent::new_perfmap()?,
3170 ProfilingStrategy::JitDump => profiling_agent::new_jitdump()?,
3171 ProfilingStrategy::VTune => profiling_agent::new_vtune()?,
3172 ProfilingStrategy::None => profiling_agent::new_null(),
3173 ProfilingStrategy::Pulley => profiling_agent::new_pulley()?,
3174 })
3175 }
3176
3177 #[cfg(any(feature = "cranelift", feature = "winch"))]
3178 pub(crate) fn build_compiler(
3179 mut self,
3180 tunables: &mut Tunables,
3181 features: WasmFeatures,
3182 ) -> Result<(Self, Box<dyn wasmtime_environ::Compiler>)> {
3183 let target = self.compiler_target();
3184
3185 // The target passed to the builders below is an `Option<Triple>` where
3186 // `None` represents the current host with CPU features inferred from
3187 // the host's CPU itself. The `target` above is not an `Option`, so
3188 // switch it to `None` in the case that a target wasn't explicitly
3189 // specified (which indicates no feature inference) and the target
3190 // matches the host.
3191 let target_for_builder =
3192 if self.target.is_none() && target == target_lexicon::Triple::host() {
3193 None
3194 } else {
3195 Some(target.clone())
3196 };
3197
3198 let mut compiler = match self.compiler_config_mut().strategy {
3199 #[cfg(feature = "cranelift")]
3200 Some(Strategy::Cranelift) => wasmtime_cranelift::builder(target_for_builder)?,
3201 #[cfg(not(feature = "cranelift"))]
3202 Some(Strategy::Cranelift) => bail!("cranelift support not compiled in"),
3203 #[cfg(feature = "winch")]
3204 Some(Strategy::Winch) => wasmtime_winch::builder(target_for_builder)?,
3205 #[cfg(not(feature = "winch"))]
3206 Some(Strategy::Winch) => bail!("winch support not compiled in"),
3207
3208 None | Some(Strategy::Auto) => unreachable!(),
3209 };
3210
3211 if let Some(path) = &self.compiler_config_mut().clif_dir {
3212 compiler.clif_dir(path)?;
3213 }
3214
3215 // If probestack is enabled for a target, Wasmtime will always use the
3216 // inline strategy which doesn't require us to define a `__probestack`
3217 // function or similar.
3218 self.compiler_config_mut().settings.insert(
3219 "probestack_strategy".into(),
3220 ("inline".into(), UserSpecified::No),
3221 );
3222
3223 // We enable stack probing by default on all targets.
3224 // This is required on Windows because of the way Windows
3225 // commits its stacks, but it's also a good idea on other
3226 // platforms to ensure guard pages are hit for large frame
3227 // sizes.
3228 self.compiler_config_mut()
3229 .flags
3230 .insert("enable_probestack".into(), UserSpecified::No);
3231
3232 // The current wasm multivalue implementation depends on this.
3233 // FIXME(#9510) handle this in wasmtime-cranelift instead.
3234 self.compiler_config_mut()
3235 .flags
3236 .insert("enable_multi_ret_implicit_sret".into(), UserSpecified::No);
3237
3238 if let Some(unwind_requested) = self.native_unwind_info {
3239 if !self
3240 .compiler_config_mut()
3241 .ensure_setting_unset_or_given("unwind_info", &unwind_requested.to_string())
3242 {
3243 bail!(
3244 "incompatible settings requested for Cranelift and Wasmtime `unwind-info` settings"
3245 );
3246 }
3247 }
3248
3249 if target.operating_system == target_lexicon::OperatingSystem::Windows {
3250 if !self
3251 .compiler_config_mut()
3252 .ensure_setting_unset_or_given("unwind_info", "true")
3253 {
3254 bail!("`native_unwind_info` cannot be disabled on Windows");
3255 }
3256 }
3257
3258 // Record/replay requires that floating-point results not depend on the
3259 // host, so that a trace replays the same on another architecture.
3260 if tunables.rr.is_some()
3261 && !self
3262 .compiler_config_mut()
3263 .ensure_setting_unset_or_given("enable_nan_canonicalization", "true")
3264 {
3265 bail!("NaN canonicalization cannot be disabled when determinism is enforced");
3266 }
3267
3268 // We require frame pointers for correct stack walking, which is safety
3269 // critical in the presence of reference types, and otherwise it is just
3270 // really bad developer experience to get wrong.
3271 self.compiler_config_mut().settings.insert(
3272 "preserve_frame_pointers".into(),
3273 ("true".into(), UserSpecified::No),
3274 );
3275
3276 if !tunables.signals_based_traps {
3277 let mut ok = self
3278 .compiler_config_mut()
3279 .ensure_setting_unset_or_given("enable_table_access_spectre_mitigation", "false");
3280 ok = ok
3281 && self.compiler_config_mut().ensure_setting_unset_or_given(
3282 "enable_heap_access_spectre_mitigation",
3283 "false",
3284 );
3285
3286 // Right now spectre-mitigated bounds checks will load from zero so
3287 // if host-based signal handlers are disabled then that's a mismatch
3288 // and doesn't work right now. Fixing this will require more thought
3289 // of how to implement the bounds check in spectre-only mode.
3290 if !ok {
3291 bail!(
3292 "when signals-based traps are disabled then spectre \
3293 mitigations must also be disabled"
3294 );
3295 }
3296 }
3297
3298 if features.contains(WasmFeatures::RELAXED_SIMD) && !features.contains(WasmFeatures::SIMD) {
3299 bail!("cannot disable the simd proposal but enable the relaxed simd proposal");
3300 }
3301
3302 if features.contains(WasmFeatures::STACK_SWITCHING) {
3303 use target_lexicon::OperatingSystem;
3304 let model = match target.operating_system {
3305 OperatingSystem::Windows => "update_windows_tib",
3306 OperatingSystem::Linux
3307 | OperatingSystem::MacOSX(_)
3308 | OperatingSystem::Darwin(_) => "basic",
3309 _ => bail!("stack-switching feature not supported on this platform "),
3310 };
3311
3312 if !self
3313 .compiler_config_mut()
3314 .ensure_setting_unset_or_given("stack_switch_model", model)
3315 {
3316 bail!(
3317 "compiler option 'stack_switch_model' must be set to '{model}' on this platform"
3318 );
3319 }
3320 }
3321
3322 // Apply compiler settings and flags
3323 compiler.set_tunables(tunables.clone())?;
3324 for (k, (v, _)) in self.compiler_config_mut().settings.iter() {
3325 compiler.set(k, v)?;
3326 }
3327 for (flag, _) in self.compiler_config_mut().flags.iter() {
3328 compiler.enable(flag)?;
3329 }
3330 *tunables = compiler.tunables().cloned().unwrap();
3331
3332 #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
3333 if let Some(cache_store) = &self.compiler_config_mut().cache_store {
3334 compiler.enable_incremental_compilation(cache_store.clone())?;
3335 }
3336
3337 compiler.wmemcheck(self.compiler_config_mut().wmemcheck);
3338
3339 let compiler = compiler.build()?;
3340
3341 // SIMD support can depend on ISA flags, such as `has_v` on riscv64,
3342 // which aren't known until now, so it's checked here and not in
3343 // `compiler_panicking_wasm_features`.
3344 if !compiler.supports_wasm_simd() {
3345 let simd = WasmFeatures::SIMD | WasmFeatures::RELAXED_SIMD;
3346 if let Some((name, _)) = (features & simd).iter_names().next() {
3347 bail!(
3348 "the wasm_{} feature is not supported on this compiler \
3349 configuration, enable the target's vector extension or \
3350 disable both simd and relaxed-simd",
3351 name.to_lowercase()
3352 );
3353 }
3354 }
3355
3356 Ok((self, compiler))
3357 }
3358
3359 /// Internal setting for whether adapter modules for components will have
3360 /// extra WebAssembly instructions inserted performing more debug checks
3361 /// then are necessary.
3362 #[cfg(feature = "component-model")]
3363 pub fn debug_adapter_modules(&mut self, debug: bool) -> &mut Self {
3364 self.tunables.debug_adapter_modules = Some(debug);
3365 self
3366 }
3367
3368 /// Enables clif output when compiling a WebAssembly module.
3369 #[cfg(any(feature = "cranelift", feature = "winch"))]
3370 pub fn emit_clif(&mut self, path: &Path) -> &mut Self {
3371 self.compiler_config_mut().clif_dir = Some(path.to_path_buf());
3372 self
3373 }
3374
3375 /// Configures whether, when on macOS, Mach ports are used for exception
3376 /// handling instead of traditional Unix-based signal handling.
3377 ///
3378 /// WebAssembly traps in Wasmtime are implemented with native faults, for
3379 /// example a `SIGSEGV` will occur when a WebAssembly guest accesses
3380 /// out-of-bounds memory. Handling this can be configured to either use Unix
3381 /// signals or Mach ports on macOS. By default Mach ports are used.
3382 ///
3383 /// Mach ports enable Wasmtime to work by default with foreign
3384 /// error-handling systems such as breakpad which also use Mach ports to
3385 /// handle signals. In this situation Wasmtime will continue to handle guest
3386 /// faults gracefully while any non-guest faults will get forwarded to
3387 /// process-level handlers such as breakpad. Some more background on this
3388 /// can be found in #2456.
3389 ///
3390 /// A downside of using mach ports, however, is that they don't interact
3391 /// well with `fork()`. Forking a Wasmtime process on macOS will produce a
3392 /// child process that cannot successfully run WebAssembly. In this
3393 /// situation traditional Unix signal handling should be used as that's
3394 /// inherited and works across forks.
3395 ///
3396 /// If your embedding wants to use a custom error handler which leverages
3397 /// Mach ports and you additionally wish to `fork()` the process and use
3398 /// Wasmtime in the child process that's not currently possible. Please
3399 /// reach out to us if you're in this bucket!
3400 ///
3401 /// This option defaults to `true`, using Mach ports by default.
3402 pub fn macos_use_mach_ports(&mut self, mach_ports: bool) -> &mut Self {
3403 self.macos_use_mach_ports = mach_ports;
3404 self
3405 }
3406
3407 /// Configures an embedder-provided function, `detect`, which is used to
3408 /// determine if an ISA-specific feature is available on the current host.
3409 ///
3410 /// This function is used to verify that any features enabled for a compiler
3411 /// backend, such as AVX support on x86\_64, are also available on the host.
3412 /// It is undefined behavior to execute an AVX instruction on a host that
3413 /// doesn't support AVX instructions, for example.
3414 ///
3415 /// When the `std` feature is active on this crate then this function is
3416 /// configured to a default implementation that uses the standard library's
3417 /// feature detection. When the `std` feature is disabled then there is no
3418 /// default available and this method must be called to configure a feature
3419 /// probing function.
3420 ///
3421 /// The `detect` function provided is given a string name of an ISA feature.
3422 /// The function should then return:
3423 ///
3424 /// * `Some(true)` - indicates that the feature was found on the host and it
3425 /// is supported.
3426 /// * `Some(false)` - the feature name was recognized but it was not
3427 /// detected on the host, for example the CPU is too old.
3428 /// * `None` - the feature name was not recognized and it's not known
3429 /// whether it's on the host or not.
3430 ///
3431 /// Feature names passed to `detect` match the same feature name used in the
3432 /// Rust standard library. For example `"sse4.2"` is used on x86\_64.
3433 ///
3434 /// # Unsafety
3435 ///
3436 /// This function is `unsafe` because it is undefined behavior to execute
3437 /// instructions that a host does not support. This means that the result of
3438 /// `detect` must be correct for memory safe execution at runtime.
3439 pub unsafe fn detect_host_feature(&mut self, detect: fn(&str) -> Option<bool>) -> &mut Self {
3440 self.detect_host_feature = Some(detect);
3441 self
3442 }
3443
3444 /// Configures Wasmtime to not use signals-based trap handlers, for example
3445 /// disables `SIGILL` and `SIGSEGV` handler registration on Unix platforms.
3446 ///
3447 /// > **Note:** this option has important performance ramifications, be sure
3448 /// > to understand the implications. Wasm programs have been measured to
3449 /// > run up to 2x slower when signals-based traps are disabled.
3450 ///
3451 /// Wasmtime will by default leverage signals-based trap handlers (or the
3452 /// platform equivalent, for example "vectored exception handlers" on
3453 /// Windows) to make generated code more efficient. For example, when
3454 /// Wasmtime can use signals-based traps, it can elide explicit bounds
3455 /// checks for Wasm linear memory accesses, instead relying on virtual
3456 /// memory guard pages to raise a `SIGSEGV` (on Unix) for out-of-bounds
3457 /// accesses, which Wasmtime's runtime then catches and handles. Another
3458 /// example is divide-by-zero: with signals-based traps, Wasmtime can let
3459 /// the hardware raise a trap when the divisor is zero. Without
3460 /// signals-based traps, Wasmtime must explicitly emit additional
3461 /// instructions to check for zero and conditionally branch to a trapping
3462 /// code path.
3463 ///
3464 /// Some environments however may not have access to signal handlers. For
3465 /// example embedded scenarios may not support virtual memory. Other
3466 /// environments where Wasmtime is embedded within the surrounding
3467 /// environment may require that new signal handlers aren't registered due
3468 /// to the global nature of signal handlers. This option exists to disable
3469 /// the signal handler registration when required for these scenarios.
3470 ///
3471 /// When signals-based trap handlers are disabled, then Wasmtime and its
3472 /// generated code will *never* rely on segfaults or other
3473 /// signals. Generated code will be slower because bounds must be explicitly
3474 /// checked along with other conditions like division by zero.
3475 ///
3476 /// The following additional factors can also affect Wasmtime's ability to
3477 /// elide explicit bounds checks and leverage signals-based traps:
3478 ///
3479 /// * The [`Config::memory_reservation`] and [`Config::memory_guard_size`]
3480 /// settings
3481 /// * The index type of the linear memory (e.g. 32-bit or 64-bit)
3482 /// * The page size of the linear memory
3483 ///
3484 /// When this option is disabled, the
3485 /// `enable_heap_access_spectre_mitigation` and
3486 /// `enable_table_access_spectre_mitigation` Cranelift settings must also be
3487 /// disabled. This means that generated code must have spectre mitigations
3488 /// disabled. This is because spectre mitigations rely on faults from
3489 /// loading from the null address to implement bounds checks.
3490 ///
3491 /// This option defaults to `true`: signals-based trap handlers are enabled
3492 /// by default.
3493 ///
3494 /// > **Note:** Disabling this option is not compatible with the Winch
3495 /// > compiler.
3496 pub fn signals_based_traps(&mut self, enable: bool) -> &mut Self {
3497 self.tunables.signals_based_traps = Some(enable);
3498 self
3499 }
3500
3501 /// Enable/disable GC support in Wasmtime entirely.
3502 ///
3503 /// This flag can be used to gate whether GC infrastructure is enabled or
3504 /// initialized in Wasmtime at all. Wasmtime's GC implementation is required
3505 /// for the [`Self::wasm_gc`] proposal, [`Self::wasm_function_references`],
3506 /// and [`Self::wasm_exceptions`] at this time. None of those proposal can
3507 /// be enabled without also having this option enabled.
3508 ///
3509 /// This option defaults to whether the crate `gc` feature is enabled or
3510 /// not, except when using [`Strategy::Winch`] where it defaults to
3511 /// `false`.
3512 pub fn gc_support(&mut self, enable: bool) -> &mut Self {
3513 self.wasm_features(WasmFeatures::GC_TYPES, enable)
3514 }
3515
3516 /// Explicitly indicate or not whether the host is using a hardware float
3517 /// ABI on x86 targets.
3518 ///
3519 /// This configuration option is only applicable on the
3520 /// `x86_64-unknown-none` Rust target and has no effect on other host
3521 /// targets. The `x86_64-unknown-none` Rust target does not support hardware
3522 /// floats by default and uses a "soft float" implementation and ABI. This
3523 /// means that `f32`, for example, is passed in a general-purpose register
3524 /// between functions instead of a floating-point register. This does not
3525 /// match Cranelift's ABI for `f32` where it's passed in floating-point
3526 /// registers. Cranelift does not have support for a "soft float"
3527 /// implementation where all floating-point operations are lowered to
3528 /// libcalls.
3529 ///
3530 /// This means that for the `x86_64-unknown-none` target the ABI between
3531 /// Wasmtime's libcalls and the host is incompatible when floats are used.
3532 /// This further means that, by default, Wasmtime is unable to load native
3533 /// code when compiled to the `x86_64-unknown-none` target. The purpose of
3534 /// this option is to explicitly allow loading code and bypass this check.
3535 ///
3536 /// Setting this configuration option to `true` indicates that either:
3537 /// (a) the Rust target is compiled with the hard-float ABI manually via
3538 /// `-Zbuild-std` and a custom target JSON configuration, or (b) sufficient
3539 /// x86 features have been enabled in the compiler such that float libcalls
3540 /// will not be used in Wasmtime. For (a) there is no way in Rust at this
3541 /// time to detect whether a hard-float or soft-float ABI is in use on
3542 /// stable Rust, so this manual opt-in is required. For (b) the only
3543 /// instance where Wasmtime passes a floating-point value in a register
3544 /// between the host and compiled wasm code is with libcalls.
3545 ///
3546 /// Float-based libcalls are only used when the compilation target for a
3547 /// wasm module has insufficient target features enabled for native
3548 /// support. For example SSE4.1 is required for the `f32.ceil` WebAssembly
3549 /// instruction to be compiled to a native instruction. If SSE4.1 is not
3550 /// enabled then `f32.ceil` is translated to a "libcall" which is
3551 /// implemented on the host. Float-based libcalls can be avoided with
3552 /// sufficient target features enabled, for example:
3553 ///
3554 /// * `self.cranelift_flag_enable("has_sse3")`
3555 /// * `self.cranelift_flag_enable("has_ssse3")`
3556 /// * `self.cranelift_flag_enable("has_sse41")`
3557 /// * `self.cranelift_flag_enable("has_sse42")`
3558 /// * `self.cranelift_flag_enable("has_fma")`
3559 ///
3560 /// Note that when these features are enabled Wasmtime will perform a
3561 /// runtime check to determine that the host actually has the feature
3562 /// present.
3563 ///
3564 /// For some more discussion see [#11506].
3565 ///
3566 /// [#11506]: https://github.com/bytecodealliance/wasmtime/issues/11506
3567 ///
3568 /// # Safety
3569 ///
3570 /// This method is not safe because it cannot be detected in Rust right now
3571 /// whether the host is compiled with a soft or hard float ABI. Additionally
3572 /// if the host is compiled with a soft float ABI disabling this check does
3573 /// not ensure that the wasm module in question has zero usage of floats
3574 /// in the boundary to the host.
3575 ///
3576 /// Safely using this method requires one of:
3577 ///
3578 /// * The host target is compiled to use hardware floats.
3579 /// * Wasm modules loaded are compiled with enough x86 Cranelift features
3580 /// enabled to avoid float-related hostcalls.
3581 pub unsafe fn x86_float_abi_ok(&mut self, enable: bool) -> &mut Self {
3582 self.x86_float_abi_ok = Some(enable);
3583 self
3584 }
3585
3586 /// Enable or disable the ability to create a
3587 /// [`SharedMemory`](crate::SharedMemory).
3588 ///
3589 /// The WebAssembly threads proposal, configured by [`Config::wasm_threads`]
3590 /// is on-by-default but there are enough deficiencies in Wasmtime's
3591 /// implementation and API integration that creation of a shared memory is
3592 /// disabled by default. This configuration knob can be used to enable this.
3593 ///
3594 /// When enabling this method be aware that wasm threads are, at this time,
3595 /// a [tier 2
3596 /// feature](https://docs.wasmtime.dev/stability-tiers.html#tier-2) in
3597 /// Wasmtime meaning that it will not receive security updates or fixes to
3598 /// historical releases. Additionally security CVEs will not be issued for
3599 /// bugs in the implementation.
3600 ///
3601 /// This option is `false` by default.
3602 pub fn shared_memory(&mut self, enable: bool) -> &mut Self {
3603 self.shared_memory = enable;
3604 self
3605 }
3606
3607 /// Specifies whether support for concurrent execution of WebAssembly is
3608 /// supported within this store.
3609 ///
3610 /// This configuration option affects whether runtime data structures are
3611 /// initialized within a `Store` on creation to support concurrent execution
3612 /// of WebAssembly guests. This is primarily applicable to the
3613 /// [`Config::wasm_component_model_async`] configuration which is the first
3614 /// time Wasmtime has supported concurrent execution of guests. This
3615 /// configuration option, for example, enables usage of
3616 /// [`Store::run_concurrent`], [`Func::call_concurrent`], [`StreamReader`],
3617 /// etc.
3618 ///
3619 /// This configuration option can be manually disabled to avoid initializing
3620 /// data structures in the [`Store`] related to concurrent execution. When
3621 /// this option is disabled then APIs related to concurrency will all fail
3622 /// with a panic. For example [`Store::run_concurrent`] will panic, creating
3623 /// a [`StreamReader`] will panic, etc.
3624 ///
3625 /// The value of this option additionally affects whether a [`Config`] is
3626 /// valid and the default set of enabled WebAssembly features. If this
3627 /// option is disabled then component-model features related to concurrency
3628 /// will all be disabled. If this option is enabled, then the options will
3629 /// retain their normal defaults. It is not valid to create a [`Config`]
3630 /// with component-model-async explicitly enabled and this option explicitly
3631 /// disabled, however.
3632 ///
3633 /// This option defaults to `true`.
3634 ///
3635 /// [`Store`]: crate::Store
3636 /// [`Store::run_concurrent`]: crate::Store::run_concurrent
3637 /// [`Func::call_concurrent`]: crate::component::Func::call_concurrent
3638 /// [`StreamReader`]: crate::component::StreamReader
3639 pub fn concurrency_support(&mut self, enable: bool) -> &mut Self {
3640 self.tunables.concurrency_support = Some(enable);
3641 self
3642 }
3643
3644 /// Configures whether compiled code is compatible with a Wasmtime runtime
3645 /// built with AddressSanitizer (ASan) enabled.
3646 ///
3647 /// Some code Wasmtime generates must cooperate with ASan's bookkeeping
3648 /// when it runs inside an ASan-instrumented host. For example,
3649 /// stack-switching instructions must tell ASan about every switch between
3650 /// stacks. When this option is enabled the generated code includes those
3651 /// hooks. A runtime built without ASan treats them as no-ops.
3652 ///
3653 /// This option is part of a compiled artifact's compatibility key.
3654 /// Artifacts produced by [`Module::serialize`] or
3655 /// [`Component::serialize`] can only be deserialized by an [`Engine`]
3656 /// with the same setting. Code compiled without this option must not run
3657 /// in an ASan-enabled runtime.
3658 ///
3659 /// This option is useful when compiling code outside of ASan, for
3660 /// example with `Engine::precompile_module`, that will later run in a
3661 /// Wasmtime built with `-Zsanitizer=address`.
3662 ///
3663 /// This option defaults to `true` if Wasmtime itself was built with ASan
3664 /// and `false` otherwise.
3665 ///
3666 /// [`Engine`]: crate::Engine
3667 /// [`Module::serialize`]: crate::Module::serialize
3668 /// [`Component::serialize`]: crate::component::Component::serialize
3669 pub fn asan_compatible_code(&mut self, enable: bool) -> &mut Self {
3670 self.tunables.asan_stack_switching = Some(enable);
3671 self
3672 }
3673
3674 /// Validate if the current configuration has conflicting overrides that prevent
3675 /// execution determinism. Returns an error if a conflict exists.
3676 ///
3677 /// NaN canonicalization is a compiler setting, so `build_compiler`
3678 /// enforces it instead.
3679 #[inline]
3680 pub(crate) fn validate_rr_determinism_conflicts(&self) -> Result<()> {
3681 if let Some(v) = self.tunables.relaxed_simd_deterministic {
3682 if v == false {
3683 bail!("Relaxed deterministic SIMD cannot be disabled when determinism is enforced");
3684 }
3685 }
3686 Ok(())
3687 }
3688
3689 /// Enables recording (`Store::new_recording`) or replay, or with `None`
3690 /// (the default) neither.
3691 ///
3692 /// Compiled artifacts are specific to this setting: for example, a module
3693 /// that was compiled for recording cannot be loaded for replay.
3694 ///
3695 /// This feature is experimental, and requires the `rr` Cargo feature.
3696 /// Unless explicitly configured otherwise,
3697 /// this enables NaN canonicalization and deterministic relaxed SIMD;
3698 /// explicitly disabling either makes engine creation fail.
3699 #[inline]
3700 pub fn rr(&mut self, cfg: Option<RrConfig>) -> &mut Self {
3701 self.tunables.rr = Some(cfg);
3702 self
3703 }
3704
3705 /// Whether or not trap metadata is generated in compiled wasms for internal
3706 /// asserts in the compiled code itself.
3707 ///
3708 /// Wasmtime inserts metadata within compiled artifacts which contain a
3709 /// table of known trap codes for all instructions. If a trap via a signal
3710 /// happens, and it's not listed in these tables, then that's considered a
3711 /// fatal bug that crashes the process. This option controls whether trap
3712 /// codes are inserted into metadata for internal asserts as part of
3713 /// Wasmtime's translation process. These internal asserts should never be
3714 /// triggered, but if they are then the process dies with a signal.
3715 ///
3716 /// Inserting trap metadata into compiled artifacts can take extra space in
3717 /// the final artifact. The trap tables for the artifact will be larger as
3718 /// they contain more trap codes to contain.
3719 ///
3720 /// This is intended as a debugging option and is set to `false` by
3721 /// default.
3722 pub fn metadata_for_internal_asserts(&mut self, enable: bool) -> &mut Self {
3723 self.tunables.metadata_for_internal_asserts = Some(enable);
3724 self
3725 }
3726
3727 /// Whether or not trap metadata is generated in compiled wasms for
3728 /// detection of corruption in the GC heap.
3729 ///
3730 /// For more information about what metadata is in this scenario, see
3731 /// [`Config::metadata_for_internal_asserts`]. Note, though, that this
3732 /// option is enabled by default unlike internal asserts. This is intended
3733 /// as a defense-in-depth option for generated code in the face of GC heap
3734 /// corruption. If the GC heap is corrupted and is detected then the
3735 /// trapping instruction will be gracefully handled and delivered to the
3736 /// embedder. Otherwise if this option were set to `false` then the process
3737 /// would be aborted due to a signal.
3738 pub fn metadata_for_gc_heap_corruption(&mut self, enable: bool) -> &mut Self {
3739 self.tunables.metadata_for_gc_heap_corruption = Some(enable);
3740 self
3741 }
3742}
3743
3744impl Default for Config {
3745 fn default() -> Config {
3746 Config::new()
3747 }
3748}
3749
3750impl fmt::Debug for Config {
3751 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3752 let mut f = f.debug_struct("Config");
3753
3754 // Not every flag in WasmFeatures can be enabled as part of creating
3755 // a Config. This impl gives a complete picture of all WasmFeatures
3756 // enabled, and doesn't require maintenance by hand (which has become out
3757 // of date in the past), at the cost of possible confusion for why
3758 // a flag in this set doesn't have a Config setter.
3759 let features = self.features();
3760 for flag in WasmFeatures::FLAGS.iter() {
3761 f.field(
3762 &format!("wasm_{}", flag.name().to_lowercase()),
3763 &features.contains(*flag.value()),
3764 );
3765 }
3766
3767 f.field("parallel_compilation", &self.parallel_compilation);
3768 #[cfg(any(feature = "cranelift", feature = "winch"))]
3769 {
3770 f.field("compiler_config", &self.compiler_config);
3771 }
3772
3773 self.tunables.format(&mut f);
3774 f.finish()
3775 }
3776}
3777
3778/// Possible Compilation strategies for a wasm module.
3779///
3780/// This is used as an argument to the [`Config::strategy`] method.
3781#[non_exhaustive]
3782#[derive(PartialEq, Eq, Clone, Debug, Copy)]
3783pub enum Strategy {
3784 /// An indicator that the compilation strategy should be automatically
3785 /// selected.
3786 ///
3787 /// This is generally what you want for most projects and indicates that the
3788 /// `wasmtime` crate itself should make the decision about what the best
3789 /// code generator for a wasm module is.
3790 ///
3791 /// Currently this always defaults to Cranelift, but the default value may
3792 /// change over time.
3793 Auto,
3794
3795 /// Currently the default backend, Cranelift aims to be a reasonably fast
3796 /// code generator which generates high quality machine code.
3797 Cranelift,
3798
3799 /// A low-latency baseline compiler for WebAssembly.
3800 /// For more details regarding ISA support and Wasm proposals support
3801 /// see <https://docs.wasmtime.dev/stability-tiers.html#current-tier-status>
3802 Winch,
3803}
3804
3805#[cfg(any(feature = "winch", feature = "cranelift"))]
3806impl Strategy {
3807 fn not_auto(&self) -> Option<Strategy> {
3808 match self {
3809 Strategy::Auto => {
3810 if cfg!(feature = "cranelift") {
3811 Some(Strategy::Cranelift)
3812 } else if cfg!(feature = "winch") {
3813 Some(Strategy::Winch)
3814 } else {
3815 None
3816 }
3817 }
3818 other => Some(*other),
3819 }
3820 }
3821}
3822
3823/// Possible garbage collector implementations for Wasm.
3824///
3825/// This is used as an argument to the [`Config::collector`] method.
3826///
3827/// The properties of Wasmtime's available collectors are summarized in the
3828/// following table:
3829///
3830/// | Collector | Collects Garbage[^1] | Latency[^2] | Throughput[^3] | Allocation Speed[^4] | Heap Utilization[^5] |
3831/// |-----------------------------|-----------------------|-------------|----------------|----------------------|----------------------|
3832/// | `Copying` | Yes, including cycles | 🙁 | 🙂 | 🙂 | 🙁 |
3833/// | `DeferredReferenceCounting` | Yes, but not cycles | 🙂 | 🙁 | 😐 | 😐 |
3834/// | `Null` | No | 🙂 | 🙂 | 🙂 | 🙂 |
3835///
3836/// [^1]: Whether or not the collector is capable of collecting garbage and cyclic garbage.
3837///
3838/// [^2]: How long the Wasm program is paused during garbage
3839/// collections. Shorter is better. In general, better latency implies
3840/// worse throughput and vice versa.
3841///
3842/// [^3]: How fast the Wasm program runs when using this collector. Roughly
3843/// equivalent to the number of Wasm instructions executed per
3844/// second. Faster is better. In general, better throughput implies worse
3845/// latency and vice versa.
3846///
3847/// [^4]: How fast can individual objects be allocated?
3848///
3849/// [^5]: How many objects can the collector fit into N bytes of memory? That
3850/// is, how much space for bookkeeping and metadata does this collector
3851/// require? Less space taken up by metadata means more space for
3852/// additional objects. Reference counts are larger than mark bits and
3853/// free lists are larger than bump pointers, for example.
3854#[non_exhaustive]
3855#[derive(PartialEq, Eq, Clone, Debug, Copy)]
3856pub enum Collector {
3857 /// An indicator that the garbage collector should be automatically
3858 /// selected.
3859 ///
3860 /// This is generally what you want for most projects and indicates that the
3861 /// `wasmtime` crate itself should make the decision about what the best
3862 /// collector to use is.
3863 ///
3864 /// Currently this always defaults to the copying collector, but the default
3865 /// value may change over time.
3866 Auto,
3867
3868 /// The deferred reference-counting collector.
3869 ///
3870 /// A reference-counting collector, generally trading improved latency for
3871 /// worsened throughput. However, to avoid the largest overheads of
3872 /// reference counting, it avoids manipulating reference counts for Wasm
3873 /// objects on the stack. Instead, it will hold a reference count for an
3874 /// over-approximation of all objects that are currently on the stack, trace
3875 /// the stack during collection to find the precise set of on-stack roots,
3876 /// and decrement the reference count of any object that was in the
3877 /// over-approximation but not the precise set. This improves throughput,
3878 /// compared to "pure" reference counting, by performing many fewer
3879 /// refcount-increment and -decrement operations. The cost is the increased
3880 /// latency associated with tracing the stack.
3881 ///
3882 /// This collector cannot currently collect cycles; they will leak until the
3883 /// GC heap's store is dropped.
3884 DeferredReferenceCounting,
3885
3886 /// The null collector.
3887 ///
3888 /// This collector does not actually collect any garbage. It simply
3889 /// allocates objects until it runs out of memory, at which point further
3890 /// objects allocation attempts will trap.
3891 ///
3892 /// This collector is useful for incredibly short-running Wasm instances
3893 /// where additionally you would rather halt an over-allocating Wasm program
3894 /// than spend time collecting its garbage to allow it to keep running. It
3895 /// is also useful for measuring the overheads associated with other
3896 /// collectors, as this collector imposes as close to zero throughput and
3897 /// latency overhead as possible.
3898 Null,
3899
3900 /// The copying collector.
3901 ///
3902 /// A tracing collector that splits the GC heap in half, bump-allocates
3903 /// objects in one half until it fills up, and then does a GC and copies
3904 /// live objects into the other half, and repeats the process. It has fast
3905 /// allocation, collects cyclic garbage, and good collection throughput,
3906 /// however it suffers from poor latency due to its stop-the-world
3907 /// collections and poor heap utilization due to only using half the GC
3908 /// heap's full capacity at any given time.
3909 ///
3910 /// Note that this collector is still under construction and is not yet
3911 /// functional.
3912 Copying,
3913}
3914
3915impl Default for Collector {
3916 fn default() -> Collector {
3917 Collector::Auto
3918 }
3919}
3920
3921#[cfg(feature = "gc")]
3922impl Collector {
3923 fn not_auto(&self) -> Option<Collector> {
3924 match self {
3925 Collector::Auto => {
3926 if cfg!(feature = "gc-copying") {
3927 Some(Collector::Copying)
3928 } else if cfg!(feature = "gc-drc") {
3929 Some(Collector::DeferredReferenceCounting)
3930 } else if cfg!(feature = "gc-null") {
3931 Some(Collector::Null)
3932 } else {
3933 None
3934 }
3935 }
3936 other => Some(*other),
3937 }
3938 }
3939
3940 fn try_not_auto(&self) -> Result<Self> {
3941 match self.not_auto() {
3942 #[cfg(feature = "gc-drc")]
3943 Some(c @ Collector::DeferredReferenceCounting) => Ok(c),
3944 #[cfg(not(feature = "gc-drc"))]
3945 Some(Collector::DeferredReferenceCounting) => bail!(
3946 "cannot create an engine using the deferred reference-counting \
3947 collector because the `gc-drc` feature was not enabled at \
3948 compile time",
3949 ),
3950
3951 #[cfg(feature = "gc-null")]
3952 Some(c @ Collector::Null) => Ok(c),
3953 #[cfg(not(feature = "gc-null"))]
3954 Some(Collector::Null) => bail!(
3955 "cannot create an engine using the null collector because \
3956 the `gc-null` feature was not enabled at compile time",
3957 ),
3958
3959 #[cfg(feature = "gc-copying")]
3960 Some(c @ Collector::Copying) => Ok(c),
3961 #[cfg(not(feature = "gc-copying"))]
3962 Some(Collector::Copying) => bail!(
3963 "cannot create an engine using the copying collector because \
3964 the `gc-copying` feature was not enabled at compile time",
3965 ),
3966
3967 Some(Collector::Auto) => unreachable!(),
3968
3969 None => bail!(
3970 "cannot create an engine with GC support when none of the \
3971 collectors are available; enable one of the following \
3972 features: `gc-drc`, `gc-null`, `gc-copying`",
3973 ),
3974 }
3975 }
3976}
3977
3978/// Possible optimization levels for the Cranelift codegen backend.
3979#[non_exhaustive]
3980#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3981pub enum OptLevel {
3982 /// No optimizations performed, minimizes compilation time by disabling most
3983 /// optimizations.
3984 None,
3985 /// Generates the fastest possible code, but may take longer.
3986 Speed,
3987 /// Similar to `speed`, but also performs transformations aimed at reducing
3988 /// code size.
3989 SpeedAndSize,
3990}
3991
3992/// Possible register allocator algorithms for the Cranelift codegen backend.
3993#[non_exhaustive]
3994#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3995pub enum RegallocAlgorithm {
3996 /// Generates the fastest possible code, but may take longer.
3997 ///
3998 /// This algorithm performs "backtracking", which means that it may
3999 /// undo its earlier work and retry as it discovers conflicts. This
4000 /// results in better register utilization, producing fewer spills
4001 /// and moves, but can cause super-linear compile runtime.
4002 Backtracking,
4003 /// Generates acceptable code very quickly.
4004 ///
4005 /// This algorithm performs a single pass through the code,
4006 /// guaranteed to work in linear time. (Note that the rest of
4007 /// Cranelift is not necessarily guaranteed to run in linear time,
4008 /// however.) It cannot undo earlier decisions, however, and it
4009 /// cannot foresee constraints or issues that may occur further
4010 /// ahead in the code, so the code may have more spills and moves as
4011 /// a result.
4012 ///
4013 /// > **Note**: This algorithm is not yet production-ready and has
4014 /// > historically had known problems. It is not recommended to enable this
4015 /// > algorithm for security-sensitive applications and the Wasmtime project
4016 /// > does not consider this configuration option for issuing security
4017 /// > advisories at this time.
4018 SinglePass,
4019}
4020
4021/// Select which profiling technique to support.
4022#[derive(Debug, Clone, Copy, PartialEq)]
4023pub enum ProfilingStrategy {
4024 /// No profiler support.
4025 None,
4026
4027 /// Collect function name information as the "perf map" file format, used with `perf` on Linux.
4028 PerfMap,
4029
4030 /// Collect profiling info for "jitdump" file format, used with `perf` on
4031 /// Linux.
4032 JitDump,
4033
4034 /// Collect profiling info using the "ittapi", used with `VTune` on Linux.
4035 VTune,
4036
4037 /// Support for profiling Pulley, Wasmtime's interpreter. Note that enabling
4038 /// this at runtime requires enabling the `profile-pulley` Cargo feature at
4039 /// compile time.
4040 Pulley,
4041}
4042
4043/// Select how wasm backtrace detailed information is handled.
4044#[derive(Debug, Clone, Copy)]
4045pub enum WasmBacktraceDetails {
4046 /// Support is unconditionally enabled and wasmtime will parse and read
4047 /// debug information.
4048 Enable,
4049
4050 /// Support is disabled, and wasmtime will not parse debug information for
4051 /// backtrace details.
4052 Disable,
4053
4054 /// Support for backtrace details is conditional on the
4055 /// `WASMTIME_BACKTRACE_DETAILS` environment variable.
4056 Environment,
4057}
4058
4059/// Describe the tri-state configuration of keys such as MPK or PAGEMAP_SCAN.
4060#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
4061pub enum Enabled {
4062 /// Enable this feature if it's detected on the host system, otherwise leave
4063 /// it disabled.
4064 Auto,
4065 /// Enable this feature and fail configuration if the feature is not
4066 /// detected on the host system.
4067 Yes,
4068 /// Do not enable this feature, even if the host system supports it.
4069 No,
4070}
4071
4072/// Configuration options used with [`InstanceAllocationStrategy::Pooling`] to
4073/// change the behavior of the pooling instance allocator.
4074///
4075/// This structure has a builder-style API in the same manner as [`Config`] and
4076/// is configured with [`Config::allocation_strategy`].
4077///
4078/// Note that usage of the pooling allocator does not affect compiled
4079/// WebAssembly code. Compiled `*.cwasm` files, for example, are usable both
4080/// with and without the pooling allocator.
4081///
4082/// ## Advantages of Pooled Allocation
4083///
4084/// The main benefit of the pooling allocator is to make WebAssembly
4085/// instantiation both faster and more scalable in terms of parallelism.
4086/// Allocation is faster because virtual memory is already configured and ready
4087/// to go within the pool, there's no need to [`mmap`] (for example on Unix) a
4088/// new region and configure it with guard pages. By avoiding [`mmap`] this
4089/// avoids whole-process virtual memory locks which can improve scalability and
4090/// performance through avoiding this.
4091///
4092/// Additionally with pooled allocation it's possible to create "affine slots"
4093/// to a particular WebAssembly module or component over time. For example if
4094/// the same module is multiple times over time the pooling allocator will, by
4095/// default, attempt to reuse the same slot. This mean that the slot has been
4096/// pre-configured and can retain virtual memory mappings for a copy-on-write
4097/// image, for example (see [`Config::memory_init_cow`] for more information.
4098/// This means that in a steady state instance deallocation is a single
4099/// [`madvise`] to reset linear memory to its original contents followed by a
4100/// single (optional) [`mprotect`] during the next instantiation to shrink
4101/// memory back to its original size. Compared to non-pooled allocation this
4102/// avoids the need to [`mmap`] a new region of memory, [`munmap`] it, and
4103/// [`mprotect`] regions too.
4104///
4105/// Another benefit of pooled allocation is that it's possible to configure
4106/// things such that no virtual memory management is required at all in a steady
4107/// state. For example a pooling allocator can be configured with:
4108///
4109/// * [`Config::memory_init_cow`] disabled
4110/// * [`Config::memory_guard_size`] disabled
4111/// * [`Config::memory_reservation`] shrunk to minimal size
4112/// * [`PoolingAllocationConfig::table_keep_resident`] sufficiently large
4113/// * [`PoolingAllocationConfig::linear_memory_keep_resident`] sufficiently large
4114///
4115/// With all these options in place no virtual memory tricks are used at all and
4116/// everything is manually managed by Wasmtime (for example resetting memory is
4117/// a `memset(0)`). This is not as fast in a single-threaded scenario but can
4118/// provide benefits in high-parallelism situations as no virtual memory locks
4119/// or IPIs need happen.
4120///
4121/// ## Disadvantages of Pooled Allocation
4122///
4123/// Despite the above advantages to instantiation performance the pooling
4124/// allocator is not enabled by default in Wasmtime. One reason is that the
4125/// performance advantages are not necessarily portable, for example while the
4126/// pooling allocator works on Windows it has not been tuned for performance on
4127/// Windows in the same way it has on Linux.
4128///
4129/// Additionally the main cost of the pooling allocator is that it requires a
4130/// very large reservation of virtual memory (on the order of most of the
4131/// addressable virtual address space). WebAssembly 32-bit linear memories in
4132/// Wasmtime are, by default 4G address space reservations with a small guard
4133/// region both before and after the linear memory. Memories in the pooling
4134/// allocator are contiguous which means that we only need a guard after linear
4135/// memory because the previous linear memory's slot post-guard is our own
4136/// pre-guard. This means that, by default, the pooling allocator uses roughly
4137/// 4G of virtual memory per WebAssembly linear memory slot. 4G of virtual
4138/// memory is 32 bits of a 64-bit address. Many 64-bit systems can only
4139/// actually use 48-bit addresses by default (although this can be extended on
4140/// architectures nowadays too), and of those 48 bits one of them is reserved
4141/// to indicate kernel-vs-userspace. This leaves 47-32=15 bits left,
4142/// meaning you can only have at most 32k slots of linear memories on many
4143/// systems by default. This is a relatively small number and shows how the
4144/// pooling allocator can quickly exhaust all of virtual memory.
4145///
4146/// Another disadvantage of the pooling allocator is that it may keep memory
4147/// alive when nothing is using it. A previously used slot for an instance might
4148/// have paged-in memory that will not get paged out until the
4149/// [`Engine`] owning the pooling allocator is dropped. While
4150/// suitable for some applications this behavior may not be suitable for all
4151/// applications.
4152///
4153/// Finally the last disadvantage of the pooling allocator is that the
4154/// configuration values for the maximum number of instances, memories, tables,
4155/// etc, must all be fixed up-front. There's not always a clear answer as to
4156/// what these values should be so not all applications may be able to work
4157/// with this constraint.
4158///
4159/// [`madvise`]: https://man7.org/linux/man-pages/man2/madvise.2.html
4160/// [`mprotect`]: https://man7.org/linux/man-pages/man2/mprotect.2.html
4161/// [`mmap`]: https://man7.org/linux/man-pages/man2/mmap.2.html
4162/// [`munmap`]: https://man7.org/linux/man-pages/man2/munmap.2.html
4163#[derive(Debug, Clone)]
4164pub struct PoolingAllocationConfig {
4165 /// See `PoolingAllocatorConfig::max_unused_warm_slots` in `wasmtime`
4166 pub(crate) max_unused_warm_slots: u32,
4167 /// The target number of decommits to do per batch. This is not precise, as
4168 /// we can queue up decommits at times when we aren't prepared to
4169 /// immediately flush them, and so we may go over this target size
4170 /// occasionally.
4171 pub(crate) decommit_batch_size: usize,
4172 /// The size, in bytes, of async stacks to allocate (not including the guard
4173 /// page).
4174 #[cfg_attr(
4175 not(all(feature = "async", feature = "pooling-allocator")),
4176 expect(dead_code, reason = "easier to cfg")
4177 )]
4178 pub(crate) stack_size: usize,
4179 /// The limits to apply to instances allocated within this allocator.
4180 pub(crate) limits: InstanceLimits,
4181 /// Whether or not async stacks are zeroed after use.
4182 #[cfg_attr(
4183 not(all(feature = "async", feature = "pooling-allocator")),
4184 expect(dead_code, reason = "easier to cfg")
4185 )]
4186 pub(crate) async_stack_zeroing: bool,
4187 /// If async stack zeroing is enabled and the host platform is Linux this is
4188 /// how much memory to zero out with `memset`.
4189 ///
4190 /// The rest of memory will be zeroed out with `madvise`.
4191 pub(crate) async_stack_keep_resident: usize,
4192 /// How much linear memory, in bytes, to keep resident after resetting for
4193 /// use with the next instance. This much memory will be `memset` to zero
4194 /// when a linear memory is deallocated.
4195 ///
4196 /// Memory exceeding this amount in the wasm linear memory will be released
4197 /// with `madvise` back to the kernel.
4198 ///
4199 /// Only applicable on Linux.
4200 pub(crate) linear_memory_keep_resident: usize,
4201 /// Same as `linear_memory_keep_resident` but for tables.
4202 pub(crate) table_keep_resident: usize,
4203 /// Whether to enable memory protection keys.
4204 pub(crate) memory_protection_keys: Enabled,
4205 /// How many memory protection keys to allocate.
4206 pub(crate) max_memory_protection_keys: usize,
4207 /// Whether to enable PAGEMAP_SCAN on Linux.
4208 pub(crate) pagemap_scan: Enabled,
4209}
4210
4211impl Default for PoolingAllocationConfig {
4212 fn default() -> Self {
4213 Self {
4214 max_unused_warm_slots: 100,
4215 decommit_batch_size: 1,
4216 stack_size: 2 << 20,
4217 limits: InstanceLimits::default(),
4218 async_stack_zeroing: false,
4219 async_stack_keep_resident: 0,
4220 linear_memory_keep_resident: 0,
4221 table_keep_resident: 0,
4222 memory_protection_keys: Enabled::No,
4223 max_memory_protection_keys: 16,
4224 pagemap_scan: Enabled::No,
4225 }
4226 }
4227}
4228
4229/// Instance-related limit configuration for pooling.
4230///
4231/// More docs on this can be found at `wasmtime::PoolingAllocationConfig`.
4232#[derive(Debug, Copy, Clone)]
4233pub(crate) struct InstanceLimits {
4234 /// The maximum number of component instances that may be allocated
4235 /// concurrently.
4236 pub(crate) total_component_instances: u32,
4237
4238 /// The maximum size of a component's `VMComponentContext`, including
4239 /// the aggregate size of all its inner core modules' `VMContext` sizes.
4240 pub(crate) component_instance_size: usize,
4241
4242 /// The maximum number of core module instances that may be allocated
4243 /// concurrently.
4244 pub(crate) total_core_instances: u32,
4245
4246 /// The maximum number of core module instances that a single component may
4247 /// transitively contain.
4248 pub(crate) max_core_instances_per_component: u32,
4249
4250 /// The maximum number of Wasm linear memories that a component may
4251 /// transitively contain.
4252 pub(crate) max_memories_per_component: u32,
4253
4254 /// The maximum number of tables that a component may transitively contain.
4255 pub(crate) max_tables_per_component: u32,
4256
4257 /// The total number of linear memories in the pool, across all instances.
4258 pub(crate) total_memories: u32,
4259
4260 /// The total number of tables in the pool, across all instances.
4261 pub(crate) total_tables: u32,
4262
4263 /// The total number of async stacks in the pool, across all instances.
4264 pub(crate) total_stacks: u32,
4265
4266 /// Maximum size of a core instance's `VMContext`.
4267 pub(crate) core_instance_size: usize,
4268
4269 /// Maximum number of tables per instance.
4270 pub(crate) max_tables_per_module: u32,
4271
4272 /// Maximum number of word-size elements per table.
4273 ///
4274 /// Note that tables for element types such as continuations
4275 /// that use more than one word of storage may store fewer
4276 /// elements.
4277 pub(crate) table_elements: usize,
4278
4279 /// Maximum number of linear memories per instance.
4280 pub(crate) max_memories_per_module: u32,
4281
4282 /// Maximum byte size of a linear memory, must be smaller than
4283 /// `memory_reservation` in `Tunables`.
4284 pub(crate) max_memory_size: usize,
4285
4286 /// The total number of GC heaps in the pool, across all instances.
4287 pub(crate) total_gc_heaps: u32,
4288}
4289
4290impl Default for InstanceLimits {
4291 fn default() -> Self {
4292 let total = if cfg!(target_pointer_width = "32") {
4293 100
4294 } else {
4295 1000
4296 };
4297 // See doc comments for `wasmtime::PoolingAllocationConfig` for these
4298 // default values
4299 Self {
4300 total_component_instances: total,
4301 component_instance_size: 1 << 20, // 1 MiB
4302 total_core_instances: total,
4303 max_core_instances_per_component: u32::MAX,
4304 max_memories_per_component: u32::MAX,
4305 max_tables_per_component: u32::MAX,
4306 total_memories: total,
4307 total_tables: total,
4308 total_stacks: total,
4309 core_instance_size: 1 << 20, // 1 MiB
4310 max_tables_per_module: 1,
4311 // NB: in #8504 it was seen that a C# module in debug module can
4312 // have 10k+ elements.
4313 table_elements: 20_000,
4314 max_memories_per_module: 1,
4315 #[cfg(target_pointer_width = "64")]
4316 max_memory_size: 1 << 32, // 4G,
4317 #[cfg(target_pointer_width = "32")]
4318 max_memory_size: 10 << 20, // 10 MiB
4319 total_gc_heaps: total,
4320 }
4321 }
4322}
4323
4324impl PoolingAllocationConfig {
4325 /// Returns a new configuration builder with all default settings
4326 /// configured.
4327 pub fn new() -> PoolingAllocationConfig {
4328 PoolingAllocationConfig::default()
4329 }
4330
4331 /// Configures the maximum number of "unused warm slots" to retain in the
4332 /// pooling allocator.
4333 ///
4334 /// The pooling allocator operates over slots to allocate from, and each
4335 /// slot is considered "cold" if it's never been used before or "warm" if
4336 /// it's been used by some module in the past. Slots in the pooling
4337 /// allocator additionally track an "affinity" flag to a particular core
4338 /// wasm module. When a module is instantiated into a slot then the slot is
4339 /// considered affine to that module, even after the instance has been
4340 /// deallocated.
4341 ///
4342 /// When a new instance is created then a slot must be chosen, and the
4343 /// current algorithm for selecting a slot is:
4344 ///
4345 /// * If there are slots that are affine to the module being instantiated,
4346 /// then the most recently used slot is selected to be allocated from.
4347 /// This is done to improve reuse of resources such as memory mappings and
4348 /// additionally try to benefit from temporal locality for things like
4349 /// caches.
4350 ///
4351 /// * Otherwise if there are more than N affine slots to other modules, then
4352 /// one of those affine slots is chosen to be allocated. The slot chosen
4353 /// is picked on a least-recently-used basis.
4354 ///
4355 /// * Finally, if there are less than N affine slots to other modules, then
4356 /// the non-affine slots are allocated from.
4357 ///
4358 /// This setting, `max_unused_warm_slots`, is the value for N in the above
4359 /// algorithm. The purpose of this setting is to have a knob over the RSS
4360 /// impact of "unused slots" for a long-running wasm server.
4361 ///
4362 /// If this setting is set to 0, for example, then affine slots are
4363 /// aggressively reused on a least-recently-used basis. A "cold" slot is
4364 /// only used if there are no affine slots available to allocate from. This
4365 /// means that the set of slots used over the lifetime of a program is the
4366 /// same as the maximum concurrent number of wasm instances.
4367 ///
4368 /// If this setting is set to infinity, however, then cold slots are
4369 /// prioritized to be allocated from. This means that the set of slots used
4370 /// over the lifetime of a program will approach
4371 /// [`PoolingAllocationConfig::total_memories`], or the maximum number of
4372 /// slots in the pooling allocator.
4373 ///
4374 /// Wasmtime does not aggressively decommit all resources associated with a
4375 /// slot when the slot is not in use. For example the
4376 /// [`PoolingAllocationConfig::linear_memory_keep_resident`] option can be
4377 /// used to keep memory associated with a slot, even when it's not in use.
4378 /// This means that the total set of used slots in the pooling instance
4379 /// allocator can impact the overall RSS usage of a program.
4380 ///
4381 /// The default value for this option is `100`.
4382 pub fn max_unused_warm_slots(&mut self, max: u32) -> &mut Self {
4383 self.max_unused_warm_slots = max;
4384 self
4385 }
4386
4387 /// The target number of decommits to do per batch.
4388 ///
4389 /// This is not precise, as we can queue up decommits at times when we
4390 /// aren't prepared to immediately flush them, and so we may go over this
4391 /// target size occasionally.
4392 ///
4393 /// Note additionally that the queue of not-yet-decommitted entities is
4394 /// sharded to reduce lock contention: one shard per available CPU, capped
4395 /// at 16. Each shard batches up to this many decommits independently,
4396 /// meaning that up to `min(available_parallelism, 16) * (batch_size - 1)`
4397 /// decommits may be queued and not yet flushed at any given time.
4398 ///
4399 /// A batch size of one effectively disables batching.
4400 ///
4401 /// Defaults to `1`.
4402 pub fn decommit_batch_size(&mut self, batch_size: usize) -> &mut Self {
4403 self.decommit_batch_size = batch_size;
4404 self
4405 }
4406
4407 /// How much memory, in bytes, to keep resident for async stacks allocated
4408 /// with the pooling allocator.
4409 ///
4410 /// When [`Config::async_stack_zeroing`] is enabled then Wasmtime will reset
4411 /// the contents of async stacks back to zero upon deallocation. This option
4412 /// can be used to perform the zeroing operation with `memset` up to a
4413 /// certain threshold of bytes instead of using system calls to reset the
4414 /// stack to zero.
4415 ///
4416 /// Note that when using this option the memory with async stacks will
4417 /// never be decommitted.
4418 pub fn async_stack_keep_resident(&mut self, size: usize) -> &mut Self {
4419 self.async_stack_keep_resident = size;
4420 self
4421 }
4422
4423 /// How much memory, in bytes, to keep resident for each linear memory
4424 /// after deallocation.
4425 ///
4426 /// This option is only applicable on Linux and has no effect on other
4427 /// platforms.
4428 ///
4429 /// By default Wasmtime will use `madvise` to reset the entire contents of
4430 /// linear memory back to zero when a linear memory is deallocated. This
4431 /// option can be used to use `memset` instead to set memory back to zero
4432 /// which can, in some configurations, reduce the number of page faults
4433 /// taken when a slot is reused.
4434 pub fn linear_memory_keep_resident(&mut self, size: usize) -> &mut Self {
4435 self.linear_memory_keep_resident = size;
4436 self
4437 }
4438
4439 /// How much memory, in bytes, to keep resident for each table after
4440 /// deallocation.
4441 ///
4442 /// This option is only applicable on Linux and has no effect on other
4443 /// platforms.
4444 ///
4445 /// This option is the same as
4446 /// [`PoolingAllocationConfig::linear_memory_keep_resident`] except that it
4447 /// is applicable to tables instead.
4448 pub fn table_keep_resident(&mut self, size: usize) -> &mut Self {
4449 self.table_keep_resident = size;
4450 self
4451 }
4452
4453 /// The maximum number of concurrent component instances supported (default
4454 /// is `1000`).
4455 ///
4456 /// This provides an upper-bound on the total size of component
4457 /// metadata-related allocations, along with
4458 /// [`PoolingAllocationConfig::max_component_instance_size`]. The upper bound is
4459 ///
4460 /// ```text
4461 /// total_component_instances * max_component_instance_size
4462 /// ```
4463 ///
4464 /// where `max_component_instance_size` is rounded up to the size and alignment
4465 /// of the internal representation of the metadata.
4466 pub fn total_component_instances(&mut self, count: u32) -> &mut Self {
4467 self.limits.total_component_instances = count;
4468 self
4469 }
4470
4471 /// The maximum size, in bytes, allocated for a component instance's
4472 /// `VMComponentContext` metadata as well as the aggregate size of this
4473 /// component's core instances `VMContext` metadata.
4474 ///
4475 /// The [`wasmtime::component::Instance`][crate::component::Instance] type
4476 /// has a static size but its internal `VMComponentContext` is dynamically
4477 /// sized depending on the component being instantiated. This size limit
4478 /// loosely correlates to the size of the component, taking into account
4479 /// factors such as:
4480 ///
4481 /// * number of lifted and lowered functions,
4482 /// * number of memories
4483 /// * number of inner instances
4484 /// * number of resources
4485 ///
4486 /// If the allocated size per instance is too small then instantiation of a
4487 /// module will fail at runtime with an error indicating how many bytes were
4488 /// needed.
4489 ///
4490 /// In addition to the memory in the runtime for the component itself,
4491 /// components contain one or more core module instances. Each of these
4492 /// require some memory in the runtime as described in
4493 /// [`PoolingAllocationConfig::max_core_instance_size`]. The limit here
4494 /// applies against the sum of all of these individual allocations.
4495 ///
4496 /// The default value for this is 1MiB.
4497 ///
4498 /// This provides an upper-bound on the total size of all component's
4499 /// metadata-related allocations (for both the component and its embedded
4500 /// core module instances), along with
4501 /// [`PoolingAllocationConfig::total_component_instances`]. The upper bound is
4502 ///
4503 /// ```text
4504 /// total_component_instances * max_component_instance_size
4505 /// ```
4506 ///
4507 /// where `max_component_instance_size` is rounded up to the size and alignment
4508 /// of the internal representation of the metadata.
4509 pub fn max_component_instance_size(&mut self, size: usize) -> &mut Self {
4510 self.limits.component_instance_size = size;
4511 self
4512 }
4513
4514 /// The maximum number of core instances a single component may contain
4515 /// (default is unlimited).
4516 ///
4517 /// This method (along with
4518 /// [`PoolingAllocationConfig::max_memories_per_component`],
4519 /// [`PoolingAllocationConfig::max_tables_per_component`], and
4520 /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
4521 /// the amount of resources a single component allocation consumes.
4522 ///
4523 /// If a component will instantiate more core instances than `count`, then
4524 /// the component will fail to instantiate.
4525 pub fn max_core_instances_per_component(&mut self, count: u32) -> &mut Self {
4526 self.limits.max_core_instances_per_component = count;
4527 self
4528 }
4529
4530 /// The maximum number of Wasm linear memories that a single component may
4531 /// transitively contain (default is unlimited).
4532 ///
4533 /// This method (along with
4534 /// [`PoolingAllocationConfig::max_core_instances_per_component`],
4535 /// [`PoolingAllocationConfig::max_tables_per_component`], and
4536 /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
4537 /// the amount of resources a single component allocation consumes.
4538 ///
4539 /// If a component transitively contains more linear memories than `count`,
4540 /// then the component will fail to instantiate.
4541 pub fn max_memories_per_component(&mut self, count: u32) -> &mut Self {
4542 self.limits.max_memories_per_component = count;
4543 self
4544 }
4545
4546 /// The maximum number of tables that a single component may transitively
4547 /// contain (default is unlimited).
4548 ///
4549 /// This method (along with
4550 /// [`PoolingAllocationConfig::max_core_instances_per_component`],
4551 /// [`PoolingAllocationConfig::max_memories_per_component`],
4552 /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
4553 /// the amount of resources a single component allocation consumes.
4554 ///
4555 /// If a component will transitively contains more tables than `count`, then
4556 /// the component will fail to instantiate.
4557 pub fn max_tables_per_component(&mut self, count: u32) -> &mut Self {
4558 self.limits.max_tables_per_component = count;
4559 self
4560 }
4561
4562 /// The maximum number of concurrent Wasm linear memories supported (default
4563 /// is `1000`).
4564 ///
4565 /// This value has a direct impact on the amount of memory allocated by the pooling
4566 /// instance allocator.
4567 ///
4568 /// The pooling instance allocator allocates a memory pool, where each entry
4569 /// in the pool contains the reserved address space for each linear memory
4570 /// supported by an instance.
4571 ///
4572 /// The memory pool will reserve a large quantity of host process address
4573 /// space to elide the bounds checks required for correct WebAssembly memory
4574 /// semantics. Even with 64-bit address spaces, the address space is limited
4575 /// when dealing with a large number of linear memories.
4576 ///
4577 /// For example, on Linux x86_64, the userland address space limit is 128
4578 /// TiB. That might seem like a lot, but each linear memory will *reserve* 6
4579 /// GiB of space by default.
4580 pub fn total_memories(&mut self, count: u32) -> &mut Self {
4581 self.limits.total_memories = count;
4582 self
4583 }
4584
4585 /// The maximum number of concurrent tables supported (default is `1000`).
4586 ///
4587 /// This value has a direct impact on the amount of memory allocated by the
4588 /// pooling instance allocator.
4589 ///
4590 /// The pooling instance allocator allocates a table pool, where each entry
4591 /// in the pool contains the space needed for each WebAssembly table
4592 /// supported by an instance (see `table_elements` to control the size of
4593 /// each table).
4594 pub fn total_tables(&mut self, count: u32) -> &mut Self {
4595 self.limits.total_tables = count;
4596 self
4597 }
4598
4599 /// The maximum number of execution stacks allowed for asynchronous
4600 /// execution, when enabled (default is `1000`).
4601 ///
4602 /// This value has a direct impact on the amount of memory allocated by the
4603 /// pooling instance allocator.
4604 #[cfg(feature = "async")]
4605 pub fn total_stacks(&mut self, count: u32) -> &mut Self {
4606 self.limits.total_stacks = count;
4607 self
4608 }
4609
4610 /// The maximum number of concurrent core instances supported (default is
4611 /// `1000`).
4612 ///
4613 /// This provides an upper-bound on the total size of core instance
4614 /// metadata-related allocations, along with
4615 /// [`PoolingAllocationConfig::max_core_instance_size`]. The upper bound is
4616 ///
4617 /// ```text
4618 /// total_core_instances * max_core_instance_size
4619 /// ```
4620 ///
4621 /// where `max_core_instance_size` is rounded up to the size and alignment of
4622 /// the internal representation of the metadata.
4623 pub fn total_core_instances(&mut self, count: u32) -> &mut Self {
4624 self.limits.total_core_instances = count;
4625 self
4626 }
4627
4628 /// The maximum size, in bytes, allocated for a core instance's `VMContext`
4629 /// metadata.
4630 ///
4631 /// The [`Instance`][crate::Instance] type has a static size but its
4632 /// `VMContext` metadata is dynamically sized depending on the module being
4633 /// instantiated. This size limit loosely correlates to the size of the Wasm
4634 /// module, taking into account factors such as:
4635 ///
4636 /// * number of functions
4637 /// * number of globals
4638 /// * number of memories
4639 /// * number of tables
4640 /// * number of function types
4641 ///
4642 /// If the allocated size per instance is too small then instantiation of a
4643 /// module will fail at runtime with an error indicating how many bytes were
4644 /// needed.
4645 ///
4646 /// The default value for this is 1MiB.
4647 ///
4648 /// This provides an upper-bound on the total size of core instance
4649 /// metadata-related allocations, along with
4650 /// [`PoolingAllocationConfig::total_core_instances`]. The upper bound is
4651 ///
4652 /// ```text
4653 /// total_core_instances * max_core_instance_size
4654 /// ```
4655 ///
4656 /// where `max_core_instance_size` is rounded up to the size and alignment of
4657 /// the internal representation of the metadata.
4658 pub fn max_core_instance_size(&mut self, size: usize) -> &mut Self {
4659 self.limits.core_instance_size = size;
4660 self
4661 }
4662
4663 /// The maximum number of defined tables for a core module (default is `1`).
4664 ///
4665 /// This value controls the capacity of the `VMTableDefinition` table in
4666 /// each instance's `VMContext` structure.
4667 ///
4668 /// The allocated size of the table will be `tables *
4669 /// sizeof(VMTableDefinition)` for each instance regardless of how many
4670 /// tables are defined by an instance's module.
4671 pub fn max_tables_per_module(&mut self, tables: u32) -> &mut Self {
4672 self.limits.max_tables_per_module = tables;
4673 self
4674 }
4675
4676 /// The maximum table elements for any table defined in a module (default is
4677 /// `20000`).
4678 ///
4679 /// If a table's minimum element limit is greater than this value, the
4680 /// module will fail to instantiate.
4681 ///
4682 /// If a table's maximum element limit is unbounded or greater than this
4683 /// value, the maximum will be `table_elements` for the purpose of any
4684 /// `table.grow` instruction.
4685 ///
4686 /// This value is used to reserve the maximum space for each supported
4687 /// table; table elements are pointer-sized in the Wasmtime runtime.
4688 /// Therefore, the space reserved for each instance is `tables *
4689 /// table_elements * sizeof::<*const ()>`.
4690 pub fn table_elements(&mut self, elements: usize) -> &mut Self {
4691 self.limits.table_elements = elements;
4692 self
4693 }
4694
4695 /// The maximum number of defined linear memories for a module (default is
4696 /// `1`).
4697 ///
4698 /// This value controls the capacity of the `VMMemoryDefinition` table in
4699 /// each core instance's `VMContext` structure.
4700 ///
4701 /// The allocated size of the table will be `memories *
4702 /// sizeof(VMMemoryDefinition)` for each core instance regardless of how
4703 /// many memories are defined by the core instance's module.
4704 pub fn max_memories_per_module(&mut self, memories: u32) -> &mut Self {
4705 self.limits.max_memories_per_module = memories;
4706 self
4707 }
4708
4709 /// The maximum byte size that any WebAssembly linear memory may grow to.
4710 ///
4711 /// This option defaults to 4 GiB meaning that for 32-bit linear memories
4712 /// there is no restrictions. 64-bit linear memories will not be allowed to
4713 /// grow beyond 4 GiB by default.
4714 ///
4715 /// If a memory's minimum size is greater than this value, the module will
4716 /// fail to instantiate.
4717 ///
4718 /// If a memory's maximum size is unbounded or greater than this value, the
4719 /// maximum will be `max_memory_size` for the purpose of any `memory.grow`
4720 /// instruction.
4721 ///
4722 /// This value is used to control the maximum accessible space for each
4723 /// linear memory of a core instance. This can be thought of as a simple
4724 /// mechanism like [`Store::limiter`](crate::Store::limiter) to limit memory
4725 /// at runtime. This value can also affect striping/coloring behavior when
4726 /// used in conjunction with
4727 /// [`memory_protection_keys`](PoolingAllocationConfig::memory_protection_keys).
4728 ///
4729 /// The virtual memory reservation size of each linear memory is controlled
4730 /// by the [`Config::memory_reservation`] setting and this method's
4731 /// configuration cannot exceed [`Config::memory_reservation`].
4732 pub fn max_memory_size(&mut self, bytes: usize) -> &mut Self {
4733 self.limits.max_memory_size = bytes;
4734 self
4735 }
4736
4737 /// Configures whether memory protection keys (MPK) should be used for more
4738 /// efficient layout of pool-allocated memories.
4739 ///
4740 /// When using the pooling allocator (see [`Config::allocation_strategy`],
4741 /// [`InstanceAllocationStrategy::Pooling`]), memory protection keys can
4742 /// reduce the total amount of allocated virtual memory by eliminating guard
4743 /// regions between WebAssembly memories in the pool. It does so by
4744 /// "coloring" memory regions with different memory keys and setting which
4745 /// regions are accessible each time executions switches from host to guest
4746 /// (or vice versa).
4747 ///
4748 /// Leveraging MPK requires configuring a smaller-than-default
4749 /// [`max_memory_size`](PoolingAllocationConfig::max_memory_size) to enable
4750 /// this coloring/striping behavior. For example embeddings might want to
4751 /// reduce the default 4G allowance to 128M.
4752 ///
4753 /// MPK is only available on Linux (called `pku` there) and recent x86
4754 /// systems; we check for MPK support at runtime by examining the `CPUID`
4755 /// register. This configuration setting can be in three states:
4756 ///
4757 /// - `auto`: if MPK support is available the guard regions are removed; if
4758 /// not, the guard regions remain
4759 /// - `yes`: use MPK to eliminate guard regions; fail if MPK is not
4760 /// supported
4761 /// - `no`: never use MPK
4762 ///
4763 /// By default this value is `no`, but may become `auto` in future
4764 /// releases.
4765 ///
4766 /// __WARNING__: this configuration options is still experimental--use at
4767 /// your own risk! MPK uses kernel and CPU features to protect memory
4768 /// regions; you may observe segmentation faults if anything is
4769 /// misconfigured.
4770 #[cfg(feature = "memory-protection-keys")]
4771 pub fn memory_protection_keys(&mut self, enable: Enabled) -> &mut Self {
4772 self.memory_protection_keys = enable;
4773 self
4774 }
4775
4776 /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
4777 /// will use.
4778 ///
4779 /// This setting is only applicable when
4780 /// [`PoolingAllocationConfig::memory_protection_keys`] is set to `enable`
4781 /// or `auto`. Configuring this above the HW and OS limits (typically 15)
4782 /// has no effect.
4783 ///
4784 /// If multiple Wasmtime engines are used in the same process, note that all
4785 /// engines will share the same set of allocated keys; this setting will
4786 /// limit how many keys are allocated initially and thus available to all
4787 /// other engines.
4788 #[cfg(feature = "memory-protection-keys")]
4789 pub fn max_memory_protection_keys(&mut self, max: usize) -> &mut Self {
4790 self.max_memory_protection_keys = max;
4791 self
4792 }
4793
4794 /// Check if memory protection keys (MPK) are available on the current host.
4795 ///
4796 /// This is a convenience method for determining MPK availability using the
4797 /// same method that [`Enabled::Auto`] does. See
4798 /// [`PoolingAllocationConfig::memory_protection_keys`] for more
4799 /// information.
4800 #[cfg(feature = "memory-protection-keys")]
4801 pub fn are_memory_protection_keys_available() -> bool {
4802 crate::runtime::vm::mpk::is_supported()
4803 }
4804
4805 /// The maximum number of concurrent GC heaps supported (default is `1000`).
4806 ///
4807 /// This value has a direct impact on the amount of memory allocated by the
4808 /// pooling instance allocator.
4809 ///
4810 /// The pooling instance allocator allocates a GC heap pool, where each
4811 /// entry in the pool contains the space needed for each GC heap used by a
4812 /// store.
4813 #[cfg(feature = "gc")]
4814 pub fn total_gc_heaps(&mut self, count: u32) -> &mut Self {
4815 self.limits.total_gc_heaps = count;
4816 self
4817 }
4818
4819 /// Configures whether the Linux-specific [`PAGEMAP_SCAN` ioctl][ioctl] is
4820 /// used to help reset linear memory.
4821 ///
4822 /// When [`Self::linear_memory_keep_resident`] or
4823 /// [`Self::table_keep_resident`] options are configured to nonzero values
4824 /// the default behavior is to `memset` the lowest addresses of a table or
4825 /// memory back to their original contents. With the `PAGEMAP_SCAN` ioctl on
4826 /// Linux this can be done to more intelligently scan for resident pages in
4827 /// the region and only reset those pages back to their original contents
4828 /// with `memset` rather than assuming the low addresses are all resident.
4829 ///
4830 /// This ioctl has the potential to provide a number of performance benefits
4831 /// in high-reuse and high concurrency scenarios. Notably this enables
4832 /// Wasmtime to scan the entire region of WebAssembly linear memory and
4833 /// manually reset memory back to its original contents, up to
4834 /// [`Self::linear_memory_keep_resident`] bytes, possibly skipping an
4835 /// `madvise` entirely. This can be more efficient by avoiding removing
4836 /// pages from the address space entirely and additionally ensuring that
4837 /// future use of the linear memory doesn't incur page faults as the pages
4838 /// remain resident.
4839 ///
4840 /// At this time this configuration option is still being evaluated as to
4841 /// how appropriate it is for all use cases. It currently defaults to
4842 /// `no` or disabled but may change to `auto`, enable if supported, in the
4843 /// future. This option is only supported on Linux and requires a kernel
4844 /// version of 6.7 or higher.
4845 ///
4846 /// [ioctl]: https://www.man7.org/linux/man-pages/man2/PAGEMAP_SCAN.2const.html
4847 pub fn pagemap_scan(&mut self, enable: Enabled) -> &mut Self {
4848 self.pagemap_scan = enable;
4849 self
4850 }
4851
4852 /// Returns the configured
4853 /// [`PoolingAllocationConfig::decommit_batch_size`], if enabled.
4854 pub fn get_decommit_batch_size(&self) -> usize {
4855 self.decommit_batch_size
4856 }
4857
4858 /// Returns the configured
4859 /// [`PoolingAllocationConfig::max_unused_warm_slots`], if enabled.
4860 pub fn get_max_unused_warm_slots(&self) -> u32 {
4861 self.max_unused_warm_slots
4862 }
4863
4864 /// Returns the configured
4865 /// [`PoolingAllocationConfig::linear_memory_keep_resident`], if
4866 /// enabled.
4867 pub fn get_memory_keep_resident(&self) -> usize {
4868 self.linear_memory_keep_resident
4869 }
4870
4871 /// Returns the configured
4872 /// [`PoolingAllocationConfig::table_keep_resident`], if enabled.
4873 pub fn get_table_keep_resident(&self) -> usize {
4874 self.table_keep_resident
4875 }
4876
4877 /// Returns the configured
4878 /// [`PoolingAllocationConfig::async_stack_keep_resident`], if
4879 /// enabled.
4880 pub fn get_async_stack_keep_resident(&self) -> usize {
4881 self.async_stack_keep_resident
4882 }
4883
4884 /// Returns the configured
4885 /// [`PoolingAllocationConfig::memory_protection_keys`], if enabled.
4886 pub fn get_memory_protection_keys(&self) -> Enabled {
4887 self.memory_protection_keys
4888 }
4889
4890 /// Returns the configured
4891 /// [`PoolingAllocationConfig::max_memory_protection_keys`], if
4892 /// enabled.
4893 pub fn get_max_memory_protection_keys(&self) -> usize {
4894 self.max_memory_protection_keys
4895 }
4896
4897 /// Returns the configured
4898 /// [`PoolingAllocationConfig::pagemap_scan`], if enabled.
4899 pub fn get_pagemap_scan(&self) -> Enabled {
4900 self.pagemap_scan
4901 }
4902
4903 /// Returns the configured
4904 /// [`PoolingAllocationConfig::total_core_instances`], if enabled.
4905 pub fn get_total_core_instances(&self) -> u32 {
4906 self.limits.total_core_instances
4907 }
4908
4909 /// Returns the configured
4910 /// [`PoolingAllocationConfig::total_component_instances`], if
4911 /// enabled.
4912 pub fn get_total_component_instances(&self) -> u32 {
4913 self.limits.total_component_instances
4914 }
4915
4916 /// Returns the configured
4917 /// [`PoolingAllocationConfig::total_memories`], if enabled.
4918 pub fn get_total_memories(&self) -> u32 {
4919 self.limits.total_memories
4920 }
4921
4922 /// Returns the configured
4923 /// [`PoolingAllocationConfig::total_tables`], if enabled.
4924 pub fn get_total_tables(&self) -> u32 {
4925 self.limits.total_tables
4926 }
4927
4928 /// Returns the configured
4929 /// [`PoolingAllocationConfig::total_stacks`], if enabled.
4930 pub fn get_total_stacks(&self) -> u32 {
4931 self.limits.total_stacks
4932 }
4933
4934 /// Returns the configured
4935 /// [`PoolingAllocationConfig::total_gc_heaps`], if enabled.
4936 pub fn get_total_gc_heaps(&self) -> u32 {
4937 self.limits.total_gc_heaps
4938 }
4939
4940 /// Returns the configured
4941 /// [`PoolingAllocationConfig::max_memory_size`], if enabled.
4942 pub fn get_max_memory_size(&self) -> usize {
4943 self.limits.max_memory_size
4944 }
4945
4946 /// Returns the configured
4947 /// [`PoolingAllocationConfig::table_elements`], if enabled.
4948 pub fn get_table_elements(&self) -> usize {
4949 self.limits.table_elements
4950 }
4951
4952 /// Returns the configured
4953 /// [`PoolingAllocationConfig::max_core_instance_size`], if enabled.
4954 pub fn get_max_core_instance_size(&self) -> usize {
4955 self.limits.core_instance_size
4956 }
4957
4958 /// Returns the configured
4959 /// [`PoolingAllocationConfig::max_component_instance_size`], if
4960 /// enabled.
4961 pub fn get_max_component_instance_size(&self) -> usize {
4962 self.limits.component_instance_size
4963 }
4964
4965 /// Returns the configured
4966 /// [`PoolingAllocationConfig::max_core_instances_per_component`], if
4967 /// enabled.
4968 pub fn get_max_core_instances_per_component(&self) -> u32 {
4969 self.limits.max_core_instances_per_component
4970 }
4971
4972 /// Returns the configured
4973 /// [`PoolingAllocationConfig::max_memories_per_component`], if
4974 /// enabled.
4975 pub fn get_max_memories_per_component(&self) -> u32 {
4976 self.limits.max_memories_per_component
4977 }
4978
4979 /// Returns the configured
4980 /// [`PoolingAllocationConfig::max_tables_per_component`], if enabled.
4981 pub fn get_max_tables_per_component(&self) -> u32 {
4982 self.limits.max_tables_per_component
4983 }
4984
4985 /// Returns the configured
4986 /// [`PoolingAllocationConfig::max_tables_per_module`], if enabled.
4987 pub fn get_max_tables_per_module(&self) -> u32 {
4988 self.limits.max_tables_per_module
4989 }
4990
4991 /// Returns the configured
4992 /// [`PoolingAllocationConfig::max_memories_per_module`], if enabled.
4993 pub fn get_max_memories_per_module(&self) -> u32 {
4994 self.limits.max_memories_per_module
4995 }
4996}
4997
4998#[cfg(feature = "std")]
4999fn detect_host_feature(feature: &str) -> Option<bool> {
5000 #[cfg(target_arch = "aarch64")]
5001 {
5002 return match feature {
5003 "lse" => Some(std::arch::is_aarch64_feature_detected!("lse")),
5004 "paca" => Some(std::arch::is_aarch64_feature_detected!("paca")),
5005 "fp16" => Some(std::arch::is_aarch64_feature_detected!("fp16")),
5006 "dotprod" => Some(std::arch::is_aarch64_feature_detected!("dotprod")),
5007 "i8mm" => Some(std::arch::is_aarch64_feature_detected!("i8mm")),
5008
5009 _ => None,
5010 };
5011 }
5012
5013 // `is_s390x_feature_detected` is nightly only for now, so use the
5014 // STORE FACILITY LIST EXTENDED instruction as a temporary measure.
5015 #[cfg(target_arch = "s390x")]
5016 {
5017 let mut facility_list: [u64; 4] = [0; 4];
5018 unsafe {
5019 core::arch::asm!(
5020 "stfle 0({})",
5021 in(reg_addr) facility_list.as_mut_ptr() ,
5022 inout("r0") facility_list.len() as u64 - 1 => _,
5023 options(nostack)
5024 );
5025 }
5026 let get_facility_bit = |n: usize| {
5027 // NOTE: bits are numbered from the left.
5028 facility_list[n / 64] & (1 << (63 - (n % 64))) != 0
5029 };
5030
5031 return match feature {
5032 "mie3" => Some(get_facility_bit(61)),
5033 "mie4" => Some(get_facility_bit(84)),
5034 "vxrs_ext2" => Some(get_facility_bit(148)),
5035 "vxrs_ext3" => Some(get_facility_bit(198)),
5036
5037 _ => None,
5038 };
5039 }
5040
5041 #[cfg(target_arch = "riscv64")]
5042 {
5043 return match feature {
5044 // due to `is_riscv64_feature_detected` is not stable.
5045 // we cannot use it. For now lie and say all features are always
5046 // found to keep tests working.
5047 _ => Some(true),
5048 };
5049 }
5050
5051 #[cfg(target_arch = "x86_64")]
5052 {
5053 return match feature {
5054 "cmpxchg16b" => Some(std::is_x86_feature_detected!("cmpxchg16b")),
5055 "sse3" => Some(std::is_x86_feature_detected!("sse3")),
5056 "ssse3" => Some(std::is_x86_feature_detected!("ssse3")),
5057 "sse4.1" => Some(std::is_x86_feature_detected!("sse4.1")),
5058 "sse4.2" => Some(std::is_x86_feature_detected!("sse4.2")),
5059 "popcnt" => Some(std::is_x86_feature_detected!("popcnt")),
5060 "avx" => Some(std::is_x86_feature_detected!("avx")),
5061 "avx2" => Some(std::is_x86_feature_detected!("avx2")),
5062 "fma" => Some(std::is_x86_feature_detected!("fma")),
5063 "avxvnni" => Some(std::is_x86_feature_detected!("avxvnni")),
5064 "bmi1" => Some(std::is_x86_feature_detected!("bmi1")),
5065 "bmi2" => Some(std::is_x86_feature_detected!("bmi2")),
5066 "avx512bitalg" => Some(std::is_x86_feature_detected!("avx512bitalg")),
5067 "avx512dq" => Some(std::is_x86_feature_detected!("avx512dq")),
5068 "avx512f" => Some(std::is_x86_feature_detected!("avx512f")),
5069 "avx512vl" => Some(std::is_x86_feature_detected!("avx512vl")),
5070 "avx512vbmi" => Some(std::is_x86_feature_detected!("avx512vbmi")),
5071 "avx512vnni" => Some(std::is_x86_feature_detected!("avx512vnni")),
5072 "lzcnt" => Some(std::is_x86_feature_detected!("lzcnt")),
5073
5074 _ => None,
5075 };
5076 }
5077
5078 #[allow(
5079 unreachable_code,
5080 reason = "reachable or not depending on if a target above matches"
5081 )]
5082 {
5083 let _ = feature;
5084 return None;
5085 }
5086}
5087
5088// What follows in this impl block is intended to be a somewhat-mechanical
5089// mostly-complete set of getters for relevant configuration options on
5090// `Config`. The `Config` type does not reflect a complete configuration so
5091// default values cannot be directly read from it. An `Engine`, however,
5092// represents a concrete and complete configuration with all default values
5093// fully specified. The purpose of these getters are then to perform a dual
5094// function of reflecting what was explicitly configured above as well as
5095// defaults that Wasmtime sets.
5096//
5097// The current pattern is:
5098//
5099// * All methods are `get_<config_name>`
5100// * Return values return `T` instead of `Option<T>` where possible unless the
5101// state for `T` is completely missing.
5102//
5103// This impl is primarily in service of
5104// `wasmtime_cli_flags::CommonOptions::from_engine` at this time, and CLI flags
5105// are not as comprehensive as `Config` options, but it's expected that the set
5106// will settle/grow over time.
5107impl Engine {
5108 /// Returns the configured [`Config::memory_may_move`] value.
5109 pub fn get_memory_may_move(&self) -> bool {
5110 self.tunables().memory_may_move
5111 }
5112
5113 /// Returns the configured [`Config::memory_reservation`] value.
5114 pub fn get_memory_reservation(&self) -> u64 {
5115 self.tunables().memory_reservation
5116 }
5117
5118 /// Returns the configured [`Config::memory_reservation_for_growth`] value.
5119 pub fn get_memory_reservation_for_growth(&self) -> u64 {
5120 self.tunables().memory_reservation_for_growth
5121 }
5122
5123 /// Returns the configured [`Config::memory_guard_size`] value.
5124 pub fn get_memory_guard_size(&self) -> u64 {
5125 self.tunables().memory_guard_size
5126 }
5127
5128 /// Returns the configured [`Config::gc_heap_may_move`] value.
5129 pub fn get_gc_heap_may_move(&self) -> bool {
5130 self.tunables().gc_heap_may_move
5131 }
5132
5133 /// Returns the configured [`Config::gc_heap_reservation`] value.
5134 pub fn get_gc_heap_reservation(&self) -> u64 {
5135 self.tunables().gc_heap_reservation
5136 }
5137
5138 /// Returns the configured [`Config::gc_heap_initial_size`] value.
5139 pub fn get_gc_heap_initial_size(&self) -> u64 {
5140 self.tunables().gc_heap_initial_size
5141 }
5142
5143 /// Returns the configured [`Config::gc_heap_reservation_for_growth`] value.
5144 pub fn get_gc_heap_reservation_for_growth(&self) -> u64 {
5145 self.tunables().gc_heap_reservation_for_growth
5146 }
5147
5148 /// Returns the configured [`Config::gc_heap_guard_size`] value.
5149 pub fn get_gc_heap_guard_size(&self) -> u64 {
5150 self.tunables().gc_heap_guard_size
5151 }
5152
5153 /// Returns the configured [`Config::guard_before_linear_memory`] value.
5154 pub fn get_guard_before_linear_memory(&self) -> bool {
5155 self.tunables().guard_before_linear_memory
5156 }
5157
5158 /// Returns the configured [`Config::table_lazy_init`] value.
5159 pub fn get_table_lazy_init(&self) -> bool {
5160 self.tunables().table_lazy_init
5161 }
5162
5163 /// Returns the configured [`Config::memory_init_cow`] value.
5164 pub fn get_memory_init_cow(&self) -> bool {
5165 self.tunables().memory_init_cow
5166 }
5167
5168 /// Returns the configured [`Config::memory_guaranteed_dense_image_size`] value.
5169 pub fn get_memory_guaranteed_dense_image_size(&self) -> u64 {
5170 self.config().memory_guaranteed_dense_image_size
5171 }
5172
5173 /// Returns the configured [`Config::signals_based_traps`] value.
5174 pub fn get_signals_based_traps(&self) -> bool {
5175 self.tunables().signals_based_traps
5176 }
5177
5178 /// Returns the configured [`Config::gc_zeal_alloc_counter`] value.
5179 pub fn get_gc_zeal_alloc_counter(&self) -> Option<core::num::NonZeroU32> {
5180 self.tunables().gc_zeal_alloc_counter
5181 }
5182
5183 /// Returns the configured [`Config::cranelift_opt_level`] value.
5184 pub fn get_cranelift_opt_level(&self) -> Option<OptLevel> {
5185 #[cfg(any(feature = "cranelift", feature = "winch"))]
5186 if let Some(compiler) = self.compiler() {
5187 let flags = compiler.flags();
5188 let (_, FlagValue::Enum(opt)) = flags.iter().find(|(f, _)| *f == "opt_level")? else {
5189 return None;
5190 };
5191 return match &opt[..] {
5192 "none" => Some(OptLevel::None),
5193 "speed" => Some(OptLevel::Speed),
5194 "speed_and_size" => Some(OptLevel::SpeedAndSize),
5195 _ => None,
5196 };
5197 }
5198 None
5199 }
5200
5201 /// Returns the configured [`Config::cranelift_regalloc_algorithm`] value.
5202 pub fn get_cranelift_regalloc_algorithm(&self) -> Option<RegallocAlgorithm> {
5203 #[cfg(any(feature = "cranelift", feature = "winch"))]
5204 if let Some(compiler) = self.compiler() {
5205 let flags = compiler.flags();
5206 let (_, FlagValue::Enum(opt)) =
5207 flags.iter().find(|(f, _)| *f == "regalloc_algorithm")?
5208 else {
5209 return None;
5210 };
5211 return match &opt[..] {
5212 "backtracking" => Some(RegallocAlgorithm::Backtracking),
5213 "single_pass" => Some(RegallocAlgorithm::SinglePass),
5214 _ => None,
5215 };
5216 }
5217 None
5218 }
5219
5220 /// Returns the configured [`Config::strategy`] value.
5221 pub fn get_strategy(&self) -> Option<Strategy> {
5222 self.config().get_strategy()
5223 }
5224
5225 /// Returns the configured [`Config::collector`] value.
5226 pub fn get_collector(&self) -> Option<Collector> {
5227 #[cfg(feature = "gc")]
5228 return Some(self.config().collector);
5229 #[cfg(not(feature = "gc"))]
5230 return None;
5231 }
5232
5233 /// Returns the configured [`Config::cranelift_debug_verifier`] value.
5234 pub fn get_cranelift_debug_verifier(&self) -> Option<bool> {
5235 #[cfg(any(feature = "cranelift", feature = "winch"))]
5236 if let Some(compiler) = self.compiler() {
5237 let flags = compiler.flags();
5238 let (_, FlagValue::Bool(b)) = flags.iter().find(|(f, _)| *f == "enable_verifier")?
5239 else {
5240 return None;
5241 };
5242 return Some(*b);
5243 }
5244 None
5245 }
5246
5247 /// Returns the configured [`Config::compiler_inlining`] value.
5248 pub fn get_compiler_inlining(&self) -> Inlining {
5249 self.tunables().inlining
5250 }
5251
5252 /// Returns the configured [`Config::native_unwind_info`] value.
5253 pub fn get_native_unwind_info(&self) -> Option<bool> {
5254 #[cfg(any(feature = "cranelift", feature = "winch"))]
5255 if let Some(compiler) = self.compiler() {
5256 let flags = compiler.flags();
5257 let (_, FlagValue::Bool(b)) = flags.iter().find(|(f, _)| *f == "unwind_info")? else {
5258 return None;
5259 };
5260 return Some(*b);
5261 }
5262 None
5263 }
5264
5265 /// Returns the configured [`Config::parallel_compilation`] value.
5266 pub fn get_parallel_compilation(&self) -> bool {
5267 self.config().parallel_compilation
5268 }
5269
5270 /// Returns the configured [`Config::metadata_for_internal_asserts`] value.
5271 pub fn get_metadata_for_internal_asserts(&self) -> bool {
5272 self.tunables().metadata_for_internal_asserts
5273 }
5274
5275 /// Returns the configured [`Config::metadata_for_gc_heap_corruption`] value.
5276 pub fn get_metadata_for_gc_heap_corruption(&self) -> bool {
5277 self.tunables().metadata_for_gc_heap_corruption
5278 }
5279
5280 /// Returns the runtime pooling allocator configuration, if the pooling
5281 /// allocator is in use.
5282 pub fn get_pooling_config(&self) -> Option<&PoolingAllocationConfig> {
5283 #[cfg(feature = "pooling-allocator")]
5284 {
5285 Some(self.allocator().as_pooling()?.config())
5286 }
5287 #[cfg(not(feature = "pooling-allocator"))]
5288 {
5289 None
5290 }
5291 }
5292
5293 /// Returns the configured wasm proposals enabled in this engine.
5294 pub fn get_wasm_features(&self) -> WasmFeatures {
5295 self.features()
5296 }
5297
5298 /// Returns the configured [`Config::async_stack_size`] value.
5299 pub fn get_async_stack_size(&self) -> usize {
5300 self.config().async_stack_size
5301 }
5302
5303 /// Returns the configured [`Config::async_stack_zeroing`] value.
5304 pub fn get_async_stack_zeroing(&self) -> bool {
5305 self.config().async_stack_zeroing
5306 }
5307
5308 /// Returns the configured [`Config::wasm_branch_hinting`] value.
5309 pub fn get_wasm_branch_hinting(&self) -> bool {
5310 self.tunables().branch_hinting
5311 }
5312
5313 /// Returns the configured [`Config::concurrency_support`] value.
5314 pub fn get_concurrency_support(&self) -> bool {
5315 self.tunables().concurrency_support
5316 }
5317
5318 /// Returns the configured [`Config::asan_compatible_code`] value.
5319 pub fn get_asan_compatible_code(&self) -> bool {
5320 self.tunables().asan_stack_switching
5321 }
5322
5323 /// Returns the configured [`Config::epoch_interruption`] value.
5324 pub fn get_epoch_interruption(&self) -> bool {
5325 self.tunables().epoch_interruption
5326 }
5327
5328 /// Returns the configured [`Config::mmu_interruption`] value.
5329 #[doc(hidden)]
5330 pub fn get_mmu_interruption(&self) -> bool {
5331 self.tunables().mmu_interruption
5332 }
5333
5334 /// Returns the configured [`Config::consume_fuel`] value.
5335 pub fn get_consume_fuel(&self) -> bool {
5336 self.tunables().consume_fuel
5337 }
5338
5339 /// Returns the configured [`Config::max_wasm_stack`] value.
5340 pub fn get_max_wasm_stack(&self) -> usize {
5341 self.config().max_wasm_stack
5342 }
5343
5344 /// Returns the configured [`Config::cranelift_nan_canonicalization`] value.
5345 pub fn get_cranelift_nan_canonicalization(&self) -> Option<bool> {
5346 #[cfg(any(feature = "cranelift", feature = "winch"))]
5347 if let Some(compiler) = self.compiler() {
5348 let flags = compiler.flags();
5349 let (_, FlagValue::Bool(b)) = flags
5350 .iter()
5351 .find(|(f, _)| *f == "enable_nan_canonicalization")?
5352 else {
5353 return None;
5354 };
5355 return Some(*b);
5356 }
5357 None
5358 }
5359
5360 /// Returns the configured [`Config::relaxed_simd_deterministic`] value.
5361 pub fn get_relaxed_simd_deterministic(&self) -> bool {
5362 self.tunables().relaxed_simd_deterministic
5363 }
5364
5365 /// Returns the configured [`Config::shared_memory`] value.
5366 pub fn get_shared_memory(&self) -> bool {
5367 self.config().shared_memory
5368 }
5369
5370 /// Returns the configured [`Config::generate_address_map`] value.
5371 pub fn get_generate_address_map(&self) -> bool {
5372 self.tunables().generate_address_map
5373 }
5374
5375 /// Returns the configured [`Config::debug_info`] value.
5376 pub fn get_debug_info(&self) -> bool {
5377 self.tunables().debug_native
5378 }
5379
5380 /// Returns the configured [`Config::guest_debug`] value.
5381 pub fn get_guest_debug(&self) -> bool {
5382 self.tunables().debug_guest
5383 }
5384
5385 /// Returns the configured [`Config::debug_symbols`] value.
5386 pub fn get_debug_symbols(&self) -> bool {
5387 self.tunables().debug_symbols
5388 }
5389
5390 /// Returns the configured [`Config::wasm_backtrace_max_frames`] value.
5391 pub fn get_wasm_backtrace_max_frames(&self) -> usize {
5392 self.config()
5393 .wasm_backtrace_max_frames
5394 .map(|f| f.get())
5395 .unwrap_or(0)
5396 }
5397
5398 /// Returns the configured [`Config::target`] value.
5399 pub fn get_target(&self) -> Option<String> {
5400 #[cfg(any(feature = "cranelift", feature = "winch"))]
5401 if let Some(compiler) = self.compiler() {
5402 return Some(compiler.triple().to_string());
5403 }
5404 None
5405 }
5406
5407 /// Returns the enabled flags via [`Config::cranelift_flag_enable`].
5408 pub fn get_cranelift_flags_enabled(&self) -> impl Iterator<Item = &str> {
5409 #[cfg(any(feature = "cranelift", feature = "winch"))]
5410 if let Some(config) = &self.config().compiler_config {
5411 return config
5412 .flags
5413 .iter()
5414 .filter_map(|(k, v)| match v {
5415 UserSpecified::Yes => Some(k.as_str()),
5416 UserSpecified::No => None,
5417 })
5418 .collect::<Vec<_>>()
5419 .into_iter();
5420 }
5421
5422 Vec::new().into_iter()
5423 }
5424
5425 /// Returns the enabled flags via [`Config::cranelift_flag_set`].
5426 pub fn get_cranelift_flags_set(&self) -> impl Iterator<Item = (&str, &str)> {
5427 #[cfg(any(feature = "cranelift", feature = "winch"))]
5428 if let Some(config) = &self.config().compiler_config {
5429 return config
5430 .settings
5431 .iter()
5432 .filter_map(|(k, (v, s))| match s {
5433 UserSpecified::Yes => Some((k.as_str(), v.as_str())),
5434 UserSpecified::No => None,
5435 })
5436 .collect::<Vec<_>>()
5437 .into_iter();
5438 }
5439
5440 Vec::new().into_iter()
5441 }
5442}