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