libafl 0.15.4

Slot your own fuzzers together and extend their features using Rust
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! An extension to the `ScheduledMutator` which schedules multiple mutations internally.
//!
//! Instead of a random mutator for a random amount of iterations, we can run
//! a specific mutator for a specified amount of iterations

use alloc::{borrow::Cow, vec::Vec};
use core::{fmt::Debug, num::NonZero};

use libafl_bolts::{
    Named, impl_serdeany, math::calculate_cumulative_distribution_in_place, rands::Rand,
    tuples::NamedTuple,
};
use serde::{Deserialize, Serialize};

pub use crate::mutators::{mutations::*, token_mutations::*};
use crate::{
    Error, HasMetadata,
    mutators::{
        ComposedByMutations, MutationId, MutationResult, Mutator, MutatorsTuple, ScheduledMutator,
    },
    state::HasRand,
};

/// Metadata in the state, that controls the behavior of the [`TuneableScheduledMutator`] at runtime
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[cfg_attr(
    any(not(feature = "serdeany_autoreg"), miri),
    expect(clippy::unsafe_derive_deserialize)
)] // for SerdeAny
pub struct TuneableScheduledMutatorMetadata {
    /// The offsets of mutators to run, in order. Clear to fall back to random,
    /// or use `mutation_probabilities`
    pub mutation_ids: Vec<MutationId>,
    /// The next index to read from in the `next` vec
    pub next_id: MutationId,
    /// The cumulative probability distribution for each mutation.
    /// Will not be used when `mutation_ids` are set.
    /// Clear to fall back to random.
    pub mutation_probabilities_cumulative: Vec<f32>,
    /// The count of mutations to stack.
    /// If `mutation_ids` is of length `10`, and this number is `20`,
    /// the mutations will be iterated through twice.
    pub iters: Option<u64>,
    /// The probability of each number of mutations to stack.
    pub iter_probabilities_pow_cumulative: Vec<f32>,
}

impl_serdeany!(TuneableScheduledMutatorMetadata);

impl Default for TuneableScheduledMutatorMetadata {
    fn default() -> Self {
        Self {
            mutation_ids: Vec::default(),
            next_id: 0.into(),
            mutation_probabilities_cumulative: Vec::default(),
            iters: None,
            iter_probabilities_pow_cumulative: Vec::default(),
        }
    }
}

impl TuneableScheduledMutatorMetadata {
    /// Gets the stored metadata, used to alter the [`TuneableScheduledMutator`] behavior
    pub fn get<S: HasMetadata>(state: &S) -> Result<&Self, Error> {
        state
            .metadata_map()
            .get::<Self>()
            .ok_or_else(|| Error::illegal_state("TuneableScheduledMutator not in use"))
    }

    /// Gets the stored metadata, used to alter the [`TuneableScheduledMutator`] behavior, mut
    pub fn get_mut<S: HasMetadata>(state: &mut S) -> Result<&mut Self, Error> {
        state
            .metadata_map_mut()
            .get_mut::<Self>()
            .ok_or_else(|| Error::illegal_state("TuneableScheduledMutator not in use"))
    }
}

/// A [`Mutator`] that schedules one of the embedded mutations on each call.
/// The index of the next mutation can be set.
#[derive(Debug)]
pub struct TuneableScheduledMutator<MT> {
    name: Cow<'static, str>,
    mutations: MT,
    max_stack_pow: usize,
}

impl<I, MT, S> Mutator<I, S> for TuneableScheduledMutator<MT>
where
    MT: MutatorsTuple<I, S>,
    S: HasRand + HasMetadata,
{
    #[inline]
    fn mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
        self.scheduled_mutate(state, input)
    }
    #[inline]
    fn post_exec(
        &mut self,
        _state: &mut S,
        _new_corpus_id: Option<crate::corpus::CorpusId>,
    ) -> Result<(), Error> {
        Ok(())
    }
}

impl<MT> ComposedByMutations for TuneableScheduledMutator<MT> {
    type Mutations = MT;
    /// Get the mutations
    #[inline]
    fn mutations(&self) -> &MT {
        &self.mutations
    }

    // Get the mutations (mutable)
    #[inline]
    fn mutations_mut(&mut self) -> &mut MT {
        &mut self.mutations
    }
}

impl<MT> Named for TuneableScheduledMutator<MT> {
    fn name(&self) -> &Cow<'static, str> {
        &self.name
    }
}

