Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

83.1 KB
Raw Blame
//! A utility crate for managing Wasmtime configuration options in a
//! serializable format.
//!
//! This crate primarily provides a [`CommonOptions`] structure which can be
//! parsed from CLI flags via [`clap`] or with [`serde::Deserialize`]. This
//! structure can additionally be created from a [`wasmtime::Engine`] to
//! serialize some of the significant configuration options affecting an engine.
//!
//! This is intended to be a shared way for embedders to configure Wasmtime with
//! serializable configuration. The source of truth for Wasmtime's configuration
//! is the [`Config`] type but this additionally serves as a means of creating
//! that type.

use crate::opt::NonzeroDuration;
use std::num::NonZeroUsize;
use std::{fmt, num::NonZeroU32, path::PathBuf};
use wasmtime::{Config, Engine, Result, WasmBacktraceDetails, WasmFeatures, bail};

pub mod opt;

#[cfg(feature = "logging")]
fn init_file_per_thread_logger(prefix: &'static str) {
    file_per_thread_logger::initialize(prefix);
    file_per_thread_logger::allow_uninitialized();

    // Extending behavior of default spawner:
    // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler
    // Source code says DefaultSpawner is implementation detail and
    // shouldn't be used directly.
    #[cfg(feature = "parallel-compilation")]
    rayon::ThreadPoolBuilder::new()
        .spawn_handler(move |thread| {
            let mut b = std::thread::Builder::new();
            if let Some(name) = thread.name() {
                b = b.name(name.to_owned());
            }
            if let Some(stack_size) = thread.stack_size() {
                b = b.stack_size(stack_size);
            }
            b.spawn(move || {
                file_per_thread_logger::initialize(prefix);
                thread.run()
            })?;
            Ok(())
        })
        .build_global()
        .unwrap();
}

wasmtime_option_group! {
    #[env = "OPTIMIZE"]
    pub struct OptimizeOptions {
        /// Optimization level of generated code (0-2, s; default: 2)
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub opt_level: Option<wasmtime::OptLevel>,

        /// Register allocator algorithm choice.
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>,

        /// Do not allow Wasm linear memories to move in the host process's
        /// address space.
        pub memory_may_move: Option<bool>,

        /// Initial virtual memory allocation size for memories.
        pub memory_reservation: Option<u64>,

        /// Bytes to reserve at the end of linear memory for growth into.
        pub memory_reservation_for_growth: Option<u64>,

        /// Size, in bytes, of guard pages for linear memories.
        pub memory_guard_size: Option<u64>,

        /// Do not allow the GC heap to move in the host process's address
        /// space.
        pub gc_heap_may_move: Option<bool>,

        /// Initial virtual memory allocation size for the GC heap.
        pub gc_heap_reservation: Option<u64>,

        /// Bytes to reserve at the end of the GC heap for growth into.
        pub gc_heap_reservation_for_growth: Option<u64>,

        /// Size, in bytes, of guard pages for the GC heap.
        pub gc_heap_guard_size: Option<u64>,

        /// Initial allocated size for the GC heap.
        pub gc_heap_initial_size: Option<u64>,

        /// Indicates whether an unmapped region of memory is placed before all
        /// linear memories.
        pub guard_before_linear_memory: Option<bool>,

        /// Whether to initialize tables lazily, so that instantiation is
        /// fast but indirect calls are a little slower. If no, tables are
        /// initialized eagerly from any active element segments that apply to
        /// them during instantiation. (default: yes)
        pub table_lazy_init: Option<bool>,

        /// Enable the pooling allocator, in place of the on-demand allocator.
        pub pooling_allocator: Option<bool>,

        /// The number of decommits to do per batch. A batch size of 1
        /// effectively disables decommit batching. (default: 1)
        pub pooling_decommit_batch_size: Option<usize>,

        /// How many bytes to keep resident between instantiations for the
        /// pooling allocator in linear memories.
        pub pooling_memory_keep_resident: Option<usize>,

        /// How many bytes to keep resident between instantiations for the
        /// pooling allocator in tables.
        pub pooling_table_keep_resident: Option<usize>,

        /// Enable memory protection keys for the pooling allocator; this can
        /// optimize the size of memory slots.
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub pooling_memory_protection_keys: Option<wasmtime::Enabled>,

        /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime
        /// will use. (default: 16)
        pub pooling_max_memory_protection_keys: Option<usize>,

        /// Configure attempting to initialize linear memory via a
        /// copy-on-write mapping (default: yes)
        pub memory_init_cow: Option<bool>,

        /// Threshold below which CoW images are guaranteed to be used and be
        /// dense.
        pub memory_guaranteed_dense_image_size: Option<u64>,

        /// The maximum number of WebAssembly instances which can be created
        /// with the pooling allocator.
        pub pooling_total_core_instances: Option<u32>,

        /// The maximum number of WebAssembly components which can be created
        /// with the pooling allocator.
        pub pooling_total_component_instances: Option<u32>,

        /// The maximum number of WebAssembly memories which can be created with
        /// the pooling allocator.
        pub pooling_total_memories: Option<u32>,

        /// The maximum number of WebAssembly tables which can be created with
        /// the pooling allocator.
        pub pooling_total_tables: Option<u32>,

        /// The maximum number of WebAssembly stacks which can be created with
        /// the pooling allocator.
        pub pooling_total_stacks: Option<u32>,

        /// The maximum runtime size of each linear memory in the pooling
        /// allocator, in bytes.
        pub pooling_max_memory_size: Option<usize>,

        /// The maximum table elements for any table defined in a module when
        /// using the pooling allocator.
        pub pooling_table_elements: Option<usize>,

        /// The maximum size, in bytes, allocated for a core instance's metadata
        /// when using the pooling allocator.
        pub pooling_max_core_instance_size: Option<usize>,

        /// Configures the maximum number of "unused warm slots" to retain in the
        /// pooling allocator. (default: 100)
        pub pooling_max_unused_warm_slots: Option<u32>,

        /// How much memory, in bytes, to keep resident for async stacks allocated
        /// with the pooling allocator. (default: 0)
        pub pooling_async_stack_keep_resident: Option<usize>,

        /// The maximum size, in bytes, allocated for a component instance's
        /// `VMComponentContext` metadata. (default: 1MiB)
        pub pooling_max_component_instance_size: Option<usize>,

        /// The maximum number of core instances a single component may contain
        /// (default is unlimited).
        pub pooling_max_core_instances_per_component: Option<u32>,

        /// The maximum number of Wasm linear memories that a single component may
        /// transitively contain (default is unlimited).
        pub pooling_max_memories_per_component: Option<u32>,

        /// The maximum number of tables that a single component may transitively
        /// contain (default is unlimited).
        pub pooling_max_tables_per_component: Option<u32>,

        /// The maximum number of defined tables for a core module. (default: 1)
        pub pooling_max_tables_per_module: Option<u32>,

        /// The maximum number of defined linear memories for a module. (default: 1)
        pub pooling_max_memories_per_module: Option<u32>,

        /// The maximum number of concurrent GC heaps supported. (default: 1000)
        pub pooling_total_gc_heaps: Option<u32>,

        /// Enable or disable the use of host signal handlers for traps.
        pub signals_based_traps: Option<bool>,

        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
        pub dynamic_memory_guard_size: Option<u64>,

        /// DEPRECATED: Use `-Cmemory-guard-size=N` instead.
        pub static_memory_guard_size: Option<u64>,

        /// DEPRECATED: Use `-Cmemory-may-move` instead.
        pub static_memory_forced: Option<bool>,

        /// DEPRECATED: Use `-Cmemory-reservation=N` instead.
        pub static_memory_maximum_size: Option<u64>,

        /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead.
        pub dynamic_memory_reserved_for_growth: Option<u64>,

        /// Whether or not `PAGEMAP_SCAN` ioctls are used to reset linear
        /// memory.
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub pooling_pagemap_scan: Option<wasmtime::Enabled>,

        /// XXX: For internal fuzzing and debugging use only!
        #[doc(hidden)]
        pub gc_zeal_alloc_counter: Option<NonZeroU32>,
    }

    enum Optimize {
        ...
    }
}

