| 1 |
use arbitrary::{Result, Unstructured}; |
| 2 |
use std::sync::atomic::{AtomicU64, Ordering}; |
| 3 |
use wasmparser::WasmFeatures; |
| 4 |
|
| 5 |
static NUM_RUNS: AtomicU64 = AtomicU64::new(0); |
| 6 |
static NUM_SUCCESSFUL_MUTATIONS: AtomicU64 = AtomicU64::new(0); |
| 7 |
|
| 8 |
pub fn run(u: &mut Unstructured<'_>) -> Result<()> { |
| 9 |
// Generate a random Wasm module with `wasm-smith` as well as a RNG seed for |
| 10 |
// use with `wasm-mutate`. |
| 11 |
|
| 12 |
let mut seed = 0; |
| 13 |
let mut preserve_semantics = false; |
| 14 |
let (wasm, _config) = crate::generate_valid_module(u, |config, u| { |
| 15 |
// NB: wasm-mutate is a general-purpose tool so unsupported proposals by |
| 16 |
// wasm-mutate are not disabled here. Those must be rejected with a |
| 17 |
// first-class error in wasm-mutate instead of panicking. |
| 18 |
seed = u.arbitrary()?; |
| 19 |
preserve_semantics = u.arbitrary()?; |
| 20 |
|
| 21 |
// NB: the mutator will change shared to unshared in ways that create |
| 22 |
// invalid modules so we disable the proposal (TODO: handle shared). |
| 23 |
config.shared_everything_threads_enabled = false; |
| 24 |
Ok(()) |
| 25 |
})?; |
| 26 |
log::debug!("seed = {seed}"); |
| 27 |
|
| 28 |
// Keep track of how many runs we've done thus far and how many of those |
| 29 |
// runs had successful mutations. |
| 30 |
|
| 31 |
let old_num_runs = NUM_RUNS.fetch_add(1, Ordering::Relaxed); |
| 32 |
if old_num_runs % 4096 == 4095 && log::log_enabled!(log::Level::Info) { |
| 33 |
let successful = NUM_SUCCESSFUL_MUTATIONS.load(Ordering::Relaxed); |
| 34 |
let percent = successful as f64 / old_num_runs as f64 * 100.0; |
| 35 |
log::info!("{successful} / {old_num_runs} ({percent:.2}%) successful mutations."); |
| 36 |
} |
| 37 |
|
| 38 |
// Mutate the Wasm with `wasm-mutate`. Assert that each mutation is still |
| 39 |
// valid Wasm. |
| 40 |
|
| 41 |
let mut wasm_mutate = wasm_mutate::WasmMutate::default(); |
| 42 |
wasm_mutate.seed(seed); |
| 43 |
wasm_mutate.fuel(300); |
| 44 |
wasm_mutate.preserve_semantics(preserve_semantics); |
| 45 |
|
| 46 |
let iterator = match wasm_mutate.run(&wasm) { |
| 47 |
Ok(iterator) => iterator, |
| 48 |
Err(e) => { |
| 49 |
log::warn!("Failed to mutate the Wasm: {e}"); |
| 50 |
return Ok(()); |
| 51 |
} |
| 52 |
}; |
| 53 |
|
| 54 |
let features = WasmFeatures::all(); |
| 55 |
|
| 56 |
for (i, mutated_wasm) in iterator.take(10).enumerate() { |
| 57 |
let mutated_wasm = match mutated_wasm { |
| 58 |
Ok(w) => w, |
| 59 |
Err(e) => match e.kind() { |
| 60 |
wasm_mutate::ErrorKind::NoMutationsApplicable => continue, |
| 61 |
_ => panic!("Unexpected mutation failure: {e}"), |
| 62 |
}, |
| 63 |
}; |
| 64 |
|
| 65 |
// Increase ony once for the same input Wasm. |
| 66 |
if i == 0 { |
| 67 |
NUM_SUCCESSFUL_MUTATIONS.fetch_add(1, Ordering::Relaxed); |
| 68 |
} |
| 69 |
|
| 70 |
let validation_result = |
| 71 |
wasmparser::Validator::new_with_features(features).validate_all(&mutated_wasm); |
| 72 |
|
| 73 |
if log::log_enabled!(log::Level::Debug) { |
| 74 |
log::debug!("writing mutated Wasm to `mutated.wasm`"); |
| 75 |
std::fs::write("mutated.wasm", &mutated_wasm) |
| 76 |
.expect("should write `mutated.wasm` okay"); |
| 77 |
if let Ok(mutated_wat) = wasmprinter::print_bytes(&mutated_wasm) { |
| 78 |
log::debug!("writing mutated WAT to `mutated.wat`"); |
| 79 |
std::fs::write("mutated.wat", &mutated_wat) |
| 80 |
.expect("should write `mutated.wat` okay"); |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
validation_result.expect("`wasm-mutate` should always produce a valid Wasm file"); |
| 85 |
|
| 86 |
// If semantics are preserved then assert so between executions of |
| 87 |
// Wasmtime if that's also enabled. |
| 88 |
#[cfg(feature = "wasmtime")] |
| 89 |
if preserve_semantics { |
| 90 |
eval::assert_same_evaluation(&wasm, &mutated_wasm); |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
Ok(()) |
| 95 |
} |
| 96 |
|
| 97 |
#[cfg(feature = "wasmtime")] |
| 98 |
#[path = "../../crates/fuzz-stats/src/lib.rs"] |
| 99 |
pub mod fuzz_stats; |
| 100 |
|
| 101 |
#[cfg(feature = "wasmtime")] |
| 102 |
mod eval { |
| 103 |
use super::fuzz_stats::{dummy, limits::StoreLimits}; |
| 104 |
use std::collections::hash_map::DefaultHasher; |
| 105 |
use std::hash::{Hash, Hasher}; |
| 106 |
use wasmtime::{ResourceLimiter, Val}; |
| 107 |
|
| 108 |
/// Compile, instantiate, and evaluate both the original and mutated Wasm. |
| 109 |
/// |
| 110 |
/// We should get identical results because we told `wasm-mutate` to preserve |
| 111 |
/// semantics. |
| 112 |
pub fn assert_same_evaluation(wasm: &[u8], mutated_wasm: &[u8]) { |
| 113 |
// FIXME: should re-enable this when the fuzzer works again, needs |
| 114 |
// someone to invest energy into running this locally for a long time |
| 115 |
// and then be on the hook for incoming oss-fuzz bugs. |
| 116 |
if true { |
| 117 |
return; |
| 118 |
} |
| 119 |
|
| 120 |
let mut config = wasmtime::Config::default(); |
| 121 |
config.cranelift_nan_canonicalization(true); |
| 122 |
config.consume_fuel(true); |
| 123 |
|
| 124 |
let engine = wasmtime::Engine::new(&config).unwrap(); |
| 125 |
|
| 126 |
let (orig_module, mutated_module) = match ( |
| 127 |
wasmtime::Module::new(&engine, &wasm), |
| 128 |
wasmtime::Module::new(&engine, &mutated_wasm), |
| 129 |
) { |
| 130 |
(Ok(o), Ok(m)) => (o, m), |
| 131 |
// Ideally we would assert that they both errored if either one did, but |
| 132 |
// it is possible that a mutation bumped some count above/below an |
| 133 |
// implementation limit. |
| 134 |
(_, _) => return, |
| 135 |
}; |
| 136 |
|
| 137 |
let limits = StoreLimits { |
| 138 |
remaining_memory: 1 << 30, |
| 139 |
oom: false, |
| 140 |
}; |
| 141 |
let mut orig_store = wasmtime::Store::new(&engine, limits.clone()); |
| 142 |
let mut mutated_store = wasmtime::Store::new(&engine, limits); |
| 143 |
orig_store.limiter(|s| s as &mut dyn ResourceLimiter); |
| 144 |
mutated_store.limiter(|s| s as &mut dyn ResourceLimiter); |
| 145 |
let orig_imports = match dummy::dummy_imports(&mut orig_store, &orig_module) { |
| 146 |
Ok(imps) => imps, |
| 147 |
Err(_) => return, |
| 148 |
}; |
| 149 |
let mutated_imports = match dummy::dummy_imports(&mut mutated_store, &mutated_module) { |
| 150 |
Ok(imps) => imps, |
| 151 |
Err(_) => return, |
| 152 |
}; |
| 153 |
|
| 154 |
let (orig_instance, mutated_instance) = match ( |
| 155 |
wasmtime::Instance::new(&mut orig_store, &orig_module, &orig_imports), |
| 156 |
wasmtime::Instance::new(&mut mutated_store, &mutated_module, &mutated_imports), |
| 157 |
) { |
| 158 |
(Ok(x), Ok(y)) => (x, y), |
| 159 |
(_, _) => return, |
| 160 |
}; |
| 161 |
|
| 162 |
assert_same_state( |
| 163 |
&orig_module, |
| 164 |
&mut orig_store, |
| 165 |
orig_instance, |
| 166 |
&mut mutated_store, |
| 167 |
mutated_instance, |
| 168 |
); |
| 169 |
let should_have_same_state = assert_same_calls( |
| 170 |
&orig_module, |
| 171 |
&mut orig_store, |
| 172 |
orig_instance, |
| 173 |
&mut mutated_store, |
| 174 |
mutated_instance, |
| 175 |
); |
| 176 |
|
| 177 |
if should_have_same_state { |
| 178 |
assert_same_state( |
| 179 |
&orig_module, |
| 180 |
&mut orig_store, |
| 181 |
orig_instance, |
| 182 |
&mut mutated_store, |
| 183 |
mutated_instance, |
| 184 |
); |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
fn assert_same_state( |
| 189 |
orig_module: &wasmtime::Module, |
| 190 |
orig_store: &mut wasmtime::Store<StoreLimits>, |
| 191 |
orig_instance: wasmtime::Instance, |
| 192 |
mutated_store: &mut wasmtime::Store<StoreLimits>, |
| 193 |
mutated_instance: wasmtime::Instance, |
| 194 |
) { |
| 195 |
for export in orig_module.exports() { |
| 196 |
match export.ty() { |
| 197 |
wasmtime::ExternType::Global(_) => { |
| 198 |
let orig = orig_instance |
| 199 |
.get_export(&mut *orig_store, export.name()) |
| 200 |
.unwrap() |
| 201 |
.into_global() |
| 202 |
.unwrap() |
| 203 |
.get(&mut *orig_store); |
| 204 |
let mutated = mutated_instance |
| 205 |
.get_export(&mut *mutated_store, export.name()) |
| 206 |
.unwrap() |
| 207 |
.into_global() |
| 208 |
.unwrap() |
| 209 |
.get(&mut *mutated_store); |
| 210 |
assert_val_eq(&orig, &mutated); |
| 211 |
} |
| 212 |
wasmtime::ExternType::Memory(_) => { |
| 213 |
let orig = orig_instance |
| 214 |
.get_export(&mut *orig_store, export.name()) |
| 215 |
.unwrap() |
| 216 |
.into_memory() |
| 217 |
.unwrap(); |
| 218 |
let mut h = DefaultHasher::default(); |
| 219 |
orig.data(&orig_store).hash(&mut h); |
| 220 |
let orig = h.finish(); |
| 221 |
let mutated = mutated_instance |
| 222 |
.get_export(&mut *mutated_store, export.name()) |
| 223 |
.unwrap() |
| 224 |
.into_memory() |
| 225 |
.unwrap(); |
| 226 |
let mut h = DefaultHasher::default(); |
| 227 |
mutated.data(&mutated_store).hash(&mut h); |
| 228 |
let mutated = h.finish(); |
| 229 |
assert_eq!(orig, mutated, "original and mutated Wasm memories diverged"); |
| 230 |
} |
| 231 |
_ => continue, |
| 232 |
} |
| 233 |
} |
| 234 |
} |
| 235 |
|
| 236 |
fn assert_same_calls( |
| 237 |
orig_module: &wasmtime::Module, |
| 238 |
orig_store: &mut wasmtime::Store<StoreLimits>, |
| 239 |
orig_instance: wasmtime::Instance, |
| 240 |
mutated_store: &mut wasmtime::Store<StoreLimits>, |
| 241 |
mutated_instance: wasmtime::Instance, |
| 242 |
) -> bool { |
| 243 |
for export in orig_module.exports() { |
| 244 |
let func_ty = match export.ty() { |
| 245 |
wasmtime::ExternType::Func(func_ty) => func_ty, |
| 246 |
_ => continue, |
| 247 |
}; |
| 248 |
let orig_func = orig_instance |
| 249 |
.get_func(&mut *orig_store, export.name()) |
| 250 |
.unwrap(); |
| 251 |
let mutated_func = mutated_instance |
| 252 |
.get_func(&mut *mutated_store, export.name()) |
| 253 |
.unwrap(); |
| 254 |
let args = dummy::dummy_values(func_ty.params()); |
| 255 |
let mut orig_results = vec![Val::I32(0); func_ty.results().len()]; |
| 256 |
let mut mutated_results = orig_results.clone(); |
| 257 |
log::debug!("invoking `{}`", export.name()); |
| 258 |
match ( |
| 259 |
{ |
| 260 |
orig_store.set_fuel(1_000).unwrap(); |
| 261 |
orig_func.call(&mut *orig_store, &args, &mut orig_results) |
| 262 |
}, |
| 263 |
{ |
| 264 |
mutated_store.set_fuel(1000).unwrap(); |
| 265 |
mutated_func.call(&mut *mutated_store, &args, &mut mutated_results) |
| 266 |
}, |
| 267 |
) { |
| 268 |
(Ok(()), Ok(())) => { |
| 269 |
for (orig_val, mutated_val) in orig_results.iter().zip(mutated_results.iter()) { |
| 270 |
assert_val_eq(orig_val, mutated_val); |
| 271 |
} |
| 272 |
} |
| 273 |
// If either test case ran out of fuel then that's ok since |
| 274 |
// mutation may add code or delete code which causes one side to |
| 275 |
// take more or less fuel than the other. In this situation, |
| 276 |
// however, execution has diverged so throw out the test case. |
| 277 |
(Err(e), _) | (_, Err(e)) |
| 278 |
if e.downcast_ref() == Some(&wasmtime::Trap::OutOfFuel) => |
| 279 |
{ |
| 280 |
return false; |
| 281 |
} |
| 282 |
(Err(orig), Err(mutated)) => { |
| 283 |
log::debug!("original error {orig:?}"); |
| 284 |
log::debug!("mutated error {mutated:?}"); |
| 285 |
continue; |
| 286 |
} |
| 287 |
(orig, mutated) => panic!( |
| 288 |
"mutated and original Wasm diverged: orig = {:?}; mutated = {:?}", |
| 289 |
orig, mutated, |
| 290 |
), |
| 291 |
} |
| 292 |
} |
| 293 |
|
| 294 |
true |
| 295 |
} |
| 296 |
|
| 297 |
fn assert_val_eq(orig_val: &wasmtime::Val, mutated_val: &wasmtime::Val) { |
| 298 |
match (orig_val, mutated_val) { |
| 299 |
(wasmtime::Val::I32(o), wasmtime::Val::I32(m)) => assert_eq!(o, m), |
| 300 |
(wasmtime::Val::I64(o), wasmtime::Val::I64(m)) => assert_eq!(o, m), |
| 301 |
(wasmtime::Val::F32(o), wasmtime::Val::F32(m)) => { |
| 302 |
let o = f32::from_bits(*o); |
| 303 |
let m = f32::from_bits(*m); |
| 304 |
assert!(o == m || (o.is_nan() && m.is_nan())); |
| 305 |
} |
| 306 |
(wasmtime::Val::F64(o), wasmtime::Val::F64(m)) => { |
| 307 |
let o = f64::from_bits(*o); |
| 308 |
let m = f64::from_bits(*m); |
| 309 |
assert!(o == m || (o.is_nan() && m.is_nan())); |
| 310 |
} |
| 311 |
(wasmtime::Val::V128(o), wasmtime::Val::V128(m)) => { |
| 312 |
assert_eq!(o, m) |
| 313 |
} |
| 314 |
(wasmtime::Val::ExternRef(o), wasmtime::Val::ExternRef(m)) => { |
| 315 |
assert_eq!(o.is_none(), m.is_none()) |
| 316 |
} |
| 317 |
(wasmtime::Val::FuncRef(o), wasmtime::Val::FuncRef(m)) => { |
| 318 |
assert_eq!(o.is_none(), m.is_none()) |
| 319 |
} |
| 320 |
(o, m) => panic!( |
| 321 |
"mutated and original Wasm diverged: orig = {:?}; mutated = {:?}", |
| 322 |
o, m, |
| 323 |
), |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
#[test] |
| 329 |
fn smoke() { |
| 330 |
super::test::test_n_times(100, run); |
| 331 |
} |