Skip to main content

wasmtime_cli_flags/
lib.rs

1//! A utility crate for managing Wasmtime configuration options in a
2//! serializable format.
3//!
4//! This crate primarily provides a [`CommonOptions`] structure which can be
5//! parsed from CLI flags via [`clap`] or with [`serde::Deserialize`]. This
6//! structure can additionally be created from a [`wasmtime::Engine`] to
7//! serialize some of the significant configuration options affecting an engine.
8//!
9//! This is intended to be a shared way for embedders to configure Wasmtime with
10//! serializable configuration. The source of truth for Wasmtime's configuration
11//! is the [`Config`] type but this additionally serves as a means of creating
12//! that type.
13
14use std::num::NonZeroUsize;
15use std::{fmt, num::NonZeroU32, path::PathBuf, time::Duration};
16use wasmtime::{Config, Engine, Result, WasmBacktraceDetails, WasmFeatures, bail};
17
18pub mod opt;
19
20#[cfg(feature = "logging")]
21fn init_file_per_thread_logger(prefix: &'static str) {
22    file_per_thread_logger::initialize(prefix);
23    file_per_thread_logger::allow_uninitialized();
24
25    // Extending behavior of default spawner:
26    // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler
27    // Source code says DefaultSpawner is implementation detail and
28    // shouldn't be used directly.
29    #[cfg(feature = "parallel-compilation")]
30    rayon::ThreadPoolBuilder::new()
31        .spawn_handler(move |thread| {
32            let mut b = std::thread::Builder::new();
33            if let Some(name) = thread.name() {
34                b = b.name(name.to_owned());
35            }
36            if let Some(stack_size) = thread.stack_size() {
37                b = b.stack_size(stack_size);
38            }
39            b.spawn(move || {
40                file_per_thread_logger::initialize(prefix);
41                thread.run()
42            })?;
43            Ok(())
44        })
45        .build_global()
46        .unwrap();
47}
48
49wasmtime_option_group! {
50    #[env = "OPTIMIZE"]
51    pub struct OptimizeOptions {
52        /// Optimization level of generated code (0-2, s; default: 2)
53        #[serde(default)]
54        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
55        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
56        pub opt_level: Option<wasmtime::OptLevel>,
57
58        /// Register allocator algorithm choice.
59        #[serde(default)]
60        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
61        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
62        pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,
63
64        /// Do not allow Wasm linear memories to move in the host process's
65        /// address space.
66        pub memory_may_move: Option<bool>,
67
68        /// Initial virtual memory allocation size for memories.
69        pub memory_reservation: Option<u64>,
70
71        /// Bytes to reserve at the end of linear memory for growth into.
72        pub memory_reservation_for_growth: Option<u64>,
73
74        /// Size, in bytes, of guard pages for linear memories.
75        pub memory_guard_size: Option<u64>,
76
77        /// Do not allow the GC heap to move in the host process's address
78        /// space.
79        pub gc_heap_may_move: Option<bool>,
80
81        /// Initial virtual memory allocation size for the GC heap.
82        pub gc_heap_reservation: Option<u64>,
83
84        /// Bytes to reserve at the end of the GC heap for growth into.
85        pub gc_heap_reservation_for_growth: Option<u64>,
86
87        /// Size, in bytes, of guard pages for the GC heap.
88        pub gc_heap_guard_size: Option<u64>,
89
90        /// Initial allocated size for the GC heap.
91        pub gc_heap_initial_size: Option<u64>,
92
93        /// Indicates whether an unmapped region of memory is placed before all
94        /// linear memories.
95        pub guard_before_linear_memory: Option<bool>,
96
97        /// Whether to initialize tables lazily, so that instantiation is
98        /// fast but indirect calls are a little slower. If no, tables are
99        /// initialized eagerly from any active element segments that apply to
100        /// them during instantiation. (default: yes)
101        pub table_lazy_init: Option<bool>,
102
103        /// Enable the pooling allocator, in place of the on-demand allocator.
104        pub pooling_allocator: Option<bool>,
105
106        /// The number of decommits to do per batch. A batch size of 1
107        /// effectively disables decommit batching. (default: 1)
108        pub pooling_decommit_batch_size: Option<usize>,
109
110        /// How many bytes to keep resident between instantiations for the
111        /// pooling allocator in linear memories.
112        pub pooling_memory_keep_resident: Option<usize>,
113
114        /// How many bytes to keep resident between instantiations for the
115        /// pooling allocator in tables.
116        pub pooling_table_keep_resident: Option<usize>,
117
118        /// Enable memory protection keys for the pooling allocator; this can
119        /// optimize the size of memory slots.
120        #[serde(default)]
121        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
122        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
123        pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,
124
125        /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
126        /// will use. (default: 16)
127        pub pooling_max_memory_protection_keys: Option<usize>,
128
129        /// Configure attempting to initialize linear memory via a
130        /// copy-on-write mapping (default: yes)
131        pub memory_init_cow: Option<bool>,
132
133        /// Threshold below which CoW images are guaranteed to be used and be
134        /// dense.
135        pub memory_guaranteed_dense_image_size: Option<u64>,
136
137        /// The maximum number of WebAssembly instances which can be created
138        /// with the pooling allocator.
139        pub pooling_total_core_instances: Option<u32>,
140
141        /// The maximum number of WebAssembly components which can be created
142        /// with the pooling allocator.
143        pub pooling_total_component_instances: Option<u32>,
144
145        /// The maximum number of WebAssembly memories which can be created with
146        /// the pooling allocator.
147        pub pooling_total_memories: Option<u32>,
148
149        /// The maximum number of WebAssembly tables which can be created with
150        /// the pooling allocator.
151        pub pooling_total_tables: Option<u32>,
152
153        /// The maximum number of WebAssembly stacks which can be created with
154        /// the pooling allocator.
155        pub pooling_total_stacks: Option<u32>,
156
157        /// The maximum runtime size of each linear memory in the pooling
158        /// allocator, in bytes.
159        pub pooling_max_memory_size: Option<usize>,
160
161        /// The maximum table elements for any table defined in a module when
162        /// using the pooling allocator.
163        pub pooling_table_elements: Option<usize>,
164
165        /// The maximum size, in bytes, allocated for a core instance's metadata
166        /// when using the pooling allocator.
167        pub pooling_max_core_instance_size: Option<usize>,
168
169        /// Configures the maximum number of "unused warm slots" to retain in the
170        /// pooling allocator. (default: 100)
171        pub pooling_max_unused_warm_slots: Option<u32>,
172
173        /// How much memory, in bytes, to keep resident for async stacks allocated
174        /// with the pooling allocator. (default: 0)
175        pub pooling_async_stack_keep_resident: Option<usize>,
176
177        /// The maximum size, in bytes, allocated for a component instance's
178        /// `VMComponentContext` metadata. (default: 1MiB)
179        pub pooling_max_component_instance_size: Option<usize>,
180
181        /// The maximum number of core instances a single component may contain
182        /// (default is unlimited).
183        pub pooling_max_core_instances_per_component: Option<u32>,
184
185        /// The maximum number of Wasm linear memories that a single component may
186        /// transitively contain (default is unlimited).
187        pub pooling_max_memories_per_component: Option<u32>,
188
189        /// The maximum number of tables that a single component may transitively
190        /// contain (default is unlimited).
191        pub pooling_max_tables_per_component: Option<u32>,
192
193        /// The maximum number of defined tables for a core module. (default: 1)
194        pub pooling_max_tables_per_module: Option<u32>,
195
196        /// The maximum number of defined linear memories for a module. (default: 1)
197        pub pooling_max_memories_per_module: Option<u32>,
198
199        /// The maximum number of concurrent GC heaps supported. (default: 1000)
200        pub pooling_total_gc_heaps: Option<u32>,
201
202        /// Enable or disable the use of host signal handlers for traps.
203        pub signals_based_traps: Option<bool>,
204
205        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
206        pub dynamic_memory_guard_size: Option<u64>,
207
208        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
209        pub static_memory_guard_size: Option<u64>,
210
211        /// DEPRECATED: Use `-Cmemory-may-move` instead.
212        pub static_memory_forced: Option<bool>,
213
214        /// DEPRECATED: Use `-Cmemory-reservation=N` instead.
215        pub static_memory_maximum_size: Option<u64>,
216
217        /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead.
218        pub dynamic_memory_reserved_for_growth: Option<u64>,
219
220        /// Whether or not `PAGEMAP_SCAN` ioctls are used to reset linear
221        /// memory.
222        #[serde(default)]
223        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
224        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
225        pub pooling_pagemap_scan: Option<wasmtime::Enabled>,
226
227        /// XXX: For internal fuzzing and debugging use only!
228        #[doc(hidden)]
229        pub gc_zeal_alloc_counter: Option<NonZeroU32>,
230    }
231
232    enum Optimize {
233        ...
234    }
235}
236
237wasmtime_option_group! {
238    #[env = "CODEGEN"]
239    pub struct CodegenOptions {
240        /// Either `cranelift` or `winch`.
241        ///
242        /// Currently only `cranelift` and `winch` are supported, but not all
243        /// builds of Wasmtime have both built in.
244        #[serde(default)]
245        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
246        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
247        pub compiler: Option<wasmtime::Strategy>,
248        /// Which garbage collector to use: `drc`, `null`, or `copying`.
249        ///
250        /// `drc` is the deferred reference-counting collector.
251        ///
252        /// `null` is the null garbage collector, which does not collect any
253        /// garbage.
254        ///
255        /// `copying` is the copying garbage collector (not yet implemented).
256        ///
257        /// Note that not all builds of Wasmtime will have support for garbage
258        /// collection included.
259        #[serde(default)]
260        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
261        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
262        pub collector: Option<wasmtime::Collector>,
263        /// Enable Cranelift's internal debug verifier (expensive)
264        pub cranelift_debug_verifier: Option<bool>,
265        /// Whether or not to enable caching of compiled modules.
266        pub cache: Option<bool>,
267        /// Configuration for compiled module caching.
268        pub cache_config: Option<String>,
269        /// Whether or not to enable parallel compilation of modules.
270        pub parallel_compilation: Option<bool>,
271        /// Controls whether native unwind information is present in compiled
272        /// object files.
273        pub native_unwind_info: Option<bool>,
274
275        /// Whether to perform function inlining during compilation.
276        #[serde(default)]
277        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
278        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
279        pub inlining: Option<wasmtime::Inlining>,
280
281        /// Whether or not trap metadata is present for wasm internal assertions
282        /// in compiled code.
283        pub metadata_for_internal_asserts: Option<bool>,
284        /// Whether or not trap metadata is present for detection of gc
285        /// corruption in compiled code.
286        pub metadata_for_gc_heap_corruption: Option<bool>,
287
288        /// Expose Wasmtime's unsafe intrinsics to the Wasm being compiled under
289        /// the given instance import name, which defaults to
290        /// `unsafe-intrinsics` when the name is omitted.
291        ///
292        /// The unsafe intrinsics are a set of raw, unchecked load and store
293        /// operations on the host's address space, along with the address of
294        /// the store's data. They may only be used with components, not core
295        /// Wasm modules.
296        ///
297        /// This is wildly unsafe: the Wasm is given the ability to read and
298        /// write arbitrary host memory. Only use this with Wasm that you trust
299        /// as much as you trust the CLI itself.
300        ///
301        /// When `-C compile-time-builtin` is also given, the intrinsics are
302        /// exposed only to the compile-time builtins and not to the main Wasm
303        /// program.
304        ///
305        /// See the API documentation for
306        /// `CodeBuilder::expose_unsafe_intrinsics` for more details.
307        #[serde(default)]
308        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
309        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
310        pub unsafe_intrinsics: Option<UnsafeIntrinsicsImport>,
311
312        /// Define a compile-time builtin: satisfy the `<name>` instance import
313        /// of the main component with the component at `<path>` at compile
314        /// time, rather than with a host-defined import at instantiation time.
315        ///
316        /// May be specified multiple times, once per builtin. Compile-time
317        /// builtins may only be used with components, not core Wasm modules,
318        /// and require `-C unsafe-intrinsics`.
319        ///
320        /// The `<name>=` prefix may be omitted, in which case `<name>` defaults
321        /// to the file name of `<path>` without its extension. For example
322        /// `-C compile-time-builtin=path/to/my-host-api.wat` satisfies the
323        /// `my-host-api` import. Note that a `<path>` which itself contains an
324        /// `=` is interpreted as the `<name>=<path>` form; pass the explicit
325        /// form to disambiguate.
326        ///
327        /// Compile-time builtins are part of your trusted compute base: they
328        /// are given access to the unsafe intrinsics described above. Calls
329        /// into them become direct calls, so pass `-C inlining=y` to let them
330        /// be inlined into their callers.
331        ///
332        /// See the API documentation for
333        /// `CodeBuilder::compile_time_builtin_binary` for more details.
334        #[serde(skip)]
335        pub compile_time_builtin: Vec<CompileTimeBuiltin>,
336
337        #[prefixed = "cranelift"]
338        #[serde(default)]
339        /// Set a cranelift-specific option. Use `wasmtime settings` to see
340        /// all.
341        pub cranelift: Vec<(String, Option<String>)>,
342    }
343
344    enum Codegen {
345        ...
346    }
347}
348
349wasmtime_option_group! {
350    #[env = "DEBUG"]
351    pub struct DebugOptions {
352        /// Enable generation of DWARF debug information in compiled code.
353        pub debug_info: Option<bool>,
354        /// Enable guest debugging insrumentation.
355        pub guest_debug: Option<bool>,
356        /// Configure whether compiled code can map native addresses to wasm.
357        pub address_map: Option<bool>,
358        /// Configure whether logging is enabled.
359        pub logging: Option<bool>,
360        /// Configure whether logs are emitted to files
361        pub log_to_files: Option<bool>,
362        /// Enable coredump generation to this file after a WebAssembly trap.
363        pub coredump: Option<String>,
364        /// Load the given debugger component and attach it to the
365        /// main module or component.
366        pub debugger: Option<PathBuf>,
367        /// Pass the given command-line arguments to the debugger
368        /// component. May be specified multiple times.
369        #[serde(default)]
370        pub arg: Vec<String>,
371        /// Allow the debugger component to inherit stdin.Off by
372        /// default.
373        pub inherit_stdin: Option<bool>,
374        /// Allow the debugger component to inherit stdout. Off by
375        /// default.
376        pub inherit_stdout: Option<bool>,
377        /// Allow the debugger component to inherit stderr. Off by
378        /// default.
379        pub inherit_stderr: Option<bool>,
380        /// Maximum number of frames to capture in backtraces.
381        pub max_backtrace: Option<usize>,
382        /// Whether or not `*.cwasm` files have symbols in them.
383        pub symbols: Option<bool>,
384    }
385
386    enum Debug {
387        ...
388    }
389}
390
391wasmtime_option_group! {
392    #[env = "WASM"]
393    pub struct WasmOptions {
394        /// Enable canonicalization of all NaN values.
395        pub nan_canonicalization: Option<bool>,
396        /// Enable execution fuel with N units fuel, trapping after running out
397        /// of fuel.
398        ///
399        /// Most WebAssembly instructions consume 1 unit of fuel. Some
400        /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
401        /// units, as any execution cost associated with them involves other
402        /// instructions which do consume fuel.
403        pub fuel: Option<u64>,
404        /// Yield when a global epoch counter changes, allowing for async
405        /// operation without blocking the executor.
406        pub epoch_interruption: Option<bool>,
407        /// Maximum stack size, in bytes, that wasm is allowed to consume before a
408        /// stack overflow is reported.
409        pub max_wasm_stack: Option<usize>,
410        /// Stack size, in bytes, that will be allocated for async stacks.
411        ///
412        /// Note that this must be larger than `max-wasm-stack` and the
413        /// difference between the two is how much stack the host has to execute
414        /// on.
415        pub async_stack_size: Option<usize>,
416        /// Configures whether or not stacks used for async futures are zeroed
417        /// before (re)use as a defense-in-depth mechanism. (default: false)
418        pub async_stack_zeroing: Option<bool>,
419        /// Allow unknown exports when running commands.
420        pub unknown_exports_allow: Option<bool>,
421        /// Allow the main module to import unknown functions, using an
422        /// implementation that immediately traps, when running commands.
423        pub unknown_imports_trap: Option<bool>,
424        /// Allow the main module to import unknown functions, using an
425        /// implementation that returns default values, when running commands.
426        pub unknown_imports_default: Option<bool>,
427        /// Enables memory error checking. (see wmemcheck.md for more info)
428        pub wmemcheck: Option<bool>,
429        /// Maximum size, in bytes, that a linear memory is allowed to reach.
430        ///
431        /// Growth beyond this limit will cause `memory.grow` instructions in
432        /// WebAssembly modules to return -1 and fail.
433        pub max_memory_size: Option<usize>,
434        /// Maximum size, in table elements, that a table is allowed to reach.
435        pub max_table_elements: Option<usize>,
436        /// Maximum number of WebAssembly instances allowed to be created.
437        pub max_instances: Option<usize>,
438        /// Maximum number of WebAssembly tables allowed to be created.
439        pub max_tables: Option<usize>,
440        /// Maximum number of WebAssembly linear memories allowed to be created.
441        pub max_memories: Option<usize>,
442        /// Force a trap to be raised on `memory.grow` and `table.grow` failure
443        /// instead of returning -1 from these instructions.
444        ///
445        /// This is not necessarily a spec-compliant option to enable but can be
446        /// useful for tracking down a backtrace of what is requesting so much
447        /// memory, for example.
448        pub trap_on_grow_failure: Option<bool>,
449        /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc).
450        ///
451        /// Note that when this option is not set, malicious wasm code may
452        /// cause the host process to become unresponsive to inputs including
453        /// SIGTERM.
454        pub timeout: Option<Duration>,
455        /// Configures support for all WebAssembly proposals implemented.
456        pub all_proposals: Option<bool>,
457        /// Configure support for the bulk memory proposal.
458        pub bulk_memory: Option<bool>,
459        /// Configure support for the multi-memory proposal.
460        pub multi_memory: Option<bool>,
461        /// Configure support for the multi-value proposal.
462        pub multi_value: Option<bool>,
463        /// Configure support for the reference-types proposal.
464        pub reference_types: Option<bool>,
465        /// Configure support for the simd proposal.
466        pub simd: Option<bool>,
467        /// Configure support for the relaxed-simd proposal.
468        pub relaxed_simd: Option<bool>,
469        /// Configure forcing deterministic and host-independent behavior of
470        /// the relaxed-simd instructions.
471        ///
472        /// By default these instructions may have architecture-specific behavior as
473        /// allowed by the specification, but this can be used to force the behavior
474        /// of these instructions to match the deterministic behavior classified in
475        /// the specification. Note that enabling this option may come at a
476        /// performance cost.
477        pub relaxed_simd_deterministic: Option<bool>,
478        /// Configure support for the tail-call proposal.
479        pub tail_call: Option<bool>,
480        /// Configure support for the threads proposal.
481        pub threads: Option<bool>,
482        /// Configure the ability to create a `shared` memory.
483        pub shared_memory: Option<bool>,
484        /// Configure support for the shared-everything-threads proposal.
485        pub shared_everything_threads: Option<bool>,
486        /// Configure support for the memory64 proposal.
487        pub memory64: Option<bool>,
488        /// Configure support for the component-model proposal.
489        pub component_model: Option<bool>,
490        /// Component model support for async lifting/lowering.
491        pub component_model_async: Option<bool>,
492        /// Component model support for async lifting/lowering: this corresponds
493        /// to the 🚝 emoji in the component model specification.
494        pub component_model_more_async_builtins: Option<bool>,
495        /// Component model support for async lifting/lowering: this corresponds
496        /// to the 🚟 emoji in the component model specification.
497        pub component_model_async_stackful: Option<bool>,
498        /// Component model support for threading: this corresponds
499        /// to the 🧡 emoji in the component model specification.
500        pub component_model_threading: Option<bool>,
501        /// Component model support for `error-context`: this corresponds
502        /// to the πŸ“ emoji in the component model specification.
503        pub component_model_error_context: Option<bool>,
504        /// GC support in the component model: this corresponds to the πŸ›Έ emoji
505        /// in the component model specification.
506        pub component_model_gc: Option<bool>,
507        /// Map support in the component model: this corresponds to the πŸ—ΊοΈ
508        /// emoji in the component model specification.
509        pub component_model_map: Option<bool>,
510        /// Component model support for `memory64`: this corresponds
511        /// to the 🐘 emoji in the component model specification.
512        pub component_model_memory64: Option<bool>,
513        /// Configure support for the function-references proposal.
514        pub function_references: Option<bool>,
515        /// Configure support for the stack-switching proposal.
516        pub stack_switching: Option<bool>,
517        /// Configure support for the GC proposal.
518        pub gc: Option<bool>,
519        /// Configure support for the custom-page-sizes proposal.
520        pub custom_page_sizes: Option<bool>,
521        /// Configure support for the wide-arithmetic proposal.
522        pub wide_arithmetic: Option<bool>,
523        /// Configure support for the branch-hinting proposal.
524        pub branch_hinting: Option<bool>,
525        /// Configure support for compact imports.
526        pub compact_imports: Option<bool>,
527        /// Configure support for the extended-const proposal.
528        pub extended_const: Option<bool>,
529        /// Configure support for the exceptions proposal.
530        pub exceptions: Option<bool>,
531        /// Whether or not any GC infrastructure in Wasmtime is enabled or not.
532        pub gc_support: Option<bool>,
533        /// Component model support for fixed-length lists: this corresponds
534        /// to the πŸ”§ emoji in the component model specification
535        pub component_model_fixed_length_lists: Option<bool>,
536        /// Component model support for `(implements ...)` and
537        /// `(external-id ...)`, corresponds to the 🏷️ emoji in the upstream
538        /// spec.
539        pub component_model_implements: Option<bool>,
540        /// Component model support for canonical names, corresponds to the
541        /// πŸ”— emoji in the upstream spec.
542        pub component_model_canonical_names: Option<bool>,
543        /// Component model support for `[get]` and `[set]` accessors,
544        /// corresponds to the πŸ“‘ emoji in the upstream spec.
545        pub component_model_accessors: Option<bool>,
546        /// Whether or not any concurrency infrastructure in Wasmtime is
547        /// enabled or not.
548        pub concurrency_support: Option<bool>,
549    }
550
551    enum Wasm {
552        ...
553    }
554}
555
556wasmtime_option_group! {
557    #[env = "WASI"]
558    pub struct WasiOptions {
559        /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random.
560        pub cli: Option<bool>,
561        /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code)
562        pub cli_exit_with_code: Option<bool>,
563        /// Deprecated alias for `cli`
564        pub common: Option<bool>,
565        /// Enable support for WASI neural network imports (experimental)
566        pub nn: Option<bool>,
567        /// Enable support for WASI threading imports (experimental). Implies preview2=false.
568        pub threads: Option<bool>,
569        /// Enable support for WASI HTTP imports
570        pub http: Option<bool>,
571        /// Number of distinct write calls to the outgoing body's output-stream
572        /// that the implementation will buffer.
573        /// Default: 1.
574        pub http_outgoing_body_buffer_chunks: Option<NonZeroUsize>,
575        /// Maximum size allowed in a write call to the outgoing body's output-stream.
576        /// Default: 1024 * 1024.
577        pub http_outgoing_body_chunk_size: Option<NonZeroUsize>,
578        /// Enable support for WASI config imports (experimental)
579        pub config: Option<bool>,
580        /// Enable support for WASI key-value imports (experimental)
581        pub keyvalue: Option<bool>,
582        /// Grant access to the given TCP listen socket (experimental, legacy
583        /// wasip1 implementation only)
584        #[serde(default)]
585        pub tcplisten: Vec<String>,
586        /// Enable support for WASI TLS (Transport Layer Security) imports (experimental)
587        pub tls: Option<bool>,
588        /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy
589        /// implementation (false)
590        pub preview2: Option<bool>,
591        /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn.
592        ///
593        /// Each use of the flag will preload a ML model from the host directory
594        /// using the given model encoding. The model will be mapped to the
595        /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload
596        /// an OpenVINO model named `bar`. Note that which model encodings are
597        /// available is dependent on the backends implemented in the
598        /// `wasmtime_wasi_nn` crate.
599        #[serde(skip)]
600        pub nn_graph: Vec<WasiNnGraph>,
601        /// Flag for WASI preview2 to inherit the host's network within the
602        /// guest so it has full access to all addresses/ports/etc.
603        pub inherit_network: Option<bool>,
604        /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not.
605        pub allow_ip_name_lookup: Option<bool>,
606        /// Indicates whether `wasi:sockets` TCP support is enabled or not.
607        pub tcp: Option<bool>,
608        /// Indicates whether `wasi:sockets` UDP support is enabled or not.
609        pub udp: Option<bool>,
610        /// Enable WASI APIs marked as: @unstable(feature = network-error-code)
611        pub network_error_code: Option<bool>,
612        /// Allows imports from the `wasi_unstable` core wasm module. Disabled by default.
613        pub preview0: Option<bool>,
614        /// Inherit all environment variables from the parent process.
615        ///
616        /// This option can be further overwritten with `--env` flags.
617        pub inherit_env: Option<bool>,
618        /// Inherit stdin from the parent process. On by default.
619        pub inherit_stdin: Option<bool>,
620        /// Inherit stdout from the parent process. On by default.
621        pub inherit_stdout: Option<bool>,
622        /// Inherit stderr from the parent process. On by default.
623        pub inherit_stderr: Option<bool>,
624        /// Initial current working directory reported through `wasi:cli/environment`.
625        pub cwd: Option<String>,
626        /// Pass a wasi config variable to the program.
627        #[serde(skip)]
628        pub config_var: Vec<KeyValuePair>,
629        /// Preset data for the In-Memory provider of WASI key-value API.
630        #[serde(skip)]
631        pub keyvalue_in_memory_data: Vec<KeyValuePair>,
632        /// Enable support for WASIp3 APIs.
633        pub p3: Option<bool>,
634        /// Maximum resources the guest is allowed to create simultaneously.
635        pub max_resources: Option<usize>,
636        /// Fuel to use for all hostcalls to limit guest<->host data transfer.
637        pub hostcall_fuel: Option<usize>,
638        /// Maximum number of component-model handle-table slots (e.g. for
639        /// resources, streams, futures) per store; allocating past it traps.
640        /// (default: 100000)
641        pub max_component_handles: Option<usize>,
642        /// Maximum number of simultaneously-live fibers per store.
643        pub max_fibers: Option<u32>,
644        /// Maximum value, in bytes, for a wasi-random 0.2
645        /// `get{,-insecure}-random-bytes` `len` parameter. Calls with a value
646        /// exceeding this limit will trap.
647        pub max_random_size: Option<u64>,
648        /// Maximum value, in bytes, for the contents of a wasi-http 0.2
649        /// `fields` resource (aka `headers` and `trailers`). `fields` methods
650        /// which cause the contents to exceed this size limit will trap.
651        pub max_http_fields_size: Option<usize>,
652    }
653
654    enum Wasi {
655        ...
656    }
657}
658
659wasmtime_option_group! {
660    #[env = "RECORD"]
661    pub struct RecordOptions {
662        /// Filename for the recorded execution trace (or empty string to skip writing a file).
663        pub path: Option<String>,
664        /// Include (optional) signatures to facilitate validation checks during replay
665        /// (see `wasmtime replay` for details).
666        pub validation_metadata: Option<bool>,
667        /// Window size of internal buffering for record events (large windows offer more opportunities
668        /// for coalescing events at the cost of memory usage).
669        pub event_window_size: Option<usize>,
670    }
671
672    enum Record {
673        ...
674    }
675}
676
677#[derive(Debug, Clone, PartialEq)]
678pub struct WasiNnGraph {
679    pub format: String,
680    pub dir: String,
681}
682
683#[derive(Debug, Clone, PartialEq)]
684pub struct KeyValuePair {
685    pub key: String,
686    pub value: String,
687}
688
689/// The instance import name under which Wasmtime's unsafe intrinsics are
690/// exposed to the Wasm being compiled.
691#[derive(Debug, Clone, PartialEq)]
692pub struct UnsafeIntrinsicsImport(pub String);
693
694/// A compile-time builtin.
695#[derive(Debug, Clone, PartialEq)]
696pub struct CompileTimeBuiltin {
697    /// The instance import name that this satisfies in the main component.
698    pub name: String,
699    /// The path to the component that implements this builtin.
700    pub path: PathBuf,
701}
702
703/// Common options for commands that translate WebAssembly modules
704#[derive(Clone)]
705#[cfg_attr(feature = "clap", derive(clap::Parser))]
706#[cfg_attr(
707    feature = "serde",
708    derive(serde_derive::Deserialize, serde_derive::Serialize)
709)]
710#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
711pub struct CommonOptions {
712    // These options groups are used to parse `-O` and such options but aren't
713    // the raw form consumed by the CLI. Instead they're pushed into the `pub`
714    // fields below as part of the `configure` method.
715    //
716    // Ideally clap would support `pub opts: OptimizeOptions` and parse directly
717    // into that but it does not appear to do so for multiple `-O` flags for
718    // now.
719    /// Optimization and tuning related options for wasm performance, `-O help` to
720    /// see all.
721    #[cfg_attr(
722        feature = "clap",
723        arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")
724    )]
725    #[cfg_attr(feature = "serde", serde(skip))]
726    opts_raw: Vec<opt::CommaSeparated<Optimize>>,
727
728    /// Codegen-related configuration options, `-C help` to see all.
729    #[cfg_attr(
730        feature = "clap",
731        arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")
732    )]
733    #[cfg_attr(feature = "serde", serde(skip))]
734    codegen_raw: Vec<opt::CommaSeparated<Codegen>>,
735
736    /// Debug-related configuration options, `-D help` to see all.
737    #[cfg_attr(
738        feature = "clap",
739        arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")
740    )]
741    #[cfg_attr(feature = "serde", serde(skip))]
742    debug_raw: Vec<opt::CommaSeparated<Debug>>,
743
744    /// Options for configuring semantic execution of WebAssembly, `-W help` to see
745    /// all.
746    #[cfg_attr(
747        feature = "clap",
748        arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")
749    )]
750    #[cfg_attr(feature = "serde", serde(skip))]
751    wasm_raw: Vec<opt::CommaSeparated<Wasm>>,
752
753    /// Options for configuring WASI and its proposals, `-S help` to see all.
754    #[cfg_attr(
755        feature = "clap",
756        arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")
757    )]
758    #[cfg_attr(feature = "serde", serde(skip))]
759    wasi_raw: Vec<opt::CommaSeparated<Wasi>>,
760
761    /// Options to enable and configure execution recording, `-R help` to see all.
762    ///
763    /// Generates a serialized trace of the Wasm module execution that captures all
764    /// non-determinism observable by the module. This trace can subsequently be
765    /// re-executed in a deterministic, embedding-agnostic manner (see the `wasmtime replay` command).
766    ///
767    /// Note: Minimal configuration options for deterministic Wasm semantics will be
768    /// enforced during recording by default (NaN canonicalization, deterministic relaxed SIMD).
769    #[cfg_attr(
770        feature = "clap",
771        arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")
772    )]
773    #[cfg_attr(feature = "serde", serde(skip))]
774    record_raw: Vec<opt::CommaSeparated<Record>>,
775
776    // These fields are filled in by the `configure` method below via the
777    // options parsed from the CLI above. This is what the CLI should use.
778    #[cfg_attr(feature = "clap", arg(skip))]
779    #[cfg_attr(feature = "serde", serde(skip))]
780    configured: bool,
781
782    #[cfg_attr(feature = "clap", arg(skip))]
783    #[cfg_attr(feature = "serde", serde(rename = "optimize", default))]
784    pub opts: OptimizeOptions,
785
786    #[cfg_attr(feature = "clap", arg(skip))]
787    #[cfg_attr(feature = "serde", serde(default))]
788    pub codegen: CodegenOptions,
789
790    #[cfg_attr(feature = "clap", arg(skip))]
791    #[cfg_attr(feature = "serde", serde(default))]
792    pub debug: DebugOptions,
793
794    #[cfg_attr(feature = "clap", arg(skip))]
795    #[cfg_attr(feature = "serde", serde(default))]
796    pub wasm: WasmOptions,
797
798    #[cfg_attr(feature = "clap", arg(skip))]
799    #[cfg_attr(feature = "serde", serde(default))]
800    pub wasi: WasiOptions,
801
802    #[cfg_attr(feature = "clap", arg(skip))]
803    #[cfg_attr(feature = "serde", serde(default))]
804    pub record: RecordOptions,
805
806    /// The target triple; default is the host triple
807    #[cfg_attr(feature = "clap", arg(long, value_name = "TARGET"))]
808    #[cfg_attr(feature = "serde", serde(skip))]
809    pub target: Option<String>,
810
811    /// Use the specified TOML configuration file.
812    /// This TOML configuration file can provide same configuration options as the
813    /// `--optimize`, `--codegen`, `--debug`, `--wasm`, `--wasi` CLI options, with a couple exceptions.
814    ///
815    /// Additional options specified on the command line will take precedent over options loaded from
816    /// this TOML file.
817    #[cfg_attr(feature = "clap", arg(long = "config", value_name = "FILE"))]
818    #[cfg_attr(feature = "serde", serde(skip))]
819    pub config: Option<PathBuf>,
820}
821
822macro_rules! match_feature {
823    (
824        [$feat:tt : $config:expr]
825        $val:ident => $e:expr,
826        $p:pat => err,
827    ) => {
828        #[cfg(feature = $feat)]
829        {
830            if let Some($val) = $config {
831                $e;
832            }
833        }
834        #[cfg(not(feature = $feat))]
835        {
836            if let Some($p) = $config {
837                bail!(concat!("support for ", $feat, " disabled at compile time"));
838            }
839        }
840    };
841}
842
843impl CommonOptions {
844    /// Creates a blank new set of [`CommonOptions`] that can be configured.
845    pub fn new() -> CommonOptions {
846        CommonOptions {
847            opts_raw: Vec::new(),
848            codegen_raw: Vec::new(),
849            debug_raw: Vec::new(),
850            wasm_raw: Vec::new(),
851            wasi_raw: Vec::new(),
852            record_raw: Vec::new(),
853            configured: true,
854            opts: Default::default(),
855            codegen: Default::default(),
856            debug: Default::default(),
857            wasm: Default::default(),
858            wasi: Default::default(),
859            record: Default::default(),
860            target: None,
861            config: None,
862        }
863    }
864
865    fn configure(&mut self) -> Result<()> {
866        if self.configured {
867            return Ok(());
868        }
869        self.configured = true;
870        if let Some(toml_config_path) = &self.config {
871            #[cfg(feature = "toml")]
872            {
873                let toml_options = CommonOptions::from_file(toml_config_path)?;
874                self.opts = toml_options.opts;
875                self.codegen = toml_options.codegen;
876                self.debug = toml_options.debug;
877                self.wasm = toml_options.wasm;
878                self.wasi = toml_options.wasi;
879                self.record = toml_options.record;
880            }
881            #[cfg(not(feature = "toml"))]
882            {
883                bail!(
884                    "support for loading a configuration file from \
885                     {toml_config_path:?} disabled at compile time"
886                );
887            }
888        }
889        self.opts.configure_with(&self.opts_raw)?;
890        self.codegen.configure_with(&self.codegen_raw)?;
891        self.debug.configure_with(&self.debug_raw)?;
892        self.wasm.configure_with(&self.wasm_raw)?;
893        self.wasi.configure_with(&self.wasi_raw)?;
894        self.record.configure_with(&self.record_raw)?;
895        Ok(())
896    }
897
898    pub fn init_logging(&mut self) -> Result<()> {
899        self.configure()?;
900        if self.debug.logging == Some(false) {
901            return Ok(());
902        }
903        #[cfg(feature = "logging")]
904        if self.debug.log_to_files == Some(true) {
905            let prefix = "wasmtime.dbg.";
906            init_file_per_thread_logger(prefix);
907        } else {
908            use std::io::IsTerminal;
909            use tracing_subscriber::{EnvFilter, FmtSubscriber};
910            let builder = FmtSubscriber::builder()
911                .with_writer(std::io::stderr)
912                .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
913                .with_ansi(std::io::stderr().is_terminal());
914            if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
915                builder
916                    .with_level(false)
917                    .with_target(false)
918                    .without_time()
919                    .init()
920            } else {
921                builder.init();
922            }
923        }
924        #[cfg(not(feature = "logging"))]
925        if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
926            bail!("support for logging disabled at compile time");
927        }
928        Ok(())
929    }
930
931    pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
932        self.configure()?;
933        let mut config = Config::new();
934
935        match_feature! {
936            ["cranelift" : self.codegen.compiler]
937            strategy => config.strategy(strategy),
938            _ => err,
939        }
940        match_feature! {
941            ["gc" : self.codegen.collector]
942            collector => config.collector(collector),
943            _ => err,
944        }
945        if let Some(target) = &self.target {
946            config.target(target)?;
947        }
948        match_feature! {
949            ["cranelift" : self.codegen.cranelift_debug_verifier]
950            enable => config.cranelift_debug_verifier(enable),
951            true => err,
952        }
953        if let Some(enable) = self.debug.debug_info {
954            config.debug_info(enable);
955        }
956        match_feature! {
957            ["debug" : self.debug.guest_debug]
958            enable => config.guest_debug(enable),
959            _ => err,
960        }
961        if self.debug.coredump.is_some() {
962            #[cfg(feature = "coredump")]
963            config.coredump_on_trap(true);
964            #[cfg(not(feature = "coredump"))]
965            bail!("support for coredumps disabled at compile time");
966        }
967        match_feature! {
968            ["cranelift" : self.opts.opt_level]
969            level => config.cranelift_opt_level(level),
970            _ => err,
971        }
972        match_feature! {
973            ["cranelift": self.opts.regalloc_algorithm]
974            algo => config.cranelift_regalloc_algorithm(algo),
975            _ => err,
976        }
977        match_feature! {
978            ["cranelift" : self.wasm.nan_canonicalization]
979            enable => config.cranelift_nan_canonicalization(enable),
980            true => err,
981        }
982
983        self.enable_wasm_features(&mut config)?;
984
985        #[cfg(feature = "cranelift")]
986        for (name, value) in self.codegen.cranelift.iter() {
987            let name = name.replace('-', "_");
988            unsafe {
989                match value {
990                    Some(val) => {
991                        config.cranelift_flag_set(&name, val);
992                    }
993                    None => {
994                        config.cranelift_flag_enable(&name);
995                    }
996                }
997            }
998        }
999        #[cfg(not(feature = "cranelift"))]
1000        if !self.codegen.cranelift.is_empty() {
1001            bail!("support for cranelift disabled at compile time");
1002        }
1003
1004        #[cfg(feature = "cache")]
1005        if self.codegen.cache != Some(false) {
1006            use wasmtime::Cache;
1007            let cache = match &self.codegen.cache_config {
1008                Some(path) => Cache::from_file(Some(std::path::Path::new(path)))?,
1009                None => Cache::from_file(None)?,
1010            };
1011            config.cache(Some(cache));
1012        }
1013        #[cfg(not(feature = "cache"))]
1014        if self.codegen.cache == Some(true) {
1015            bail!("support for caching disabled at compile time");
1016        }
1017
1018        match_feature! {
1019            ["parallel-compilation" : self.codegen.parallel_compilation]
1020            enable => config.parallel_compilation(enable),
1021            true => err,
1022        }
1023
1024        let memory_reservation = self
1025            .opts
1026            .memory_reservation
1027            .or(self.opts.static_memory_maximum_size);
1028        if let Some(size) = memory_reservation {
1029            config.memory_reservation(size);
1030        }
1031
1032        if let Some(enable) = self.opts.static_memory_forced {
1033            config.memory_may_move(!enable);
1034        }
1035        if let Some(enable) = self.opts.memory_may_move {
1036            config.memory_may_move(enable);
1037        }
1038
1039        let memory_guard_size = self
1040            .opts
1041            .static_memory_guard_size
1042            .or(self.opts.dynamic_memory_guard_size)
1043            .or(self.opts.memory_guard_size);
1044        if let Some(size) = memory_guard_size {
1045            config.memory_guard_size(size);
1046        }
1047
1048        let mem_for_growth = self
1049            .opts
1050            .memory_reservation_for_growth
1051            .or(self.opts.dynamic_memory_reserved_for_growth);
1052        if let Some(size) = mem_for_growth {
1053            config.memory_reservation_for_growth(size);
1054        }
1055        if let Some(enable) = self.opts.guard_before_linear_memory {
1056            config.guard_before_linear_memory(enable);
1057        }
1058
1059        if let Some(size) = self.opts.gc_heap_reservation {
1060            config.gc_heap_reservation(size);
1061        }
1062        if let Some(enable) = self.opts.gc_heap_may_move {
1063            config.gc_heap_may_move(enable);
1064        }
1065        if let Some(size) = self.opts.gc_heap_guard_size {
1066            config.gc_heap_guard_size(size);
1067        }
1068        if let Some(size) = self.opts.gc_heap_reservation_for_growth {
1069            config.gc_heap_reservation_for_growth(size);
1070        }
1071
1072        if let Some(size) = self.opts.gc_heap_initial_size {
1073            config.gc_heap_initial_size(size);
1074        }
1075
1076        if let Some(enable) = self.opts.table_lazy_init {
1077            config.table_lazy_init(enable);
1078        }
1079
1080        if let Some(n) = self.opts.gc_zeal_alloc_counter
1081            && (cfg!(gc_zeal) || cfg!(fuzzing))
1082        {
1083            config.gc_zeal_alloc_counter(Some(n))?;
1084        }
1085
1086        // If fuel has been configured, set the `consume fuel` flag on the config.
1087        if self.wasm.fuel.is_some() {
1088            config.consume_fuel(true);
1089        }
1090
1091        if let Some(enable) = self.wasm.epoch_interruption {
1092            config.epoch_interruption(enable);
1093        }
1094        if let Some(enable) = self.debug.address_map {
1095            config.generate_address_map(enable);
1096        }
1097        if let Some(frames) = self.debug.max_backtrace {
1098            match NonZeroUsize::new(frames) {
1099                None => {
1100                    config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
1101                }
1102                Some(amt) => {
1103                    config.wasm_backtrace_max_frames(Some(amt));
1104                }
1105            }
1106        }
1107        if let Some(enable) = self.debug.symbols {
1108            config.debug_symbols(enable);
1109        }
1110        if let Some(enable) = self.opts.memory_init_cow {
1111            config.memory_init_cow(enable);
1112        }
1113        if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
1114            config.memory_guaranteed_dense_image_size(size);
1115        }
1116        if let Some(enable) = self.opts.signals_based_traps {
1117            config.signals_based_traps(enable);
1118        }
1119        if let Some(enable) = self.codegen.native_unwind_info {
1120            config.native_unwind_info(enable);
1121        }
1122        if let Some(enable) = self.codegen.inlining {
1123            config.compiler_inlining(enable);
1124        }
1125        if let Some(enable) = self.codegen.metadata_for_internal_asserts {
1126            config.metadata_for_internal_asserts(enable);
1127        }
1128        if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
1129            config.metadata_for_gc_heap_corruption(enable);
1130        }
1131
1132        // async_stack_size enabled by either async or stack-switching, so
1133        // cannot directly use match_feature!
1134        #[cfg(any(feature = "async", feature = "stack-switching"))]
1135        {
1136            if let Some(size) = self.wasm.async_stack_size {
1137                config.async_stack_size(size);
1138            }
1139        }
1140        #[cfg(not(any(feature = "async", feature = "stack-switching")))]
1141        {
1142            if let Some(_size) = self.wasm.async_stack_size {
1143                bail!(concat!(
1144                    "support for async/stack-switching disabled at compile time"
1145                ));
1146            }
1147        }
1148
1149        match_feature! {
1150            ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
1151            enable => {
1152                if enable {
1153                    let mut cfg = wasmtime::PoolingAllocationConfig::default();
1154                    if let Some(size) = self.opts.pooling_memory_keep_resident {
1155                        cfg.linear_memory_keep_resident(size);
1156                    }
1157                    if let Some(size) = self.opts.pooling_table_keep_resident {
1158                        cfg.table_keep_resident(size);
1159                    }
1160                    if let Some(limit) = self.opts.pooling_total_core_instances {
1161                        cfg.total_core_instances(limit);
1162                    }
1163                    if let Some(limit) = self.opts.pooling_total_component_instances {
1164                        cfg.total_component_instances(limit);
1165                    }
1166                    if let Some(limit) = self.opts.pooling_total_memories {
1167                        cfg.total_memories(limit);
1168                    }
1169                    if let Some(limit) = self.opts.pooling_total_tables {
1170                        cfg.total_tables(limit);
1171                    }
1172                    if let Some(limit) = self.opts.pooling_table_elements
1173                        .or(self.wasm.max_table_elements)
1174                    {
1175                        cfg.table_elements(limit);
1176                    }
1177                    if let Some(limit) = self.opts.pooling_max_core_instance_size {
1178                        cfg.max_core_instance_size(limit);
1179                    }
1180                    match_feature! {
1181                        ["async" : self.opts.pooling_total_stacks]
1182                        limit => cfg.total_stacks(limit),
1183                        _ => err,
1184                    }
1185                    if let Some(max) = self.opts.pooling_max_memory_size
1186                        .or(self.wasm.max_memory_size)
1187                    {
1188                        cfg.max_memory_size(max);
1189                    }
1190                    if let Some(size) = self.opts.pooling_decommit_batch_size {
1191                        cfg.decommit_batch_size(size);
1192                    }
1193                    if let Some(max) = self.opts.pooling_max_unused_warm_slots {
1194                        cfg.max_unused_warm_slots(max);
1195                    }
1196                    match_feature! {
1197                        ["async" : self.opts.pooling_async_stack_keep_resident]
1198                        size => cfg.async_stack_keep_resident(size),
1199                        _ => err,
1200                    }
1201                    if let Some(max) = self.opts.pooling_max_component_instance_size {
1202                        cfg.max_component_instance_size(max);
1203                    }
1204                    if let Some(max) = self.opts.pooling_max_core_instances_per_component {
1205                        cfg.max_core_instances_per_component(max);
1206                    }
1207                    if let Some(max) = self.opts.pooling_max_memories_per_component {
1208                        cfg.max_memories_per_component(max);
1209                    }
1210                    if let Some(max) = self.opts.pooling_max_tables_per_component {
1211                        cfg.max_tables_per_component(max);
1212                    }
1213                    if let Some(max) = self.opts.pooling_max_tables_per_module {
1214                        cfg.max_tables_per_module(max);
1215                    }
1216                    if let Some(max) = self.opts.pooling_max_memories_per_module {
1217                        cfg.max_memories_per_module(max);
1218                    }
1219                    match_feature! {
1220                        ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
1221                        enable => cfg.memory_protection_keys(enable),
1222                        _ => err,
1223                    }
1224                    match_feature! {
1225                        ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
1226                        max => cfg.max_memory_protection_keys(max),
1227                        _ => err,
1228                    }
1229                    match_feature! {
1230                        ["gc" : self.opts.pooling_total_gc_heaps]
1231                        max => cfg.total_gc_heaps(max),
1232                        _ => err,
1233                    }
1234                    if let Some(enabled) = self.opts.pooling_pagemap_scan {
1235                        cfg.pagemap_scan(enabled);
1236                    }
1237                    config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
1238                }
1239            },
1240            true => err,
1241        }
1242
1243        if self.opts.pooling_memory_protection_keys.is_some()
1244            && !self.opts.pooling_allocator.unwrap_or(false)
1245        {
1246            bail!("memory protection keys require the pooling allocator");
1247        }
1248
1249        if self.opts.pooling_max_memory_protection_keys.is_some()
1250            && !self.opts.pooling_memory_protection_keys.is_some()
1251        {
1252            bail!("max memory protection keys requires memory protection keys to be enabled");
1253        }
1254
1255        match_feature! {
1256            ["async" : self.wasm.async_stack_zeroing]
1257            enable => config.async_stack_zeroing(enable),
1258            _ => err,
1259        }
1260
1261        if let Some(max) = self.wasm.max_wasm_stack {
1262            config.max_wasm_stack(max);
1263
1264            // If `-Wasync-stack-size` isn't passed then automatically adjust it
1265            // to the wasm stack size provided here too. That prevents the need
1266            // to pass both when one can generally be inferred from the other.
1267            #[cfg(any(feature = "async", feature = "stack-switching"))]
1268            if self.wasm.async_stack_size.is_none() {
1269                const DEFAULT_HOST_STACK: usize = 512 << 10;
1270                config.async_stack_size(max.saturating_add(DEFAULT_HOST_STACK));
1271            }
1272        }
1273
1274        if let Some(enable) = self.wasm.relaxed_simd_deterministic {
1275            config.relaxed_simd_deterministic(enable);
1276        }
1277        match_feature! {
1278            ["cranelift" : self.wasm.wmemcheck]
1279            enable => config.wmemcheck(enable),
1280            true => err,
1281        }
1282
1283        if let Some(enable) = self.wasm.gc_support {
1284            config.gc_support(enable);
1285        }
1286
1287        if let Some(enable) = self.wasm.concurrency_support {
1288            config.concurrency_support(enable);
1289        }
1290
1291        if let Some(enable) = self.wasm.shared_memory {
1292            config.shared_memory(enable);
1293        }
1294
1295        let record = &self.record;
1296        match_feature! {
1297            ["rr" : &record.path]
1298            _path => {
1299                bail!("recording configuration for `rr` feature is not supported yet");
1300            },
1301            _ => err,
1302        }
1303
1304        Ok(config)
1305    }
1306
1307    pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
1308        let all = self.wasm.all_proposals;
1309
1310        if let Some(enable) = self.wasm.simd.or(all) {
1311            config.wasm_simd(enable);
1312        }
1313        if let Some(enable) = self.wasm.relaxed_simd.or(all) {
1314            config.wasm_relaxed_simd(enable);
1315        }
1316        if let Some(enable) = self.wasm.bulk_memory.or(all) {
1317            config.wasm_bulk_memory(enable);
1318        }
1319        if let Some(enable) = self.wasm.multi_value.or(all) {
1320            config.wasm_multi_value(enable);
1321        }
1322        if let Some(enable) = self.wasm.tail_call.or(all) {
1323            config.wasm_tail_call(enable);
1324        }
1325        if let Some(enable) = self.wasm.multi_memory.or(all) {
1326            config.wasm_multi_memory(enable);
1327        }
1328        if let Some(enable) = self.wasm.memory64.or(all) {
1329            config.wasm_memory64(enable);
1330        }
1331        if let Some(enable) = self.wasm.stack_switching {
1332            config.wasm_stack_switching(enable);
1333        }
1334        if let Some(enable) = self.wasm.custom_page_sizes.or(all) {
1335            config.wasm_custom_page_sizes(enable);
1336        }
1337        if let Some(enable) = self.wasm.wide_arithmetic.or(all) {
1338            config.wasm_wide_arithmetic(enable);
1339        }
1340        // Not included in `all_proposals`: off by default until fuzzed.
1341        if let Some(enable) = self.wasm.branch_hinting {
1342            config.wasm_branch_hinting(enable);
1343        }
1344        // Not included in `all_proposals`: off by default until fuzzed.
1345        if let Some(enable) = self.wasm.compact_imports {
1346            config.wasm_compact_imports(enable);
1347        }
1348        if let Some(enable) = self.wasm.extended_const.or(all) {
1349            config.wasm_extended_const(enable);
1350        }
1351
1352        macro_rules! handle_conditionally_compiled {
1353            ($(($feature:tt, $field:tt, $method:tt))*) => ($(
1354                if let Some(enable) = self.wasm.$field.or(all) {
1355                    #[cfg(feature = $feature)]
1356                    config.$method(enable);
1357                    #[cfg(not(feature = $feature))]
1358                    if enable && all.is_none() {
1359                        bail!("support for {} was disabled at compile-time", $feature);
1360                    }
1361                }
1362            )*)
1363        }
1364
1365        handle_conditionally_compiled! {
1366            ("component-model", component_model, wasm_component_model)
1367            ("component-model-async", component_model_async, wasm_component_model_async)
1368            ("component-model-async", component_model_more_async_builtins, wasm_component_model_more_async_builtins)
1369            ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful)
1370            ("component-model-async", component_model_threading, wasm_component_model_threading)
1371            ("component-model", component_model_error_context, wasm_component_model_error_context)
1372            ("component-model", component_model_map, wasm_component_model_map)
1373            ("component-model", component_model_fixed_length_lists, wasm_component_model_fixed_length_lists)
1374            ("component-model", component_model_implements, wasm_component_model_implements)
1375            ("component-model", component_model_canonical_names, wasm_component_model_canonical_names)
1376            ("component-model", component_model_accessors, wasm_component_model_accessors)
1377            ("component-model", component_model_memory64, wasm_component_model_memory64)
1378            ("threads", threads, wasm_threads)
1379            ("gc", gc, wasm_gc)
1380            ("gc", reference_types, wasm_reference_types)
1381            ("gc", function_references, wasm_function_references)
1382            ("gc", exceptions, wasm_exceptions)
1383            ("stack-switching", stack_switching, wasm_stack_switching)
1384        }
1385
1386        if let Some(enable) = self.wasm.component_model_gc {
1387            #[cfg(all(feature = "component-model", feature = "gc"))]
1388            config.wasm_component_model_gc(enable);
1389            #[cfg(not(all(feature = "component-model", feature = "gc")))]
1390            if enable && all.is_none() {
1391                bail!("support for `component-model-gc` was disabled at compile time")
1392            }
1393        }
1394
1395        Ok(())
1396    }
1397
1398    #[cfg(feature = "toml")]
1399    pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
1400        use wasmtime::error::Context;
1401
1402        let path_ref = path.as_ref();
1403        let file_contents = std::fs::read_to_string(path_ref)
1404            .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
1405        toml::from_str::<CommonOptions>(&file_contents)
1406            .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
1407    }
1408
1409    /// Creates an instance of [`CommonOptions`] by reflecting on the
1410    /// configuration present in the provided [`Engine`].
1411    ///
1412    /// This will extract all configuration values that can be set by this
1413    /// [`CommonOptions`] into a [`Config`] into the returned structure to the
1414    /// best of its ability. Not all configuration options present on [`Engine`]
1415    /// can be reflected back into [`CommonOptions`], and not all options on
1416    /// [`CommonOptions`] can be set on an [`Engine`]. This means that this
1417    /// is a lossy operation that doesn't fully capture 100% of the
1418    /// configuration of [`Engine`]. That being said, however, it can capture
1419    /// almost all of the configuration related to codegen and major other
1420    /// configuration options.
1421    pub fn from_engine(engine: &Engine) -> Self {
1422        let features = engine.get_wasm_features();
1423        let pooling = engine.get_pooling_config();
1424        CommonOptions {
1425            target: engine.get_target(),
1426            opts: OptimizeOptions {
1427                memory_may_move: Some(engine.get_memory_may_move()),
1428                memory_reservation: Some(engine.get_memory_reservation()),
1429                memory_reservation_for_growth: Some(engine.get_memory_reservation_for_growth()),
1430                memory_guard_size: Some(engine.get_memory_guard_size()),
1431                gc_heap_may_move: Some(engine.get_gc_heap_may_move()),
1432                gc_heap_reservation: Some(engine.get_gc_heap_reservation()),
1433                gc_heap_reservation_for_growth: Some(engine.get_gc_heap_reservation_for_growth()),
1434                gc_heap_guard_size: Some(engine.get_gc_heap_guard_size()),
1435                gc_heap_initial_size: Some(engine.get_gc_heap_initial_size()),
1436                guard_before_linear_memory: Some(engine.get_guard_before_linear_memory()),
1437                table_lazy_init: Some(engine.get_table_lazy_init()),
1438                memory_init_cow: Some(engine.get_memory_init_cow()),
1439                memory_guaranteed_dense_image_size: Some(
1440                    engine.get_memory_guaranteed_dense_image_size(),
1441                ),
1442                signals_based_traps: Some(engine.get_signals_based_traps()),
1443                gc_zeal_alloc_counter: engine.get_gc_zeal_alloc_counter(),
1444                opt_level: engine.get_cranelift_opt_level(),
1445                regalloc_algorithm: engine.get_cranelift_regalloc_algorithm(),
1446                pooling_allocator: Some(pooling.is_some()),
1447                pooling_decommit_batch_size: pooling.map(|c| c.get_decommit_batch_size()),
1448                pooling_memory_keep_resident: pooling.map(|c| c.get_memory_keep_resident()),
1449                pooling_table_keep_resident: pooling.map(|c| c.get_table_keep_resident()),
1450                pooling_max_unused_warm_slots: pooling.map(|c| c.get_max_unused_warm_slots()),
1451                pooling_pagemap_scan: pooling.map(|c| c.get_pagemap_scan()),
1452                pooling_total_core_instances: pooling.map(|c| c.get_total_core_instances()),
1453                pooling_total_component_instances: pooling
1454                    .map(|c| c.get_total_component_instances()),
1455                pooling_total_memories: pooling.map(|c| c.get_total_memories()),
1456                pooling_total_tables: pooling.map(|c| c.get_total_tables()),
1457                pooling_max_memory_size: pooling.map(|c| c.get_max_memory_size()),
1458                pooling_table_elements: pooling.map(|c| c.get_table_elements()),
1459                pooling_max_core_instance_size: pooling.map(|c| c.get_max_core_instance_size()),
1460                pooling_max_component_instance_size: pooling
1461                    .map(|c| c.get_max_component_instance_size()),
1462                pooling_max_core_instances_per_component: pooling
1463                    .map(|c| c.get_max_core_instances_per_component()),
1464                pooling_max_memories_per_component: pooling
1465                    .map(|c| c.get_max_memories_per_component()),
1466                pooling_max_tables_per_component: pooling.map(|c| c.get_max_tables_per_component()),
1467                pooling_max_tables_per_module: pooling.map(|c| c.get_max_tables_per_module()),
1468                pooling_max_memories_per_module: pooling.map(|c| c.get_max_memories_per_module()),
1469                pooling_async_stack_keep_resident: pooling
1470                    .map(|c| c.get_async_stack_keep_resident()),
1471                pooling_total_stacks: pooling.map(|c| c.get_total_stacks()),
1472                pooling_total_gc_heaps: pooling.map(|c| c.get_total_gc_heaps()),
1473                pooling_memory_protection_keys: pooling.map(|c| c.get_memory_protection_keys()),
1474                pooling_max_memory_protection_keys: pooling
1475                    .map(|c| c.get_max_memory_protection_keys()),
1476                // Deprecated aliases for the above options; intentionally left
1477                // unset in favor of their replacements.
1478                dynamic_memory_guard_size: None,
1479                static_memory_guard_size: None,
1480                static_memory_forced: None,
1481                static_memory_maximum_size: None,
1482                dynamic_memory_reserved_for_growth: None,
1483            },
1484            codegen: CodegenOptions {
1485                compiler: engine.get_strategy(),
1486                collector: engine.get_collector(),
1487                cranelift_debug_verifier: engine.get_cranelift_debug_verifier(),
1488                inlining: Some(engine.get_compiler_inlining()),
1489                native_unwind_info: engine.get_native_unwind_info(),
1490                parallel_compilation: Some(engine.get_parallel_compilation()),
1491                metadata_for_internal_asserts: Some(engine.get_metadata_for_internal_asserts()),
1492                metadata_for_gc_heap_corruption: Some(engine.get_metadata_for_gc_heap_corruption()),
1493                cranelift: engine
1494                    .get_cranelift_flags_set()
1495                    .map(|(k, v)| (k.to_string(), Some(v.to_string())))
1496                    .chain(
1497                        engine
1498                            .get_cranelift_flags_enabled()
1499                            .map(|k| (k.to_string(), None)),
1500                    )
1501                    .collect(),
1502
1503                // not easily extractable from `Engine` since that supports
1504                // arbitrary code-defined caches.
1505                cache: None,
1506                cache_config: None,
1507
1508                // These are configured per-`CodeBuilder`, so they cannot be
1509                // recovered here.
1510                unsafe_intrinsics: None,
1511                compile_time_builtin: Vec::new(),
1512            },
1513            debug: DebugOptions {
1514                address_map: Some(engine.get_generate_address_map()),
1515                debug_info: Some(engine.get_debug_info()),
1516                guest_debug: Some(engine.get_guest_debug()),
1517                symbols: Some(engine.get_debug_symbols()),
1518                max_backtrace: Some(engine.get_wasm_backtrace_max_frames()),
1519
1520                // Can't infer a path to emit a core dump to from engine
1521                // configuration.
1522                coredump: None,
1523                // debugger configuration not part of engine config
1524                debugger: None,
1525                arg: Vec::new(),
1526                inherit_stderr: None,
1527                inherit_stdout: None,
1528                inherit_stdin: None,
1529                // logging not part of engine config
1530                log_to_files: None,
1531                logging: None,
1532            },
1533            wasm: WasmOptions {
1534                async_stack_size: Some(engine.get_async_stack_size()),
1535                async_stack_zeroing: Some(engine.get_async_stack_zeroing()),
1536                branch_hinting: Some(engine.get_wasm_branch_hinting()),
1537                compact_imports: Some(features.contains(WasmFeatures::COMPACT_IMPORTS)),
1538                bulk_memory: Some(features.contains(WasmFeatures::BULK_MEMORY)),
1539                component_model: Some(features.contains(WasmFeatures::COMPONENT_MODEL)),
1540                component_model_async: Some(features.contains(WasmFeatures::CM_ASYNC)),
1541                component_model_async_stackful: Some(
1542                    features.contains(WasmFeatures::CM_ASYNC_STACKFUL),
1543                ),
1544                component_model_error_context: Some(
1545                    features.contains(WasmFeatures::CM_ERROR_CONTEXT),
1546                ),
1547                component_model_gc: Some(features.contains(WasmFeatures::CM_GC)),
1548                component_model_fixed_length_lists: Some(
1549                    features.contains(WasmFeatures::CM_FIXED_LENGTH_LISTS),
1550                ),
1551                component_model_implements: Some(features.contains(WasmFeatures::CM_IMPLEMENTS)),
1552                component_model_canonical_names: Some(
1553                    features.contains(WasmFeatures::CM_CANON_NAMES),
1554                ),
1555                component_model_accessors: Some(features.contains(WasmFeatures::CM_ACCESSORS)),
1556                component_model_map: Some(features.contains(WasmFeatures::CM_MAP)),
1557                component_model_memory64: Some(features.contains(WasmFeatures::CM64)),
1558                component_model_more_async_builtins: Some(
1559                    features.contains(WasmFeatures::CM_MORE_ASYNC_BUILTINS),
1560                ),
1561                component_model_threading: Some(features.contains(WasmFeatures::CM_THREADING)),
1562                custom_page_sizes: Some(features.contains(WasmFeatures::CUSTOM_PAGE_SIZES)),
1563                exceptions: Some(features.contains(WasmFeatures::EXCEPTIONS)),
1564                extended_const: Some(features.contains(WasmFeatures::EXTENDED_CONST)),
1565                function_references: Some(features.contains(WasmFeatures::FUNCTION_REFERENCES)),
1566                gc: Some(features.contains(WasmFeatures::GC)),
1567                gc_support: Some(features.contains(WasmFeatures::GC_TYPES)),
1568                memory64: Some(features.contains(WasmFeatures::MEMORY64)),
1569                multi_memory: Some(features.contains(WasmFeatures::MULTI_MEMORY)),
1570                multi_value: Some(features.contains(WasmFeatures::MULTI_VALUE)),
1571                reference_types: Some(features.contains(WasmFeatures::REFERENCE_TYPES)),
1572                relaxed_simd: Some(features.contains(WasmFeatures::RELAXED_SIMD)),
1573                shared_everything_threads: Some(
1574                    features.contains(WasmFeatures::SHARED_EVERYTHING_THREADS),
1575                ),
1576                simd: Some(features.contains(WasmFeatures::SIMD)),
1577                stack_switching: Some(features.contains(WasmFeatures::STACK_SWITCHING)),
1578                tail_call: Some(features.contains(WasmFeatures::TAIL_CALL)),
1579                threads: Some(features.contains(WasmFeatures::THREADS)),
1580                wide_arithmetic: Some(features.contains(WasmFeatures::WIDE_ARITHMETIC)),
1581                concurrency_support: Some(engine.get_concurrency_support()),
1582                epoch_interruption: Some(engine.get_epoch_interruption()),
1583                fuel: if engine.get_consume_fuel() {
1584                    Some(1)
1585                } else {
1586                    None
1587                },
1588                max_wasm_stack: Some(engine.get_max_wasm_stack()),
1589                nan_canonicalization: engine.get_cranelift_nan_canonicalization(),
1590                relaxed_simd_deterministic: Some(engine.get_relaxed_simd_deterministic()),
1591                shared_memory: Some(engine.get_shared_memory()),
1592
1593                // This is covered by individual `WasmFeatures::*` flags above.
1594                all_proposals: None,
1595                // These aren't set in `Config` any more, they're just
1596                // historical
1597                max_instances: None,
1598                max_memories: None,
1599                max_memory_size: None,
1600                max_table_elements: None,
1601                max_tables: None,
1602                // not part of engine config, specific to `run` command
1603                timeout: None,
1604                trap_on_grow_failure: None,
1605                unknown_exports_allow: None,
1606                unknown_imports_default: None,
1607                unknown_imports_trap: None,
1608                wmemcheck: None,
1609            },
1610
1611            // Not currently reflected in `Engine`.
1612            record: RecordOptions::default(),
1613
1614            // WASI options aren't reflected in an `Engine`.
1615            wasi: Default::default(),
1616
1617            // CLI flags are represented above, they have default values here.
1618            configured: true,
1619            codegen_raw: Default::default(),
1620            debug_raw: Default::default(),
1621            opts_raw: Default::default(),
1622            record_raw: Default::default(),
1623            wasi_raw: Default::default(),
1624            wasm_raw: Default::default(),
1625
1626            // No external configuration file, it's all above.
1627            config: None,
1628            //
1629            // Note that an exhaustive listing is explicitly used to avoid
1630            // forgetting to configure a field. Please don't add `..something`
1631            // here at the end.
1632        }
1633    }
1634}
1635
1636#[cfg(test)]
1637mod tests {
1638    use wasmtime::{OptLevel, RegallocAlgorithm};
1639
1640    use super::*;
1641
1642    #[test]
1643    fn from_toml() {
1644        // empty toml
1645        let empty_toml = "";
1646        let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
1647        common_options.config(None).unwrap();
1648
1649        // basic toml
1650        let basic_toml = r#"
1651            [optimize]
1652            [codegen]
1653            [debug]
1654            [wasm]
1655            [wasi]
1656            [record]
1657        "#;
1658        let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
1659        common_options.config(None).unwrap();
1660
1661        // toml with custom deserialization to match CLI flag parsing
1662        for (opt_value, expected) in [
1663            ("0", Some(OptLevel::None)),
1664            ("1", Some(OptLevel::Speed)),
1665            ("2", Some(OptLevel::Speed)),
1666            ("\"s\"", Some(OptLevel::SpeedAndSize)),
1667            ("\"hello\"", None), // should fail
1668            ("3", None),         // should fail
1669        ] {
1670            let toml = format!(
1671                r#"
1672                    [optimize]
1673                    opt-level = {opt_value}
1674                "#,
1675            );
1676            let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
1677                .ok()
1678                .and_then(|common_options| common_options.opts.opt_level);
1679
1680            assert_eq!(
1681                parsed_opt_level, expected,
1682                "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
1683            );
1684        }
1685
1686        // Regalloc algorithm
1687        for (regalloc_value, expected) in [
1688            ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
1689            ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
1690            ("\"hello\"", None), // should fail
1691            ("3", None),         // should fail
1692            ("true", None),      // should fail
1693        ] {
1694            let toml = format!(
1695                r#"
1696                    [optimize]
1697                    regalloc-algorithm = {regalloc_value}
1698                "#,
1699            );
1700            let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
1701                .ok()
1702                .and_then(|common_options| common_options.opts.regalloc_algorithm);
1703            assert_eq!(
1704                parsed_regalloc_algorithm, expected,
1705                "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
1706            );
1707        }
1708
1709        // Strategy
1710        for (strategy_value, expected) in [
1711            ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
1712            ("\"winch\"", Some(wasmtime::Strategy::Winch)),
1713            ("\"hello\"", None), // should fail
1714            ("5", None),         // should fail
1715            ("true", None),      // should fail
1716        ] {
1717            let toml = format!(
1718                r#"
1719                    [codegen]
1720                    compiler = {strategy_value}
1721                "#,
1722            );
1723            let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
1724                .ok()
1725                .and_then(|common_options| common_options.codegen.compiler);
1726            assert_eq!(
1727                parsed_strategy, expected,
1728                "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
1729            );
1730        }
1731
1732        // Collector
1733        for (collector_value, expected) in [
1734            (
1735                "\"drc\"",
1736                Some(wasmtime::Collector::DeferredReferenceCounting),
1737            ),
1738            ("\"null\"", Some(wasmtime::Collector::Null)),
1739            ("\"copying\"", Some(wasmtime::Collector::Copying)),
1740            ("\"hello\"", None), // should fail
1741            ("5", None),         // should fail
1742            ("true", None),      // should fail
1743        ] {
1744            let toml = format!(
1745                r#"
1746                    [codegen]
1747                    collector = {collector_value}
1748                "#,
1749            );
1750            let parsed_collector = toml::from_str::<CommonOptions>(&toml)
1751                .ok()
1752                .and_then(|common_options| common_options.codegen.collector);
1753            assert_eq!(
1754                parsed_collector, expected,
1755                "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
1756            );
1757        }
1758    }
1759}
1760
1761impl Default for CommonOptions {
1762    fn default() -> CommonOptions {
1763        CommonOptions::new()
1764    }
1765}
1766
1767impl fmt::Display for CommonOptions {
1768    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1769        let CommonOptions {
1770            codegen_raw,
1771            codegen,
1772            debug_raw,
1773            debug,
1774            opts_raw,
1775            opts,
1776            wasm_raw,
1777            wasm,
1778            wasi_raw,
1779            wasi,
1780            record_raw,
1781            record,
1782            configured,
1783            target,
1784            config,
1785        } = self;
1786        if let Some(target) = target {
1787            write!(f, "--target {target} ")?;
1788        }
1789        if let Some(config) = config {
1790            write!(f, "--config {} ", config.display())?;
1791        }
1792
1793        let codegen_flags;
1794        let opts_flags;
1795        let wasi_flags;
1796        let wasm_flags;
1797        let debug_flags;
1798        let record_flags;
1799
1800        if *configured {
1801            codegen_flags = codegen.to_options();
1802            debug_flags = debug.to_options();
1803            wasi_flags = wasi.to_options();
1804            wasm_flags = wasm.to_options();
1805            opts_flags = opts.to_options();
1806            record_flags = record.to_options();
1807        } else {
1808            codegen_flags = codegen_raw
1809                .iter()
1810                .flat_map(|t| t.0.iter())
1811                .cloned()
1812                .collect();
1813            debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1814            wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1815            wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1816            opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
1817            record_flags = record_raw
1818                .iter()
1819                .flat_map(|t| t.0.iter())
1820                .cloned()
1821                .collect();
1822        }
1823
1824        for flag in codegen_flags {
1825            write!(f, "-C{flag} ")?;
1826        }
1827        for flag in opts_flags {
1828            write!(f, "-O{flag} ")?;
1829        }
1830        for flag in wasi_flags {
1831            write!(f, "-S{flag} ")?;
1832        }
1833        for flag in wasm_flags {
1834            write!(f, "-W{flag} ")?;
1835        }
1836        for flag in debug_flags {
1837            write!(f, "-D{flag} ")?;
1838        }
1839        for flag in record_flags {
1840            write!(f, "-R{flag} ")?;
1841        }
1842
1843        Ok(())
1844    }
1845}