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