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