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