1 //! Test case generators. 2 //! 3 //! Test case generators take raw, unstructured input from a fuzzer 4 //! (e.g. libFuzzer) and translate that into a structured test case (e.g. a 5 //! valid Wasm binary). 6 //! 7 //! These are generally implementations of the `Arbitrary` trait, or some 8 //! wrapper over an external tool, such that the wrapper implements the 9 //! `Arbitrary` trait for the wrapped external tool. 10 11 pub mod api; 12 pub mod table_ops; 13 14 use crate::oracles::{StoreLimits, Timeout}; 15 use anyhow::Result; 16 use arbitrary::{Arbitrary, Unstructured}; 17 use std::sync::Arc; 18 use std::time::Duration; 19 use wasm_smith::SwarmConfig; 20 use wasmtime::{Engine, LinearMemory, MemoryCreator, MemoryType, Module, Store}; 21 22 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 23 enum OptLevel { 24 None, 25 Speed, 26 SpeedAndSize, 27 } 28 29 impl OptLevel { 30 fn to_wasmtime(&self) -> wasmtime::OptLevel { 31 match self { 32 OptLevel::None => wasmtime::OptLevel::None, 33 OptLevel::Speed => wasmtime::OptLevel::Speed, 34 OptLevel::SpeedAndSize => wasmtime::OptLevel::SpeedAndSize, 35 } 36 } 37 } 38 39 /// Configuration for `wasmtime::PoolingAllocationStrategy`. 40 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)] 41 pub enum PoolingAllocationStrategy { 42 /// Use next available instance slot. 43 NextAvailable, 44 /// Use random instance slot. 45 Random, 46 /// Use an affinity-based strategy. 47 ReuseAffinity, 48 } 49 50 impl PoolingAllocationStrategy { 51 fn to_wasmtime(&self) -> wasmtime::PoolingAllocationStrategy { 52 match self { 53 PoolingAllocationStrategy::NextAvailable => { 54 wasmtime::PoolingAllocationStrategy::NextAvailable 55 } 56 PoolingAllocationStrategy::Random => wasmtime::PoolingAllocationStrategy::Random, 57 PoolingAllocationStrategy::ReuseAffinity => { 58 wasmtime::PoolingAllocationStrategy::ReuseAffinity 59 } 60 } 61 } 62 } 63 /// Configuration for `wasmtime::PoolingAllocationStrategy`. 64 #[derive(Debug, Clone, Eq, PartialEq, Hash)] 65 #[allow(missing_docs)] 66 pub struct InstanceLimits { 67 pub count: u32, 68 pub memories: u32, 69 pub tables: u32, 70 pub memory_pages: u64, 71 pub table_elements: u32, 72 pub size: usize, 73 } 74 75 impl InstanceLimits { 76 fn to_wasmtime(&self) -> wasmtime::InstanceLimits { 77 wasmtime::InstanceLimits { 78 count: self.count, 79 memories: self.memories, 80 tables: self.tables, 81 memory_pages: self.memory_pages, 82 table_elements: self.table_elements, 83 size: self.size, 84 } 85 } 86 } 87 88 impl<'a> Arbitrary<'a> for InstanceLimits { 89 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 90 const MAX_COUNT: u32 = 100; 91 92 const MAX_TABLES: u32 = 10; 93 const MAX_MEMORIES: u32 = 10; 94 const MAX_ELEMENTS: u32 = 1000; 95 const MAX_MEMORY_PAGES: u64 = 160; // 10 MiB 96 const MAX_SIZE: usize = 1 << 20; // 1 MiB 97 98 Ok(Self { 99 tables: u.int_in_range(0..=MAX_TABLES)?, 100 memories: u.int_in_range(0..=MAX_MEMORIES)?, 101 table_elements: u.int_in_range(0..=MAX_ELEMENTS)?, 102 memory_pages: u.int_in_range(0..=MAX_MEMORY_PAGES)?, 103 count: u.int_in_range(1..=MAX_COUNT)?, 104 size: u.int_in_range(0..=MAX_SIZE)?, 105 }) 106 } 107 } 108 109 /// Configuration for `wasmtime::InstanceAllocationStrategy`. 110 #[derive(Arbitrary, Clone, Debug, Eq, PartialEq, Hash)] 111 pub enum InstanceAllocationStrategy { 112 /// Use the on-demand instance allocation strategy. 113 OnDemand, 114 /// Use the pooling instance allocation strategy. 115 Pooling { 116 /// The pooling strategy to use. 117 strategy: PoolingAllocationStrategy, 118 /// The instance limits. 119 instance_limits: InstanceLimits, 120 }, 121 } 122 123 impl InstanceAllocationStrategy { 124 fn to_wasmtime(&self) -> wasmtime::InstanceAllocationStrategy { 125 match self { 126 InstanceAllocationStrategy::OnDemand => wasmtime::InstanceAllocationStrategy::OnDemand, 127 InstanceAllocationStrategy::Pooling { 128 strategy, 129 instance_limits, 130 } => wasmtime::InstanceAllocationStrategy::Pooling { 131 strategy: strategy.to_wasmtime(), 132 instance_limits: instance_limits.to_wasmtime(), 133 }, 134 } 135 } 136 } 137 138 /// Configuration for `wasmtime::Config` and generated modules for a session of 139 /// fuzzing. 140 /// 141 /// This configuration guides what modules are generated, how wasmtime 142 /// configuration is generated, and is typically itself generated through a call 143 /// to `Arbitrary` which allows for a form of "swarm testing". 144 #[derive(Debug, Clone)] 145 pub struct Config { 146 /// Configuration related to the `wasmtime::Config`. 147 pub wasmtime: WasmtimeConfig, 148 /// Configuration related to generated modules. 149 pub module_config: ModuleConfig, 150 } 151 152 impl<'a> Arbitrary<'a> for Config { 153 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 154 let mut config = Self { 155 wasmtime: u.arbitrary()?, 156 module_config: u.arbitrary()?, 157 }; 158 159 // If using the pooling allocator, constrain the memory and module configurations 160 // to the module limits. 161 if let InstanceAllocationStrategy::Pooling { 162 instance_limits: limits, 163 .. 164 } = &config.wasmtime.strategy 165 { 166 // Force the use of a normal memory config when using the pooling allocator and 167 // limit the static memory maximum to be the same as the pooling allocator's memory 168 // page limit. 169 config.wasmtime.memory_config = match config.wasmtime.memory_config { 170 MemoryConfig::Normal(mut config) => { 171 config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000); 172 MemoryConfig::Normal(config) 173 } 174 MemoryConfig::CustomUnaligned => { 175 let mut config: NormalMemoryConfig = u.arbitrary()?; 176 config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000); 177 MemoryConfig::Normal(config) 178 } 179 }; 180 181 let cfg = &mut config.module_config.config; 182 cfg.max_memories = limits.memories as usize; 183 cfg.max_tables = limits.tables as usize; 184 cfg.max_memory_pages = limits.memory_pages; 185 186 // Force no aliases in any generated modules as they might count against the 187 // import limits above. 188 cfg.max_aliases = 0; 189 } 190 191 Ok(config) 192 } 193 } 194 195 /// Configuration related to `wasmtime::Config` and the various settings which 196 /// can be tweaked from within. 197 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)] 198 pub struct WasmtimeConfig { 199 opt_level: OptLevel, 200 debug_info: bool, 201 canonicalize_nans: bool, 202 interruptable: bool, 203 pub(crate) consume_fuel: bool, 204 epoch_interruption: bool, 205 /// The Wasmtime memory configuration to use. 206 pub memory_config: MemoryConfig, 207 force_jump_veneers: bool, 208 memory_init_cow: bool, 209 memory_guaranteed_dense_image_size: u64, 210 use_precompiled_cwasm: bool, 211 /// Configuration for the instance allocation strategy to use. 212 pub strategy: InstanceAllocationStrategy, 213 codegen: CodegenSettings, 214 padding_between_functions: Option<u16>, 215 generate_address_map: bool, 216 wasm_backtraces: bool, 217 } 218 219 /// Configuration for linear memories in Wasmtime. 220 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)] 221 pub enum MemoryConfig { 222 /// Configuration for linear memories which correspond to normal 223 /// configuration settings in `wasmtime` itself. This will tweak various 224 /// parameters about static/dynamic memories. 225 Normal(NormalMemoryConfig), 226 227 /// Configuration to force use of a linear memory that's unaligned at its 228 /// base address to force all wasm addresses to be unaligned at the hardware 229 /// level, even if the wasm itself correctly aligns everything internally. 230 CustomUnaligned, 231 } 232 233 /// Represents a normal memory configuration for Wasmtime with the given 234 /// static and dynamic memory sizes. 235 #[derive(Clone, Debug, Eq, Hash, PartialEq)] 236 pub struct NormalMemoryConfig { 237 static_memory_maximum_size: Option<u64>, 238 static_memory_guard_size: Option<u64>, 239 dynamic_memory_guard_size: Option<u64>, 240 guard_before_linear_memory: bool, 241 } 242 243 impl<'a> Arbitrary<'a> for NormalMemoryConfig { 244 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 245 // This attempts to limit memory and guard sizes to 32-bit ranges so 246 // we don't exhaust a 64-bit address space easily. 247 Ok(Self { 248 static_memory_maximum_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into), 249 static_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into), 250 dynamic_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into), 251 guard_before_linear_memory: u.arbitrary()?, 252 }) 253 } 254 } 255 256 impl Config { 257 /// Indicates that this configuration is being used for differential 258 /// execution so only a single function should be generated since that's all 259 /// that's going to be exercised. 260 pub fn set_differential_config(&mut self) { 261 let config = &mut self.module_config.config; 262 263 config.allow_start_export = false; 264 // Make sure there's a type available for the function. 265 config.min_types = 1; 266 config.max_types = 1; 267 268 // Generate one and only one function 269 config.min_funcs = 1; 270 config.max_funcs = 1; 271 272 // Give the function a memory, but keep it small 273 config.min_memories = 1; 274 config.max_memories = 1; 275 config.max_memory_pages = 1; 276 config.memory_max_size_required = true; 277 278 // While reference types are disabled below, only allow one table 279 config.max_tables = 1; 280 281 // Don't allow any imports 282 config.max_imports = 0; 283 284 // Try to get the function and the memory exported 285 config.min_exports = 2; 286 config.max_exports = 4; 287 288 // NaN is canonicalized at the wasm level for differential fuzzing so we 289 // can paper over NaN differences between engines. 290 config.canonicalize_nans = true; 291 292 // When diffing against a non-wasmtime engine then disable wasm 293 // features to get selectively re-enabled against each differential 294 // engine. 295 config.bulk_memory_enabled = false; 296 config.reference_types_enabled = false; 297 config.simd_enabled = false; 298 config.memory64_enabled = false; 299 300 // If using the pooling allocator, update the instance limits too 301 if let InstanceAllocationStrategy::Pooling { 302 instance_limits: limits, 303 .. 304 } = &mut self.wasmtime.strategy 305 { 306 // One single-page memory 307 limits.memories = 1; 308 limits.memory_pages = 1; 309 310 limits.tables = 1; 311 312 match &mut self.wasmtime.memory_config { 313 MemoryConfig::Normal(config) => { 314 config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000); 315 } 316 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this 317 } 318 } 319 } 320 321 /// Uses this configuration and the supplied source of data to generate 322 /// a wasm module. 323 /// 324 /// If a `default_fuel` is provided, the resulting module will be configured 325 /// to ensure termination; as doing so will add an additional global to the module, 326 /// the pooling allocator, if configured, will also have its globals limit updated. 327 pub fn generate( 328 &mut self, 329 input: &mut Unstructured<'_>, 330 default_fuel: Option<u32>, 331 ) -> arbitrary::Result<wasm_smith::Module> { 332 let mut module = wasm_smith::Module::new(self.module_config.config.clone(), input)?; 333 334 if let Some(default_fuel) = default_fuel { 335 module.ensure_termination(default_fuel); 336 } 337 338 Ok(module) 339 } 340 341 /// Indicates that this configuration should be spec-test-compliant, 342 /// disabling various features the spec tests assert are disabled. 343 pub fn set_spectest_compliant(&mut self) { 344 let config = &mut self.module_config.config; 345 config.memory64_enabled = false; 346 config.simd_enabled = false; 347 config.bulk_memory_enabled = true; 348 config.reference_types_enabled = true; 349 config.multi_value_enabled = true; 350 config.simd_enabled = true; 351 config.max_memories = 1; 352 config.max_tables = 5; 353 354 if let InstanceAllocationStrategy::Pooling { 355 instance_limits: limits, 356 .. 357 } = &mut self.wasmtime.strategy 358 { 359 // Configure the lower bound of a number of limits to what's 360 // required to actually run the spec tests. Fuzz-generated inputs 361 // may have limits less than these thresholds which would cause the 362 // spec tests to fail which isn't particularly interesting. 363 limits.memories = limits.memories.max(1); 364 limits.tables = limits.memories.max(5); 365 limits.table_elements = limits.memories.max(1_000); 366 limits.memory_pages = limits.memory_pages.max(900); 367 limits.count = limits.count.max(500); 368 limits.size = limits.size.max(64 * 1024); 369 370 match &mut self.wasmtime.memory_config { 371 MemoryConfig::Normal(config) => { 372 config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000); 373 } 374 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this 375 } 376 } 377 } 378 379 /// Converts this to a `wasmtime::Config` object 380 pub fn to_wasmtime(&self) -> wasmtime::Config { 381 crate::init_fuzzing(); 382 log::debug!("creating wasmtime config with {:#?}", self.wasmtime); 383 384 let mut cfg = wasmtime::Config::new(); 385 cfg.wasm_bulk_memory(true) 386 .wasm_reference_types(true) 387 .wasm_multi_value(self.module_config.config.multi_value_enabled) 388 .wasm_multi_memory(self.module_config.config.max_memories > 1) 389 .wasm_simd(self.module_config.config.simd_enabled) 390 .wasm_memory64(self.module_config.config.memory64_enabled) 391 .wasm_backtrace(self.wasmtime.wasm_backtraces) 392 .cranelift_nan_canonicalization(self.wasmtime.canonicalize_nans) 393 .cranelift_opt_level(self.wasmtime.opt_level.to_wasmtime()) 394 .consume_fuel(self.wasmtime.consume_fuel) 395 .epoch_interruption(self.wasmtime.epoch_interruption) 396 .memory_init_cow(self.wasmtime.memory_init_cow) 397 .memory_guaranteed_dense_image_size(std::cmp::min( 398 // Clamp this at 16MiB so we don't get huge in-memory 399 // images during fuzzing. 400 16 << 20, 401 self.wasmtime.memory_guaranteed_dense_image_size, 402 )) 403 .allocation_strategy(self.wasmtime.strategy.to_wasmtime()) 404 .generate_address_map(self.wasmtime.generate_address_map); 405 406 self.wasmtime.codegen.configure(&mut cfg); 407 408 // If the wasm-smith-generated module use nan canonicalization then we 409 // don't need to enable it, but if it doesn't enable it already then we 410 // enable this codegen option. 411 cfg.cranelift_nan_canonicalization(!self.module_config.config.canonicalize_nans); 412 413 // Enabling the verifier will at-least-double compilation time, which 414 // with a 20-30x slowdown in fuzzing can cause issues related to 415 // timeouts. If generated modules can have more than a small handful of 416 // functions then disable the verifier when fuzzing to try to lessen the 417 // impact of timeouts. 418 if self.module_config.config.max_funcs > 10 { 419 cfg.cranelift_debug_verifier(false); 420 } 421 422 if self.wasmtime.force_jump_veneers { 423 unsafe { 424 cfg.cranelift_flag_set("wasmtime_linkopt_force_jump_veneer", "true"); 425 } 426 } 427 428 if let Some(pad) = self.wasmtime.padding_between_functions { 429 unsafe { 430 cfg.cranelift_flag_set( 431 "wasmtime_linkopt_padding_between_functions", 432 &pad.to_string(), 433 ); 434 } 435 } 436 437 match &self.wasmtime.memory_config { 438 MemoryConfig::Normal(memory_config) => { 439 cfg.static_memory_maximum_size( 440 memory_config.static_memory_maximum_size.unwrap_or(0), 441 ) 442 .static_memory_guard_size(memory_config.static_memory_guard_size.unwrap_or(0)) 443 .dynamic_memory_guard_size(memory_config.dynamic_memory_guard_size.unwrap_or(0)) 444 .guard_before_linear_memory(memory_config.guard_before_linear_memory); 445 } 446 MemoryConfig::CustomUnaligned => { 447 cfg.with_host_memory(Arc::new(UnalignedMemoryCreator)) 448 .static_memory_maximum_size(0) 449 .dynamic_memory_guard_size(0) 450 .static_memory_guard_size(0) 451 .guard_before_linear_memory(false); 452 } 453 } 454 455 return cfg; 456 } 457 458 /// Convenience function for generating a `Store<T>` using this 459 /// configuration. 460 pub fn to_store(&self) -> Store<StoreLimits> { 461 let engine = Engine::new(&self.to_wasmtime()).unwrap(); 462 let mut store = Store::new(&engine, StoreLimits::new()); 463 self.configure_store(&mut store); 464 store 465 } 466 467 /// Configures a store based on this configuration. 468 pub fn configure_store(&self, store: &mut Store<StoreLimits>) { 469 store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter); 470 if self.wasmtime.consume_fuel { 471 store.add_fuel(u64::max_value()).unwrap(); 472 } 473 if self.wasmtime.epoch_interruption { 474 // Without fuzzing of async execution, we can't test the 475 // "update deadline and continue" behavior, but we can at 476 // least test the codegen paths and checks with the 477 // trapping behavior, which works synchronously too. We'll 478 // set the deadline one epoch tick in the future; then 479 // this works exactly like an interrupt flag. We expect no 480 // traps/interrupts unless we bump the epoch, which we do 481 // as one particular Timeout mode (`Timeout::Epoch`). 482 store.epoch_deadline_trap(); 483 store.set_epoch_deadline(1); 484 } 485 } 486 487 /// Generates an arbitrary method of timing out an instance, ensuring that 488 /// this configuration supports the returned timeout. 489 pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> { 490 let time_duration = Duration::from_secs(20); 491 let timeout = u 492 .choose(&[Timeout::Fuel(100_000), Timeout::Epoch(time_duration)])? 493 .clone(); 494 match &timeout { 495 Timeout::Fuel(..) => { 496 self.wasmtime.consume_fuel = true; 497 } 498 Timeout::Epoch(..) => { 499 self.wasmtime.epoch_interruption = true; 500 } 501 Timeout::None => unreachable!("Not an option given to choose()"), 502 } 503 Ok(timeout) 504 } 505 506 /// Compiles the `wasm` within the `engine` provided. 507 /// 508 /// This notably will use `Module::{serialize,deserialize_file}` to 509 /// round-trip if configured in the fuzzer. 510 pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> { 511 // Propagate this error in case the caller wants to handle 512 // valid-vs-invalid wasm. 513 let module = Module::new(engine, wasm)?; 514 if !self.wasmtime.use_precompiled_cwasm { 515 return Ok(module); 516 } 517 518 // Don't propagate these errors to prevent them from accidentally being 519 // interpreted as invalid wasm, these should never fail on a 520 // well-behaved host system. 521 let file = tempfile::NamedTempFile::new().unwrap(); 522 std::fs::write(file.path(), module.serialize().unwrap()).unwrap(); 523 unsafe { Ok(Module::deserialize_file(engine, file.path()).unwrap()) } 524 } 525 } 526 527 struct UnalignedMemoryCreator; 528 529 unsafe impl MemoryCreator for UnalignedMemoryCreator { 530 fn new_memory( 531 &self, 532 _ty: MemoryType, 533 minimum: usize, 534 maximum: Option<usize>, 535 reserved_size_in_bytes: Option<usize>, 536 guard_size_in_bytes: usize, 537 ) -> Result<Box<dyn LinearMemory>, String> { 538 assert_eq!(guard_size_in_bytes, 0); 539 assert!(reserved_size_in_bytes.is_none() || reserved_size_in_bytes == Some(0)); 540 Ok(Box::new(UnalignedMemory { 541 src: vec![0; minimum + 1], 542 maximum, 543 })) 544 } 545 } 546 547 /// A custom "linear memory allocator" for wasm which only works with the 548 /// "dynamic" mode of configuration where wasm always does explicit bounds 549 /// checks. 550 /// 551 /// This memory attempts to always use unaligned host addresses for the base 552 /// address of linear memory with wasm. This means that all jit loads/stores 553 /// should be unaligned, which is a "big hammer way" of testing that all our JIT 554 /// code works with unaligned addresses since alignment is not required for 555 /// correctness in wasm itself. 556 struct UnalignedMemory { 557 /// This memory is always one byte larger than the actual size of linear 558 /// memory. 559 src: Vec<u8>, 560 maximum: Option<usize>, 561 } 562 563 unsafe impl LinearMemory for UnalignedMemory { 564 fn byte_size(&self) -> usize { 565 // Chop off the extra byte reserved for the true byte size of this 566 // linear memory. 567 self.src.len() - 1 568 } 569 570 fn maximum_byte_size(&self) -> Option<usize> { 571 self.maximum 572 } 573 574 fn grow_to(&mut self, new_size: usize) -> Result<()> { 575 // Make sure to allocate an extra byte for our "unalignment" 576 self.src.resize(new_size + 1, 0); 577 Ok(()) 578 } 579 580 fn as_ptr(&self) -> *mut u8 { 581 // Return our allocated memory, offset by one, so that the base address 582 // of memory is always unaligned. 583 self.src[1..].as_ptr() as *mut _ 584 } 585 } 586 587 include!(concat!(env!("OUT_DIR"), "/spectests.rs")); 588 589 /// A spec test from the upstream wast testsuite, arbitrarily chosen from the 590 /// list of known spec tests. 591 #[derive(Debug)] 592 pub struct SpecTest { 593 /// The filename of the spec test 594 pub file: &'static str, 595 /// The `*.wast` contents of the spec test 596 pub contents: &'static str, 597 } 598 599 impl<'a> Arbitrary<'a> for SpecTest { 600 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 601 // NB: this does get a uniform value in the provided range. 602 let i = u.int_in_range(0..=FILES.len() - 1)?; 603 let (file, contents) = FILES[i]; 604 Ok(SpecTest { file, contents }) 605 } 606 607 fn size_hint(_depth: usize) -> (usize, Option<usize>) { 608 (1, Some(std::mem::size_of::<usize>())) 609 } 610 } 611 612 /// Default module-level configuration for fuzzing Wasmtime. 613 /// 614 /// Internally this uses `wasm-smith`'s own `SwarmConfig` but we further refine 615 /// the defaults here as well. 616 #[derive(Debug, Clone)] 617 pub struct ModuleConfig { 618 #[allow(missing_docs)] 619 pub config: SwarmConfig, 620 } 621 622 impl<'a> Arbitrary<'a> for ModuleConfig { 623 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<ModuleConfig> { 624 let mut config = SwarmConfig::arbitrary(u)?; 625 626 // Allow multi-memory by default. 627 config.max_memories = config.max_memories.max(2); 628 629 // Allow multi-table by default. 630 config.max_tables = config.max_tables.max(4); 631 632 // Allow enabling some various wasm proposals by default. Note that 633 // these are all unconditionally turned off even with 634 // `SwarmConfig::arbitrary`. 635 config.memory64_enabled = u.arbitrary()?; 636 637 Ok(ModuleConfig { config }) 638 } 639 } 640 641 #[derive(Clone, Debug, Eq, Hash, PartialEq)] 642 enum CodegenSettings { 643 Native, 644 #[allow(dead_code)] 645 Target { 646 target: String, 647 flags: Vec<(String, String)>, 648 }, 649 } 650 651 impl CodegenSettings { 652 fn configure(&self, config: &mut wasmtime::Config) { 653 match self { 654 CodegenSettings::Native => {} 655 CodegenSettings::Target { target, flags } => { 656 config.target(target).unwrap(); 657 for (key, value) in flags { 658 unsafe { 659 config.cranelift_flag_set(key, value); 660 } 661 } 662 } 663 } 664 } 665 } 666 667 impl<'a> Arbitrary<'a> for CodegenSettings { 668 #[allow(unused_macros, unused_variables)] 669 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 670 // Helper macro to enable clif features based on what the native host 671 // supports. If the input says to enable a feature and the host doesn't 672 // support it then that test case is rejected with a warning. 673 // 674 // Note that this specifically consumes bytes from the fuzz input for 675 // features for all targets, discarding anything which isn't applicable 676 // to the current target. The theory behind this is that most fuzz bugs 677 // won't be related to this feature selection so by consistently 678 // consuming input irrespective of the current platform reproducing fuzz 679 // bugs should be easier between different architectures. 680 macro_rules! target_features { 681 ( 682 $( 683 $arch:tt => { 684 test:$test:ident, 685 $(std: $std:tt => clif: $clif:tt $(ratio: $a:tt in $b:tt)?,)* 686 }, 687 )* 688 ) => ({ 689 let mut flags = Vec::new(); 690 $( // for each `$arch` 691 $( // for each `$std`/`$clif` pair 692 // Use the input to generate whether `$clif` will be 693 // enabled. By default this is a 1 in 2 chance but each 694 // feature supports a custom ratio as well which shadows 695 // the (low, hi) 696 let (low, hi) = (1, 2); 697 $(let (low, hi) = ($a, $b);)? 698 let enable = u.ratio(low, hi)?; 699 700 // If we're actually on the relevant platform and the 701 // feature is enabled be sure to check that this host 702 // supports it. If the host doesn't support it then 703 // print a warning and return an error because this fuzz 704 // input must be discarded. 705 #[cfg(target_arch = $arch)] 706 if enable && !std::arch::$test!($std) { 707 log::warn!("want to enable clif `{}` but host doesn't support it", 708 $clif); 709 return Err(arbitrary::Error::EmptyChoose) 710 } 711 712 // And finally actually push the feature into the set of 713 // flags to enable, but only if we're on the right 714 // architecture. 715 if cfg!(target_arch = $arch) { 716 flags.push(( 717 $clif.to_string(), 718 enable.to_string(), 719 )); 720 } 721 )* 722 )* 723 flags 724 }) 725 } 726 if u.ratio(1, 10)? { 727 let flags = target_features! { 728 "x86_64" => { 729 test: is_x86_feature_detected, 730 731 // These features are considered to be baseline required by 732 // Wasmtime. Currently some SIMD code generation will 733 // fail if these features are disabled, so unconditionally 734 // enable them as we're not interested in fuzzing without 735 // them. 736 std:"sse3" => clif:"has_sse3" ratio: 1 in 1, 737 std:"ssse3" => clif:"has_ssse3" ratio: 1 in 1, 738 std:"sse4.1" => clif:"has_sse41" ratio: 1 in 1, 739 std:"sse4.2" => clif:"has_sse42" ratio: 1 in 1, 740 741 std:"popcnt" => clif:"has_popcnt", 742 std:"avx" => clif:"has_avx", 743 std:"avx2" => clif:"has_avx2", 744 std:"bmi1" => clif:"has_bmi1", 745 std:"bmi2" => clif:"has_bmi2", 746 std:"lzcnt" => clif:"has_lzcnt", 747 748 // not a lot of of cpus support avx512 so these are weighted 749 // to get enabled much less frequently. 750 std:"avx512bitalg" => clif:"has_avx512bitalg" ratio:1 in 1000, 751 std:"avx512dq" => clif:"has_avx512dq" ratio: 1 in 1000, 752 std:"avx512f" => clif:"has_avx512f" ratio: 1 in 1000, 753 std:"avx512vl" => clif:"has_avx512vl" ratio: 1 in 1000, 754 std:"avx512vbmi" => clif:"has_avx512vbmi" ratio: 1 in 1000, 755 }, 756 "aarch64" => { 757 test: is_aarch64_feature_detected, 758 759 std: "lse" => clif: "has_lse", 760 }, 761 }; 762 return Ok(CodegenSettings::Target { 763 target: target_lexicon::Triple::host().to_string(), 764 flags, 765 }); 766 } 767 Ok(CodegenSettings::Native) 768 } 769 } 770