Skip to main content

wasmtime_cli_flags/
lib.rs

1//! A utility crate for managing Wasmtime configuration options in a
2//! serializable format.
3//!
4//! This crate primarily provides a [`CommonOptions`] structure which can be
5//! parsed from CLI flags via [`clap`] or with [`serde::Deserialize`]. This
6//! structure can additionally be created from a [`wasmtime::Engine`] to
7//! serialize some of the significant configuration options affecting an engine.
8//!
9//! This is intended to be a shared way for embedders to configure Wasmtime with
10//! serializable configuration. The source of truth for Wasmtime's configuration
11//! is the [`Config`] type but this additionally serves as a means of creating
12//! that type.
13
14use std::num::NonZeroUsize;
15use std::{fmt, num::NonZeroU32, path::PathBuf, time::Duration};
16use wasmtime::{Config, Engine, Result, WasmBacktraceDetails, WasmFeatures, bail};
17
18pub mod opt;
19
20#[cfg(feature = "logging")]
21fn init_file_per_thread_logger(prefix: &'static str) {
22    file_per_thread_logger::initialize(prefix);
23    file_per_thread_logger::allow_uninitialized();
24
25    // Extending behavior of default spawner:
26    // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler
27    // Source code says DefaultSpawner is implementation detail and
28    // shouldn't be used directly.
29    #[cfg(feature = "parallel-compilation")]
30    rayon::ThreadPoolBuilder::new()
31        .spawn_handler(move |thread| {
32            let mut b = std::thread::Builder::new();
33            if let Some(name) = thread.name() {
34                b = b.name(name.to_owned());
35            }
36            if let Some(stack_size) = thread.stack_size() {
37                b = b.stack_size(stack_size);
38            }
39            b.spawn(move || {
40                file_per_thread_logger::initialize(prefix);
41                thread.run()
42            })?;
43            Ok(())
44        })
45        .build_global()
46        .unwrap();
47}
48
49wasmtime_option_group! {
50    #[env = "OPTIMIZE"]
51    pub struct OptimizeOptions {
52        /// Optimization level of generated code (0-2, s; default: 2)
53        #[serde(default)]
54        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
55        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
56        pub opt_level: Option<wasmtime::OptLevel>,
57
58        /// Register allocator algorithm choice.
59        #[serde(default)]
60        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
61        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
62        pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
63
64        /// Do not allow Wasm linear memories to move in the host process's
65        /// address space.
66        pub memory_may_move: Option<bool>,
67
68        /// Initial virtual memory allocation size for memories.
69        pub memory_reservation: Option<u64>,
70
71        /// Bytes to reserve at the end of linear memory for growth into.
72        pub memory_reservation_for_growth: Option<u64>,
73
74        /// Size, in bytes, of guard pages for linear memories.
75        pub memory_guard_size: Option<u64>,
76
77        /// Do not allow the GC heap to move in the host process's address
78        /// space.
79        pub gc_heap_may_move: Option<bool>,
80
81        /// Initial virtual memory allocation size for the GC heap.
82        pub gc_heap_reservation: Option<u64>,
83
84        /// Bytes to reserve at the end of the GC heap for growth into.
85        pub gc_heap_reservation_for_growth: Option<u64>,
86
87        /// Size, in bytes, of guard pages for the GC heap.
88        pub gc_heap_guard_size: Option<u64>,
89
90        /// Initial allocated size for the GC heap.
91        pub gc_heap_initial_size: Option<u64>,
92
93        /// Indicates whether an unmapped region of memory is placed before all
94        /// linear memories.
95        pub guard_before_linear_memory: Option<bool>,
96
97        /// Whether to initialize tables lazily, so that instantiation is
98        /// fast but indirect calls are a little slower. If no, tables are
99        /// initialized eagerly from any active element segments that apply to
100        /// them during instantiation. (default: yes)
101        pub table_lazy_init: Option<bool>,
102
103        /// Enable the pooling allocator, in place of the on-demand allocator.
104        pub pooling_allocator: Option<bool>,
105
106        /// The number of decommits to do per batch. A batch size of 1
107        /// effectively disables decommit batching. (default: 1)
108        pub pooling_decommit_batch_size: Option<usize>,
109
110        /// How many bytes to keep resident between instantiations for the
111        /// pooling allocator in linear memories.
112        pub pooling_memory_keep_resident: Option<usize>,
113
114        /// How many bytes to keep resident between instantiations for the
115        /// pooling allocator in tables.
116        pub pooling_table_keep_resident: Option<usize>,
117
118        /// Enable memory protection keys for the pooling allocator; this can
119        /// optimize the size of memory slots.
120        #[serde(default)]
121        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
122        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
123        pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,
124
125        /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
126        /// will use. (default: 16)
127        pub pooling_max_memory_protection_keys: Option<usize>,
128
129        /// Configure attempting to initialize linear memory via a
130        /// copy-on-write mapping (default: yes)
131        pub memory_init_cow: Option<bool>,
132
133        /// Threshold below which CoW images are guaranteed to be used and be
134        /// dense.
135        pub memory_guaranteed_dense_image_size: Option<u64>,
136
137        /// The maximum number of WebAssembly instances which can be created
138        /// with the pooling allocator.
139        pub pooling_total_core_instances: Option<u32>,
140
141        /// The maximum number of WebAssembly components which can be created
142        /// with the pooling allocator.
143        pub pooling_total_component_instances: Option<u32>,
144
145        /// The maximum number of WebAssembly memories which can be created with
146        /// the pooling allocator.
147        pub pooling_total_memories: Option<u32>,
148
149        /// The maximum number of WebAssembly tables which can be created with
150        /// the pooling allocator.
151        pub pooling_total_tables: Option<u32>,
152
153        /// The maximum number of WebAssembly stacks which can be created with
154        /// the pooling allocator.
155        pub pooling_total_stacks: Option<u32>,
156
157        /// The maximum runtime size of each linear memory in the pooling
158        /// allocator, in bytes.
159        pub pooling_max_memory_size: Option<usize>,
160
161        /// The maximum table elements for any table defined in a module when
162        /// using the pooling allocator.
163        pub pooling_table_elements: Option<usize>,
164
165        /// The maximum size, in bytes, allocated for a core instance's metadata
166        /// when using the pooling allocator.
167        pub pooling_max_core_instance_size: Option<usize>,
168
169        /// Configures the maximum number of "unused warm slots" to retain in the
170        /// pooling allocator. (default: 100)
171        pub pooling_max_unused_warm_slots: Option<u32>,
172
173        /// How much memory, in bytes, to keep resident for async stacks allocated
174        /// with the pooling allocator. (default: 0)
175        pub pooling_async_stack_keep_resident: Option<usize>,
176
177        /// The maximum size, in bytes, allocated for a component instance's
178        /// `VMComponentContext` metadata. (default: 1MiB)
179        pub pooling_max_component_instance_size: Option<usize>,
180
181        /// The maximum number of core instances a single component may contain
182        /// (default is unlimited).
183        pub pooling_max_core_instances_per_component: Option<u32>,
184
185        /// The maximum number of Wasm linear memories that a single component may
186        /// transitively contain (default is unlimited).
187        pub pooling_max_memories_per_component: Option<u32>,
188
189        /// The maximum number of tables that a single component may transitively
190        /// contain (default is unlimited).
191        pub pooling_max_tables_per_component: Option<u32>,
192
193        /// The maximum number of defined tables for a core module. (default: 1)
194        pub pooling_max_tables_per_module: Option<u32>,
195
196        /// The maximum number of defined linear memories for a module. (default: 1)
197        pub pooling_max_memories_per_module: Option<u32>,
198
199        /// The maximum number of concurrent GC heaps supported. (default: 1000)
200        pub pooling_total_gc_heaps: Option<u32>,
201
202        /// Enable or disable the use of host signal handlers for traps.
203        pub signals_based_traps: Option<bool>,
204
205        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
206        pub dynamic_memory_guard_size: Option<u64>,
207
208        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
209        pub static_memory_guard_size: Option<u64>,
210
211        /// DEPRECATED: Use `-Cmemory-may-move` instead.
212        pub static_memory_forced: Option<bool>,
213
214        /// DEPRECATED: Use `-Cmemory-reservation=N` instead.
215        pub static_memory_maximum_size: Option<u64>,
216
217        /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead.
218        pub dynamic_memory_reserved_for_growth: Option<u64>,
219
220        /// Whether or not `PAGEMAP_SCAN` ioctls are used to reset linear
221        /// memory.
222        #[serde(default)]
223        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
224        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
225        pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
226
227        /// XXX: For internal fuzzing and debugging use only!
228        #[doc(hidden)]
229        pub gc_zeal_alloc_counter: Option<NonZeroU32>,
230    }
231
232    enum Optimize {
233        ...
234    }
235}
236
237wasmtime_option_group! {
238    #[env = "CODEGEN"]
239    pub struct CodegenOptions {
240        /// Either `cranelift` or `winch`.
241        ///
242        /// Currently only `cranelift` and `winch` are supported, but not all
243        /// builds of Wasmtime have both built in.
244        #[serde(default)]
245        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
246        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
247        pub compiler: Option<wasmtime::Strategy>,
248        /// Which garbage collector to use: `drc`, `null`, or `copying`.
249        ///
250        /// `drc` is the deferred reference-counting collector.
251        ///
252        /// `null` is the null garbage collector, which does not collect any
253        /// garbage.
254        ///
255        /// `copying` is the copying garbage collector (not yet implemented).
256        ///
257        /// Note that not all builds of Wasmtime will have support for garbage
258        /// collection included.
259        #[serde(default)]
260        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
261        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
262        pub collector: Option<wasmtime::Collector>,
263        /// Enable Cranelift's internal debug verifier (expensive)
264        pub cranelift_debug_verifier: Option<bool>,
265        /// Whether or not to enable caching of compiled modules.
266        pub cache: Option<bool>,
267        /// Configuration for compiled module caching.
268        pub cache_config: Option<String>,
269        /// Whether or not to enable parallel compilation of modules.
270        pub parallel_compilation: Option<bool>,
271        /// Controls whether native unwind information is present in compiled
272        /// object files.
273        pub native_unwind_info: Option<bool>,
274
275        /// Whether to perform function inlining during compilation.
276        #[serde(default)]
277        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
278        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
279        pub inlining: Option<wasmtime::Inlining>,
280
281        /// Whether or not trap metadata is present for wasm internal assertions
282        /// in compiled code.
283        pub metadata_for_internal_asserts: Option<bool>,
284        /// Whether or not trap metadata is present for detection of gc
285        /// corruption in compiled code.
286        pub metadata_for_gc_heap_corruption: Option<bool>,
287
288        #[prefixed = "cranelift"]
289        #[serde(default)]
290        /// Set a cranelift-specific option. Use `wasmtime settings` to see
291        /// all.
292        pub cranelift: Vec<(String, Option<String>)>,
293    }
294
295    enum Codegen {
296        ...
297    }
298}
299
300wasmtime_option_group! {
301    #[env = "DEBUG"]
302    pub struct DebugOptions {
303        /// Enable generation of DWARF debug information in compiled code.
304        pub debug_info: Option<bool>,
305        /// Enable guest debugging insrumentation.
306        pub guest_debug: Option<bool>,
307        /// Configure whether compiled code can map native addresses to wasm.
308        pub address_map: Option<bool>,
309        /// Configure whether logging is enabled.
310        pub logging: Option<bool>,
311        /// Configure whether logs are emitted to files
312        pub log_to_files: Option<bool>,
313        /// Enable coredump generation to this file after a WebAssembly trap.
314        pub coredump: Option<String>,
315        /// Load the given debugger component and attach it to the
316        /// main module or component.
317        pub debugger: Option<PathBuf>,
318        /// Pass the given command-line arguments to the debugger
319        /// component. May be specified multiple times.
320        #[serde(default)]
321        pub arg: Vec<String>,
322        /// Allow the debugger component to inherit stdin.Off by
323        /// default.
324        pub inherit_stdin: Option<bool>,
325        /// Allow the debugger component to inherit stdout. Off by
326        /// default.
327        pub inherit_stdout: Option<bool>,
328        /// Allow the debugger component to inherit stderr. Off by
329        /// default.
330        pub inherit_stderr: Option<bool>,
331        /// Maximum number of frames to capture in backtraces.
332        pub max_backtrace: Option<usize>,
333        /// Whether or not `*.cwasm` files have symbols in them.
334        pub symbols: Option<bool>,
335    }
336
337    enum Debug {
338        ...
339    }
340}
341
342wasmtime_option_group! {
343    #[env = "WASM"]
344    pub struct WasmOptions {
345        /// Enable canonicalization of all NaN values.
346        pub nan_canonicalization: Option<bool>,
347        /// Enable execution fuel with N units fuel, trapping after running out
348        /// of fuel.
349        ///
350        /// Most WebAssembly instructions consume 1 unit of fuel. Some
351        /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
352        /// units, as any execution cost associated with them involves other
353        /// instructions which do consume fuel.
354        pub fuel: Option<u64>,
355        /// Yield when a global epoch counter changes, allowing for async
356        /// operation without blocking the executor.
357        pub epoch_interruption: Option<bool>,
358        /// Maximum stack size, in bytes, that wasm is allowed to consume before a
359        /// stack overflow is reported.
360        pub max_wasm_stack: Option<usize>,
361        /// Stack size, in bytes, that will be allocated for async stacks.
362        ///
363        /// Note that this must be larger than `max-wasm-stack` and the
364        /// difference between the two is how much stack the host has to execute
365        /// on.
366        pub async_stack_size: Option<usize>,
367        /// Configures whether or not stacks used for async futures are zeroed
368        /// before (re)use as a defense-in-depth mechanism. (default: false)
369        pub async_stack_zeroing: Option<bool>,
370        /// Allow unknown exports when running commands.
371        pub unknown_exports_allow: Option<bool>,
372        /// Allow the main module to import unknown functions, using an
373        /// implementation that immediately traps, when running commands.
374        pub unknown_imports_trap: Option<bool>,
375        /// Allow the main module to import unknown functions, using an
376        /// implementation that returns default values, when running commands.
377        pub unknown_imports_default: Option<bool>,
378        /// Enables memory error checking. (see wmemcheck.md for more info)
379        pub wmemcheck: Option<bool>,
380        /// Maximum size, in bytes, that a linear memory is allowed to reach.
381        ///
382        /// Growth beyond this limit will cause `memory.grow` instructions in
383        /// WebAssembly modules to return -1 and fail.
384        pub max_memory_size: Option<usize>,
385        /// Maximum size, in table elements, that a table is allowed to reach.
386        pub max_table_elements: Option<usize>,
387        /// Maximum number of WebAssembly instances allowed to be created.
388        pub max_instances: Option<usize>,
389        /// Maximum number of WebAssembly tables allowed to be created.
390        pub max_tables: Option<usize>,
391        /// Maximum number of WebAssembly linear memories allowed to be created.
392        pub max_memories: Option<usize>,
393        /// Force a trap to be raised on `memory.grow` and `table.grow` failure
394        /// instead of returning -1 from these instructions.
395        ///
396        /// This is not necessarily a spec-compliant option to enable but can be
397        /// useful for tracking down a backtrace of what is requesting so much
398        /// memory, for example.
399        pub trap_on_grow_failure: Option<bool>,
400        /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc)
401        pub timeout: Option<Duration>,
402        /// Configures support for all WebAssembly proposals implemented.
403        pub all_proposals: Option<bool>,
404        /// Configure support for the bulk memory proposal.
405        pub bulk_memory: Option<bool>,
406        /// Configure support for the multi-memory proposal.
407        pub multi_memory: Option<bool>,
408        /// Configure support for the multi-value proposal.
409        pub multi_value: Option<bool>,
410        /// Configure support for the reference-types proposal.
411        pub reference_types: Option<bool>,
412        /// Configure support for the simd proposal.
413        pub simd: Option<bool>,
414        /// Configure support for the relaxed-simd proposal.
415        pub relaxed_simd: Option<bool>,
416        /// Configure forcing deterministic and host-independent behavior of
417        /// the relaxed-simd instructions.
418        ///
419        /// By default these instructions may have architecture-specific behavior as
420        /// allowed by the specification, but this can be used to force the behavior
421        /// of these instructions to match the deterministic behavior classified in
422        /// the specification. Note that enabling this option may come at a
423        /// performance cost.
424        pub relaxed_simd_deterministic: Option<bool>,
425        /// Configure support for the tail-call proposal.
426        pub tail_call: Option<bool>,
427        /// Configure support for the threads proposal.
428        pub threads: Option<bool>,
429        /// Configure the ability to create a `shared` memory.
430        pub shared_memory: Option<bool>,
431        /// Configure support for the shared-everything-threads proposal.
432        pub shared_everything_threads: Option<bool>,
433        /// Configure support for the memory64 proposal.
434        pub memory64: Option<bool>,
435        /// Configure support for the component-model proposal.
436        pub component_model: Option<bool>,
437        /// Component model support for async lifting/lowering.
438        pub component_model_async: Option<bool>,
439        /// Component model support for async lifting/lowering: this corresponds
440        /// to the ๐Ÿš emoji in the component model specification.
441        pub component_model_more_async_builtins: Option<bool>,
442        /// Component model support for async lifting/lowering: this corresponds
443        /// to the ๐ŸšŸ emoji in the component model specification.
444        pub component_model_async_stackful: Option<bool>,
445        /// Component model support for threading: this corresponds
446        /// to the ๐Ÿงต emoji in the component model specification.
447        pub component_model_threading: Option<bool>,
448        /// Component model support for `error-context`: this corresponds
449        /// to the ๐Ÿ“ emoji in the component model specification.
450        pub component_model_error_context: Option<bool>,
451        /// GC support in the component model: this corresponds to the ๐Ÿ›ธ emoji
452        /// in the component model specification.
453        pub component_model_gc: Option<bool>,
454        /// Map support in the component model.
455        pub component_model_map: Option<bool>,
456        /// Component model support for `memory64`: this corresponds
457        /// to the ๐Ÿ˜ emoji in the component model specification.
458        pub component_model_memory64: Option<bool>,
459        /// Configure support for the function-references proposal.
460        pub function_references: Option<bool>,
461        /// Configure support for the stack-switching proposal.
462        pub stack_switching: Option<bool>,
463        /// Configure support for the GC proposal.
464        pub gc: Option<bool>,
465        /// Configure support for the custom-page-sizes proposal.
466        pub custom_page_sizes: Option<bool>,
467        /// Configure support for the wide-arithmetic proposal.
468        pub wide_arithmetic: Option<bool>,
469        /// Configure support for the branch-hinting proposal.
470        pub branch_hinting: Option<bool>,
471        /// Configure support for the extended-const proposal.
472        pub extended_const: Option<bool>,
473        /// Configure support for the exceptions proposal.
474        pub exceptions: Option<bool>,
475        /// Whether or not any GC infrastructure in Wasmtime is enabled or not.
476        pub gc_support: Option<bool>,
477        /// Component model support for fixed-length lists: this corresponds
478        /// to the ๐Ÿ”ง emoji in the component model specification
479        pub component_model_fixed_length_lists: Option<bool>,
480        /// Component model support for `(implements ...)`, corresponds to the
481        /// ๐Ÿท๏ธ emoji in the upstream spec.
482        pub component_model_implements: Option<bool>,
483        /// Whether or not any concurrency infrastructure in Wasmtime is
484        /// enabled or not.
485        pub concurrency_support: Option<bool>,
486    }
487
488    enum Wasm {
489        ...
490    }
491}
492
493wasmtime_option_group! {
494    #[env = "WASI"]
495    pub struct WasiOptions {
496        /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random.
497        pub cli: Option<bool>,
498        /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code)
499        pub cli_exit_with_code: Option<bool>,
500        /// Deprecated alias for `cli`
501        pub common: Option<bool>,
502        /// Enable support for WASI neural network imports (experimental)
503        pub nn: Option<bool>,
504        /// Enable support for WASI threading imports (experimental). Implies preview2=false.
505        pub threads: Option<bool>,
506        /// Enable support for WASI HTTP imports
507        pub http: Option<bool>,
508        /// Number of distinct write calls to the outgoing body's output-stream
509        /// that the implementation will buffer.
510        /// Default: 1.
511        pub http_outgoing_body_buffer_chunks: Option<usize>,
512        /// Maximum size allowed in a write call to the outgoing body's output-stream.
513        /// Default: 1024 * 1024.
514        pub http_outgoing_body_chunk_size: Option<usize>,
515        /// Enable support for WASI config imports (experimental)
516        pub config: Option<bool>,
517        /// Enable support for WASI key-value imports (experimental)
518        pub keyvalue: Option<bool>,
519        /// Inherit environment variables and file descriptors following the
520        /// systemd listen fd specification (UNIX only) (legacy wasip1
521        /// implementation only)
522        pub listenfd: Option<bool>,
523        /// Grant access to the given TCP listen socket (experimental, legacy
524        /// wasip1 implementation only)
525        #[serde(default)]
526        pub tcplisten: Vec<String>,
527        /// Enable support for WASI TLS (Transport Layer Security) imports (experimental)
528        pub tls: Option<bool>,
529        /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy
530        /// implementation (false)
531        pub preview2: Option<bool>,
532        /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn.
533        ///
534        /// Each use of the flag will preload a ML model from the host directory
535        /// using the given model encoding. The model will be mapped to the
536        /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload
537        /// an OpenVINO model named `bar`. Note that which model encodings are
538        /// available is dependent on the backends implemented in the
539        /// `wasmtime_wasi_nn` crate.
540        #[serde(skip)]
541        pub nn_graph: Vec<WasiNnGraph>,
542        /// Flag for WASI preview2 to inherit the host's network within the
543        /// guest so it has full access to all addresses/ports/etc.
544        pub inherit_network: Option<bool>,
545        /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not.
546        pub allow_ip_name_lookup: Option<bool>,
547        /// Indicates whether `wasi:sockets` TCP support is enabled or not.
548        pub tcp: Option<bool>,
549        /// Indicates whether `wasi:sockets` UDP support is enabled or not.
550        pub udp: Option<bool>,
551        /// Enable WASI APIs marked as: @unstable(feature = network-error-code)
552        pub network_error_code: Option<bool>,
553        /// Allows imports from the `wasi_unstable` core wasm module.
554        pub preview0: Option<bool>,
555        /// Inherit all environment variables from the parent process.
556        ///
557        /// This option can be further overwritten with `--env` flags.
558        pub inherit_env: Option<bool>,
559        /// Inherit stdin from the parent process. On by default.
560        pub inherit_stdin: Option<bool>,
561        /// Inherit stdout from the parent process. On by default.
562        pub inherit_stdout: Option<bool>,
563        /// Inherit stderr from the parent process. On by default.
564        pub inherit_stderr: Option<bool>,
565        /// Initial current working directory reported through `wasi:cli/environment`.
566        pub cwd: Option<String>,
567        /// Pass a wasi config variable to the program.
568        #[serde(skip)]
569        pub config_var: Vec<KeyValuePair>,
570        /// Preset data for the In-Memory provider of WASI key-value API.
571        #[serde(skip)]
572        pub keyvalue_in_memory_data: Vec<KeyValuePair>,
573        /// Enable support for WASIp3 APIs.
574        pub p3: Option<bool>,
575        /// Maximum resources the guest is allowed to create simultaneously.
576        pub max_resources: Option<usize>,
577        /// Fuel to use for all hostcalls to limit guest<->host data transfer.
578        pub hostcall_fuel: Option<usize>,
579        /// Maximum value, in bytes, for a wasi-random 0.2
580        /// `get{,-insecure}-random-bytes` `len` parameter. Calls with a value
581        /// exceeding this limit will trap.
582        pub max_random_size: Option<u64>,
583        /// Maximum value, in bytes, for the contents of a wasi-http 0.2
584        /// `fields` resource (aka `headers` and `trailers`). `fields` methods
585        /// which cause the contents to exceed this size limit will trap.
586        pub max_http_fields_size: Option<usize>,
587    }
588
589    enum Wasi {
590        ...
591    }
592}
593
594wasmtime_option_group! {
595    #[env = "RECORD"]
596    pub struct RecordOptions {
597        /// Filename for the recorded execution trace (or empty string to skip writing a file).
598        pub path: Option<String>,
599        /// Include (optional) signatures to facilitate validation checks during replay
600        /// (see `wasmtime replay` for details).
601        pub validation_metadata: Option<bool>,
602        /// Window size of internal buffering for record events (large windows offer more opportunities
603        /// for coalescing events at the cost of memory usage).
604        pub event_window_size: Option<usize>,
605    }
606
607    enum Record {
608        ...
609    }
610}
611
612#[derive(Debug, Clone, PartialEq)]
613pub struct WasiNnGraph {
614    pub format: String,
615    pub dir: String,
616}
617
618#[derive(Debug, Clone, PartialEq)]
619pub struct KeyValuePair {
620    pub key: String,
621    pub value: String,
622}
623
624/// Common options for commands that translate WebAssembly modules
625#[derive(Clone)]
626#[cfg_attr(feature = "clap", derive(clap::Parser))]
627#[cfg_attr(
628    feature = "serde",
629    derive(serde_derive::Deserialize, serde_derive::Serialize)
630)]
631#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
632pub struct CommonOptions {
633    // These options groups are used to parse `-O` and such options but aren't
634    // the raw form consumed by the CLI. Instead they're pushed into the `pub`
635    // fields below as part of the `configure` method.
636    //
637    // Ideally clap would support `pub opts: OptimizeOptions` and parse directly
638    // into that but it does not appear to do so for multiple `-O` flags for
639    // now.
640    /// Optimization and tuning related options for wasm performance, `-O help` to
641    /// see all.
642    #[cfg_attr(
643        feature = "clap",
644        arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")
645    )]
646    #[cfg_attr(feature = "serde", serde(skip))]
647    opts_raw: Vec<opt::CommaSeparated<Optimize>>,
648
649    /// Codegen-related configuration options, `-C help` to see all.
650    #[cfg_attr(
651        feature = "clap",
652        arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")
653    )]
654    #[cfg_attr(feature = "serde", serde(skip))]
655    codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
656
657    /// Debug-related configuration options, `-D help` to see all.
658    #[cfg_attr(
659        feature = "clap",
660        arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")
661    )]
662    #[cfg_attr(feature = "serde", serde(skip))]
663    debug_raw: Vec<opt::CommaSeparated<Debug>>,
664
665    /// Options for configuring semantic execution of WebAssembly, `-W help` to see
666    /// all.
667    #[cfg_attr(
668        feature = "clap",
669        arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")
670    )]
671    #[cfg_attr(feature = "serde", serde(skip))]
672    wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
673
674    /// Options for configuring WASI and its proposals, `-S help` to see all.
675    #[cfg_attr(
676        feature = "clap",
677        arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")
678    )]
679    #[cfg_attr(feature = "serde", serde(skip))]
680    wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
681
682    /// Options to enable and configure execution recording, `-R help` to see all.
683    ///
684    /// Generates a serialized trace of the Wasm module execution that captures all
685    /// non-determinism observable by the module. This trace can subsequently be
686    /// re-executed in a deterministic, embedding-agnostic manner (see the `wasmtime replay` command).
687    ///
688    /// Note: Minimal configuration options for deterministic Wasm semantics will be
689    /// enforced during recording by default (NaN canonicalization, deterministic relaxed SIMD).
690    #[cfg_attr(
691        feature = "clap",
692        arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")
693    )]
694    #[cfg_attr(feature = "serde", serde(skip))]
695    record_raw: Vec<opt::CommaSeparated<Record>>,
696
697    // These fields are filled in by the `configure` method below via the
698    // options parsed from the CLI above. This is what the CLI should use.
699    #[cfg_attr(feature = "clap", arg(skip))]
700    #[cfg_attr(feature = "serde", serde(skip))]
701    configured: bool,
702
703    #[cfg_attr(feature = "clap", arg(skip))]
704    #[cfg_attr(feature = "serde", serde(rename = "optimize", default))]
705    pub opts: OptimizeOptions,
706
707    #[cfg_attr(feature = "clap", arg(skip))]
708    #[cfg_attr(feature = "serde", serde(default))]
709    pub codegen: CodegenOptions,
710
711    #[cfg_attr(feature = "clap", arg(skip))]
712    #[cfg_attr(feature = "serde", serde(default))]
713    pub debug: DebugOptions,
714
715    #[cfg_attr(feature = "clap", arg(skip))]
716    #[cfg_attr(feature = "serde", serde(default))]
717    pub wasm: WasmOptions,
718
719    #[cfg_attr(feature = "clap", arg(skip))]
720    #[cfg_attr(feature = "serde", serde(default))]
721    pub wasi: WasiOptions,
722
723    #[cfg_attr(feature = "clap", arg(skip))]
724    #[cfg_attr(feature = "serde", serde(default))]
725    pub record: RecordOptions,
726
727    /// The target triple; default is the host triple
728    #[cfg_attr(feature = "clap", arg(long, value_name = "TARGET"))]
729    #[cfg_attr(feature = "serde", serde(skip))]
730    pub target: Option<String>,
731
732    /// Use the specified TOML configuration file.
733    /// This TOML configuration file can provide same configuration options as the
734    /// `--optimize`, `--codegen`, `--debug`, `--wasm`, `--wasi` CLI options, with a couple exceptions.
735    ///
736    /// Additional options specified on the command line will take precedent over options loaded from
737    /// this TOML file.
738    #[cfg_attr(feature = "clap", arg(long = "config", value_name = "FILE"))]
739    #[cfg_attr(feature = "serde", serde(skip))]
740    pub config: Option<PathBuf>,
741}
742
743macro_rules! match_feature {
744    (
745        [$feat:tt : $config:expr]
746        $val:ident => $e:expr,
747        $p:pat => err,
748    ) => {
749        #[cfg(feature = $feat)]
750        {
751            if let Some($val) = $config {
752                $e;
753            }
754        }
755        #[cfg(not(feature = $feat))]
756        {
757            if let Some($p) = $config {
758                bail!(concat!("support for ", $feat, " disabled at compile time"));
759            }
760        }
761    };
762}
763
764impl CommonOptions {
765    /// Creates a blank new set of [`CommonOptions`] that can be configured.
766    pub fn new() -> CommonOptions {
767        CommonOptions {
768            opts_raw: Vec::new(),
769            codegen_raw: Vec::new(),
770            debug_raw: Vec::new(),
771            wasm_raw: Vec::new(),
772            wasi_raw: Vec::new(),
773            record_raw: Vec::new(),
774            configured: true,
775            opts: Default::default(),
776            codegen: Default::default(),
777            debug: Default::default(),
778            wasm: Default::default(),
779            wasi: Default::default(),
780            record: Default::default(),
781            target: None,
782            config: None,
783        }
784    }
785
786    fn configure(&mut self) -> Result<()> {
787        if self.configured {
788            return Ok(());
789        }
790        self.configured = true;
791        if let Some(toml_config_path) = &self.config {
792            #[cfg(feature = "toml")]
793            {
794                let toml_options = CommonOptions::from_file(toml_config_path)?;
795                self.opts = toml_options.opts;
796                self.codegen = toml_options.codegen;
797                self.debug = toml_options.debug;
798                self.wasm = toml_options.wasm;
799                self.wasi = toml_options.wasi;
800                self.record = toml_options.record;
801            }
802            #[cfg(not(feature = "toml"))]
803            {
804                bail!(
805                    "support for loading a configuration file from \
806                     {toml_config_path:?} disabled at compile time"
807                );
808            }
809        }
810        self.opts.configure_with(&self.opts_raw)?;
811        self.codegen.configure_with(&self.codegen_raw)?;
812        self.debug.configure_with(&self.debug_raw)?;
813        self.wasm.configure_with(&self.wasm_raw)?;
814        self.wasi.configure_with(&self.wasi_raw)?;
815        self.record.configure_with(&self.record_raw)?;
816        Ok(())
817    }
818
819    pub fn init_logging(&mut self) -> Result<()> {
820        self.configure()?;
821        if self.debug.logging == Some(false) {
822            return Ok(());
823        }
824        #[cfg(feature = "logging")]
825        if self.debug.log_to_files == Some(true) {
826            let prefix = "wasmtime.dbg.";
827            init_file_per_thread_logger(prefix);
828        } else {
829            use std::io::IsTerminal;
830            use tracing_subscriber::{EnvFilter, FmtSubscriber};
831            let builder = FmtSubscriber::builder()
832                .with_writer(std::io::stderr)
833                .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
834                .with_ansi(std::io::stderr().is_terminal());
835            if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
836                builder
837                    .with_level(false)
838                    .with_target(false)
839                    .without_time()
840                    .init()
841            } else {
842                builder.init();
843            }
844        }
845        #[cfg(not(feature = "logging"))]
846        if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
847            bail!("support for logging disabled at compile time");
848        }
849        Ok(())
850    }
851
852    pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
853        self.configure()?;
854        let mut config = Config::new();
855
856        match_feature! {
857            ["cranelift" : self.codegen.compiler]
858            strategy => config.strategy(strategy),
859            _ => err,
860        }
861        match_feature! {
862            ["gc" : self.codegen.collector]
863            collector => config.collector(collector),
864            _ => err,
865        }
866        if let Some(target) = &self.target {
867            config.target(target)?;
868        }
869        match_feature! {
870            ["cranelift" : self.codegen.cranelift_debug_verifier]
871            enable => config.cranelift_debug_verifier(enable),
872            true => err,
873        }
874        if let Some(enable) = self.debug.debug_info {
875            config.debug_info(enable);
876        }
877        match_feature! {
878            ["debug" : self.debug.guest_debug]
879            enable => config.guest_debug(enable),
880            _ => err,
881        }
882        if self.debug.coredump.is_some() {
883            #[cfg(feature = "coredump")]
884            config.coredump_on_trap(true);
885            #[cfg(not(feature = "coredump"))]
886            bail!("support for coredumps disabled at compile time");
887        }
888        match_feature! {
889            ["cranelift" : self.opts.opt_level]
890            level => config.cranelift_opt_level(level),
891            _ => err,
892        }
893        match_feature! {
894            ["cranelift": self.opts.regalloc_algorithm]
895            algo => config.cranelift_regalloc_algorithm(algo),
896            _ => err,
897        }
898        match_feature! {
899            ["cranelift" : self.wasm.nan_canonicalization]
900            enable => config.cranelift_nan_canonicalization(enable),
901            true => err,
902        }
903
904        self.enable_wasm_features(&mut config)?;
905
906        #[cfg(feature = "cranelift")]
907        for (name, value) in self.codegen.cranelift.iter() {
908            let name = name.replace('-', "_");
909            unsafe {
910                match value {
911                    Some(val) => {
912                        config.cranelift_flag_set(&name, val);
913                    }
914                    None => {
915                        config.cranelift_flag_enable(&name);
916                    }
917                }
918            }
919        }
920        #[cfg(not(feature = "cranelift"))]
921        if !self.codegen.cranelift.is_empty() {
922            bail!("support for cranelift disabled at compile time");
923        }
924
925        #[cfg(feature = "cache")]
926        if self.codegen.cache != Some(false) {
927            use wasmtime::Cache;
928            let cache = match &self.codegen.cache_config {
929                Some(path) => Cache::from_file(Some(std::path::Path::new(path)))?,
930                None => Cache::from_file(None)?,
931            };
932            config.cache(Some(cache));
933        }
934        #[cfg(not(feature = "cache"))]
935        if self.codegen.cache == Some(true) {
936            bail!("support for caching disabled at compile time");
937        }
938
939        match_feature! {
940            ["parallel-compilation" : self.codegen.parallel_compilation]
941            enable => config.parallel_compilation(enable),
942            true => err,
943        }
944
945        let memory_reservation = self
946            .opts
947            .memory_reservation
948            .or(self.opts.static_memory_maximum_size);
949        if let Some(size) = memory_reservation {
950            config.memory_reservation(size);
951        }
952
953        if let Some(enable) = self.opts.static_memory_forced {
954            config.memory_may_move(!enable);
955        }
956        if let Some(enable) = self.opts.memory_may_move {
957            config.memory_may_move(enable);
958        }
959
960        let memory_guard_size = self
961            .opts
962            .static_memory_guard_size
963            .or(self.opts.dynamic_memory_guard_size)
964            .or(self.opts.memory_guard_size);
965        if let Some(size) = memory_guard_size {
966            config.memory_guard_size(size);
967        }
968
969        let mem_for_growth = self
970            .opts
971            .memory_reservation_for_growth
972            .or(self.opts.dynamic_memory_reserved_for_growth);
973        if let Some(size) = mem_for_growth {
974            config.memory_reservation_for_growth(size);
975        }
976        if let Some(enable) = self.opts.guard_before_linear_memory {
977            config.guard_before_linear_memory(enable);
978        }
979
980        if let Some(size) = self.opts.gc_heap_reservation {
981            config.gc_heap_reservation(size);
982        }
983        if let Some(enable) = self.opts.gc_heap_may_move {
984            config.gc_heap_may_move(enable);
985        }
986        if let Some(size) = self.opts.gc_heap_guard_size {
987            config.gc_heap_guard_size(size);
988        }
989        if let Some(size) = self.opts.gc_heap_reservation_for_growth {
990            config.gc_heap_reservation_for_growth(size);
991        }
992
993        if let Some(size) = self.opts.gc_heap_initial_size {
994            config.gc_heap_initial_size(size);
995        }
996
997        if let Some(enable) = self.opts.table_lazy_init {
998            config.table_lazy_init(enable);
999        }
1000
1001        if let Some(n) = self.opts.gc_zeal_alloc_counter
1002            && (cfg!(gc_zeal) || cfg!(fuzzing))
1003        {
1004            config.gc_zeal_alloc_counter(Some(n))?;
1005        }
1006
1007        // If fuel has been configured, set the `consume fuel` flag on the config.
1008        if self.wasm.fuel.is_some() {
1009            config.consume_fuel(true);
1010        }
1011
1012        if let Some(enable) = self.wasm.epoch_interruption {
1013            config.epoch_interruption(enable);
1014        }
1015        if let Some(enable) = self.debug.address_map {
1016            config.generate_address_map(enable);
1017        }
1018        if let Some(frames) = self.debug.max_backtrace {
1019            match NonZeroUsize::new(frames) {
1020                None => {
1021                    config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
1022                }
1023                Some(amt) => {
1024                    config.wasm_backtrace_max_frames(Some(amt));
1025                }
1026            }
1027        }
1028        if let Some(enable) = self.debug.symbols {
1029            config.debug_symbols(enable);
1030        }
1031        if let Some(enable) = self.opts.memory_init_cow {
1032            config.memory_init_cow(enable);
1033        }
1034        if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
1035            config.memory_guaranteed_dense_image_size(size);
1036        }
1037        if let Some(enable) = self.opts.signals_based_traps {
1038            config.signals_based_traps(enable);
1039        }
1040        if let Some(enable) = self.codegen.native_unwind_info {
1041            config.native_unwind_info(enable);
1042        }
1043        if let Some(enable) = self.codegen.inlining {
1044            config.compiler_inlining(enable);
1045        }
1046        if let Some(enable) = self.codegen.metadata_for_internal_asserts {
1047            config.metadata_for_internal_asserts(enable);
1048        }
1049        if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
1050            config.metadata_for_gc_heap_corruption(enable);
1051        }
1052
1053        // async_stack_size enabled by either async or stack-switching, so
1054        // cannot directly use match_feature!
1055        #[cfg(any(feature = "async", feature = "stack-switching"))]
1056        {
1057            if let Some(size) = self.wasm.async_stack_size {
1058                config.async_stack_size(size);
1059            }
1060        }
1061        #[cfg(not(any(feature = "async", feature = "stack-switching")))]
1062        {
1063            if let Some(_size) = self.wasm.async_stack_size {
1064                bail!(concat!(
1065                    "support for async/stack-switching disabled at compile time"
1066                ));
1067            }
1068        }
1069
1070        match_feature! {
1071            ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
1072            enable => {
1073                if enable {
1074                    let mut cfg = wasmtime::PoolingAllocationConfig::default();
1075                    if let Some(size) = self.opts.pooling_memory_keep_resident {
1076                        cfg.linear_memory_keep_resident(size);
1077                    }
1078                    if let Some(size) = self.opts.pooling_table_keep_resident {
1079                        cfg.table_keep_resident(size);
1080                    }
1081                    if let Some(limit) = self.opts.pooling_total_core_instances {
1082                        cfg.total_core_instances(limit);
1083                    }
1084                    if let Some(limit) = self.opts.pooling_total_component_instances {
1085                        cfg.total_component_instances(limit);
1086                    }
1087                    if let Some(limit) = self.opts.pooling_total_memories {
1088                        cfg.total_memories(limit);
1089                    }
1090                    if let Some(limit) = self.opts.pooling_total_tables {
1091                        cfg.total_tables(limit);
1092                    }
1093                    if let Some(limit) = self.opts.pooling_table_elements
1094                        .or(self.wasm.max_table_elements)
1095                    {
1096                        cfg.table_elements(limit);
1097                    }
1098                    if let Some(limit) = self.opts.pooling_max_core_instance_size {
1099                        cfg.max_core_instance_size(limit);
1100                    }
1101                    match_feature! {
1102                        ["async" : self.opts.pooling_total_stacks]
1103                        limit => cfg.total_stacks(limit),
1104                        _ => err,
1105                    }
1106                    if let Some(max) = self.opts.pooling_max_memory_size
1107                        .or(self.wasm.max_memory_size)
1108                    {
1109                        cfg.max_memory_size(max);
1110                    }
1111                    if let Some(size) = self.opts.pooling_decommit_batch_size {
1112                        cfg.decommit_batch_size(size);
1113                    }
1114                    if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1115                        cfg.max_unused_warm_slots(max);
1116                    }
1117                    match_feature! {
1118                        ["async" : self.opts.pooling_async_stack_keep_resident]
1119                        size => cfg.async_stack_keep_resident(size),
1120                        _ => err,
1121                    }
1122                    if let Some(max) = self.opts.pooling_max_component_instance_size {
1123                        cfg.max_component_instance_size(max);
1124                    }
1125                    if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1126                        cfg.max_core_instances_per_component(max);
1127                    }
1128                    if let Some(max) = self.opts.pooling_max_memories_per_component {
1129                        cfg.max_memories_per_component(max);
1130                    }
1131                    if let Some(max) = self.opts.pooling_max_tables_per_component {
1132                        cfg.max_tables_per_component(max);
1133                    }
1134                    if let Some(max) = self.opts.pooling_max_tables_per_module {
1135                        cfg.max_tables_per_module(max);
1136                    }
1137                    if let Some(max) = self.opts.pooling_max_memories_per_module {
1138                        cfg.max_memories_per_module(max);
1139                    }
1140                    match_feature! {
1141                        ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1142                        enable => cfg.memory_protection_keys(enable),
1143                        _ => err,
1144                    }
1145                    match_feature! {
1146                        ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1147                        max => cfg.max_memory_protection_keys(max),
1148                        _ => err,
1149                    }
1150                    match_feature! {
1151                        ["gc" : self.opts.pooling_total_gc_heaps]
1152                        max => cfg.total_gc_heaps(max),
1153                        _ => err,
1154                    }
1155                    if let Some(enabled) = self.opts.pooling_pagemap_scan {
1156                        cfg.pagemap_scan(enabled);
1157                    }
1158                    config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1159                }
1160            },
1161            true => err,
1162        }
1163
1164        if self.opts.pooling_memory_protection_keys.is_some()
1165            && !self.opts.pooling_allocator.unwrap_or(false)
1166        {
1167            bail!("memory protection keys require the pooling allocator");
1168        }
1169
1170        if self.opts.pooling_max_memory_protection_keys.is_some()
1171            && !self.opts.pooling_memory_protection_keys.is_some()
1172        {
1173            bail!("max memory protection keys requires memory protection keys to be enabled");
1174        }
1175
1176        match_feature! {
1177            ["async" : self.wasm.async_stack_zeroing]
1178            enable => config.async_stack_zeroing(enable),
1179            _ => err,
1180        }
1181
1182        if let Some(max) = self.wasm.max_wasm_stack {
1183            config.max_wasm_stack(max);
1184
1185            // If `-Wasync-stack-size` isn't passed then automatically adjust it
1186            // to the wasm stack size provided here too. That prevents the need
1187            // to pass both when one can generally be inferred from the other.
1188            #[cfg(any(feature = "async", feature = "stack-switching"))]
1189            if self.wasm.async_stack_size.is_none() {
1190                const DEFAULT_HOST_STACK: usize = 512 << 10;
1191                config.async_stack_size(max + DEFAULT_HOST_STACK);
1192            }
1193        }
1194
1195        if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1196            config.relaxed_simd_deterministic(enable);
1197        }
1198        match_feature! {
1199            ["cranelift" : self.wasm.wmemcheck]
1200            enable => config.wmemcheck(enable),
1201            true => err,
1202        }
1203
1204        if let Some(enable) = self.wasm.gc_support {
1205            config.gc_support(enable);
1206        }
1207
1208        if let Some(enable) = self.wasm.concurrency_support {
1209            config.concurrency_support(enable);
1210        }
1211
1212        if let Some(enable) = self.wasm.shared_memory {
1213            config.shared_memory(enable);
1214        }
1215
1216        let record = &self.record;
1217        match_feature! {
1218            ["rr" : &record.path]
1219            _path => {
1220                bail!("recording configuration for `rr` feature is not supported yet");
1221            },
1222            _ => err,
1223        }
1224
1225        Ok(config)
1226    }
1227
1228    pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1229        let all = self.wasm.all_proposals;
1230
1231        if let Some(enable) = self.wasm.simd.or(all) {
1232            config.wasm_simd(enable);
1233        }
1234        if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1235            config.wasm_relaxed_simd(enable);
1236        }
1237        if let Some(enable) = self.wasm.bulk_memory.or(all) {
1238            config.wasm_bulk_memory(enable);
1239        }
1240        if let Some(enable) = self.wasm.multi_value.or(all) {
1241            config.wasm_multi_value(enable);
1242        }
1243        if let Some(enable) = self.wasm.tail_call.or(all) {
1244            config.wasm_tail_call(enable);
1245        }
1246        if let Some(enable) = self.wasm.multi_memory.or(all) {
1247            config.wasm_multi_memory(enable);
1248        }
1249        if let Some(enable) = self.wasm.memory64.or(all) {
1250            config.wasm_memory64(enable);
1251        }
1252        if let Some(enable) = self.wasm.stack_switching {
1253            config.wasm_stack_switching(enable);
1254        }
1255        if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1256            config.wasm_custom_page_sizes(enable);
1257        }
1258        if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1259            config.wasm_wide_arithmetic(enable);
1260        }
1261        // Not included in `all_proposals`: off by default until fuzzed.
1262        if let Some(enable) = self.wasm.branch_hinting {
1263            config.wasm_branch_hinting(enable);
1264        }
1265        if let Some(enable) = self.wasm.extended_const.or(all) {
1266            config.wasm_extended_const(enable);
1267        }
1268
1269        macro_rules! handle_conditionally_compiled {
1270            ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1271                if let Some(enable) = self.wasm.$field.or(all) {
1272                    #[cfg(feature = $feature)]
1273                    config.$method(enable);
1274                    #[cfg(not(feature = $feature))]
1275                    if enable && all.is_none() {
1276                        bail!("support for {} was disabled at compile-time", $feature);
1277                    }
1278                }
1279            )*)
1280        }
1281
1282        handle_conditionally_compiled! {
1283            ("component-model", component_model, wasm_component_model)
1284            ("component-model-async", component_model_async, wasm_component_model_async)
1285            ("component-model-async", component_model_more_async_builtins, wasm_component_model_more_async_builtins)
1286            ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1287            ("component-model-async", component_model_threading, wasm_component_model_threading)
1288            ("component-model", component_model_error_context, wasm_component_model_error_context)
1289            ("component-model", component_model_map, wasm_component_model_map)
1290            ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1291            ("component-model", component_model_implements, wasm_component_model_implements)
1292            ("component-model", component_model_memory64, wasm_component_model_memory64)
1293            ("threads", threads, wasm_threads)
1294            ("gc", gc, wasm_gc)
1295            ("gc", reference_types, wasm_reference_types)
1296            ("gc", function_references, wasm_function_references)
1297            ("gc", exceptions, wasm_exceptions)
1298            ("stack-switching", stack_switching, wasm_stack_switching)
1299        }
1300
1301        if let Some(enable) = self.wasm.component_model_gc {
1302            #[cfg(all(feature = "component-model", feature = "gc"))]
1303            config.wasm_component_model_gc(enable);
1304            #[cfg(not(all(feature = "component-model", feature = "gc")))]
1305            if enable && all.is_none() {
1306                bail!("support for `component-model-gc` was disabled at compile time")
1307            }
1308        }
1309
1310        Ok(())
1311    }
1312
1313    #[cfg(feature = "toml")]
1314    pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
1315        use wasmtime::error::Context;
1316
1317        let path_ref = path.as_ref();
1318        let file_contents = std::fs::read_to_string(path_ref)
1319            .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1320        toml::from_str::<CommonOptions>(&file_contents)
1321            .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1322    }
1323
1324    /// Creates an instance of [`CommonOptions`] by reflecting on the
1325    /// configuration present in the provided [`Engine`].
1326    ///
1327    /// This will extract all configuration values that can be set by this
1328    /// [`CommonOptions`] into a [`Config`] into the returned structure to the
1329    /// best of its ability. Not all configuration options present on [`Engine`]
1330    /// can be reflected back into [`CommonOptions`], and not all options on
1331    /// [`CommonOptions`] can be set on an [`Engine`]. This means that this
1332    /// is a lossy operation that doesn't fully capture 100% of the
1333    /// configuration of [`Engine`]. That being said, however, it can capture
1334    /// almost all of the configuration related to codegen and major other
1335    /// configuration options.
1336    pub fn from_engine(engine: &Engine) -> Self {
1337        let features = engine.get_wasm_features();
1338        let pooling = engine.get_pooling_config();
1339        CommonOptions {
1340            target: engine.get_target(),
1341            opts: OptimizeOptions {
1342                memory_may_move: Some(engine.get_memory_may_move()),
1343                memory_reservation: Some(engine.get_memory_reservation()),
1344                memory_reservation_for_growth: Some(engine.get_memory_reservation_for_growth()),
1345                memory_guard_size: Some(engine.get_memory_guard_size()),
1346                gc_heap_may_move: Some(engine.get_gc_heap_may_move()),
1347                gc_heap_reservation: Some(engine.get_gc_heap_reservation()),
1348                gc_heap_reservation_for_growth: Some(engine.get_gc_heap_reservation_for_growth()),
1349                gc_heap_guard_size: Some(engine.get_gc_heap_guard_size()),
1350                gc_heap_initial_size: Some(engine.get_gc_heap_initial_size()),
1351                guard_before_linear_memory: Some(engine.get_guard_before_linear_memory()),
1352                table_lazy_init: Some(engine.get_table_lazy_init()),
1353                memory_init_cow: Some(engine.get_memory_init_cow()),
1354                memory_guaranteed_dense_image_size: Some(
1355                    engine.get_memory_guaranteed_dense_image_size(),
1356                ),
1357                signals_based_traps: Some(engine.get_signals_based_traps()),
1358                gc_zeal_alloc_counter: engine.get_gc_zeal_alloc_counter(),
1359                opt_level: engine.get_cranelift_opt_level(),
1360                regalloc_algorithm: engine.get_cranelift_regalloc_algorithm(),
1361                pooling_allocator: Some(pooling.is_some()),
1362                pooling_decommit_batch_size: pooling.map(|c| c.get_decommit_batch_size()),
1363                pooling_memory_keep_resident: pooling.map(|c| c.get_memory_keep_resident()),
1364                pooling_table_keep_resident: pooling.map(|c| c.get_table_keep_resident()),
1365                pooling_max_unused_warm_slots: pooling.map(|c| c.get_max_unused_warm_slots()),
1366                pooling_pagemap_scan: pooling.map(|c| c.get_pagemap_scan()),
1367                pooling_total_core_instances: pooling.map(|c| c.get_total_core_instances()),
1368                pooling_total_component_instances: pooling
1369                    .map(|c| c.get_total_component_instances()),
1370                pooling_total_memories: pooling.map(|c| c.get_total_memories()),
1371                pooling_total_tables: pooling.map(|c| c.get_total_tables()),
1372                pooling_max_memory_size: pooling.map(|c| c.get_max_memory_size()),
1373                pooling_table_elements: pooling.map(|c| c.get_table_elements()),
1374                pooling_max_core_instance_size: pooling.map(|c| c.get_max_core_instance_size()),
1375                pooling_max_component_instance_size: pooling
1376                    .map(|c| c.get_max_component_instance_size()),
1377                pooling_max_core_instances_per_component: pooling
1378                    .map(|c| c.get_max_core_instances_per_component()),
1379                pooling_max_memories_per_component: pooling
1380                    .map(|c| c.get_max_memories_per_component()),
1381                pooling_max_tables_per_component: pooling.map(|c| c.get_max_tables_per_component()),
1382                pooling_max_tables_per_module: pooling.map(|c| c.get_max_tables_per_module()),
1383                pooling_max_memories_per_module: pooling.map(|c| c.get_max_memories_per_module()),
1384                pooling_async_stack_keep_resident: pooling
1385                    .map(|c| c.get_async_stack_keep_resident()),
1386                pooling_total_stacks: pooling.map(|c| c.get_total_stacks()),
1387                pooling_total_gc_heaps: pooling.map(|c| c.get_total_gc_heaps()),
1388                pooling_memory_protection_keys: pooling.map(|c| c.get_memory_protection_keys()),
1389                pooling_max_memory_protection_keys: pooling
1390                    .map(|c| c.get_max_memory_protection_keys()),
1391                // Deprecated aliases for the above options; intentionally left
1392                // unset in favor of their replacements.
1393                dynamic_memory_guard_size: None,
1394                static_memory_guard_size: None,
1395                static_memory_forced: None,
1396                static_memory_maximum_size: None,
1397                dynamic_memory_reserved_for_growth: None,
1398            },
1399            codegen: CodegenOptions {
1400                compiler: engine.get_strategy(),
1401                collector: engine.get_collector(),
1402                cranelift_debug_verifier: engine.get_cranelift_debug_verifier(),
1403                inlining: Some(engine.get_compiler_inlining()),
1404                native_unwind_info: engine.get_native_unwind_info(),
1405                parallel_compilation: Some(engine.get_parallel_compilation()),
1406                metadata_for_internal_asserts: Some(engine.get_metadata_for_internal_asserts()),
1407                metadata_for_gc_heap_corruption: Some(engine.get_metadata_for_gc_heap_corruption()),
1408                cranelift: engine
1409                    .get_cranelift_flags_set()
1410                    .map(|(k, v)| (k.to_string(), Some(v.to_string())))
1411                    .chain(
1412                        engine
1413                            .get_cranelift_flags_enabled()
1414                            .map(|k| (k.to_string(), None)),
1415                    )
1416                    .collect(),
1417
1418                // not easily extractable from `Engine` since that supports
1419                // arbitrary code-defined caches.
1420                cache: None,
1421                cache_config: None,
1422            },
1423            debug: DebugOptions {
1424                address_map: Some(engine.get_generate_address_map()),
1425                debug_info: Some(engine.get_debug_info()),
1426                guest_debug: Some(engine.get_guest_debug()),
1427                symbols: Some(engine.get_debug_symbols()),
1428                max_backtrace: Some(engine.get_wasm_backtrace_max_frames()),
1429
1430                // Can't infer a path to emit a core dump to from engine
1431                // configuration.
1432                coredump: None,
1433                // debugger configuration not part of engine config
1434                debugger: None,
1435                arg: Vec::new(),
1436                inherit_stderr: None,
1437                inherit_stdout: None,
1438                inherit_stdin: None,
1439                // logging not part of engine config
1440                log_to_files: None,
1441                logging: None,
1442            },
1443            wasm: WasmOptions {
1444                async_stack_size: Some(engine.get_async_stack_size()),
1445                async_stack_zeroing: Some(engine.get_async_stack_zeroing()),
1446                branch_hinting: Some(engine.get_wasm_branch_hinting()),
1447                bulk_memory: Some(features.contains(WasmFeatures::BULK_MEMORY)),
1448                component_model: Some(features.contains(WasmFeatures::COMPONENT_MODEL)),
1449                component_model_async: Some(features.contains(WasmFeatures::CM_ASYNC)),
1450                component_model_async_stackful: Some(
1451                    features.contains(WasmFeatures::CM_ASYNC_STACKFUL),
1452                ),
1453                component_model_error_context: Some(
1454                    features.contains(WasmFeatures::CM_ERROR_CONTEXT),
1455                ),
1456                component_model_gc: Some(features.contains(WasmFeatures::CM_GC)),
1457                component_model_fixed_length_lists: Some(
1458                    features.contains(WasmFeatures::CM_FIXED_LENGTH_LISTS),
1459                ),
1460                component_model_implements: Some(features.contains(WasmFeatures::CM_IMPLEMENTS)),
1461                component_model_map: Some(features.contains(WasmFeatures::CM_MAP)),
1462                component_model_memory64: Some(features.contains(WasmFeatures::CM64)),
1463                component_model_more_async_builtins: Some(
1464                    features.contains(WasmFeatures::CM_MORE_ASYNC_BUILTINS),
1465                ),
1466                component_model_threading: Some(features.contains(WasmFeatures::CM_THREADING)),
1467                custom_page_sizes: Some(features.contains(WasmFeatures::CUSTOM_PAGE_SIZES)),
1468                exceptions: Some(features.contains(WasmFeatures::EXCEPTIONS)),
1469                extended_const: Some(features.contains(WasmFeatures::EXTENDED_CONST)),
1470                function_references: Some(features.contains(WasmFeatures::FUNCTION_REFERENCES)),
1471                gc: Some(features.contains(WasmFeatures::GC)),
1472                gc_support: Some(features.contains(WasmFeatures::GC_TYPES)),
1473                memory64: Some(features.contains(WasmFeatures::MEMORY64)),
1474                multi_memory: Some(features.contains(WasmFeatures::MULTI_MEMORY)),
1475                multi_value: Some(features.contains(WasmFeatures::MULTI_VALUE)),
1476                reference_types: Some(features.contains(WasmFeatures::REFERENCE_TYPES)),
1477                relaxed_simd: Some(features.contains(WasmFeatures::RELAXED_SIMD)),
1478                shared_everything_threads: Some(
1479                    features.contains(WasmFeatures::SHARED_EVERYTHING_THREADS),
1480                ),
1481                simd: Some(features.contains(WasmFeatures::SIMD)),
1482                stack_switching: Some(features.contains(WasmFeatures::STACK_SWITCHING)),
1483                tail_call: Some(features.contains(WasmFeatures::TAIL_CALL)),
1484                threads: Some(features.contains(WasmFeatures::THREADS)),
1485                wide_arithmetic: Some(features.contains(WasmFeatures::WIDE_ARITHMETIC)),
1486                concurrency_support: Some(engine.get_concurrency_support()),
1487                epoch_interruption: Some(engine.get_epoch_interruption()),
1488                fuel: if engine.get_consume_fuel() {
1489                    Some(1)
1490                } else {
1491                    None
1492                },
1493                max_wasm_stack: Some(engine.get_max_wasm_stack()),
1494                nan_canonicalization: engine.get_cranelift_nan_canonicalization(),
1495                relaxed_simd_deterministic: Some(engine.get_relaxed_simd_deterministic()),
1496                shared_memory: Some(engine.get_shared_memory()),
1497
1498                // This is covered by individual `WasmFeatures::*` flags above.
1499                all_proposals: None,
1500                // These aren't set in `Config` any more, they're just
1501                // historical
1502                max_instances: None,
1503                max_memories: None,
1504                max_memory_size: None,
1505                max_table_elements: None,
1506                max_tables: None,
1507                // not part of engine config, specific to `run` command
1508                timeout: None,
1509                trap_on_grow_failure: None,
1510                unknown_exports_allow: None,
1511                unknown_imports_default: None,
1512                unknown_imports_trap: None,
1513                wmemcheck: None,
1514            },
1515
1516            // Not currently reflected in `Engine`.
1517            record: RecordOptions::default(),
1518
1519            // WASI options aren't reflected in an `Engine`.
1520            wasi: Default::default(),
1521
1522            // CLI flags are represented above, they have default values here.
1523            configured: true,
1524            codegen_raw: Default::default(),
1525            debug_raw: Default::default(),
1526            opts_raw: Default::default(),
1527            record_raw: Default::default(),
1528            wasi_raw: Default::default(),
1529            wasm_raw: Default::default(),
1530
1531            // No external configuration file, it's all above.
1532            config: None,
1533            //
1534            // Note that an exhaustive listing is explicitly used to avoid
1535            // forgetting to configure a field. Please don't add `..something`
1536            // here at the end.
1537        }
1538    }
1539}
1540
1541#[cfg(test)]
1542mod tests {
1543    use wasmtime::{OptLevel, RegallocAlgorithm};
1544
1545    use super::*;
1546
1547    #[test]
1548    fn from_toml() {
1549        // empty toml
1550        let empty_toml = "";
1551        let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1552        common_options.config(None).unwrap();
1553
1554        // basic toml
1555        let basic_toml = r#"
1556            [optimize]
1557            [codegen]
1558            [debug]
1559            [wasm]
1560            [wasi]
1561            [record]
1562        "#;
1563        let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1564        common_options.config(None).unwrap();
1565
1566        // toml with custom deserialization to match CLI flag parsing
1567        for (opt_value, expected) in [
1568            ("0", Some(OptLevel::None)),
1569            ("1", Some(OptLevel::Speed)),
1570            ("2", Some(OptLevel::Speed)),
1571            ("\"s\"", Some(OptLevel::SpeedAndSize)),
1572            ("\"hello\"", None), // should fail
1573            ("3", None),         // should fail
1574        ] {
1575            let toml = format!(
1576                r#"
1577                    [optimize]
1578                    opt-level = {opt_value}
1579                "#,
1580            );
1581            let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1582                .ok()
1583                .and_then(|common_options| common_options.opts.opt_level);
1584
1585            assert_eq!(
1586                parsed_opt_level, expected,
1587                "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1588            );
1589        }
1590
1591        // Regalloc algorithm
1592        for (regalloc_value, expected) in [
1593            ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1594            ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1595            ("\"hello\"", None), // should fail
1596            ("3", None),         // should fail
1597            ("true", None),      // should fail
1598        ] {
1599            let toml = format!(
1600                r#"
1601                    [optimize]
1602                    regalloc-algorithm = {regalloc_value}
1603                "#,
1604            );
1605            let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1606                .ok()
1607                .and_then(|common_options| common_options.opts.regalloc_algorithm);
1608            assert_eq!(
1609                parsed_regalloc_algorithm, expected,
1610                "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1611            );
1612        }
1613
1614        // Strategy
1615        for (strategy_value, expected) in [
1616            ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1617            ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1618            ("\"hello\"", None), // should fail
1619            ("5", None),         // should fail
1620            ("true", None),      // should fail
1621        ] {
1622            let toml = format!(
1623                r#"
1624                    [codegen]
1625                    compiler = {strategy_value}
1626                "#,
1627            );
1628            let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1629                .ok()
1630                .and_then(|common_options| common_options.codegen.compiler);
1631            assert_eq!(
1632                parsed_strategy, expected,
1633                "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1634            );
1635        }
1636
1637        // Collector
1638        for (collector_value, expected) in [
1639            (
1640                "\"drc\"",
1641                Some(wasmtime::Collector::DeferredReferenceCounting),
1642            ),
1643            ("\"null\"", Some(wasmtime::Collector::Null)),
1644            ("\"copying\"", Some(wasmtime::Collector::Copying)),
1645            ("\"hello\"", None), // should fail
1646            ("5", None),         // should fail
1647            ("true", None),      // should fail
1648        ] {
1649            let toml = format!(
1650                r#"
1651                    [codegen]
1652                    collector = {collector_value}
1653                "#,
1654            );
1655            let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1656                .ok()
1657                .and_then(|common_options| common_options.codegen.collector);
1658            assert_eq!(
1659                parsed_collector, expected,
1660                "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1661            );
1662        }
1663    }
1664}
1665
1666impl Default for CommonOptions {
1667    fn default() -> CommonOptions {
1668        CommonOptions::new()
1669    }
1670}
1671
1672impl fmt::Display for CommonOptions {
1673    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1674        let CommonOptions {
1675            codegen_raw,
1676            codegen,
1677            debug_raw,
1678            debug,
1679            opts_raw,
1680            opts,
1681            wasm_raw,
1682            wasm,
1683            wasi_raw,
1684            wasi,
1685            record_raw,
1686            record,
1687            configured,
1688            target,
1689            config,
1690        } = self;
1691        if let Some(target) = target {
1692            write!(f, "--target {target} ")?;
1693        }
1694        if let Some(config) = config {
1695            write!(f, "--config {} ", config.display())?;
1696        }
1697
1698        let codegen_flags;
1699        let opts_flags;
1700        let wasi_flags;
1701        let wasm_flags;
1702        let debug_flags;
1703        let record_flags;
1704
1705        if *configured {
1706            codegen_flags = codegen.to_options();
1707            debug_flags = debug.to_options();
1708            wasi_flags = wasi.to_options();
1709            wasm_flags = wasm.to_options();
1710            opts_flags = opts.to_options();
1711            record_flags = record.to_options();
1712        } else {
1713            codegen_flags = codegen_raw
1714                .iter()
1715                .flat_map(|t| t.0.iter())
1716                .cloned()
1717                .collect();
1718            debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1719            wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1720            wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1721            opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1722            record_flags = record_raw
1723                .iter()
1724                .flat_map(|t| t.0.iter())
1725                .cloned()
1726                .collect();
1727        }
1728
1729        for flag in codegen_flags {
1730            write!(f, "-C{flag} ")?;
1731        }
1732        for flag in opts_flags {
1733            write!(f, "-O{flag} ")?;
1734        }
1735        for flag in wasi_flags {
1736            write!(f, "-S{flag} ")?;
1737        }
1738        for flag in wasm_flags {
1739            write!(f, "-W{flag} ")?;
1740        }
1741        for flag in debug_flags {
1742            write!(f, "-D{flag} ")?;
1743        }
1744        for flag in record_flags {
1745            write!(f, "-R{flag} ")?;
1746        }
1747
1748        Ok(())
1749    }
1750}