wasmtime_option_group! {
    #[env = "CODEGEN"]
    pub struct CodegenOptions {
        /// Either `cranelift` or `winch`.
        ///
        /// Currently only `cranelift` and `winch` are supported, but not all
        /// builds of Wasmtime have both built in.
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub compiler: Option<wasmtime::Strategy>,
        /// Which garbage collector to use: `drc`, `null`, or `copying`.
        ///
        /// `drc` is the deferred reference-counting collector.
        ///
        /// `null` is the null garbage collector, which does not collect any
        /// garbage.
        ///
        /// `copying` is the copying garbage collector (not yet implemented).
        ///
        /// Note that not all builds of Wasmtime will have support for garbage
        /// collection included.
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub collector: Option<wasmtime::Collector>,
        /// Enable Cranelift's internal debug verifier (expensive)
        pub cranelift_debug_verifier: Option<bool>,
        /// Whether or not to enable caching of compiled modules.
        pub cache: Option<bool>,
        /// Configuration for compiled module caching.
        pub cache_config: Option<String>,
        /// Whether or not to enable parallel compilation of modules.
        pub parallel_compilation: Option<bool>,
        /// Controls whether native unwind information is present in compiled
        /// object files.
        pub native_unwind_info: Option<bool>,
        /// Whether compiled code includes the hooks needed to run in a
        /// Wasmtime built with AddressSanitizer (defaults to whether this
        /// Wasmtime was built with AddressSanitizer).
        pub asan_compatible_code: Option<bool>,

        /// Whether to perform function inlining during compilation.
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub inlining: Option<wasmtime::Inlining>,

        /// Whether or not trap metadata is present for wasm internal assertions
        /// in compiled code.
        pub metadata_for_internal_asserts: Option<bool>,
        /// Whether or not trap metadata is present for detection of gc
        /// corruption in compiled code.
        pub metadata_for_gc_heap_corruption: Option<bool>,

        /// Expose Wasmtime's unsafe intrinsics to the Wasm being compiled under
        /// the given instance import name, which defaults to
        /// `unsafe-intrinsics` when the name is omitted.
        ///
        /// The unsafe intrinsics are a set of raw, unchecked load and store
        /// operations on the host's address space, along with the address of
        /// the store's data. They may only be used with components, not core
        /// Wasm modules.
        ///
        /// This is wildly unsafe: the Wasm is given the ability to read and
        /// write arbitrary host memory. Only use this with Wasm that you trust
        /// as much as you trust the CLI itself.
        ///
        /// When `-C compile-time-builtin` is also given, the intrinsics are
        /// exposed only to the compile-time builtins and not to the main Wasm
        /// program.
        ///
        /// See the API documentation for
        /// `CodeBuilder::expose_unsafe_intrinsics` for more details.
        #[serde(default)]
        #[serde(deserialize_with = "crate::opt::deserialize_cli_parse_wrapper")]
        #[serde(serialize_with = "crate::opt::serialize_cli_parse_wrapper")]
        pub unsafe_intrinsics: Option<UnsafeIntrinsicsImport>,

        /// Define a compile-time builtin: satisfy the `<name>` instance import
        /// of the main component with the component at `<path>` at compile
        /// time, rather than with a host-defined import at instantiation time.
        ///
        /// May be specified multiple times, once per builtin. Compile-time
        /// builtins may only be used with components, not core Wasm modules,
        /// and require `-C unsafe-intrinsics`.
        ///
        /// The `<name>=` prefix may be omitted, in which case `<name>` defaults
        /// to the file name of `<path>` without its extension. For example
        /// `-C compile-time-builtin=path/to/my-host-api.wat` satisfies the
        /// `my-host-api` import. Note that a `<path>` which itself contains an
        /// `=` is interpreted as the `<name>=<path>` form; pass the explicit
        /// form to disambiguate.
        ///
        /// Compile-time builtins are part of your trusted compute base: they
        /// are given access to the unsafe intrinsics described above. Calls
        /// into them become direct calls, so pass `-C inlining=y` to let them
        /// be inlined into their callers.
        ///
        /// See the API documentation for
        /// `CodeBuilder::compile_time_builtin_binary` for more details.
        #[serde(skip)]
        pub compile_time_builtin: Vec<CompileTimeBuiltin>,

        #[prefixed = "cranelift"]
        #[serde(default)]
        /// Set a cranelift-specific option. Use `wasmtime settings` to see
        /// all.
        pub cranelift: Vec<(String, Option<String>)>,
    }

    enum Codegen {
        ...
    }
}

wasmtime_option_group! {
    #[env = "DEBUG"]
    pub struct DebugOptions {
        /// Enable generation of DWARF debug information in compiled code.
        pub debug_info: Option<bool>,
        /// Enable guest debugging insrumentation.
        pub guest_debug: Option<bool>,
        /// Configure whether compiled code can map native addresses to wasm.
        pub address_map: Option<bool>,
        /// Configure whether logging is enabled.
        pub logging: Option<bool>,
        /// Configure whether logs are emitted to files
        pub log_to_files: Option<bool>,
        /// Enable coredump generation to this file after a WebAssembly trap.
        pub coredump: Option<String>,
        /// Load the given debugger component and attach it to the
        /// main module or component.
        pub debugger: Option<PathBuf>,
        /// Pass the given command-line arguments to the debugger
        /// component. May be specified multiple times.
        #[serde(default)]
        pub arg: Vec<String>,
        /// Allow the debugger component to inherit stdin.Off by
        /// default.
        pub inherit_stdin: Option<bool>,
        /// Allow the debugger component to inherit stdout. Off by
        /// default.
        pub inherit_stdout: Option<bool>,
        /// Allow the debugger component to inherit stderr. Off by
        /// default.
        pub inherit_stderr: Option<bool>,
        /// Maximum number of frames to capture in backtraces.
        pub max_backtrace: Option<usize>,
        /// Whether or not `*.cwasm` files have symbols in them.
        pub symbols: Option<bool>,
    }

    enum Debug {
        ...
    }
}

wasmtime_option_group! {
    #[env = "WASM"]
    pub struct WasmOptions {
        /// Enable canonicalization of all NaN values.
        pub nan_canonicalization: Option<bool>,
        /// Enable execution fuel with N units fuel, trapping after running out
        /// of fuel.
        ///
        /// Most WebAssembly instructions consume 1 unit of fuel. Some
        /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0
        /// units, as any execution cost associated with them involves other
        /// instructions which do consume fuel.
        pub fuel: Option<u64>,
        /// Yield when a global epoch counter changes, allowing for async
        /// operation without blocking the executor.
        pub epoch_interruption: Option<bool>,
        /// Maximum stack size, in bytes, that wasm is allowed to consume before a
        /// stack overflow is reported.
        pub max_wasm_stack: Option<usize>,
        /// Stack size, in bytes, that will be allocated for async stacks.
        ///
        /// Note that this must be larger than `max-wasm-stack` and the
        /// difference between the two is how much stack the host has to execute
        /// on.
        pub async_stack_size: Option<usize>,
        /// Configures whether or not stacks used for async futures are zeroed
        /// before (re)use as a defense-in-depth mechanism. (default: false)
        pub async_stack_zeroing: Option<bool>,
        /// Allow unknown exports when running commands.
        pub unknown_exports_allow: Option<bool>,
        /// Allow the main module to import unknown functions, using an
        /// implementation that immediately traps, when running commands.
        pub unknown_imports_trap: Option<bool>,
        /// Allow the main module to import unknown functions, using an
        /// implementation that returns default values, when running commands.
        pub unknown_imports_default: Option<bool>,
        /// Enables memory error checking. (see wmemcheck.md for more info)
        pub wmemcheck: Option<bool>,
        /// Maximum size, in bytes, that a linear memory is allowed to reach.
        ///
        /// Growth beyond this limit will cause `memory.grow` instructions in
        /// WebAssembly modules to return -1 and fail.
        pub max_memory_size: Option<usize>,
        /// Maximum size, in table elements, that a table is allowed to reach.
        pub max_table_elements: Option<usize>,
        /// Maximum number of WebAssembly instances allowed to be created.
        pub max_instances: Option<usize>,
        /// Maximum number of WebAssembly tables allowed to be created.
        pub max_tables: Option<usize>,
        /// Maximum number of WebAssembly linear memories allowed to be created.
        pub max_memories: Option<usize>,
        /// Force a trap to be raised on `memory.grow` and `table.grow` failure
        /// instead of returning -1 from these instructions.
        ///
        /// This is not necessarily a spec-compliant option to enable but can be
        /// useful for tracking down a backtrace of what is requesting so much
        /// memory, for example.
        pub trap_on_grow_failure: Option<bool>,
        /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc).
        ///
        /// Note that when this option is not set, malicious wasm code may
        /// cause the host process to become unresponsive to inputs including
        /// SIGTERM.
        pub timeout: Option<NonzeroDuration>,
        /// Configures support for all WebAssembly proposals implemented.
        pub all_proposals: Option<bool>,
        /// Configure support for the bulk memory proposal.
        pub bulk_memory: Option<bool>,
        /// Configure support for the multi-memory proposal.
        pub multi_memory: Option<bool>,
        /// Configure support for the multi-value proposal.
        pub multi_value: Option<bool>,
        /// Configure support for the reference-types proposal.
        pub reference_types: Option<bool>,
        /// Configure support for the simd proposal.
        pub simd: Option<bool>,
        /// Configure support for the relaxed-simd proposal.
        pub relaxed_simd: Option<bool>,
        /// Configure forcing deterministic and host-independent behavior of
        /// the relaxed-simd instructions.
        ///
        /// By default these instructions may have architecture-specific behavior as
        /// allowed by the specification, but this can be used to force the behavior
        /// of these instructions to match the deterministic behavior classified in
        /// the specification. Note that enabling this option may come at a
        /// performance cost.
        pub relaxed_simd_deterministic: Option<bool>,
        /// Configure support for the tail-call proposal.
        pub tail_call: Option<bool>,
        /// Configure support for the threads proposal.
        pub threads: Option<bool>,
        /// Configure the ability to create a `shared` memory.
        pub shared_memory: Option<bool>,
        /// Configure support for the memory64 proposal.
        pub memory64: Option<bool>,
        /// Configure support for the component-model proposal.
        pub component_model: Option<bool>,
        /// Component model support for async lifting/lowering.
        pub component_model_async: Option<bool>,
        /// Component model support for async lifting/lowering: this corresponds
        /// to the 🚝 emoji in the component model specification.
        pub component_model_more_async_builtins: Option<bool>,
        /// Component model support for async lifting/lowering: this corresponds
        /// to the 🚟 emoji in the component model specification.
        pub component_model_async_stackful: Option<bool>,
        /// Component model support for threading: this corresponds
        /// to the 🧵 emoji in the component model specification.
        pub component_model_threading: Option<bool>,
        /// Component model support for `error-context`: this corresponds
        /// to the 📝 emoji in the component model specification.
        pub component_model_error_context: Option<bool>,
        /// GC support in the component model: this corresponds to the 🛸 emoji
        /// in the component model specification.
        pub component_model_gc: Option<bool>,
        /// Map support in the component model: this corresponds to the 🗺️
        /// emoji in the component model specification.
        pub component_model_map: Option<bool>,
        /// Component model support for `memory64`: this corresponds
        /// to the 🐘 emoji in the component model specification.
        pub component_model_memory64: Option<bool>,
        /// Configure support for the function-references proposal.
        pub function_references: Option<bool>,
        /// Configure support for the stack-switching proposal.
        pub stack_switching: Option<bool>,
        /// Configure support for the GC proposal.
        pub gc: Option<bool>,
        /// Configure support for the custom-page-sizes proposal.
        pub custom_page_sizes: Option<bool>,
        /// Configure support for the wide-arithmetic proposal.
        pub wide_arithmetic: Option<bool>,
        /// Configure support for the branch-hinting proposal.
        pub branch_hinting: Option<bool>,
        /// Configure support for compact imports.
        pub compact_imports: Option<bool>,
        /// Configure support for the extended-const proposal.
        pub extended_const: Option<bool>,
        /// Configure support for the exceptions proposal.
        pub exceptions: Option<bool>,
        /// Configure support for the legacy exceptions proposal.
        ///
        /// This only exists for Wasmtime's own testing of the spec test suite
        /// and may be removed at any time.
        pub legacy_exceptions: Option<bool>,
        /// Whether or not any GC infrastructure in Wasmtime is enabled or not.
        pub gc_support: Option<bool>,
        /// Component model support for fixed-length lists: this corresponds
        /// to the 🔧 emoji in the component model specification
        pub component_model_fixed_length_lists: Option<bool>,
        /// Component model support for `(implements ...)` and
        /// `(external-id ...)`, corresponds to the 🏷️ emoji in the upstream
        /// spec.
        pub component_model_implements: Option<bool>,
        /// Component model support for canonical names, corresponds to the
        /// 🔗 emoji in the upstream spec.
        pub component_model_canonical_names: Option<bool>,
        /// Component model support for `[get]` and `[set]` accessors,
        /// corresponds to the 📡 emoji in the upstream spec.
        pub component_model_accessors: Option<bool>,
        /// Whether or not any concurrency infrastructure in Wasmtime is
        /// enabled or not.
        pub concurrency_support: Option<bool>,
    }

    enum Wasm {
        ...
    }
}

