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