1 //! Generate a configuration for both Wasmtime and the Wasm module to execute. 2 3 use super::{ 4 AsyncConfig, CodegenSettings, InstanceAllocationStrategy, MemoryConfig, ModuleConfig, 5 NormalMemoryConfig, UnalignedMemoryCreator, 6 }; 7 use crate::oracles::{StoreLimits, Timeout}; 8 use anyhow::Result; 9 use arbitrary::{Arbitrary, Unstructured}; 10 use std::sync::Arc; 11 use std::time::Duration; 12 use wasmtime::{Engine, Module, MpkEnabled, Store}; 13 use wasmtime_test_util::wast::{WastConfig, WastTest, limits}; 14 15 /// Configuration for `wasmtime::Config` and generated modules for a session of 16 /// fuzzing. 17 /// 18 /// This configuration guides what modules are generated, how wasmtime 19 /// configuration is generated, and is typically itself generated through a call 20 /// to `Arbitrary` which allows for a form of "swarm testing". 21 #[derive(Debug, Clone)] 22 pub struct Config { 23 /// Configuration related to the `wasmtime::Config`. 24 pub wasmtime: WasmtimeConfig, 25 /// Configuration related to generated modules. 26 pub module_config: ModuleConfig, 27 } 28 29 impl Config { 30 /// Indicates that this configuration is being used for differential 31 /// execution. 32 /// 33 /// The purpose of this function is to update the configuration which was 34 /// generated to be compatible with execution in multiple engines. The goal 35 /// is to produce the exact same result in all engines so we need to paper 36 /// over things like nan differences and memory/table behavior differences. 37 pub fn set_differential_config(&mut self) { 38 let config = &mut self.module_config.config; 39 40 // Make it more likely that there are types available to generate a 41 // function with. 42 config.min_types = config.min_types.max(1); 43 config.max_types = config.max_types.max(1); 44 45 // Generate at least one function 46 config.min_funcs = config.min_funcs.max(1); 47 config.max_funcs = config.max_funcs.max(1); 48 49 // Allow a memory to be generated, but don't let it get too large. 50 // Additionally require the maximum size to guarantee that the growth 51 // behavior is consistent across engines. 52 config.max_memory32_bytes = 10 << 16; 53 config.max_memory64_bytes = 10 << 16; 54 config.memory_max_size_required = true; 55 56 // If tables are generated make sure they don't get too large to avoid 57 // hitting any engine-specific limit. Additionally ensure that the 58 // maximum size is required to guarantee consistent growth across 59 // engines. 60 // 61 // Note that while reference types are disabled below, only allow one 62 // table. 63 config.max_table_elements = 1_000; 64 config.table_max_size_required = true; 65 66 // Don't allow any imports 67 config.max_imports = 0; 68 69 // Try to get the function and the memory exported 70 config.export_everything = true; 71 72 // NaN is canonicalized at the wasm level for differential fuzzing so we 73 // can paper over NaN differences between engines. 74 config.canonicalize_nans = true; 75 76 // If using the pooling allocator, update the instance limits too 77 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.wasmtime.strategy { 78 // One single-page memory 79 pooling.total_memories = config.max_memories as u32; 80 pooling.max_memory_size = 10 << 16; 81 pooling.max_memories_per_module = config.max_memories as u32; 82 if pooling.memory_protection_keys == MpkEnabled::Auto 83 && pooling.max_memory_protection_keys > 1 84 { 85 pooling.total_memories = 86 pooling.total_memories * (pooling.max_memory_protection_keys as u32); 87 } 88 89 pooling.total_tables = config.max_tables as u32; 90 pooling.table_elements = 1_000; 91 pooling.max_tables_per_module = config.max_tables as u32; 92 93 pooling.core_instance_size = 1_000_000; 94 95 if let MemoryConfig::Normal(cfg) = &mut self.wasmtime.memory_config { 96 match &mut cfg.memory_reservation { 97 Some(size) => *size = (*size).max(pooling.max_memory_size as u64), 98 other @ None => *other = Some(pooling.max_memory_size as u64), 99 } 100 } 101 } 102 103 // These instructions are explicitly not expected to be exactly the same 104 // across engines. Don't fuzz them. 105 config.relaxed_simd_enabled = false; 106 } 107 108 /// Uses this configuration and the supplied source of data to generate 109 /// a wasm module. 110 /// 111 /// If a `default_fuel` is provided, the resulting module will be configured 112 /// to ensure termination; as doing so will add an additional global to the module, 113 /// the pooling allocator, if configured, will also have its globals limit updated. 114 pub fn generate( 115 &self, 116 input: &mut Unstructured<'_>, 117 default_fuel: Option<u32>, 118 ) -> arbitrary::Result<wasm_smith::Module> { 119 self.module_config.generate(input, default_fuel) 120 } 121 122 /// Updates this configuration to be able to run the `test` specified. 123 /// 124 /// This primarily updates `self.module_config` to ensure that it enables 125 /// all features and proposals necessary to execute the `test` specified. 126 /// This will additionally update limits in the pooling allocator to be able 127 /// to execute all tests. 128 pub fn make_wast_test_compliant(&mut self, test: &WastTest) -> WastConfig { 129 let wasmtime_test_util::wast::TestConfig { 130 memory64, 131 custom_page_sizes, 132 multi_memory, 133 threads, 134 shared_everything_threads, 135 gc, 136 function_references, 137 relaxed_simd, 138 reference_types, 139 tail_call, 140 extended_const, 141 wide_arithmetic, 142 component_model_async, 143 component_model_async_builtins, 144 component_model_async_stackful, 145 component_model_error_context, 146 simd, 147 exceptions, 148 legacy_exceptions, 149 150 hogs_memory: _, 151 nan_canonicalization: _, 152 gc_types: _, 153 stack_switching: _, 154 } = test.config; 155 156 // Enable/disable some proposals that aren't configurable in wasm-smith 157 // but are configurable in Wasmtime. 158 self.module_config.function_references_enabled = 159 function_references.or(gc).unwrap_or(false); 160 self.module_config.component_model_async = component_model_async.unwrap_or(false); 161 self.module_config.component_model_async_builtins = 162 component_model_async_builtins.unwrap_or(false); 163 self.module_config.component_model_async_stackful = 164 component_model_async_stackful.unwrap_or(false); 165 self.module_config.component_model_error_context = 166 component_model_error_context.unwrap_or(false); 167 self.module_config.legacy_exceptions = legacy_exceptions.unwrap_or(false); 168 169 // Enable/disable proposals that wasm-smith has knobs for which will be 170 // read when creating `wasmtime::Config`. 171 let config = &mut self.module_config.config; 172 config.bulk_memory_enabled = true; 173 config.multi_value_enabled = true; 174 config.wide_arithmetic_enabled = wide_arithmetic.unwrap_or(false); 175 config.memory64_enabled = memory64.unwrap_or(false); 176 config.relaxed_simd_enabled = relaxed_simd.unwrap_or(false); 177 config.simd_enabled = config.relaxed_simd_enabled || simd.unwrap_or(false); 178 config.tail_call_enabled = tail_call.unwrap_or(false); 179 config.custom_page_sizes_enabled = custom_page_sizes.unwrap_or(false); 180 config.threads_enabled = threads.unwrap_or(false); 181 config.shared_everything_threads_enabled = shared_everything_threads.unwrap_or(false); 182 config.gc_enabled = gc.unwrap_or(false); 183 config.reference_types_enabled = config.gc_enabled 184 || self.module_config.function_references_enabled 185 || reference_types.unwrap_or(false); 186 config.extended_const_enabled = extended_const.unwrap_or(false); 187 config.exceptions_enabled = exceptions.unwrap_or(false); 188 if multi_memory.unwrap_or(false) { 189 config.max_memories = limits::MEMORIES_PER_MODULE as usize; 190 } else { 191 config.max_memories = 1; 192 } 193 194 match &mut self.wasmtime.memory_config { 195 MemoryConfig::Normal(config) => { 196 if let Some(n) = &mut config.memory_reservation { 197 *n = (*n).max(limits::MEMORY_SIZE as u64); 198 } 199 } 200 MemoryConfig::CustomUnaligned => {} 201 } 202 203 // FIXME: it might be more ideal to avoid the need for this entirely 204 // and to just let the test fail. If a test fails due to a pooling 205 // allocator resource limit being met we could ideally detect that and 206 // let the fuzz test case pass. That would avoid the need to hardcode 207 // so much here and in theory wouldn't reduce the usefulness of fuzzers 208 // all that much. At this time though we can't easily test this configuration. 209 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.wasmtime.strategy { 210 // Clamp protection keys between 1 & 2 to reduce the number of 211 // slots and then multiply the total memories by the number of keys 212 // we have since a single store has access to only one key. 213 pooling.max_memory_protection_keys = pooling.max_memory_protection_keys.max(1).min(2); 214 pooling.total_memories = pooling 215 .total_memories 216 .max(limits::MEMORIES * (pooling.max_memory_protection_keys as u32)); 217 218 // For other limits make sure they meet the minimum threshold 219 // required for our wast tests. 220 pooling.total_component_instances = pooling 221 .total_component_instances 222 .max(limits::COMPONENT_INSTANCES); 223 pooling.total_tables = pooling.total_tables.max(limits::TABLES); 224 pooling.max_tables_per_module = 225 pooling.max_tables_per_module.max(limits::TABLES_PER_MODULE); 226 pooling.max_memories_per_module = pooling 227 .max_memories_per_module 228 .max(limits::MEMORIES_PER_MODULE); 229 pooling.max_memories_per_component = pooling 230 .max_memories_per_component 231 .max(limits::MEMORIES_PER_MODULE); 232 pooling.total_core_instances = pooling.total_core_instances.max(limits::CORE_INSTANCES); 233 pooling.max_memory_size = pooling.max_memory_size.max(limits::MEMORY_SIZE); 234 pooling.table_elements = pooling.table_elements.max(limits::TABLE_ELEMENTS); 235 pooling.core_instance_size = pooling.core_instance_size.max(limits::CORE_INSTANCE_SIZE); 236 pooling.component_instance_size = pooling 237 .component_instance_size 238 .max(limits::CORE_INSTANCE_SIZE); 239 } 240 241 // Return the test configuration that this fuzz configuration represents 242 // which is used afterwards to test if the `test` here is expected to 243 // fail or not. 244 WastConfig { 245 collector: match self.wasmtime.collector { 246 Collector::Null => wasmtime_test_util::wast::Collector::Null, 247 Collector::DeferredReferenceCounting => { 248 wasmtime_test_util::wast::Collector::DeferredReferenceCounting 249 } 250 }, 251 pooling: matches!( 252 self.wasmtime.strategy, 253 InstanceAllocationStrategy::Pooling(_) 254 ), 255 compiler: match self.wasmtime.compiler_strategy { 256 CompilerStrategy::CraneliftNative => { 257 wasmtime_test_util::wast::Compiler::CraneliftNative 258 } 259 CompilerStrategy::CraneliftPulley => { 260 wasmtime_test_util::wast::Compiler::CraneliftPulley 261 } 262 CompilerStrategy::Winch => wasmtime_test_util::wast::Compiler::Winch, 263 }, 264 } 265 } 266 267 /// Converts this to a `wasmtime::Config` object 268 pub fn to_wasmtime(&self) -> wasmtime::Config { 269 crate::init_fuzzing(); 270 271 let mut cfg = wasmtime_cli_flags::CommonOptions::default(); 272 cfg.codegen.native_unwind_info = 273 Some(cfg!(target_os = "windows") || self.wasmtime.native_unwind_info); 274 cfg.codegen.parallel_compilation = Some(false); 275 cfg.debug.address_map = Some(self.wasmtime.generate_address_map); 276 cfg.opts.opt_level = Some(self.wasmtime.opt_level.to_wasmtime()); 277 cfg.opts.regalloc_algorithm = Some(self.wasmtime.regalloc_algorithm.to_wasmtime()); 278 cfg.opts.signals_based_traps = Some(self.wasmtime.signals_based_traps); 279 cfg.opts.memory_guaranteed_dense_image_size = Some(std::cmp::min( 280 // Clamp this at 16MiB so we don't get huge in-memory 281 // images during fuzzing. 282 16 << 20, 283 self.wasmtime.memory_guaranteed_dense_image_size, 284 )); 285 cfg.wasm.async_stack_zeroing = Some(self.wasmtime.async_stack_zeroing); 286 cfg.wasm.bulk_memory = Some(true); 287 cfg.wasm.component_model_async = Some(self.module_config.component_model_async); 288 cfg.wasm.component_model_async_builtins = 289 Some(self.module_config.component_model_async_builtins); 290 cfg.wasm.component_model_async_stackful = 291 Some(self.module_config.component_model_async_stackful); 292 cfg.wasm.component_model_error_context = 293 Some(self.module_config.component_model_error_context); 294 cfg.wasm.custom_page_sizes = Some(self.module_config.config.custom_page_sizes_enabled); 295 cfg.wasm.epoch_interruption = Some(self.wasmtime.epoch_interruption); 296 cfg.wasm.extended_const = Some(self.module_config.config.extended_const_enabled); 297 cfg.wasm.fuel = self.wasmtime.consume_fuel.then(|| u64::MAX); 298 cfg.wasm.function_references = Some(self.module_config.function_references_enabled); 299 cfg.wasm.gc = Some(self.module_config.config.gc_enabled); 300 cfg.wasm.memory64 = Some(self.module_config.config.memory64_enabled); 301 cfg.wasm.multi_memory = Some(self.module_config.config.max_memories > 1); 302 cfg.wasm.multi_value = Some(self.module_config.config.multi_value_enabled); 303 cfg.wasm.nan_canonicalization = Some(self.wasmtime.canonicalize_nans); 304 cfg.wasm.reference_types = Some(self.module_config.config.reference_types_enabled); 305 cfg.wasm.simd = Some(self.module_config.config.simd_enabled); 306 cfg.wasm.tail_call = Some(self.module_config.config.tail_call_enabled); 307 cfg.wasm.threads = Some(self.module_config.config.threads_enabled); 308 cfg.wasm.shared_everything_threads = 309 Some(self.module_config.config.shared_everything_threads_enabled); 310 cfg.wasm.wide_arithmetic = Some(self.module_config.config.wide_arithmetic_enabled); 311 cfg.wasm.exceptions = Some(self.module_config.config.exceptions_enabled); 312 cfg.wasm.legacy_exceptions = Some(self.module_config.legacy_exceptions); 313 if !self.module_config.config.simd_enabled { 314 cfg.wasm.relaxed_simd = Some(false); 315 } 316 cfg.codegen.collector = Some(self.wasmtime.collector.to_wasmtime()); 317 318 let compiler_strategy = &self.wasmtime.compiler_strategy; 319 let cranelift_strategy = match compiler_strategy { 320 CompilerStrategy::CraneliftNative | CompilerStrategy::CraneliftPulley => true, 321 CompilerStrategy::Winch => false, 322 }; 323 self.wasmtime.compiler_strategy.configure(&mut cfg); 324 325 self.wasmtime.codegen.configure(&mut cfg); 326 327 // Determine whether we will actually enable PCC -- this is 328 // disabled if the module requires memory64, which is not yet 329 // compatible (due to the need for dynamic checks). 330 let pcc = cfg!(feature = "fuzz-pcc") 331 && self.wasmtime.pcc 332 && !self.module_config.config.memory64_enabled; 333 334 // Only set cranelift specific flags when the Cranelift strategy is 335 // chosen. 336 if cranelift_strategy { 337 // If the wasm-smith-generated module use nan canonicalization then we 338 // don't need to enable it, but if it doesn't enable it already then we 339 // enable this codegen option. 340 cfg.wasm.nan_canonicalization = Some(!self.module_config.config.canonicalize_nans); 341 342 // Enabling the verifier will at-least-double compilation time, which 343 // with a 20-30x slowdown in fuzzing can cause issues related to 344 // timeouts. If generated modules can have more than a small handful of 345 // functions then disable the verifier when fuzzing to try to lessen the 346 // impact of timeouts. 347 if self.module_config.config.max_funcs > 10 { 348 cfg.codegen.cranelift_debug_verifier = Some(false); 349 } 350 351 if self.wasmtime.force_jump_veneers { 352 cfg.codegen.cranelift.push(( 353 "wasmtime_linkopt_force_jump_veneer".to_string(), 354 Some("true".to_string()), 355 )); 356 } 357 358 if let Some(pad) = self.wasmtime.padding_between_functions { 359 cfg.codegen.cranelift.push(( 360 "wasmtime_linkopt_padding_between_functions".to_string(), 361 Some(pad.to_string()), 362 )); 363 } 364 365 cfg.codegen.pcc = Some(pcc); 366 367 // Eager init is currently only supported on Cranelift, not Winch. 368 cfg.opts.table_lazy_init = Some(self.wasmtime.table_lazy_init); 369 } 370 371 self.wasmtime.strategy.configure(&mut cfg); 372 373 // Vary the memory configuration, but only if threads are not enabled. 374 // When the threads proposal is enabled we might generate shared memory, 375 // which is less amenable to different memory configurations: 376 // - shared memories are required to be "static" so fuzzing the various 377 // memory configurations will mostly result in uninteresting errors. 378 // The interesting part about shared memories is the runtime so we 379 // don't fuzz non-default settings. 380 // - shared memories are required to be aligned which means that the 381 // `CustomUnaligned` variant isn't actually safe to use with a shared 382 // memory. 383 let host_memory = if !self.module_config.config.threads_enabled { 384 // If PCC is enabled, force other options to be compatible: PCC is currently only 385 // supported when bounds checks are elided. 386 let memory_config = if pcc { 387 MemoryConfig::Normal(NormalMemoryConfig { 388 memory_reservation: Some(4 << 30), // 4 GiB 389 memory_guard_size: Some(2 << 30), // 2 GiB 390 memory_reservation_for_growth: Some(0), 391 guard_before_linear_memory: false, 392 memory_init_cow: true, 393 // Doesn't matter, only using virtual memory. 394 cranelift_enable_heap_access_spectre_mitigations: None, 395 }) 396 } else { 397 self.wasmtime.memory_config.clone() 398 }; 399 400 match &memory_config { 401 MemoryConfig::Normal(memory_config) => { 402 memory_config.configure(&mut cfg); 403 None 404 } 405 MemoryConfig::CustomUnaligned => { 406 cfg.opts.memory_reservation = Some(0); 407 cfg.opts.memory_guard_size = Some(0); 408 cfg.opts.memory_reservation_for_growth = Some(0); 409 cfg.opts.guard_before_linear_memory = Some(false); 410 cfg.opts.memory_init_cow = Some(false); 411 log::debug!("a custom unaligned host memory will be in use"); 412 Some(Arc::new(UnalignedMemoryCreator)) 413 } 414 } 415 } else { 416 None 417 }; 418 419 // If malloc-based memory is going to be used, which requires these four 420 // options set to specific values (and Pulley auto-sets two of them) 421 // then be sure to cap `memory_reservation_for_growth` at a smaller 422 // value than the default. For malloc-based memory reservation beyond 423 // the end of memory isn't captured by `StoreLimiter` so we need to be 424 // sure it's small enough to not blow OOM limits while fuzzing. 425 if ((cfg.opts.signals_based_traps == Some(true) && cfg.opts.memory_guard_size == Some(0)) 426 || self.wasmtime.compiler_strategy == CompilerStrategy::CraneliftPulley) 427 && cfg.opts.memory_reservation == Some(0) 428 && cfg.opts.memory_init_cow == Some(false) 429 { 430 let growth = &mut cfg.opts.memory_reservation_for_growth; 431 let max = 1 << 20; 432 *growth = match *growth { 433 Some(n) => Some(n.min(max)), 434 None => Some(max), 435 }; 436 } 437 438 log::debug!("creating wasmtime config with CLI options:\n{cfg}"); 439 let mut cfg = cfg.config(None).expect("failed to create wasmtime::Config"); 440 441 if let Some(host_memory) = host_memory { 442 cfg.with_host_memory(host_memory); 443 } 444 445 if self.wasmtime.async_config != AsyncConfig::Disabled { 446 log::debug!("async config in use {:?}", self.wasmtime.async_config); 447 self.wasmtime.async_config.configure(&mut cfg); 448 } 449 450 return cfg; 451 } 452 453 /// Convenience function for generating a `Store<T>` using this 454 /// configuration. 455 pub fn to_store(&self) -> Store<StoreLimits> { 456 let engine = Engine::new(&self.to_wasmtime()).unwrap(); 457 let mut store = Store::new(&engine, StoreLimits::new()); 458 self.configure_store(&mut store); 459 store 460 } 461 462 /// Configures a store based on this configuration. 463 pub fn configure_store(&self, store: &mut Store<StoreLimits>) { 464 store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter); 465 466 // Configure the store to never abort by default, that is it'll have 467 // max fuel or otherwise trap on an epoch change but the epoch won't 468 // ever change. 469 // 470 // Afterwards though see what `AsyncConfig` is being used an further 471 // refine the store's configuration based on that. 472 if self.wasmtime.consume_fuel { 473 store.set_fuel(u64::MAX).unwrap(); 474 } 475 if self.wasmtime.epoch_interruption { 476 store.epoch_deadline_trap(); 477 store.set_epoch_deadline(1); 478 } 479 match self.wasmtime.async_config { 480 AsyncConfig::Disabled => {} 481 AsyncConfig::YieldWithFuel(amt) => { 482 assert!(self.wasmtime.consume_fuel); 483 store.fuel_async_yield_interval(Some(amt)).unwrap(); 484 } 485 AsyncConfig::YieldWithEpochs { ticks, .. } => { 486 assert!(self.wasmtime.epoch_interruption); 487 store.set_epoch_deadline(ticks); 488 store.epoch_deadline_async_yield_and_update(ticks); 489 } 490 } 491 } 492 493 /// Generates an arbitrary method of timing out an instance, ensuring that 494 /// this configuration supports the returned timeout. 495 pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> { 496 let time_duration = Duration::from_millis(100); 497 let timeout = u 498 .choose(&[Timeout::Fuel(100_000), Timeout::Epoch(time_duration)])? 499 .clone(); 500 match &timeout { 501 Timeout::Fuel(..) => { 502 self.wasmtime.consume_fuel = true; 503 } 504 Timeout::Epoch(..) => { 505 self.wasmtime.epoch_interruption = true; 506 } 507 Timeout::None => unreachable!("Not an option given to choose()"), 508 } 509 Ok(timeout) 510 } 511 512 /// Compiles the `wasm` within the `engine` provided. 513 /// 514 /// This notably will use `Module::{serialize,deserialize_file}` to 515 /// round-trip if configured in the fuzzer. 516 pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> { 517 // Propagate this error in case the caller wants to handle 518 // valid-vs-invalid wasm. 519 let module = Module::new(engine, wasm)?; 520 if !self.wasmtime.use_precompiled_cwasm { 521 return Ok(module); 522 } 523 524 // Don't propagate these errors to prevent them from accidentally being 525 // interpreted as invalid wasm, these should never fail on a 526 // well-behaved host system. 527 let dir = tempfile::TempDir::new().unwrap(); 528 let file = dir.path().join("module.wasm"); 529 std::fs::write(&file, module.serialize().unwrap()).unwrap(); 530 unsafe { Ok(Module::deserialize_file(engine, &file).unwrap()) } 531 } 532 533 /// Updates this configuration to forcibly enable async support. Only useful 534 /// in fuzzers which do async calls. 535 pub fn enable_async(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<()> { 536 if self.wasmtime.consume_fuel || u.arbitrary()? { 537 self.wasmtime.async_config = 538 AsyncConfig::YieldWithFuel(u.int_in_range(1000..=100_000)?); 539 self.wasmtime.consume_fuel = true; 540 } else { 541 self.wasmtime.async_config = AsyncConfig::YieldWithEpochs { 542 dur: Duration::from_millis(u.int_in_range(1..=10)?), 543 ticks: u.int_in_range(1..=10)?, 544 }; 545 self.wasmtime.epoch_interruption = true; 546 } 547 Ok(()) 548 } 549 } 550 551 impl<'a> Arbitrary<'a> for Config { 552 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 553 let mut config = Self { 554 wasmtime: u.arbitrary()?, 555 module_config: u.arbitrary()?, 556 }; 557 558 config 559 .wasmtime 560 .update_module_config(&mut config.module_config, u)?; 561 562 Ok(config) 563 } 564 } 565 566 /// Configuration related to `wasmtime::Config` and the various settings which 567 /// can be tweaked from within. 568 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)] 569 pub struct WasmtimeConfig { 570 opt_level: OptLevel, 571 regalloc_algorithm: RegallocAlgorithm, 572 debug_info: bool, 573 canonicalize_nans: bool, 574 interruptable: bool, 575 pub(crate) consume_fuel: bool, 576 pub(crate) epoch_interruption: bool, 577 /// The Wasmtime memory configuration to use. 578 pub memory_config: MemoryConfig, 579 force_jump_veneers: bool, 580 memory_init_cow: bool, 581 memory_guaranteed_dense_image_size: u64, 582 use_precompiled_cwasm: bool, 583 async_stack_zeroing: bool, 584 /// Configuration for the instance allocation strategy to use. 585 pub strategy: InstanceAllocationStrategy, 586 codegen: CodegenSettings, 587 padding_between_functions: Option<u16>, 588 generate_address_map: bool, 589 native_unwind_info: bool, 590 /// Configuration for the compiler to use. 591 pub compiler_strategy: CompilerStrategy, 592 collector: Collector, 593 table_lazy_init: bool, 594 595 /// Whether or not fuzzing should enable PCC. 596 pcc: bool, 597 598 /// Configuration for whether wasm is invoked in an async fashion and how 599 /// it's cooperatively time-sliced. 600 pub async_config: AsyncConfig, 601 602 /// Whether or not host signal handlers are enabled for this configuration, 603 /// aka whether signal handlers are supported. 604 signals_based_traps: bool, 605 } 606 607 impl WasmtimeConfig { 608 /// Force `self` to be a configuration compatible with `other`. This is 609 /// useful for differential execution to avoid unhelpful fuzz crashes when 610 /// one engine has a feature enabled and the other does not. 611 pub fn make_compatible_with(&mut self, other: &Self) { 612 // Use the same allocation strategy between the two configs. 613 // 614 // Ideally this wouldn't be necessary, but, during differential 615 // evaluation, if the `lhs` is using ondemand and the `rhs` is using the 616 // pooling allocator (or vice versa), then the module may have been 617 // generated in such a way that is incompatible with the other 618 // allocation strategy. 619 // 620 // We can remove this in the future when it's possible to access the 621 // fields of `wasm_smith::Module` to constrain the pooling allocator 622 // based on what was actually generated. 623 self.strategy = other.strategy.clone(); 624 if let InstanceAllocationStrategy::Pooling { .. } = &other.strategy { 625 // Also use the same memory configuration when using the pooling 626 // allocator. 627 self.memory_config = other.memory_config.clone(); 628 } 629 630 self.make_internally_consistent(); 631 } 632 633 /// Updates `config` to be compatible with `self` and the other way around 634 /// too. 635 pub fn update_module_config( 636 &mut self, 637 config: &mut ModuleConfig, 638 u: &mut Unstructured<'_>, 639 ) -> arbitrary::Result<()> { 640 match self.compiler_strategy { 641 CompilerStrategy::CraneliftNative => {} 642 643 CompilerStrategy::Winch => { 644 // Winch is not complete on non-x64 targets, so just abandon this test 645 // case. We don't want to force Cranelift because we change what module 646 // config features are enabled based on the compiler strategy, and we 647 // don't want to make the same fuzz input DNA generate different test 648 // cases on different targets. 649 if cfg!(not(target_arch = "x86_64")) { 650 log::warn!( 651 "want to compile with Winch but host architecture does not support it" 652 ); 653 return Err(arbitrary::Error::IncorrectFormat); 654 } 655 656 // Winch doesn't support the same set of wasm proposal as Cranelift 657 // at this time, so if winch is selected be sure to disable wasm 658 // proposals in `Config` to ensure that Winch can compile the 659 // module that wasm-smith generates. 660 config.config.relaxed_simd_enabled = false; 661 config.config.gc_enabled = false; 662 config.config.tail_call_enabled = false; 663 config.config.reference_types_enabled = false; 664 config.function_references_enabled = false; 665 666 // Winch's SIMD implementations require AVX and AVX2. 667 if self 668 .codegen_flag("has_avx") 669 .is_some_and(|value| value == "false") 670 || self 671 .codegen_flag("has_avx2") 672 .is_some_and(|value| value == "false") 673 { 674 config.config.simd_enabled = false; 675 } 676 677 // Tuning the following engine options is currently not supported 678 // by Winch. 679 self.signals_based_traps = true; 680 self.table_lazy_init = true; 681 self.debug_info = false; 682 } 683 684 CompilerStrategy::CraneliftPulley => { 685 config.config.threads_enabled = false; 686 } 687 } 688 689 // Forcibly don't use the `CustomUnaligned` memory configuration when 690 // wasm threads are enabled or when the pooling allocator is used. For 691 // the pooling allocator it doesn't use custom memory creators anyway 692 // and for wasm threads that will require some refactoring of the 693 // `LinearMemory` trait to bubble up the request that the linear memory 694 // not move. Otherwise that just generates a panic right now. 695 if config.config.threads_enabled 696 || matches!(self.strategy, InstanceAllocationStrategy::Pooling(_)) 697 { 698 self.avoid_custom_unaligned_memory(u)?; 699 } 700 701 // If using the pooling allocator, constrain the memory and module configurations 702 // to the module limits. 703 if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.strategy { 704 // If the pooling allocator is used, do not allow shared memory to 705 // be created. FIXME: see 706 // https://github.com/bytecodealliance/wasmtime/issues/4244. 707 config.config.threads_enabled = false; 708 709 // Ensure the pooling allocator can support the maximal size of 710 // memory, picking the smaller of the two to win. 711 let min_bytes = config 712 .config 713 .max_memory32_bytes 714 // memory64_bytes is a u128, but since we are taking the min 715 // we can truncate it down to a u64. 716 .min( 717 config 718 .config 719 .max_memory64_bytes 720 .try_into() 721 .unwrap_or(u64::MAX), 722 ); 723 let mut min = min_bytes.min(pooling.max_memory_size as u64); 724 if let MemoryConfig::Normal(cfg) = &self.memory_config { 725 min = min.min(cfg.memory_reservation.unwrap_or(0)); 726 } 727 pooling.max_memory_size = min as usize; 728 config.config.max_memory32_bytes = min; 729 config.config.max_memory64_bytes = min as u128; 730 731 // If traps are disallowed then memories must have at least one page 732 // of memory so if we still are only allowing 0 pages of memory then 733 // increase that to one here. 734 if config.config.disallow_traps { 735 if pooling.max_memory_size < (1 << 16) { 736 pooling.max_memory_size = 1 << 16; 737 config.config.max_memory32_bytes = 1 << 16; 738 config.config.max_memory64_bytes = 1 << 16; 739 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 740 match &mut cfg.memory_reservation { 741 Some(size) => *size = (*size).max(pooling.max_memory_size as u64), 742 size @ None => *size = Some(pooling.max_memory_size as u64), 743 } 744 } 745 } 746 // .. additionally update tables 747 if pooling.table_elements == 0 { 748 pooling.table_elements = 1; 749 } 750 } 751 752 // Don't allow too many linear memories per instance since massive 753 // virtual mappings can fail to get allocated. 754 config.config.min_memories = config.config.min_memories.min(10); 755 config.config.max_memories = config.config.max_memories.min(10); 756 757 // Force this pooling allocator to always be able to accommodate the 758 // module that may be generated. 759 pooling.total_memories = config.config.max_memories as u32; 760 pooling.total_tables = config.config.max_tables as u32; 761 } 762 763 if !self.signals_based_traps { 764 // At this time shared memories require a "static" memory 765 // configuration but when signals-based traps are disabled all 766 // memories are forced to the "dynamic" configuration. This is 767 // fixable with some more work on the bounds-checks side of things 768 // to do a full bounds check even on static memories, but that's 769 // left for a future PR. 770 config.config.threads_enabled = false; 771 772 // Spectre-based heap mitigations require signal handlers so this 773 // must always be disabled if signals-based traps are disabled. 774 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 775 cfg.cranelift_enable_heap_access_spectre_mitigations = None; 776 } 777 } 778 779 self.make_internally_consistent(); 780 781 Ok(()) 782 } 783 784 /// Returns the codegen flag value, if any, for `name`. 785 pub(crate) fn codegen_flag(&self, name: &str) -> Option<&str> { 786 self.codegen.flags().iter().find_map(|(n, value)| { 787 if n == name { 788 Some(value.as_str()) 789 } else { 790 None 791 } 792 }) 793 } 794 795 /// Helper to switch `MemoryConfig::CustomUnaligned` to 796 /// `MemoryConfig::Normal` 797 fn avoid_custom_unaligned_memory(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<()> { 798 if let MemoryConfig::CustomUnaligned = self.memory_config { 799 self.memory_config = MemoryConfig::Normal(u.arbitrary()?); 800 } 801 Ok(()) 802 } 803 804 /// Helper method to handle some dependencies between various configuration 805 /// options. This is intended to be called whenever a `Config` is created or 806 /// modified to ensure that the final result is an instantiable `Config`. 807 /// 808 /// Note that in general this probably shouldn't exist and anything here can 809 /// be considered a "TODO" to go implement more stuff in Wasmtime to accept 810 /// these sorts of configurations. For now though it's intended to reflect 811 /// the current state of the engine's development. 812 fn make_internally_consistent(&mut self) { 813 if !self.signals_based_traps { 814 if let MemoryConfig::Normal(cfg) = &mut self.memory_config { 815 // Spectre-based heap mitigations require signal handlers so 816 // this must always be disabled if signals-based traps are 817 // disabled. 818 cfg.cranelift_enable_heap_access_spectre_mitigations = None; 819 820 // With configuration settings that match the use of malloc for 821 // linear memories cap the `memory_reservation_for_growth` value 822 // to something reasonable to avoid OOM in fuzzing. 823 if !cfg.memory_init_cow 824 && cfg.memory_guard_size == Some(0) 825 && cfg.memory_reservation == Some(0) 826 { 827 let min = 10 << 20; // 10 MiB 828 if let Some(val) = &mut cfg.memory_reservation_for_growth { 829 *val = (*val).min(min); 830 } else { 831 cfg.memory_reservation_for_growth = Some(min); 832 } 833 } 834 } 835 } 836 } 837 } 838 839 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 840 enum OptLevel { 841 None, 842 Speed, 843 SpeedAndSize, 844 } 845 846 impl OptLevel { 847 fn to_wasmtime(&self) -> wasmtime::OptLevel { 848 match self { 849 OptLevel::None => wasmtime::OptLevel::None, 850 OptLevel::Speed => wasmtime::OptLevel::Speed, 851 OptLevel::SpeedAndSize => wasmtime::OptLevel::SpeedAndSize, 852 } 853 } 854 } 855 856 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 857 enum RegallocAlgorithm { 858 Backtracking, 859 SinglePass, 860 } 861 862 impl RegallocAlgorithm { 863 fn to_wasmtime(&self) -> wasmtime::RegallocAlgorithm { 864 match self { 865 RegallocAlgorithm::Backtracking => wasmtime::RegallocAlgorithm::Backtracking, 866 // Note: we have disabled `single_pass` for now because of 867 // its limitations w.r.t. exception handling 868 // (https://github.com/bytecodealliance/regalloc2/issues/217). To 869 // avoid breaking all existing fuzzbugs by changing the 870 // `arbitrary` mappings, we keep the `RegallocAlgorithm` 871 // enum as it is and remap here to `Backtracking`. 872 RegallocAlgorithm::SinglePass => wasmtime::RegallocAlgorithm::Backtracking, 873 } 874 } 875 } 876 877 #[derive(Clone, Debug, PartialEq, Eq, Hash)] 878 /// Compiler to use. 879 pub enum CompilerStrategy { 880 /// Cranelift compiler for the native architecture. 881 CraneliftNative, 882 /// Winch compiler. 883 Winch, 884 /// Cranelift compiler for the native architecture. 885 CraneliftPulley, 886 } 887 888 impl CompilerStrategy { 889 /// Configures `config` to use this compilation strategy 890 pub fn configure(&self, config: &mut wasmtime_cli_flags::CommonOptions) { 891 match self { 892 CompilerStrategy::CraneliftNative => { 893 config.codegen.compiler = Some(wasmtime::Strategy::Cranelift); 894 } 895 CompilerStrategy::Winch => { 896 config.codegen.compiler = Some(wasmtime::Strategy::Winch); 897 } 898 CompilerStrategy::CraneliftPulley => { 899 config.codegen.compiler = Some(wasmtime::Strategy::Cranelift); 900 config.target = Some("pulley64".to_string()); 901 } 902 } 903 } 904 } 905 906 impl Arbitrary<'_> for CompilerStrategy { 907 fn arbitrary(u: &mut Unstructured<'_>) -> arbitrary::Result<Self> { 908 // Favor fuzzing native cranelift, but if allowed also enable 909 // winch/pulley. 910 match u.int_in_range(0..=19)? { 911 1 => Ok(Self::CraneliftPulley), 912 2 => Ok(Self::Winch), 913 _ => Ok(Self::CraneliftNative), 914 } 915 } 916 } 917 918 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 919 pub enum Collector { 920 DeferredReferenceCounting, 921 Null, 922 } 923 924 impl Collector { 925 fn to_wasmtime(&self) -> wasmtime::Collector { 926 match self { 927 Collector::DeferredReferenceCounting => wasmtime::Collector::DeferredReferenceCounting, 928 Collector::Null => wasmtime::Collector::Null, 929 } 930 } 931 } 932