wasmtime_option_group! {
    #[env = "WASI"]
    pub struct WasiOptions {
        /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random.
        pub cli: Option<bool>,
        /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code)
        pub cli_exit_with_code: Option<bool>,
        /// Deprecated alias for `cli`
        pub common: Option<bool>,
        /// Enable support for WASI neural network imports (experimental)
        pub nn: Option<bool>,
        /// Enable support for WASI threading imports (experimental). Implies preview2=false.
        pub threads: Option<bool>,
        /// Enable support for WASI HTTP imports
        pub http: Option<bool>,
        /// Number of distinct write calls to the outgoing body's output-stream
        /// that the implementation will buffer.
        /// Default: 1.
        pub http_outgoing_body_buffer_chunks: Option<NonZeroUsize>,
        /// Maximum size allowed in a write call to the outgoing body's output-stream.
        /// Default: 1024 * 1024.
        pub http_outgoing_body_chunk_size: Option<NonZeroUsize>,
        /// Enable support for WASI config imports (experimental)
        pub config: Option<bool>,
        /// Enable support for WASI key-value imports (experimental)
        pub keyvalue: Option<bool>,
        /// Grant access to the given TCP listen socket (experimental, legacy
        /// wasip1 implementation only)
        #[serde(default)]
        pub tcplisten: Vec<String>,
        /// Enable support for WASI TLS (Transport Layer Security) imports (experimental)
        pub tls: Option<bool>,
        /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy
        /// implementation (false)
        pub preview2: Option<bool>,
        /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn.
        ///
        /// Each use of the flag will preload a ML model from the host directory
        /// using the given model encoding. The model will be mapped to the
        /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload
        /// an OpenVINO model named `bar`. Note that which model encodings are
        /// available is dependent on the backends implemented in the
        /// `wasmtime_wasi_nn` crate.
        #[serde(skip)]
        pub nn_graph: Vec<WasiNnGraph>,
        /// Flag for WASI preview2 to inherit the host's network within the
        /// guest so it has full access to all addresses/ports/etc.
        pub inherit_network: Option<bool>,
        /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not.
        pub allow_ip_name_lookup: Option<bool>,
        /// Indicates whether `wasi:sockets` TCP support is enabled or not.
        pub tcp: Option<bool>,
        /// Indicates whether `wasi:sockets` UDP support is enabled or not.
        pub udp: Option<bool>,
        /// Enable WASI APIs marked as: @unstable(feature = network-error-code)
        pub network_error_code: Option<bool>,
        /// Allows imports from the `wasi_unstable` core wasm module. Disabled by default.
        pub preview0: Option<bool>,
        /// Inherit all environment variables from the parent process.
        ///
        /// This option can be further overwritten with `--env` flags.
        pub inherit_env: Option<bool>,
        /// Inherit stdin from the parent process. On by default.
        pub inherit_stdin: Option<bool>,
        /// Inherit stdout from the parent process. On by default.
        pub inherit_stdout: Option<bool>,
        /// Inherit stderr from the parent process. On by default.
        pub inherit_stderr: Option<bool>,
        /// Initial current working directory reported through `wasi:cli/environment`.
        pub cwd: Option<String>,
        /// Pass a wasi config variable to the program.
        #[serde(skip)]
        pub config_var: Vec<KeyValuePair>,
        /// Preset data for the In-Memory provider of WASI key-value API.
        #[serde(skip)]
        pub keyvalue_in_memory_data: Vec<KeyValuePair>,
        /// Enable support for WASIp3 APIs.
        pub p3: Option<bool>,
        /// Maximum resources the guest is allowed to create simultaneously.
        pub max_resources: Option<usize>,
        /// Fuel to use for all hostcalls to limit guest<->host data transfer.
        pub hostcall_fuel: Option<usize>,
        /// Maximum size, in bytes, of a single WASI filesystem or socket read
        /// or write, which bounds the host buffer allocated per I/O operation.
        /// (default: 2MiB)
        pub max_io_size: Option<NonZeroUsize>,
        /// Maximum number of component-model handle-table slots (e.g. for
        /// resources, streams, futures) per store; allocating past it traps.
        /// (default: 100000)
        pub max_component_handles: Option<usize>,
        /// Maximum number of simultaneously-live fibers per store.
        pub max_fibers: Option<u32>,
        /// Maximum value, in bytes, for a wasi-random 0.2
        /// `get{,-insecure}-random-bytes` `len` parameter. Calls with a value
        /// exceeding this limit will trap.
        pub max_random_size: Option<u64>,
        /// Maximum value, in bytes, for the contents of a wasi-http 0.2
        /// `fields` resource (aka `headers` and `trailers`). `fields` methods
        /// which cause the contents to exceed this size limit will trap.
        pub max_http_fields_size: Option<usize>,
    }

    enum Wasi {
        ...
    }
}

