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