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
//! Whole corpus minimizers, for reducing the number of samples/the total size/the average runtime
//! of your corpus.
use alloc::{borrow::Cow, string::ToString, vec::Vec};
use core::{hash::Hash, marker::PhantomData, time::Duration};
use hashbrown::{HashMap, HashSet};
use libafl_bolts::{
AsIter, Named,
tuples::{Handle, Handled},
};
use num_traits::ToPrimitive;
use z3::{Optimize, ast::Bool};
use crate::{
Error, HasMetadata, HasScheduler,
corpus::Corpus,
events::{Event, EventFirer, EventWithStats, LogSeverity},
executors::{Executor, ExitKind, HasObservers},
inputs::Input,
monitors::stats::{AggregatorOps, UserStats, UserStatsValue},
observers::{MapObserver, ObserversTuple},
schedulers::{LenTimeMulTestcasePenalty, RemovableScheduler, Scheduler, TestcasePenalty},
stages::run_target_with_timing,
state::{HasCorpus, HasExecutions},
};
/// Minimizes a corpus according to coverage maps, weighting by the specified `TestcasePenalty`.
///
/// Algorithm based on WMOPT: <https://hexhive.epfl.ch/publications/files/21ISSTA2.pdf>
#[derive(Debug)]
pub struct MapCorpusMinimizer<C, E, I, O, S, T, TP> {
observer_handle: Handle<C>,
phantom: PhantomData<(E, I, O, S, T, TP)>,
}
/// Standard corpus minimizer, which weights inputs by length and time.
pub type StdCorpusMinimizer<C, E, I, O, S, T> =
MapCorpusMinimizer<C, E, I, O, S, T, LenTimeMulTestcasePenalty>;
impl<C, E, I, O, S, T, TP> MapCorpusMinimizer<C, E, I, O, S, T, TP>
where
C: Named,
{
/// Constructs a new `MapCorpusMinimizer` from a provided observer. This observer will be used
/// in the future to get observed maps from an executed input.
pub fn new(obs: &C) -> Self {
Self {
observer_handle: obs.handle(),
phantom: PhantomData,
}
}
}
impl<C, E, I, O, S, T, TP> MapCorpusMinimizer<C, E, I, O, S, T, TP>
where
for<'a> O: MapObserver<Entry = T> + AsIter<'a, Item = T>,
C: AsRef<O>,
I: Input,
S: HasMetadata + HasCorpus<I> + HasExecutions,
T: Copy + Hash + Eq,
TP: TestcasePenalty<I, S>,
{
/// Do the minimization
#[expect(clippy::too_many_lines)]
pub fn minimize<CS, EM, Z>(
&self,
fuzzer: &mut Z,
executor: &mut E,
mgr: &mut EM,
state: &mut S,
) -> Result<(), Error>
where
E: Executor<EM, I, S, Z> + HasObservers,
E::Observers: ObserversTuple<I, S>,
CS: Scheduler<I, S> + RemovableScheduler<I, S>,
EM: EventFirer<I, S>,
Z: HasScheduler<I, S, Scheduler = CS>,
{
// don't delete this else it won't work after restart
let current = *state.corpus().current();
let opt = Optimize::new();
let mut seed_exprs = HashMap::new();
let mut cov_map = HashMap::new();
let mut cur_id = state.corpus().first();
mgr.log(
state,
LogSeverity::Info,
"Executing each input...".to_string(),
)?;
let total = state.corpus().count() as u64;
let mut curr = 0;
while let Some(id) = cur_id {
let (weight, executions) = {
if state.corpus().get(id)?.borrow().scheduled_count() == 0 {
// Execute the input; we cannot rely on the metadata already being present.
let input = state
.corpus()
.get(id)?
.borrow_mut()
.load_input(state.corpus())?
.clone();
let (exit_kind, mut total_time, _) =
run_target_with_timing(fuzzer, executor, state, mgr, &input, false)?;
if exit_kind != ExitKind::Ok {
total_time = Duration::from_secs(1);
}
state
.corpus()
.get(id)?
.borrow_mut()
.set_exec_time(total_time);
}
let mut testcase = state.corpus().get(id)?.borrow_mut();
(
TP::compute(state, &mut *testcase)?
.to_u64()
.expect("Weight must be computable."),
*state.executions(),
)
};
curr += 1;
mgr.fire(
state,
EventWithStats::with_current_time(
Event::UpdateUserStats {
name: Cow::from("minimisation exec pass"),
value: UserStats::new(
UserStatsValue::Ratio(curr, total),
AggregatorOps::None,
),
phantom: PhantomData,
},
executions,
),
)?;
let seed_expr = Bool::fresh_const("seed");
let observers = executor.observers();
let obs = observers[&self.observer_handle].as_ref();
// Store coverage, mapping coverage map indices to hit counts (if present) and the
// associated seeds for the map indices with those hit counts.
for (i, e) in obs.as_iter().map(|x| *x).enumerate() {
if e != obs.initial() {
cov_map
.entry(i)
.or_insert_with(HashMap::new)
.entry(e)
.or_insert_with(HashSet::new)
.insert(seed_expr.clone());
}
}
// Keep track of that seed's index and weight
seed_exprs.insert(seed_expr, (id, weight));
cur_id = state.corpus().next(id);
}
mgr.log(
state,
LogSeverity::Info,
"Preparing Z3 assertions...".to_string(),
)?;
for (_, cov) in cov_map {
for (_, seeds) in cov {
// At least one seed for each hit count of each coverage map index
if let Some(reduced) = seeds.into_iter().reduce(|s1, s2| s1 | s2) {
opt.assert(&reduced);
}
}
}
for (seed, (_, weight)) in &seed_exprs {
// opt will attempt to minimise the number of violated assertions.
//
// To tell opt to minimize the number of seeds, we tell opt to maximize the number of
// not seeds.
//
// Additionally, each seed has a weight associated with them; the higher, the more z3
// doesn't want to violate the assertion. Thus, inputs which have higher weights will be
// less likely to appear in the final corpus -- provided all their coverage points are
// hit by at least one other input.
opt.assert_soft(&!seed, *weight, None);
}
mgr.log(state, LogSeverity::Info, "Performing MaxSAT...".to_string())?;
// Perform the optimization!
opt.check(&[]);
if let Some(model) = opt.get_model() {
let mut removed = Vec::with_capacity(state.corpus().count());
for (seed, (id, _)) in seed_exprs {
// if the model says the seed isn't there, mark it for deletion
if !model.eval(&seed, true).unwrap().as_bool().unwrap() {
removed.push(id);
}
}
// reverse order; if indexes are stored in a vec, we need to remove from back to front
removed.sort_unstable_by(|id1, id2| id2.cmp(id1));
for id in removed {
if let Some(_cur) = current {
continue;
}
let removed = state.corpus_mut().remove(id)?;
// scheduler needs to know we've removed the input, or it will continue to try
// to use now-missing inputs
fuzzer
.scheduler_mut()
.on_remove(state, id, &Some(removed))?;
}
*state.corpus_mut().current_mut() = None; //we may have removed the current ID from the corpus
return Ok(());
}
Err(Error::unknown("Corpus minimization failed; unsat."))
}
}