wasmtime_option_group! {
    #[env = "RECORD"]
    pub struct RecordOptions {
        /// Filename for the recorded execution trace (or empty string to skip writing a file).
        pub path: Option<String>,
        /// Include (optional) signatures to facilitate validation checks during replay
        /// (see `wasmtime replay` for details).
        pub validation_metadata: Option<bool>,
        /// Window size of internal buffering for record events (large windows offer more opportunities
        /// for coalescing events at the cost of memory usage).
        pub event_window_size: Option<usize>,
    }

    enum Record {
        ...
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct WasiNnGraph {
    pub format: String,
    pub dir: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct KeyValuePair {
    pub key: String,
    pub value: String,
}

/// The instance import name under which Wasmtime's unsafe intrinsics are
/// exposed to the Wasm being compiled.
#[derive(Debug, Clone, PartialEq)]
pub struct UnsafeIntrinsicsImport(pub String);

/// A compile-time builtin.
#[derive(Debug, Clone, PartialEq)]
pub struct CompileTimeBuiltin {
    /// The instance import name that this satisfies in the main component.
    pub name: String,
    /// The path to the component that implements this builtin.
    pub path: PathBuf,
}

/// Common options for commands that translate WebAssembly modules
#[derive(Clone)]
#[cfg_attr(feature = "clap", derive(clap::Parser))]
#[cfg_attr(
    feature = "serde",
    derive(serde_derive::Deserialize, serde_derive::Serialize)
)]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct CommonOptions {
    // These options groups are used to parse `-O` and such options but aren't
    // the raw form consumed by the CLI. Instead they're pushed into the `pub`
    // fields below as part of the `configure` method.
    //
    // Ideally clap would support `pub opts: OptimizeOptions` and parse directly
    // into that but it does not appear to do so for multiple `-O` flags for
    // now.
    /// Optimization and tuning related options for wasm performance, `-O help` to
    /// see all.
    #[cfg_attr(
        feature = "clap",
        arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")
    )]
    #[cfg_attr(feature = "serde", serde(skip))]
    opts_raw: Vec<opt::CommaSeparated<Optimize>>,

    /// Codegen-related configuration options, `-C help` to see all.
    #[cfg_attr(
        feature = "clap",
        arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")
    )]
    #[cfg_attr(feature = "serde", serde(skip))]
    codegen_raw: Vec<opt::CommaSeparated<Codegen>>,

    /// Debug-related configuration options, `-D help` to see all.
    #[cfg_attr(
        feature = "clap",
        arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")
    )]
    #[cfg_attr(feature = "serde", serde(skip))]
    debug_raw: Vec<opt::CommaSeparated<Debug>>,

    /// Options for configuring semantic execution of WebAssembly, `-W help` to see
    /// all.
    #[cfg_attr(
        feature = "clap",
        arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")
    )]
    #[cfg_attr(feature = "serde", serde(skip))]
    wasm_raw: Vec<opt::CommaSeparated<Wasm>>,

    /// Options for configuring WASI and its proposals, `-S help` to see all.
    #[cfg_attr(
        feature = "clap",
        arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")
    )]
    #[cfg_attr(feature = "serde", serde(skip))]
    wasi_raw: Vec<opt::CommaSeparated<Wasi>>,

    /// Options to enable and configure execution recording, `-R help` to see all.
    ///
    /// Generates a serialized trace of the Wasm module execution that captures all
    /// non-determinism observable by the module. This trace can subsequently be
    /// re-executed in a deterministic, embedding-agnostic manner (see the `wasmtime replay` command).
    ///
    /// Note: Minimal configuration options for deterministic Wasm semantics will be
    /// enforced during recording by default (NaN canonicalization, deterministic relaxed SIMD).
    #[cfg_attr(
        feature = "clap",
        arg(short = 'R', long = "record", value_name = "KEY[=VAL[,..]]")
    )]
    #[cfg_attr(feature = "serde", serde(skip))]
    record_raw: Vec<opt::CommaSeparated<Record>>,

    // These fields are filled in by the `configure` method below via the
    // options parsed from the CLI above. This is what the CLI should use.
    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(skip))]
    configured: bool,

    /// Whether to ignore `WASMTIME_*` environment variables, which are
    /// otherwise read as options in addition to those specified here.
    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(skip))]
    pub ignore_env: bool,

    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(rename = "optimize", default))]
    pub opts: OptimizeOptions,

    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(default))]
    pub codegen: CodegenOptions,

    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(default))]
    pub debug: DebugOptions,

    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(default))]
    pub wasm: WasmOptions,

    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(default))]
    pub wasi: WasiOptions,

    #[cfg_attr(feature = "clap", arg(skip))]
    #[cfg_attr(feature = "serde", serde(default))]
    pub record: RecordOptions,

    /// The target triple; default is the host triple
    #[cfg_attr(feature = "clap", arg(long, value_name = "TARGET"))]
    #[cfg_attr(feature = "serde", serde(skip))]
    pub target: Option<String>,

    /// Use the specified TOML configuration file.
    /// This TOML configuration file can provide same configuration options as the
    /// `--optimize`, `--codegen`, `--debug`, `--wasm`, `--wasi` CLI options, with a couple exceptions.
    ///
    /// Additional options specified on the command line will take precedent over options loaded from
    /// this TOML file.
    #[cfg_attr(feature = "clap", arg(long = "config", value_name = "FILE"))]
    #[cfg_attr(feature = "serde", serde(skip))]
    pub config: Option<PathBuf>,
}

type F = WasmFeatures;

/// The options in [`WasmOptions`] that enable or disable a [`WasmFeatures`]
/// flag.
///
/// Each entry is the flag, the option, and the option's name if it's not the
/// flag's name in lowercase with dashes (`CM_ASYNC` is `cm-async`).
static WASM_FEATURE_OPTIONS: &[(WasmFeatures, fn(&WasmOptions) -> Option<bool>, Option<&str>)] = &[
    (F::SIMD, |w| w.simd, None),
    (F::RELAXED_SIMD, |w| w.relaxed_simd, None),
    (F::BULK_MEMORY, |w| w.bulk_memory, None),
    (F::MULTI_VALUE, |w| w.multi_value, None),
    (F::TAIL_CALL, |w| w.tail_call, None),
    (F::MULTI_MEMORY, |w| w.multi_memory, None),
    (F::MEMORY64, |w| w.memory64, None),
    (F::CUSTOM_PAGE_SIZES, |w| w.custom_page_sizes, None),
    (F::WIDE_ARITHMETIC, |w| w.wide_arithmetic, None),
    (F::COMPACT_IMPORTS, |w| w.compact_imports, None),
    (F::EXTENDED_CONST, |w| w.extended_const, None),
    (F::THREADS, |w| w.threads, None),
    (F::GC, |w| w.gc, None),
    (F::GC_TYPES, |w| w.gc_support, Some("gc-support")),
    (F::REFERENCE_TYPES, |w| w.reference_types, None),
    (F::FUNCTION_REFERENCES, |w| w.function_references, None),
    (F::EXCEPTIONS, |w| w.exceptions, None),
    (F::LEGACY_EXCEPTIONS, |w| w.legacy_exceptions, None),
    (F::STACK_SWITCHING, |w| w.stack_switching, None),
    (F::COMPONENT_MODEL, |w| w.component_model, None),
    (
        F::CM_ASYNC,
        |w| w.component_model_async,
        Some("component-model-async"),
    ),
    (
        F::CM_MORE_ASYNC_BUILTINS,
        |w| w.component_model_more_async_builtins,
        Some("component-model-more-async-builtins"),
    ),
    (
        F::CM_ASYNC_STACKFUL,
        |w| w.component_model_async_stackful,
        Some("component-model-async-stackful"),
    ),
    (
        F::CM_THREADING,
        |w| w.component_model_threading,
        Some("component-model-threading"),
    ),
    (
        F::CM_ERROR_CONTEXT,
        |w| w.component_model_error_context,
        Some("component-model-error-context"),
    ),
    (
        F::CM_MAP,
        |w| w.component_model_map,
        Some("component-model-map"),
    ),
    (
        F::CM_FIXED_LENGTH_LISTS,
        |w| w.component_model_fixed_length_lists,
        Some("component-model-fixed-length-lists"),
    ),
    (
        F::CM_IMPLEMENTS,
        |w| w.component_model_implements,
        Some("component-model-implements"),
    ),
    (
        F::CM_CANON_NAMES,
        |w| w.component_model_canonical_names,
        Some("component-model-canonical-names"),
    ),
    (
        F::CM_ACCESSORS,
        |w| w.component_model_accessors,
        Some("component-model-accessors"),
    ),
    (
        F::CM64,
        |w| w.component_model_memory64,
        Some("component-model-memory64"),
    ),
    (
        F::CM_GC,
        |w| w.component_model_gc,
        Some("component-model-gc"),
    ),
];

macro_rules! match_feature {
    (
        [$feat:tt : $config:expr]
        $val:ident => $e:expr,
        $p:pat => err,
    ) => {
        #[cfg(feature = $feat)]
        {
            if let Some($val) = $config {
                $e;
            }
        }
        #[cfg(not(feature = $feat))]
        {
            if let Some($p) = $config {
                bail!(concat!("support for ", $feat, " disabled at compile time"));
            }
        }
    };
}

impl CommonOptions {
    /// Creates a blank new set of [`CommonOptions`] that can be configured.
    pub fn new() -> CommonOptions {
        CommonOptions {
            opts_raw: Vec::new(),
            codegen_raw: Vec::new(),
            debug_raw: Vec::new(),
            wasm_raw: Vec::new(),
            wasi_raw: Vec::new(),
            record_raw: Vec::new(),
            configured: true,
            ignore_env: false,
            opts: Default::default(),
            codegen: Default::default(),
            debug: Default::default(),
            wasm: Default::default(),
            wasi: Default::default(),
            record: Default::default(),
            target: None,
            config: None,
        }
    }

