Skip to main content

wasmtime/
config.rs

1use crate::prelude::*;
2use alloc::sync::Arc;
3use bitflags::Flags;
4use core::fmt;
5use core::num::NonZeroUsize;
6use core::str::FromStr;
7#[cfg(any(feature = "cranelift", feature = "winch"))]
8use std::path::Path;
9pub use wasmparser::WasmFeatures;
10use wasmtime_environ::{ConfigTunables, OperatorCost, OperatorCostStrategy, TripleExt, Tunables};
11
12#[cfg(feature = "runtime")]
13use crate::memory::MemoryCreator;
14#[cfg(feature = "runtime")]
15use crate::profiling_agent::{self, ProfilingAgent};
16#[cfg(feature = "runtime")]
17use crate::runtime::vm::{
18    GcRuntime, InstanceAllocator, OnDemandInstanceAllocator, RuntimeMemoryCreator,
19};
20#[cfg(feature = "runtime")]
21use crate::trampoline::MemoryCreatorProxy;
22
23#[cfg(feature = "async")]
24use crate::stack::{StackCreator, StackCreatorProxy};
25#[cfg(feature = "async")]
26use wasmtime_fiber::RuntimeFiberStackCreator;
27
28#[cfg(feature = "runtime")]
29pub use crate::runtime::code_memory::CustomCodeMemory;
30#[cfg(feature = "cache")]
31pub use wasmtime_cache::{Cache, CacheConfig};
32#[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
33pub use wasmtime_environ::CacheStore;
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    #[cfg(feature = "pooling-allocator")]
54    Pooling(PoolingAllocationConfig),
55}
56
57impl InstanceAllocationStrategy {
58    /// The default pooling instance allocation strategy.
59    #[cfg(feature = "pooling-allocator")]
60    pub fn pooling() -> Self {
61        Self::Pooling(Default::default())
62    }
63}
64
65impl Default for InstanceAllocationStrategy {
66    fn default() -> Self {
67        Self::OnDemand
68    }
69}
70
71#[cfg(feature = "pooling-allocator")]
72impl From<PoolingAllocationConfig> for InstanceAllocationStrategy {
73    fn from(cfg: PoolingAllocationConfig) -> InstanceAllocationStrategy {
74        InstanceAllocationStrategy::Pooling(cfg)
75    }
76}
77
78#[derive(Clone)]
79/// Configure the strategy used for versioning in serializing and deserializing [`crate::Module`].
80pub enum ModuleVersionStrategy {
81    /// Use the wasmtime crate's Cargo package version.
82    WasmtimeVersion,
83    /// Use a custom version string. Must be at most 255 bytes.
84    Custom(String),
85    /// Emit no version string in serialization, and accept all version strings in deserialization.
86    None,
87}
88
89impl Default for ModuleVersionStrategy {
90    fn default() -> Self {
91        ModuleVersionStrategy::WasmtimeVersion
92    }
93}
94
95impl core::hash::Hash for ModuleVersionStrategy {
96    fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
97        match self {
98            Self::WasmtimeVersion => env!("CARGO_PKG_VERSION").hash(hasher),
99            Self::Custom(s) => s.hash(hasher),
100            Self::None => {}
101        };
102    }
103}
104
105impl ModuleVersionStrategy {
106    /// Get the string-encoding version of the module.
107    pub fn as_str(&self) -> &str {
108        match &self {
109            Self::WasmtimeVersion => env!("CARGO_PKG_VERSION_MAJOR"),
110            Self::Custom(c) => c,
111            Self::None => "",
112        }
113    }
114}
115
116/// Configuration for record/replay
117#[derive(Clone)]
118#[non_exhaustive]
119pub enum RRConfig {
120    #[cfg(feature = "rr")]
121    /// Recording on store is enabled
122    Recording,
123    #[cfg(feature = "rr")]
124    /// Replaying on store is enabled
125    Replaying,
126    /// No record/replay is enabled
127    None,
128}
129
130/// Global configuration options used to create an [`Engine`](crate::Engine)
131/// and customize its behavior.
132///
133/// This structure exposed a builder-like interface and is primarily consumed by
134/// [`Engine::new()`](crate::Engine::new).
135///
136/// The validation of `Config` is deferred until the engine is being built, thus
137/// a problematic config may cause `Engine::new` to fail.
138///
139/// # Defaults
140///
141/// The `Default` trait implementation and the return value from
142/// [`Config::new()`] are the same and represent the default set of
143/// configuration for an engine. The exact set of defaults will differ based on
144/// properties such as enabled Cargo features at compile time and the configured
145/// target (see [`Config::target`]). Configuration options document their
146/// default values and what the conditional value of the default is where
147/// applicable.
148#[derive(Clone)]
149pub struct Config {
150    #[cfg(any(feature = "cranelift", feature = "winch"))]
151    compiler_config: Option<CompilerConfig>,
152    target: Option<target_lexicon::Triple>,
153    #[cfg(feature = "gc")]
154    collector: Collector,
155    profiling_strategy: ProfilingStrategy,
156    tunables: ConfigTunables,
157
158    #[cfg(feature = "cache")]
159    pub(crate) cache: Option<Cache>,
160    #[cfg(feature = "runtime")]
161    pub(crate) mem_creator: Option<Arc<dyn RuntimeMemoryCreator>>,
162    #[cfg(feature = "runtime")]
163    pub(crate) custom_code_memory: Option<Arc<dyn CustomCodeMemory>>,
164    pub(crate) allocation_strategy: InstanceAllocationStrategy,
165    pub(crate) max_wasm_stack: usize,
166    /// Explicitly enabled features via `Config::wasm_*` methods. This is a
167    /// signal that the embedder specifically wants something turned on
168    /// regardless of the defaults that Wasmtime might otherwise have enabled.
169    ///
170    /// Note that this, and `disabled_features` below, start as the empty set of
171    /// features to only track explicit user requests.
172    pub(crate) enabled_features: WasmFeatures,
173    /// Same as `enabled_features`, but for those that are explicitly disabled.
174    pub(crate) disabled_features: WasmFeatures,
175    pub(crate) wasm_backtrace_details_env_used: bool,
176    pub(crate) wasm_backtrace_max_frames: Option<NonZeroUsize>,
177    pub(crate) native_unwind_info: Option<bool>,
178    #[cfg(any(feature = "async", feature = "stack-switching"))]
179    pub(crate) async_stack_size: usize,
180    #[cfg(feature = "async")]
181    pub(crate) async_stack_zeroing: bool,
182    #[cfg(feature = "async")]
183    pub(crate) stack_creator: Option<Arc<dyn RuntimeFiberStackCreator>>,
184    pub(crate) module_version: ModuleVersionStrategy,
185    pub(crate) parallel_compilation: bool,
186    pub(crate) memory_guaranteed_dense_image_size: u64,
187    pub(crate) force_memory_init_memfd: bool,
188    pub(crate) wmemcheck: bool,
189    #[cfg(feature = "coredump")]
190    pub(crate) coredump_on_trap: bool,
191    pub(crate) macos_use_mach_ports: bool,
192    pub(crate) detect_host_feature: Option<fn(&str) -> Option<bool>>,
193    pub(crate) x86_float_abi_ok: Option<bool>,
194    pub(crate) shared_memory: bool,
195    pub(crate) rr_config: RRConfig,
196}
197
198/// User-provided configuration for the compiler.
199#[cfg(any(feature = "cranelift", feature = "winch"))]
200#[derive(Debug, Clone)]
201struct CompilerConfig {
202    strategy: Option<Strategy>,
203    settings: crate::hash_map::HashMap<String, String>,
204    flags: crate::hash_set::HashSet<String>,
205    #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
206    cache_store: Option<Arc<dyn CacheStore>>,
207    clif_dir: Option<std::path::PathBuf>,
208    wmemcheck: bool,
209}
210
211#[cfg(any(feature = "cranelift", feature = "winch"))]
212impl CompilerConfig {
213    fn new() -> Self {
214        Self {
215            strategy: Strategy::Auto.not_auto(),
216            settings: Default::default(),
217            flags: Default::default(),
218            #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
219            cache_store: None,
220            clif_dir: None,
221            wmemcheck: false,
222        }
223    }
224
225    /// Ensures that the key is not set or equals to the given value.
226    /// If the key is not set, it will be set to the given value.
227    ///
228    /// # Returns
229    ///
230    /// Returns true if successfully set or already had the given setting
231    /// value, or false if the setting was explicitly set to something
232    /// else previously.
233    fn ensure_setting_unset_or_given(&mut self, k: &str, v: &str) -> bool {
234        if let Some(value) = self.settings.get(k) {
235            if value != v {
236                return false;
237            }
238        } else {
239            self.settings.insert(k.to_string(), v.to_string());
240        }
241        true
242    }
243}
244
245#[cfg(any(feature = "cranelift", feature = "winch"))]
246impl Default for CompilerConfig {
247    fn default() -> Self {
248        Self::new()
249    }
250}
251
252impl Config {
253    /// Creates a new configuration object with the default configuration
254    /// specified.
255    pub fn new() -> Self {
256        let mut ret = Self {
257            tunables: ConfigTunables::default(),
258            #[cfg(any(feature = "cranelift", feature = "winch"))]
259            compiler_config: Some(CompilerConfig::default()),
260            target: None,
261            #[cfg(feature = "gc")]
262            collector: Collector::default(),
263            #[cfg(feature = "cache")]
264            cache: None,
265            profiling_strategy: ProfilingStrategy::None,
266            #[cfg(feature = "runtime")]
267            mem_creator: None,
268            #[cfg(feature = "runtime")]
269            custom_code_memory: None,
270            allocation_strategy: InstanceAllocationStrategy::OnDemand,
271            // 512k of stack -- note that this is chosen currently to not be too
272            // big, not be too small, and be a good default for most platforms.
273            // One platform of particular note is Windows where the stack size
274            // of the main thread seems to, by default, be smaller than that of
275            // Linux and macOS. This 512k value at least lets our current test
276            // suite pass on the main thread of Windows (using `--test-threads
277            // 1` forces this), or at least it passed when this change was
278            // committed.
279            max_wasm_stack: 512 * 1024,
280            wasm_backtrace_details_env_used: false,
281            wasm_backtrace_max_frames: Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES),
282            native_unwind_info: None,
283            enabled_features: WasmFeatures::empty(),
284            disabled_features: WasmFeatures::empty(),
285            #[cfg(any(feature = "async", feature = "stack-switching"))]
286            async_stack_size: 2 << 20,
287            #[cfg(feature = "async")]
288            async_stack_zeroing: false,
289            #[cfg(feature = "async")]
290            stack_creator: None,
291            module_version: ModuleVersionStrategy::default(),
292            parallel_compilation: !cfg!(miri),
293            memory_guaranteed_dense_image_size: 16 << 20,
294            force_memory_init_memfd: false,
295            wmemcheck: false,
296            #[cfg(feature = "coredump")]
297            coredump_on_trap: false,
298            macos_use_mach_ports: !cfg!(miri),
299            #[cfg(feature = "std")]
300            detect_host_feature: Some(detect_host_feature),
301            #[cfg(not(feature = "std"))]
302            detect_host_feature: None,
303            x86_float_abi_ok: None,
304            shared_memory: false,
305            rr_config: RRConfig::None,
306        };
307        ret.wasm_backtrace_details(WasmBacktraceDetails::Environment);
308        ret
309    }
310
311    #[cfg(any(feature = "cranelift", feature = "winch"))]
312    pub(crate) fn has_compiler(&self) -> bool {
313        self.compiler_config.is_some()
314    }
315
316    #[track_caller]
317    #[cfg(any(feature = "cranelift", feature = "winch"))]
318    fn compiler_config_mut(&mut self) -> &mut CompilerConfig {
319        self.compiler_config.as_mut().expect(
320            "cannot configure compiler settings for `Config`s \
321             created by `Config::without_compiler`",
322        )
323    }
324
325    /// Configure whether Wasm compilation is enabled.
326    ///
327    /// Disabling Wasm compilation will allow you to load and run
328    /// [pre-compiled][crate::Engine::precompile_module] Wasm programs, but not
329    /// to compile and run new Wasm programs that have not already been
330    /// pre-compiled.
331    ///
332    /// Many compilation-related configuration methods will panic if compilation
333    /// has been disabled.
334    ///
335    /// Note that there are two ways to disable Wasm compilation:
336    ///
337    /// 1. Statically, by disabling the `"cranelift"` and `"winch"` cargo
338    ///    features when building Wasmtime. These builds of Wasmtime will have
339    ///    smaller code size, since they do not include any of the code to
340    ///    compile Wasm.
341    ///
342    /// 2. Dynamically, by passing `false` to this method at run-time when
343    ///    configuring Wasmtime. The Wasmtime binary will still include the code
344    ///    for compiling Wasm, it just won't be executed, so code size is larger
345    ///    than with the first approach.
346    ///
347    /// The static approach is better in most cases, however dynamically calling
348    /// `enable_compiler(false)` is useful whenever you create multiple
349    /// `Engine`s in the same process, some of which must be able to compile
350    /// Wasm and some of which should never do so. Tests are a common example of
351    /// such a situation, especially when there are multiple Rust binaries in
352    /// the same cargo workspace, and cargo's feature resolution enables the
353    /// `"cranelift"` or `"winch"` features across the whole workspace.
354    #[cfg(any(feature = "cranelift", feature = "winch"))]
355    pub fn enable_compiler(&mut self, enable: bool) -> &mut Self {
356        match (enable, &self.compiler_config) {
357            (true, Some(_)) | (false, None) => {}
358            (true, None) => {
359                self.compiler_config = Some(CompilerConfig::default());
360            }
361            (false, Some(_)) => {
362                self.compiler_config = None;
363            }
364        }
365        self
366    }
367
368    /// Configures the target platform of this [`Config`].
369    ///
370    /// This method is used to configure the output of compilation in an
371    /// [`Engine`](crate::Engine). This can be used, for example, to
372    /// cross-compile from one platform to another. By default, the host target
373    /// triple is used meaning compiled code is suitable to run on the host.
374    ///
375    /// Note that the [`Module`](crate::Module) type can only be created if the
376    /// target configured here matches the host. Otherwise if a cross-compile is
377    /// being performed where the host doesn't match the target then
378    /// [`Engine::precompile_module`](crate::Engine::precompile_module) must be
379    /// used instead.
380    ///
381    /// Target-specific flags (such as CPU features) will not be inferred by
382    /// default for the target when one is provided here. This means that this
383    /// can also be used, for example, with the host architecture to disable all
384    /// host-inferred feature flags. Configuring target-specific flags can be
385    /// done with [`Config::cranelift_flag_set`] and
386    /// [`Config::cranelift_flag_enable`].
387    ///
388    /// # Errors
389    ///
390    /// This method will error if the given target triple is not supported.
391    pub fn target(&mut self, target: &str) -> Result<&mut Self> {
392        self.target =
393            Some(target_lexicon::Triple::from_str(target).map_err(|e| crate::format_err!(e))?);
394
395        Ok(self)
396    }
397
398    /// Enables the incremental compilation cache in Cranelift, using the provided `CacheStore`
399    /// backend for storage.
400    ///
401    /// # Panics
402    ///
403    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
404    #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
405    pub fn enable_incremental_compilation(
406        &mut self,
407        cache_store: Arc<dyn CacheStore>,
408    ) -> Result<&mut Self> {
409        self.compiler_config_mut().cache_store = Some(cache_store);
410        Ok(self)
411    }
412
413    #[doc(hidden)]
414    #[deprecated(note = "no longer has any effect")]
415    #[cfg(feature = "async")]
416    pub fn async_support(&mut self, _enable: bool) -> &mut Self {
417        self
418    }
419
420    /// Configures whether DWARF debug information will be emitted
421    /// during compilation for a native debugger on the Wasmtime
422    /// process to consume.
423    ///
424    /// Note that the `debug-builtins` compile-time Cargo feature must also be
425    /// enabled for native debuggers such as GDB or LLDB to be able to debug
426    /// guest WebAssembly programs.
427    ///
428    /// By default this option is `false`.
429    /// **Note** Enabling this option is not compatible with the Winch compiler.
430    pub fn debug_info(&mut self, enable: bool) -> &mut Self {
431        self.tunables.debug_native = Some(enable);
432        self
433    }
434
435    /// Configures whether compiled guest code will be instrumented to
436    /// provide debugging at the Wasm VM level.
437    ///
438    /// This is required in order to enable a guest-level debugging
439    /// API that can precisely examine Wasm VM state and (eventually,
440    /// once it is complete) set breakpoints and watchpoints and step
441    /// through code.
442    ///
443    /// Without this enabled, debugging can only be done via a native
444    /// debugger operating on the compiled guest code (see
445    /// [`Config::debug_info`] and is "best-effort": we may be able to
446    /// recover some Wasm locals or operand stack values, but it is
447    /// not guaranteed, even when optimizations are disabled.
448    ///
449    /// When this is enabled, additional instrumentation is inserted
450    /// that directly tracks the Wasm VM state at every step. This has
451    /// some performance impact, but allows perfect debugging
452    /// fidelity.
453    ///
454    /// Breakpoints, watchpoints, and stepping are not yet supported,
455    /// but will be added in a future version of Wasmtime.
456    ///
457    /// This enables use of the [`crate::FrameHandle`] API which is
458    /// provided by [`crate::Caller::debug_exit_frames`] or
459    /// [`crate::Store::debug_exit_frames`].
460    ///
461    /// ***Note*** Enabling this option is not compatible with the
462    /// Winch compiler.
463    #[cfg(feature = "debug")]
464    pub fn guest_debug(&mut self, enable: bool) -> &mut Self {
465        self.tunables.debug_guest = Some(enable);
466        self
467    }
468
469    /// Configures whether [`WasmBacktrace`] will be present in the context of
470    /// errors returned from Wasmtime.
471    ///
472    /// This method is deprecated in favor of
473    /// [`Config::wasm_backtrace_max_frames`]. Calling `wasm_backtrace(false)`
474    /// is equivalent to `wasm_backtrace_max_frames(None)`, and
475    /// `wasm_backtrace(true)` will leave `wasm_backtrace_max_frames` unchanged
476    /// if the value is `Some` and will otherwise restore the default `Some`
477    /// value.
478    ///
479    /// [`WasmBacktrace`]: crate::WasmBacktrace
480    #[deprecated = "use `wasm_backtrace_max_frames` instead"]
481    pub fn wasm_backtrace(&mut self, enable: bool) -> &mut Self {
482        match (enable, self.wasm_backtrace_max_frames) {
483            (false, _) => self.wasm_backtrace_max_frames = None,
484            // Wasm backtraces were disabled; enable them with the
485            // default maximum number of frames to capture.
486            (true, None) => {
487                self.wasm_backtrace_max_frames = Some(DEFAULT_WASM_BACKTRACE_MAX_FRAMES)
488            }
489            // Wasm backtraces are already enabled; keep the existing
490            // max-frames configuration.
491            (true, Some(_)) => {}
492        }
493        self
494    }
495
496    /// Configures whether backtraces in `Trap` will parse debug info in the wasm file to
497    /// have filename/line number information.
498    ///
499    /// When enabled this will causes modules to retain debugging information
500    /// found in wasm binaries. This debug information will be used when a trap
501    /// happens to symbolicate each stack frame and attempt to print a
502    /// filename/line number for each wasm frame in the stack trace.
503    ///
504    /// By default this option is `WasmBacktraceDetails::Environment`, meaning
505    /// that wasm will read `WASMTIME_BACKTRACE_DETAILS` to indicate whether
506    /// details should be parsed. Note that the `std` feature of this crate must
507    /// be active to read environment variables, otherwise this is disabled by
508    /// default.
509    pub fn wasm_backtrace_details(&mut self, enable: WasmBacktraceDetails) -> &mut Self {
510        self.wasm_backtrace_details_env_used = false;
511        self.tunables.parse_wasm_debuginfo = match enable {
512            WasmBacktraceDetails::Enable => Some(true),
513            WasmBacktraceDetails::Disable => Some(false),
514            WasmBacktraceDetails::Environment => {
515                #[cfg(feature = "std")]
516                {
517                    self.wasm_backtrace_details_env_used = true;
518                    std::env::var("WASMTIME_BACKTRACE_DETAILS")
519                        .map(|s| Some(s == "1"))
520                        .unwrap_or(Some(false))
521                }
522                #[cfg(not(feature = "std"))]
523                {
524                    Some(false)
525                }
526            }
527        };
528        self
529    }
530
531    /// Configures the maximum number of WebAssembly frames to collect in
532    /// backtraces.
533    ///
534    /// A backtrace may be collected whenever an error is returned from a host
535    /// function call through to WebAssembly or when WebAssembly itself hits a
536    /// trap condition, such as an out-of-bounds memory access. This flag
537    /// indicates, in these conditions, whether the backtrace is collected or
538    /// not and how many frames should be collected.
539    ///
540    /// Currently wasm backtraces are implemented through frame pointer walking.
541    /// This means that collecting a backtrace is expected to be a fast and
542    /// relatively cheap operation. Additionally backtrace collection is
543    /// suitable in concurrent environments since one thread capturing a
544    /// backtrace won't block other threads.
545    ///
546    /// Collected backtraces are attached via
547    /// [`Error::context`](crate::Error::context) to errors returned from host
548    /// functions. The [`WasmBacktrace`] type can be acquired via
549    /// [`Error::downcast_ref`](crate::Error::downcast_ref) to inspect the
550    /// backtrace. When this option is set to `None` then this context is never
551    /// applied to errors coming out of wasm.
552    ///
553    /// The default value is 20.
554    ///
555    /// [`WasmBacktrace`]: crate::WasmBacktrace
556    pub fn wasm_backtrace_max_frames(&mut self, limit: Option<NonZeroUsize>) -> &mut Self {
557        self.wasm_backtrace_max_frames = limit;
558        self
559    }
560
561    /// Configures whether to generate native unwind information
562    /// (e.g. `.eh_frame` on Linux).
563    ///
564    /// This configuration option only exists to help third-party stack
565    /// capturing mechanisms, such as the system's unwinder or the `backtrace`
566    /// crate, determine how to unwind through Wasm frames. It does not affect
567    /// whether Wasmtime can capture Wasm backtraces or not. The presence of
568    /// [`WasmBacktrace`] is controlled by the
569    /// [`Config::wasm_backtrace_max_frames`] option.
570    ///
571    /// Native unwind information is included:
572    /// - When targeting Windows, since the Windows ABI requires it.
573    /// - By default.
574    ///
575    /// Note that systems loading many modules may wish to disable this
576    /// configuration option instead of leaving it on-by-default. Some platforms
577    /// exhibit quadratic behavior when registering/unregistering unwinding
578    /// information which can greatly slow down the module loading/unloading
579    /// process.
580    ///
581    /// [`WasmBacktrace`]: crate::WasmBacktrace
582    pub fn native_unwind_info(&mut self, enable: bool) -> &mut Self {
583        self.native_unwind_info = Some(enable);
584        self
585    }
586
587    /// Configures whether execution of WebAssembly will "consume fuel" to
588    /// either halt or yield execution as desired.
589    ///
590    /// This can be used to deterministically prevent infinitely-executing
591    /// WebAssembly code by instrumenting generated code to consume fuel as it
592    /// executes. When fuel runs out a trap is raised, however [`Store`] can be
593    /// configured to yield execution periodically via
594    /// [`crate::Store::fuel_async_yield_interval`].
595    ///
596    /// Note that a [`Store`] starts with no fuel, so if you enable this option
597    /// you'll have to be sure to pour some fuel into [`Store`] before
598    /// executing some code.
599    ///
600    /// By default this option is `false`.
601    ///
602    /// **Note** Enabling this option is not compatible with the Winch compiler.
603    ///
604    /// [`Store`]: crate::Store
605    pub fn consume_fuel(&mut self, enable: bool) -> &mut Self {
606        self.tunables.consume_fuel = Some(enable);
607        self
608    }
609
610    /// Configures the fuel cost of each WebAssembly operator.
611    ///
612    /// This is only relevant when [`Config::consume_fuel`] is enabled.
613    pub fn operator_cost(&mut self, cost: OperatorCost) -> &mut Self {
614        self.tunables.operator_cost = Some(OperatorCostStrategy::table(cost));
615        self
616    }
617
618    /// Enables epoch-based interruption.
619    ///
620    /// When executing code in async mode, we sometimes want to
621    /// implement a form of cooperative timeslicing: long-running Wasm
622    /// guest code should periodically yield to the executor
623    /// loop. This yielding could be implemented by using "fuel" (see
624    /// [`consume_fuel`](Config::consume_fuel)). However, fuel
625    /// instrumentation is somewhat expensive: it modifies the
626    /// compiled form of the Wasm code so that it maintains a precise
627    /// instruction count, frequently checking this count against the
628    /// remaining fuel. If one does not need this precise count or
629    /// deterministic interruptions, and only needs a periodic
630    /// interrupt of some form, then It would be better to have a more
631    /// lightweight mechanism.
632    ///
633    /// Epoch-based interruption is that mechanism. There is a global
634    /// "epoch", which is a counter that divides time into arbitrary
635    /// periods (or epochs). This counter lives on the
636    /// [`Engine`](crate::Engine) and can be incremented by calling
637    /// [`Engine::increment_epoch`](crate::Engine::increment_epoch).
638    /// Epoch-based instrumentation works by setting a "deadline
639    /// epoch". The compiled code knows the deadline, and at certain
640    /// points, checks the current epoch against that deadline. It
641    /// will yield if the deadline has been reached.
642    ///
643    /// The idea is that checking an infrequently-changing counter is
644    /// cheaper than counting and frequently storing a precise metric
645    /// (instructions executed) locally. The interruptions are not
646    /// deterministic, but if the embedder increments the epoch in a
647    /// periodic way (say, every regular timer tick by a thread or
648    /// signal handler), then we can ensure that all async code will
649    /// yield to the executor within a bounded time.
650    ///
651    /// The deadline check cannot be avoided by malicious wasm code. It is safe
652    /// to use epoch deadlines to limit the execution time of untrusted
653    /// code.
654    ///
655    /// The [`Store`](crate::Store) tracks the deadline, and controls
656    /// what happens when the deadline is reached during
657    /// execution. Several behaviors are possible:
658    ///
659    /// - Trap if code is executing when the epoch deadline is
660    ///   met. See
661    ///   [`Store::epoch_deadline_trap`](crate::Store::epoch_deadline_trap).
662    ///
663    /// - Call an arbitrary function. This function may chose to trap or
664    ///   increment the epoch. See
665    ///   [`Store::epoch_deadline_callback`](crate::Store::epoch_deadline_callback).
666    ///
667    /// - Yield to the executor loop, then resume when the future is
668    ///   next polled. See
669    ///   [`Store::epoch_deadline_async_yield_and_update`](crate::Store::epoch_deadline_async_yield_and_update).
670    ///
671    /// Trapping is the default. The yielding behaviour may be used for
672    /// the timeslicing behavior described above.
673    ///
674    /// This feature is available with or without async support.
675    /// However, without async support, the timeslicing behaviour is
676    /// not available. This means epoch-based interruption can only
677    /// serve as a simple external-interruption mechanism.
678    ///
679    /// An initial deadline must be set before executing code by calling
680    /// [`Store::set_epoch_deadline`](crate::Store::set_epoch_deadline). If this
681    /// deadline is not configured then wasm will immediately trap.
682    ///
683    /// ## Interaction with blocking host calls
684    ///
685    /// Epochs (and fuel) do not assist in handling WebAssembly code blocked in
686    /// a call to the host. For example if the WebAssembly function calls
687    /// `wasi:io/poll.poll` to sleep epochs will not assist in waking this up or
688    /// timing it out. Epochs intentionally only affect running WebAssembly code
689    /// itself and it's left to the embedder to determine how best to wake up
690    /// indefinitely blocking code in the host.
691    ///
692    /// The typical solution for this, however, is to use the `async` variant of
693    /// WASI host functions. This models computation as a Rust `Future` which
694    /// means that when blocking happens the future is only suspended and
695    /// control yields back to the main event loop. This gives the embedder the
696    /// opportunity to use `tokio::time::timeout` for example on a wasm
697    /// computation and have the desired effect of cancelling a blocking
698    /// operation when a timeout expires.
699    ///
700    /// ## When to use fuel vs. epochs
701    ///
702    /// In general, epoch-based interruption results in faster
703    /// execution. This difference is sometimes significant: in some
704    /// measurements, up to 2-3x. This is because epoch-based
705    /// interruption does less work: it only watches for a global
706    /// rarely-changing counter to increment, rather than keeping a
707    /// local frequently-changing counter and comparing it to a
708    /// deadline.
709    ///
710    /// Fuel, in contrast, should be used when *deterministic*
711    /// yielding or trapping is needed. For example, if it is required
712    /// that the same function call with the same starting state will
713    /// always either complete or trap with an out-of-fuel error,
714    /// deterministically, then fuel with a fixed bound should be
715    /// used.
716    ///
717    /// **Note** Enabling this option is not compatible with the Winch compiler.
718    ///
719    /// # See Also
720    ///
721    /// - [`Engine::increment_epoch`](crate::Engine::increment_epoch)
722    /// - [`Store::set_epoch_deadline`](crate::Store::set_epoch_deadline)
723    /// - [`Store::epoch_deadline_trap`](crate::Store::epoch_deadline_trap)
724    /// - [`Store::epoch_deadline_callback`](crate::Store::epoch_deadline_callback)
725    /// - [`Store::epoch_deadline_async_yield_and_update`](crate::Store::epoch_deadline_async_yield_and_update)
726    pub fn epoch_interruption(&mut self, enable: bool) -> &mut Self {
727        self.tunables.epoch_interruption = Some(enable);
728        self
729    }
730
731    /// Configures the maximum amount of stack space available for
732    /// executing WebAssembly code.
733    ///
734    /// WebAssembly has well-defined semantics on stack overflow. This is
735    /// intended to be a knob which can help configure how much stack space
736    /// wasm execution is allowed to consume. Note that the number here is not
737    /// super-precise, but rather wasm will take at most "pretty close to this
738    /// much" stack space.
739    ///
740    /// If a wasm call (or series of nested wasm calls) take more stack space
741    /// than the `size` specified then a stack overflow trap will be raised.
742    ///
743    /// Caveat: this knob only limits the stack space consumed by wasm code.
744    /// More importantly, it does not ensure that this much stack space is
745    /// available on the calling thread stack. Exhausting the thread stack
746    /// typically leads to an **abort** of the process.
747    ///
748    /// Here are some examples of how that could happen:
749    ///
750    /// - Let's assume this option is set to 2 MiB and then a thread that has
751    ///   a stack with 512 KiB left.
752    ///
753    ///   If wasm code consumes more than 512 KiB then the process will be aborted.
754    ///
755    /// - Assuming the same conditions, but this time wasm code does not consume
756    ///   any stack but calls into a host function. The host function consumes
757    ///   more than 512 KiB of stack space. The process will be aborted.
758    ///
759    /// There's another gotcha related to recursive calling into wasm: the stack
760    /// space consumed by a host function is counted towards this limit. The
761    /// host functions are not prevented from consuming more than this limit.
762    /// However, if the host function that used more than this limit and called
763    /// back into wasm, then the execution will trap immediately because of
764    /// stack overflow.
765    ///
766    /// When the `async` feature is enabled, this value cannot exceed the
767    /// `async_stack_size` option. Be careful not to set this value too close
768    /// to `async_stack_size` as doing so may limit how much stack space
769    /// is available for host functions.
770    ///
771    /// By default this option is 512 KiB.
772    ///
773    /// # Errors
774    ///
775    /// The `Engine::new` method will fail if the `size` specified here is
776    /// either 0 or larger than the [`Config::async_stack_size`] configuration.
777    pub fn max_wasm_stack(&mut self, size: usize) -> &mut Self {
778        self.max_wasm_stack = size;
779        self
780    }
781
782    /// Configures the size of the stacks used for asynchronous execution.
783    ///
784    /// This setting configures the size of the stacks that are allocated for
785    /// asynchronous execution. The value cannot be less than `max_wasm_stack`.
786    ///
787    /// The amount of stack space guaranteed for host functions is
788    /// `async_stack_size - max_wasm_stack`, so take care not to set these two values
789    /// close to one another; doing so may cause host functions to overflow the
790    /// stack and abort the process.
791    ///
792    /// By default this option is 2 MiB.
793    ///
794    /// # Errors
795    ///
796    /// The `Engine::new` method will fail if the value for this option is
797    /// smaller than the [`Config::max_wasm_stack`] option.
798    #[cfg(any(feature = "async", feature = "stack-switching"))]
799    pub fn async_stack_size(&mut self, size: usize) -> &mut Self {
800        self.async_stack_size = size;
801        self
802    }
803
804    /// Configures whether or not stacks used for async futures are zeroed
805    /// before (re)use.
806    ///
807    /// When the [`call_async`] variant of calling WebAssembly is used
808    /// then Wasmtime will create a separate runtime execution stack for each
809    /// future produced by [`call_async`]. By default upon allocation, depending
810    /// on the platform, these stacks might be filled with uninitialized
811    /// memory. This is safe and correct because, modulo bugs in Wasmtime,
812    /// compiled Wasm code will never read from a stack slot before it
813    /// initializes the stack slot.
814    ///
815    /// However, as a defense-in-depth mechanism, you may configure Wasmtime to
816    /// ensure that these stacks are zeroed before they are used. Notably, if
817    /// you are using the pooling allocator, stacks can be pooled and reused
818    /// across different Wasm guests; ensuring that stacks are zeroed can
819    /// prevent data leakage between Wasm guests even in the face of potential
820    /// read-of-stack-slot-before-initialization bugs in Wasmtime's compiler.
821    ///
822    /// Stack zeroing can be a costly operation in highly concurrent
823    /// environments due to modifications of the virtual address space requiring
824    /// process-wide synchronization. It can also be costly in `no-std`
825    /// environments that must manually zero memory, and cannot rely on an OS
826    /// and virtual memory to provide zeroed pages.
827    ///
828    /// This option defaults to `false`.
829    ///
830    /// [`call_async`]: crate::TypedFunc::call_async
831    #[cfg(feature = "async")]
832    pub fn async_stack_zeroing(&mut self, enable: bool) -> &mut Self {
833        self.async_stack_zeroing = enable;
834        self
835    }
836
837    /// Explicitly enables (and un-disables) a given set of [`WasmFeatures`].
838    ///
839    /// Note: this is a low-level method that does not necessarily imply that
840    /// wasmtime _supports_ a feature. It should only be used to _disable_
841    /// features that callers want to be rejected by the parser or _enable_
842    /// features callers are certain that the current configuration of wasmtime
843    /// supports.
844    ///
845    /// Feature validation is deferred until an engine is being built, thus by
846    /// enabling features here a caller may cause
847    /// [`Engine::new`](crate::Engine::new) to fail later, if the feature
848    /// configuration isn't supported.
849    pub fn wasm_features(&mut self, flag: WasmFeatures, enable: bool) -> &mut Self {
850        self.enabled_features.set(flag, enable);
851        self.disabled_features.set(flag, !enable);
852        self
853    }
854
855    /// Configures whether the WebAssembly tail calls proposal will be enabled
856    /// for compilation or not.
857    ///
858    /// The [WebAssembly tail calls proposal] introduces the `return_call` and
859    /// `return_call_indirect` instructions. These instructions allow for Wasm
860    /// programs to implement some recursive algorithms with *O(1)* stack space
861    /// usage.
862    ///
863    /// This is `true` by default except when the Winch compiler is enabled.
864    ///
865    /// [WebAssembly tail calls proposal]: https://github.com/WebAssembly/tail-call
866    pub fn wasm_tail_call(&mut self, enable: bool) -> &mut Self {
867        self.wasm_features(WasmFeatures::TAIL_CALL, enable);
868        self
869    }
870
871    /// Configures whether the WebAssembly custom-page-sizes proposal will be
872    /// enabled for compilation or not.
873    ///
874    /// The [WebAssembly custom-page-sizes proposal] allows a memory to
875    /// customize its page sizes. By default, Wasm page sizes are 64KiB
876    /// large. This proposal allows the memory to opt into smaller page sizes
877    /// instead, allowing Wasm to run in environments with less than 64KiB RAM
878    /// available, for example.
879    ///
880    /// Note that the page size is part of the memory's type, and because
881    /// different memories may have different types, they may also have
882    /// different page sizes.
883    ///
884    /// Currently the only valid page sizes are 64KiB (the default) and 1
885    /// byte. Future extensions may relax this constraint and allow all powers
886    /// of two.
887    ///
888    /// Support for this proposal is disabled by default.
889    ///
890    /// [WebAssembly custom-page-sizes proposal]: https://github.com/WebAssembly/custom-page-sizes
891    pub fn wasm_custom_page_sizes(&mut self, enable: bool) -> &mut Self {
892        self.wasm_features(WasmFeatures::CUSTOM_PAGE_SIZES, enable);
893        self
894    }
895
896    /// Configures whether the WebAssembly [threads] proposal will be enabled
897    /// for compilation.
898    ///
899    /// This feature gates items such as shared memories and atomic
900    /// instructions. Note that the threads feature depends on the bulk memory
901    /// feature, which is enabled by default. Additionally note that while the
902    /// wasm feature is called "threads" it does not actually include the
903    /// ability to spawn threads. Spawning threads is part of the [wasi-threads]
904    /// proposal which is a separately gated feature in Wasmtime.
905    ///
906    /// Embeddings of Wasmtime are able to build their own custom threading
907    /// scheme on top of the core wasm threads proposal, however.
908    ///
909    /// The default value for this option is whether the `threads`
910    /// crate feature of Wasmtime is enabled or not. By default this crate
911    /// feature is enabled.
912    ///
913    /// [threads]: https://github.com/webassembly/threads
914    /// [wasi-threads]: https://github.com/webassembly/wasi-threads
915    #[cfg(feature = "threads")]
916    pub fn wasm_threads(&mut self, enable: bool) -> &mut Self {
917        self.wasm_features(WasmFeatures::THREADS, enable);
918        self
919    }
920
921    /// Configures whether the WebAssembly [shared-everything-threads] proposal
922    /// will be enabled for compilation.
923    ///
924    /// This feature gates extended use of the `shared` attribute on items other
925    /// than memories, extra atomic instructions, and new component model
926    /// intrinsics for spawning threads. It depends on the
927    /// [`wasm_threads`][Self::wasm_threads] being enabled.
928    ///
929    /// [shared-everything-threads]:
930    ///     https://github.com/webassembly/shared-everything-threads
931    pub fn wasm_shared_everything_threads(&mut self, enable: bool) -> &mut Self {
932        self.wasm_features(WasmFeatures::SHARED_EVERYTHING_THREADS, enable);
933        self
934    }
935
936    /// Configures whether the [WebAssembly reference types proposal][proposal]
937    /// will be enabled for compilation.
938    ///
939    /// This feature gates items such as the `externref` and `funcref` types as
940    /// well as allowing a module to define multiple tables.
941    ///
942    /// Note that the reference types proposal depends on the bulk memory proposal.
943    ///
944    /// This feature is `true` by default.
945    ///
946    /// # Errors
947    ///
948    /// The validation of this feature are deferred until the engine is being built,
949    /// and thus may cause `Engine::new` fail if the `bulk_memory` feature is disabled.
950    ///
951    /// [proposal]: https://github.com/webassembly/reference-types
952    #[cfg(feature = "gc")]
953    pub fn wasm_reference_types(&mut self, enable: bool) -> &mut Self {
954        self.wasm_features(WasmFeatures::REFERENCE_TYPES, enable);
955        self
956    }
957
958    /// Configures whether the [WebAssembly function references
959    /// proposal][proposal] will be enabled for compilation.
960    ///
961    /// This feature gates non-nullable reference types, function reference
962    /// types, `call_ref`, `ref.func`, and non-nullable reference related
963    /// instructions.
964    ///
965    /// Note that the function references proposal depends on the reference
966    /// types proposal.
967    ///
968    /// This feature is `false` by default.
969    ///
970    /// [proposal]: https://github.com/WebAssembly/function-references
971    #[cfg(feature = "gc")]
972    pub fn wasm_function_references(&mut self, enable: bool) -> &mut Self {
973        self.wasm_features(WasmFeatures::FUNCTION_REFERENCES, enable);
974        self
975    }
976
977    /// Configures whether the [WebAssembly wide-arithmetic][proposal] will be
978    /// enabled for compilation.
979    ///
980    /// This feature is `false` by default.
981    ///
982    /// [proposal]: https://github.com/WebAssembly/wide-arithmetic
983    pub fn wasm_wide_arithmetic(&mut self, enable: bool) -> &mut Self {
984        self.wasm_features(WasmFeatures::WIDE_ARITHMETIC, enable);
985        self
986    }
987
988    /// Configures whether the [WebAssembly Garbage Collection
989    /// proposal][proposal] will be enabled for compilation.
990    ///
991    /// This feature gates `struct` and `array` type definitions and references,
992    /// the `i31ref` type, and all related instructions.
993    ///
994    /// Note that the function references proposal depends on the typed function
995    /// references proposal.
996    ///
997    /// This feature is `false` by default.
998    ///
999    /// **Warning: Wasmtime's implementation of the GC proposal is still in
1000    /// progress and generally not ready for primetime.**
1001    ///
1002    /// [proposal]: https://github.com/WebAssembly/gc
1003    #[cfg(feature = "gc")]
1004    pub fn wasm_gc(&mut self, enable: bool) -> &mut Self {
1005        self.wasm_features(WasmFeatures::GC, enable);
1006        self
1007    }
1008
1009    /// Configures whether the WebAssembly SIMD proposal will be
1010    /// enabled for compilation.
1011    ///
1012    /// The [WebAssembly SIMD proposal][proposal]. This feature gates items such
1013    /// as the `v128` type and all of its operators being in a module. Note that
1014    /// this does not enable the [relaxed simd proposal].
1015    ///
1016    /// **Note**
1017    ///
1018    /// On x86_64 platforms the base CPU feature requirement for SIMD
1019    /// is SSE2 for the Cranelift compiler and AVX for the Winch compiler.
1020    ///
1021    /// This is `true` by default.
1022    ///
1023    /// [proposal]: https://github.com/webassembly/simd
1024    /// [relaxed simd proposal]: https://github.com/WebAssembly/relaxed-simd
1025    pub fn wasm_simd(&mut self, enable: bool) -> &mut Self {
1026        self.wasm_features(WasmFeatures::SIMD, enable);
1027        self
1028    }
1029
1030    /// Configures whether the WebAssembly Relaxed SIMD proposal will be
1031    /// enabled for compilation.
1032    ///
1033    /// The relaxed SIMD proposal adds new instructions to WebAssembly which,
1034    /// for some specific inputs, are allowed to produce different results on
1035    /// different hosts. More-or-less this proposal enables exposing
1036    /// platform-specific semantics of SIMD instructions in a controlled
1037    /// fashion to a WebAssembly program. From an embedder's perspective this
1038    /// means that WebAssembly programs may execute differently depending on
1039    /// whether the host is x86_64 or AArch64, for example.
1040    ///
1041    /// By default Wasmtime lowers relaxed SIMD instructions to the fastest
1042    /// lowering for the platform it's running on. This means that, by default,
1043    /// some relaxed SIMD instructions may have different results for the same
1044    /// inputs across x86_64 and AArch64. This behavior can be disabled through
1045    /// the [`Config::relaxed_simd_deterministic`] option which will force
1046    /// deterministic behavior across all platforms, as classified by the
1047    /// specification, at the cost of performance.
1048    ///
1049    /// This is `true` by default.
1050    ///
1051    /// [proposal]: https://github.com/webassembly/relaxed-simd
1052    pub fn wasm_relaxed_simd(&mut self, enable: bool) -> &mut Self {
1053        self.wasm_features(WasmFeatures::RELAXED_SIMD, enable);
1054        self
1055    }
1056
1057    /// This option can be used to control the behavior of the [relaxed SIMD
1058    /// proposal's][proposal] instructions.
1059    ///
1060    /// The relaxed SIMD proposal introduces instructions that are allowed to
1061    /// have different behavior on different architectures, primarily to afford
1062    /// an efficient implementation on all architectures. This means, however,
1063    /// that the same module may execute differently on one host than another,
1064    /// which typically is not otherwise the case. This option is provided to
1065    /// force Wasmtime to generate deterministic code for all relaxed simd
1066    /// instructions, at the cost of performance, for all architectures. When
1067    /// this option is enabled then the deterministic behavior of all
1068    /// instructions in the relaxed SIMD proposal is selected.
1069    ///
1070    /// This is `false` by default.
1071    ///
1072    /// [proposal]: https://github.com/webassembly/relaxed-simd
1073    pub fn relaxed_simd_deterministic(&mut self, enable: bool) -> &mut Self {
1074        self.tunables.relaxed_simd_deterministic = Some(enable);
1075        self
1076    }
1077
1078    /// Configures whether the [WebAssembly bulk memory operations
1079    /// proposal][proposal] will be enabled for compilation.
1080    ///
1081    /// This feature gates items such as the `memory.copy` instruction, passive
1082    /// data/table segments, etc, being in a module.
1083    ///
1084    /// This is `true` by default.
1085    ///
1086    /// Feature `reference_types`, which is also `true` by default, requires
1087    /// this feature to be enabled. Thus disabling this feature must also disable
1088    /// `reference_types` as well using [`wasm_reference_types`](crate::Config::wasm_reference_types).
1089    ///
1090    /// # Errors
1091    ///
1092    /// Disabling this feature without disabling `reference_types` will cause
1093    /// `Engine::new` to fail.
1094    ///
1095    /// [proposal]: https://github.com/webassembly/bulk-memory-operations
1096    pub fn wasm_bulk_memory(&mut self, enable: bool) -> &mut Self {
1097        self.wasm_features(WasmFeatures::BULK_MEMORY, enable);
1098        self
1099    }
1100
1101    /// Configures whether the WebAssembly multi-value [proposal] will
1102    /// be enabled for compilation.
1103    ///
1104    /// This feature gates functions and blocks returning multiple values in a
1105    /// module, for example.
1106    ///
1107    /// This is `true` by default.
1108    ///
1109    /// [proposal]: https://github.com/webassembly/multi-value
1110    pub fn wasm_multi_value(&mut self, enable: bool) -> &mut Self {
1111        self.wasm_features(WasmFeatures::MULTI_VALUE, enable);
1112        self
1113    }
1114
1115    /// Configures whether the WebAssembly multi-memory [proposal] will
1116    /// be enabled for compilation.
1117    ///
1118    /// This feature gates modules having more than one linear memory
1119    /// declaration or import.
1120    ///
1121    /// This is `true` by default.
1122    ///
1123    /// [proposal]: https://github.com/webassembly/multi-memory
1124    pub fn wasm_multi_memory(&mut self, enable: bool) -> &mut Self {
1125        self.wasm_features(WasmFeatures::MULTI_MEMORY, enable);
1126        self
1127    }
1128
1129    /// Configures whether the WebAssembly memory64 [proposal] will
1130    /// be enabled for compilation.
1131    ///
1132    /// Note that this the upstream specification is not finalized and Wasmtime
1133    /// may also have bugs for this feature since it hasn't been exercised
1134    /// much.
1135    ///
1136    /// This is `false` by default.
1137    ///
1138    /// [proposal]: https://github.com/webassembly/memory64
1139    pub fn wasm_memory64(&mut self, enable: bool) -> &mut Self {
1140        self.wasm_features(WasmFeatures::MEMORY64, enable);
1141        self
1142    }
1143
1144    /// Configures whether the WebAssembly extended-const [proposal] will
1145    /// be enabled for compilation.
1146    ///
1147    /// This is `true` by default.
1148    ///
1149    /// [proposal]: https://github.com/webassembly/extended-const
1150    pub fn wasm_extended_const(&mut self, enable: bool) -> &mut Self {
1151        self.wasm_features(WasmFeatures::EXTENDED_CONST, enable);
1152        self
1153    }
1154
1155    /// Configures whether the [WebAssembly stack switching
1156    /// proposal][proposal] will be enabled for compilation.
1157    ///
1158    /// This feature gates the use of control tags.
1159    ///
1160    /// This feature depends on the `function_reference_types` and
1161    /// `exceptions` features.
1162    ///
1163    /// This feature is `false` by default.
1164    ///
1165    /// # Errors
1166    ///
1167    /// [proposal]: https://github.com/webassembly/stack-switching
1168    pub fn wasm_stack_switching(&mut self, enable: bool) -> &mut Self {
1169        self.wasm_features(WasmFeatures::STACK_SWITCHING, enable);
1170        self
1171    }
1172
1173    /// Configures whether the WebAssembly component-model [proposal] will
1174    /// be enabled for compilation.
1175    ///
1176    /// This flag can be used to blanket disable all components within Wasmtime.
1177    /// Otherwise usage of components requires statically using
1178    /// [`Component`](crate::component::Component) instead of
1179    /// [`Module`](crate::Module) for example anyway.
1180    ///
1181    /// The default value for this option is whether the `component-model`
1182    /// crate feature of Wasmtime is enabled or not. By default this crate
1183    /// feature is enabled.
1184    ///
1185    /// [proposal]: https://github.com/webassembly/component-model
1186    #[cfg(feature = "component-model")]
1187    pub fn wasm_component_model(&mut self, enable: bool) -> &mut Self {
1188        self.wasm_features(WasmFeatures::COMPONENT_MODEL, enable);
1189        self
1190    }
1191
1192    /// Configures whether components support the async ABI [proposal] for
1193    /// lifting and lowering functions, as well as `stream`, `future`, and
1194    /// `error-context` types.
1195    ///
1196    /// Please note that Wasmtime's support for this feature is _very_
1197    /// incomplete.
1198    ///
1199    /// [proposal]:
1200    ///     https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1201    #[cfg(feature = "component-model-async")]
1202    pub fn wasm_component_model_async(&mut self, enable: bool) -> &mut Self {
1203        self.wasm_features(WasmFeatures::CM_ASYNC, enable);
1204        self
1205    }
1206
1207    /// This corresponds to the 🚝 emoji in the component model specification.
1208    ///
1209    /// Please note that Wasmtime's support for this feature is _very_
1210    /// incomplete.
1211    ///
1212    /// [proposal]:
1213    ///     https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1214    #[cfg(feature = "component-model-async")]
1215    pub fn wasm_component_model_async_builtins(&mut self, enable: bool) -> &mut Self {
1216        self.wasm_features(WasmFeatures::CM_ASYNC_BUILTINS, enable);
1217        self
1218    }
1219
1220    /// This corresponds to the 🚟 emoji in the component model specification.
1221    ///
1222    /// Please note that Wasmtime's support for this feature is _very_
1223    /// incomplete.
1224    ///
1225    /// [proposal]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1226    #[cfg(feature = "component-model-async")]
1227    pub fn wasm_component_model_async_stackful(&mut self, enable: bool) -> &mut Self {
1228        self.wasm_features(WasmFeatures::CM_ASYNC_STACKFUL, enable);
1229        self
1230    }
1231
1232    /// This corresponds to the 🧵 emoji in the component model specification.
1233    ///
1234    /// Please note that Wasmtime's support for this feature is _very_
1235    /// incomplete.
1236    ///
1237    /// [proposal]:
1238    ///     https://github.com/WebAssembly/component-model/pull/557
1239    #[cfg(feature = "component-model-async")]
1240    pub fn wasm_component_model_threading(&mut self, enable: bool) -> &mut Self {
1241        self.wasm_features(WasmFeatures::CM_THREADING, enable);
1242        self
1243    }
1244
1245    /// This corresponds to the 📝 emoji in the component model specification.
1246    ///
1247    /// Please note that Wasmtime's support for this feature is _very_
1248    /// incomplete.
1249    ///
1250    /// [proposal]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/Concurrency.md
1251    #[cfg(feature = "component-model")]
1252    pub fn wasm_component_model_error_context(&mut self, enable: bool) -> &mut Self {
1253        self.wasm_features(WasmFeatures::CM_ERROR_CONTEXT, enable);
1254        self
1255    }
1256
1257    /// Configures whether the [GC extension to the component-model
1258    /// proposal][proposal] is enabled or not.
1259    ///
1260    /// This corresponds to the 🛸 emoji in the component model specification.
1261    ///
1262    /// Please note that Wasmtime's support for this feature is _very_
1263    /// incomplete.
1264    ///
1265    /// [proposal]: https://github.com/WebAssembly/component-model/issues/525
1266    #[cfg(feature = "component-model")]
1267    pub fn wasm_component_model_gc(&mut self, enable: bool) -> &mut Self {
1268        self.wasm_features(WasmFeatures::CM_GC, enable);
1269        self
1270    }
1271
1272    /// This corresponds to the 🔧 emoji in the component model specification.
1273    ///
1274    /// Please note that Wasmtime's support for this feature is _very_
1275    /// incomplete.
1276    #[cfg(feature = "component-model")]
1277    pub fn wasm_component_model_fixed_length_lists(&mut self, enable: bool) -> &mut Self {
1278        self.wasm_features(WasmFeatures::CM_FIXED_LENGTH_LISTS, enable);
1279        self
1280    }
1281
1282    /// Configures whether the [Exception-handling proposal][proposal] is enabled or not.
1283    ///
1284    /// [proposal]: https://github.com/WebAssembly/exception-handling
1285    #[cfg(feature = "gc")]
1286    pub fn wasm_exceptions(&mut self, enable: bool) -> &mut Self {
1287        self.wasm_features(WasmFeatures::EXCEPTIONS, enable);
1288        self
1289    }
1290
1291    #[doc(hidden)] // FIXME(#3427) - if/when implemented then un-hide this
1292    #[deprecated = "This configuration option only exists for internal \
1293                    usage with the spec testsuite. It may be removed at \
1294                    any time and without warning. Do not rely on it!"]
1295    pub fn wasm_legacy_exceptions(&mut self, enable: bool) -> &mut Self {
1296        self.wasm_features(WasmFeatures::LEGACY_EXCEPTIONS, enable);
1297        self
1298    }
1299
1300    /// Configures which compilation strategy will be used for wasm modules.
1301    ///
1302    /// This method can be used to configure which compiler is used for wasm
1303    /// modules, and for more documentation consult the [`Strategy`] enumeration
1304    /// and its documentation.
1305    ///
1306    /// The default value for this is `Strategy::Auto`.
1307    ///
1308    /// # Panics
1309    ///
1310    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1311    #[cfg(any(feature = "cranelift", feature = "winch"))]
1312    pub fn strategy(&mut self, strategy: Strategy) -> &mut Self {
1313        self.compiler_config_mut().strategy = strategy.not_auto();
1314        self
1315    }
1316
1317    /// Configures which garbage collector will be used for Wasm modules.
1318    ///
1319    /// This method can be used to configure which garbage collector
1320    /// implementation is used for Wasm modules. For more documentation, consult
1321    /// the [`Collector`] enumeration and its documentation.
1322    ///
1323    /// The default value for this is `Collector::Auto`.
1324    #[cfg(feature = "gc")]
1325    pub fn collector(&mut self, collector: Collector) -> &mut Self {
1326        self.collector = collector;
1327        self
1328    }
1329
1330    /// Creates a default profiler based on the profiling strategy chosen.
1331    ///
1332    /// Profiler creation calls the type's default initializer where the purpose is
1333    /// really just to put in place the type used for profiling.
1334    ///
1335    /// Some [`ProfilingStrategy`] require specific platforms or particular feature
1336    /// to be enabled, such as `ProfilingStrategy::JitDump` requires the `jitdump`
1337    /// feature.
1338    ///
1339    /// # Errors
1340    ///
1341    /// The validation of this field is deferred until the engine is being built, and thus may
1342    /// cause `Engine::new` fail if the required feature is disabled, or the platform is not
1343    /// supported.
1344    pub fn profiler(&mut self, profile: ProfilingStrategy) -> &mut Self {
1345        self.profiling_strategy = profile;
1346        self
1347    }
1348
1349    /// Configures whether the debug verifier of Cranelift is enabled or not.
1350    ///
1351    /// When Cranelift is used as a code generation backend this will configure
1352    /// it to have the `enable_verifier` flag which will enable a number of debug
1353    /// checks inside of Cranelift. This is largely only useful for the
1354    /// developers of wasmtime itself.
1355    ///
1356    /// The default value for this is `false`
1357    ///
1358    /// # Panics
1359    ///
1360    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1361    #[cfg(any(feature = "cranelift", feature = "winch"))]
1362    pub fn cranelift_debug_verifier(&mut self, enable: bool) -> &mut Self {
1363        let val = if enable { "true" } else { "false" };
1364        self.compiler_config_mut()
1365            .settings
1366            .insert("enable_verifier".to_string(), val.to_string());
1367        self
1368    }
1369
1370    /// Configures whether extra debug checks are inserted into
1371    /// Wasmtime-generated code by Cranelift.
1372    ///
1373    /// The default value for this is `false`
1374    ///
1375    /// # Panics
1376    ///
1377    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1378    #[cfg(any(feature = "cranelift", feature = "winch"))]
1379    pub fn cranelift_wasmtime_debug_checks(&mut self, enable: bool) -> &mut Self {
1380        unsafe { self.cranelift_flag_set("wasmtime_debug_checks", &enable.to_string()) }
1381    }
1382
1383    /// Configures the Cranelift code generator optimization level.
1384    ///
1385    /// When the Cranelift code generator is used you can configure the
1386    /// optimization level used for generated code in a few various ways. For
1387    /// more information see the documentation of [`OptLevel`].
1388    ///
1389    /// The default value for this is `OptLevel::Speed`.
1390    ///
1391    /// # Panics
1392    ///
1393    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1394    #[cfg(any(feature = "cranelift", feature = "winch"))]
1395    pub fn cranelift_opt_level(&mut self, level: OptLevel) -> &mut Self {
1396        let val = match level {
1397            OptLevel::None => "none",
1398            OptLevel::Speed => "speed",
1399            OptLevel::SpeedAndSize => "speed_and_size",
1400        };
1401        self.compiler_config_mut()
1402            .settings
1403            .insert("opt_level".to_string(), val.to_string());
1404        self
1405    }
1406
1407    /// Configures the regalloc algorithm used by the Cranelift code generator.
1408    ///
1409    /// Cranelift can select any of several register allocator algorithms. Each
1410    /// of these algorithms generates correct code, but they represent different
1411    /// tradeoffs between compile speed (how expensive the compilation process
1412    /// is) and run-time speed (how fast the generated code runs).
1413    /// For more information see the documentation of [`RegallocAlgorithm`].
1414    ///
1415    /// The default value for this is `RegallocAlgorithm::Backtracking`.
1416    ///
1417    /// # Panics
1418    ///
1419    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1420    #[cfg(any(feature = "cranelift", feature = "winch"))]
1421    pub fn cranelift_regalloc_algorithm(&mut self, algo: RegallocAlgorithm) -> &mut Self {
1422        let val = match algo {
1423            RegallocAlgorithm::Backtracking => "backtracking",
1424            RegallocAlgorithm::SinglePass => "single_pass",
1425        };
1426        self.compiler_config_mut()
1427            .settings
1428            .insert("regalloc_algorithm".to_string(), val.to_string());
1429        self
1430    }
1431
1432    /// Configures whether Cranelift should perform a NaN-canonicalization pass.
1433    ///
1434    /// When Cranelift is used as a code generation backend this will configure
1435    /// it to replace NaNs with a single canonical value. This is useful for
1436    /// users requiring entirely deterministic WebAssembly computation.  This is
1437    /// not required by the WebAssembly spec, so it is not enabled by default.
1438    ///
1439    /// Note that this option affects not only WebAssembly's `f32` and `f64`
1440    /// types but additionally the `v128` type. This option will cause
1441    /// operations using any of these types to have extra checks placed after
1442    /// them to normalize NaN values as needed.
1443    ///
1444    /// The default value for this is `false`
1445    ///
1446    /// # Panics
1447    ///
1448    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1449    #[cfg(any(feature = "cranelift", feature = "winch"))]
1450    pub fn cranelift_nan_canonicalization(&mut self, enable: bool) -> &mut Self {
1451        let val = if enable { "true" } else { "false" };
1452        self.compiler_config_mut()
1453            .settings
1454            .insert("enable_nan_canonicalization".to_string(), val.to_string());
1455        self
1456    }
1457
1458    /// Controls whether proof-carrying code (PCC) is used to validate
1459    /// lowering of Wasm sandbox checks.
1460    ///
1461    /// Proof-carrying code carries "facts" about program values from
1462    /// the IR all the way to machine code, and checks those facts
1463    /// against known machine-instruction semantics. This guards
1464    /// against bugs in instruction lowering that might create holes
1465    /// in the Wasm sandbox.
1466    ///
1467    /// PCC is designed to be fast: it does not require complex
1468    /// solvers or logic engines to verify, but only a linear pass
1469    /// over a trail of "breadcrumbs" or facts at each intermediate
1470    /// value. Thus, it is appropriate to enable in production.
1471    ///
1472    /// # Panics
1473    ///
1474    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1475    #[cfg(any(feature = "cranelift", feature = "winch"))]
1476    pub fn cranelift_pcc(&mut self, enable: bool) -> &mut Self {
1477        let val = if enable { "true" } else { "false" };
1478        self.compiler_config_mut()
1479            .settings
1480            .insert("enable_pcc".to_string(), val.to_string());
1481        self
1482    }
1483
1484    /// Allows setting a Cranelift boolean flag or preset. This allows
1485    /// fine-tuning of Cranelift settings.
1486    ///
1487    /// Since Cranelift flags may be unstable, this method should not be considered to be stable
1488    /// either; other `Config` functions should be preferred for stability.
1489    ///
1490    /// # Safety
1491    ///
1492    /// This is marked as unsafe, because setting the wrong flag might break invariants,
1493    /// resulting in execution hazards.
1494    ///
1495    /// # Errors
1496    ///
1497    /// The validation of the flags are deferred until the engine is being built, and thus may
1498    /// cause `Engine::new` fail if the flag's name does not exist, or the value is not appropriate
1499    /// for the flag type.
1500    ///
1501    /// # Panics
1502    ///
1503    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1504    #[cfg(any(feature = "cranelift", feature = "winch"))]
1505    pub unsafe fn cranelift_flag_enable(&mut self, flag: &str) -> &mut Self {
1506        self.compiler_config_mut().flags.insert(flag.to_string());
1507        self
1508    }
1509
1510    /// Allows settings another Cranelift flag defined by a flag name and value. This allows
1511    /// fine-tuning of Cranelift settings.
1512    ///
1513    /// Since Cranelift flags may be unstable, this method should not be considered to be stable
1514    /// either; other `Config` functions should be preferred for stability.
1515    ///
1516    /// # Safety
1517    ///
1518    /// This is marked as unsafe, because setting the wrong flag might break invariants,
1519    /// resulting in execution hazards.
1520    ///
1521    /// # Errors
1522    ///
1523    /// The validation of the flags are deferred until the engine is being built, and thus may
1524    /// cause `Engine::new` fail if the flag's name does not exist, or incompatible with other
1525    /// settings.
1526    ///
1527    /// For example, feature `wasm_backtrace` will set `unwind_info` to `true`, but if it's
1528    /// manually set to false then it will fail.
1529    ///
1530    /// # Panics
1531    ///
1532    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
1533    #[cfg(any(feature = "cranelift", feature = "winch"))]
1534    pub unsafe fn cranelift_flag_set(&mut self, name: &str, value: &str) -> &mut Self {
1535        self.compiler_config_mut()
1536            .settings
1537            .insert(name.to_string(), value.to_string());
1538        self
1539    }
1540
1541    /// Set a custom [`Cache`].
1542    ///
1543    /// To load a cache configuration from a file, use [`Cache::from_file`]. Otherwise, you can
1544    /// create a new cache config using [`CacheConfig::new`] and passing that to [`Cache::new`].
1545    ///
1546    /// If you want to disable the cache, you can call this method with `None`.
1547    ///
1548    /// By default, new configs do not have caching enabled.
1549    /// Every call to [`Module::new(my_wasm)`][crate::Module::new] will recompile `my_wasm`,
1550    /// even when it is unchanged, unless an enabled `CacheConfig` is provided.
1551    ///
1552    /// This method is only available when the `cache` feature of this crate is
1553    /// enabled.
1554    ///
1555    /// [docs]: https://bytecodealliance.github.io/wasmtime/cli-cache.html
1556    #[cfg(feature = "cache")]
1557    pub fn cache(&mut self, cache: Option<Cache>) -> &mut Self {
1558        self.cache = cache;
1559        self
1560    }
1561
1562    /// Sets a custom memory creator.
1563    ///
1564    /// Custom memory creators are used when creating host `Memory` objects or when
1565    /// creating instance linear memories for the on-demand instance allocation strategy.
1566    #[cfg(feature = "runtime")]
1567    pub fn with_host_memory(&mut self, mem_creator: Arc<dyn MemoryCreator>) -> &mut Self {
1568        self.mem_creator = Some(Arc::new(MemoryCreatorProxy(mem_creator)));
1569        self
1570    }
1571
1572    /// Sets a custom stack creator.
1573    ///
1574    /// Custom memory creators are used when creating creating async instance stacks for
1575    /// the on-demand instance allocation strategy.
1576    #[cfg(feature = "async")]
1577    pub fn with_host_stack(&mut self, stack_creator: Arc<dyn StackCreator>) -> &mut Self {
1578        self.stack_creator = Some(Arc::new(StackCreatorProxy(stack_creator)));
1579        self
1580    }
1581
1582    /// Sets a custom executable-memory publisher.
1583    ///
1584    /// Custom executable-memory publishers are hooks that allow
1585    /// Wasmtime to make certain regions of memory executable when
1586    /// loading precompiled modules or compiling new modules
1587    /// in-process. In most modern operating systems, memory allocated
1588    /// for heap usage is readable and writable by default but not
1589    /// executable. To jump to machine code stored in that memory, we
1590    /// need to make it executable. For security reasons, we usually
1591    /// also make it read-only at the same time, so the executing code
1592    /// can't be modified later.
1593    ///
1594    /// By default, Wasmtime will use the appropriate system calls on
1595    /// the host platform for this work. However, it also allows
1596    /// plugging in a custom implementation via this configuration
1597    /// option. This may be useful on custom or `no_std` platforms,
1598    /// for example, especially where virtual memory is not otherwise
1599    /// used by Wasmtime (no `signals-and-traps` feature).
1600    #[cfg(feature = "runtime")]
1601    pub fn with_custom_code_memory(
1602        &mut self,
1603        custom_code_memory: Option<Arc<dyn CustomCodeMemory>>,
1604    ) -> &mut Self {
1605        self.custom_code_memory = custom_code_memory;
1606        self
1607    }
1608
1609    /// Sets the instance allocation strategy to use.
1610    ///
1611    /// This is notably used in conjunction with
1612    /// [`InstanceAllocationStrategy::Pooling`] and [`PoolingAllocationConfig`].
1613    pub fn allocation_strategy(
1614        &mut self,
1615        strategy: impl Into<InstanceAllocationStrategy>,
1616    ) -> &mut Self {
1617        self.allocation_strategy = strategy.into();
1618        self
1619    }
1620
1621    /// Specifies the capacity of linear memories, in bytes, in their initial
1622    /// allocation.
1623    ///
1624    /// > Note: this value has important performance ramifications, be sure to
1625    /// > benchmark when setting this to a non-default value and read over this
1626    /// > documentation.
1627    ///
1628    /// This function will change the size of the initial memory allocation made
1629    /// for linear memories. This setting is only applicable when the initial
1630    /// size of a linear memory is below this threshold. Linear memories are
1631    /// allocated in the virtual address space of the host process with OS APIs
1632    /// such as `mmap` and this setting affects how large the allocation will
1633    /// be.
1634    ///
1635    /// ## Background: WebAssembly Linear Memories
1636    ///
1637    /// WebAssembly linear memories always start with a minimum size and can
1638    /// possibly grow up to a maximum size. The minimum size is always specified
1639    /// in a WebAssembly module itself and the maximum size can either be
1640    /// optionally specified in the module or inherently limited by the index
1641    /// type. For example for this module:
1642    ///
1643    /// ```wasm
1644    /// (module
1645    ///     (memory $a 4)
1646    ///     (memory $b 4096 4096 (pagesize 1))
1647    ///     (memory $c i64 10)
1648    /// )
1649    /// ```
1650    ///
1651    /// * Memory `$a` initially allocates 4 WebAssembly pages (256KiB) and can
1652    ///   grow up to 4GiB, the limit of the 32-bit index space.
1653    /// * Memory `$b` initially allocates 4096 WebAssembly pages, but in this
1654    ///   case its page size is 1, so it's 4096 bytes. Memory can also grow no
1655    ///   further meaning that it will always be 4096 bytes.
1656    /// * Memory `$c` is a 64-bit linear memory which starts with 640KiB of
1657    ///   memory and can theoretically grow up to 2^64 bytes, although most
1658    ///   hosts will run out of memory long before that.
1659    ///
1660    /// All operations on linear memories done by wasm are required to be
1661    /// in-bounds. Any access beyond the end of a linear memory is considered a
1662    /// trap.
1663    ///
1664    /// ## What this setting affects: Virtual Memory
1665    ///
1666    /// This setting is used to configure the behavior of the size of the linear
1667    /// memory allocation performed for each of these memories. For example the
1668    /// initial linear memory allocation looks like this:
1669    ///
1670    /// ```text
1671    ///              memory_reservation
1672    ///                    |
1673    ///          ◄─────────┴────────────────►
1674    /// ┌───────┬─────────┬──────────────────┬───────┐
1675    /// │ guard │ initial │ ... capacity ... │ guard │
1676    /// └───────┴─────────┴──────────────────┴───────┘
1677    ///  ◄──┬──►                              ◄──┬──►
1678    ///     │                                    │
1679    ///     │                             memory_guard_size
1680    ///     │
1681    ///     │
1682    ///  memory_guard_size (if guard_before_linear_memory)
1683    /// ```
1684    ///
1685    /// Memory in the `initial` range is accessible to the instance and can be
1686    /// read/written by wasm code. Memory in the `guard` regions is never
1687    /// accessible to wasm code and memory in `capacity` is initially
1688    /// inaccessible but may become accessible through `memory.grow` instructions
1689    /// for example.
1690    ///
1691    /// This means that this setting is the size of the initial chunk of virtual
1692    /// memory that a linear memory may grow into.
1693    ///
1694    /// ## What this setting affects: Runtime Speed
1695    ///
1696    /// This is a performance-sensitive setting which is taken into account
1697    /// during the compilation process of a WebAssembly module. For example if a
1698    /// 32-bit WebAssembly linear memory has a `memory_reservation` size of 4GiB
1699    /// then bounds checks can be elided because `capacity` will be guaranteed
1700    /// to be unmapped for all addressable bytes that wasm can access (modulo a
1701    /// few details).
1702    ///
1703    /// If `memory_reservation` was something smaller like 256KiB then that
1704    /// would have a much smaller impact on virtual memory but the compile code
1705    /// would then need to have explicit bounds checks to ensure that
1706    /// loads/stores are in-bounds.
1707    ///
1708    /// The goal of this setting is to enable skipping bounds checks in most
1709    /// modules by default. Some situations which require explicit bounds checks
1710    /// though are:
1711    ///
1712    /// * When `memory_reservation` is smaller than the addressable size of the
1713    ///   linear memory. For example if 64-bit linear memories always need
1714    ///   bounds checks as they can address the entire virtual address spacce.
1715    ///   For 32-bit linear memories a `memory_reservation` minimum size of 4GiB
1716    ///   is required to elide bounds checks.
1717    ///
1718    /// * When linear memories have a page size of 1 then bounds checks are
1719    ///   required. In this situation virtual memory can't be relied upon
1720    ///   because that operates at the host page size granularity where wasm
1721    ///   requires a per-byte level granularity.
1722    ///
1723    /// * Configuration settings such as [`Config::signals_based_traps`] can be
1724    ///   used to disable the use of signal handlers and virtual memory so
1725    ///   explicit bounds checks are required.
1726    ///
1727    /// * When [`Config::memory_guard_size`] is too small a bounds check may be
1728    ///   required. For 32-bit wasm addresses are actually 33-bit effective
1729    ///   addresses because loads/stores have a 32-bit static offset to add to
1730    ///   the dynamic 32-bit address. If the static offset is larger than the
1731    ///   size of the guard region then an explicit bounds check is required.
1732    ///
1733    /// ## What this setting affects: Memory Growth Behavior
1734    ///
1735    /// In addition to affecting bounds checks emitted in compiled code this
1736    /// setting also affects how WebAssembly linear memories are grown. The
1737    /// `memory.grow` instruction can be used to make a linear memory larger and
1738    /// this is also affected by APIs such as
1739    /// [`Memory::grow`](crate::Memory::grow).
1740    ///
1741    /// In these situations when the amount being grown is small enough to fit
1742    /// within the remaining capacity then the linear memory doesn't have to be
1743    /// moved at runtime. If the capacity runs out though then a new linear
1744    /// memory allocation must be made and the contents of linear memory is
1745    /// copied over.
1746    ///
1747    /// For example here's a situation where a copy happens:
1748    ///
1749    /// * The `memory_reservation` setting is configured to 128KiB.
1750    /// * A WebAssembly linear memory starts with a single 64KiB page.
1751    /// * This memory can be grown by one page to contain the full 128KiB of
1752    ///   memory.
1753    /// * If grown by one more page, though, then a 192KiB allocation must be
1754    ///   made and the previous 128KiB of contents are copied into the new
1755    ///   allocation.
1756    ///
1757    /// This growth behavior can have a significant performance impact if lots
1758    /// of data needs to be copied on growth. Conversely if memory growth never
1759    /// needs to happen because the capacity will always be large enough then
1760    /// optimizations can be applied to cache the base pointer of linear memory.
1761    ///
1762    /// When memory is grown then the
1763    /// [`Config::memory_reservation_for_growth`] is used for the new
1764    /// memory allocation to have memory to grow into.
1765    ///
1766    /// When using the pooling allocator via [`PoolingAllocationConfig`] then
1767    /// memories are never allowed to move so requests for growth are instead
1768    /// rejected with an error.
1769    ///
1770    /// ## When this setting is not used
1771    ///
1772    /// This setting is ignored and unused when the initial size of linear
1773    /// memory is larger than this threshold. For example if this setting is set
1774    /// to 1MiB but a wasm module requires a 2MiB minimum allocation then this
1775    /// setting is ignored. In this situation the minimum size of memory will be
1776    /// allocated along with [`Config::memory_reservation_for_growth`]
1777    /// after it to grow into.
1778    ///
1779    /// That means that this value can be set to zero. That can be useful in
1780    /// benchmarking to see the overhead of bounds checks for example.
1781    /// Additionally it can be used to minimize the virtual memory allocated by
1782    /// Wasmtime.
1783    ///
1784    /// ## Default Value
1785    ///
1786    /// The default value for this property depends on the host platform. For
1787    /// 64-bit platforms there's lots of address space available, so the default
1788    /// configured here is 4GiB. When coupled with the default size of
1789    /// [`Config::memory_guard_size`] this means that 32-bit WebAssembly linear
1790    /// memories with 64KiB page sizes will skip almost all bounds checks by
1791    /// default.
1792    ///
1793    /// For 32-bit platforms this value defaults to 10MiB. This means that
1794    /// bounds checks will be required on 32-bit platforms.
1795    pub fn memory_reservation(&mut self, bytes: u64) -> &mut Self {
1796        self.tunables.memory_reservation = Some(bytes);
1797        self
1798    }
1799
1800    /// Indicates whether linear memories may relocate their base pointer at
1801    /// runtime.
1802    ///
1803    /// WebAssembly linear memories either have a maximum size that's explicitly
1804    /// listed in the type of a memory or inherently limited by the index type
1805    /// of the memory (e.g. 4GiB for 32-bit linear memories). Depending on how
1806    /// the linear memory is allocated (see [`Config::memory_reservation`]) it
1807    /// may be necessary to move the memory in the host's virtual address space
1808    /// during growth. This option controls whether this movement is allowed or
1809    /// not.
1810    ///
1811    /// An example of a linear memory needing to move is when
1812    /// [`Config::memory_reservation`] is 0 then a linear memory will be
1813    /// allocated as the minimum size of the memory plus
1814    /// [`Config::memory_reservation_for_growth`]. When memory grows beyond the
1815    /// reservation for growth then the memory needs to be relocated.
1816    ///
1817    /// When this option is set to `false` then it can have a number of impacts
1818    /// on how memories work at runtime:
1819    ///
1820    /// * Modules can be compiled with static knowledge the base pointer of
1821    ///   linear memory never changes to enable optimizations such as
1822    ///   loop invariant code motion (hoisting the base pointer out of a loop).
1823    ///
1824    /// * Memories cannot grow in excess of their original allocation. This
1825    ///   means that [`Config::memory_reservation`] and
1826    ///   [`Config::memory_reservation_for_growth`] may need tuning to ensure
1827    ///   the memory configuration works at runtime.
1828    ///
1829    /// The default value for this option is `true`.
1830    pub fn memory_may_move(&mut self, enable: bool) -> &mut Self {
1831        self.tunables.memory_may_move = Some(enable);
1832        self
1833    }
1834
1835    /// Configures the size, in bytes, of the guard region used at the end of a
1836    /// linear memory's address space reservation.
1837    ///
1838    /// > Note: this value has important performance ramifications, be sure to
1839    /// > understand what this value does before tweaking it and benchmarking.
1840    ///
1841    /// This setting controls how many bytes are guaranteed to be unmapped after
1842    /// the virtual memory allocation of a linear memory. When
1843    /// combined with sufficiently large values of
1844    /// [`Config::memory_reservation`] (e.g. 4GiB for 32-bit linear memories)
1845    /// then a guard region can be used to eliminate bounds checks in generated
1846    /// code.
1847    ///
1848    /// This setting additionally can be used to help deduplicate bounds checks
1849    /// in code that otherwise requires bounds checks. For example with a 4KiB
1850    /// guard region then a 64-bit linear memory which accesses addresses `x+8`
1851    /// and `x+16` only needs to perform a single bounds check on `x`. If that
1852    /// bounds check passes then the offset is guaranteed to either reside in
1853    /// linear memory or the guard region, resulting in deterministic behavior
1854    /// either way.
1855    ///
1856    /// ## How big should the guard be?
1857    ///
1858    /// In general, like with configuring [`Config::memory_reservation`], you
1859    /// probably don't want to change this value from the defaults. Removing
1860    /// bounds checks is dependent on a number of factors where the size of the
1861    /// guard region is only one piece of the equation. Other factors include:
1862    ///
1863    /// * [`Config::memory_reservation`]
1864    /// * The index type of the linear memory (e.g. 32-bit or 64-bit)
1865    /// * The page size of the linear memory
1866    /// * Other settings such as [`Config::signals_based_traps`]
1867    ///
1868    /// Embeddings using virtual memory almost always want at least some guard
1869    /// region, but otherwise changes from the default should be profiled
1870    /// locally to see the performance impact.
1871    ///
1872    /// ## Default
1873    ///
1874    /// The default value for this property is 32MiB on 64-bit platforms. This
1875    /// allows eliminating almost all bounds checks on loads/stores with an
1876    /// immediate offset of less than 32MiB. On 32-bit platforms this defaults
1877    /// to 64KiB.
1878    pub fn memory_guard_size(&mut self, bytes: u64) -> &mut Self {
1879        self.tunables.memory_guard_size = Some(bytes);
1880        self
1881    }
1882
1883    /// Configures the size, in bytes, of the extra virtual memory space
1884    /// reserved after a linear memory is relocated.
1885    ///
1886    /// This setting is used in conjunction with [`Config::memory_reservation`]
1887    /// to configure what happens after a linear memory is relocated in the host
1888    /// address space. If the initial size of a linear memory exceeds
1889    /// [`Config::memory_reservation`] or if it grows beyond that size
1890    /// throughout its lifetime then this setting will be used.
1891    ///
1892    /// When a linear memory is relocated it will initially look like this:
1893    ///
1894    /// ```text
1895    ///            memory.size
1896    ///                 │
1897    ///          ◄──────┴─────►
1898    /// ┌───────┬──────────────┬───────┐
1899    /// │ guard │  accessible  │ guard │
1900    /// └───────┴──────────────┴───────┘
1901    ///                         ◄──┬──►
1902    ///                            │
1903    ///                     memory_guard_size
1904    /// ```
1905    ///
1906    /// where `accessible` needs to be grown but there's no more memory to grow
1907    /// into. A new region of the virtual address space will be allocated that
1908    /// looks like this:
1909    ///
1910    /// ```text
1911    ///                           memory_reservation_for_growth
1912    ///                                       │
1913    ///            memory.size                │
1914    ///                 │                     │
1915    ///          ◄──────┴─────► ◄─────────────┴───────────►
1916    /// ┌───────┬──────────────┬───────────────────────────┬───────┐
1917    /// │ guard │  accessible  │ .. reserved for growth .. │ guard │
1918    /// └───────┴──────────────┴───────────────────────────┴───────┘
1919    ///                                                     ◄──┬──►
1920    ///                                                        │
1921    ///                                               memory_guard_size
1922    /// ```
1923    ///
1924    /// This means that up to `memory_reservation_for_growth` bytes can be
1925    /// allocated again before the entire linear memory needs to be moved again
1926    /// when another `memory_reservation_for_growth` bytes will be appended to
1927    /// the size of the allocation.
1928    ///
1929    /// Note that this is a currently simple heuristic for optimizing the growth
1930    /// of dynamic memories, primarily implemented for the memory64 proposal
1931    /// where the maximum size of memory is larger than 4GiB. This setting is
1932    /// unlikely to be a one-size-fits-all style approach and if you're an
1933    /// embedder running into issues with growth and are interested in having
1934    /// other growth strategies available here please feel free to [open an
1935    /// issue on the Wasmtime repository][issue]!
1936    ///
1937    /// [issue]: https://github.com/bytecodealliance/wasmtime/issues/new
1938    ///
1939    /// ## Default
1940    ///
1941    /// For 64-bit platforms this defaults to 2GiB, and for 32-bit platforms
1942    /// this defaults to 1MiB.
1943    pub fn memory_reservation_for_growth(&mut self, bytes: u64) -> &mut Self {
1944        self.tunables.memory_reservation_for_growth = Some(bytes);
1945        self
1946    }
1947
1948    /// Indicates whether a guard region is present before allocations of
1949    /// linear memory.
1950    ///
1951    /// Guard regions before linear memories are never used during normal
1952    /// operation of WebAssembly modules, even if they have out-of-bounds
1953    /// loads. The only purpose for a preceding guard region in linear memory
1954    /// is extra protection against possible bugs in code generators like
1955    /// Cranelift. This setting does not affect performance in any way, but will
1956    /// result in larger virtual memory reservations for linear memories (it
1957    /// won't actually ever use more memory, just use more of the address
1958    /// space).
1959    ///
1960    /// The size of the guard region before linear memory is the same as the
1961    /// guard size that comes after linear memory, which is configured by
1962    /// [`Config::memory_guard_size`].
1963    ///
1964    /// ## Default
1965    ///
1966    /// This value defaults to `true`.
1967    pub fn guard_before_linear_memory(&mut self, enable: bool) -> &mut Self {
1968        self.tunables.guard_before_linear_memory = Some(enable);
1969        self
1970    }
1971
1972    /// Indicates whether to initialize tables lazily, so that instantiation
1973    /// is fast but indirect calls are a little slower. If false, tables
1974    /// are initialized eagerly during instantiation from any active element
1975    /// segments that apply to them.
1976    ///
1977    /// **Note** Disabling this option is not compatible with the Winch compiler.
1978    ///
1979    /// ## Default
1980    ///
1981    /// This value defaults to `true`.
1982    pub fn table_lazy_init(&mut self, table_lazy_init: bool) -> &mut Self {
1983        self.tunables.table_lazy_init = Some(table_lazy_init);
1984        self
1985    }
1986
1987    /// Configure the version information used in serialized and deserialized [`crate::Module`]s.
1988    /// This effects the behavior of [`crate::Module::serialize()`], as well as
1989    /// [`crate::Module::deserialize()`] and related functions.
1990    ///
1991    /// The default strategy is to use the wasmtime crate's Cargo package version.
1992    pub fn module_version(&mut self, strategy: ModuleVersionStrategy) -> Result<&mut Self> {
1993        match strategy {
1994            // This case requires special precondition for assertion in SerializedModule::to_bytes
1995            ModuleVersionStrategy::Custom(ref v) => {
1996                if v.as_bytes().len() > 255 {
1997                    bail!("custom module version cannot be more than 255 bytes: {v}");
1998                }
1999            }
2000            _ => {}
2001        }
2002        self.module_version = strategy;
2003        Ok(self)
2004    }
2005
2006    /// Configure whether wasmtime should compile a module using multiple
2007    /// threads.
2008    ///
2009    /// Disabling this will result in a single thread being used to compile
2010    /// the wasm bytecode.
2011    ///
2012    /// By default parallel compilation is enabled.
2013    #[cfg(feature = "parallel-compilation")]
2014    pub fn parallel_compilation(&mut self, parallel: bool) -> &mut Self {
2015        self.parallel_compilation = parallel;
2016        self
2017    }
2018
2019    /// Configures whether compiled artifacts will contain information to map
2020    /// native program addresses back to the original wasm module.
2021    ///
2022    /// This configuration option is `true` by default and, if enabled,
2023    /// generates the appropriate tables in compiled modules to map from native
2024    /// address back to wasm source addresses. This is used for displaying wasm
2025    /// program counters in backtraces as well as generating filenames/line
2026    /// numbers if so configured as well (and the original wasm module has DWARF
2027    /// debugging information present).
2028    pub fn generate_address_map(&mut self, generate: bool) -> &mut Self {
2029        self.tunables.generate_address_map = Some(generate);
2030        self
2031    }
2032
2033    /// Configures whether copy-on-write memory-mapped data is used to
2034    /// initialize a linear memory.
2035    ///
2036    /// Initializing linear memory via a copy-on-write mapping can drastically
2037    /// improve instantiation costs of a WebAssembly module because copying
2038    /// memory is deferred. Additionally if a page of memory is only ever read
2039    /// from WebAssembly and never written too then the same underlying page of
2040    /// data will be reused between all instantiations of a module meaning that
2041    /// if a module is instantiated many times this can lower the overall memory
2042    /// required needed to run that module.
2043    ///
2044    /// The main disadvantage of copy-on-write initialization, however, is that
2045    /// it may be possible for highly-parallel scenarios to be less scalable. If
2046    /// a page is read initially by a WebAssembly module then that page will be
2047    /// mapped to a read-only copy shared between all WebAssembly instances. If
2048    /// the same page is then written, however, then a private copy is created
2049    /// and swapped out from the read-only version. This also requires an [IPI],
2050    /// however, which can be a significant bottleneck in high-parallelism
2051    /// situations.
2052    ///
2053    /// This feature is only applicable when a WebAssembly module meets specific
2054    /// criteria to be initialized in this fashion, such as:
2055    ///
2056    /// * Only memories defined in the module can be initialized this way.
2057    /// * Data segments for memory must use statically known offsets.
2058    /// * Data segments for memory must all be in-bounds.
2059    ///
2060    /// Modules which do not meet these criteria will fall back to
2061    /// initialization of linear memory based on copying memory.
2062    ///
2063    /// This feature of Wasmtime is also platform-specific:
2064    ///
2065    /// * Linux - this feature is supported for all instances of [`Module`].
2066    ///   Modules backed by an existing mmap (such as those created by
2067    ///   [`Module::deserialize_file`]) will reuse that mmap to cow-initialize
2068    ///   memory. Other instance of [`Module`] may use the `memfd_create`
2069    ///   syscall to create an initialization image to `mmap`.
2070    /// * Unix (not Linux) - this feature is only supported when loading modules
2071    ///   from a precompiled file via [`Module::deserialize_file`] where there
2072    ///   is a file descriptor to use to map data into the process. Note that
2073    ///   the module must have been compiled with this setting enabled as well.
2074    /// * Windows - there is no support for this feature at this time. Memory
2075    ///   initialization will always copy bytes.
2076    ///
2077    /// By default this option is enabled.
2078    ///
2079    /// [`Module::deserialize_file`]: crate::Module::deserialize_file
2080    /// [`Module`]: crate::Module
2081    /// [IPI]: https://en.wikipedia.org/wiki/Inter-processor_interrupt
2082    pub fn memory_init_cow(&mut self, enable: bool) -> &mut Self {
2083        self.tunables.memory_init_cow = Some(enable);
2084        self
2085    }
2086
2087    /// A configuration option to force the usage of `memfd_create` on Linux to
2088    /// be used as the backing source for a module's initial memory image.
2089    ///
2090    /// When [`Config::memory_init_cow`] is enabled, which is enabled by
2091    /// default, module memory initialization images are taken from a module's
2092    /// original mmap if possible. If a precompiled module was loaded from disk
2093    /// this means that the disk's file is used as an mmap source for the
2094    /// initial linear memory contents. This option can be used to force, on
2095    /// Linux, that instead of using the original file on disk a new in-memory
2096    /// file is created with `memfd_create` to hold the contents of the initial
2097    /// image.
2098    ///
2099    /// This option can be used to avoid possibly loading the contents of memory
2100    /// from disk through a page fault. Instead with `memfd_create` the contents
2101    /// of memory are always in RAM, meaning that even page faults which
2102    /// initially populate a wasm linear memory will only work with RAM instead
2103    /// of ever hitting the disk that the original precompiled module is stored
2104    /// on.
2105    ///
2106    /// This option is disabled by default.
2107    pub fn force_memory_init_memfd(&mut self, enable: bool) -> &mut Self {
2108        self.force_memory_init_memfd = enable;
2109        self
2110    }
2111
2112    /// Configures whether or not a coredump should be generated and attached to
2113    /// the [`Error`](crate::Error) when a trap is raised.
2114    ///
2115    /// This option is disabled by default.
2116    #[cfg(feature = "coredump")]
2117    pub fn coredump_on_trap(&mut self, enable: bool) -> &mut Self {
2118        self.coredump_on_trap = enable;
2119        self
2120    }
2121
2122    /// Enables memory error checking for wasm programs.
2123    ///
2124    /// This option is disabled by default.
2125    ///
2126    /// # Panics
2127    ///
2128    /// Panics if this configuration's compiler was [disabled][Config::enable_compiler].
2129    #[cfg(any(feature = "cranelift", feature = "winch"))]
2130    pub fn wmemcheck(&mut self, enable: bool) -> &mut Self {
2131        self.wmemcheck = enable;
2132        self.compiler_config_mut().wmemcheck = enable;
2133        self
2134    }
2135
2136    /// Configures the "guaranteed dense image size" for copy-on-write
2137    /// initialized memories.
2138    ///
2139    /// When using the [`Config::memory_init_cow`] feature to initialize memory
2140    /// efficiently (which is enabled by default), compiled modules contain an
2141    /// image of the module's initial heap. If the module has a fairly sparse
2142    /// initial heap, with just a few data segments at very different offsets,
2143    /// this could result in a large region of zero bytes in the image. In
2144    /// other words, it's not very memory-efficient.
2145    ///
2146    /// We normally use a heuristic to avoid this: if less than half
2147    /// of the initialized range (first non-zero to last non-zero
2148    /// byte) of any memory in the module has pages with nonzero
2149    /// bytes, then we avoid creating a memory image for the entire module.
2150    ///
2151    /// However, if the embedder always needs the instantiation-time efficiency
2152    /// of copy-on-write initialization, and is otherwise carefully controlling
2153    /// parameters of the modules (for example, by limiting the maximum heap
2154    /// size of the modules), then it may be desirable to ensure a memory image
2155    /// is created even if this could go against the heuristic above. Thus, we
2156    /// add another condition: there is a size of initialized data region up to
2157    /// which we *always* allow a memory image. The embedder can set this to a
2158    /// known maximum heap size if they desire to always get the benefits of
2159    /// copy-on-write images.
2160    ///
2161    /// In the future we may implement a "best of both worlds"
2162    /// solution where we have a dense image up to some limit, and
2163    /// then support a sparse list of initializers beyond that; this
2164    /// would get most of the benefit of copy-on-write and pay the incremental
2165    /// cost of eager initialization only for those bits of memory
2166    /// that are out-of-bounds. However, for now, an embedder desiring
2167    /// fast instantiation should ensure that this setting is as large
2168    /// as the maximum module initial memory content size.
2169    ///
2170    /// By default this value is 16 MiB.
2171    pub fn memory_guaranteed_dense_image_size(&mut self, size_in_bytes: u64) -> &mut Self {
2172        self.memory_guaranteed_dense_image_size = size_in_bytes;
2173        self
2174    }
2175
2176    /// Whether to enable function inlining during compilation or not.
2177    ///
2178    /// This may result in faster execution at runtime, but adds additional
2179    /// compilation time. Inlining may also enlarge the size of compiled
2180    /// artifacts (for example, the size of the result of
2181    /// [`Engine::precompile_component`](crate::Engine::precompile_component)).
2182    ///
2183    /// Inlining is not supported by all of Wasmtime's compilation strategies;
2184    /// currently, it only Cranelift supports it. This setting will be ignored
2185    /// when using a compilation strategy that does not support inlining, like
2186    /// Winch.
2187    ///
2188    /// Note that inlining is still somewhat experimental at the moment (as of
2189    /// the Wasmtime version 36).
2190    pub fn compiler_inlining(&mut self, inlining: bool) -> &mut Self {
2191        self.tunables.inlining = Some(inlining);
2192        self
2193    }
2194
2195    /// Returns the set of features that the currently selected compiler backend
2196    /// does not support at all and may panic on.
2197    ///
2198    /// Wasmtime strives to reject unknown modules or unsupported modules with
2199    /// first-class errors instead of panics. Not all compiler backends have the
2200    /// same level of feature support on all platforms as well. This method
2201    /// returns a set of features that the currently selected compiler
2202    /// configuration is known to not support and may panic on. This acts as a
2203    /// first-level filter on incoming wasm modules/configuration to fail-fast
2204    /// instead of panicking later on.
2205    ///
2206    /// Note that if a feature is not listed here it does not mean that the
2207    /// backend fully supports the proposal. Instead that means that the backend
2208    /// doesn't ever panic on the proposal, but errors during compilation may
2209    /// still be returned. This means that features listed here are definitely
2210    /// not supported at all, but features not listed here may still be
2211    /// partially supported. For example at the time of this writing the Winch
2212    /// backend partially supports simd so it's not listed here. Winch doesn't
2213    /// fully support simd but unimplemented instructions just return errors.
2214    fn compiler_panicking_wasm_features(&self) -> WasmFeatures {
2215        // First we compute the set of features that Wasmtime itself knows;
2216        // this is a sort of "maximal set" that we invert to create a set
2217        // of features we _definitely can't support_ because wasmtime
2218        // has never heard of them.
2219        let features_known_to_wasmtime = WasmFeatures::empty()
2220            | WasmFeatures::MUTABLE_GLOBAL
2221            | WasmFeatures::SATURATING_FLOAT_TO_INT
2222            | WasmFeatures::SIGN_EXTENSION
2223            | WasmFeatures::REFERENCE_TYPES
2224            | WasmFeatures::CALL_INDIRECT_OVERLONG
2225            | WasmFeatures::MULTI_VALUE
2226            | WasmFeatures::BULK_MEMORY
2227            | WasmFeatures::BULK_MEMORY_OPT
2228            | WasmFeatures::SIMD
2229            | WasmFeatures::RELAXED_SIMD
2230            | WasmFeatures::THREADS
2231            | WasmFeatures::SHARED_EVERYTHING_THREADS
2232            | WasmFeatures::TAIL_CALL
2233            | WasmFeatures::FLOATS
2234            | WasmFeatures::MULTI_MEMORY
2235            | WasmFeatures::EXCEPTIONS
2236            | WasmFeatures::MEMORY64
2237            | WasmFeatures::EXTENDED_CONST
2238            | WasmFeatures::COMPONENT_MODEL
2239            | WasmFeatures::FUNCTION_REFERENCES
2240            | WasmFeatures::GC
2241            | WasmFeatures::CUSTOM_PAGE_SIZES
2242            | WasmFeatures::GC_TYPES
2243            | WasmFeatures::STACK_SWITCHING
2244            | WasmFeatures::WIDE_ARITHMETIC
2245            | WasmFeatures::CM_ASYNC
2246            | WasmFeatures::CM_ASYNC_STACKFUL
2247            | WasmFeatures::CM_ASYNC_BUILTINS
2248            | WasmFeatures::CM_THREADING
2249            | WasmFeatures::CM_ERROR_CONTEXT
2250            | WasmFeatures::CM_GC
2251            | WasmFeatures::CM_FIXED_LENGTH_LISTS;
2252
2253        #[allow(unused_mut, reason = "easier to avoid #[cfg]")]
2254        let mut unsupported = !features_known_to_wasmtime;
2255
2256        #[cfg(any(feature = "cranelift", feature = "winch"))]
2257        match self.compiler_config.as_ref().and_then(|c| c.strategy) {
2258            None | Some(Strategy::Cranelift) => {
2259                // Pulley at this time fundamentally doesn't support the
2260                // `threads` proposal, notably shared memory, because Rust can't
2261                // safely implement loads/stores in the face of shared memory.
2262                // Stack switching is not implemented, either.
2263                if self.compiler_target().is_pulley() {
2264                    unsupported |= WasmFeatures::THREADS;
2265                    unsupported |= WasmFeatures::STACK_SWITCHING;
2266                }
2267
2268                use target_lexicon::*;
2269                match self.compiler_target() {
2270                    Triple {
2271                        architecture: Architecture::X86_64 | Architecture::X86_64h,
2272                        operating_system:
2273                            OperatingSystem::Linux
2274                            | OperatingSystem::MacOSX(_)
2275                            | OperatingSystem::Darwin(_),
2276                        ..
2277                    } => {
2278                        // Stack switching supported on (non-Pulley) Cranelift.
2279                    }
2280
2281                    _ => {
2282                        // On platforms other than x64 Unix-like, we don't
2283                        // support stack switching.
2284                        unsupported |= WasmFeatures::STACK_SWITCHING;
2285                    }
2286                }
2287            }
2288            Some(Strategy::Winch) => {
2289                unsupported |= WasmFeatures::GC
2290                    | WasmFeatures::FUNCTION_REFERENCES
2291                    | WasmFeatures::RELAXED_SIMD
2292                    | WasmFeatures::TAIL_CALL
2293                    | WasmFeatures::GC_TYPES
2294                    | WasmFeatures::EXCEPTIONS
2295                    | WasmFeatures::LEGACY_EXCEPTIONS
2296                    | WasmFeatures::STACK_SWITCHING
2297                    | WasmFeatures::CM_ASYNC;
2298                match self.compiler_target().architecture {
2299                    target_lexicon::Architecture::Aarch64(_) => {
2300                        unsupported |= WasmFeatures::THREADS;
2301                        unsupported |= WasmFeatures::WIDE_ARITHMETIC;
2302                    }
2303
2304                    // Winch doesn't support other non-x64 architectures at this
2305                    // time either but will return an first-class error for
2306                    // them.
2307                    _ => {}
2308                }
2309            }
2310            Some(Strategy::Auto) => unreachable!(),
2311        }
2312        unsupported
2313    }
2314
2315    /// Calculates the set of features that are enabled for this `Config`.
2316    ///
2317    /// This method internally will start with the an empty set of features to
2318    /// avoid being tied to wasmparser's defaults. Next Wasmtime's set of
2319    /// default features are added to this set, some of which are conditional
2320    /// depending on crate features. Finally explicitly requested features via
2321    /// `wasm_*` methods on `Config` are applied. Everything is then validated
2322    /// later in `Config::validate`.
2323    fn features(&self) -> WasmFeatures {
2324        // Wasmtime by default supports all of the wasm 2.0 version of the
2325        // specification.
2326        let mut features = WasmFeatures::WASM2;
2327
2328        // On-by-default features that wasmtime has. Note that these are all
2329        // subject to the criteria at
2330        // https://docs.wasmtime.dev/contributing-implementing-wasm-proposals.html
2331        // and
2332        // https://docs.wasmtime.dev/stability-wasm-proposals.html
2333        features |= WasmFeatures::MULTI_MEMORY;
2334        features |= WasmFeatures::RELAXED_SIMD;
2335        features |= WasmFeatures::TAIL_CALL;
2336        features |= WasmFeatures::EXTENDED_CONST;
2337        features |= WasmFeatures::MEMORY64;
2338        // NB: if you add a feature above this line please double-check
2339        // https://docs.wasmtime.dev/stability-wasm-proposals.html
2340        // to ensure all requirements are met and/or update the documentation
2341        // there too.
2342
2343        // Set some features to their conditionally-enabled defaults depending
2344        // on crate compile-time features.
2345        features.set(WasmFeatures::GC_TYPES, cfg!(feature = "gc"));
2346        features.set(WasmFeatures::THREADS, cfg!(feature = "threads"));
2347        features.set(
2348            WasmFeatures::COMPONENT_MODEL,
2349            cfg!(feature = "component-model"),
2350        );
2351
2352        // From the default set of proposals remove any that the current
2353        // compiler backend may panic on if the module contains them.
2354        features = features & !self.compiler_panicking_wasm_features();
2355
2356        // After wasmtime's defaults are configured then factor in user requests
2357        // and disable/enable features. Note that the enable/disable sets should
2358        // be disjoint.
2359        debug_assert!((self.enabled_features & self.disabled_features).is_empty());
2360        features &= !self.disabled_features;
2361        features |= self.enabled_features;
2362
2363        features
2364    }
2365
2366    /// Returns the configured compiler target for this `Config`.
2367    pub(crate) fn compiler_target(&self) -> target_lexicon::Triple {
2368        // If a target is explicitly configured, always use that.
2369        if let Some(target) = self.target.clone() {
2370            return target;
2371        }
2372
2373        // If the `build.rs` script determined that this platform uses pulley by
2374        // default, then use Pulley.
2375        if cfg!(default_target_pulley) {
2376            return target_lexicon::Triple::pulley_host();
2377        }
2378
2379        // And at this point the target is for sure the host.
2380        target_lexicon::Triple::host()
2381    }
2382
2383    pub(crate) fn validate(&self) -> Result<(Tunables, WasmFeatures)> {
2384        let features = self.features();
2385
2386        // First validate that the selected compiler backend and configuration
2387        // supports the set of `features` that are enabled. This will help
2388        // provide more first class errors instead of panics about unsupported
2389        // features and configurations.
2390        let unsupported = features & self.compiler_panicking_wasm_features();
2391        if !unsupported.is_empty() {
2392            for flag in WasmFeatures::FLAGS.iter() {
2393                if !unsupported.contains(*flag.value()) {
2394                    continue;
2395                }
2396                bail!(
2397                    "the wasm_{} feature is not supported on this compiler configuration",
2398                    flag.name().to_lowercase()
2399                );
2400            }
2401
2402            panic!("should have returned an error by now")
2403        }
2404
2405        #[cfg(any(feature = "async", feature = "stack-switching"))]
2406        if self.max_wasm_stack > self.async_stack_size {
2407            bail!("max_wasm_stack size cannot exceed the async_stack_size");
2408        }
2409        if self.max_wasm_stack == 0 {
2410            bail!("max_wasm_stack size cannot be zero");
2411        }
2412        if !cfg!(feature = "wmemcheck") && self.wmemcheck {
2413            bail!("wmemcheck (memory checker) was requested but is not enabled in this build");
2414        }
2415
2416        if !cfg!(feature = "gc") && features.gc_types() {
2417            bail!("support for GC was disabled at compile time")
2418        }
2419
2420        if !cfg!(feature = "gc") && features.contains(WasmFeatures::EXCEPTIONS) {
2421            bail!("exceptions support requires garbage collection (GC) to be enabled in the build");
2422        }
2423
2424        match &self.rr_config {
2425            #[cfg(feature = "rr")]
2426            RRConfig::Recording | RRConfig::Replaying => {
2427                self.validate_rr_determinism_conflicts()?;
2428            }
2429            RRConfig::None => {}
2430        };
2431
2432        let mut tunables = Tunables::default_for_target(&self.compiler_target())?;
2433
2434        // By default this is enabled with the Cargo feature, and if the feature
2435        // is missing this is disabled.
2436        tunables.concurrency_support = cfg!(feature = "component-model-async");
2437
2438        #[cfg(feature = "rr")]
2439        {
2440            tunables.recording = matches!(self.rr_config, RRConfig::Recording);
2441        }
2442
2443        // If no target is explicitly specified then further refine `tunables`
2444        // for the configuration of this host depending on what platform
2445        // features were found available at compile time. This means that anyone
2446        // cross-compiling for a customized host will need to further refine
2447        // compilation options.
2448        if self.target.is_none() {
2449            // If this platform doesn't have native signals then change some
2450            // defaults to account for that. Note that VM guards are turned off
2451            // here because that's primarily a feature of eliding
2452            // bounds-checks.
2453            if !cfg!(has_native_signals) {
2454                tunables.signals_based_traps = cfg!(has_native_signals);
2455                tunables.memory_guard_size = 0;
2456            }
2457
2458            // When virtual memory is not available use slightly different
2459            // defaults for tunables to be more amenable to `MallocMemory`.
2460            // Note that these can still be overridden by config options.
2461            if !cfg!(has_virtual_memory) {
2462                tunables.memory_reservation = 0;
2463                tunables.memory_reservation_for_growth = 1 << 20; // 1MB
2464                tunables.memory_init_cow = false;
2465            }
2466        }
2467
2468        // If guest-debugging is enabled, we must disable
2469        // signals-based traps. Do this before we process the user's
2470        // provided tunables settings so we can detect a conflict with
2471        // an explicit request to use signals-based traps.
2472        #[cfg(feature = "debug")]
2473        if self.tunables.debug_guest == Some(true) {
2474            tunables.signals_based_traps = false;
2475        }
2476
2477        self.tunables.configure(&mut tunables);
2478
2479        // If we're going to compile with winch, we must use the winch calling convention.
2480        #[cfg(any(feature = "cranelift", feature = "winch"))]
2481        {
2482            tunables.winch_callable = self
2483                .compiler_config
2484                .as_ref()
2485                .is_some_and(|c| c.strategy == Some(Strategy::Winch));
2486        }
2487
2488        tunables.collector = if features.gc_types() {
2489            #[cfg(feature = "gc")]
2490            {
2491                use wasmtime_environ::Collector as EnvCollector;
2492                Some(match self.collector.try_not_auto()? {
2493                    Collector::DeferredReferenceCounting => EnvCollector::DeferredReferenceCounting,
2494                    Collector::Null => EnvCollector::Null,
2495                    Collector::Auto => unreachable!(),
2496                })
2497            }
2498            #[cfg(not(feature = "gc"))]
2499            bail!("cannot use GC types: the `gc` feature was disabled at compile time")
2500        } else {
2501            None
2502        };
2503
2504        if tunables.debug_guest {
2505            ensure!(
2506                cfg!(feature = "debug"),
2507                "debug instrumentation support was disabled at compile time"
2508            );
2509            ensure!(
2510                !tunables.signals_based_traps,
2511                "cannot use signals-based traps with guest debugging enabled"
2512            );
2513        }
2514
2515        // Concurrency support is required for some component model features.
2516        let requires_concurrency = WasmFeatures::CM_ASYNC
2517            | WasmFeatures::CM_ASYNC_BUILTINS
2518            | WasmFeatures::CM_ASYNC_STACKFUL
2519            | WasmFeatures::CM_THREADING
2520            | WasmFeatures::CM_ERROR_CONTEXT;
2521        if tunables.concurrency_support && !cfg!(feature = "component-model-async") {
2522            bail!(
2523                "concurrency support was requested but was not \
2524                 compiled into this build of Wasmtime"
2525            )
2526        }
2527        if !tunables.concurrency_support && features.intersects(requires_concurrency) {
2528            bail!(
2529                "concurrency support must be enabled to use the component \
2530                 model async or threading features"
2531            )
2532        }
2533
2534        Ok((tunables, features))
2535    }
2536
2537    #[cfg(feature = "runtime")]
2538    pub(crate) fn build_allocator(
2539        &self,
2540        tunables: &Tunables,
2541    ) -> Result<Box<dyn InstanceAllocator + Send + Sync>> {
2542        #[cfg(feature = "async")]
2543        let (stack_size, stack_zeroing) = (self.async_stack_size, self.async_stack_zeroing);
2544
2545        #[cfg(not(feature = "async"))]
2546        let (stack_size, stack_zeroing) = (0, false);
2547
2548        let _ = tunables;
2549
2550        match &self.allocation_strategy {
2551            InstanceAllocationStrategy::OnDemand => {
2552                let mut _allocator = try_new::<Box<_>>(OnDemandInstanceAllocator::new(
2553                    self.mem_creator.clone(),
2554                    stack_size,
2555                    stack_zeroing,
2556                ))?;
2557                #[cfg(feature = "async")]
2558                if let Some(stack_creator) = &self.stack_creator {
2559                    _allocator.set_stack_creator(stack_creator.clone());
2560                }
2561                Ok(_allocator as _)
2562            }
2563            #[cfg(feature = "pooling-allocator")]
2564            InstanceAllocationStrategy::Pooling(config) => {
2565                let mut config = config.config;
2566                config.stack_size = stack_size;
2567                config.async_stack_zeroing = stack_zeroing;
2568                let allocator = try_new::<Box<_>>(
2569                    crate::runtime::vm::PoolingInstanceAllocator::new(&config, tunables)?,
2570                )?;
2571                Ok(allocator as _)
2572            }
2573        }
2574    }
2575
2576    #[cfg(feature = "runtime")]
2577    pub(crate) fn build_gc_runtime(&self) -> Result<Option<Arc<dyn GcRuntime>>> {
2578        if !self.features().gc_types() {
2579            return Ok(None);
2580        }
2581
2582        #[cfg(not(feature = "gc"))]
2583        bail!("cannot create a GC runtime: the `gc` feature was disabled at compile time");
2584
2585        #[cfg(feature = "gc")]
2586        #[cfg_attr(
2587            not(any(feature = "gc-null", feature = "gc-drc")),
2588            expect(unreachable_code, reason = "definitions known to be dummy")
2589        )]
2590        {
2591            Ok(Some(match self.collector.try_not_auto()? {
2592                #[cfg(feature = "gc-drc")]
2593                Collector::DeferredReferenceCounting => {
2594                    try_new::<Arc<_>>(crate::runtime::vm::DrcCollector::default())? as _
2595                }
2596                #[cfg(not(feature = "gc-drc"))]
2597                Collector::DeferredReferenceCounting => unreachable!(),
2598
2599                #[cfg(feature = "gc-null")]
2600                Collector::Null => {
2601                    try_new::<Arc<_>>(crate::runtime::vm::NullCollector::default())? as _
2602                }
2603                #[cfg(not(feature = "gc-null"))]
2604                Collector::Null => unreachable!(),
2605
2606                Collector::Auto => unreachable!(),
2607            }))
2608        }
2609    }
2610
2611    #[cfg(feature = "runtime")]
2612    pub(crate) fn build_profiler(&self) -> Result<Box<dyn ProfilingAgent>> {
2613        Ok(match self.profiling_strategy {
2614            ProfilingStrategy::PerfMap => profiling_agent::new_perfmap()?,
2615            ProfilingStrategy::JitDump => profiling_agent::new_jitdump()?,
2616            ProfilingStrategy::VTune => profiling_agent::new_vtune()?,
2617            ProfilingStrategy::None => profiling_agent::new_null(),
2618            ProfilingStrategy::Pulley => profiling_agent::new_pulley()?,
2619        })
2620    }
2621
2622    #[cfg(any(feature = "cranelift", feature = "winch"))]
2623    pub(crate) fn build_compiler(
2624        mut self,
2625        tunables: &mut Tunables,
2626        features: WasmFeatures,
2627    ) -> Result<(Self, Box<dyn wasmtime_environ::Compiler>)> {
2628        let target = self.compiler_target();
2629
2630        // The target passed to the builders below is an `Option<Triple>` where
2631        // `None` represents the current host with CPU features inferred from
2632        // the host's CPU itself. The `target` above is not an `Option`, so
2633        // switch it to `None` in the case that a target wasn't explicitly
2634        // specified (which indicates no feature inference) and the target
2635        // matches the host.
2636        let target_for_builder =
2637            if self.target.is_none() && target == target_lexicon::Triple::host() {
2638                None
2639            } else {
2640                Some(target.clone())
2641            };
2642
2643        let mut compiler = match self.compiler_config_mut().strategy {
2644            #[cfg(feature = "cranelift")]
2645            Some(Strategy::Cranelift) => wasmtime_cranelift::builder(target_for_builder)?,
2646            #[cfg(not(feature = "cranelift"))]
2647            Some(Strategy::Cranelift) => bail!("cranelift support not compiled in"),
2648            #[cfg(feature = "winch")]
2649            Some(Strategy::Winch) => wasmtime_winch::builder(target_for_builder)?,
2650            #[cfg(not(feature = "winch"))]
2651            Some(Strategy::Winch) => bail!("winch support not compiled in"),
2652
2653            None | Some(Strategy::Auto) => unreachable!(),
2654        };
2655
2656        if let Some(path) = &self.compiler_config_mut().clif_dir {
2657            compiler.clif_dir(path)?;
2658        }
2659
2660        // If probestack is enabled for a target, Wasmtime will always use the
2661        // inline strategy which doesn't require us to define a `__probestack`
2662        // function or similar.
2663        self.compiler_config_mut()
2664            .settings
2665            .insert("probestack_strategy".into(), "inline".into());
2666
2667        // We enable stack probing by default on all targets.
2668        // This is required on Windows because of the way Windows
2669        // commits its stacks, but it's also a good idea on other
2670        // platforms to ensure guard pages are hit for large frame
2671        // sizes.
2672        self.compiler_config_mut()
2673            .flags
2674            .insert("enable_probestack".into());
2675
2676        // The current wasm multivalue implementation depends on this.
2677        // FIXME(#9510) handle this in wasmtime-cranelift instead.
2678        self.compiler_config_mut()
2679            .flags
2680            .insert("enable_multi_ret_implicit_sret".into());
2681
2682        if let Some(unwind_requested) = self.native_unwind_info {
2683            if !self
2684                .compiler_config_mut()
2685                .ensure_setting_unset_or_given("unwind_info", &unwind_requested.to_string())
2686            {
2687                bail!(
2688                    "incompatible settings requested for Cranelift and Wasmtime `unwind-info` settings"
2689                );
2690            }
2691        }
2692
2693        if target.operating_system == target_lexicon::OperatingSystem::Windows {
2694            if !self
2695                .compiler_config_mut()
2696                .ensure_setting_unset_or_given("unwind_info", "true")
2697            {
2698                bail!("`native_unwind_info` cannot be disabled on Windows");
2699            }
2700        }
2701
2702        // We require frame pointers for correct stack walking, which is safety
2703        // critical in the presence of reference types, and otherwise it is just
2704        // really bad developer experience to get wrong.
2705        self.compiler_config_mut()
2706            .settings
2707            .insert("preserve_frame_pointers".into(), "true".into());
2708
2709        if !tunables.signals_based_traps {
2710            let mut ok = self
2711                .compiler_config_mut()
2712                .ensure_setting_unset_or_given("enable_table_access_spectre_mitigation", "false");
2713            ok = ok
2714                && self.compiler_config_mut().ensure_setting_unset_or_given(
2715                    "enable_heap_access_spectre_mitigation",
2716                    "false",
2717                );
2718
2719            // Right now spectre-mitigated bounds checks will load from zero so
2720            // if host-based signal handlers are disabled then that's a mismatch
2721            // and doesn't work right now. Fixing this will require more thought
2722            // of how to implement the bounds check in spectre-only mode.
2723            if !ok {
2724                bail!(
2725                    "when signals-based traps are disabled then spectre \
2726                     mitigations must also be disabled"
2727                );
2728            }
2729        }
2730
2731        if features.contains(WasmFeatures::RELAXED_SIMD) && !features.contains(WasmFeatures::SIMD) {
2732            bail!("cannot disable the simd proposal but enable the relaxed simd proposal");
2733        }
2734
2735        if features.contains(WasmFeatures::STACK_SWITCHING) {
2736            use target_lexicon::OperatingSystem;
2737            let model = match target.operating_system {
2738                OperatingSystem::Windows => "update_windows_tib",
2739                OperatingSystem::Linux
2740                | OperatingSystem::MacOSX(_)
2741                | OperatingSystem::Darwin(_) => "basic",
2742                _ => bail!("stack-switching feature not supported on this platform "),
2743            };
2744
2745            if !self
2746                .compiler_config_mut()
2747                .ensure_setting_unset_or_given("stack_switch_model", model)
2748            {
2749                bail!(
2750                    "compiler option 'stack_switch_model' must be set to '{model}' on this platform"
2751                );
2752            }
2753        }
2754
2755        // Apply compiler settings and flags
2756        compiler.set_tunables(tunables.clone())?;
2757        for (k, v) in self.compiler_config_mut().settings.iter() {
2758            compiler.set(k, v)?;
2759        }
2760        for flag in self.compiler_config_mut().flags.iter() {
2761            compiler.enable(flag)?;
2762        }
2763        *tunables = compiler.tunables().cloned().unwrap();
2764
2765        #[cfg(all(feature = "incremental-cache", feature = "cranelift"))]
2766        if let Some(cache_store) = &self.compiler_config_mut().cache_store {
2767            compiler.enable_incremental_compilation(cache_store.clone())?;
2768        }
2769
2770        compiler.wmemcheck(self.compiler_config_mut().wmemcheck);
2771
2772        Ok((self, compiler.build()?))
2773    }
2774
2775    /// Internal setting for whether adapter modules for components will have
2776    /// extra WebAssembly instructions inserted performing more debug checks
2777    /// then are necessary.
2778    #[cfg(feature = "component-model")]
2779    pub fn debug_adapter_modules(&mut self, debug: bool) -> &mut Self {
2780        self.tunables.debug_adapter_modules = Some(debug);
2781        self
2782    }
2783
2784    /// Enables clif output when compiling a WebAssembly module.
2785    #[cfg(any(feature = "cranelift", feature = "winch"))]
2786    pub fn emit_clif(&mut self, path: &Path) -> &mut Self {
2787        self.compiler_config_mut().clif_dir = Some(path.to_path_buf());
2788        self
2789    }
2790
2791    /// Configures whether, when on macOS, Mach ports are used for exception
2792    /// handling instead of traditional Unix-based signal handling.
2793    ///
2794    /// WebAssembly traps in Wasmtime are implemented with native faults, for
2795    /// example a `SIGSEGV` will occur when a WebAssembly guest accesses
2796    /// out-of-bounds memory. Handling this can be configured to either use Unix
2797    /// signals or Mach ports on macOS. By default Mach ports are used.
2798    ///
2799    /// Mach ports enable Wasmtime to work by default with foreign
2800    /// error-handling systems such as breakpad which also use Mach ports to
2801    /// handle signals. In this situation Wasmtime will continue to handle guest
2802    /// faults gracefully while any non-guest faults will get forwarded to
2803    /// process-level handlers such as breakpad. Some more background on this
2804    /// can be found in #2456.
2805    ///
2806    /// A downside of using mach ports, however, is that they don't interact
2807    /// well with `fork()`. Forking a Wasmtime process on macOS will produce a
2808    /// child process that cannot successfully run WebAssembly. In this
2809    /// situation traditional Unix signal handling should be used as that's
2810    /// inherited and works across forks.
2811    ///
2812    /// If your embedding wants to use a custom error handler which leverages
2813    /// Mach ports and you additionally wish to `fork()` the process and use
2814    /// Wasmtime in the child process that's not currently possible. Please
2815    /// reach out to us if you're in this bucket!
2816    ///
2817    /// This option defaults to `true`, using Mach ports by default.
2818    pub fn macos_use_mach_ports(&mut self, mach_ports: bool) -> &mut Self {
2819        self.macos_use_mach_ports = mach_ports;
2820        self
2821    }
2822
2823    /// Configures an embedder-provided function, `detect`, which is used to
2824    /// determine if an ISA-specific feature is available on the current host.
2825    ///
2826    /// This function is used to verify that any features enabled for a compiler
2827    /// backend, such as AVX support on x86\_64, are also available on the host.
2828    /// It is undefined behavior to execute an AVX instruction on a host that
2829    /// doesn't support AVX instructions, for example.
2830    ///
2831    /// When the `std` feature is active on this crate then this function is
2832    /// configured to a default implementation that uses the standard library's
2833    /// feature detection. When the `std` feature is disabled then there is no
2834    /// default available and this method must be called to configure a feature
2835    /// probing function.
2836    ///
2837    /// The `detect` function provided is given a string name of an ISA feature.
2838    /// The function should then return:
2839    ///
2840    /// * `Some(true)` - indicates that the feature was found on the host and it
2841    ///   is supported.
2842    /// * `Some(false)` - the feature name was recognized but it was not
2843    ///   detected on the host, for example the CPU is too old.
2844    /// * `None` - the feature name was not recognized and it's not known
2845    ///   whether it's on the host or not.
2846    ///
2847    /// Feature names passed to `detect` match the same feature name used in the
2848    /// Rust standard library. For example `"sse4.2"` is used on x86\_64.
2849    ///
2850    /// # Unsafety
2851    ///
2852    /// This function is `unsafe` because it is undefined behavior to execute
2853    /// instructions that a host does not support. This means that the result of
2854    /// `detect` must be correct for memory safe execution at runtime.
2855    pub unsafe fn detect_host_feature(&mut self, detect: fn(&str) -> Option<bool>) -> &mut Self {
2856        self.detect_host_feature = Some(detect);
2857        self
2858    }
2859
2860    /// Configures Wasmtime to not use signals-based trap handlers, for example
2861    /// disables `SIGILL` and `SIGSEGV` handler registration on Unix platforms.
2862    ///
2863    /// > **Note:** this option has important performance ramifications, be sure
2864    /// > to understand the implications. Wasm programs have been measured to
2865    /// > run up to 2x slower when signals-based traps are disabled.
2866    ///
2867    /// Wasmtime will by default leverage signals-based trap handlers (or the
2868    /// platform equivalent, for example "vectored exception handlers" on
2869    /// Windows) to make generated code more efficient. For example, when
2870    /// Wasmtime can use signals-based traps, it can elide explicit bounds
2871    /// checks for Wasm linear memory accesses, instead relying on virtual
2872    /// memory guard pages to raise a `SIGSEGV` (on Unix) for out-of-bounds
2873    /// accesses, which Wasmtime's runtime then catches and handles. Another
2874    /// example is divide-by-zero: with signals-based traps, Wasmtime can let
2875    /// the hardware raise a trap when the divisor is zero. Without
2876    /// signals-based traps, Wasmtime must explicitly emit additional
2877    /// instructions to check for zero and conditionally branch to a trapping
2878    /// code path.
2879    ///
2880    /// Some environments however may not have access to signal handlers. For
2881    /// example embedded scenarios may not support virtual memory. Other
2882    /// environments where Wasmtime is embedded within the surrounding
2883    /// environment may require that new signal handlers aren't registered due
2884    /// to the global nature of signal handlers. This option exists to disable
2885    /// the signal handler registration when required for these scenarios.
2886    ///
2887    /// When signals-based trap handlers are disabled, then Wasmtime and its
2888    /// generated code will *never* rely on segfaults or other
2889    /// signals. Generated code will be slower because bounds must be explicitly
2890    /// checked along with other conditions like division by zero.
2891    ///
2892    /// The following additional factors can also affect Wasmtime's ability to
2893    /// elide explicit bounds checks and leverage signals-based traps:
2894    ///
2895    /// * The [`Config::memory_reservation`] and [`Config::memory_guard_size`]
2896    ///   settings
2897    /// * The index type of the linear memory (e.g. 32-bit or 64-bit)
2898    /// * The page size of the linear memory
2899    ///
2900    /// When this option is disabled, the
2901    /// `enable_heap_access_spectre_mitigation` and
2902    /// `enable_table_access_spectre_mitigation` Cranelift settings must also be
2903    /// disabled. This means that generated code must have spectre mitigations
2904    /// disabled. This is because spectre mitigations rely on faults from
2905    /// loading from the null address to implement bounds checks.
2906    ///
2907    /// This option defaults to `true`: signals-based trap handlers are enabled
2908    /// by default.
2909    ///
2910    /// > **Note:** Disabling this option is not compatible with the Winch
2911    /// > compiler.
2912    pub fn signals_based_traps(&mut self, enable: bool) -> &mut Self {
2913        self.tunables.signals_based_traps = Some(enable);
2914        self
2915    }
2916
2917    /// Enable/disable GC support in Wasmtime entirely.
2918    ///
2919    /// This flag can be used to gate whether GC infrastructure is enabled or
2920    /// initialized in Wasmtime at all. Wasmtime's GC implementation is required
2921    /// for the [`Self::wasm_gc`] proposal, [`Self::wasm_function_references`],
2922    /// and [`Self::wasm_exceptions`] at this time. None of those proposal can
2923    /// be enabled without also having this option enabled.
2924    ///
2925    /// This option defaults to whether the crate `gc` feature is enabled or
2926    /// not.
2927    pub fn gc_support(&mut self, enable: bool) -> &mut Self {
2928        self.wasm_features(WasmFeatures::GC_TYPES, enable)
2929    }
2930
2931    /// Explicitly indicate or not whether the host is using a hardware float
2932    /// ABI on x86 targets.
2933    ///
2934    /// This configuration option is only applicable on the
2935    /// `x86_64-unknown-none` Rust target and has no effect on other host
2936    /// targets. The `x86_64-unknown-none` Rust target does not support hardware
2937    /// floats by default and uses a "soft float" implementation and ABI. This
2938    /// means that `f32`, for example, is passed in a general-purpose register
2939    /// between functions instead of a floating-point register. This does not
2940    /// match Cranelift's ABI for `f32` where it's passed in floating-point
2941    /// registers.  Cranelift does not have support for a "soft float"
2942    /// implementation where all floating-point operations are lowered to
2943    /// libcalls.
2944    ///
2945    /// This means that for the `x86_64-unknown-none` target the ABI between
2946    /// Wasmtime's libcalls and the host is incompatible when floats are used.
2947    /// This further means that, by default, Wasmtime is unable to load native
2948    /// code when compiled to the `x86_64-unknown-none` target. The purpose of
2949    /// this option is to explicitly allow loading code and bypass this check.
2950    ///
2951    /// Setting this configuration option to `true` indicates that either:
2952    /// (a) the Rust target is compiled with the hard-float ABI manually via
2953    /// `-Zbuild-std` and a custom target JSON configuration, or (b) sufficient
2954    /// x86 features have been enabled in the compiler such that float libcalls
2955    /// will not be used in Wasmtime. For (a) there is no way in Rust at this
2956    /// time to detect whether a hard-float or soft-float ABI is in use on
2957    /// stable Rust, so this manual opt-in is required. For (b) the only
2958    /// instance where Wasmtime passes a floating-point value in a register
2959    /// between the host and compiled wasm code is with libcalls.
2960    ///
2961    /// Float-based libcalls are only used when the compilation target for a
2962    /// wasm module has insufficient target features enabled for native
2963    /// support. For example SSE4.1 is required for the `f32.ceil` WebAssembly
2964    /// instruction to be compiled to a native instruction. If SSE4.1 is not
2965    /// enabled then `f32.ceil` is translated to a "libcall" which is
2966    /// implemented on the host. Float-based libcalls can be avoided with
2967    /// sufficient target features enabled, for example:
2968    ///
2969    /// * `self.cranelift_flag_enable("has_sse3")`
2970    /// * `self.cranelift_flag_enable("has_ssse3")`
2971    /// * `self.cranelift_flag_enable("has_sse41")`
2972    /// * `self.cranelift_flag_enable("has_sse42")`
2973    /// * `self.cranelift_flag_enable("has_fma")`
2974    ///
2975    /// Note that when these features are enabled Wasmtime will perform a
2976    /// runtime check to determine that the host actually has the feature
2977    /// present.
2978    ///
2979    /// For some more discussion see [#11506].
2980    ///
2981    /// [#11506]: https://github.com/bytecodealliance/wasmtime/issues/11506
2982    ///
2983    /// # Safety
2984    ///
2985    /// This method is not safe because it cannot be detected in Rust right now
2986    /// whether the host is compiled with a soft or hard float ABI. Additionally
2987    /// if the host is compiled with a soft float ABI disabling this check does
2988    /// not ensure that the wasm module in question has zero usage of floats
2989    /// in the boundary to the host.
2990    ///
2991    /// Safely using this method requires one of:
2992    ///
2993    /// * The host target is compiled to use hardware floats.
2994    /// * Wasm modules loaded are compiled with enough x86 Cranelift features
2995    ///   enabled to avoid float-related hostcalls.
2996    pub unsafe fn x86_float_abi_ok(&mut self, enable: bool) -> &mut Self {
2997        self.x86_float_abi_ok = Some(enable);
2998        self
2999    }
3000
3001    /// Enable or disable the ability to create a
3002    /// [`SharedMemory`](crate::SharedMemory).
3003    ///
3004    /// The WebAssembly threads proposal, configured by [`Config::wasm_threads`]
3005    /// is on-by-default but there are enough deficiencies in Wasmtime's
3006    /// implementation and API integration that creation of a shared memory is
3007    /// disabled by default. This cofiguration knob can be used to enable this.
3008    ///
3009    /// When enabling this method be aware that wasm threads are, at this time,
3010    /// a [tier 2
3011    /// feature](https://docs.wasmtime.dev/stability-tiers.html#tier-2) in
3012    /// Wasmtime meaning that it will not receive security updates or fixes to
3013    /// historical releases. Additionally security CVEs will not be issued for
3014    /// bugs in the implementation.
3015    ///
3016    /// This option is `false` by default.
3017    pub fn shared_memory(&mut self, enable: bool) -> &mut Self {
3018        self.shared_memory = enable;
3019        self
3020    }
3021
3022    /// Specifies whether support for concurrent execution of WebAssembly is
3023    /// supported within this store.
3024    ///
3025    /// This configuration option affects whether runtime data structures are
3026    /// initialized within a `Store` on creation to support concurrent execution
3027    /// of WebAssembly guests. This is primarily applicable to the
3028    /// [`Config::wasm_component_model_async`] configuration which is the first
3029    /// time Wasmtime has supported concurrent execution of guests. This
3030    /// configuration option, for example, enables usage of
3031    /// [`Store::run_concurrent`], [`Func::call_concurrent`], [`StreamReader`],
3032    /// etc.
3033    ///
3034    /// This configuration option can be manually disabled to avoid initializing
3035    /// data structures in the [`Store`] related to concurrent execution. When
3036    /// this option is disabled then APIs related to concurrency will all fail
3037    /// with a panic. For example [`Store::run_concurrent`] will panic, creating
3038    /// a [`StreamReader`] will panic, etc.
3039    ///
3040    /// The value of this option additionally affects whether a [`Config`] is
3041    /// valid and the default set of enabled WebAssembly features. If this
3042    /// option is disabled then component-model features related to concurrency
3043    /// will all be disabled. If this option is enabled, then the options will
3044    /// retain their normal defaults. It is not valid to create a [`Config`]
3045    /// with component-model-async explicitly enabled and this option explicitly
3046    /// disabled, however.
3047    ///
3048    /// This option defaults to `true`.
3049    ///
3050    /// [`Store`]: crate::Store
3051    /// [`Store::run_concurrent`]: crate::Store::run_concurrent
3052    /// [`Func::call_concurrent`]: crate::component::Func::call_concurrent
3053    /// [`StreamReader`]: crate::component::StreamReader
3054    pub fn concurrency_support(&mut self, enable: bool) -> &mut Self {
3055        self.tunables.concurrency_support = Some(enable);
3056        self
3057    }
3058
3059    /// Validate if the current configuration has conflicting overrides that prevent
3060    /// execution determinism. Returns an error if a conflict exists.
3061    ///
3062    /// Note: Keep this in sync with [`Config::enforce_determinism`].
3063    #[inline]
3064    #[cfg(feature = "rr")]
3065    pub(crate) fn validate_rr_determinism_conflicts(&self) -> Result<()> {
3066        if let Some(v) = self.tunables.relaxed_simd_deterministic {
3067            if v == false {
3068                bail!("Relaxed deterministic SIMD cannot be disabled when determinism is enforced");
3069            }
3070        }
3071        #[cfg(any(feature = "cranelift", feature = "winch"))]
3072        if let Some(v) = self
3073            .compiler_config
3074            .as_ref()
3075            .and_then(|c| c.settings.get("enable_nan_canonicalization"))
3076        {
3077            if v != "true" {
3078                bail!("NaN canonicalization cannot be disabled when determinism is enforced");
3079            }
3080        }
3081        Ok(())
3082    }
3083
3084    /// Enable execution trace recording or replaying to the configuration.
3085    ///
3086    /// When either recording/replaying are enabled, validation fails if settings
3087    /// that control determinism are not set appropriately. In particular, RR requires
3088    /// doing the following:
3089    /// * Enabling NaN canonicalization with [`Config::cranelift_nan_canonicalization`].
3090    /// * Enabling deterministic relaxed SIMD with [`Config::relaxed_simd_deterministic`].
3091    #[inline]
3092    pub fn rr(&mut self, cfg: RRConfig) -> &mut Self {
3093        self.rr_config = cfg;
3094        self
3095    }
3096}
3097
3098impl Default for Config {
3099    fn default() -> Config {
3100        Config::new()
3101    }
3102}
3103
3104impl fmt::Debug for Config {
3105    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3106        let mut f = f.debug_struct("Config");
3107
3108        // Not every flag in WasmFeatures can be enabled as part of creating
3109        // a Config. This impl gives a complete picture of all WasmFeatures
3110        // enabled, and doesn't require maintenance by hand (which has become out
3111        // of date in the past), at the cost of possible confusion for why
3112        // a flag in this set doesn't have a Config setter.
3113        let features = self.features();
3114        for flag in WasmFeatures::FLAGS.iter() {
3115            f.field(
3116                &format!("wasm_{}", flag.name().to_lowercase()),
3117                &features.contains(*flag.value()),
3118            );
3119        }
3120
3121        f.field("parallel_compilation", &self.parallel_compilation);
3122        #[cfg(any(feature = "cranelift", feature = "winch"))]
3123        {
3124            f.field("compiler_config", &self.compiler_config);
3125        }
3126
3127        self.tunables.format(&mut f);
3128        f.finish()
3129    }
3130}
3131
3132/// Possible Compilation strategies for a wasm module.
3133///
3134/// This is used as an argument to the [`Config::strategy`] method.
3135#[non_exhaustive]
3136#[derive(PartialEq, Eq, Clone, Debug, Copy)]
3137pub enum Strategy {
3138    /// An indicator that the compilation strategy should be automatically
3139    /// selected.
3140    ///
3141    /// This is generally what you want for most projects and indicates that the
3142    /// `wasmtime` crate itself should make the decision about what the best
3143    /// code generator for a wasm module is.
3144    ///
3145    /// Currently this always defaults to Cranelift, but the default value may
3146    /// change over time.
3147    Auto,
3148
3149    /// Currently the default backend, Cranelift aims to be a reasonably fast
3150    /// code generator which generates high quality machine code.
3151    Cranelift,
3152
3153    /// A low-latency baseline compiler for WebAssembly.
3154    /// For more details regarding ISA support and Wasm proposals support
3155    /// see <https://docs.wasmtime.dev/stability-tiers.html#current-tier-status>
3156    Winch,
3157}
3158
3159#[cfg(any(feature = "winch", feature = "cranelift"))]
3160impl Strategy {
3161    fn not_auto(&self) -> Option<Strategy> {
3162        match self {
3163            Strategy::Auto => {
3164                if cfg!(feature = "cranelift") {
3165                    Some(Strategy::Cranelift)
3166                } else if cfg!(feature = "winch") {
3167                    Some(Strategy::Winch)
3168                } else {
3169                    None
3170                }
3171            }
3172            other => Some(*other),
3173        }
3174    }
3175}
3176
3177/// Possible garbage collector implementations for Wasm.
3178///
3179/// This is used as an argument to the [`Config::collector`] method.
3180///
3181/// The properties of Wasmtime's available collectors are summarized in the
3182/// following table:
3183///
3184/// | Collector                   | Collects Garbage[^1] | Latency[^2] | Throughput[^3] | Allocation Speed[^4] | Heap Utilization[^5] |
3185/// |-----------------------------|----------------------|-------------|----------------|----------------------|----------------------|
3186/// | `DeferredReferenceCounting` | Yes, but not cycles  | 🙂         | 🙁             | 😐                   | 😐                  |
3187/// | `Null`                      | No                   | 🙂         | 🙂             | 🙂                   | 🙂                  |
3188///
3189/// [^1]: Whether or not the collector is capable of collecting garbage and cyclic garbage.
3190///
3191/// [^2]: How long the Wasm program is paused during garbage
3192///       collections. Shorter is better. In general, better latency implies
3193///       worse throughput and vice versa.
3194///
3195/// [^3]: How fast the Wasm program runs when using this collector. Roughly
3196///       equivalent to the number of Wasm instructions executed per
3197///       second. Faster is better. In general, better throughput implies worse
3198///       latency and vice versa.
3199///
3200/// [^4]: How fast can individual objects be allocated?
3201///
3202/// [^5]: How many objects can the collector fit into N bytes of memory? That
3203///       is, how much space for bookkeeping and metadata does this collector
3204///       require? Less space taken up by metadata means more space for
3205///       additional objects. Reference counts are larger than mark bits and
3206///       free lists are larger than bump pointers, for example.
3207#[non_exhaustive]
3208#[derive(PartialEq, Eq, Clone, Debug, Copy)]
3209pub enum Collector {
3210    /// An indicator that the garbage collector should be automatically
3211    /// selected.
3212    ///
3213    /// This is generally what you want for most projects and indicates that the
3214    /// `wasmtime` crate itself should make the decision about what the best
3215    /// collector for a wasm module is.
3216    ///
3217    /// Currently this always defaults to the deferred reference-counting
3218    /// collector, but the default value may change over time.
3219    Auto,
3220
3221    /// The deferred reference-counting collector.
3222    ///
3223    /// A reference-counting collector, generally trading improved latency for
3224    /// worsened throughput. However, to avoid the largest overheads of
3225    /// reference counting, it avoids manipulating reference counts for Wasm
3226    /// objects on the stack. Instead, it will hold a reference count for an
3227    /// over-approximation of all objects that are currently on the stack, trace
3228    /// the stack during collection to find the precise set of on-stack roots,
3229    /// and decrement the reference count of any object that was in the
3230    /// over-approximation but not the precise set. This improves throughput,
3231    /// compared to "pure" reference counting, by performing many fewer
3232    /// refcount-increment and -decrement operations. The cost is the increased
3233    /// latency associated with tracing the stack.
3234    ///
3235    /// This collector cannot currently collect cycles; they will leak until the
3236    /// GC heap's store is dropped.
3237    DeferredReferenceCounting,
3238
3239    /// The null collector.
3240    ///
3241    /// This collector does not actually collect any garbage. It simply
3242    /// allocates objects until it runs out of memory, at which point further
3243    /// objects allocation attempts will trap.
3244    ///
3245    /// This collector is useful for incredibly short-running Wasm instances
3246    /// where additionally you would rather halt an over-allocating Wasm program
3247    /// than spend time collecting its garbage to allow it to keep running. It
3248    /// is also useful for measuring the overheads associated with other
3249    /// collectors, as this collector imposes as close to zero throughput and
3250    /// latency overhead as possible.
3251    Null,
3252}
3253
3254impl Default for Collector {
3255    fn default() -> Collector {
3256        Collector::Auto
3257    }
3258}
3259
3260#[cfg(feature = "gc")]
3261impl Collector {
3262    fn not_auto(&self) -> Option<Collector> {
3263        match self {
3264            Collector::Auto => {
3265                if cfg!(feature = "gc-drc") {
3266                    Some(Collector::DeferredReferenceCounting)
3267                } else if cfg!(feature = "gc-null") {
3268                    Some(Collector::Null)
3269                } else {
3270                    None
3271                }
3272            }
3273            other => Some(*other),
3274        }
3275    }
3276
3277    fn try_not_auto(&self) -> Result<Self> {
3278        match self.not_auto() {
3279            #[cfg(feature = "gc-drc")]
3280            Some(c @ Collector::DeferredReferenceCounting) => Ok(c),
3281            #[cfg(not(feature = "gc-drc"))]
3282            Some(Collector::DeferredReferenceCounting) => bail!(
3283                "cannot create an engine using the deferred reference-counting \
3284                 collector because the `gc-drc` feature was not enabled at \
3285                 compile time",
3286            ),
3287
3288            #[cfg(feature = "gc-null")]
3289            Some(c @ Collector::Null) => Ok(c),
3290            #[cfg(not(feature = "gc-null"))]
3291            Some(Collector::Null) => bail!(
3292                "cannot create an engine using the null collector because \
3293                 the `gc-null` feature was not enabled at compile time",
3294            ),
3295
3296            Some(Collector::Auto) => unreachable!(),
3297
3298            None => bail!(
3299                "cannot create an engine with GC support when none of the \
3300                 collectors are available; enable one of the following \
3301                 features: `gc-drc`, `gc-null`",
3302            ),
3303        }
3304    }
3305}
3306
3307/// Possible optimization levels for the Cranelift codegen backend.
3308#[non_exhaustive]
3309#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3310pub enum OptLevel {
3311    /// No optimizations performed, minimizes compilation time by disabling most
3312    /// optimizations.
3313    None,
3314    /// Generates the fastest possible code, but may take longer.
3315    Speed,
3316    /// Similar to `speed`, but also performs transformations aimed at reducing
3317    /// code size.
3318    SpeedAndSize,
3319}
3320
3321/// Possible register allocator algorithms for the Cranelift codegen backend.
3322#[non_exhaustive]
3323#[derive(Copy, Clone, Debug, Eq, PartialEq)]
3324pub enum RegallocAlgorithm {
3325    /// Generates the fastest possible code, but may take longer.
3326    ///
3327    /// This algorithm performs "backtracking", which means that it may
3328    /// undo its earlier work and retry as it discovers conflicts. This
3329    /// results in better register utilization, producing fewer spills
3330    /// and moves, but can cause super-linear compile runtime.
3331    Backtracking,
3332    /// Generates acceptable code very quickly.
3333    ///
3334    /// This algorithm performs a single pass through the code,
3335    /// guaranteed to work in linear time.  (Note that the rest of
3336    /// Cranelift is not necessarily guaranteed to run in linear time,
3337    /// however.) It cannot undo earlier decisions, however, and it
3338    /// cannot foresee constraints or issues that may occur further
3339    /// ahead in the code, so the code may have more spills and moves as
3340    /// a result.
3341    ///
3342    /// > **Note**: This algorithm is not yet production-ready and has
3343    /// > historically had known problems. It is not recommended to enable this
3344    /// > algorithm for security-sensitive applications and the Wasmtime project
3345    /// > does not consider this configuration option for issuing security
3346    /// > advisories at this time.
3347    SinglePass,
3348}
3349
3350/// Select which profiling technique to support.
3351#[derive(Debug, Clone, Copy, PartialEq)]
3352pub enum ProfilingStrategy {
3353    /// No profiler support.
3354    None,
3355
3356    /// Collect function name information as the "perf map" file format, used with `perf` on Linux.
3357    PerfMap,
3358
3359    /// Collect profiling info for "jitdump" file format, used with `perf` on
3360    /// Linux.
3361    JitDump,
3362
3363    /// Collect profiling info using the "ittapi", used with `VTune` on Linux.
3364    VTune,
3365
3366    /// Support for profiling Pulley, Wasmtime's interpreter. Note that enabling
3367    /// this at runtime requires enabling the `profile-pulley` Cargo feature at
3368    /// compile time.
3369    Pulley,
3370}
3371
3372/// Select how wasm backtrace detailed information is handled.
3373#[derive(Debug, Clone, Copy)]
3374pub enum WasmBacktraceDetails {
3375    /// Support is unconditionally enabled and wasmtime will parse and read
3376    /// debug information.
3377    Enable,
3378
3379    /// Support is disabled, and wasmtime will not parse debug information for
3380    /// backtrace details.
3381    Disable,
3382
3383    /// Support for backtrace details is conditional on the
3384    /// `WASMTIME_BACKTRACE_DETAILS` environment variable.
3385    Environment,
3386}
3387
3388/// Describe the tri-state configuration of keys such as MPK or PAGEMAP_SCAN.
3389#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
3390pub enum Enabled {
3391    /// Enable this feature if it's detected on the host system, otherwise leave
3392    /// it disabled.
3393    Auto,
3394    /// Enable this feature and fail configuration if the feature is not
3395    /// detected on the host system.
3396    Yes,
3397    /// Do not enable this feature, even if the host system supports it.
3398    No,
3399}
3400
3401/// Configuration options used with [`InstanceAllocationStrategy::Pooling`] to
3402/// change the behavior of the pooling instance allocator.
3403///
3404/// This structure has a builder-style API in the same manner as [`Config`] and
3405/// is configured with [`Config::allocation_strategy`].
3406///
3407/// Note that usage of the pooling allocator does not affect compiled
3408/// WebAssembly code. Compiled `*.cwasm` files, for example, are usable both
3409/// with and without the pooling allocator.
3410///
3411/// ## Advantages of Pooled Allocation
3412///
3413/// The main benefit of the pooling allocator is to make WebAssembly
3414/// instantiation both faster and more scalable in terms of parallelism.
3415/// Allocation is faster because virtual memory is already configured and ready
3416/// to go within the pool, there's no need to [`mmap`] (for example on Unix) a
3417/// new region and configure it with guard pages. By avoiding [`mmap`] this
3418/// avoids whole-process virtual memory locks which can improve scalability and
3419/// performance through avoiding this.
3420///
3421/// Additionally with pooled allocation it's possible to create "affine slots"
3422/// to a particular WebAssembly module or component over time. For example if
3423/// the same module is multiple times over time the pooling allocator will, by
3424/// default, attempt to reuse the same slot. This mean that the slot has been
3425/// pre-configured and can retain virtual memory mappings for a copy-on-write
3426/// image, for example (see [`Config::memory_init_cow`] for more information.
3427/// This means that in a steady state instance deallocation is a single
3428/// [`madvise`] to reset linear memory to its original contents followed by a
3429/// single (optional) [`mprotect`] during the next instantiation to shrink
3430/// memory back to its original size. Compared to non-pooled allocation this
3431/// avoids the need to [`mmap`] a new region of memory, [`munmap`] it, and
3432/// [`mprotect`] regions too.
3433///
3434/// Another benefit of pooled allocation is that it's possible to configure
3435/// things such that no virtual memory management is required at all in a steady
3436/// state. For example a pooling allocator can be configured with:
3437///
3438/// * [`Config::memory_init_cow`] disabled
3439/// * [`Config::memory_guard_size`] disabled
3440/// * [`Config::memory_reservation`] shrunk to minimal size
3441/// * [`PoolingAllocationConfig::table_keep_resident`] sufficiently large
3442/// * [`PoolingAllocationConfig::linear_memory_keep_resident`] sufficiently large
3443///
3444/// With all these options in place no virtual memory tricks are used at all and
3445/// everything is manually managed by Wasmtime (for example resetting memory is
3446/// a `memset(0)`). This is not as fast in a single-threaded scenario but can
3447/// provide benefits in high-parallelism situations as no virtual memory locks
3448/// or IPIs need happen.
3449///
3450/// ## Disadvantages of Pooled Allocation
3451///
3452/// Despite the above advantages to instantiation performance the pooling
3453/// allocator is not enabled by default in Wasmtime. One reason is that the
3454/// performance advantages are not necessarily portable, for example while the
3455/// pooling allocator works on Windows it has not been tuned for performance on
3456/// Windows in the same way it has on Linux.
3457///
3458/// Additionally the main cost of the pooling allocator is that it requires a
3459/// very large reservation of virtual memory (on the order of most of the
3460/// addressable virtual address space). WebAssembly 32-bit linear memories in
3461/// Wasmtime are, by default 4G address space reservations with a small guard
3462/// region both before and after the linear memory. Memories in the pooling
3463/// allocator are contiguous which means that we only need a guard after linear
3464/// memory because the previous linear memory's slot post-guard is our own
3465/// pre-guard. This means that, by default, the pooling allocator uses roughly
3466/// 4G of virtual memory per WebAssembly linear memory slot. 4G of virtual
3467/// memory is 32 bits of a 64-bit address. Many 64-bit systems can only
3468/// actually use 48-bit addresses by default (although this can be extended on
3469/// architectures nowadays too), and of those 48 bits one of them is reserved
3470/// to indicate kernel-vs-userspace. This leaves 47-32=15 bits left,
3471/// meaning you can only have at most 32k slots of linear memories on many
3472/// systems by default. This is a relatively small number and shows how the
3473/// pooling allocator can quickly exhaust all of virtual memory.
3474///
3475/// Another disadvantage of the pooling allocator is that it may keep memory
3476/// alive when nothing is using it. A previously used slot for an instance might
3477/// have paged-in memory that will not get paged out until the
3478/// [`Engine`](crate::Engine) owning the pooling allocator is dropped. While
3479/// suitable for some applications this behavior may not be suitable for all
3480/// applications.
3481///
3482/// Finally the last disadvantage of the pooling allocator is that the
3483/// configuration values for the maximum number of instances, memories, tables,
3484/// etc, must all be fixed up-front. There's not always a clear answer as to
3485/// what these values should be so not all applications may be able to work
3486/// with this constraint.
3487///
3488/// [`madvise`]: https://man7.org/linux/man-pages/man2/madvise.2.html
3489/// [`mprotect`]: https://man7.org/linux/man-pages/man2/mprotect.2.html
3490/// [`mmap`]: https://man7.org/linux/man-pages/man2/mmap.2.html
3491/// [`munmap`]: https://man7.org/linux/man-pages/man2/munmap.2.html
3492#[cfg(feature = "pooling-allocator")]
3493#[derive(Debug, Clone, Default)]
3494pub struct PoolingAllocationConfig {
3495    config: crate::runtime::vm::PoolingInstanceAllocatorConfig,
3496}
3497
3498#[cfg(feature = "pooling-allocator")]
3499impl PoolingAllocationConfig {
3500    /// Returns a new configuration builder with all default settings
3501    /// configured.
3502    pub fn new() -> PoolingAllocationConfig {
3503        PoolingAllocationConfig::default()
3504    }
3505
3506    /// Configures the maximum number of "unused warm slots" to retain in the
3507    /// pooling allocator.
3508    ///
3509    /// The pooling allocator operates over slots to allocate from, and each
3510    /// slot is considered "cold" if it's never been used before or "warm" if
3511    /// it's been used by some module in the past. Slots in the pooling
3512    /// allocator additionally track an "affinity" flag to a particular core
3513    /// wasm module. When a module is instantiated into a slot then the slot is
3514    /// considered affine to that module, even after the instance has been
3515    /// deallocated.
3516    ///
3517    /// When a new instance is created then a slot must be chosen, and the
3518    /// current algorithm for selecting a slot is:
3519    ///
3520    /// * If there are slots that are affine to the module being instantiated,
3521    ///   then the most recently used slot is selected to be allocated from.
3522    ///   This is done to improve reuse of resources such as memory mappings and
3523    ///   additionally try to benefit from temporal locality for things like
3524    ///   caches.
3525    ///
3526    /// * Otherwise if there are more than N affine slots to other modules, then
3527    ///   one of those affine slots is chosen to be allocated. The slot chosen
3528    ///   is picked on a least-recently-used basis.
3529    ///
3530    /// * Finally, if there are less than N affine slots to other modules, then
3531    ///   the non-affine slots are allocated from.
3532    ///
3533    /// This setting, `max_unused_warm_slots`, is the value for N in the above
3534    /// algorithm. The purpose of this setting is to have a knob over the RSS
3535    /// impact of "unused slots" for a long-running wasm server.
3536    ///
3537    /// If this setting is set to 0, for example, then affine slots are
3538    /// aggressively reused on a least-recently-used basis. A "cold" slot is
3539    /// only used if there are no affine slots available to allocate from. This
3540    /// means that the set of slots used over the lifetime of a program is the
3541    /// same as the maximum concurrent number of wasm instances.
3542    ///
3543    /// If this setting is set to infinity, however, then cold slots are
3544    /// prioritized to be allocated from. This means that the set of slots used
3545    /// over the lifetime of a program will approach
3546    /// [`PoolingAllocationConfig::total_memories`], or the maximum number of
3547    /// slots in the pooling allocator.
3548    ///
3549    /// Wasmtime does not aggressively decommit all resources associated with a
3550    /// slot when the slot is not in use. For example the
3551    /// [`PoolingAllocationConfig::linear_memory_keep_resident`] option can be
3552    /// used to keep memory associated with a slot, even when it's not in use.
3553    /// This means that the total set of used slots in the pooling instance
3554    /// allocator can impact the overall RSS usage of a program.
3555    ///
3556    /// The default value for this option is `100`.
3557    pub fn max_unused_warm_slots(&mut self, max: u32) -> &mut Self {
3558        self.config.max_unused_warm_slots = max;
3559        self
3560    }
3561
3562    /// The target number of decommits to do per batch.
3563    ///
3564    /// This is not precise, as we can queue up decommits at times when we
3565    /// aren't prepared to immediately flush them, and so we may go over this
3566    /// target size occasionally.
3567    ///
3568    /// A batch size of one effectively disables batching.
3569    ///
3570    /// Defaults to `1`.
3571    pub fn decommit_batch_size(&mut self, batch_size: usize) -> &mut Self {
3572        self.config.decommit_batch_size = batch_size;
3573        self
3574    }
3575
3576    /// How much memory, in bytes, to keep resident for async stacks allocated
3577    /// with the pooling allocator.
3578    ///
3579    /// When [`Config::async_stack_zeroing`] is enabled then Wasmtime will reset
3580    /// the contents of async stacks back to zero upon deallocation. This option
3581    /// can be used to perform the zeroing operation with `memset` up to a
3582    /// certain threshold of bytes instead of using system calls to reset the
3583    /// stack to zero.
3584    ///
3585    /// Note that when using this option the memory with async stacks will
3586    /// never be decommitted.
3587    #[cfg(feature = "async")]
3588    pub fn async_stack_keep_resident(&mut self, size: usize) -> &mut Self {
3589        self.config.async_stack_keep_resident = size;
3590        self
3591    }
3592
3593    /// How much memory, in bytes, to keep resident for each linear memory
3594    /// after deallocation.
3595    ///
3596    /// This option is only applicable on Linux and has no effect on other
3597    /// platforms.
3598    ///
3599    /// By default Wasmtime will use `madvise` to reset the entire contents of
3600    /// linear memory back to zero when a linear memory is deallocated. This
3601    /// option can be used to use `memset` instead to set memory back to zero
3602    /// which can, in some configurations, reduce the number of page faults
3603    /// taken when a slot is reused.
3604    pub fn linear_memory_keep_resident(&mut self, size: usize) -> &mut Self {
3605        self.config.linear_memory_keep_resident = size;
3606        self
3607    }
3608
3609    /// How much memory, in bytes, to keep resident for each table after
3610    /// deallocation.
3611    ///
3612    /// This option is only applicable on Linux and has no effect on other
3613    /// platforms.
3614    ///
3615    /// This option is the same as
3616    /// [`PoolingAllocationConfig::linear_memory_keep_resident`] except that it
3617    /// is applicable to tables instead.
3618    pub fn table_keep_resident(&mut self, size: usize) -> &mut Self {
3619        self.config.table_keep_resident = size;
3620        self
3621    }
3622
3623    /// The maximum number of concurrent component instances supported (default
3624    /// is `1000`).
3625    ///
3626    /// This provides an upper-bound on the total size of component
3627    /// metadata-related allocations, along with
3628    /// [`PoolingAllocationConfig::max_component_instance_size`]. The upper bound is
3629    ///
3630    /// ```text
3631    /// total_component_instances * max_component_instance_size
3632    /// ```
3633    ///
3634    /// where `max_component_instance_size` is rounded up to the size and alignment
3635    /// of the internal representation of the metadata.
3636    pub fn total_component_instances(&mut self, count: u32) -> &mut Self {
3637        self.config.limits.total_component_instances = count;
3638        self
3639    }
3640
3641    /// The maximum size, in bytes, allocated for a component instance's
3642    /// `VMComponentContext` metadata.
3643    ///
3644    /// The [`wasmtime::component::Instance`][crate::component::Instance] type
3645    /// has a static size but its internal `VMComponentContext` is dynamically
3646    /// sized depending on the component being instantiated. This size limit
3647    /// loosely correlates to the size of the component, taking into account
3648    /// factors such as:
3649    ///
3650    /// * number of lifted and lowered functions,
3651    /// * number of memories
3652    /// * number of inner instances
3653    /// * number of resources
3654    ///
3655    /// If the allocated size per instance is too small then instantiation of a
3656    /// module will fail at runtime with an error indicating how many bytes were
3657    /// needed.
3658    ///
3659    /// The default value for this is 1MiB.
3660    ///
3661    /// This provides an upper-bound on the total size of component
3662    /// metadata-related allocations, along with
3663    /// [`PoolingAllocationConfig::total_component_instances`]. The upper bound is
3664    ///
3665    /// ```text
3666    /// total_component_instances * max_component_instance_size
3667    /// ```
3668    ///
3669    /// where `max_component_instance_size` is rounded up to the size and alignment
3670    /// of the internal representation of the metadata.
3671    pub fn max_component_instance_size(&mut self, size: usize) -> &mut Self {
3672        self.config.limits.component_instance_size = size;
3673        self
3674    }
3675
3676    /// The maximum number of core instances a single component may contain
3677    /// (default is unlimited).
3678    ///
3679    /// This method (along with
3680    /// [`PoolingAllocationConfig::max_memories_per_component`],
3681    /// [`PoolingAllocationConfig::max_tables_per_component`], and
3682    /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
3683    /// the amount of resources a single component allocation consumes.
3684    ///
3685    /// If a component will instantiate more core instances than `count`, then
3686    /// the component will fail to instantiate.
3687    pub fn max_core_instances_per_component(&mut self, count: u32) -> &mut Self {
3688        self.config.limits.max_core_instances_per_component = count;
3689        self
3690    }
3691
3692    /// The maximum number of Wasm linear memories that a single component may
3693    /// transitively contain (default is unlimited).
3694    ///
3695    /// This method (along with
3696    /// [`PoolingAllocationConfig::max_core_instances_per_component`],
3697    /// [`PoolingAllocationConfig::max_tables_per_component`], and
3698    /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
3699    /// the amount of resources a single component allocation consumes.
3700    ///
3701    /// If a component transitively contains more linear memories than `count`,
3702    /// then the component will fail to instantiate.
3703    pub fn max_memories_per_component(&mut self, count: u32) -> &mut Self {
3704        self.config.limits.max_memories_per_component = count;
3705        self
3706    }
3707
3708    /// The maximum number of tables that a single component may transitively
3709    /// contain (default is unlimited).
3710    ///
3711    /// This method (along with
3712    /// [`PoolingAllocationConfig::max_core_instances_per_component`],
3713    /// [`PoolingAllocationConfig::max_memories_per_component`],
3714    /// [`PoolingAllocationConfig::max_component_instance_size`]) allows you to cap
3715    /// the amount of resources a single component allocation consumes.
3716    ///
3717    /// If a component will transitively contains more tables than `count`, then
3718    /// the component will fail to instantiate.
3719    pub fn max_tables_per_component(&mut self, count: u32) -> &mut Self {
3720        self.config.limits.max_tables_per_component = count;
3721        self
3722    }
3723
3724    /// The maximum number of concurrent Wasm linear memories supported (default
3725    /// is `1000`).
3726    ///
3727    /// This value has a direct impact on the amount of memory allocated by the pooling
3728    /// instance allocator.
3729    ///
3730    /// The pooling instance allocator allocates a memory pool, where each entry
3731    /// in the pool contains the reserved address space for each linear memory
3732    /// supported by an instance.
3733    ///
3734    /// The memory pool will reserve a large quantity of host process address
3735    /// space to elide the bounds checks required for correct WebAssembly memory
3736    /// semantics. Even with 64-bit address spaces, the address space is limited
3737    /// when dealing with a large number of linear memories.
3738    ///
3739    /// For example, on Linux x86_64, the userland address space limit is 128
3740    /// TiB. That might seem like a lot, but each linear memory will *reserve* 6
3741    /// GiB of space by default.
3742    pub fn total_memories(&mut self, count: u32) -> &mut Self {
3743        self.config.limits.total_memories = count;
3744        self
3745    }
3746
3747    /// The maximum number of concurrent tables supported (default is `1000`).
3748    ///
3749    /// This value has a direct impact on the amount of memory allocated by the
3750    /// pooling instance allocator.
3751    ///
3752    /// The pooling instance allocator allocates a table pool, where each entry
3753    /// in the pool contains the space needed for each WebAssembly table
3754    /// supported by an instance (see `table_elements` to control the size of
3755    /// each table).
3756    pub fn total_tables(&mut self, count: u32) -> &mut Self {
3757        self.config.limits.total_tables = count;
3758        self
3759    }
3760
3761    /// The maximum number of execution stacks allowed for asynchronous
3762    /// execution, when enabled (default is `1000`).
3763    ///
3764    /// This value has a direct impact on the amount of memory allocated by the
3765    /// pooling instance allocator.
3766    #[cfg(feature = "async")]
3767    pub fn total_stacks(&mut self, count: u32) -> &mut Self {
3768        self.config.limits.total_stacks = count;
3769        self
3770    }
3771
3772    /// The maximum number of concurrent core instances supported (default is
3773    /// `1000`).
3774    ///
3775    /// This provides an upper-bound on the total size of core instance
3776    /// metadata-related allocations, along with
3777    /// [`PoolingAllocationConfig::max_core_instance_size`]. The upper bound is
3778    ///
3779    /// ```text
3780    /// total_core_instances * max_core_instance_size
3781    /// ```
3782    ///
3783    /// where `max_core_instance_size` is rounded up to the size and alignment of
3784    /// the internal representation of the metadata.
3785    pub fn total_core_instances(&mut self, count: u32) -> &mut Self {
3786        self.config.limits.total_core_instances = count;
3787        self
3788    }
3789
3790    /// The maximum size, in bytes, allocated for a core instance's `VMContext`
3791    /// metadata.
3792    ///
3793    /// The [`Instance`][crate::Instance] type has a static size but its
3794    /// `VMContext` metadata is dynamically sized depending on the module being
3795    /// instantiated. This size limit loosely correlates to the size of the Wasm
3796    /// module, taking into account factors such as:
3797    ///
3798    /// * number of functions
3799    /// * number of globals
3800    /// * number of memories
3801    /// * number of tables
3802    /// * number of function types
3803    ///
3804    /// If the allocated size per instance is too small then instantiation of a
3805    /// module will fail at runtime with an error indicating how many bytes were
3806    /// needed.
3807    ///
3808    /// The default value for this is 1MiB.
3809    ///
3810    /// This provides an upper-bound on the total size of core instance
3811    /// metadata-related allocations, along with
3812    /// [`PoolingAllocationConfig::total_core_instances`]. The upper bound is
3813    ///
3814    /// ```text
3815    /// total_core_instances * max_core_instance_size
3816    /// ```
3817    ///
3818    /// where `max_core_instance_size` is rounded up to the size and alignment of
3819    /// the internal representation of the metadata.
3820    pub fn max_core_instance_size(&mut self, size: usize) -> &mut Self {
3821        self.config.limits.core_instance_size = size;
3822        self
3823    }
3824
3825    /// The maximum number of defined tables for a core module (default is `1`).
3826    ///
3827    /// This value controls the capacity of the `VMTableDefinition` table in
3828    /// each instance's `VMContext` structure.
3829    ///
3830    /// The allocated size of the table will be `tables *
3831    /// sizeof(VMTableDefinition)` for each instance regardless of how many
3832    /// tables are defined by an instance's module.
3833    pub fn max_tables_per_module(&mut self, tables: u32) -> &mut Self {
3834        self.config.limits.max_tables_per_module = tables;
3835        self
3836    }
3837
3838    /// The maximum table elements for any table defined in a module (default is
3839    /// `20000`).
3840    ///
3841    /// If a table's minimum element limit is greater than this value, the
3842    /// module will fail to instantiate.
3843    ///
3844    /// If a table's maximum element limit is unbounded or greater than this
3845    /// value, the maximum will be `table_elements` for the purpose of any
3846    /// `table.grow` instruction.
3847    ///
3848    /// This value is used to reserve the maximum space for each supported
3849    /// table; table elements are pointer-sized in the Wasmtime runtime.
3850    /// Therefore, the space reserved for each instance is `tables *
3851    /// table_elements * sizeof::<*const ()>`.
3852    pub fn table_elements(&mut self, elements: usize) -> &mut Self {
3853        self.config.limits.table_elements = elements;
3854        self
3855    }
3856
3857    /// The maximum number of defined linear memories for a module (default is
3858    /// `1`).
3859    ///
3860    /// This value controls the capacity of the `VMMemoryDefinition` table in
3861    /// each core instance's `VMContext` structure.
3862    ///
3863    /// The allocated size of the table will be `memories *
3864    /// sizeof(VMMemoryDefinition)` for each core instance regardless of how
3865    /// many memories are defined by the core instance's module.
3866    pub fn max_memories_per_module(&mut self, memories: u32) -> &mut Self {
3867        self.config.limits.max_memories_per_module = memories;
3868        self
3869    }
3870
3871    /// The maximum byte size that any WebAssembly linear memory may grow to.
3872    ///
3873    /// This option defaults to 4 GiB meaning that for 32-bit linear memories
3874    /// there is no restrictions. 64-bit linear memories will not be allowed to
3875    /// grow beyond 4 GiB by default.
3876    ///
3877    /// If a memory's minimum size is greater than this value, the module will
3878    /// fail to instantiate.
3879    ///
3880    /// If a memory's maximum size is unbounded or greater than this value, the
3881    /// maximum will be `max_memory_size` for the purpose of any `memory.grow`
3882    /// instruction.
3883    ///
3884    /// This value is used to control the maximum accessible space for each
3885    /// linear memory of a core instance. This can be thought of as a simple
3886    /// mechanism like [`Store::limiter`](crate::Store::limiter) to limit memory
3887    /// at runtime. This value can also affect striping/coloring behavior when
3888    /// used in conjunction with
3889    /// [`memory_protection_keys`](PoolingAllocationConfig::memory_protection_keys).
3890    ///
3891    /// The virtual memory reservation size of each linear memory is controlled
3892    /// by the [`Config::memory_reservation`] setting and this method's
3893    /// configuration cannot exceed [`Config::memory_reservation`].
3894    pub fn max_memory_size(&mut self, bytes: usize) -> &mut Self {
3895        self.config.limits.max_memory_size = bytes;
3896        self
3897    }
3898
3899    /// Configures whether memory protection keys (MPK) should be used for more
3900    /// efficient layout of pool-allocated memories.
3901    ///
3902    /// When using the pooling allocator (see [`Config::allocation_strategy`],
3903    /// [`InstanceAllocationStrategy::Pooling`]), memory protection keys can
3904    /// reduce the total amount of allocated virtual memory by eliminating guard
3905    /// regions between WebAssembly memories in the pool. It does so by
3906    /// "coloring" memory regions with different memory keys and setting which
3907    /// regions are accessible each time executions switches from host to guest
3908    /// (or vice versa).
3909    ///
3910    /// Leveraging MPK requires configuring a smaller-than-default
3911    /// [`max_memory_size`](PoolingAllocationConfig::max_memory_size) to enable
3912    /// this coloring/striping behavior. For example embeddings might want to
3913    /// reduce the default 4G allowance to 128M.
3914    ///
3915    /// MPK is only available on Linux (called `pku` there) and recent x86
3916    /// systems; we check for MPK support at runtime by examining the `CPUID`
3917    /// register. This configuration setting can be in three states:
3918    ///
3919    /// - `auto`: if MPK support is available the guard regions are removed; if
3920    ///   not, the guard regions remain
3921    /// - `yes`: use MPK to eliminate guard regions; fail if MPK is not
3922    ///   supported
3923    /// - `no`: never use MPK
3924    ///
3925    /// By default this value is `no`, but may become `auto` in future
3926    /// releases.
3927    ///
3928    /// __WARNING__: this configuration options is still experimental--use at
3929    /// your own risk! MPK uses kernel and CPU features to protect memory
3930    /// regions; you may observe segmentation faults if anything is
3931    /// misconfigured.
3932    #[cfg(feature = "memory-protection-keys")]
3933    pub fn memory_protection_keys(&mut self, enable: Enabled) -> &mut Self {
3934        self.config.memory_protection_keys = enable;
3935        self
3936    }
3937
3938    /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
3939    /// will use.
3940    ///
3941    /// This setting is only applicable when
3942    /// [`PoolingAllocationConfig::memory_protection_keys`] is set to `enable`
3943    /// or `auto`. Configuring this above the HW and OS limits (typically 15)
3944    /// has no effect.
3945    ///
3946    /// If multiple Wasmtime engines are used in the same process, note that all
3947    /// engines will share the same set of allocated keys; this setting will
3948    /// limit how many keys are allocated initially and thus available to all
3949    /// other engines.
3950    #[cfg(feature = "memory-protection-keys")]
3951    pub fn max_memory_protection_keys(&mut self, max: usize) -> &mut Self {
3952        self.config.max_memory_protection_keys = max;
3953        self
3954    }
3955
3956    /// Check if memory protection keys (MPK) are available on the current host.
3957    ///
3958    /// This is a convenience method for determining MPK availability using the
3959    /// same method that [`Enabled::Auto`] does. See
3960    /// [`PoolingAllocationConfig::memory_protection_keys`] for more
3961    /// information.
3962    #[cfg(feature = "memory-protection-keys")]
3963    pub fn are_memory_protection_keys_available() -> bool {
3964        crate::runtime::vm::mpk::is_supported()
3965    }
3966
3967    /// The maximum number of concurrent GC heaps supported (default is `1000`).
3968    ///
3969    /// This value has a direct impact on the amount of memory allocated by the
3970    /// pooling instance allocator.
3971    ///
3972    /// The pooling instance allocator allocates a GC heap pool, where each
3973    /// entry in the pool contains the space needed for each GC heap used by a
3974    /// store.
3975    #[cfg(feature = "gc")]
3976    pub fn total_gc_heaps(&mut self, count: u32) -> &mut Self {
3977        self.config.limits.total_gc_heaps = count;
3978        self
3979    }
3980
3981    /// Configures whether the Linux-specific [`PAGEMAP_SCAN` ioctl][ioctl] is
3982    /// used to help reset linear memory.
3983    ///
3984    /// When [`Self::linear_memory_keep_resident`] or
3985    /// [`Self::table_keep_resident`] options are configured to nonzero values
3986    /// the default behavior is to `memset` the lowest addresses of a table or
3987    /// memory back to their original contents. With the `PAGEMAP_SCAN` ioctl on
3988    /// Linux this can be done to more intelligently scan for resident pages in
3989    /// the region and only reset those pages back to their original contents
3990    /// with `memset` rather than assuming the low addresses are all resident.
3991    ///
3992    /// This ioctl has the potential to provide a number of performance benefits
3993    /// in high-reuse and high concurrency scenarios. Notably this enables
3994    /// Wasmtime to scan the entire region of WebAssembly linear memory and
3995    /// manually reset memory back to its original contents, up to
3996    /// [`Self::linear_memory_keep_resident`] bytes, possibly skipping an
3997    /// `madvise` entirely. This can be more efficient by avoiding removing
3998    /// pages from the address space entirely and additionally ensuring that
3999    /// future use of the linear memory doesn't incur page faults as the pages
4000    /// remain resident.
4001    ///
4002    /// At this time this configuration option is still being evaluated as to
4003    /// how appropriate it is for all use cases. It currently defaults to
4004    /// `no` or disabled but may change to `auto`, enable if supported, in the
4005    /// future. This option is only supported on Linux and requires a kernel
4006    /// version of 6.7 or higher.
4007    ///
4008    /// [ioctl]: https://www.man7.org/linux/man-pages/man2/PAGEMAP_SCAN.2const.html
4009    pub fn pagemap_scan(&mut self, enable: Enabled) -> &mut Self {
4010        self.config.pagemap_scan = enable;
4011        self
4012    }
4013
4014    /// Tests whether [`Self::pagemap_scan`] is available or not on the host
4015    /// system.
4016    pub fn is_pagemap_scan_available() -> bool {
4017        crate::runtime::vm::PoolingInstanceAllocatorConfig::is_pagemap_scan_available()
4018    }
4019}
4020
4021#[cfg(feature = "std")]
4022fn detect_host_feature(feature: &str) -> Option<bool> {
4023    #[cfg(target_arch = "aarch64")]
4024    {
4025        return match feature {
4026            "lse" => Some(std::arch::is_aarch64_feature_detected!("lse")),
4027            "paca" => Some(std::arch::is_aarch64_feature_detected!("paca")),
4028            "fp16" => Some(std::arch::is_aarch64_feature_detected!("fp16")),
4029
4030            _ => None,
4031        };
4032    }
4033
4034    // `is_s390x_feature_detected` is nightly only for now, so use the
4035    // STORE FACILITY LIST EXTENDED instruction as a temporary measure.
4036    #[cfg(target_arch = "s390x")]
4037    {
4038        let mut facility_list: [u64; 4] = [0; 4];
4039        unsafe {
4040            core::arch::asm!(
4041                "stfle 0({})",
4042                in(reg_addr) facility_list.as_mut_ptr() ,
4043                inout("r0") facility_list.len() as u64 - 1 => _,
4044                options(nostack)
4045            );
4046        }
4047        let get_facility_bit = |n: usize| {
4048            // NOTE: bits are numbered from the left.
4049            facility_list[n / 64] & (1 << (63 - (n % 64))) != 0
4050        };
4051
4052        return match feature {
4053            "mie3" => Some(get_facility_bit(61)),
4054            "mie4" => Some(get_facility_bit(84)),
4055            "vxrs_ext2" => Some(get_facility_bit(148)),
4056            "vxrs_ext3" => Some(get_facility_bit(198)),
4057
4058            _ => None,
4059        };
4060    }
4061
4062    #[cfg(target_arch = "riscv64")]
4063    {
4064        return match feature {
4065            // due to `is_riscv64_feature_detected` is not stable.
4066            // we cannot use it. For now lie and say all features are always
4067            // found to keep tests working.
4068            _ => Some(true),
4069        };
4070    }
4071
4072    #[cfg(target_arch = "x86_64")]
4073    {
4074        return match feature {
4075            "cmpxchg16b" => Some(std::is_x86_feature_detected!("cmpxchg16b")),
4076            "sse3" => Some(std::is_x86_feature_detected!("sse3")),
4077            "ssse3" => Some(std::is_x86_feature_detected!("ssse3")),
4078            "sse4.1" => Some(std::is_x86_feature_detected!("sse4.1")),
4079            "sse4.2" => Some(std::is_x86_feature_detected!("sse4.2")),
4080            "popcnt" => Some(std::is_x86_feature_detected!("popcnt")),
4081            "avx" => Some(std::is_x86_feature_detected!("avx")),
4082            "avx2" => Some(std::is_x86_feature_detected!("avx2")),
4083            "fma" => Some(std::is_x86_feature_detected!("fma")),
4084            "bmi1" => Some(std::is_x86_feature_detected!("bmi1")),
4085            "bmi2" => Some(std::is_x86_feature_detected!("bmi2")),
4086            "avx512bitalg" => Some(std::is_x86_feature_detected!("avx512bitalg")),
4087            "avx512dq" => Some(std::is_x86_feature_detected!("avx512dq")),
4088            "avx512f" => Some(std::is_x86_feature_detected!("avx512f")),
4089            "avx512vl" => Some(std::is_x86_feature_detected!("avx512vl")),
4090            "avx512vbmi" => Some(std::is_x86_feature_detected!("avx512vbmi")),
4091            "lzcnt" => Some(std::is_x86_feature_detected!("lzcnt")),
4092
4093            _ => None,
4094        };
4095    }
4096
4097    #[allow(
4098        unreachable_code,
4099        reason = "reachable or not depending on if a target above matches"
4100    )]
4101    {
4102        let _ = feature;
4103        return None;
4104    }
4105}