1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
use std::collections::HashSet;
use anyhow::{Context, Result};
use rand::{rngs::SmallRng, Rng, SeedableRng};
use wasm_mutate::WasmMutate;
#[rustfmt::skip]
static EMPTY_WASM: &'static [u8] = &[
0x00, b'a', b's', b'm',
0x01, 0x00, 0x00, 0x00,
];
#[cfg_attr(
not(feature = "clap"),
doc = r###"
Shrink a Wasm file while maintaining a property of interest (such as
triggering a compiler bug).
# Example
```
use wasm_shrink::WasmShrink;
# fn foo() -> anyhow::Result<()> {
// Get the Wasm you want to shrink from somewhere.
let my_input_wasm: Vec<u8> = todo!();
// Configure the shrinking task.
let shrink = WasmShrink::default()
// Give up on shrinking after 999 failed attempts to shrink a given
// Wasm test case any further.
.attempts(999);
// Run the configured shrinking task.
let info = shrink.run(
my_input_wasm,
// Predicate.
&mut |wasm| {
let is_interesting: bool = todo!(
"check for whether the given Wasm is interesting"
);
Ok(is_interesting)
},
// Callback called each time we find a new smallest interesting
// Wasm.
&mut |new_smallest| {
// Optionally do something with the new smallest Wasm.
Ok(())
},
)?;
// Get the shrunken Wasm and other information about the completed shrink
// task from the returned `ShrinkInfo`.
let shrunken_wasm = info.output;
# Ok(()) }
```
"###
)]
#[cfg_attr(feature = "clap", derive(clap::Parser))]
pub struct WasmShrink {
#[cfg_attr(feature = "clap", clap(short, long, default_value = "1000"))]
attempts: u32,
#[cfg_attr(feature = "clap", clap(long))]
allow_empty: bool,
#[cfg_attr(feature = "clap", clap(short, long, default_value = "42"))]
seed: u64,
}
impl Default for WasmShrink {
fn default() -> Self {
WasmShrink {
attempts: 1000,
allow_empty: false,
seed: 42,
}
}
}
impl WasmShrink {
pub fn attempts(mut self, attempts: u32) -> WasmShrink {
self.attempts = attempts;
self
}
pub fn allow_empty(mut self, allow_empty: bool) -> WasmShrink {
self.allow_empty = allow_empty;
self
}
pub fn seed(mut self, seed: u64) -> WasmShrink {
self.seed = seed;
self
}
pub fn run<P, I, S>(
self,
input: Vec<u8>,
mut predicate: P,
mut on_new_smallest: S,
) -> Result<ShrinkInfo>
where
P: FnMut(&[u8]) -> Result<I>,
I: IsInteresting,
S: FnMut(&[u8]) -> Result<()>,
{
let input_size = input.len() as u64;
self.validate_wasm(&input)
.context("The input is not valid Wasm.")?;
let result = predicate(&input)?;
anyhow::ensure!(
result.is_interesting(),
"The predicate does not consider the input Wasm interesting: {}",
result
);
let mut best = input;
let mut new_best = |old_best: &mut Vec<u8>, new: Vec<u8>| -> Result<()> {
debug_assert!(
new.len() < old_best.len() || (new == EMPTY_WASM && *old_best == EMPTY_WASM)
);
log::info!("New smallest Wasm found: {} bytes", new.len());
on_new_smallest(&new)?;
*old_best = new;
Ok(())
};
let result = predicate(EMPTY_WASM)?;
if result.is_interesting() {
if self.allow_empty {
new_best(&mut best, EMPTY_WASM.to_vec())?;
return Ok(ShrinkInfo {
input_size,
output_size: best.len() as u64,
output: best,
});
} else {
anyhow::bail!(
"The predicate considers the empty Wasm module \
interesting, which is usually not desired and \
is a symptom of a bug in the predicate:\n\
\n\
{}",
result
);
}
}
let mut rng = SmallRng::seed_from_u64(self.seed);
let mut uninteresting = HashSet::new();
loop {
let mut new_smallest = None;
let mut attempt = 0;
'attempts: while attempt < self.attempts {
let mut mutate = WasmMutate::default();
let seed = rng.gen();
mutate.reduce(true).seed(seed);
log::trace!("Attempt #{}: seed: {}", attempt, seed);
let mutations = match mutate.run(&best) {
Ok(m) => m,
Err(e) => {
log::trace!("Attempt #{}: mutation failed ({:?})", attempt, e);
attempt += 1;
continue;
}
};
for mutated_wasm in mutations
.take(std::cmp::min(self.attempts - attempt, 10) as usize)
{
let mutated_wasm = match mutated_wasm {
Ok(w) => w,
Err(e) => {
log::trace!("Attempt #{}: mutation failed ({:?})", attempt, e);
attempt += 1;
continue;
}
};
if mutated_wasm.len() >= best.len() {
log::trace!(
"Attempt #{}: mutated Wasm ({} bytes) is not smaller than \
best ({} bytes)",
attempt,
mutated_wasm.len(),
best.len(),
);
attempt += 1;
continue;
}
let hash = blake3::hash(&mutated_wasm);
if uninteresting.contains(&hash) {
log::trace!(
"Attempt #{}: already tested this candidate and found it uninteresting",
attempt
);
attempt += 1;
continue;
}
log::trace!(
"Attempt #{}: testing candidate ({} bytes)",
attempt,
mutated_wasm.len()
);
attempt += 1;
if predicate(&mutated_wasm)?.is_interesting() {
new_smallest = Some(mutated_wasm);
break 'attempts;
}
uninteresting.insert(hash);
}
}
match new_smallest {
None => break,
Some(w) => new_best(&mut best, w)?,
}
}
Ok(ShrinkInfo {
input_size,
output_size: best.len() as u64,
output: best,
})
}
fn validate_wasm(&self, wasm: &[u8]) -> Result<()> {
let mut validator = wasmparser::Validator::new();
validator.wasm_features(wasmparser::WasmFeatures {
reference_types: true,
multi_value: true,
bulk_memory: true,
module_linking: false,
simd: true,
threads: true,
tail_call: true,
multi_memory: true,
exceptions: true,
memory64: true,
relaxed_simd: true,
extended_const: true,
deterministic_only: false,
});
validator.validate_all(wasm)?;
Ok(())
}
}
pub trait IsInteresting: std::fmt::Display {
fn is_interesting(&self) -> bool;
}
impl IsInteresting for bool {
fn is_interesting(&self) -> bool {
*self
}
}
pub struct ShrinkInfo {
pub input_size: u64,
pub output_size: u64,
pub output: Vec<u8>,
}