    fn configure(&mut self) -> Result<()> {
        if self.configured {
            return Ok(());
        }
        self.configured = true;
        if let Some(toml_config_path) = &self.config {
            #[cfg(feature = "toml")]
            {
                let toml_options = CommonOptions::from_file(toml_config_path)?;
                self.opts = toml_options.opts;
                self.codegen = toml_options.codegen;
                self.debug = toml_options.debug;
                self.wasm = toml_options.wasm;
                self.wasi = toml_options.wasi;
                self.record = toml_options.record;
            }
            #[cfg(not(feature = "toml"))]
            {
                bail!(
                    "support for loading a configuration file from \
                     {toml_config_path:?} disabled at compile time"
                );
            }
        }
        self.opts.configure_with(&self.opts_raw, !self.ignore_env)?;
        self.codegen
            .configure_with(&self.codegen_raw, !self.ignore_env)?;
        self.debug
            .configure_with(&self.debug_raw, !self.ignore_env)?;
        self.wasm.configure_with(&self.wasm_raw, !self.ignore_env)?;
        self.wasi.configure_with(&self.wasi_raw, !self.ignore_env)?;
        self.record
            .configure_with(&self.record_raw, !self.ignore_env)?;
        Ok(())
    }

    /// Layers `other` on top of `self`.
    ///
    /// Each option that `other` specifies overrides the one in `self`, and
    /// options that `other` doesn't specify are left as they are in `self`.
    pub fn merge(&mut self, other: &mut CommonOptions) -> Result<()> {
        self.configure()?;
        other.configure()?;
        let CommonOptions {
            // Processed into the fields below by `configure`.
            opts_raw: _,
            codegen_raw: _,
            debug_raw: _,
            wasm_raw: _,
            wasi_raw: _,
            record_raw: _,
            configured: _,
            ignore_env: _,
            config: _,

            opts,
            codegen,
            debug,
            wasm,
            wasi,
            record,
            target,
        } = other;
        for opt in opts.to_options() {
            self.opts.configure(&opt);
        }
        for opt in codegen.to_options() {
            self.codegen.configure(&opt);
        }
        for opt in debug.to_options() {
            self.debug.configure(&opt);
        }
        for opt in wasm.to_options() {
            self.wasm.configure(&opt);
        }
        for opt in wasi.to_options() {
            self.wasi.configure(&opt);
        }
        for opt in record.to_options() {
            self.record.configure(&opt);
        }
        if target.is_some() {
            self.target = target.clone();
        }
        Ok(())
    }

