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