impl<I, MT, S> ScheduledMutator<I, S> for TuneableScheduledMutator<MT>
where
    MT: MutatorsTuple<I, S>,
    S: HasRand + HasMetadata,
{
    /// Compute the number of iterations used to apply stacked mutations
    fn iterations(&self, state: &mut S, _: &I) -> u64 {
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();

        if metadata.iter_probabilities_pow_cumulative.is_empty() {
            if let Some(iters) = metadata.iters {
                iters
            } else {
                // fall back to random
                1 << (1 + state.rand_mut().below_or_zero(self.max_stack_pow))
            }
        } else {
            // We will sample using the mutation probabilities.
            // Doing this outside of the original if branch to make the borrow checker happy.
            let coin = state.rand_mut().next_float() as f32;

            let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();
            let power = metadata
                .iter_probabilities_pow_cumulative
                .iter()
                .position(|i| *i >= coin)
                .unwrap();

            1 << (1 + power)
        }
    }

    /// Get the next mutation to apply
    fn schedule(&self, state: &mut S, _: &I) -> MutationId {
        // Assumption: we can not reach this code path without previously adding this metadatum.
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();

        if !metadata.mutation_ids.is_empty() {
            // using pre-set ids.
            let ret = metadata.mutation_ids[metadata.next_id.0];
            metadata.next_id.0 += 1_usize;
            if metadata.next_id.0 >= metadata.mutation_ids.len() {
                metadata.next_id = 0.into();
            }
            debug_assert!(
                self.mutations.len() > ret.0,
                "TuneableScheduler: next vec may not contain id larger than number of mutations!"
            );
            return ret;
        }

        if !metadata.mutation_probabilities_cumulative.is_empty() {
            // We will sample using the mutation probabilities.
            // Doing this outside of the original if branch to make the borrow checker happy.
            let coin = state.rand_mut().next_float() as f32;

            let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();
            debug_assert_eq!(
                self.mutations.len(),
                metadata.mutation_probabilities_cumulative.len(),
                "TuneableScheduler: mutation probabilities do not match with number of mutations"
            );

            let mutation_id = metadata
                .mutation_probabilities_cumulative
                .iter()
                .position(|i| *i >= coin)
                .unwrap()
                .into();

            return mutation_id;
        }

        // fall back to random if no entries in either vec, the scheduling is not tuned.
        state
            .rand_mut()
            .below(NonZero::new(self.mutations.len()).expect("No mutations provided!"))
            .into()
    }
}

impl<MT> TuneableScheduledMutator<MT> {
    /// Create a new [`TuneableScheduledMutator`] instance specifying mutations
    pub fn new<S>(state: &mut S, mutations: MT) -> Self
    where
        MT: NamedTuple,
        S: HasRand + HasMetadata,
    {
        if !state.has_metadata::<TuneableScheduledMutatorMetadata>() {
            state.add_metadata(TuneableScheduledMutatorMetadata::default());
        }
        TuneableScheduledMutator {
            name: Cow::from(format!("TuneableMutator[{}]", mutations.names().join(", "))),
            mutations,
            max_stack_pow: 7,
        }
    }
}

impl<MT> TuneableScheduledMutator<MT> {
    /// Sets the next iterations count, i.e., how many times to mutate the input
    ///
    /// Using `set_mutation_ids_and_iter` to set multiple values at the same time
    /// will be faster than setting them individually
    /// as it internally only needs a single metadata lookup
    pub fn set_iters<S>(&self, state: &mut S, iters: u64)
    where
        S: HasMetadata,
    {
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();

        metadata.iters = Some(iters);
        metadata.iter_probabilities_pow_cumulative.clear();
    }

    /// Sets the probability of next iteration counts,
    /// i.e., how many times the mutation is likely to get mutated.
    ///
    /// So, setting the `iter_probabilities` to `vec![0.1, 0.7, 0.2]`
    /// would apply 2^1 mutation with the likelihood of 10%, 2^2 mutations with the
    /// a probability of 70% (0.7), and 2^3 mutations with the likelihood of 20%.
    /// These will be applied for each call of this `mutate` function.
    ///
    /// Setting this function will unset everything previously set in `set_iters`.
    pub fn set_iter_probabilities_pow<S>(
        &self,
        state: &mut S,
        mut iter_probabilities_pow: Vec<f32>,
    ) -> Result<(), Error>
    where
        S: HasMetadata,
    {
        if iter_probabilities_pow.len() >= 32 {
            return Err(Error::illegal_argument(
                "Cannot stack more than 2^32 mutations",
            ));
        }
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();
        metadata.iters = None;

        // we precalculate the cumulative probability to be faster when sampling later.
        calculate_cumulative_distribution_in_place(&mut iter_probabilities_pow)?;
        metadata.iter_probabilities_pow_cumulative = iter_probabilities_pow;

        Ok(())
    }

    /// Gets the set amount of iterations
    pub fn get_iters<S>(&self, state: &S) -> Option<u64>
    where
        S: HasMetadata,
    {
        let metadata = TuneableScheduledMutatorMetadata::get(state).unwrap();
        metadata.iters
    }

    /// Sets the mutation ids
    pub fn set_mutation_ids<S>(&self, state: &mut S, mutations: Vec<MutationId>)
    where
        S: HasMetadata,
    {
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();
        metadata.mutation_ids = mutations;
        metadata.next_id = 0.into();
    }