    pub fn init_logging(&mut self) -> Result<()> {
        self.configure()?;
        if self.debug.logging == Some(false) {
            return Ok(());
        }
        #[cfg(feature = "logging")]
        if self.debug.log_to_files == Some(true) {
            let prefix = "wasmtime.dbg.";
            init_file_per_thread_logger(prefix);
        } else {
            use std::io::IsTerminal;
            use tracing_subscriber::{EnvFilter, FmtSubscriber};
            let builder = FmtSubscriber::builder()
                .with_writer(std::io::stderr)
                .with_env_filter(EnvFilter::from_env("WASMTIME_LOG"))
                .with_ansi(std::io::stderr().is_terminal());
            if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) {
                builder
                    .with_level(false)
                    .with_target(false)
                    .without_time()
                    .init()
            } else {
                builder.init();
            }
        }
        #[cfg(not(feature = "logging"))]
        if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) {
            bail!("support for logging disabled at compile time");
        }
        Ok(())
    }

    /// Returns a fresh new [`Config`] which reflects all configuration settings
    /// in `self`.
    pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> {
        let mut config = Config::new();
        self.apply_config(&mut config, pooling_allocator_default)?;
        Ok(config)
    }

    /// Applies the options in `self` to an existing `config`.
    pub fn apply_config(
        &mut self,
        config: &mut Config,
        pooling_allocator_default: Option<bool>,
    ) -> Result<()> {
        self.configure()?;

        match_feature! {
            ["cranelift" : self.codegen.compiler]
            strategy => config.strategy(strategy),
            _ => err,
        }
        match_feature! {
            ["gc" : self.codegen.collector]
            collector => config.collector(collector),
            _ => err,
        }
        if let Some(target) = &self.target {
            config.target(target)?;
        }
        match_feature! {
            ["cranelift" : self.codegen.cranelift_debug_verifier]
            enable => config.cranelift_debug_verifier(enable),
            true => err,
        }
        if let Some(enable) = self.debug.debug_info {
            config.debug_info(enable);
        }
        match_feature! {
            ["debug" : self.debug.guest_debug]
            enable => config.guest_debug(enable),
            _ => err,
        }
        if self.debug.coredump.is_some() {
            #[cfg(feature = "coredump")]
            config.coredump_on_trap(true);
            #[cfg(not(feature = "coredump"))]
            bail!("support for coredumps disabled at compile time");
        }
        match_feature! {
            ["cranelift" : self.opts.opt_level]
            level => config.cranelift_opt_level(level),
            _ => err,
        }
        match_feature! {
            ["cranelift": self.opts.regalloc_algorithm]
            algo => config.cranelift_regalloc_algorithm(algo),
            _ => err,
        }
        match_feature! {
            ["cranelift" : self.wasm.nan_canonicalization]
            enable => config.cranelift_nan_canonicalization(enable),
            true => err,
        }

        self.enable_wasm_features(config)?;

        #[cfg(feature = "cranelift")]
        for (name, value) in self.codegen.cranelift.iter() {
            let name = name.replace('-', "_");
            unsafe {
                match value {
                    Some(val) => {
                        config.cranelift_flag_set(&name, val);
                    }
                    None => {
                        config.cranelift_flag_enable(&name);
                    }
                }
            }
        }
        #[cfg(not(feature = "cranelift"))]
        if !self.codegen.cranelift.is_empty() {
            bail!("support for cranelift disabled at compile time");
        }

        #[cfg(feature = "cache")]
        if self.codegen.cache != Some(false) {
            use wasmtime::Cache;
            let cache = match &self.codegen.cache_config {
                Some(path) => Cache::from_file(Some(std::path::Path::new(path)))?,
                None => Cache::from_file(None)?,
            };
            config.cache(Some(cache));
        }
        #[cfg(not(feature = "cache"))]
        if self.codegen.cache == Some(true) {
            bail!("support for caching disabled at compile time");
        }

        match_feature! {
            ["parallel-compilation" : self.codegen.parallel_compilation]
            enable => config.parallel_compilation(enable),
            true => err,
        }

        let memory_reservation = self
            .opts
            .memory_reservation
            .or(self.opts.static_memory_maximum_size);
        if let Some(size) = memory_reservation {
            config.memory_reservation(size);
        }

        if let Some(enable) = self.opts.static_memory_forced {
            config.memory_may_move(!enable);
        }
        if let Some(enable) = self.opts.memory_may_move {
            config.memory_may_move(enable);
        }

        let memory_guard_size = self
            .opts
            .static_memory_guard_size
            .or(self.opts.dynamic_memory_guard_size)
            .or(self.opts.memory_guard_size);
        if let Some(size) = memory_guard_size {
            config.memory_guard_size(size);
        }

        let mem_for_growth = self
            .opts
            .memory_reservation_for_growth
            .or(self.opts.dynamic_memory_reserved_for_growth);
        if let Some(size) = mem_for_growth {
            config.memory_reservation_for_growth(size);
        }
        if let Some(enable) = self.opts.guard_before_linear_memory {
            config.guard_before_linear_memory(enable);
        }

        if let Some(size) = self.opts.gc_heap_reservation {
            config.gc_heap_reservation(size);
        }
        if let Some(enable) = self.opts.gc_heap_may_move {
            config.gc_heap_may_move(enable);
        }
        if let Some(size) = self.opts.gc_heap_guard_size {
            config.gc_heap_guard_size(size);
        }
        if let Some(size) = self.opts.gc_heap_reservation_for_growth {
            config.gc_heap_reservation_for_growth(size);
        }

        if let Some(size) = self.opts.gc_heap_initial_size {
            config.gc_heap_initial_size(size);
        }

        if let Some(enable) = self.opts.table_lazy_init {
            config.table_lazy_init(enable);
        }

        if let Some(n) = self.opts.gc_zeal_alloc_counter
            && (cfg!(gc_zeal) || cfg!(fuzzing))
        {
            config.gc_zeal_alloc_counter(Some(n))?;
        }

        // If fuel has been configured, set the `consume fuel` flag on the config.
        if self.wasm.fuel.is_some() {
            config.consume_fuel(true);
        }

        if let Some(enable) = self.wasm.epoch_interruption {
            config.epoch_interruption(enable);
        }
        if let Some(enable) = self.debug.address_map {
            config.generate_address_map(enable);
        }
        if let Some(frames) = self.debug.max_backtrace {
            match NonZeroUsize::new(frames) {
                None => {
                    config.wasm_backtrace_details(WasmBacktraceDetails::Disable);
                }
                Some(amt) => {
                    config.wasm_backtrace_max_frames(Some(amt));
                }
            }
        }
        if let Some(enable) = self.debug.symbols {
            config.debug_symbols(enable);
        }
        if let Some(enable) = self.opts.memory_init_cow {
            config.memory_init_cow(enable);
        }
        if let Some(size) = self.opts.memory_guaranteed_dense_image_size {
            config.memory_guaranteed_dense_image_size(size);
        }
        if let Some(enable) = self.opts.signals_based_traps {
            config.signals_based_traps(enable);
        }
        if let Some(enable) = self.codegen.native_unwind_info {
            config.native_unwind_info(enable);
        }
        if let Some(enable) = self.codegen.asan_compatible_code {
            config.asan_compatible_code(enable);
        }
        if let Some(enable) = self.codegen.inlining {
            config.compiler_inlining(enable);
        }
        if let Some(enable) = self.codegen.metadata_for_internal_asserts {
            config.metadata_for_internal_asserts(enable);
        }
        if let Some(enable) = self.codegen.metadata_for_gc_heap_corruption {
            config.metadata_for_gc_heap_corruption(enable);
        }

        // async_stack_size enabled by either async or stack-switching, so
        // cannot directly use match_feature!
        #[cfg(any(feature = "async", feature = "stack-switching"))]
        {
            if let Some(size) = self.wasm.async_stack_size {
                config.async_stack_size(size);
            }
        }
        #[cfg(not(any(feature = "async", feature = "stack-switching")))]
        {
            if let Some(_size) = self.wasm.async_stack_size {
                bail!(concat!(
                    "support for async/stack-switching disabled at compile time"
                ));
            }
        }

        match_feature! {
            ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)]
            enable => {
                if enable {
                    let mut cfg = wasmtime::PoolingAllocationConfig::default();
                    if let Some(size) = self.opts.pooling_memory_keep_resident {
                        cfg.linear_memory_keep_resident(size);
                    }
                    if let Some(size) = self.opts.pooling_table_keep_resident {
                        cfg.table_keep_resident(size);
                    }
                    if let Some(limit) = self.opts.pooling_total_core_instances {
                        cfg.total_core_instances(limit);
                    }
                    if let Some(limit) = self.opts.pooling_total_component_instances {
                        cfg.total_component_instances(limit);
                    }
                    if let Some(limit) = self.opts.pooling_total_memories {
                        cfg.total_memories(limit);
                    }
                    if let Some(limit) = self.opts.pooling_total_tables {
                        cfg.total_tables(limit);
                    }
                    if let Some(limit) = self.opts.pooling_table_elements
                        .or(self.wasm.max_table_elements)
                    {
                        cfg.table_elements(limit);
                    }
                    if let Some(limit) = self.opts.pooling_max_core_instance_size {
                        cfg.max_core_instance_size(limit);
                    }
                    match_feature! {
                        ["async" : self.opts.pooling_total_stacks]
                        limit => cfg.total_stacks(limit),
                        _ => err,
                    }
                    if let Some(max) = self.opts.pooling_max_memory_size
                        .or(self.wasm.max_memory_size)
                    {
                        cfg.max_memory_size(max);
                    }
                    if let Some(size) = self.opts.pooling_decommit_batch_size {
                        cfg.decommit_batch_size(size);
                    }
                    if let Some(max) = self.opts.pooling_max_unused_warm_slots {
                        cfg.max_unused_warm_slots(max);
                    }
                    match_feature! {
                        ["async" : self.opts.pooling_async_stack_keep_resident]
                        size => cfg.async_stack_keep_resident(size),
                        _ => err,
                    }
                    if let Some(max) = self.opts.pooling_max_component_instance_size {
                        cfg.max_component_instance_size(max);
                    }
                    if let Some(max) = self.opts.pooling_max_core_instances_per_component {
                        cfg.max_core_instances_per_component(max);
                    }
                    if let Some(max) = self.opts.pooling_max_memories_per_component {
                        cfg.max_memories_per_component(max);
                    }
                    if let Some(max) = self.opts.pooling_max_tables_per_component {
                        cfg.max_tables_per_component(max);
                    }
                    if let Some(max) = self.opts.pooling_max_tables_per_module {
                        cfg.max_tables_per_module(max);
                    }
                    if let Some(max) = self.opts.pooling_max_memories_per_module {
                        cfg.max_memories_per_module(max);
                    }
                    match_feature! {
                        ["memory-protection-keys" : self.opts.pooling_memory_protection_keys]
                        enable => cfg.memory_protection_keys(enable),
                        _ => err,
                    }
                    match_feature! {
                        ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys]
                        max => cfg.max_memory_protection_keys(max),
                        _ => err,
                    }
                    match_feature! {
                        ["gc" : self.opts.pooling_total_gc_heaps]
                        max => cfg.total_gc_heaps(max),
                        _ => err,
                    }
                    if let Some(enabled) = self.opts.pooling_pagemap_scan {
                        cfg.pagemap_scan(enabled);
                    }
                    config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg));
                }
            },
            true => err,
        }

        if self.opts.pooling_memory_protection_keys.is_some()
            && !self.opts.pooling_allocator.unwrap_or(false)
        {
            bail!("memory protection keys require the pooling allocator");
        }

        if self.opts.pooling_max_memory_protection_keys.is_some()
            && !self.opts.pooling_memory_protection_keys.is_some()
        {
            bail!("max memory protection keys requires memory protection keys to be enabled");
        }

        match_feature! {
            ["async" : self.wasm.async_stack_zeroing]
            enable => config.async_stack_zeroing(enable),
            _ => err,
        }

        if let Some(max) = self.wasm.max_wasm_stack {
            config.max_wasm_stack(max);

            // If `-Wasync-stack-size` isn't passed then automatically adjust it
            // to the wasm stack size provided here too. That prevents the need
            // to pass both when one can generally be inferred from the other.
            #[cfg(any(feature = "async", feature = "stack-switching"))]
            if self.wasm.async_stack_size.is_none() {
                const DEFAULT_HOST_STACK: usize = 512 << 10;
                config.async_stack_size(max.saturating_add(DEFAULT_HOST_STACK));
            }
        }

        if let Some(enable) = self.wasm.relaxed_simd_deterministic {
            config.relaxed_simd_deterministic(enable);
        }
        match_feature! {
            ["cranelift" : self.wasm.wmemcheck]
            enable => config.wmemcheck(enable),
            true => err,
        }

        if let Some(enable) = self.wasm.concurrency_support {
            config.concurrency_support(enable);
        }

        if let Some(enable) = self.wasm.shared_memory {
            config.shared_memory(enable);
        }

        let record = &self.record;
        match_feature! {
            ["rr" : &record.path]
            _path => {
                bail!("recording configuration for `rr` feature is not supported yet");
            },
            _ => err,
        }

        Ok(())
    }

    /// Applies the per-`Store` options in `self` to `store`.
    ///
    /// Note that [`CommonOptions::config`] or [`CommonOptions::apply_config`]
    /// should be called before this to ensure options are processed internally
    /// correctly.
    #[cfg(feature = "runtime")]
    pub fn configure_store<T>(&self, store: &mut wasmtime::Store<T>) -> Result<()> {
        debug_assert!(self.configured, "`config` or `apply_config` not called");
        #[cfg(feature = "component-model")]
        {
            if let Some(fuel) = self.wasi.hostcall_fuel {
                store.set_hostcall_fuel(fuel);
            }
            if let Some(max) = self.wasi.max_component_handles {
                store.set_max_component_handles(max);
            }
        }
        #[cfg(feature = "async")]
        if let Some(max) = self.wasi.max_fibers {
            store.set_max_fibers(max);
        }
        if let Some(fuel) = self.wasm.fuel {
            store.set_fuel(fuel)?;
        }
        Ok(())
    }

    fn enable_wasm_features(&self, config: &mut Config) -> Result<()> {
        let all = self.wasm.all_proposals;
        for (feature, option, _) in WASM_FEATURE_OPTIONS {
            let mut value = option(&self.wasm);
            // Exempt legacy exceptions from `-Wall-proposals`.
            if *feature != F::LEGACY_EXCEPTIONS {
                value = value.or(all);
            }
            if let Some(enable) = value {
                config.wasm_features(*feature, enable);
            }
        }

        // Branch hinting is a setting of the compiler rather than a
        // `WasmFeatures` flag.
        if let Some(enable) = self.wasm.branch_hinting.or(all) {
            config.wasm_branch_hinting(enable);
        }

        Ok(())
    }

    /// Returns the names of the specified options that enable or disable a
    /// WebAssembly feature, such as `simd` for `-W simd=y`.
    ///
    /// This includes `all-proposals` for `-W all-proposals`.
    pub fn wasm_features_specified(&self) -> Vec<String> {
        let mut ret = Vec::new();
        for (feature, option, name) in WASM_FEATURE_OPTIONS {
            if option(&self.wasm).is_none() {
                continue;
            }
            ret.push(match name {
                Some(name) => name.to_string(),
                None => {
                    let (name, _) = feature.iter_names().next().unwrap();
                    name.to_lowercase().replace('_', "-")
                }
            });
        }
        if self.wasm.all_proposals.is_some() {
            ret.push("all-proposals".to_string());
        }
        ret
    }

    #[cfg(feature = "toml")]
    pub fn from_file<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
        use wasmtime::error::Context;

        let path_ref = path.as_ref();
        let file_contents = std::fs::read_to_string(path_ref)
            .with_context(|| format!("failed to read config file: {path_ref:?}"))?;
        toml::from_str::<CommonOptions>(&file_contents)
            .with_context(|| format!("failed to parse TOML config file {path_ref:?}"))
    }

    /// Creates an instance of [`CommonOptions`] by reflecting on the
    /// configuration present in the provided [`Engine`].
    ///
    /// This will extract all configuration values that can be set by this
    /// [`CommonOptions`] into a [`Config`] into the returned structure to the
    /// best of its ability. Not all configuration options present on [`Engine`]
    /// can be reflected back into [`CommonOptions`], and not all options on
    /// [`CommonOptions`] can be set on an [`Engine`]. This means that this
    /// is a lossy operation that doesn't fully capture 100% of the
    /// configuration of [`Engine`]. That being said, however, it can capture
    /// almost all of the configuration related to codegen and major other
    /// configuration options.
    pub fn from_engine(engine: &Engine) -> Self {
        let features = engine.get_wasm_features();
        let pooling = engine.get_pooling_config();
        CommonOptions {
            target: engine.get_target(),
            opts: OptimizeOptions {
                memory_may_move: Some(engine.get_memory_may_move()),
                memory_reservation: Some(engine.get_memory_reservation()),
                memory_reservation_for_growth: Some(engine.get_memory_reservation_for_growth()),
                memory_guard_size: Some(engine.get_memory_guard_size()),
                gc_heap_may_move: Some(engine.get_gc_heap_may_move()),
                gc_heap_reservation: Some(engine.get_gc_heap_reservation()),
                gc_heap_reservation_for_growth: Some(engine.get_gc_heap_reservation_for_growth()),
                gc_heap_guard_size: Some(engine.get_gc_heap_guard_size()),
                gc_heap_initial_size: Some(engine.get_gc_heap_initial_size()),
                guard_before_linear_memory: Some(engine.get_guard_before_linear_memory()),
                table_lazy_init: Some(engine.get_table_lazy_init()),
                memory_init_cow: Some(engine.get_memory_init_cow()),
                memory_guaranteed_dense_image_size: Some(
                    engine.get_memory_guaranteed_dense_image_size(),
                ),
                signals_based_traps: Some(engine.get_signals_based_traps()),
                gc_zeal_alloc_counter: engine.get_gc_zeal_alloc_counter(),
                opt_level: engine.get_cranelift_opt_level(),
                regalloc_algorithm: engine.get_cranelift_regalloc_algorithm(),
                pooling_allocator: Some(pooling.is_some()),
                pooling_decommit_batch_size: pooling.map(|c| c.get_decommit_batch_size()),
                pooling_memory_keep_resident: pooling.map(|c| c.get_memory_keep_resident()),
                pooling_table_keep_resident: pooling.map(|c| c.get_table_keep_resident()),
                pooling_max_unused_warm_slots: pooling.map(|c| c.get_max_unused_warm_slots()),
                pooling_pagemap_scan: pooling.map(|c| c.get_pagemap_scan()),
                pooling_total_core_instances: pooling.map(|c| c.get_total_core_instances()),
                pooling_total_component_instances: pooling
                    .map(|c| c.get_total_component_instances()),
                pooling_total_memories: pooling.map(|c| c.get_total_memories()),
                pooling_total_tables: pooling.map(|c| c.get_total_tables()),
                pooling_max_memory_size: pooling.map(|c| c.get_max_memory_size()),
                pooling_table_elements: pooling.map(|c| c.get_table_elements()),
                pooling_max_core_instance_size: pooling.map(|c| c.get_max_core_instance_size()),
                pooling_max_component_instance_size: pooling
                    .map(|c| c.get_max_component_instance_size()),
                pooling_max_core_instances_per_component: pooling
                    .map(|c| c.get_max_core_instances_per_component()),
                pooling_max_memories_per_component: pooling
                    .map(|c| c.get_max_memories_per_component()),
                pooling_max_tables_per_component: pooling.map(|c| c.get_max_tables_per_component()),
                pooling_max_tables_per_module: pooling.map(|c| c.get_max_tables_per_module()),
                pooling_max_memories_per_module: pooling.map(|c| c.get_max_memories_per_module()),
                pooling_async_stack_keep_resident: pooling
                    .map(|c| c.get_async_stack_keep_resident()),
                pooling_total_stacks: pooling.map(|c| c.get_total_stacks()),
                pooling_total_gc_heaps: pooling.map(|c| c.get_total_gc_heaps()),
                pooling_memory_protection_keys: pooling.map(|c| c.get_memory_protection_keys()),
                pooling_max_memory_protection_keys: pooling
                    .map(|c| c.get_max_memory_protection_keys()),
                // Deprecated aliases for the above options; intentionally left
                // unset in favor of their replacements.
                dynamic_memory_guard_size: None,
                static_memory_guard_size: None,
                static_memory_forced: None,
                static_memory_maximum_size: None,
                dynamic_memory_reserved_for_growth: None,
            },
            codegen: CodegenOptions {
                compiler: engine.get_strategy(),
                collector: engine.get_collector(),
                cranelift_debug_verifier: engine.get_cranelift_debug_verifier(),
                inlining: Some(engine.get_compiler_inlining()),
                native_unwind_info: engine.get_native_unwind_info(),
                asan_compatible_code: Some(engine.get_asan_compatible_code()),
                parallel_compilation: Some(engine.get_parallel_compilation()),
                metadata_for_internal_asserts: Some(engine.get_metadata_for_internal_asserts()),
                metadata_for_gc_heap_corruption: Some(engine.get_metadata_for_gc_heap_corruption()),
                cranelift: engine
                    .get_cranelift_flags_set()
                    .map(|(k, v)| (k.to_string(), Some(v.to_string())))
                    .chain(
                        engine
                            .get_cranelift_flags_enabled()
                            .map(|k| (k.to_string(), None)),
                    )
                    .collect(),

                // not easily extractable from `Engine` since that supports
                // arbitrary code-defined caches.
                cache: None,
                cache_config: None,

                // These are configured per-`CodeBuilder`, so they cannot be
                // recovered here.
                unsafe_intrinsics: None,
                compile_time_builtin: Vec::new(),
            },
            debug: DebugOptions {
                address_map: Some(engine.get_generate_address_map()),
                debug_info: Some(engine.get_debug_info()),
                guest_debug: Some(engine.get_guest_debug()),
                symbols: Some(engine.get_debug_symbols()),
                max_backtrace: Some(engine.get_wasm_backtrace_max_frames()),

                // Can't infer a path to emit a core dump to from engine
                // configuration.
                coredump: None,
                // debugger configuration not part of engine config
                debugger: None,
                arg: Vec::new(),
                inherit_stderr: None,
                inherit_stdout: None,
                inherit_stdin: None,
                // logging not part of engine config
                log_to_files: None,
                logging: None,
            },
            wasm: WasmOptions {
                async_stack_size: Some(engine.get_async_stack_size()),
                async_stack_zeroing: Some(engine.get_async_stack_zeroing()),
                branch_hinting: Some(engine.get_wasm_branch_hinting()),
                compact_imports: Some(features.contains(WasmFeatures::COMPACT_IMPORTS)),
                bulk_memory: Some(features.contains(WasmFeatures::BULK_MEMORY)),
                component_model: Some(features.contains(WasmFeatures::COMPONENT_MODEL)),
                component_model_async: Some(features.contains(WasmFeatures::CM_ASYNC)),
                component_model_async_stackful: Some(
                    features.contains(WasmFeatures::CM_ASYNC_STACKFUL),
                ),
                component_model_error_context: Some(
                    features.contains(WasmFeatures::CM_ERROR_CONTEXT),
                ),
                component_model_gc: Some(features.contains(WasmFeatures::CM_GC)),
                component_model_fixed_length_lists: Some(
                    features.contains(WasmFeatures::CM_FIXED_LENGTH_LISTS),
                ),
                component_model_implements: Some(features.contains(WasmFeatures::CM_IMPLEMENTS)),
                component_model_canonical_names: Some(
                    features.contains(WasmFeatures::CM_CANON_NAMES),
                ),
                component_model_accessors: Some(features.contains(WasmFeatures::CM_ACCESSORS)),
                component_model_map: Some(features.contains(WasmFeatures::CM_MAP)),
                component_model_memory64: Some(features.contains(WasmFeatures::CM64)),
                component_model_more_async_builtins: Some(
                    features.contains(WasmFeatures::CM_MORE_ASYNC_BUILTINS),
                ),
                component_model_threading: Some(features.contains(WasmFeatures::CM_THREADING)),
                custom_page_sizes: Some(features.contains(WasmFeatures::CUSTOM_PAGE_SIZES)),
                exceptions: Some(features.contains(WasmFeatures::EXCEPTIONS)),
                legacy_exceptions: Some(features.contains(WasmFeatures::LEGACY_EXCEPTIONS)),
                extended_const: Some(features.contains(WasmFeatures::EXTENDED_CONST)),
                function_references: Some(features.contains(WasmFeatures::FUNCTION_REFERENCES)),
                gc: Some(features.contains(WasmFeatures::GC)),
                gc_support: Some(features.contains(WasmFeatures::GC_TYPES)),
                memory64: Some(features.contains(WasmFeatures::MEMORY64)),
                multi_memory: Some(features.contains(WasmFeatures::MULTI_MEMORY)),
                multi_value: Some(features.contains(WasmFeatures::MULTI_VALUE)),
                reference_types: Some(features.contains(WasmFeatures::REFERENCE_TYPES)),
                relaxed_simd: Some(features.contains(WasmFeatures::RELAXED_SIMD)),
                simd: Some(features.contains(WasmFeatures::SIMD)),
                stack_switching: Some(features.contains(WasmFeatures::STACK_SWITCHING)),
                tail_call: Some(features.contains(WasmFeatures::TAIL_CALL)),
                threads: Some(features.contains(WasmFeatures::THREADS)),
                wide_arithmetic: Some(features.contains(WasmFeatures::WIDE_ARITHMETIC)),
                concurrency_support: Some(engine.get_concurrency_support()),
                epoch_interruption: Some(engine.get_epoch_interruption()),
                fuel: if engine.get_consume_fuel() {
                    Some(1)
                } else {
                    None
                },
                max_wasm_stack: Some(engine.get_max_wasm_stack()),
                nan_canonicalization: engine.get_cranelift_nan_canonicalization(),
                relaxed_simd_deterministic: Some(engine.get_relaxed_simd_deterministic()),
                shared_memory: Some(engine.get_shared_memory()),

                // This is covered by individual `WasmFeatures::*` flags above.
                all_proposals: None,
                // These aren't set in `Config` any more, they're just
                // historical
                max_instances: None,
                max_memories: None,
                max_memory_size: None,
                max_table_elements: None,
                max_tables: None,
                // not part of engine config, specific to `run` command
                timeout: None,
                trap_on_grow_failure: None,
                unknown_exports_allow: None,
                unknown_imports_default: None,
                unknown_imports_trap: None,
                wmemcheck: None,
            },

            // Not currently reflected in `Engine`.
            record: RecordOptions::default(),

            // WASI options aren't reflected in an `Engine`.
            wasi: Default::default(),

            // CLI flags are represented above, they have default values here.
            configured: true,
            ignore_env: false,
            codegen_raw: Default::default(),
            debug_raw: Default::default(),
            opts_raw: Default::default(),
            record_raw: Default::default(),
            wasi_raw: Default::default(),
            wasm_raw: Default::default(),

            // No external configuration file, it's all above.
            config: None,
            //
            // Note that an exhaustive listing is explicitly used to avoid
            // forgetting to configure a field. Please don't add `..something`
            // here at the end.
        }
    }
}

