Skip to main content

wasmtime_environ/
tunables.rs

1use crate::prelude::*;
2use crate::{IndexType, Limits, Memory, TripleExt};
3use core::num::NonZeroU32;
4use core::{fmt, str::FromStr};
5use serde_derive::{Deserialize, Serialize};
6use target_lexicon::{PointerWidth, Triple};
7use wasmparser::Operator;
8
9macro_rules! define_tunables {
10    (
11        $(#[$outer_attr:meta])*
12        pub struct $tunables:ident {
13            $(
14                $(#[$field_attr:meta])*
15                pub $field:ident : $field_ty:ty,
16            )*
17        }
18
19        pub struct $config_tunables:ident {
20            ...
21        }
22    ) => {
23        $(#[$outer_attr])*
24        pub struct $tunables {
25            $(
26                $(#[$field_attr])*
27                pub $field: $field_ty,
28            )*
29        }
30
31        /// Optional tunable configuration options used in `wasmtime::Config`
32        #[derive(Default, Clone)]
33        #[expect(missing_docs, reason = "macro-generated fields")]
34        pub struct $config_tunables {
35            $(pub $field: Option<$field_ty>,)*
36        }
37
38        impl $config_tunables {
39            /// Formats configured fields into `f`.
40            pub fn format(&self, f: &mut fmt::DebugStruct<'_,'_>) {
41                $(
42                    if let Some(val) = &self.$field {
43                        f.field(stringify!($field), val);
44                    }
45                )*
46            }
47
48            /// Configure the `Tunables` provided.
49            pub fn configure(&self, tunables: &mut Tunables) {
50                $(
51                    if let Some(val) = &self.$field {
52                        tunables.$field = val.clone();
53                    }
54                )*
55            }
56        }
57    };
58}
59
60define_tunables! {
61    /// Tunable parameters for WebAssembly compilation.
62    #[derive(Clone, Hash, Serialize, Deserialize, Debug)]
63    pub struct Tunables {
64        /// The garbage collector implementation to use, which implies the layout of
65        /// GC objects and barriers that must be emitted in Wasm code.
66        pub collector: Option<Collector>,
67
68        /// Initial size, in bytes, to be allocated for linear memories.
69        pub memory_reservation: u64,
70
71        /// The size, in bytes, of the guard page region for linear memories.
72        pub memory_guard_size: u64,
73
74        /// The size, in bytes, to allocate at the end of a relocated linear
75        /// memory for growth.
76        pub memory_reservation_for_growth: u64,
77
78        /// Whether or not to generate native DWARF debug information.
79        pub debug_native: bool,
80
81        /// Whether we are enabling precise Wasm-level debugging in
82        /// the guest.
83        pub debug_guest: bool,
84
85        /// Whether or not to retain DWARF sections in compiled modules.
86        pub parse_wasm_debuginfo: bool,
87
88        /// Whether or not fuel is enabled for generated code, meaning that fuel
89        /// will be consumed every time a wasm instruction is executed.
90        pub consume_fuel: bool,
91
92        /// The cost of each operator. If fuel is not enabled, this is ignored.
93        pub operator_cost: OperatorCostStrategy,
94
95        /// Whether or not we use epoch-based interruption.
96        pub epoch_interruption: bool,
97
98        /// Whether or not linear memories are allowed to be reallocated after
99        /// initial allocation at runtime.
100        pub memory_may_move: bool,
101
102        /// Whether or not linear memory allocations will have a guard region at the
103        /// beginning of the allocation in addition to the end.
104        pub guard_before_linear_memory: bool,
105
106        /// Whether to initialize tables lazily, so that instantiation is fast but
107        /// indirect calls are a little slower. If false, tables are initialized
108        /// eagerly from any active element segments that apply to them during
109        /// instantiation.
110        pub table_lazy_init: bool,
111
112        /// Indicates whether an address map from compiled native code back to wasm
113        /// offsets in the original file is generated.
114        pub generate_address_map: bool,
115
116        /// Flag for the component module whether adapter modules have debug
117        /// assertions baked into them.
118        pub debug_adapter_modules: bool,
119
120        /// Whether or not lowerings for relaxed simd instructions are forced to
121        /// be deterministic.
122        pub relaxed_simd_deterministic: bool,
123
124        /// Whether or not Wasm functions target the winch abi.
125        pub winch_callable: bool,
126
127        /// Whether or not the host will be using native signals (e.g. SIGILL,
128        /// SIGSEGV, etc) to implement traps.
129        pub signals_based_traps: bool,
130
131        /// Whether CoW images might be used to initialize linear memories.
132        pub memory_init_cow: bool,
133
134        /// Whether to enable inlining in Wasmtime's compilation orchestration
135        /// or not.
136        pub inlining: bool,
137
138        /// Whether to inline calls within the same core Wasm module or not.
139        pub inlining_intra_module: IntraModuleInlining,
140
141        /// The size of "small callees" that can be inlined regardless of the
142        /// caller's size.
143        pub inlining_small_callee_size: u32,
144
145        /// The general size threshold for the sum of the caller's and callee's
146        /// sizes, past which we will generally not inline calls anymore.
147        pub inlining_sum_size_threshold: u32,
148
149        /// Whether any component model feature related to concurrency is
150        /// enabled.
151        pub concurrency_support: bool,
152
153        /// Whether recording in RR is enabled or not. This is used primarily
154        /// to signal checksum computation for compiled artifacts.
155        pub recording: bool,
156
157        /// An allocation counter that triggers GC when it reaches zero.
158        ///
159        /// Decremented on every allocation and when it hits zero, a GC is
160        /// forced and the counter is reset. Only effective when
161        /// `cfg(gc_zeal)` is enabled.
162        pub gc_zeal_alloc_counter: Option<NonZeroU32>,
163
164        /// Initial size, in bytes, to be allocated for GC heaps.
165        ///
166        /// This is the same as `memory_reservation` but for GC heaps.
167        pub gc_heap_reservation: u64,
168
169        /// The size, in bytes, of the guard page region for GC heaps.
170        ///
171        /// This is the same as `memory_guard_size` but for GC heaps.
172        pub gc_heap_guard_size: u64,
173
174        /// The size, in bytes, to allocate at the end of a relocated GC heap
175        /// for growth.
176        ///
177        /// This is the same as `memory_reservation_for_growth` but for GC
178        /// heaps.
179        pub gc_heap_reservation_for_growth: u64,
180
181        /// Whether or not GC heaps are allowed to be reallocated after initial
182        /// allocation at runtime.
183        ///
184        /// This is the same as `memory_may_move` but for GC heaps.
185        pub gc_heap_may_move: bool,
186    }
187
188    pub struct ConfigTunables {
189        ...
190    }
191}
192
193impl Tunables {
194    /// Returns a `Tunables` configuration assumed for running code on the host.
195    pub fn default_host() -> Self {
196        if cfg!(miri) {
197            Tunables::default_miri()
198        } else if cfg!(target_pointer_width = "32") {
199            Tunables::default_u32()
200        } else if cfg!(target_pointer_width = "64") {
201            Tunables::default_u64()
202        } else {
203            panic!("unsupported target_pointer_width");
204        }
205    }
206
207    /// Returns the default set of tunables for the given target triple.
208    pub fn default_for_target(target: &Triple) -> Result<Self> {
209        if cfg!(miri) {
210            return Ok(Tunables::default_miri());
211        }
212        let mut ret = match target
213            .pointer_width()
214            .map_err(|_| format_err!("failed to retrieve target pointer width"))?
215        {
216            PointerWidth::U32 => Tunables::default_u32(),
217            PointerWidth::U64 => Tunables::default_u64(),
218            _ => bail!("unsupported target pointer width"),
219        };
220
221        // Pulley targets never use signals-based-traps and also can't benefit
222        // from guard pages, so disable them.
223        if target.is_pulley() {
224            ret.signals_based_traps = false;
225            ret.memory_guard_size = 0;
226            ret.gc_heap_guard_size = 0;
227        }
228        Ok(ret)
229    }
230
231    /// Returns the default set of tunables for running under MIRI.
232    pub fn default_miri() -> Tunables {
233        Tunables {
234            collector: None,
235
236            // No virtual memory tricks are available on miri so make these
237            // limits quite conservative.
238            memory_reservation: 1 << 20,
239            memory_guard_size: 0,
240            memory_reservation_for_growth: 0,
241
242            // General options which have the same defaults regardless of
243            // architecture.
244            debug_native: false,
245            parse_wasm_debuginfo: true,
246            consume_fuel: false,
247            operator_cost: OperatorCostStrategy::Default,
248            epoch_interruption: false,
249            memory_may_move: true,
250            guard_before_linear_memory: true,
251            table_lazy_init: true,
252            generate_address_map: true,
253            debug_adapter_modules: false,
254            relaxed_simd_deterministic: false,
255            winch_callable: false,
256            signals_based_traps: false,
257            memory_init_cow: true,
258            inlining: false,
259            inlining_intra_module: IntraModuleInlining::WhenUsingGc,
260            inlining_small_callee_size: 50,
261            inlining_sum_size_threshold: 2000,
262            debug_guest: false,
263            concurrency_support: true,
264            recording: false,
265            gc_zeal_alloc_counter: None,
266            gc_heap_reservation: 0,
267            gc_heap_guard_size: 0,
268            gc_heap_reservation_for_growth: 0,
269            gc_heap_may_move: true,
270        }
271    }
272
273    /// Returns the default set of tunables for running under a 32-bit host.
274    pub fn default_u32() -> Tunables {
275        Tunables {
276            // For 32-bit we scale way down to 10MB of reserved memory. This
277            // impacts performance severely but allows us to have more than a
278            // few instances running around.
279            memory_reservation: 10 * (1 << 20),
280            memory_guard_size: 0x1_0000,
281            memory_reservation_for_growth: 1 << 20, // 1MB
282            signals_based_traps: true,
283
284            // GC heaps on 32-bit: conservative defaults similar to linear
285            // memories.
286            gc_heap_reservation: 10 * (1 << 20),
287            gc_heap_guard_size: 0x1_0000,
288            gc_heap_reservation_for_growth: 1 << 20, // 1MB
289
290            ..Tunables::default_miri()
291        }
292    }
293
294    /// Returns the default set of tunables for running under a 64-bit host.
295    pub fn default_u64() -> Tunables {
296        Tunables {
297            // 64-bit has tons of address space to static memories can have 4gb
298            // address space reservations liberally by default, allowing us to
299            // help eliminate bounds checks.
300            //
301            // A 32MiB default guard size is then allocated so we can remove
302            // explicit bounds checks if any static offset is less than this
303            // value. SpiderMonkey found, for example, that in a large corpus of
304            // wasm modules 20MiB was the maximum offset so this is the
305            // power-of-two-rounded up from that and matches SpiderMonkey.
306            memory_reservation: 1 << 32,
307            memory_guard_size: 32 << 20,
308
309            // We've got lots of address space on 64-bit so use a larger
310            // grow-into-this area, but on 32-bit we aren't as lucky. Miri is
311            // not exactly fast so reduce memory consumption instead of trying
312            // to avoid memory movement.
313            memory_reservation_for_growth: 2 << 30, // 2GB
314
315            // GC heaps on 64-bit: use 4GiB reservation and 32MiB guard pages
316            // to enable bounds check elision, matching linear memory defaults.
317            gc_heap_reservation: 1 << 32,
318            gc_heap_guard_size: 32 << 20,
319            gc_heap_reservation_for_growth: 2 << 30, // 2GB
320
321            signals_based_traps: true,
322            ..Tunables::default_miri()
323        }
324    }
325
326    /// Get the GC heap's memory type, given our configured tunables.
327    pub fn gc_heap_memory_type(&self) -> Memory {
328        Memory {
329            idx_type: IndexType::I32,
330            limits: Limits { min: 0, max: None },
331            shared: false,
332            // We *could* try to match the target architecture's page size, but that
333            // would require exercising a page size for memories that we don't
334            // otherwise support for Wasm; we conservatively avoid that, and just
335            // use the default Wasm page size, for now.
336            page_size_log2: 16,
337        }
338    }
339}
340
341/// Whether a heap is backing a linear memory or a GC heap.
342///
343/// This is used by [`MemoryTunables`] to select between the memory tunables and
344/// the GC heap tunables.
345#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
346pub enum MemoryKind {
347    /// A WebAssembly linear memory.
348    LinearMemory,
349    /// A GC heap for garbage-collected objects.
350    GcHeap,
351}
352
353/// A view into a [`Tunables`] that selects the appropriate linear-memory or
354/// GC-heap flavor of each tunable based on a [`MemoryKind`].
355pub struct MemoryTunables<'a> {
356    tunables: &'a Tunables,
357    kind: MemoryKind,
358}
359
360impl<'a> MemoryTunables<'a> {
361    /// Create a new `MemoryTunables` view.
362    pub fn new(tunables: &'a Tunables, kind: MemoryKind) -> Self {
363        Self { tunables, kind }
364    }
365
366    /// The virtual memory reservation for this kind of memory.
367    pub fn reservation(&self) -> u64 {
368        match self.kind {
369            MemoryKind::LinearMemory => self.tunables.memory_reservation,
370            MemoryKind::GcHeap => self.tunables.gc_heap_reservation,
371        }
372    }
373
374    /// The size of the guard page region for this kind of memory.
375    pub fn guard_size(&self) -> u64 {
376        match self.kind {
377            MemoryKind::LinearMemory => self.tunables.memory_guard_size,
378            MemoryKind::GcHeap => self.tunables.gc_heap_guard_size,
379        }
380    }
381
382    /// Extra virtual memory to reserve beyond the initially mapped pages for
383    /// this kind of memory.
384    pub fn reservation_for_growth(&self) -> u64 {
385        match self.kind {
386            MemoryKind::LinearMemory => self.tunables.memory_reservation_for_growth,
387            MemoryKind::GcHeap => self.tunables.gc_heap_reservation_for_growth,
388        }
389    }
390
391    /// Whether this kind of memory's base pointer may be relocated at runtime.
392    pub fn may_move(&self) -> bool {
393        match self.kind {
394            MemoryKind::LinearMemory => self.tunables.memory_may_move,
395            MemoryKind::GcHeap => self.tunables.gc_heap_may_move,
396        }
397    }
398
399    /// Get the underlying tunables.
400    ///
401    /// This is ONLY for accessing tunable fields that DO NOT come in a
402    /// linear-memory flavor and a GC-heap flavor.
403    pub fn tunables(&self) -> &'a Tunables {
404        self.tunables
405    }
406}
407
408/// The garbage collector implementation to use.
409#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
410pub enum Collector {
411    /// The deferred reference-counting collector.
412    DeferredReferenceCounting,
413    /// The null collector.
414    Null,
415    /// The copying collector.
416    Copying,
417}
418
419impl fmt::Display for Collector {
420    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
421        match self {
422            Collector::DeferredReferenceCounting => write!(f, "deferred reference-counting"),
423            Collector::Null => write!(f, "null"),
424            Collector::Copying => write!(f, "copying"),
425        }
426    }
427}
428
429/// Whether to inline function calls within the same module.
430#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
431#[expect(missing_docs, reason = "self-describing variants")]
432pub enum IntraModuleInlining {
433    Yes,
434    No,
435    WhenUsingGc,
436}
437
438impl FromStr for IntraModuleInlining {
439    type Err = Error;
440
441    fn from_str(s: &str) -> Result<Self, Self::Err> {
442        match s {
443            "y" | "yes" | "true" => Ok(Self::Yes),
444            "n" | "no" | "false" => Ok(Self::No),
445            "gc" => Ok(Self::WhenUsingGc),
446            _ => bail!(
447                "invalid intra-module inlining option string: `{s}`, \
448                 only yes,no,gc accepted"
449            ),
450        }
451    }
452}
453
454/// The cost of each operator.
455///
456/// Note: a more dynamic approach (e.g. a user-supplied callback) can be
457/// added as a variant in the future if needed.
458#[derive(Clone, Hash, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
459pub enum OperatorCostStrategy {
460    /// A table of operator costs.
461    Table(Box<OperatorCost>),
462
463    /// Each cost defaults to 1 fuel unit, except `Nop`, `Drop` and
464    /// a few control flow operators.
465    #[default]
466    Default,
467}
468
469impl OperatorCostStrategy {
470    /// Create a new operator cost strategy with a table of costs.
471    pub fn table(cost: OperatorCost) -> Self {
472        OperatorCostStrategy::Table(Box::new(cost))
473    }
474
475    /// Get the cost of an operator.
476    pub fn cost(&self, op: &Operator) -> i64 {
477        match self {
478            OperatorCostStrategy::Table(cost) => cost.cost(op),
479            OperatorCostStrategy::Default => default_operator_cost(op),
480        }
481    }
482}
483
484const fn default_operator_cost(op: &Operator) -> i64 {
485    match op {
486        // Nop and drop generate no code, so don't consume fuel for them.
487        Operator::Nop | Operator::Drop => 0,
488
489        // Control flow may create branches, but is generally cheap and
490        // free, so don't consume fuel. Note the lack of `if` since some
491        // cost is incurred with the conditional check.
492        Operator::Block { .. }
493        | Operator::Loop { .. }
494        | Operator::Unreachable
495        | Operator::Return
496        | Operator::Else
497        | Operator::End => 0,
498
499        // Everything else, just call it one operation.
500        _ => 1,
501    }
502}
503
504macro_rules! default_cost {
505    // Nop and drop generate no code, so don't consume fuel for them.
506    (Nop) => {
507        0
508    };
509    (Drop) => {
510        0
511    };
512
513    // Control flow may create branches, but is generally cheap and
514    // free, so don't consume fuel. Note the lack of `if` since some
515    // cost is incurred with the conditional check.
516    (Block) => {
517        0
518    };
519    (Loop) => {
520        0
521    };
522    (Unreachable) => {
523        0
524    };
525    (Return) => {
526        0
527    };
528    (Else) => {
529        0
530    };
531    (End) => {
532        0
533    };
534
535    // Everything else, just call it one operation.
536    ($op:ident) => {
537        1
538    };
539}
540
541macro_rules! define_operator_cost {
542    ($(@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*) )*) => {
543        /// The fuel cost of each operator in a table.
544        #[derive(Clone, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
545        #[allow(missing_docs, non_snake_case, reason = "to avoid triggering clippy lints")]
546        pub struct OperatorCost {
547            $(
548                pub $op: u8,
549            )*
550        }
551
552        impl OperatorCost {
553            /// Returns the cost of the given operator.
554            pub fn cost(&self, op: &Operator) -> i64 {
555                match op {
556                    $(
557                        Operator::$op $({ $($arg: _),* })? => self.$op as i64,
558                    )*
559                    unknown => panic!("unknown op: {unknown:?}"),
560                }
561            }
562        }
563
564        impl OperatorCost {
565            /// Creates a new `OperatorCost` table with default costs for each operator.
566            pub const fn new() -> Self {
567                Self {
568                    $(
569                        $op: default_cost!($op),
570                    )*
571                }
572            }
573        }
574
575        impl Default for OperatorCost {
576            fn default() -> Self {
577                Self::new()
578            }
579        }
580    }
581}
582
583wasmparser::for_each_operator!(define_operator_cost);