    /// Sets the mutation probabilities.
    /// The `Vec` contains a probability per [`MutationId`]: between 0 and 1, and they have to add
    /// up to 1.
    /// Setting the probabilities will remove the value set through `set_mutation_ids`.
    pub fn set_mutation_probabilities<S>(
        &self,
        state: &mut S,
        mut mutation_probabilities: Vec<f32>,
    ) -> Result<(), Error>
    where
        S: HasMetadata,
    {
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();
        metadata.mutation_ids.clear();
        metadata.next_id = 0.into();

        // we precalculate the cumulative probability to be faster when sampling later.
        calculate_cumulative_distribution_in_place(&mut mutation_probabilities)?;
        metadata.mutation_probabilities_cumulative = mutation_probabilities;
        Ok(())
    }

    /// mutation ids and iterations
    pub fn set_mutation_ids_and_iters<S>(
        &self,
        state: &mut S,
        mutations: Vec<MutationId>,
        iters: u64,
    ) where
        S: HasMetadata,
    {
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();
        metadata.mutation_ids = mutations;
        metadata.next_id = 0.into();
        metadata.iters = Some(iters);
    }

    /// Appends a mutation id to the end of the mutations
    pub fn push_mutation_id<S>(state: &mut S, mutation_id: MutationId)
    where
        S: HasMetadata,
    {
        let metadata = TuneableScheduledMutatorMetadata::get_mut(state).unwrap();
        metadata.mutation_ids.push(mutation_id);
    }

    /// Resets this to a randomic mutational stage
    pub fn reset<S>(self, state: &mut S)
    where
        S: HasMetadata,
    {
        let metadata = state
            .metadata_map_mut()
            .get_mut::<TuneableScheduledMutatorMetadata>()
            .unwrap();
        metadata.mutation_ids.clear();
        metadata.next_id = 0.into();
        metadata.iters = None;
        metadata.mutation_probabilities_cumulative.clear();
        metadata.iter_probabilities_pow_cumulative.clear();
    }
}

#[cfg(test)]
mod test {
    use libafl_bolts::tuples::tuple_list;

    use super::{
        BitFlipMutator, ByteDecMutator, TuneableScheduledMutator, TuneableScheduledMutatorMetadata,
    };
    use crate::{
        inputs::BytesInput,
        mutators::{ByteRandMutator, ScheduledMutator},
        state::NopState,
    };

    #[test]
    fn test_tuning() {
        // # Safety
        // No concurrency per testcase
        #[cfg(any(not(feature = "serdeany_autoreg"), miri))]
        unsafe {
            TuneableScheduledMutatorMetadata::register();
        }

        let mut state: NopState<BytesInput> = NopState::new();
        let mutators = tuple_list!(
            BitFlipMutator::new(),
            ByteDecMutator::new(),
            ByteRandMutator::new()
        );
        let tuneable = TuneableScheduledMutator::new(&mut state, mutators);
        let input = BytesInput::new(vec![42]);
        let metadata = TuneableScheduledMutatorMetadata::get_mut(&mut state).unwrap();
        metadata.mutation_ids.push(1.into());
        metadata.mutation_ids.push(2.into());
        assert_eq!(tuneable.schedule(&mut state, &input), 1.into());
        assert_eq!(tuneable.schedule(&mut state, &input), 2.into());
        assert_eq!(tuneable.schedule(&mut state, &input), 1.into());
    }

    #[test]
    fn test_mutation_distribution() {
        // # Safety
        // No concurrency per testcase
        #[cfg(any(not(feature = "serdeany_autoreg"), miri))]
        unsafe {
            TuneableScheduledMutatorMetadata::register();
        }

        let mut state: NopState<BytesInput> = NopState::new();
        let mutators = tuple_list!(
            BitFlipMutator::new(),
            ByteDecMutator::new(),
            ByteRandMutator::new()
        );
        let tuneable = TuneableScheduledMutator::new(&mut state, mutators);
        let input = BytesInput::new(vec![42]);

        // Basic tests over the probability distribution.
        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![0.0])
                .is_err()
        );
        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![1.0; 3])
                .is_err()
        );
        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![-1.0, 1.0, 1.0])
                .is_err()
        );
        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![])
                .is_err()
        );

        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![0.0, 0.0, 1.0])
                .is_ok()
        );
        assert_eq!(tuneable.schedule(&mut state, &input), 2.into());
        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![0.0, 1.0, 0.0])
                .is_ok()
        );
        assert_eq!(tuneable.schedule(&mut state, &input), 1.into());
        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![1.0, 0.0, 0.0])
                .is_ok()
        );
        assert_eq!(tuneable.schedule(&mut state, &input), 0.into());

        // We should not choose a mutation with p=0.
        assert!(
            tuneable
                .set_mutation_probabilities(&mut state, vec![0.5, 0.0, 0.5])
                .is_ok()
        );
        assert!(tuneable.schedule(&mut state, &input) != 1.into());
    }
}