#[cfg(test)]
mod tests {
    use wasmtime::{OptLevel, RegallocAlgorithm};

    use super::*;

    #[test]
    fn from_toml() {
        // empty toml
        let empty_toml = "";
        let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap();
        common_options.config(None).unwrap();

        // basic toml
        let basic_toml = r#"
            [optimize]
            [codegen]
            [debug]
            [wasm]
            [wasi]
            [record]
        "#;
        let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap();
        common_options.config(None).unwrap();

        // toml with custom deserialization to match CLI flag parsing
        for (opt_value, expected) in [
            ("0", Some(OptLevel::None)),
            ("1", Some(OptLevel::Speed)),
            ("2", Some(OptLevel::Speed)),
            ("\"s\"", Some(OptLevel::SpeedAndSize)),
            ("\"hello\"", None), // should fail
            ("3", None),         // should fail
        ] {
            let toml = format!(
                r#"
                    [optimize]
                    opt-level = {opt_value}
                "#,
            );
            let parsed_opt_level = toml::from_str::<CommonOptions>(&toml)
                .ok()
                .and_then(|common_options| common_options.opts.opt_level);

            assert_eq!(
                parsed_opt_level, expected,
                "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}"
            );
        }

        // Regalloc algorithm
        for (regalloc_value, expected) in [
            ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)),
            ("\"single-pass\"", Some(RegallocAlgorithm::SinglePass)),
            ("\"hello\"", None), // should fail
            ("3", None),         // should fail
            ("true", None),      // should fail
        ] {
            let toml = format!(
                r#"
                    [optimize]
                    regalloc-algorithm = {regalloc_value}
                "#,
            );
            let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml)
                .ok()
                .and_then(|common_options| common_options.opts.regalloc_algorithm);
            assert_eq!(
                parsed_regalloc_algorithm, expected,
                "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}"
            );
        }

        // Strategy
        for (strategy_value, expected) in [
            ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)),
            ("\"winch\"", Some(wasmtime::Strategy::Winch)),
            ("\"hello\"", None), // should fail
            ("5", None),         // should fail
            ("true", None),      // should fail
        ] {
            let toml = format!(
                r#"
                    [codegen]
                    compiler = {strategy_value}
                "#,
            );
            let parsed_strategy = toml::from_str::<CommonOptions>(&toml)
                .ok()
                .and_then(|common_options| common_options.codegen.compiler);
            assert_eq!(
                parsed_strategy, expected,
                "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}",
            );
        }

        // Collector
        for (collector_value, expected) in [
            (
                "\"drc\"",
                Some(wasmtime::Collector::DeferredReferenceCounting),
            ),
            ("\"null\"", Some(wasmtime::Collector::Null)),
            ("\"copying\"", Some(wasmtime::Collector::Copying)),
            ("\"hello\"", None), // should fail
            ("5", None),         // should fail
            ("true", None),      // should fail
        ] {
            let toml = format!(
                r#"
                    [codegen]
                    collector = {collector_value}
                "#,
            );
            let parsed_collector = toml::from_str::<CommonOptions>(&toml)
                .ok()
                .and_then(|common_options| common_options.codegen.collector);
            assert_eq!(
                parsed_collector, expected,
                "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}",
            );
        }

        // Timeout: zero is rejected, as it is on the command line
        for (timeout_value, expected) in [
            (
                "{ secs = 5, nanos = 0 }",
                Some(std::time::Duration::from_secs(5)),
            ),
            (
                "{ secs = 0, nanos = 1 }",
                Some(std::time::Duration::from_nanos(1)),
            ),
            ("{ secs = 0, nanos = 0 }", None), // should fail
        ] {
            let toml = format!(
                r#"
                    [wasm]
                    timeout = {timeout_value}
                "#,
            );
            let parsed_timeout = toml::from_str::<CommonOptions>(&toml)
                .ok()
                .and_then(|common_options| common_options.wasm.timeout)
                .map(|timeout| *timeout);
            assert_eq!(
                parsed_timeout, expected,
                "Mismatch for input '{timeout_value}'. Parsed: {parsed_timeout:?}, Expected: {expected:?}",
            );
        }
    }
}

