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 } 215 216 /// Configuration for linear memories in Wasmtime. 217 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)] 218 pub enum MemoryConfig { 219 /// Configuration for linear memories which correspond to normal 220 /// configuration settings in `wasmtime` itself. This will tweak various 221 /// parameters about static/dynamic memories. 222 Normal(NormalMemoryConfig), 223 224 /// Configuration to force use of a linear memory that's unaligned at its 225 /// base address to force all wasm addresses to be unaligned at the hardware 226 /// level, even if the wasm itself correctly aligns everything internally. 227 CustomUnaligned, 228 } 229 230 /// Represents a normal memory configuration for Wasmtime with the given 231 /// static and dynamic memory sizes. 232 #[derive(Clone, Debug, Eq, Hash, PartialEq)] 233 pub struct NormalMemoryConfig { 234 static_memory_maximum_size: Option<u64>, 235 static_memory_guard_size: Option<u64>, 236 dynamic_memory_guard_size: Option<u64>, 237 guard_before_linear_memory: bool, 238 } 239 240 impl<'a> Arbitrary<'a> for NormalMemoryConfig { 241 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 242 // This attempts to limit memory and guard sizes to 32-bit ranges so 243 // we don't exhaust a 64-bit address space easily. 244 Ok(Self { 245 static_memory_maximum_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into), 246 static_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into), 247 dynamic_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into), 248 guard_before_linear_memory: u.arbitrary()?, 249 }) 250 } 251 } 252 253 impl Config { 254 /// Indicates that this configuration is being used for differential 255 /// execution so only a single function should be generated since that's all 256 /// that's going to be exercised. 257 pub fn set_differential_config(&mut self) { 258 let config = &mut self.module_config.config; 259 260 config.allow_start_export = false; 261 // Make sure there's a type available for the function. 262 config.min_types = 1; 263 config.max_types = 1; 264 265 // Generate one and only one function 266 config.min_funcs = 1; 267 config.max_funcs = 1; 268 269 // Give the function a memory, but keep it small 270 config.min_memories = 1; 271 config.max_memories = 1; 272 config.max_memory_pages = 1; 273 config.memory_max_size_required = true; 274 275 // While reference types are disabled below, only allow one table 276 config.max_tables = 1; 277 278 // Don't allow any imports 279 config.max_imports = 0; 280 281 // Try to get the function and the memory exported 282 config.min_exports = 2; 283 config.max_exports = 4; 284 285 // NaN is canonicalized at the wasm level for differential fuzzing so we 286 // can paper over NaN differences between engines. 287 config.canonicalize_nans = true; 288 289 // When diffing against a non-wasmtime engine then disable wasm 290 // features to get selectively re-enabled against each differential 291 // engine. 292 config.bulk_memory_enabled = false; 293 config.reference_types_enabled = false; 294 config.simd_enabled = false; 295 config.memory64_enabled = false; 296 297 // If using the pooling allocator, update the instance limits too 298 if let InstanceAllocationStrategy::Pooling { 299 instance_limits: limits, 300 .. 301 } = &mut self.wasmtime.strategy 302 { 303 // One single-page memory 304 limits.memories = 1; 305 limits.memory_pages = 1; 306 307 match &mut self.wasmtime.memory_config { 308 MemoryConfig::Normal(config) => { 309 config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000); 310 } 311 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this 312 } 313 } 314 } 315 316 /// Uses this configuration and the supplied source of data to generate 317 /// a wasm module. 318 /// 319 /// If a `default_fuel` is provided, the resulting module will be configured 320 /// to ensure termination; as doing so will add an additional global to the module, 321 /// the pooling allocator, if configured, will also have its globals limit updated. 322 pub fn generate( 323 &mut self, 324 input: &mut Unstructured<'_>, 325 default_fuel: Option<u32>, 326 ) -> arbitrary::Result<wasm_smith::Module> { 327 let mut module = wasm_smith::Module::new(self.module_config.config.clone(), input)?; 328 329 if let Some(default_fuel) = default_fuel { 330 module.ensure_termination(default_fuel); 331 } 332 333 Ok(module) 334 } 335 336 /// Indicates that this configuration should be spec-test-compliant, 337 /// disabling various features the spec tests assert are disabled. 338 pub fn set_spectest_compliant(&mut self) { 339 let config = &mut self.module_config.config; 340 config.memory64_enabled = false; 341 config.simd_enabled = false; 342 config.bulk_memory_enabled = true; 343 config.reference_types_enabled = true; 344 config.max_memories = 1; 345 346 if let InstanceAllocationStrategy::Pooling { 347 instance_limits: limits, 348 .. 349 } = &mut self.wasmtime.strategy 350 { 351 limits.memories = 1; 352 // Set a lower bound of 10 pages as the spec tests define memories with at 353 // least a few pages and some tests do memory grow operations. 354 limits.memory_pages = std::cmp::max(limits.memory_pages, 10); 355 356 match &mut self.wasmtime.memory_config { 357 MemoryConfig::Normal(config) => { 358 config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000); 359 } 360 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this 361 } 362 } 363 } 364 365 /// Converts this to a `wasmtime::Config` object 366 pub fn to_wasmtime(&self) -> wasmtime::Config { 367 crate::init_fuzzing(); 368 369 let mut cfg = wasmtime::Config::new(); 370 cfg.wasm_bulk_memory(true) 371 .wasm_reference_types(true) 372 .wasm_module_linking(self.module_config.config.module_linking_enabled) 373 .wasm_multi_value(self.module_config.config.multi_value_enabled) 374 .wasm_multi_memory(self.module_config.config.max_memories > 1) 375 .wasm_simd(self.module_config.config.simd_enabled) 376 .wasm_memory64(self.module_config.config.memory64_enabled) 377 .cranelift_nan_canonicalization(self.wasmtime.canonicalize_nans) 378 .cranelift_opt_level(self.wasmtime.opt_level.to_wasmtime()) 379 .interruptable(self.wasmtime.interruptable) 380 .consume_fuel(self.wasmtime.consume_fuel) 381 .epoch_interruption(self.wasmtime.epoch_interruption) 382 .memory_init_cow(self.wasmtime.memory_init_cow) 383 .memory_guaranteed_dense_image_size(std::cmp::min( 384 // Clamp this at 16MiB so we don't get huge in-memory 385 // images during fuzzing. 386 16 << 20, 387 self.wasmtime.memory_guaranteed_dense_image_size, 388 )) 389 .allocation_strategy(self.wasmtime.strategy.to_wasmtime()); 390 391 self.wasmtime.codegen.configure(&mut cfg); 392 393 // If the wasm-smith-generated module use nan canonicalization then we 394 // don't need to enable it, but if it doesn't enable it already then we 395 // enable this codegen option. 396 cfg.cranelift_nan_canonicalization(!self.module_config.config.canonicalize_nans); 397 398 // Enabling the verifier will at-least-double compilation time, which 399 // with a 20-30x slowdown in fuzzing can cause issues related to 400 // timeouts. If generated modules can have more than a small handful of 401 // functions then disable the verifier when fuzzing to try to lessen the 402 // impact of timeouts. 403 if self.module_config.config.max_funcs > 10 { 404 cfg.cranelift_debug_verifier(false); 405 } 406 407 if self.wasmtime.force_jump_veneers { 408 unsafe { 409 cfg.cranelift_flag_set("wasmtime_linkopt_force_jump_veneer", "true") 410 .unwrap(); 411 } 412 } 413 414 match &self.wasmtime.memory_config { 415 MemoryConfig::Normal(memory_config) => { 416 cfg.static_memory_maximum_size( 417 memory_config.static_memory_maximum_size.unwrap_or(0), 418 ) 419 .static_memory_guard_size(memory_config.static_memory_guard_size.unwrap_or(0)) 420 .dynamic_memory_guard_size(memory_config.dynamic_memory_guard_size.unwrap_or(0)) 421 .guard_before_linear_memory(memory_config.guard_before_linear_memory); 422 } 423 MemoryConfig::CustomUnaligned => { 424 cfg.with_host_memory(Arc::new(UnalignedMemoryCreator)) 425 .static_memory_maximum_size(0) 426 .dynamic_memory_guard_size(0) 427 .static_memory_guard_size(0) 428 .guard_before_linear_memory(false); 429 } 430 } 431 432 return cfg; 433 } 434 435 /// Convenience function for generating a `Store<T>` using this 436 /// configuration. 437 pub fn to_store(&self) -> Store<StoreLimits> { 438 let engine = Engine::new(&self.to_wasmtime()).unwrap(); 439 let mut store = Store::new(&engine, StoreLimits::new()); 440 self.configure_store(&mut store); 441 store 442 } 443 444 /// Configures a store based on this configuration. 445 pub fn configure_store(&self, store: &mut Store<StoreLimits>) { 446 store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter); 447 if self.wasmtime.consume_fuel { 448 store.add_fuel(u64::max_value()).unwrap(); 449 } 450 if self.wasmtime.epoch_interruption { 451 // Without fuzzing of async execution, we can't test the 452 // "update deadline and continue" behavior, but we can at 453 // least test the codegen paths and checks with the 454 // trapping behavior, which works synchronously too. We'll 455 // set the deadline one epoch tick in the future; then 456 // this works exactly like an interrupt flag. We expect no 457 // traps/interrupts unless we bump the epoch, which we do 458 // as one particular Timeout mode (`Timeout::Epoch`). 459 store.epoch_deadline_trap(); 460 store.set_epoch_deadline(1); 461 } 462 } 463 464 /// Generates an arbitrary method of timing out an instance, ensuring that 465 /// this configuration supports the returned timeout. 466 pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> { 467 let time_duration = Duration::from_secs(20); 468 let timeout = u 469 .choose(&[ 470 Timeout::Time(time_duration), 471 Timeout::Fuel(100_000), 472 Timeout::Epoch(time_duration), 473 ])? 474 .clone(); 475 match &timeout { 476 &Timeout::Time(..) => { 477 self.wasmtime.interruptable = true; 478 } 479 &Timeout::Fuel(..) => { 480 self.wasmtime.consume_fuel = true; 481 } 482 &Timeout::Epoch(..) => { 483 self.wasmtime.epoch_interruption = true; 484 } 485 &Timeout::None => unreachable!("Not an option given to choose()"), 486 } 487 Ok(timeout) 488 } 489 490 /// Compiles the `wasm` within the `engine` provided. 491 /// 492 /// This notably will use `Module::{serialize,deserialize_file}` to 493 /// round-trip if configured in the fuzzer. 494 pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> { 495 // Propagate this error in case the caller wants to handle 496 // valid-vs-invalid wasm. 497 let module = Module::new(engine, wasm)?; 498 if !self.wasmtime.use_precompiled_cwasm { 499 return Ok(module); 500 } 501 502 // Don't propagate these errors to prevent them from accidentally being 503 // interpreted as invalid wasm, these should never fail on a 504 // well-behaved host system. 505 let file = tempfile::NamedTempFile::new().unwrap(); 506 std::fs::write(file.path(), module.serialize().unwrap()).unwrap(); 507 unsafe { Ok(Module::deserialize_file(engine, file.path()).unwrap()) } 508 } 509 } 510 511 struct UnalignedMemoryCreator; 512 513 unsafe impl MemoryCreator for UnalignedMemoryCreator { 514 fn new_memory( 515 &self, 516 _ty: MemoryType, 517 minimum: usize, 518 maximum: Option<usize>, 519 reserved_size_in_bytes: Option<usize>, 520 guard_size_in_bytes: usize, 521 ) -> Result<Box<dyn LinearMemory>, String> { 522 assert_eq!(guard_size_in_bytes, 0); 523 assert!(reserved_size_in_bytes.is_none() || reserved_size_in_bytes == Some(0)); 524 Ok(Box::new(UnalignedMemory { 525 src: vec![0; minimum + 1], 526 maximum, 527 })) 528 } 529 } 530 531 /// A custom "linear memory allocator" for wasm which only works with the 532 /// "dynamic" mode of configuration where wasm always does explicit bounds 533 /// checks. 534 /// 535 /// This memory attempts to always use unaligned host addresses for the base 536 /// address of linear memory with wasm. This means that all jit loads/stores 537 /// should be unaligned, which is a "big hammer way" of testing that all our JIT 538 /// code works with unaligned addresses since alignment is not required for 539 /// correctness in wasm itself. 540 struct UnalignedMemory { 541 /// This memory is always one byte larger than the actual size of linear 542 /// memory. 543 src: Vec<u8>, 544 maximum: Option<usize>, 545 } 546 547 unsafe impl LinearMemory for UnalignedMemory { 548 fn byte_size(&self) -> usize { 549 // Chop off the extra byte reserved for the true byte size of this 550 // linear memory. 551 self.src.len() - 1 552 } 553 554 fn maximum_byte_size(&self) -> Option<usize> { 555 self.maximum 556 } 557 558 fn grow_to(&mut self, new_size: usize) -> Result<()> { 559 // Make sure to allocate an extra byte for our "unalignment" 560 self.src.resize(new_size + 1, 0); 561 Ok(()) 562 } 563 564 fn as_ptr(&self) -> *mut u8 { 565 // Return our allocated memory, offset by one, so that the base address 566 // of memory is always unaligned. 567 self.src[1..].as_ptr() as *mut _ 568 } 569 } 570 571 include!(concat!(env!("OUT_DIR"), "/spectests.rs")); 572 573 /// A spec test from the upstream wast testsuite, arbitrarily chosen from the 574 /// list of known spec tests. 575 #[derive(Debug)] 576 pub struct SpecTest { 577 /// The filename of the spec test 578 pub file: &'static str, 579 /// The `*.wast` contents of the spec test 580 pub contents: &'static str, 581 } 582 583 impl<'a> Arbitrary<'a> for SpecTest { 584 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 585 // NB: this does get a uniform value in the provided range. 586 let i = u.int_in_range(0..=FILES.len() - 1)?; 587 let (file, contents) = FILES[i]; 588 Ok(SpecTest { file, contents }) 589 } 590 591 fn size_hint(_depth: usize) -> (usize, Option<usize>) { 592 (1, Some(std::mem::size_of::<usize>())) 593 } 594 } 595 596 /// Default module-level configuration for fuzzing Wasmtime. 597 /// 598 /// Internally this uses `wasm-smith`'s own `SwarmConfig` but we further refine 599 /// the defaults here as well. 600 #[derive(Debug, Clone)] 601 pub struct ModuleConfig { 602 #[allow(missing_docs)] 603 pub config: SwarmConfig, 604 } 605 606 impl<'a> Arbitrary<'a> for ModuleConfig { 607 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<ModuleConfig> { 608 let mut config = SwarmConfig::arbitrary(u)?; 609 610 // Allow multi-memory by default. 611 config.max_memories = config.max_memories.max(2); 612 613 // Allow multi-table by default. 614 config.max_tables = config.max_tables.max(4); 615 616 // Allow enabling some various wasm proposals by default. Note that 617 // these are all unconditionally turned off even with 618 // `SwarmConfig::arbitrary`. 619 config.memory64_enabled = u.arbitrary()?; 620 621 Ok(ModuleConfig { config }) 622 } 623 } 624 625 #[derive(Clone, Debug, Eq, Hash, PartialEq)] 626 enum CodegenSettings { 627 Native, 628 #[allow(dead_code)] 629 Target { 630 target: String, 631 flags: Vec<(String, String)>, 632 }, 633 } 634 635 impl CodegenSettings { 636 fn configure(&self, config: &mut wasmtime::Config) { 637 match self { 638 CodegenSettings::Native => {} 639 CodegenSettings::Target { target, flags } => { 640 config.target(target).unwrap(); 641 for (key, value) in flags { 642 unsafe { 643 config.cranelift_flag_set(key, value).unwrap(); 644 } 645 } 646 } 647 } 648 } 649 } 650 651 impl<'a> Arbitrary<'a> for CodegenSettings { 652 #[allow(unused_macros, unused_variables)] 653 fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { 654 // Helper macro to enable clif features based on what the native host 655 // supports. If the input says to enable a feature and the host doesn't 656 // support it then that test case is rejected with a warning. 657 // 658 // Note that this specifically consumes bytes from the fuzz input for 659 // features for all targets, discarding anything which isn't applicable 660 // to the current target. The theory behind this is that most fuzz bugs 661 // won't be related to this feature selection so by consistently 662 // consuming input irrespective of the current platform reproducing fuzz 663 // bugs should be easier between different architectures. 664 macro_rules! target_features { 665 ( 666 $( 667 $arch:tt => { 668 test:$test:ident, 669 $(std: $std:tt => clif: $clif:tt $(ratio: $a:tt in $b:tt)?,)* 670 }, 671 )* 672 ) => ({ 673 let mut flags = Vec::new(); 674 $( // for each `$arch` 675 $( // for each `$std`/`$clif` pair 676 // Use the input to generate whether `$clif` will be 677 // enabled. By default this is a 1 in 2 chance but each 678 // feature supports a custom ratio as well which shadows 679 // the (low, hi) 680 let (low, hi) = (1, 2); 681 $(let (low, hi) = ($a, $b);)? 682 let enable = u.ratio(low, hi)?; 683 684 // If we're actually on the relevant platform and the 685 // feature is enabled be sure to check that this host 686 // supports it. If the host doesn't support it then 687 // print a warning and return an error because this fuzz 688 // input must be discarded. 689 #[cfg(target_arch = $arch)] 690 if enable && !std::$test!($std) { 691 log::warn!("want to enable clif `{}` but host doesn't support it", 692 $clif); 693 return Err(arbitrary::Error::EmptyChoose) 694 } 695 696 // And finally actually push the feature into the set of 697 // flags to enable, but only if we're on the right 698 // architecture. 699 if cfg!(target_arch = $arch) { 700 flags.push(( 701 $clif.to_string(), 702 enable.to_string(), 703 )); 704 } 705 )* 706 )* 707 flags 708 }) 709 } 710 if u.ratio(1, 10)? { 711 let flags = target_features! { 712 "x86_64" => { 713 test: is_x86_feature_detected, 714 715 // These features are considered to be baseline required by 716 // Wasmtime. Currently some SIMD code generation will 717 // fail if these features are disabled, so unconditionally 718 // enable them as we're not interested in fuzzing without 719 // them. 720 std:"sse3" => clif:"has_sse3" ratio: 1 in 1, 721 std:"ssse3" => clif:"has_ssse3" ratio: 1 in 1, 722 std:"sse4.1" => clif:"has_sse41" ratio: 1 in 1, 723 std:"sse4.2" => clif:"has_sse42" ratio: 1 in 1, 724 725 std:"popcnt" => clif:"has_popcnt", 726 std:"avx" => clif:"has_avx", 727 std:"avx2" => clif:"has_avx2", 728 std:"bmi1" => clif:"has_bmi1", 729 std:"bmi2" => clif:"has_bmi2", 730 std:"lzcnt" => clif:"has_lzcnt", 731 732 // not a lot of of cpus support avx512 so these are weighted 733 // to get enabled much less frequently. 734 std:"avx512bitalg" => clif:"has_avx512bitalg" ratio:1 in 1000, 735 std:"avx512dq" => clif:"has_avx512dq" ratio: 1 in 1000, 736 std:"avx512f" => clif:"has_avx512f" ratio: 1 in 1000, 737 std:"avx512vl" => clif:"has_avx512vl" ratio: 1 in 1000, 738 std:"avx512vbmi" => clif:"has_avx512vbmi" ratio: 1 in 1000, 739 }, 740 }; 741 return Ok(CodegenSettings::Target { 742 target: target_lexicon::Triple::host().to_string(), 743 flags, 744 }); 745 } 746 Ok(CodegenSettings::Native) 747 } 748 } 749