Skip to main content

wasmtime_cli_flags/
lib.rs

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