impl Default for CommonOptions {
    fn default() -> CommonOptions {
        CommonOptions::new()
    }
}

impl fmt::Display for CommonOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let CommonOptions {
            codegen_raw,
            codegen,
            debug_raw,
            debug,
            opts_raw,
            opts,
            wasm_raw,
            wasm,
            wasi_raw,
            wasi,
            record_raw,
            record,
            configured,
            ignore_env: _,
            target,
            config,
        } = self;
        if let Some(target) = target {
            write!(f, "--target {target} ")?;
        }
        if let Some(config) = config {
            write!(f, "--config {} ", config.display())?;
        }

        let codegen_flags;
        let opts_flags;
        let wasi_flags;
        let wasm_flags;
        let debug_flags;
        let record_flags;

        if *configured {
            codegen_flags = codegen.to_options();
            debug_flags = debug.to_options();
            wasi_flags = wasi.to_options();
            wasm_flags = wasm.to_options();
            opts_flags = opts.to_options();
            record_flags = record.to_options();
        } else {
            codegen_flags = codegen_raw
                .iter()
                .flat_map(|t| t.0.iter())
                .cloned()
                .collect();
            debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
            wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
            wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
            opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect();
            record_flags = record_raw
                .iter()
                .flat_map(|t| t.0.iter())
                .cloned()
                .collect();
        }

        for flag in codegen_flags {
            write!(f, "-C{flag} ")?;
        }
        for flag in opts_flags {
            write!(f, "-O{flag} ")?;
        }
        for flag in wasi_flags {
            write!(f, "-S{flag} ")?;
        }
        for flag in wasm_flags {
            write!(f, "-W{flag} ")?;
        }
        for flag in debug_flags {
            write!(f, "-D{flag} ")?;
        }
        for flag in record_flags {
            write!(f, "-R{flag} ")?;
        }

        Ok(())
    }
}