1 //! Contains the common Wasmtime command line interface (CLI) flags. 2 3 use anyhow::Result; 4 use clap::Parser; 5 use std::time::Duration; 6 use wasmtime::Config; 7 8 pub mod opt; 9 10 #[cfg(feature = "logging")] 11 fn init_file_per_thread_logger(prefix: &'static str) { 12 file_per_thread_logger::initialize(prefix); 13 file_per_thread_logger::allow_uninitialized(); 14 15 // Extending behavior of default spawner: 16 // https://docs.rs/rayon/1.1.0/rayon/struct.ThreadPoolBuilder.html#method.spawn_handler 17 // Source code says DefaultSpawner is implementation detail and 18 // shouldn't be used directly. 19 #[cfg(feature = "parallel-compilation")] 20 rayon::ThreadPoolBuilder::new() 21 .spawn_handler(move |thread| { 22 let mut b = std::thread::Builder::new(); 23 if let Some(name) = thread.name() { 24 b = b.name(name.to_owned()); 25 } 26 if let Some(stack_size) = thread.stack_size() { 27 b = b.stack_size(stack_size); 28 } 29 b.spawn(move || { 30 file_per_thread_logger::initialize(prefix); 31 thread.run() 32 })?; 33 Ok(()) 34 }) 35 .build_global() 36 .unwrap(); 37 } 38 39 wasmtime_option_group! { 40 #[derive(PartialEq, Clone)] 41 pub struct OptimizeOptions { 42 /// Optimization level of generated code (0-2, s; default: 2) 43 pub opt_level: Option<wasmtime::OptLevel>, 44 45 /// Register allocator algorithm choice. 46 pub regalloc_algorithm: Option<wasmtime::RegallocAlgorithm>, 47 48 /// Do not allow Wasm linear memories to move in the host process's 49 /// address space. 50 pub memory_may_move: Option<bool>, 51 52 /// Initial virtual memory allocation size for memories. 53 pub memory_reservation: Option<u64>, 54 55 /// Bytes to reserve at the end of linear memory for growth into. 56 pub memory_reservation_for_growth: Option<u64>, 57 58 /// Size, in bytes, of guard pages for linear memories. 59 pub memory_guard_size: Option<u64>, 60 61 /// Indicates whether an unmapped region of memory is placed before all 62 /// linear memories. 63 pub guard_before_linear_memory: Option<bool>, 64 65 /// Whether to initialize tables lazily, so that instantiation is 66 /// fast but indirect calls are a little slower. If no, tables are 67 /// initialized eagerly from any active element segments that apply to 68 /// them during instantiation. (default: yes) 69 pub table_lazy_init: Option<bool>, 70 71 /// Enable the pooling allocator, in place of the on-demand allocator. 72 pub pooling_allocator: Option<bool>, 73 74 /// The number of decommits to do per batch. A batch size of 1 75 /// effectively disables decommit batching. (default: 1) 76 pub pooling_decommit_batch_size: Option<usize>, 77 78 /// How many bytes to keep resident between instantiations for the 79 /// pooling allocator in linear memories. 80 pub pooling_memory_keep_resident: Option<usize>, 81 82 /// How many bytes to keep resident between instantiations for the 83 /// pooling allocator in tables. 84 pub pooling_table_keep_resident: Option<usize>, 85 86 /// Enable memory protection keys for the pooling allocator; this can 87 /// optimize the size of memory slots. 88 pub pooling_memory_protection_keys: Option<bool>, 89 90 /// Sets an upper limit on how many memory protection keys (MPK) Wasmtime 91 /// will use. (default: 16) 92 pub pooling_max_memory_protection_keys: Option<usize>, 93 94 /// Configure attempting to initialize linear memory via a 95 /// copy-on-write mapping (default: yes) 96 pub memory_init_cow: Option<bool>, 97 98 /// The maximum number of WebAssembly instances which can be created 99 /// with the pooling allocator. 100 pub pooling_total_core_instances: Option<u32>, 101 102 /// The maximum number of WebAssembly components which can be created 103 /// with the pooling allocator. 104 pub pooling_total_component_instances: Option<u32>, 105 106 /// The maximum number of WebAssembly memories which can be created with 107 /// the pooling allocator. 108 pub pooling_total_memories: Option<u32>, 109 110 /// The maximum number of WebAssembly tables which can be created with 111 /// the pooling allocator. 112 pub pooling_total_tables: Option<u32>, 113 114 /// The maximum number of WebAssembly stacks which can be created with 115 /// the pooling allocator. 116 pub pooling_total_stacks: Option<u32>, 117 118 /// The maximum runtime size of each linear memory in the pooling 119 /// allocator, in bytes. 120 pub pooling_max_memory_size: Option<usize>, 121 122 /// The maximum table elements for any table defined in a module when 123 /// using the pooling allocator. 124 pub pooling_table_elements: Option<usize>, 125 126 /// The maximum size, in bytes, allocated for a core instance's metadata 127 /// when using the pooling allocator. 128 pub pooling_max_core_instance_size: Option<usize>, 129 130 /// Configures the maximum number of "unused warm slots" to retain in the 131 /// pooling allocator. (default: 100) 132 pub pooling_max_unused_warm_slots: Option<u32>, 133 134 /// How much memory, in bytes, to keep resident for async stacks allocated 135 /// with the pooling allocator. (default: 0) 136 pub pooling_async_stack_keep_resident: Option<usize>, 137 138 /// The maximum size, in bytes, allocated for a component instance's 139 /// `VMComponentContext` metadata. (default: 1MiB) 140 pub pooling_max_component_instance_size: Option<usize>, 141 142 /// The maximum number of core instances a single component may contain 143 /// (default is unlimited). 144 pub pooling_max_core_instances_per_component: Option<u32>, 145 146 /// The maximum number of Wasm linear memories that a single component may 147 /// transitively contain (default is unlimited). 148 pub pooling_max_memories_per_component: Option<u32>, 149 150 /// The maximum number of tables that a single component may transitively 151 /// contain (default is unlimited). 152 pub pooling_max_tables_per_component: Option<u32>, 153 154 /// The maximum number of defined tables for a core module. (default: 1) 155 pub pooling_max_tables_per_module: Option<u32>, 156 157 /// The maximum number of defined linear memories for a module. (default: 1) 158 pub pooling_max_memories_per_module: Option<u32>, 159 160 /// The maximum number of concurrent GC heaps supported. (default: 1000) 161 pub pooling_total_gc_heaps: Option<u32>, 162 163 /// Enable or disable the use of host signal handlers for traps. 164 pub signals_based_traps: Option<bool>, 165 166 /// DEPRECATED: Use `-Cmemory-guard-size=N` instead. 167 pub dynamic_memory_guard_size: Option<u64>, 168 169 /// DEPRECATED: Use `-Cmemory-guard-size=N` instead. 170 pub static_memory_guard_size: Option<u64>, 171 172 /// DEPRECATED: Use `-Cmemory-may-move` instead. 173 pub static_memory_forced: Option<bool>, 174 175 /// DEPRECATED: Use `-Cmemory-reservation=N` instead. 176 pub static_memory_maximum_size: Option<u64>, 177 178 /// DEPRECATED: Use `-Cmemory-reservation-for-growth=N` instead. 179 pub dynamic_memory_reserved_for_growth: Option<u64>, 180 } 181 182 enum Optimize { 183 ... 184 } 185 } 186 187 wasmtime_option_group! { 188 #[derive(PartialEq, Clone)] 189 pub struct CodegenOptions { 190 /// Either `cranelift` or `winch`. 191 /// 192 /// Currently only `cranelift` and `winch` are supported, but not all 193 /// builds of Wasmtime have both built in. 194 pub compiler: Option<wasmtime::Strategy>, 195 /// Which garbage collector to use: `drc` or `null`. 196 /// 197 /// `drc` is the deferred reference-counting collector. 198 /// 199 /// `null` is the null garbage collector, which does not collect any 200 /// garbage. 201 /// 202 /// Note that not all builds of Wasmtime will have support for garbage 203 /// collection included. 204 pub collector: Option<wasmtime::Collector>, 205 /// Enable Cranelift's internal debug verifier (expensive) 206 pub cranelift_debug_verifier: Option<bool>, 207 /// Whether or not to enable caching of compiled modules. 208 pub cache: Option<bool>, 209 /// Configuration for compiled module caching. 210 pub cache_config: Option<String>, 211 /// Whether or not to enable parallel compilation of modules. 212 pub parallel_compilation: Option<bool>, 213 /// Whether to enable proof-carrying code (PCC)-based validation. 214 pub pcc: Option<bool>, 215 /// Controls whether native unwind information is present in compiled 216 /// object files. 217 pub native_unwind_info: Option<bool>, 218 219 #[prefixed = "cranelift"] 220 /// Set a cranelift-specific option. Use `wasmtime settings` to see 221 /// all. 222 pub cranelift: Vec<(String, Option<String>)>, 223 } 224 225 enum Codegen { 226 ... 227 } 228 } 229 230 wasmtime_option_group! { 231 #[derive(PartialEq, Clone)] 232 pub struct DebugOptions { 233 /// Enable generation of DWARF debug information in compiled code. 234 pub debug_info: Option<bool>, 235 /// Configure whether compiled code can map native addresses to wasm. 236 pub address_map: Option<bool>, 237 /// Configure whether logging is enabled. 238 pub logging: Option<bool>, 239 /// Configure whether logs are emitted to files 240 pub log_to_files: Option<bool>, 241 /// Enable coredump generation to this file after a WebAssembly trap. 242 pub coredump: Option<String>, 243 } 244 245 enum Debug { 246 ... 247 } 248 } 249 250 wasmtime_option_group! { 251 #[derive(PartialEq, Clone)] 252 pub struct WasmOptions { 253 /// Enable canonicalization of all NaN values. 254 pub nan_canonicalization: Option<bool>, 255 /// Enable execution fuel with N units fuel, trapping after running out 256 /// of fuel. 257 /// 258 /// Most WebAssembly instructions consume 1 unit of fuel. Some 259 /// instructions, such as `nop`, `drop`, `block`, and `loop`, consume 0 260 /// units, as any execution cost associated with them involves other 261 /// instructions which do consume fuel. 262 pub fuel: Option<u64>, 263 /// Yield when a global epoch counter changes, allowing for async 264 /// operation without blocking the executor. 265 pub epoch_interruption: Option<bool>, 266 /// Maximum stack size, in bytes, that wasm is allowed to consume before a 267 /// stack overflow is reported. 268 pub max_wasm_stack: Option<usize>, 269 /// Stack size, in bytes, that will be allocated for async stacks. 270 /// 271 /// Note that this must be larger than `max-wasm-stack` and the 272 /// difference between the two is how much stack the host has to execute 273 /// on. 274 pub async_stack_size: Option<usize>, 275 /// Configures whether or not stacks used for async futures are zeroed 276 /// before (re)use as a defense-in-depth mechanism. (default: false) 277 pub async_stack_zeroing: Option<bool>, 278 /// Allow unknown exports when running commands. 279 pub unknown_exports_allow: Option<bool>, 280 /// Allow the main module to import unknown functions, using an 281 /// implementation that immediately traps, when running commands. 282 pub unknown_imports_trap: Option<bool>, 283 /// Allow the main module to import unknown functions, using an 284 /// implementation that returns default values, when running commands. 285 pub unknown_imports_default: Option<bool>, 286 /// Enables memory error checking. (see wmemcheck.md for more info) 287 pub wmemcheck: Option<bool>, 288 /// Maximum size, in bytes, that a linear memory is allowed to reach. 289 /// 290 /// Growth beyond this limit will cause `memory.grow` instructions in 291 /// WebAssembly modules to return -1 and fail. 292 pub max_memory_size: Option<usize>, 293 /// Maximum size, in table elements, that a table is allowed to reach. 294 pub max_table_elements: Option<usize>, 295 /// Maximum number of WebAssembly instances allowed to be created. 296 pub max_instances: Option<usize>, 297 /// Maximum number of WebAssembly tables allowed to be created. 298 pub max_tables: Option<usize>, 299 /// Maximum number of WebAssembly linear memories allowed to be created. 300 pub max_memories: Option<usize>, 301 /// Force a trap to be raised on `memory.grow` and `table.grow` failure 302 /// instead of returning -1 from these instructions. 303 /// 304 /// This is not necessarily a spec-compliant option to enable but can be 305 /// useful for tracking down a backtrace of what is requesting so much 306 /// memory, for example. 307 pub trap_on_grow_failure: Option<bool>, 308 /// Maximum execution time of wasm code before timing out (1, 2s, 100ms, etc) 309 pub timeout: Option<Duration>, 310 /// Configures support for all WebAssembly proposals implemented. 311 pub all_proposals: Option<bool>, 312 /// Configure support for the bulk memory proposal. 313 pub bulk_memory: Option<bool>, 314 /// Configure support for the multi-memory proposal. 315 pub multi_memory: Option<bool>, 316 /// Configure support for the multi-value proposal. 317 pub multi_value: Option<bool>, 318 /// Configure support for the reference-types proposal. 319 pub reference_types: Option<bool>, 320 /// Configure support for the simd proposal. 321 pub simd: Option<bool>, 322 /// Configure support for the relaxed-simd proposal. 323 pub relaxed_simd: Option<bool>, 324 /// Configure forcing deterministic and host-independent behavior of 325 /// the relaxed-simd instructions. 326 /// 327 /// By default these instructions may have architecture-specific behavior as 328 /// allowed by the specification, but this can be used to force the behavior 329 /// of these instructions to match the deterministic behavior classified in 330 /// the specification. Note that enabling this option may come at a 331 /// performance cost. 332 pub relaxed_simd_deterministic: Option<bool>, 333 /// Configure support for the tail-call proposal. 334 pub tail_call: Option<bool>, 335 /// Configure support for the threads proposal. 336 pub threads: Option<bool>, 337 /// Configure support for the memory64 proposal. 338 pub memory64: Option<bool>, 339 /// Configure support for the component-model proposal. 340 pub component_model: Option<bool>, 341 /// Configure support for 33+ flags in the component model. 342 pub component_model_more_flags: Option<bool>, 343 /// Component model support for more than one return value. 344 pub component_model_multiple_returns: Option<bool>, 345 /// Configure support for the function-references proposal. 346 pub function_references: Option<bool>, 347 /// Configure support for the GC proposal. 348 pub gc: Option<bool>, 349 /// Configure support for the custom-page-sizes proposal. 350 pub custom_page_sizes: Option<bool>, 351 /// Configure support for the wide-arithmetic proposal. 352 pub wide_arithmetic: Option<bool>, 353 /// Configure support for the extended-const proposal. 354 pub extended_const: Option<bool>, 355 } 356 357 enum Wasm { 358 ... 359 } 360 } 361 362 wasmtime_option_group! { 363 #[derive(PartialEq, Clone)] 364 pub struct WasiOptions { 365 /// Enable support for WASI CLI APIs, including filesystems, sockets, clocks, and random. 366 pub cli: Option<bool>, 367 /// Enable WASI APIs marked as: @unstable(feature = cli-exit-with-code) 368 pub cli_exit_with_code: Option<bool>, 369 /// Deprecated alias for `cli` 370 pub common: Option<bool>, 371 /// Enable support for WASI neural network imports (experimental) 372 pub nn: Option<bool>, 373 /// Enable support for WASI threading imports (experimental). Implies preview2=false. 374 pub threads: Option<bool>, 375 /// Enable support for WASI HTTP imports 376 pub http: Option<bool>, 377 /// Number of distinct write calls to the outgoing body's output-stream 378 /// that the implementation will buffer. 379 /// Default: 1. 380 pub http_outgoing_body_buffer_chunks: Option<usize>, 381 /// Maximum size allowed in a write call to the outgoing body's output-stream. 382 /// Default: 1024 * 1024. 383 pub http_outgoing_body_chunk_size: Option<usize>, 384 /// Enable support for WASI config imports (experimental) 385 pub config: Option<bool>, 386 /// Enable support for WASI key-value imports (experimental) 387 pub keyvalue: Option<bool>, 388 /// Inherit environment variables and file descriptors following the 389 /// systemd listen fd specification (UNIX only) 390 pub listenfd: Option<bool>, 391 /// Grant access to the given TCP listen socket 392 pub tcplisten: Vec<String>, 393 /// Implement WASI Preview1 using new Preview2 implementation (true, default) or legacy 394 /// implementation (false) 395 pub preview2: Option<bool>, 396 /// Pre-load machine learning graphs (i.e., models) for use by wasi-nn. 397 /// 398 /// Each use of the flag will preload a ML model from the host directory 399 /// using the given model encoding. The model will be mapped to the 400 /// directory name: e.g., `--wasi-nn-graph openvino:/foo/bar` will preload 401 /// an OpenVINO model named `bar`. Note that which model encodings are 402 /// available is dependent on the backends implemented in the 403 /// `wasmtime_wasi_nn` crate. 404 pub nn_graph: Vec<WasiNnGraph>, 405 /// Flag for WASI preview2 to inherit the host's network within the 406 /// guest so it has full access to all addresses/ports/etc. 407 pub inherit_network: Option<bool>, 408 /// Indicates whether `wasi:sockets/ip-name-lookup` is enabled or not. 409 pub allow_ip_name_lookup: Option<bool>, 410 /// Indicates whether `wasi:sockets` TCP support is enabled or not. 411 pub tcp: Option<bool>, 412 /// Indicates whether `wasi:sockets` UDP support is enabled or not. 413 pub udp: Option<bool>, 414 /// Enable WASI APIs marked as: @unstable(feature = network-error-code) 415 pub network_error_code: Option<bool>, 416 /// Allows imports from the `wasi_unstable` core wasm module. 417 pub preview0: Option<bool>, 418 /// Inherit all environment variables from the parent process. 419 /// 420 /// This option can be further overwritten with `--env` flags. 421 pub inherit_env: Option<bool>, 422 /// Pass a wasi config variable to the program. 423 pub config_var: Vec<KeyValuePair>, 424 /// Preset data for the In-Memory provider of WASI key-value API. 425 pub keyvalue_in_memory_data: Vec<KeyValuePair>, 426 } 427 428 enum Wasi { 429 ... 430 } 431 } 432 433 #[derive(Debug, Clone, PartialEq)] 434 pub struct WasiNnGraph { 435 pub format: String, 436 pub dir: String, 437 } 438 439 #[derive(Debug, Clone, PartialEq)] 440 pub struct KeyValuePair { 441 pub key: String, 442 pub value: String, 443 } 444 445 /// Common options for commands that translate WebAssembly modules 446 #[derive(Parser, Clone)] 447 pub struct CommonOptions { 448 // These options groups are used to parse `-O` and such options but aren't 449 // the raw form consumed by the CLI. Instead they're pushed into the `pub` 450 // fields below as part of the `configure` method. 451 // 452 // Ideally clap would support `pub opts: OptimizeOptions` and parse directly 453 // into that but it does not appear to do so for multiple `-O` flags for 454 // now. 455 /// Optimization and tuning related options for wasm performance, `-O help` to 456 /// see all. 457 #[arg(short = 'O', long = "optimize", value_name = "KEY[=VAL[,..]]")] 458 opts_raw: Vec<opt::CommaSeparated<Optimize>>, 459 460 /// Codegen-related configuration options, `-C help` to see all. 461 #[arg(short = 'C', long = "codegen", value_name = "KEY[=VAL[,..]]")] 462 codegen_raw: Vec<opt::CommaSeparated<Codegen>>, 463 464 /// Debug-related configuration options, `-D help` to see all. 465 #[arg(short = 'D', long = "debug", value_name = "KEY[=VAL[,..]]")] 466 debug_raw: Vec<opt::CommaSeparated<Debug>>, 467 468 /// Options for configuring semantic execution of WebAssembly, `-W help` to see 469 /// all. 470 #[arg(short = 'W', long = "wasm", value_name = "KEY[=VAL[,..]]")] 471 wasm_raw: Vec<opt::CommaSeparated<Wasm>>, 472 473 /// Options for configuring WASI and its proposals, `-S help` to see all. 474 #[arg(short = 'S', long = "wasi", value_name = "KEY[=VAL[,..]]")] 475 wasi_raw: Vec<opt::CommaSeparated<Wasi>>, 476 477 // These fields are filled in by the `configure` method below via the 478 // options parsed from the CLI above. This is what the CLI should use. 479 #[arg(skip)] 480 configured: bool, 481 #[arg(skip)] 482 pub opts: OptimizeOptions, 483 #[arg(skip)] 484 pub codegen: CodegenOptions, 485 #[arg(skip)] 486 pub debug: DebugOptions, 487 #[arg(skip)] 488 pub wasm: WasmOptions, 489 #[arg(skip)] 490 pub wasi: WasiOptions, 491 492 /// The target triple; default is the host triple 493 #[arg(long, value_name = "TARGET")] 494 pub target: Option<String>, 495 } 496 497 macro_rules! match_feature { 498 ( 499 [$feat:tt : $config:expr] 500 $val:ident => $e:expr, 501 $p:pat => err, 502 ) => { 503 #[cfg(feature = $feat)] 504 { 505 if let Some($val) = $config { 506 $e; 507 } 508 } 509 #[cfg(not(feature = $feat))] 510 { 511 if let Some($p) = $config { 512 anyhow::bail!(concat!("support for ", $feat, " disabled at compile time")); 513 } 514 } 515 }; 516 } 517 518 impl CommonOptions { 519 fn configure(&mut self) { 520 if self.configured { 521 return; 522 } 523 self.configured = true; 524 self.opts.configure_with(&self.opts_raw); 525 self.codegen.configure_with(&self.codegen_raw); 526 self.debug.configure_with(&self.debug_raw); 527 self.wasm.configure_with(&self.wasm_raw); 528 self.wasi.configure_with(&self.wasi_raw); 529 } 530 531 pub fn init_logging(&mut self) -> Result<()> { 532 self.configure(); 533 if self.debug.logging == Some(false) { 534 return Ok(()); 535 } 536 #[cfg(feature = "logging")] 537 if self.debug.log_to_files == Some(true) { 538 let prefix = "wasmtime.dbg."; 539 init_file_per_thread_logger(prefix); 540 } else { 541 use std::io::IsTerminal; 542 use tracing_subscriber::{EnvFilter, FmtSubscriber}; 543 let builder = FmtSubscriber::builder() 544 .with_writer(std::io::stderr) 545 .with_env_filter(EnvFilter::from_env("WASMTIME_LOG")) 546 .with_ansi(std::io::stderr().is_terminal()); 547 if std::env::var("WASMTIME_LOG_NO_CONTEXT").is_ok_and(|value| value.eq("1")) { 548 builder 549 .with_level(false) 550 .with_target(false) 551 .without_time() 552 .init() 553 } else { 554 builder.init(); 555 } 556 } 557 #[cfg(not(feature = "logging"))] 558 if self.debug.log_to_files == Some(true) || self.debug.logging == Some(true) { 559 anyhow::bail!("support for logging disabled at compile time"); 560 } 561 Ok(()) 562 } 563 564 pub fn config(&mut self, pooling_allocator_default: Option<bool>) -> Result<Config> { 565 self.configure(); 566 let mut config = Config::new(); 567 568 match_feature! { 569 ["cranelift" : self.codegen.compiler] 570 strategy => config.strategy(strategy), 571 _ => err, 572 } 573 match_feature! { 574 ["gc" : self.codegen.collector] 575 collector => config.collector(collector), 576 _ => err, 577 } 578 if let Some(target) = &self.target { 579 config.target(target)?; 580 } 581 match_feature! { 582 ["cranelift" : self.codegen.cranelift_debug_verifier] 583 enable => config.cranelift_debug_verifier(enable), 584 true => err, 585 } 586 if let Some(enable) = self.debug.debug_info { 587 config.debug_info(enable); 588 } 589 if self.debug.coredump.is_some() { 590 #[cfg(feature = "coredump")] 591 config.coredump_on_trap(true); 592 #[cfg(not(feature = "coredump"))] 593 anyhow::bail!("support for coredumps disabled at compile time"); 594 } 595 match_feature! { 596 ["cranelift" : self.opts.opt_level] 597 level => config.cranelift_opt_level(level), 598 _ => err, 599 } 600 match_feature! { 601 ["cranelift": self.opts.regalloc_algorithm] 602 algo => config.cranelift_regalloc_algorithm(algo), 603 _ => err, 604 } 605 match_feature! { 606 ["cranelift" : self.wasm.nan_canonicalization] 607 enable => config.cranelift_nan_canonicalization(enable), 608 true => err, 609 } 610 match_feature! { 611 ["cranelift" : self.codegen.pcc] 612 enable => config.cranelift_pcc(enable), 613 true => err, 614 } 615 616 self.enable_wasm_features(&mut config)?; 617 618 #[cfg(feature = "cranelift")] 619 for (name, value) in self.codegen.cranelift.iter() { 620 let name = name.replace('-', "_"); 621 unsafe { 622 match value { 623 Some(val) => { 624 config.cranelift_flag_set(&name, val); 625 } 626 None => { 627 config.cranelift_flag_enable(&name); 628 } 629 } 630 } 631 } 632 #[cfg(not(feature = "cranelift"))] 633 if !self.codegen.cranelift.is_empty() { 634 anyhow::bail!("support for cranelift disabled at compile time"); 635 } 636 637 #[cfg(feature = "cache")] 638 if self.codegen.cache != Some(false) { 639 match &self.codegen.cache_config { 640 Some(path) => { 641 config.cache_config_load(path)?; 642 } 643 None => { 644 config.cache_config_load_default()?; 645 } 646 } 647 } 648 #[cfg(not(feature = "cache"))] 649 if self.codegen.cache == Some(true) { 650 anyhow::bail!("support for caching disabled at compile time"); 651 } 652 653 match_feature! { 654 ["parallel-compilation" : self.codegen.parallel_compilation] 655 enable => config.parallel_compilation(enable), 656 true => err, 657 } 658 659 let memory_reservation = self 660 .opts 661 .memory_reservation 662 .or(self.opts.static_memory_maximum_size); 663 if let Some(size) = memory_reservation { 664 config.memory_reservation(size); 665 } 666 667 if let Some(enable) = self.opts.static_memory_forced { 668 config.memory_may_move(!enable); 669 } 670 if let Some(enable) = self.opts.memory_may_move { 671 config.memory_may_move(enable); 672 } 673 674 let memory_guard_size = self 675 .opts 676 .static_memory_guard_size 677 .or(self.opts.dynamic_memory_guard_size) 678 .or(self.opts.memory_guard_size); 679 if let Some(size) = memory_guard_size { 680 config.memory_guard_size(size); 681 } 682 683 let mem_for_growth = self 684 .opts 685 .memory_reservation_for_growth 686 .or(self.opts.dynamic_memory_reserved_for_growth); 687 if let Some(size) = mem_for_growth { 688 config.memory_reservation_for_growth(size); 689 } 690 if let Some(enable) = self.opts.guard_before_linear_memory { 691 config.guard_before_linear_memory(enable); 692 } 693 if let Some(enable) = self.opts.table_lazy_init { 694 config.table_lazy_init(enable); 695 } 696 697 // If fuel has been configured, set the `consume fuel` flag on the config. 698 if self.wasm.fuel.is_some() { 699 config.consume_fuel(true); 700 } 701 702 if let Some(enable) = self.wasm.epoch_interruption { 703 config.epoch_interruption(enable); 704 } 705 if let Some(enable) = self.debug.address_map { 706 config.generate_address_map(enable); 707 } 708 if let Some(enable) = self.opts.memory_init_cow { 709 config.memory_init_cow(enable); 710 } 711 if let Some(enable) = self.opts.signals_based_traps { 712 config.signals_based_traps(enable); 713 } 714 if let Some(enable) = self.codegen.native_unwind_info { 715 config.native_unwind_info(enable); 716 } 717 718 match_feature! { 719 ["pooling-allocator" : self.opts.pooling_allocator.or(pooling_allocator_default)] 720 enable => { 721 if enable { 722 let mut cfg = wasmtime::PoolingAllocationConfig::default(); 723 if let Some(size) = self.opts.pooling_memory_keep_resident { 724 cfg.linear_memory_keep_resident(size); 725 } 726 if let Some(size) = self.opts.pooling_table_keep_resident { 727 cfg.table_keep_resident(size); 728 } 729 if let Some(limit) = self.opts.pooling_total_core_instances { 730 cfg.total_core_instances(limit); 731 } 732 if let Some(limit) = self.opts.pooling_total_component_instances { 733 cfg.total_component_instances(limit); 734 } 735 if let Some(limit) = self.opts.pooling_total_memories { 736 cfg.total_memories(limit); 737 } 738 if let Some(limit) = self.opts.pooling_total_tables { 739 cfg.total_tables(limit); 740 } 741 if let Some(limit) = self.opts.pooling_table_elements { 742 cfg.table_elements(limit); 743 } 744 if let Some(limit) = self.opts.pooling_max_core_instance_size { 745 cfg.max_core_instance_size(limit); 746 } 747 match_feature! { 748 ["async" : self.opts.pooling_total_stacks] 749 limit => cfg.total_stacks(limit), 750 _ => err, 751 } 752 if let Some(max) = self.opts.pooling_max_memory_size { 753 cfg.max_memory_size(max); 754 } 755 if let Some(size) = self.opts.pooling_decommit_batch_size { 756 cfg.decommit_batch_size(size); 757 } 758 if let Some(max) = self.opts.pooling_max_unused_warm_slots { 759 cfg.max_unused_warm_slots(max); 760 } 761 match_feature! { 762 ["async" : self.opts.pooling_async_stack_keep_resident] 763 size => cfg.async_stack_keep_resident(size), 764 _ => err, 765 } 766 if let Some(max) = self.opts.pooling_max_component_instance_size { 767 cfg.max_component_instance_size(max); 768 } 769 if let Some(max) = self.opts.pooling_max_core_instances_per_component { 770 cfg.max_core_instances_per_component(max); 771 } 772 if let Some(max) = self.opts.pooling_max_memories_per_component { 773 cfg.max_memories_per_component(max); 774 } 775 if let Some(max) = self.opts.pooling_max_tables_per_component { 776 cfg.max_tables_per_component(max); 777 } 778 if let Some(max) = self.opts.pooling_max_tables_per_module { 779 cfg.max_tables_per_module(max); 780 } 781 if let Some(max) = self.opts.pooling_max_memories_per_module { 782 cfg.max_memories_per_module(max); 783 } 784 match_feature! { 785 ["memory-protection-keys" : self.opts.pooling_memory_protection_keys] 786 enable => cfg.memory_protection_keys(if enable { 787 wasmtime::MpkEnabled::Enable 788 } else { 789 wasmtime::MpkEnabled::Disable 790 }), 791 _ => err, 792 } 793 match_feature! { 794 ["memory-protection-keys" : self.opts.pooling_max_memory_protection_keys] 795 max => cfg.max_memory_protection_keys(max), 796 _ => err, 797 } 798 match_feature! { 799 ["gc" : self.opts.pooling_total_gc_heaps] 800 max => cfg.total_gc_heaps(max), 801 _ => err, 802 } 803 config.allocation_strategy(wasmtime::InstanceAllocationStrategy::Pooling(cfg)); 804 } 805 }, 806 true => err, 807 } 808 809 if self.opts.pooling_memory_protection_keys.unwrap_or(false) 810 && !self.opts.pooling_allocator.unwrap_or(false) 811 { 812 anyhow::bail!("memory protection keys require the pooling allocator"); 813 } 814 815 if self.opts.pooling_max_memory_protection_keys.is_some() 816 && !self.opts.pooling_memory_protection_keys.unwrap_or(false) 817 { 818 anyhow::bail!( 819 "max memory protection keys requires memory protection keys to be enabled" 820 ); 821 } 822 823 match_feature! { 824 ["async" : self.wasm.async_stack_size] 825 size => config.async_stack_size(size), 826 _ => err, 827 } 828 match_feature! { 829 ["async" : self.wasm.async_stack_zeroing] 830 enable => config.async_stack_zeroing(enable), 831 _ => err, 832 } 833 834 if let Some(max) = self.wasm.max_wasm_stack { 835 config.max_wasm_stack(max); 836 837 // If `-Wasync-stack-size` isn't passed then automatically adjust it 838 // to the wasm stack size provided here too. That prevents the need 839 // to pass both when one can generally be inferred from the other. 840 #[cfg(feature = "async")] 841 if self.wasm.async_stack_size.is_none() { 842 const DEFAULT_HOST_STACK: usize = 512 << 10; 843 config.async_stack_size(max + DEFAULT_HOST_STACK); 844 } 845 } 846 847 if let Some(enable) = self.wasm.relaxed_simd_deterministic { 848 config.relaxed_simd_deterministic(enable); 849 } 850 match_feature! { 851 ["cranelift" : self.wasm.wmemcheck] 852 enable => config.wmemcheck(enable), 853 true => err, 854 } 855 856 Ok(config) 857 } 858 859 pub fn enable_wasm_features(&self, config: &mut Config) -> Result<()> { 860 let all = self.wasm.all_proposals; 861 862 if let Some(enable) = self.wasm.simd.or(all) { 863 config.wasm_simd(enable); 864 } 865 if let Some(enable) = self.wasm.relaxed_simd.or(all) { 866 config.wasm_relaxed_simd(enable); 867 } 868 if let Some(enable) = self.wasm.bulk_memory.or(all) { 869 config.wasm_bulk_memory(enable); 870 } 871 if let Some(enable) = self.wasm.multi_value.or(all) { 872 config.wasm_multi_value(enable); 873 } 874 if let Some(enable) = self.wasm.tail_call.or(all) { 875 config.wasm_tail_call(enable); 876 } 877 if let Some(enable) = self.wasm.multi_memory.or(all) { 878 config.wasm_multi_memory(enable); 879 } 880 if let Some(enable) = self.wasm.memory64.or(all) { 881 config.wasm_memory64(enable); 882 } 883 if let Some(enable) = self.wasm.custom_page_sizes.or(all) { 884 config.wasm_custom_page_sizes(enable); 885 } 886 if let Some(enable) = self.wasm.wide_arithmetic.or(all) { 887 config.wasm_wide_arithmetic(enable); 888 } 889 if let Some(enable) = self.wasm.extended_const.or(all) { 890 config.wasm_extended_const(enable); 891 } 892 893 macro_rules! handle_conditionally_compiled { 894 ($(($feature:tt, $field:tt, $method:tt))*) => ($( 895 if let Some(enable) = self.wasm.$field.or(all) { 896 #[cfg(feature = $feature)] 897 config.$method(enable); 898 #[cfg(not(feature = $feature))] 899 if enable && all.is_none() { 900 anyhow::bail!("support for {} was disabled at compile-time", $feature); 901 } 902 } 903 )*) 904 } 905 906 handle_conditionally_compiled! { 907 ("component-model", component_model, wasm_component_model) 908 ("component-model", component_model_more_flags, wasm_component_model_more_flags) 909 ("component-model", component_model_multiple_returns, wasm_component_model_multiple_returns) 910 ("threads", threads, wasm_threads) 911 ("gc", gc, wasm_gc) 912 ("gc", reference_types, wasm_reference_types) 913 ("gc", function_references, wasm_function_references) 914 } 915 Ok(()) 916 } 917 } 918