1 //! Contains the common Wasmtime command line interface (CLI) flags. 2 3 use anyhow::{Context, Result}; 4 use clap::Parser; 5 use serde::Deserialize; 6 use std::{ 7 fmt, fs, 8 path::{Path, PathBuf}, 9 time::Duration, 10 }; 11 use wasmtime::Config; 12 13 pub mod opt; 14 15 #[cfg(feature = "logging")] 16 fn init_file_per_thread_logger(prefix: &'static str) { 17 file_per_thread_logger::initialize(prefix); 18 file_per_thread_logger::allow_uninitialized(); 19 20 // Extending behavior of default spawner: 21 // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler 22 // Source code says DefaultSpawner is implementation detail and 23 // shouldn't be used directly. 24 #[cfg(feature = "parallel-compilation")] 25 rayon::ThreadPoolBuilder::new() 26 .spawn_handler(move |thread| { 27 let mut b = std::thread::Builder::new(); 28 if let Some(name) = thread.name() { 29 b = b.name(name.to_owned()); 30 } 31 if let Some(stack_size) = thread.stack_size() { 32 b = b.stack_size(stack_size); 33 } 34 b.spawn(move || { 35 file_per_thread_logger::initialize(prefix); 36 thread.run() 37 })?; 38 Ok(()) 39 }) 40 .build_global() 41 .unwrap(); 42 } 43 44 wasmtime_option_group! { 45 #[derive(PartialEq, Clone, Deserialize)] 46 #[serde(rename_all = "kebab-case", deny_unknown_fields)] 47 pub struct OptimizeOptions { 48 /// Optimization level of generated code (0-2, s; default: 2) 49 #[serde(default)] 50 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")] 51 pub opt_level: Option<wasmtime::OptLevel>, 52 53 /// Register allocator algorithm choice. 54 #[serde(default)] 55 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")] 56 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>, 57 58 /// Do not allow Wasm linear memories to move in the host process's 59 /// address space. 60 pub memory_may_move: Option<bool>, 61 62 /// Initial virtual memory allocation size for memories. 63 pub memory_reservation: Option<u64>, 64 65 /// Bytes to reserve at the end of linear memory for growth into. 66 pub memory_reservation_for_growth: Option<u64>, 67 68 /// Size, in bytes, of guard pages for linear memories. 69 pub memory_guard_size: Option<u64>, 70 71 /// Indicates whether an unmapped region of memory is placed before all 72 /// linear memories. 73 pub guard_before_linear_memory: Option<bool>, 74 75 /// Whether to initialize tables lazily, so that instantiation is 76 /// fast but indirect calls are a little slower. If no, tables are 77 /// initialized eagerly from any active element segments that apply to 78 /// them during instantiation. (default: yes) 79 pub table_lazy_init: Option<bool>, 80 81 /// Enable the pooling allocator, in place of the on-demand allocator. 82 pub pooling_allocator: Option<bool>, 83 84 /// The number of decommits to do per batch. A batch size of 1 85 /// effectively disables decommit batching. (default: 1) 86 pub pooling_decommit_batch_size: Option<usize>, 87 88 /// How many bytes to keep resident between instantiations for the 89 /// pooling allocator in linear memories. 90 pub pooling_memory_keep_resident: Option<usize>, 91 92 /// How many bytes to keep resident between instantiations for the 93 /// pooling allocator in tables. 94 pub pooling_table_keep_resident: Option<usize>, 95 96 /// Enable memory protection keys for the pooling allocator; this can 97 /// optimize the size of memory slots. 98 #[serde(default)] 99 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")] 100 pub pooling_memory_protection_keys: Option<wasmtime::Enabled>, 101 102 /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime 103 /// will use. (default: 16) 104 pub pooling_max_memory_protection_keys: Option<usize>, 105 106 /// Configure attempting to initialize linear memory via a 107 /// copy-on-write mapping (default: yes) 108 pub memory_init_cow: Option<bool>, 109 110 /// Threshold below which CoW images are guaranteed to be used and be 111 /// dense. 112 pub memory_guaranteed_dense_image_size: Option<u64>, 113 114 /// The maximum number of WebAssembly instances which can be created 115 /// with the pooling allocator. 116 pub pooling_total_core_instances: Option<u32>, 117 118 /// The maximum number of WebAssembly components which can be created 119 /// with the pooling allocator. 120 pub pooling_total_component_instances: Option<u32>, 121 122 /// The maximum number of WebAssembly memories which can be created with 123 /// the pooling allocator. 124 pub pooling_total_memories: Option<u32>, 125 126 /// The maximum number of WebAssembly tables which can be created with 127 /// the pooling allocator. 128 pub pooling_total_tables: Option<u32>, 129 130 /// The maximum number of WebAssembly stacks which can be created with 131 /// the pooling allocator. 132 pub pooling_total_stacks: Option<u32>, 133 134 /// The maximum runtime size of each linear memory in the pooling 135 /// allocator, in bytes. 136 pub pooling_max_memory_size: Option<usize>, 137 138 /// The maximum table elements for any table defined in a module when 139 /// using the pooling allocator. 140 pub pooling_table_elements: Option<usize>, 141 142 /// The maximum size, in bytes, allocated for a core instance's metadata 143 /// when using the pooling allocator. 144 pub pooling_max_core_instance_size: Option<usize>, 145 146 /// Configures the maximum number of "unused warm slots" to retain in the 147 /// pooling allocator. (default: 100) 148 pub pooling_max_unused_warm_slots: Option<u32>, 149 150 /// How much memory, in bytes, to keep resident for async stacks allocated 151 /// with the pooling allocator. (default: 0) 152 pub pooling_async_stack_keep_resident: Option<usize>, 153 154 /// The maximum size, in bytes, allocated for a component instance's 155 /// `VMComponentContext` metadata. (default: 1MiB) 156 pub pooling_max_component_instance_size: Option<usize>, 157 158 /// The maximum number of core instances a single component may contain 159 /// (default is unlimited). 160 pub pooling_max_core_instances_per_component: Option<u32>, 161 162 /// The maximum number of Wasm linear memories that a single component may 163 /// transitively contain (default is unlimited). 164 pub pooling_max_memories_per_component: Option<u32>, 165 166 /// The maximum number of tables that a single component may transitively 167 /// contain (default is unlimited). 168 pub pooling_max_tables_per_component: Option<u32>, 169 170 /// The maximum number of defined tables for a core module. (default: 1) 171 pub pooling_max_tables_per_module: Option<u32>, 172 173 /// The maximum number of defined linear memories for a module. (default: 1) 174 pub pooling_max_memories_per_module: Option<u32>, 175 176 /// The maximum number of concurrent GC heaps supported. (default: 1000) 177 pub pooling_total_gc_heaps: Option<u32>, 178 179 /// Enable or disable the use of host signal handlers for traps. 180 pub signals_based_traps: Option<bool>, 181 182 /// DEPRECATED: Use `-Cmemory-guard-size=N` instead. 183 pub dynamic_memory_guard_size: Option<u64>, 184 185 /// DEPRECATED: Use `-Cmemory-guard-size=N` instead. 186 pub static_memory_guard_size: Option<u64>, 187 188 /// DEPRECATED: Use `-Cmemory-may-move` instead. 189 pub static_memory_forced: Option<bool>, 190 191 /// DEPRECATED: Use `-Cmemory-reservation=N` instead. 192 pub static_memory_maximum_size: Option<u64>, 193 194 /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead. 195 pub dynamic_memory_reserved_for_growth: Option<u64>, 196 197 /// Whether or not `PAGEMAP_SCAN` ioctls are used to reset linear 198 /// memory. 199 #[serde(default)] 200 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")] 201 pub pooling_pagemap_scan: Option<wasmtime::Enabled>, 202 } 203 204 enum Optimize { 205 ... 206 } 207 } 208 209 wasmtime_option_group! { 210 #[derive(PartialEq, Clone, Deserialize)] 211 #[serde(rename_all = "kebab-case", deny_unknown_fields)] 212 pub struct CodegenOptions { 213 /// Either `cranelift` or `winch`. 214 /// 215 /// Currently only `cranelift` and `winch` are supported, but not all 216 /// builds of Wasmtime have both built in. 217 #[serde(default)] 218 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")] 219 pub compiler: Option<wasmtime::Strategy>, 220 /// Which garbage collector to use: `drc` or `null`. 221 /// 222 /// `drc` is the deferred reference-counting collector. 223 /// 224 /// `null` is the null garbage collector, which does not collect any 225 /// garbage. 226 /// 227 /// Note that not all builds of Wasmtime will have support for garbage 228 /// collection included. 229 #[serde(default)] 230 #[serde(deserialize_with = "crate::opt::cli_parse_wrapper")] 231 pub collector: Option<wasmtime::Collector>, 232 /// Enable Cranelift's internal debug verifier (expensive) 233 pub cranelift_debug_verifier: Option<bool>, 234 /// Whether or not to enable caching of compiled modules. 235 pub cache: Option<bool>, 236 /// Configuration for compiled module caching. 237 pub cache_config: Option<String>, 238 /// Whether or not to enable parallel compilation of modules. 239 pub parallel_compilation: Option<bool>, 240 /// Whether to enable proof-carrying code (PCC)-based validation. 241 pub pcc: Option<bool>, 242 /// Controls whether native unwind information is present in compiled 243 /// object files. 244 pub native_unwind_info: Option<bool>, 245 246 /// Whether to perform function inlining during compilation. 247 pub inlining: Option<bool>, 248 249 #[prefixed = "cranelift"] 250 #[serde(default)] 251 /// Set a cranelift-specific option. Use `wasmtime settings` to see 252 /// all. 253 pub cranelift: Vec<(String, Option<String>)>, 254 } 255 256 enum Codegen { 257 ... 258 } 259 } 260 261 wasmtime_option_group! { 262 #[derive(PartialEq, Clone, Deserialize)] 263 #[serde(rename_all = "kebab-case", deny_unknown_fields)] 264 pub struct DebugOptions { 265 /// Enable generation of DWARF debug information in compiled code. 266 pub debug_info: Option<bool>, 267 /// Configure whether compiled code can map native addresses to wasm. 268 pub address_map: Option<bool>, 269 /// Configure whether logging is enabled. 270 pub logging: Option<bool>, 271 /// Configure whether logs are emitted to files 272 pub log_to_files: Option<bool>, 273 /// Enable coredump generation to this file after a WebAssembly trap. 274 pub coredump: Option<String>, 275 } 276 277 enum Debug { 278 ... 279 } 280 } 281 282 wasmtime_option_group! { 283 #[derive(PartialEq, Clone, Deserialize)] 284 #[serde(rename_all = "kebab-case", deny_unknown_fields)] 285 pub struct WasmOptions { 286 /// Enable canonicalization of all NaN values. 287 pub nan_canonicalization: Option<bool>, 288 /// Enable execution fuel with N units fuel, trapping after running out 289 /// of fuel. 290 /// 291 /// Most WebAssembly instructions consume 1 unit of fuel. Some 292 /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0 293 /// units, as any execution cost associated with them involves other 294 /// instructions which do consume fuel. 295 pub fuel: Option<u64>, 296 /// Yield when a global epoch counter changes, allowing for async 297 /// operation without blocking the executor. 298 pub epoch_interruption: Option<bool>, 299 /// Maximum stack size, in bytes, that wasm is allowed to consume before a 300 /// stack overflow is reported. 301 pub max_wasm_stack: Option<usize>, 302 /// Stack size, in bytes, that will be allocated for async stacks. 303 /// 304 /// Note that this must be larger than `max-wasm-stack` and the 305 /// difference between the two is how much stack the host has to execute 306 /// on. 307 pub async_stack_size: Option<usize>, 308 /// Configures whether or not stacks used for async futures are zeroed 309 /// before (re)use as a defense-in-depth mechanism. (default: false) 310 pub async_stack_zeroing: Option<bool>, 311 /// Allow unknown exports when running commands. 312 pub unknown_exports_allow: Option<bool>, 313 /// Allow the main module to import unknown functions, using an 314 /// implementation that immediately traps, when running commands. 315 pub unknown_imports_trap: Option<bool>, 316 /// Allow the main module to import unknown functions, using an 317 /// implementation that returns default values, when running commands. 318 pub unknown_imports_default: Option<bool>, 319 /// Enables memory error checking. (see wmemcheck.md for more info) 320 pub wmemcheck: Option<bool>, 321 /// Maximum size, in bytes, that a linear memory is allowed to reach. 322 /// 323 /// Growth beyond this limit will cause `memory.grow` instructions in 324 /// WebAssembly modules to return -1 and fail. 325 pub max_memory_size: Option<usize>, 326 /// Maximum size, in table elements, that a table is allowed to reach. 327 pub max_table_elements: Option<usize>, 328 /// Maximum number of WebAssembly instances allowed to be created. 329 pub max_instances: Option<usize>, 330 /// Maximum number of WebAssembly tables allowed to be created. 331 pub max_tables: Option<usize>, 332 /// Maximum number of WebAssembly linear memories allowed to be created. 333 pub max_memories: Option<usize>, 334 /// Force a trap to be raised on `memory.grow` and `table.grow` failure 335 /// instead of returning -1 from these instructions. 336 /// 337 /// This is not necessarily a spec-compliant option to enable but can be 338 /// useful for tracking down a backtrace of what is requesting so much 339 /// memory, for example. 340 pub trap_on_grow_failure: Option<bool>, 341 /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc) 342 pub timeout: Option<Duration>, 343 /// Configures support for all WebAssembly proposals implemented. 344 pub all_proposals: Option<bool>, 345 /// Configure support for the bulk memory proposal. 346 pub bulk_memory: Option<bool>, 347 /// Configure support for the multi-memory proposal. 348 pub multi_memory: Option<bool>, 349 /// Configure support for the multi-value proposal. 350 pub multi_value: Option<bool>, 351 /// Configure support for the reference-types proposal. 352 pub reference_types: Option<bool>, 353 /// Configure support for the simd proposal. 354 pub simd: Option<bool>, 355 /// Configure support for the relaxed-simd proposal. 356 pub relaxed_simd: Option<bool>, 357 /// Configure forcing deterministic and host-independent behavior of 358 /// the relaxed-simd instructions. 359 /// 360 /// By default these instructions may have architecture-specific behavior as 361 /// allowed by the specification, but this can be used to force the behavior 362 /// of these instructions to match the deterministic behavior classified in 363 /// the specification. Note that enabling this option may come at a 364 /// performance cost. 365 pub relaxed_simd_deterministic: Option<bool>, 366 /// Configure support for the tail-call proposal. 367 pub tail_call: Option<bool>, 368 /// Configure support for the threads proposal. 369 pub threads: Option<bool>, 370 /// Configure support for the shared-everything-threads proposal. 371 pub shared_everything_threads: Option<bool>, 372 /// Configure support for the memory64 proposal. 373 pub memory64: Option<bool>, 374 /// Configure support for the component-model proposal. 375 pub component_model: Option<bool>, 376 /// Component model support for async lifting/lowering. 377 pub component_model_async: Option<bool>, 378 /// Component model support for async lifting/lowering: this corresponds 379 /// to the emoji in the component model specification. 380 pub component_model_async_builtins: Option<bool>, 381 /// Component model support for async lifting/lowering: this corresponds 382 /// to the emoji in the component model specification. 383 pub component_model_async_stackful: Option<bool>, 384 /// Component model support for `error-context`: this corresponds 385 /// to the emoji in the component model specification. 386 pub component_model_error_context: Option<bool>, 387 /// GC support in the component model: this corresponds to the emoji 388 /// in the component model specification. 389 pub component_model_gc: Option<bool>, 390 /// Configure support for the function-references proposal. 391 pub function_references: Option<bool>, 392 /// Configure support for the stack-switching proposal. 393 pub stack_switching: Option<bool>, 394 /// Configure support for the GC proposal. 395 pub gc: Option<bool>, 396 /// Configure support for the custom-page-sizes proposal. 397 pub custom_page_sizes: Option<bool>, 398 /// Configure support for the wide-arithmetic proposal. 399 pub wide_arithmetic: Option<bool>, 400 /// Configure support for the extended-const proposal. 401 pub extended_const: Option<bool>, 402 /// Configure support for the exceptions proposal. 403 pub exceptions: Option<bool>, 404 /// DEPRECATED: Configure support for the legacy exceptions proposal. 405 pub legacy_exceptions: Option<bool>, 406 /// Whether or not any GC infrastructure in Wasmtime is enabled or not. 407 pub gc_support: Option<bool>, 408 } 409 410 enum Wasm { 411 ... 412 } 413 } 414 415 wasmtime_option_group! { 416 #[derive(PartialEq, Clone, Deserialize)] 417 #[serde(rename_all = "kebab-case", deny_unknown_fields)] 418 pub struct WasiOptions { 419 /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random. 420 pub cli: Option<bool>, 421 /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code) 422 pub cli_exit_with_code: Option<bool>, 423 /// Deprecated alias for `cli` 424 pub common: Option<bool>, 425 /// Enable support for WASI neural network imports (experimental) 426 pub nn: Option<bool>, 427 /// Enable support for WASI threading imports (experimental). Implies preview2=false. 428 pub threads: Option<bool>, 429 /// Enable support for WASI HTTP imports 430 pub http: Option<bool>, 431 /// Number of distinct write calls to the outgoing body's output-stream 432 /// that the implementation will buffer. 433 /// Default: 1. 434 pub http_outgoing_body_buffer_chunks: Option<usize>, 435 /// Maximum size allowed in a write call to the outgoing body's output-stream. 436 /// Default: 1024 * 1024. 437 pub http_outgoing_body_chunk_size: Option<usize>, 438 /// Enable support for WASI config imports (experimental) 439 pub config: Option<bool>, 440 /// Enable support for WASI key-value imports (experimental) 441 pub keyvalue: Option<bool>, 442 /// Inherit environment variables and file descriptors following the 443 /// systemd listen fd specification (UNIX only) (legacy wasip1 444 /// implementation only) 445 pub listenfd: Option<bool>, 446 /// Grant access to the given TCP listen socket (experimental, legacy 447 /// wasip1 implementation only) 448 #[serde(default)] 449 pub tcplisten: Vec<String>, 450 /// Enable support for WASI TLS (Transport Layer Security) imports (experimental) 451 pub tls: Option<bool>, 452 /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy 453 /// implementation (false) 454 pub preview2: Option<bool>, 455 /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn. 456 /// 457 /// Each use of the flag will preload a ML model from the host directory 458 /// using the given model encoding. The model will be mapped to the 459 /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload 460 /// an OpenVINO model named `bar`. Note that which model encodings are 461 /// available is dependent on the backends implemented in the 462 /// `wasmtime_wasi_nn` crate. 463 #[serde(skip)] 464 pub nn_graph: Vec<WasiNnGraph>, 465 /// Flag for WASI preview2 to inherit the host's network within the 466 /// guest so it has full access to all addresses/ports/etc. 467 pub inherit_network: Option<bool>, 468 /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not. 469 pub allow_ip_name_lookup: Option<bool>, 470 /// Indicates whether `wasi:sockets` TCP support is enabled or not. 471 pub tcp: Option<bool>, 472 /// Indicates whether `wasi:sockets` UDP support is enabled or not. 473 pub udp: Option<bool>, 474 /// Enable WASI APIs marked as: @unstable(feature = network-error-code) 475 pub network_error_code: Option<bool>, 476 /// Allows imports from the `wasi_unstable` core wasm module. 477 pub preview0: Option<bool>, 478 /// Inherit all environment variables from the parent process. 479 /// 480 /// This option can be further overwritten with `--env` flags. 481 pub inherit_env: Option<bool>, 482 /// Pass a wasi config variable to the program. 483 #[serde(skip)] 484 pub config_var: Vec<KeyValuePair>, 485 /// Preset data for the In-Memory provider of WASI key-value API. 486 #[serde(skip)] 487 pub keyvalue_in_memory_data: Vec<KeyValuePair>, 488 /// Enable support for WASIp3 APIs. 489 pub p3: Option<bool>, 490 } 491 492 enum Wasi { 493 ... 494 } 495 } 496 497 #[derive(Debug, Clone, PartialEq)] 498 pub struct WasiNnGraph { 499 pub format: String, 500 pub dir: String, 501 } 502 503 #[derive(Debug, Clone, PartialEq)] 504 pub struct KeyValuePair { 505 pub key: String, 506 pub value: String, 507 } 508 509 /// Common options for commands that translate WebAssembly modules 510 #[derive(Parser, Clone, Deserialize)] 511 #[serde(deny_unknown_fields)] 512 pub struct CommonOptions { 513 // These options groups are used to parse `-O` and such options but aren't 514 // the raw form consumed by the CLI. Instead they're pushed into the `pub` 515 // fields below as part of the `configure` method. 516 // 517 // Ideally clap would support `pub opts: OptimizeOptions` and parse directly 518 // into that but it does not appear to do so for multiple `-O` flags for 519 // now. 520 /// Optimization and tuning related options for wasm performance, `-O help` to 521 /// see all. 522 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")] 523 #[serde(skip)] 524 opts_raw: Vec<opt::CommaSeparated<Optimize>>, 525 526 /// Codegen-related configuration options, `-C help` to see all. 527 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")] 528 #[serde(skip)] 529 codegen_raw: Vec<opt::CommaSeparated<Codegen>>, 530 531 /// Debug-related configuration options, `-D help` to see all. 532 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")] 533 #[serde(skip)] 534 debug_raw: Vec<opt::CommaSeparated<Debug>>, 535 536 /// Options for configuring semantic execution of WebAssembly, `-W help` to see 537 /// all. 538 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")] 539 #[serde(skip)] 540 wasm_raw: Vec<opt::CommaSeparated<Wasm>>, 541 542 /// Options for configuring WASI and its proposals, `-S help` to see all. 543 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")] 544 #[serde(skip)] 545 wasi_raw: Vec<opt::CommaSeparated<Wasi>>, 546 547 // These fields are filled in by the `configure` method below via the 548 // options parsed from the CLI above. This is what the CLI should use. 549 #[arg(skip)] 550 #[serde(skip)] 551 configured: bool, 552 553 #[arg(skip)] 554 #[serde(rename = "optimize", default)] 555 pub opts: OptimizeOptions, 556 557 #[arg(skip)] 558 #[serde(rename = "codegen", default)] 559 pub codegen: CodegenOptions, 560 561 #[arg(skip)] 562 #[serde(rename = "debug", default)] 563 pub debug: DebugOptions, 564 565 #[arg(skip)] 566 #[serde(rename = "wasm", default)] 567 pub wasm: WasmOptions, 568 569 #[arg(skip)] 570 #[serde(rename = "wasi", default)] 571 pub wasi: WasiOptions, 572 573 /// The target triple; default is the host triple 574 #[arg(long, value_name = "TARGET")] 575 #[serde(skip)] 576 pub target: Option<String>, 577 578 /// Use the specified TOML configuration file. 579 /// This TOML configuration file can provide same configuration options as the 580 /// `--optimize`, `--codgen`, `--debug`, `--wasm`, `--wasi` CLI options, with a couple exceptions. 581 /// 582 /// Additional options specified on the command line will take precedent over options loaded from 583 /// this TOML file. 584 #[arg(long = "config", value_name = "FILE")] 585 #[serde(skip)] 586 pub config: Option<PathBuf>, 587 } 588 589 macro_rules! match_feature { 590 ( 591 [$feat:tt : $config:expr] 592 $val:ident => $e:expr, 593 $p:pat => err, 594 ) => { 595 #[cfg(feature = $feat)] 596 { 597 if let Some($val) = $config { 598 $e; 599 } 600 } 601 #[cfg(not(feature = $feat))] 602 { 603 if let Some($p) = $config { 604 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time")); 605 } 606 } 607 }; 608 } 609 610 impl CommonOptions { 611 /// Creates a blank new set of [`CommonOptions`] that can be configured. 612 pub fn new() -> CommonOptions { 613 CommonOptions { 614 opts_raw: Vec::new(), 615 codegen_raw: Vec::new(), 616 debug_raw: Vec::new(), 617 wasm_raw: Vec::new(), 618 wasi_raw: Vec::new(), 619 configured: true, 620 opts: Default::default(), 621 codegen: Default::default(), 622 debug: Default::default(), 623 wasm: Default::default(), 624 wasi: Default::default(), 625 target: None, 626 config: None, 627 } 628 } 629 630 fn configure(&mut self) -> Result<()> { 631 if self.configured { 632 return Ok(()); 633 } 634 self.configured = true; 635 if let Some(toml_config_path) = &self.config { 636 let toml_options = CommonOptions::from_file(toml_config_path)?; 637 self.opts = toml_options.opts; 638 self.codegen = toml_options.codegen; 639 self.debug = toml_options.debug; 640 self.wasm = toml_options.wasm; 641 self.wasi = toml_options.wasi; 642 } 643 self.opts.configure_with(&self.opts_raw); 644 self.codegen.configure_with(&self.codegen_raw); 645 self.debug.configure_with(&self.debug_raw); 646 self.wasm.configure_with(&self.wasm_raw); 647 self.wasi.configure_with(&self.wasi_raw); 648 Ok(()) 649 } 650 651 pub fn init_logging(&mut self) -> Result<()> { 652 self.configure()?; 653 if self.debug.logging == Some(false) { 654 return Ok(()); 655 } 656 #[cfg(feature = "logging")] 657 if self.debug.log_to_files == Some(true) { 658 let prefix = "wasmtime.dbg."; 659 init_file_per_thread_logger(prefix); 660 } else { 661 use std::io::IsTerminal; 662 use tracing_subscriber::{EnvFilter, FmtSubscriber}; 663 let builder = FmtSubscriber::builder() 664 .with_writer(std::io::stderr) 665 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG")) 666 .with_ansi(std::io::stderr().is_terminal()); 667 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) { 668 builder 669 .with_level(false) 670 .with_target(false) 671 .without_time() 672 .init() 673 } else { 674 builder.init(); 675 } 676 } 677 #[cfg(not(feature = "logging"))] 678 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) { 679 anyhow::bail!("support for logging disabled at compile time"); 680 } 681 Ok(()) 682 } 683 684 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> { 685 self.configure()?; 686 let mut config = Config::new(); 687 688 match_feature! { 689 ["cranelift" : self.codegen.compiler] 690 strategy => config.strategy(strategy), 691 _ => err, 692 } 693 match_feature! { 694 ["gc" : self.codegen.collector] 695 collector => config.collector(collector), 696 _ => err, 697 } 698 if let Some(target) = &self.target { 699 config.target(target)?; 700 } 701 match_feature! { 702 ["cranelift" : self.codegen.cranelift_debug_verifier] 703 enable => config.cranelift_debug_verifier(enable), 704 true => err, 705 } 706 if let Some(enable) = self.debug.debug_info { 707 config.debug_info(enable); 708 } 709 if self.debug.coredump.is_some() { 710 #[cfg(feature = "coredump")] 711 config.coredump_on_trap(true); 712 #[cfg(not(feature = "coredump"))] 713 anyhow::bail!("support for coredumps disabled at compile time"); 714 } 715 match_feature! { 716 ["cranelift" : self.opts.opt_level] 717 level => config.cranelift_opt_level(level), 718 _ => err, 719 } 720 match_feature! { 721 ["cranelift": self.opts.regalloc_algorithm] 722 algo => config.cranelift_regalloc_algorithm(algo), 723 _ => err, 724 } 725 match_feature! { 726 ["cranelift" : self.wasm.nan_canonicalization] 727 enable => config.cranelift_nan_canonicalization(enable), 728 true => err, 729 } 730 match_feature! { 731 ["cranelift" : self.codegen.pcc] 732 enable => config.cranelift_pcc(enable), 733 true => err, 734 } 735 736 self.enable_wasm_features(&mut config)?; 737 738 #[cfg(feature = "cranelift")] 739 for (name, value) in self.codegen.cranelift.iter() { 740 let name = name.replace('-', "_"); 741 unsafe { 742 match value { 743 Some(val) => { 744 config.cranelift_flag_set(&name, val); 745 } 746 None => { 747 config.cranelift_flag_enable(&name); 748 } 749 } 750 } 751 } 752 #[cfg(not(feature = "cranelift"))] 753 if !self.codegen.cranelift.is_empty() { 754 anyhow::bail!("support for cranelift disabled at compile time"); 755 } 756 757 #[cfg(feature = "cache")] 758 if self.codegen.cache != Some(false) { 759 use wasmtime::Cache; 760 let cache = match &self.codegen.cache_config { 761 Some(path) => Cache::from_file(Some(Path::new(path)))?, 762 None => Cache::from_file(None)?, 763 }; 764 config.cache(Some(cache)); 765 } 766 #[cfg(not(feature = "cache"))] 767 if self.codegen.cache == Some(true) { 768 anyhow::bail!("support for caching disabled at compile time"); 769 } 770 771 match_feature! { 772 ["parallel-compilation" : self.codegen.parallel_compilation] 773 enable => config.parallel_compilation(enable), 774 true => err, 775 } 776 777 let memory_reservation = self 778 .opts 779 .memory_reservation 780 .or(self.opts.static_memory_maximum_size); 781 if let Some(size) = memory_reservation { 782 config.memory_reservation(size); 783 } 784 785 if let Some(enable) = self.opts.static_memory_forced { 786 config.memory_may_move(!enable); 787 } 788 if let Some(enable) = self.opts.memory_may_move { 789 config.memory_may_move(enable); 790 } 791 792 let memory_guard_size = self 793 .opts 794 .static_memory_guard_size 795 .or(self.opts.dynamic_memory_guard_size) 796 .or(self.opts.memory_guard_size); 797 if let Some(size) = memory_guard_size { 798 config.memory_guard_size(size); 799 } 800 801 let mem_for_growth = self 802 .opts 803 .memory_reservation_for_growth 804 .or(self.opts.dynamic_memory_reserved_for_growth); 805 if let Some(size) = mem_for_growth { 806 config.memory_reservation_for_growth(size); 807 } 808 if let Some(enable) = self.opts.guard_before_linear_memory { 809 config.guard_before_linear_memory(enable); 810 } 811 if let Some(enable) = self.opts.table_lazy_init { 812 config.table_lazy_init(enable); 813 } 814 815 // If fuel has been configured, set the `consume fuel` flag on the config. 816 if self.wasm.fuel.is_some() { 817 config.consume_fuel(true); 818 } 819 820 if let Some(enable) = self.wasm.epoch_interruption { 821 config.epoch_interruption(enable); 822 } 823 if let Some(enable) = self.debug.address_map { 824 config.generate_address_map(enable); 825 } 826 if let Some(enable) = self.opts.memory_init_cow { 827 config.memory_init_cow(enable); 828 } 829 if let Some(size) = self.opts.memory_guaranteed_dense_image_size { 830 config.memory_guaranteed_dense_image_size(size); 831 } 832 if let Some(enable) = self.opts.signals_based_traps { 833 config.signals_based_traps(enable); 834 } 835 if let Some(enable) = self.codegen.native_unwind_info { 836 config.native_unwind_info(enable); 837 } 838 if let Some(enable) = self.codegen.inlining { 839 config.compiler_inlining(enable); 840 } 841 842 // async_stack_size enabled by either async or stack-switching, so 843 // cannot directly use match_feature! 844 #[cfg(any(feature = "async", feature = "stack-switching"))] 845 { 846 if let Some(size) = self.wasm.async_stack_size { 847 config.async_stack_size(size); 848 } 849 } 850 #[cfg(not(any(feature = "async", feature = "stack-switching")))] 851 { 852 if let Some(_size) = self.wasm.async_stack_size { 853 anyhow::bail!(concat!( 854 "support for async/stack-switching disabled at compile time" 855 )); 856 } 857 } 858 859 match_feature! { 860 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)] 861 enable => { 862 if enable { 863 let mut cfg = wasmtime::PoolingAllocationConfig::default(); 864 if let Some(size) = self.opts.pooling_memory_keep_resident { 865 cfg.linear_memory_keep_resident(size); 866 } 867 if let Some(size) = self.opts.pooling_table_keep_resident { 868 cfg.table_keep_resident(size); 869 } 870 if let Some(limit) = self.opts.pooling_total_core_instances { 871 cfg.total_core_instances(limit); 872 } 873 if let Some(limit) = self.opts.pooling_total_component_instances { 874 cfg.total_component_instances(limit); 875 } 876 if let Some(limit) = self.opts.pooling_total_memories { 877 cfg.total_memories(limit); 878 } 879 if let Some(limit) = self.opts.pooling_total_tables { 880 cfg.total_tables(limit); 881 } 882 if let Some(limit) = self.opts.pooling_table_elements 883 .or(self.wasm.max_table_elements) 884 { 885 cfg.table_elements(limit); 886 } 887 if let Some(limit) = self.opts.pooling_max_core_instance_size { 888 cfg.max_core_instance_size(limit); 889 } 890 match_feature! { 891 ["async" : self.opts.pooling_total_stacks] 892 limit => cfg.total_stacks(limit), 893 _ => err, 894 } 895 if let Some(max) = self.opts.pooling_max_memory_size 896 .or(self.wasm.max_memory_size) 897 { 898 cfg.max_memory_size(max); 899 } 900 if let Some(size) = self.opts.pooling_decommit_batch_size { 901 cfg.decommit_batch_size(size); 902 } 903 if let Some(max) = self.opts.pooling_max_unused_warm_slots { 904 cfg.max_unused_warm_slots(max); 905 } 906 match_feature! { 907 ["async" : self.opts.pooling_async_stack_keep_resident] 908 size => cfg.async_stack_keep_resident(size), 909 _ => err, 910 } 911 if let Some(max) = self.opts.pooling_max_component_instance_size { 912 cfg.max_component_instance_size(max); 913 } 914 if let Some(max) = self.opts.pooling_max_core_instances_per_component { 915 cfg.max_core_instances_per_component(max); 916 } 917 if let Some(max) = self.opts.pooling_max_memories_per_component { 918 cfg.max_memories_per_component(max); 919 } 920 if let Some(max) = self.opts.pooling_max_tables_per_component { 921 cfg.max_tables_per_component(max); 922 } 923 if let Some(max) = self.opts.pooling_max_tables_per_module { 924 cfg.max_tables_per_module(max); 925 } 926 if let Some(max) = self.opts.pooling_max_memories_per_module { 927 cfg.max_memories_per_module(max); 928 } 929 match_feature! { 930 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys] 931 enable => cfg.memory_protection_keys(enable), 932 _ => err, 933 } 934 match_feature! { 935 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys] 936 max => cfg.max_memory_protection_keys(max), 937 _ => err, 938 } 939 match_feature! { 940 ["gc" : self.opts.pooling_total_gc_heaps] 941 max => cfg.total_gc_heaps(max), 942 _ => err, 943 } 944 if let Some(enabled) = self.opts.pooling_pagemap_scan { 945 cfg.pagemap_scan(enabled); 946 } 947 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg)); 948 } 949 }, 950 true => err, 951 } 952 953 if self.opts.pooling_memory_protection_keys.is_some() 954 && !self.opts.pooling_allocator.unwrap_or(false) 955 { 956 anyhow::bail!("memory protection keys require the pooling allocator"); 957 } 958 959 if self.opts.pooling_max_memory_protection_keys.is_some() 960 && !self.opts.pooling_memory_protection_keys.is_some() 961 { 962 anyhow::bail!( 963 "max memory protection keys requires memory protection keys to be enabled" 964 ); 965 } 966 967 match_feature! { 968 ["async" : self.wasm.async_stack_zeroing] 969 enable => config.async_stack_zeroing(enable), 970 _ => err, 971 } 972 973 if let Some(max) = self.wasm.max_wasm_stack { 974 config.max_wasm_stack(max); 975 976 // If `-Wasync-stack-size` isn't passed then automatically adjust it 977 // to the wasm stack size provided here too. That prevents the need 978 // to pass both when one can generally be inferred from the other. 979 #[cfg(any(feature = "async", feature = "stack-switching"))] 980 if self.wasm.async_stack_size.is_none() { 981 const DEFAULT_HOST_STACK: usize = 512 << 10; 982 config.async_stack_size(max + DEFAULT_HOST_STACK); 983 } 984 } 985 986 if let Some(enable) = self.wasm.relaxed_simd_deterministic { 987 config.relaxed_simd_deterministic(enable); 988 } 989 match_feature! { 990 ["cranelift" : self.wasm.wmemcheck] 991 enable => config.wmemcheck(enable), 992 true => err, 993 } 994 995 if let Some(enable) = self.wasm.gc_support { 996 config.gc_support(enable); 997 } 998 999 Ok(config) 1000 } 1001 1002 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> { 1003 let all = self.wasm.all_proposals; 1004 1005 if let Some(enable) = self.wasm.simd.or(all) { 1006 config.wasm_simd(enable); 1007 } 1008 if let Some(enable) = self.wasm.relaxed_simd.or(all) { 1009 config.wasm_relaxed_simd(enable); 1010 } 1011 if let Some(enable) = self.wasm.bulk_memory.or(all) { 1012 config.wasm_bulk_memory(enable); 1013 } 1014 if let Some(enable) = self.wasm.multi_value.or(all) { 1015 config.wasm_multi_value(enable); 1016 } 1017 if let Some(enable) = self.wasm.tail_call.or(all) { 1018 config.wasm_tail_call(enable); 1019 } 1020 if let Some(enable) = self.wasm.multi_memory.or(all) { 1021 config.wasm_multi_memory(enable); 1022 } 1023 if let Some(enable) = self.wasm.memory64.or(all) { 1024 config.wasm_memory64(enable); 1025 } 1026 if let Some(enable) = self.wasm.stack_switching { 1027 config.wasm_stack_switching(enable); 1028 } 1029 if let Some(enable) = self.wasm.custom_page_sizes.or(all) { 1030 config.wasm_custom_page_sizes(enable); 1031 } 1032 if let Some(enable) = self.wasm.wide_arithmetic.or(all) { 1033 config.wasm_wide_arithmetic(enable); 1034 } 1035 if let Some(enable) = self.wasm.extended_const.or(all) { 1036 config.wasm_extended_const(enable); 1037 } 1038 if let Some(enable) = self.wasm.exceptions.or(all) { 1039 config.wasm_exceptions(enable); 1040 } 1041 if let Some(enable) = self.wasm.legacy_exceptions.or(all) { 1042 #[expect(deprecated, reason = "forwarding CLI flag")] 1043 config.wasm_legacy_exceptions(enable); 1044 } 1045 1046 macro_rules! handle_conditionally_compiled { 1047 ($(($feature:tt, $field:tt, $method:tt))*) => ($( 1048 if let Some(enable) = self.wasm.$field.or(all) { 1049 #[cfg(feature = $feature)] 1050 config.$method(enable); 1051 #[cfg(not(feature = $feature))] 1052 if enable && all.is_none() { 1053 anyhow::bail!("support for {} was disabled at compile-time", $feature); 1054 } 1055 } 1056 )*) 1057 } 1058 1059 handle_conditionally_compiled! { 1060 ("component-model", component_model, wasm_component_model) 1061 ("component-model-async", component_model_async, wasm_component_model_async) 1062 ("component-model-async", component_model_async_builtins, wasm_component_model_async_builtins) 1063 ("component-model-async", component_model_async_stackful, wasm_component_model_async_stackful) 1064 ("component-model", component_model_error_context, wasm_component_model_error_context) 1065 ("threads", threads, wasm_threads) 1066 ("gc", gc, wasm_gc) 1067 ("gc", reference_types, wasm_reference_types) 1068 ("gc", function_references, wasm_function_references) 1069 ("stack-switching", stack_switching, wasm_stack_switching) 1070 } 1071 1072 if let Some(enable) = self.wasm.component_model_gc { 1073 #[cfg(all(feature = "component-model", feature = "gc"))] 1074 config.wasm_component_model_gc(enable); 1075 #[cfg(not(all(feature = "component-model", feature = "gc")))] 1076 if enable && all.is_none() { 1077 anyhow::bail!("support for `component-model-gc` was disabled at compile time") 1078 } 1079 } 1080 1081 Ok(()) 1082 } 1083 1084 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> { 1085 let path_ref = path.as_ref(); 1086 let file_contents = fs::read_to_string(path_ref) 1087 .with_context(|| format!("failed to read config file: {path_ref:?}"))?; 1088 toml::from_str::<CommonOptions>(&file_contents) 1089 .with_context(|| format!("failed to parse TOML config file {path_ref:?}")) 1090 } 1091 } 1092 1093 #[cfg(test)] 1094 mod tests { 1095 use wasmtime::{OptLevel, RegallocAlgorithm}; 1096 1097 use super::*; 1098 1099 #[test] 1100 fn from_toml() { 1101 // empty toml 1102 let empty_toml = ""; 1103 let mut common_options: CommonOptions = toml::from_str(empty_toml).unwrap(); 1104 common_options.config(None).unwrap(); 1105 1106 // basic toml 1107 let basic_toml = r#" 1108 [optimize] 1109 [codegen] 1110 [debug] 1111 [wasm] 1112 [wasi] 1113 "#; 1114 let mut common_options: CommonOptions = toml::from_str(basic_toml).unwrap(); 1115 common_options.config(None).unwrap(); 1116 1117 // toml with custom deserialization to match CLI flag parsing 1118 for (opt_value, expected) in [ 1119 ("0", Some(OptLevel::None)), 1120 ("1", Some(OptLevel::Speed)), 1121 ("2", Some(OptLevel::Speed)), 1122 ("\"s\"", Some(OptLevel::SpeedAndSize)), 1123 ("\"hello\"", None), // should fail 1124 ("3", None), // should fail 1125 ] { 1126 let toml = format!( 1127 r#" 1128 [optimize] 1129 opt-level = {opt_value} 1130 "#, 1131 ); 1132 let parsed_opt_level = toml::from_str::<CommonOptions>(&toml) 1133 .ok() 1134 .and_then(|common_options| common_options.opts.opt_level); 1135 1136 assert_eq!( 1137 parsed_opt_level, expected, 1138 "Mismatch for input '{opt_value}'. Parsed: {parsed_opt_level:?}, Expected: {expected:?}" 1139 ); 1140 } 1141 1142 // Regalloc algorithm 1143 for (regalloc_value, expected) in [ 1144 ("\"backtracking\"", Some(RegallocAlgorithm::Backtracking)), 1145 ("\"hello\"", None), // should fail 1146 ("3", None), // should fail 1147 ("true", None), // should fail 1148 ] { 1149 let toml = format!( 1150 r#" 1151 [optimize] 1152 regalloc-algorithm = {regalloc_value} 1153 "#, 1154 ); 1155 let parsed_regalloc_algorithm = toml::from_str::<CommonOptions>(&toml) 1156 .ok() 1157 .and_then(|common_options| common_options.opts.regalloc_algorithm); 1158 assert_eq!( 1159 parsed_regalloc_algorithm, expected, 1160 "Mismatch for input '{regalloc_value}'. Parsed: {parsed_regalloc_algorithm:?}, Expected: {expected:?}" 1161 ); 1162 } 1163 1164 // Strategy 1165 for (strategy_value, expected) in [ 1166 ("\"cranelift\"", Some(wasmtime::Strategy::Cranelift)), 1167 ("\"winch\"", Some(wasmtime::Strategy::Winch)), 1168 ("\"hello\"", None), // should fail 1169 ("5", None), // should fail 1170 ("true", None), // should fail 1171 ] { 1172 let toml = format!( 1173 r#" 1174 [codegen] 1175 compiler = {strategy_value} 1176 "#, 1177 ); 1178 let parsed_strategy = toml::from_str::<CommonOptions>(&toml) 1179 .ok() 1180 .and_then(|common_options| common_options.codegen.compiler); 1181 assert_eq!( 1182 parsed_strategy, expected, 1183 "Mismatch for input '{strategy_value}'. Parsed: {parsed_strategy:?}, Expected: {expected:?}", 1184 ); 1185 } 1186 1187 // Collector 1188 for (collector_value, expected) in [ 1189 ( 1190 "\"drc\"", 1191 Some(wasmtime::Collector::DeferredReferenceCounting), 1192 ), 1193 ("\"null\"", Some(wasmtime::Collector::Null)), 1194 ("\"hello\"", None), // should fail 1195 ("5", None), // should fail 1196 ("true", None), // should fail 1197 ] { 1198 let toml = format!( 1199 r#" 1200 [codegen] 1201 collector = {collector_value} 1202 "#, 1203 ); 1204 let parsed_collector = toml::from_str::<CommonOptions>(&toml) 1205 .ok() 1206 .and_then(|common_options| common_options.codegen.collector); 1207 assert_eq!( 1208 parsed_collector, expected, 1209 "Mismatch for input '{collector_value}'. Parsed: {parsed_collector:?}, Expected: {expected:?}", 1210 ); 1211 } 1212 } 1213 } 1214 1215 impl Default for CommonOptions { 1216 fn default() -> CommonOptions { 1217 CommonOptions::new() 1218 } 1219 } 1220 1221 impl fmt::Display for CommonOptions { 1222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1223 let CommonOptions { 1224 codegen_raw, 1225 codegen, 1226 debug_raw, 1227 debug, 1228 opts_raw, 1229 opts, 1230 wasm_raw, 1231 wasm, 1232 wasi_raw, 1233 wasi, 1234 configured, 1235 target, 1236 config, 1237 } = self; 1238 if let Some(target) = target { 1239 write!(f, "--target {target} ")?; 1240 } 1241 if let Some(config) = config { 1242 write!(f, "--config {} ", config.display())?; 1243 } 1244 1245 let codegen_flags; 1246 let opts_flags; 1247 let wasi_flags; 1248 let wasm_flags; 1249 let debug_flags; 1250 1251 if *configured { 1252 codegen_flags = codegen.to_options(); 1253 debug_flags = debug.to_options(); 1254 wasi_flags = wasi.to_options(); 1255 wasm_flags = wasm.to_options(); 1256 opts_flags = opts.to_options(); 1257 } else { 1258 codegen_flags = codegen_raw 1259 .iter() 1260 .flat_map(|t| t.0.iter()) 1261 .cloned() 1262 .collect(); 1263 debug_flags = debug_raw.iter().flat_map(|t| t.0.iter()).cloned().collect(); 1264 wasi_flags = wasi_raw.iter().flat_map(|t| t.0.iter()).cloned().collect(); 1265 wasm_flags = wasm_raw.iter().flat_map(|t| t.0.iter()).cloned().collect(); 1266 opts_flags = opts_raw.iter().flat_map(|t| t.0.iter()).cloned().collect(); 1267 } 1268 1269 for flag in codegen_flags { 1270 write!(f, "-C{flag} ")?; 1271 } 1272 for flag in opts_flags { 1273 write!(f, "-O{flag} ")?; 1274 } 1275 for flag in wasi_flags { 1276 write!(f, "-S{flag} ")?; 1277 } 1278 for flag in wasm_flags { 1279 write!(f, "-W{flag} ")?; 1280 } 1281 for flag in debug_flags { 1282 write!(f, "-D{flag} ")?; 1283 } 1284 1285 Ok(()) 1286 } 1287 } 1288