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: Inlining,
137
138 /// The size of "small callees" that can be inlined regardless of the
139 /// caller's size.
140 pub inlining_small_callee_size: u32,
141
142 /// The general size threshold for the sum of the caller's and callee's
143 /// sizes, past which we will generally not inline calls anymore.
144 pub inlining_sum_size_threshold: u32,
145
146 /// Whether any component model feature related to concurrency is
147 /// enabled.
148 pub concurrency_support: bool,
149
150 /// Whether recording in RR is enabled or not. This is used primarily
151 /// to signal checksum computation for compiled artifacts.
152 pub recording: bool,
153
154 /// An allocation counter that triggers GC when it reaches zero.
155 ///
156 /// Decremented on every allocation and when it hits zero, a GC is
157 /// forced and the counter is reset. Only effective when
158 /// `cfg(gc_zeal)` is enabled.
159 pub gc_zeal_alloc_counter: Option<NonZeroU32>,
160
161 /// Initial size, in bytes, to be allocated for GC heaps.
162 ///
163 /// This is the same as `memory_reservation` but for GC heaps.
164 pub gc_heap_reservation: u64,
165
166 /// The size, in bytes, of the guard page region for GC heaps.
167 ///
168 /// This is the same as `memory_guard_size` but for GC heaps.
169 pub gc_heap_guard_size: u64,
170
171 /// The size, in bytes, to allocate at the end of a relocated GC heap
172 /// for growth.
173 ///
174 /// This is the same as `memory_reservation_for_growth` but for GC
175 /// heaps.
176 pub gc_heap_reservation_for_growth: u64,
177
178 /// Whether or not GC heaps are allowed to be reallocated after initial
179 /// allocation at runtime.
180 ///
181 /// This is the same as `memory_may_move` but for GC heaps.
182 pub gc_heap_may_move: bool,
183
184 /// Boolean to track whether compiled code retains metadata necessary to
185 /// report extra information on internal assertions failing.
186 pub metadata_for_internal_asserts: bool,
187
188 /// Boolean to track whether compiled code retains metadata necessary to
189 /// report extra information on gc heap corruption being detected.
190 pub metadata_for_gc_heap_corruption: bool,
191
192 /// Whether `metadata.code.branch_hint` sections are parsed and used to
193 /// mark cold blocks during compilation.
194 pub branch_hinting: bool,
195 }
196
197 pub struct ConfigTunables {
198 ...
199 }
200}
201
202impl Tunables {
203 /// Returns a `Tunables` configuration assumed for running code on the host.
204 pub fn default_host() -> Self {
205 if cfg!(miri) {
206 Tunables::default_miri()
207 } else if cfg!(target_pointer_width = "32") {
208 Tunables::default_u32()
209 } else if cfg!(target_pointer_width = "64") {
210 Tunables::default_u64()
211 } else {
212 panic!("unsupported target_pointer_width");
213 }
214 }
215
216 /// Returns the default set of tunables for the given target triple.
217 pub fn default_for_target(target: &Triple) -> Result<Self> {
218 if cfg!(miri) {
219 return Ok(Tunables::default_miri());
220 }
221 let mut ret = match target
222 .pointer_width()
223 .map_err(|_| format_err!("failed to retrieve target pointer width"))?
224 {
225 PointerWidth::U32 => Tunables::default_u32(),
226 PointerWidth::U64 => Tunables::default_u64(),
227 _ => bail!("unsupported target pointer width"),
228 };
229
230 // Pulley targets never use signals-based-traps and also can't benefit
231 // from guard pages, so disable them.
232 if target.is_pulley() {
233 ret.signals_based_traps = false;
234 ret.memory_guard_size = 0;
235 ret.gc_heap_guard_size = 0;
236 }
237 Ok(ret)
238 }
239
240 /// Returns the default set of tunables for running under MIRI.
241 pub fn default_miri() -> Tunables {
242 Tunables {
243 collector: None,
244
245 // No virtual memory tricks are available on miri so make these
246 // limits quite conservative.
247 memory_reservation: 1 << 20,
248 memory_guard_size: 0,
249 memory_reservation_for_growth: 0,
250
251 // General options which have the same defaults regardless of
252 // architecture.
253 debug_native: false,
254 parse_wasm_debuginfo: true,
255 consume_fuel: false,
256 operator_cost: OperatorCostStrategy::Default,
257 epoch_interruption: false,
258 memory_may_move: true,
259 guard_before_linear_memory: true,
260 table_lazy_init: true,
261 generate_address_map: true,
262 debug_adapter_modules: false,
263 relaxed_simd_deterministic: false,
264 winch_callable: false,
265 signals_based_traps: false,
266 memory_init_cow: true,
267 inlining: Inlining::No,
268 inlining_small_callee_size: 50,
269 inlining_sum_size_threshold: 2000,
270 debug_guest: false,
271 concurrency_support: true,
272 recording: false,
273 gc_zeal_alloc_counter: None,
274 gc_heap_reservation: 0,
275 gc_heap_guard_size: 0,
276 gc_heap_reservation_for_growth: 0,
277 gc_heap_may_move: true,
278 metadata_for_internal_asserts: false,
279 metadata_for_gc_heap_corruption: true,
280 branch_hinting: false,
281 }
282 }
283
284 /// Returns the default set of tunables for running under a 32-bit host.
285 pub fn default_u32() -> Tunables {
286 Tunables {
287 // For 32-bit we scale way down to 10MB of reserved memory. This
288 // impacts performance severely but allows us to have more than a
289 // few instances running around.
290 memory_reservation: 10 * (1 << 20),
291 memory_guard_size: 0x1_0000,
292 memory_reservation_for_growth: 1 << 20, // 1MB
293 signals_based_traps: true,
294
295 // GC heaps on 32-bit: conservative defaults similar to linear
296 // memories.
297 gc_heap_reservation: 10 * (1 << 20),
298 gc_heap_guard_size: 0x1_0000,
299 gc_heap_reservation_for_growth: 1 << 20, // 1MB
300
301 ..Tunables::default_miri()
302 }
303 }
304
305 /// Returns the default set of tunables for running under a 64-bit host.
306 pub fn default_u64() -> Tunables {
307 Tunables {
308 // 64-bit has tons of address space to static memories can have 4gb
309 // address space reservations liberally by default, allowing us to
310 // help eliminate bounds checks.
311 //
312 // A 32MiB default guard size is then allocated so we can remove
313 // explicit bounds checks if any static offset is less than this
314 // value. SpiderMonkey found, for example, that in a large corpus of
315 // wasm modules 20MiB was the maximum offset so this is the
316 // power-of-two-rounded up from that and matches SpiderMonkey.
317 memory_reservation: 1 << 32,
318 memory_guard_size: 32 << 20,
319
320 // We've got lots of address space on 64-bit so use a larger
321 // grow-into-this area, but on 32-bit we aren't as lucky. Miri is
322 // not exactly fast so reduce memory consumption instead of trying
323 // to avoid memory movement.
324 memory_reservation_for_growth: 2 << 30, // 2GB
325
326 // GC heaps on 64-bit: use 4GiB reservation and 32MiB guard pages
327 // to enable bounds check elision, matching linear memory defaults.
328 gc_heap_reservation: 1 << 32,
329 gc_heap_guard_size: 32 << 20,
330 gc_heap_reservation_for_growth: 2 << 30, // 2GB
331
332 signals_based_traps: true,
333 ..Tunables::default_miri()
334 }
335 }
336
337 /// Get the GC heap's memory type, given our configured tunables.
338 pub fn gc_heap_memory_type(&self) -> Memory {
339 Memory {
340 idx_type: IndexType::I32,
341 limits: Limits { min: 0, max: None },
342 shared: false,
343 // We *could* try to match the target architecture's page size, but that
344 // would require exercising a page size for memories that we don't
345 // otherwise support for Wasm; we conservatively avoid that, and just
346 // use the default Wasm page size, for now.
347 page_size_log2: 16,
348 }
349 }
350}
351
352/// Whether a heap is backing a linear memory or a GC heap.
353///
354/// This is used by [`MemoryTunables`] to select between the memory tunables and
355/// the GC heap tunables.
356#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
357pub enum MemoryKind {
358 /// A WebAssembly linear memory.
359 LinearMemory,
360 /// A GC heap for garbage-collected objects.
361 GcHeap,
362}
363
364/// A view into a [`Tunables`] that selects the appropriate linear-memory or
365/// GC-heap flavor of each tunable based on a [`MemoryKind`].
366pub struct MemoryTunables<'a> {
367 tunables: &'a Tunables,
368 kind: MemoryKind,
369}
370
371impl<'a> MemoryTunables<'a> {
372 /// Create a new `MemoryTunables` view.
373 pub fn new(tunables: &'a Tunables, kind: MemoryKind) -> Self {
374 Self { tunables, kind }
375 }
376
377 /// The virtual memory reservation for this kind of memory.
378 pub fn reservation(&self) -> u64 {
379 match self.kind {
380 MemoryKind::LinearMemory => self.tunables.memory_reservation,
381 MemoryKind::GcHeap => self.tunables.gc_heap_reservation,
382 }
383 }
384
385 /// The size of the guard page region for this kind of memory.
386 pub fn guard_size(&self) -> u64 {
387 match self.kind {
388 MemoryKind::LinearMemory => self.tunables.memory_guard_size,
389 MemoryKind::GcHeap => self.tunables.gc_heap_guard_size,
390 }
391 }
392
393 /// Extra virtual memory to reserve beyond the initially mapped pages for
394 /// this kind of memory.
395 pub fn reservation_for_growth(&self) -> u64 {
396 match self.kind {
397 MemoryKind::LinearMemory => self.tunables.memory_reservation_for_growth,
398 MemoryKind::GcHeap => self.tunables.gc_heap_reservation_for_growth,
399 }
400 }
401
402 /// Whether this kind of memory's base pointer may be relocated at runtime.
403 pub fn may_move(&self) -> bool {
404 match self.kind {
405 MemoryKind::LinearMemory => self.tunables.memory_may_move,
406 MemoryKind::GcHeap => self.tunables.gc_heap_may_move,
407 }
408 }
409
410 /// Get the underlying tunables.
411 ///
412 /// This is ONLY for accessing tunable fields that DO NOT come in a
413 /// linear-memory flavor and a GC-heap flavor.
414 pub fn tunables(&self) -> &'a Tunables {
415 self.tunables
416 }
417}
418
419/// The garbage collector implementation to use.
420#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
421pub enum Collector {
422 /// The deferred reference-counting collector.
423 DeferredReferenceCounting,
424 /// The null collector.
425 Null,
426 /// The copying collector.
427 Copying,
428}
429
430impl fmt::Display for Collector {
431 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
432 match self {
433 Collector::DeferredReferenceCounting => write!(f, "deferred reference-counting"),
434 Collector::Null => write!(f, "null"),
435 Collector::Copying => write!(f, "copying"),
436 }
437 }
438}
439
440/// Inlining modes supported by Wasmtime.
441#[derive(Clone, Copy, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
442pub enum Inlining {
443 /// All inlining is enabled wherever possible.
444 ///
445 /// This includes inter-module inlining (across modules) as well as
446 /// intra-module inlining (within a module).
447 ///
448 /// Note that backtraces may omit inlined stack frames.
449 Yes,
450
451 /// Inter-module inlining (across modules) is allowed, but intra-module
452 /// (within a module) is only allowed when the module is using GC.
453 ///
454 /// Note that backtraces may omit inlined stack frames.
455 InterModuleAndIntraGc,
456
457 /// Inter-module inlining (across modules) is allowed, but intra-module
458 /// (within a module) is not allowed.
459 ///
460 /// Note that backtraces may omit inlined stack frames.
461 InterModule,
462
463 /// No module inlining is allowed, either inter- or intra-module. Only
464 /// inlining Wasmtime's intrinsics are allowed.
465 ///
466 /// This option, for example, never emits WebAssembly stack frames from
467 /// backtraces.
468 Intrinsics,
469
470 /// Inlining is disabled entirely.
471 No,
472}
473
474impl FromStr for Inlining {
475 type Err = Error;
476
477 fn from_str(s: &str) -> Result<Self, Self::Err> {
478 match s {
479 "y" | "yes" | "true" => Ok(Self::Yes),
480 "n" | "no" | "false" => Ok(Self::No),
481 "gc" => Ok(Self::InterModuleAndIntraGc),
482 "inter-module" => Ok(Self::InterModuleAndIntraGc),
483 "intrinsics" => Ok(Self::Intrinsics),
484 _ => bail!(
485 "invalid intra-module inlining option string: `{s}`, \
486 only yes,no,gc,inter-module,intrinsics accepted"
487 ),
488 }
489 }
490}
491
492impl fmt::Display for Inlining {
493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
494 match self {
495 Inlining::Yes => write!(f, "yes"),
496 Inlining::InterModuleAndIntraGc => write!(f, "gc"),
497 Inlining::InterModule => write!(f, "inter-module"),
498 Inlining::Intrinsics => write!(f, "intrinsics"),
499 Inlining::No => write!(f, "no"),
500 }
501 }
502}
503
504/// The cost of each operator.
505///
506/// Note: a more dynamic approach (e.g. a user-supplied callback) can be
507/// added as a variant in the future if needed.
508#[derive(Clone, Hash, Serialize, Deserialize, Debug, PartialEq, Eq, Default)]
509pub enum OperatorCostStrategy {
510 /// A table of operator costs.
511 Table(Box<OperatorCost>),
512
513 /// Each cost defaults to 1 fuel unit, except `Nop`, `Drop` and
514 /// a few control flow operators.
515 #[default]
516 Default,
517}
518
519impl OperatorCostStrategy {
520 /// Create a new operator cost strategy with a table of costs.
521 pub fn table(cost: OperatorCost) -> Self {
522 OperatorCostStrategy::Table(Box::new(cost))
523 }
524
525 /// Get the cost of an operator.
526 pub fn cost(&self, op: &Operator) -> i64 {
527 match self {
528 OperatorCostStrategy::Table(cost) => cost.cost(op),
529 OperatorCostStrategy::Default => default_operator_cost(op),
530 }
531 }
532}
533
534const fn default_operator_cost(op: &Operator) -> i64 {
535 match op {
536 // Nop and drop generate no code, so don't consume fuel for them.
537 Operator::Nop | Operator::Drop => 0,
538
539 // Control flow may create branches, but is generally cheap and
540 // free, so don't consume fuel. Note the lack of `if` since some
541 // cost is incurred with the conditional check.
542 Operator::Block { .. }
543 | Operator::Loop { .. }
544 | Operator::Unreachable
545 | Operator::Return
546 | Operator::Else
547 | Operator::End => 0,
548
549 // Everything else, just call it one operation.
550 _ => 1,
551 }
552}
553
554macro_rules! default_cost {
555 // Nop and drop generate no code, so don't consume fuel for them.
556 (Nop) => {
557 0
558 };
559 (Drop) => {
560 0
561 };
562
563 // Control flow may create branches, but is generally cheap and
564 // free, so don't consume fuel. Note the lack of `if` since some
565 // cost is incurred with the conditional check.
566 (Block) => {
567 0
568 };
569 (Loop) => {
570 0
571 };
572 (Unreachable) => {
573 0
574 };
575 (Return) => {
576 0
577 };
578 (Else) => {
579 0
580 };
581 (End) => {
582 0
583 };
584
585 // Everything else, just call it one operation.
586 ($op:ident) => {
587 1
588 };
589}
590
591macro_rules! define_operator_cost {
592 ($(@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*) )*) => {
593 /// The fuel cost of each operator in a table.
594 #[derive(Clone, Hash, Serialize, Deserialize, Debug, PartialEq, Eq)]
595 #[allow(missing_docs, non_snake_case, reason = "to avoid triggering clippy lints")]
596 pub struct OperatorCost {
597 $(
598 pub $op: u8,
599 )*
600 }
601
602 impl OperatorCost {
603 /// Returns the cost of the given operator.
604 pub fn cost(&self, op: &Operator) -> i64 {
605 match op {
606 $(
607 Operator::$op $({ $($arg: _),* })? => self.$op as i64,
608 )*
609 unknown => panic!("unknown op: {unknown:?}"),
610 }
611 }
612 }
613
614 impl OperatorCost {
615 /// Creates a new `OperatorCost` table with default costs for each operator.
616 pub const fn new() -> Self {
617 Self {
618 $(
619 $op: default_cost!($op),
620 )*
621 }
622 }
623 }
624
625 impl Default for OperatorCost {
626 fn default() -> Self {
627 Self::new()
628 }
629 }
630 }
631}
632
633wasmparser::for_each_operator!(define_operator_cost);