/src/wasmi/fuzz/fuzz_targets/translate.rs
Line | Count | Source |
1 | | #![no_main] |
2 | | |
3 | | use arbitrary::{Arbitrary, Unstructured}; |
4 | | use libfuzzer_sys::fuzz_target; |
5 | | use wasmi::{Config, Engine, Module}; |
6 | | use wasmi_fuzz::{config::ValidationMode, FuzzModule, FuzzWasmiConfig}; |
7 | | |
8 | | #[derive(Debug)] |
9 | | pub struct FuzzInput { |
10 | | config: FuzzWasmiConfig, |
11 | | module: FuzzModule, |
12 | | } |
13 | | |
14 | | impl<'a> Arbitrary<'a> for FuzzInput { |
15 | 12.8k | fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { |
16 | 12.8k | let config = FuzzWasmiConfig::arbitrary(u)?; |
17 | 12.8k | let fuzz_config = wasmi_fuzz::FuzzSmithConfig::arbitrary(u)?; |
18 | 12.8k | let module = wasmi_fuzz::FuzzModule::new(fuzz_config, u)?; |
19 | 12.7k | Ok(Self { config, module }) |
20 | 12.8k | } |
21 | | } |
22 | | |
23 | | fuzz_target!(|input: FuzzInput| { |
24 | | let FuzzInput { config, module } = input; |
25 | | let wasm_source = module.wasm(); |
26 | | let wasm = wasm_source.as_bytes(); |
27 | | let engine_config = Config::from(config); |
28 | | let engine = Engine::new(&engine_config); |
29 | | if matches!(config.validation_mode, ValidationMode::Unchecked) { |
30 | | // We validate the Wasm module before handing it over to Wasmi |
31 | | // despite `wasm_smith` stating to only produce valid Wasm. |
32 | | // Translating an invalid Wasm module is undefined behavior. |
33 | | if Module::validate(&engine, wasm).is_err() { |
34 | | return; |
35 | | } |
36 | | } |
37 | | let status = match config.validation_mode { |
38 | | ValidationMode::Checked => Module::new(&engine, wasm), |
39 | | ValidationMode::Unchecked => { |
40 | | // Safety: we just validated the Wasm input above. |
41 | | unsafe { Module::new_unchecked(&engine, wasm) } |
42 | | } |
43 | | }; |
44 | | if let Err(err) = status { |
45 | | let crash_input = wasmi_fuzz::generate_crash_inputs("translate", wasm).unwrap(); |
46 | | panic!( |
47 | | "\ |
48 | | encountered invalid translation: {err}\n\ |
49 | | \t- crash-report: 0x{crash_input}\n\ |
50 | | " |
51 | | ); |
52 | | } |
53 | | }); |