wasmtime_environ/
tunables.rs

1use crate::{IndexType, Limits, Memory, TripleExt};
2use anyhow::{Error, Result, anyhow, bail};
3use core::{fmt, str::FromStr};
4use serde_derive::{Deserialize, Serialize};
5use target_lexicon::{PointerWidth, Triple};
6
7macro_rules! define_tunables {
8    (
9        $(#[$outer_attr:meta])*
10        pub struct $tunables:ident {
11            $(
12                $(#[$field_attr:meta])*
13                pub $field:ident : $field_ty:ty,
14            )*
15        }
16
17        pub struct $config_tunables:ident {
18            ...
19        }
20    ) => {
21        $(#[$outer_attr])*
22        pub struct $tunables {
23            $(
24                $(#[$field_attr])*
25                pub $field: $field_ty,
26            )*
27        }
28
29        /// Optional tunable configuration options used in `wasmtime::Config`
30        #[derive(Default, Clone)]
31        #[expect(missing_docs, reason = "macro-generated fields")]
32        pub struct $config_tunables {
33            $(pub $field: Option<$field_ty>,)*
34        }
35
36        impl $config_tunables {
37            /// Formats configured fields into `f`.
38            pub fn format(&self, f: &mut fmt::DebugStruct<'_,'_>) {
39                $(
40                    if let Some(val) = &self.$field {
41                        f.field(stringify!($field), val);
42                    }
43                )*
44            }
45
46            /// Configure the `Tunables` provided.
47            pub fn configure(&self, tunables: &mut Tunables) {
48                $(
49                    if let Some(val) = self.$field {
50                        tunables.$field = val;
51                    }
52                )*
53            }
54        }
55    };
56}
57
58define_tunables! {
59    /// Tunable parameters for WebAssembly compilation.
60    #[derive(Clone, Hash, Serialize, Deserialize, Debug)]
61    pub struct Tunables {
62        /// The garbage collector implementation to use, which implies the layout of
63        /// GC objects and barriers that must be emitted in Wasm code.
64        pub collector: Option<Collector>,
65
66        /// Initial size, in bytes, to be allocated for linear memories.
67        pub memory_reservation: u64,
68
69        /// The size, in bytes, of the guard page region for linear memories.
70        pub memory_guard_size: u64,
71
72        /// The size, in bytes, to allocate at the end of a relocated linear
73        /// memory for growth.
74        pub memory_reservation_for_growth: u64,
75
76        /// Whether or not to generate native DWARF debug information.
77        pub generate_native_debuginfo: bool,
78
79        /// Whether or not to retain DWARF sections in compiled modules.
80        pub parse_wasm_debuginfo: bool,
81
82        /// Whether or not fuel is enabled for generated code, meaning that fuel
83        /// will be consumed every time a wasm instruction is executed.
84        pub consume_fuel: bool,
85
86        /// Whether or not we use epoch-based interruption.
87        pub epoch_interruption: bool,
88
89        /// Whether or not linear memories are allowed to be reallocated after
90        /// initial allocation at runtime.
91        pub memory_may_move: bool,
92
93        /// Whether or not linear memory allocations will have a guard region at the
94        /// beginning of the allocation in addition to the end.
95        pub guard_before_linear_memory: bool,
96
97        /// Whether to initialize tables lazily, so that instantiation is fast but
98        /// indirect calls are a little slower. If false, tables are initialized
99        /// eagerly from any active element segments that apply to them during
100        /// instantiation.
101        pub table_lazy_init: bool,
102
103        /// Indicates whether an address map from compiled native code back to wasm
104        /// offsets in the original file is generated.
105        pub generate_address_map: bool,
106
107        /// Flag for the component module whether adapter modules have debug
108        /// assertions baked into them.
109        pub debug_adapter_modules: bool,
110
111        /// Whether or not lowerings for relaxed simd instructions are forced to
112        /// be deterministic.
113        pub relaxed_simd_deterministic: bool,
114
115        /// Whether or not Wasm functions target the winch abi.
116        pub winch_callable: bool,
117
118        /// Whether or not the host will be using native signals (e.g. SIGILL,
119        /// SIGSEGV, etc) to implement traps.
120        pub signals_based_traps: bool,
121
122        /// Whether CoW images might be used to initialize linear memories.
123        pub memory_init_cow: bool,
124
125        /// Whether to enable inlining in Wasmtime's compilation orchestration
126        /// or not.
127        pub inlining: bool,
128
129        /// Whether to inline calls within the same core Wasm module or not.
130        pub inlining_intra_module: IntraModuleInlining,
131
132        /// The size of "small callees" that can be inlined regardless of the
133        /// caller's size.
134        pub inlining_small_callee_size: u32,
135
136        /// The general size threshold for the sum of the caller's and callee's
137        /// sizes, past which we will generally not inline calls anymore.
138        pub inlining_sum_size_threshold: u32,
139    }
140
141    pub struct ConfigTunables {
142        ...
143    }
144}
145
146impl Tunables {
147    /// Returns a `Tunables` configuration assumed for running code on the host.
148    pub fn default_host() -> Self {
149        if cfg!(miri) {
150            Tunables::default_miri()
151        } else if cfg!(target_pointer_width = "32") {
152            Tunables::default_u32()
153        } else if cfg!(target_pointer_width = "64") {
154            Tunables::default_u64()
155        } else {
156            panic!("unsupported target_pointer_width");
157        }
158    }
159
160    /// Returns the default set of tunables for the given target triple.
161    pub fn default_for_target(target: &Triple) -> Result<Self> {
162        if cfg!(miri) {
163            return Ok(Tunables::default_miri());
164        }
165        let mut ret = match target
166            .pointer_width()
167            .map_err(|_| anyhow!("failed to retrieve target pointer width"))?
168        {
169            PointerWidth::U32 => Tunables::default_u32(),
170            PointerWidth::U64 => Tunables::default_u64(),
171            _ => bail!("unsupported target pointer width"),
172        };
173
174        // Pulley targets never use signals-based-traps and also can't benefit
175        // from guard pages, so disable them.
176        if target.is_pulley() {
177            ret.signals_based_traps = false;
178            ret.memory_guard_size = 0;
179        }
180        Ok(ret)
181    }
182
183    /// Returns the default set of tunables for running under MIRI.
184    pub const fn default_miri() -> Tunables {
185        Tunables {
186            collector: None,
187
188            // No virtual memory tricks are available on miri so make these
189            // limits quite conservative.
190            memory_reservation: 1 << 20,
191            memory_guard_size: 0,
192            memory_reservation_for_growth: 0,
193
194            // General options which have the same defaults regardless of
195            // architecture.
196            generate_native_debuginfo: false,
197            parse_wasm_debuginfo: true,
198            consume_fuel: false,
199            epoch_interruption: false,
200            memory_may_move: true,
201            guard_before_linear_memory: true,
202            table_lazy_init: true,
203            generate_address_map: true,
204            debug_adapter_modules: false,
205            relaxed_simd_deterministic: false,
206            winch_callable: false,
207            signals_based_traps: false,
208            memory_init_cow: true,
209            inlining: false,
210            inlining_intra_module: IntraModuleInlining::WhenUsingGc,
211            inlining_small_callee_size: 50,
212            inlining_sum_size_threshold: 2000,
213        }
214    }
215
216    /// Returns the default set of tunables for running under a 32-bit host.
217    pub const fn default_u32() -> Tunables {
218        Tunables {
219            // For 32-bit we scale way down to 10MB of reserved memory. This
220            // impacts performance severely but allows us to have more than a
221            // few instances running around.
222            memory_reservation: 10 * (1 << 20),
223            memory_guard_size: 0x1_0000,
224            memory_reservation_for_growth: 1 << 20, // 1MB
225            signals_based_traps: true,
226
227            ..Tunables::default_miri()
228        }
229    }
230
231    /// Returns the default set of tunables for running under a 64-bit host.
232    pub const fn default_u64() -> Tunables {
233        Tunables {
234            // 64-bit has tons of address space to static memories can have 4gb
235            // address space reservations liberally by default, allowing us to
236            // help eliminate bounds checks.
237            //
238            // A 32MiB default guard size is then allocated so we can remove
239            // explicit bounds checks if any static offset is less than this
240            // value. SpiderMonkey found, for example, that in a large corpus of
241            // wasm modules 20MiB was the maximum offset so this is the
242            // power-of-two-rounded up from that and matches SpiderMonkey.
243            memory_reservation: 1 << 32,
244            memory_guard_size: 32 << 20,
245
246            // We've got lots of address space on 64-bit so use a larger
247            // grow-into-this area, but on 32-bit we aren't as lucky. Miri is
248            // not exactly fast so reduce memory consumption instead of trying
249            // to avoid memory movement.
250            memory_reservation_for_growth: 2 << 30, // 2GB
251
252            signals_based_traps: true,
253            ..Tunables::default_miri()
254        }
255    }
256
257    /// Get the GC heap's memory type, given our configured tunables.
258    pub fn gc_heap_memory_type(&self) -> Memory {
259        Memory {
260            idx_type: IndexType::I32,
261            limits: Limits { min: 0, max: None },
262            shared: false,
263            // We *could* try to match the target architecture's page size, but that
264            // would require exercising a page size for memories that we don't
265            // otherwise support for Wasm; we conservatively avoid that, and just
266            // use the default Wasm page size, for now.
267            page_size_log2: 16,
268        }
269    }
270}
271
272/// The garbage collector implementation to use.
273#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
274pub enum Collector {
275    /// The deferred reference-counting collector.
276    DeferredReferenceCounting,
277    /// The null collector.
278    Null,
279}
280
281impl fmt::Display for Collector {
282    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
283        match self {
284            Collector::DeferredReferenceCounting => write!(f, "deferred reference-counting"),
285            Collector::Null => write!(f, "null"),
286        }
287    }
288}
289
290/// Whether to inline function calls within the same module.
291#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
292#[expect(missing_docs, reason = "self-describing variants")]
293pub enum IntraModuleInlining {
294    Yes,
295    No,
296    WhenUsingGc,
297}
298
299impl FromStr for IntraModuleInlining {
300    type Err = Error;
301
302    fn from_str(s: &str) -> Result<Self, Self::Err> {
303        match s {
304            "y" | "yes" | "true" => Ok(Self::Yes),
305            "n" | "no" | "false" => Ok(Self::No),
306            "gc" => Ok(Self::WhenUsingGc),
307            _ => bail!(
308                "invalid intra-module inlining option string: `{s}`, \
309                 only yes,no,gc accepted"
310            ),
311        }
312    }
313}