Skip to main content

wasmtime/
config.rs

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