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