puffin/fuzzer/
stages.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::fmt::Debug;
4use std::marker::PhantomData;
5
6use libafl::prelude::*;
7use libafl_bolts::prelude::*;
8
9use crate::fuzzer::utils::set_step_lock;
10use crate::protocol::ProtocolTypes;
11use crate::trace::Trace;
12
13/// A [`Mutator`] that schedules one of the embedded mutations on each call.
14pub struct FocusScheduledMutator<I, MT, MtPre, MtPost, S>
15where
16    MT: MutatorsTuple<I, S>,
17    MtPre: MutatorsTuple<I, S>,
18    MtPost: MutatorsTuple<I, S>,
19    S: HasRand,
20{
21    name: Cow<'static, str>,
22    mutations_core: MT,
23    mutations_pre: MtPre,
24    mutations_post: MtPost,
25    max_stack_pow: usize,
26    phantom: PhantomData<(I, S)>,
27}
28
29impl<I, MT, MtPre, MtPost, S> Debug for FocusScheduledMutator<I, MT, MtPre, MtPost, S>
30where
31    MT: MutatorsTuple<I, S>,
32    MtPre: MutatorsTuple<I, S>,
33    MtPost: MutatorsTuple<I, S>,
34    S: HasRand,
35{
36    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
37        write!(
38            f,
39            "FocusScheduledMutator with {} core mutations, {} pre-mutations, {} post-mutations, for Input type {}",
40            self.mutations_core.len(),
41            self.mutations_pre.len(),
42            self.mutations_post.len(),
43            core::any::type_name::<I>()
44        )
45    }
46}
47
48impl<I, MT, MtPre, MtPost, S> Named for FocusScheduledMutator<I, MT, MtPre, MtPost, S>
49where
50    MT: MutatorsTuple<I, S> + NamedTuple,
51    MtPre: MutatorsTuple<I, S> + NamedTuple,
52    MtPost: MutatorsTuple<I, S> + NamedTuple,
53    S: HasRand,
54{
55    fn name(&self) -> &Cow<'static, str> {
56        &self.name
57    }
58}
59
60impl<I, MT, MtPre, MtPost, S> Mutator<I, S> for FocusScheduledMutator<I, MT, MtPre, MtPost, S>
61where
62    MT: MutatorsTuple<I, S> + NamedTuple,
63    MtPre: MutatorsTuple<I, S> + NamedTuple,
64    MtPost: MutatorsTuple<I, S> + NamedTuple,
65    S: HasRand,
66{
67    #[inline]
68    fn mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
69        self.scheduled_mutate(state, input)
70    }
71
72    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
73        Ok(())
74    }
75}
76
77impl<I, MT, MtPre, MtPost, S> ComposedByMutations for FocusScheduledMutator<I, MT, MtPre, MtPost, S>
78where
79    MT: MutatorsTuple<I, S>,
80    MtPre: MutatorsTuple<I, S>,
81    MtPost: MutatorsTuple<I, S>,
82    S: HasRand,
83{
84    type Mutations = MT;
85
86    /// Get the core mutations (pre/post are handled separately in scheduled_mutate)
87    fn mutations(&self) -> &Self::Mutations {
88        &self.mutations_core
89    }
90
91    /// Get the core mutations (mutable)
92    fn mutations_mut(&mut self) -> &mut Self::Mutations {
93        &mut self.mutations_core
94    }
95}
96
97impl<I, MT, MtPre, MtPost, S> ScheduledMutator<I, S>
98    for FocusScheduledMutator<I, MT, MtPre, MtPost, S>
99where
100    MT: MutatorsTuple<I, S> + NamedTuple,
101    MtPre: MutatorsTuple<I, S> + NamedTuple,
102    MtPost: MutatorsTuple<I, S> + NamedTuple,
103    S: HasRand,
104{
105    /// Compute the number of iterations used to apply stacked mutations
106    fn iterations(&self, state: &mut S, _: &I) -> u64 {
107        1 << (1 + state.rand_mut().below_or_zero(self.max_stack_pow))
108    }
109
110    /// Get the next mutation to apply (base implementation)
111    fn schedule(&self, _: &mut S, _: &I) -> MutationId {
112        panic!("[FocusScheduledMutator] mutations - schedule - should never be used");
113    }
114
115    /// New default implementation for mutate.
116    /// Implementations must forward `mutate()` to this method
117    fn scheduled_mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
118        let mut r = MutationResult::Skipped;
119        let num = self.iterations(state, input);
120        log::debug!(
121            "FocusScheduledMutator: num: {}, max_stack_pow: {}",
122            num,
123            self.max_stack_pow
124        );
125        // Pre-mutation: schedule exactly once
126        // Note: the pre mutations will recognize this stage_idx and there is a certain probability
127        // that the mutation won't be applied. However, a payload path will always be chosen and
128        // stored in the input metadata for the later, HAVOC, and ReadMessage mutations.
129        let idx = self.schedule_pre(state, input);
130        log::debug!("FocusScheduledMutator: PRE idx: {}", idx);
131        let outcome = self.mutations_pre_mut().get_and_mutate(idx, state, input)?;
132        if outcome == MutationResult::Mutated {
133            r = MutationResult::Mutated;
134        }
135
136        // Core mutations
137        for _ in 0..num {
138            let idx = self.schedule_core(state, input);
139            log::debug!("FocusScheduledMutator: CORE idx: {}", idx);
140            let outcome = self
141                .mutations_core_mut()
142                .get_and_mutate(idx, state, input)?;
143            if outcome == MutationResult::Mutated {
144                r = MutationResult::Mutated;
145            }
146        }
147
148        // Post-mutation: schedule exactly once
149        // Note: the post mutations will recognize this stage_idx and there is a certain probability
150        // that the mutation won't be applied, so we can skip it
151        let idx = self.schedule_post(state, input);
152        log::debug!("FocusScheduledMutator: POST idx: {}", idx);
153        let outcome = self
154            .mutations_post_mut()
155            .get_and_mutate(idx, state, input)?;
156        if outcome == MutationResult::Mutated {
157            r = MutationResult::Mutated;
158        }
159
160        Ok(r)
161    }
162}
163
164impl<I, MT, MtPre, MtPost, S> FocusScheduledMutator<I, MT, MtPre, MtPost, S>
165where
166    MT: MutatorsTuple<I, S> + NamedTuple,
167    MtPre: MutatorsTuple<I, S> + NamedTuple,
168    MtPost: MutatorsTuple<I, S> + NamedTuple,
169    S: HasRand,
170{
171    /// Create a new [`libafl::mutators::ScheduledMutator`] instance specifying mutations
172    pub fn new(mutations_pre: MtPre, mutations_core: MT, mutations_post: MtPost) -> Self {
173        FocusScheduledMutator {
174            name: Cow::from(format!(
175                "FocusScheduledMutator[{};{};{}]",
176                mutations_pre.names().join(", "),
177                mutations_core.names().join(", "),
178                mutations_post.names().join(", ")
179            )),
180            mutations_core,
181            mutations_pre,
182            mutations_post,
183            max_stack_pow: 7,
184            phantom: PhantomData,
185        }
186    }
187
188    /// Create a new [`libafl::mutators::ScheduledMutator`] instance specifying mutations and the
189    /// maximum number of iterations
190    // pub fn with_max_stack_pow(mutations_pre:  MtPre, mutations: MT, mutations_post: MtPost,
191    // max_stack_pow: u64) -> Self {     FocusScheduledMutator {
192    //         name: format!("FocusScheduledMutator[{};{};{}]", mutations_pre.names().join(", "),
193    // mutations.names().join(", "), mutations_post.names().join(", ")),         mutations,
194    //         mutations_pre,
195    //         mutations_post,
196    //         max_stack_pow,
197    //         phantom: PhantomData,
198    //     }
199    // }
200
201    /// Get the next core-mutation to apply
202    fn schedule_core(&self, state: &mut S, _: &I) -> MutationId {
203        debug_assert!(!self.mutations_core.is_empty());
204        state
205            .rand_mut()
206            .below_or_zero(self.mutations_core.len())
207            .into()
208    }
209
210    /// Get the next pre-mutation to apply
211    fn schedule_pre(&self, state: &mut S, _: &I) -> MutationId {
212        debug_assert!(!self.mutations_pre.is_empty());
213        state
214            .rand_mut()
215            .below_or_zero(self.mutations_pre.len())
216            .into()
217    }
218
219    /// Get the next post-mutation to apply
220    fn schedule_post(&self, state: &mut S, _: &I) -> MutationId {
221        debug_assert!(!self.mutations_post.is_empty());
222        state
223            .rand_mut()
224            .below_or_zero(self.mutations_post.len())
225            .into()
226    }
227
228    /// Get the pre-mutations (mutable): we use a custom selection instead of the default
229    fn mutations_pre_mut(&mut self) -> &mut MtPre {
230        &mut self.mutations_pre
231    }
232
233    /// Get the core-mutations (mutable): we use a custom selection instead of the default
234    fn mutations_core_mut(&mut self) -> &mut MT {
235        &mut self.mutations_core
236    }
237
238    /// Get the post-mutations (mutable): we use a custom selection instead of the default
239    fn mutations_post_mut(&mut self) -> &mut MtPost {
240        &mut self.mutations_post
241    }
242
243    pub fn mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
244        self.scheduled_mutate(state, input)
245    }
246}
247
248/// A [`Mutator`] that schedules one of the embedded mutations on each call.
249pub struct PuffinScheduledMutator<I, MT, S>
250where
251    I: Input,
252    MT: MutatorsTuple<I, S>,
253    S: HasRand,
254{
255    mutations: MT,
256    phantom: PhantomData<(I, S)>,
257    max_mutations_per_iteration: usize,
258}
259
260impl<I, MT, S> Debug for PuffinScheduledMutator<I, MT, S>
261where
262    I: Input,
263    MT: MutatorsTuple<I, S>,
264    S: HasRand,
265{
266    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
267        write!(
268            f,
269            "PuffinScheduledMutator with {} mutations for Input type {}",
270            self.mutations.len(),
271            core::any::type_name::<I>()
272        )
273    }
274}
275
276impl<I, MT, S> Named for PuffinScheduledMutator<I, MT, S>
277where
278    I: Input,
279    MT: MutatorsTuple<I, S>,
280    S: HasRand,
281{
282    fn name(&self) -> &Cow<'static, str> {
283        &Cow::Borrowed("PuffinScheduledMutator")
284    }
285}
286
287impl<I, MT, S> Mutator<I, S> for PuffinScheduledMutator<I, MT, S>
288where
289    I: Input,
290    MT: MutatorsTuple<I, S>,
291    S: HasRand,
292{
293    #[inline]
294    fn mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
295        self.scheduled_mutate(state, input)
296    }
297
298    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
299        Ok(())
300    }
301}
302
303impl<I, MT, S> ComposedByMutations for PuffinScheduledMutator<I, MT, S>
304where
305    I: Input,
306    MT: MutatorsTuple<I, S>,
307    S: HasRand,
308{
309    type Mutations = MT;
310
311    /// Get the mutations
312    #[inline]
313    fn mutations(&self) -> &Self::Mutations {
314        &self.mutations
315    }
316
317    // Get the mutations (mut)
318    #[inline]
319    fn mutations_mut(&mut self) -> &mut Self::Mutations {
320        &mut self.mutations
321    }
322}
323
324impl<I, MT, S> ScheduledMutator<I, S> for PuffinScheduledMutator<I, MT, S>
325where
326    I: Input,
327    MT: MutatorsTuple<I, S>,
328    S: HasRand,
329{
330    /// Compute the number of iterations used to apply stacked mutations
331    fn iterations(&self, state: &mut S, _: &I) -> u64 {
332        state
333            .rand_mut()
334            .below_or_zero(self.max_mutations_per_iteration) as u64
335    }
336
337    /// Get the next mutation to apply
338    fn schedule(&self, state: &mut S, _: &I) -> MutationId {
339        debug_assert!(!self.mutations().is_empty());
340        state
341            .rand_mut()
342            .below_or_zero(self.mutations().len())
343            .into()
344    }
345}
346
347impl<I, MT, S> PuffinScheduledMutator<I, MT, S>
348where
349    I: Input,
350    MT: MutatorsTuple<I, S>,
351    S: HasRand,
352{
353    #[allow(dead_code)]
354    /// Create a new [`PuffinScheduledMutator`] instance specifying mutations
355    pub const fn new(mutations: MT, max_mutations_per_iteration: usize) -> Self {
356        Self {
357            mutations,
358            phantom: PhantomData,
359            max_mutations_per_iteration,
360        }
361    }
362}
363
364/// Wraps a [`ScheduledMutator`], forcing a FIXED number `n` of stacked inner mutations per input
365/// instead of the random `1<<(1+rand(0..7))` = 2..256. Selected via the `DY_STACK` env var.
366///
367/// Motivation (coverage-hitchhiker effect): the mutational stage applies n mutations at once; if
368/// the bundle gains coverage, LibAFL stores ALL n even if only one was responsible. Measured: with
369/// the default stacking, ~100% of coverage-gaining inputs also restructure the trace (junk
370/// hitchhikers), eroding deep structures (e.g. the bad-switch multi-channel trace). Forcing small n
371/// keeps corpus entries clean. Delegates everything to the inner mutator except `iterations()`.
372pub struct FixedStackMutator<M> {
373    inner: M,
374    n: u64,
375}
376
377impl<M> FixedStackMutator<M> {
378    pub fn new(inner: M, n: u64) -> Self {
379        Self { inner, n }
380    }
381}
382
383impl<M: Named> Named for FixedStackMutator<M> {
384    fn name(&self) -> &Cow<'static, str> {
385        self.inner.name()
386    }
387}
388
389impl<M: ComposedByMutations> ComposedByMutations for FixedStackMutator<M> {
390    type Mutations = M::Mutations;
391
392    fn mutations(&self) -> &Self::Mutations {
393        self.inner.mutations()
394    }
395
396    fn mutations_mut(&mut self) -> &mut Self::Mutations {
397        self.inner.mutations_mut()
398    }
399}
400
401impl<I, S, M> Mutator<I, S> for FixedStackMutator<M>
402where
403    M: ScheduledMutator<I, S>,
404    M::Mutations: MutatorsTuple<I, S>,
405{
406    #[inline]
407    fn mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
408        self.scheduled_mutate(state, input)
409    }
410
411    fn post_exec(&mut self, _state: &mut S, _id: Option<CorpusId>) -> Result<(), Error> {
412        Ok(())
413    }
414}
415
416impl<I, S, M> ScheduledMutator<I, S> for FixedStackMutator<M>
417where
418    M: ScheduledMutator<I, S>,
419    M::Mutations: MutatorsTuple<I, S>,
420{
421    fn iterations(&self, _state: &mut S, _input: &I) -> u64 {
422        self.n
423    }
424
425    fn schedule(&self, state: &mut S, input: &I) -> MutationId {
426        self.inner.schedule(state, input)
427    }
428}
429
430/// Wraps a [`ScheduledMutator`], drawing the number of stacked mutations per input from a
431/// TRUNCATED-GEOMETRIC distribution concentrated on 1-2 edits instead of AFL's `1<<(1+rand(0..7))`
432/// (mean ~36, median 16). AFL's log-uniform stacking suits flat byte inputs where a mutation is
433/// cheap/local; for grammar/DY term-tree mutation each edit is semantic and stacking dozens
434/// destroys deep structure and stores ~all as coverage hitchhikers (measured: 0% clean
435/// coverage-gains).
436///
437/// Distribution (cap 16): P(1)=0.40, P(2)=0.35, and the remaining 0.25 spread geometrically over
438/// n=3..=16 (ratio 1/2). => mean ~2.0, but keeps a light tail so coordinated multi-edit bugs and
439/// plateau-escaping big jumps remain reachable. Selected via env `DY_STACK=geo`.
440pub struct GeometricStackMutator<M> {
441    inner: M,
442}
443
444impl<M> GeometricStackMutator<M> {
445    pub fn new(inner: M) -> Self {
446        Self { inner }
447    }
448}
449
450impl<M: Named> Named for GeometricStackMutator<M> {
451    fn name(&self) -> &Cow<'static, str> {
452        self.inner.name()
453    }
454}
455
456impl<M: ComposedByMutations> ComposedByMutations for GeometricStackMutator<M> {
457    type Mutations = M::Mutations;
458
459    fn mutations(&self) -> &Self::Mutations {
460        self.inner.mutations()
461    }
462
463    fn mutations_mut(&mut self) -> &mut Self::Mutations {
464        self.inner.mutations_mut()
465    }
466}
467
468impl<I, S, M> Mutator<I, S> for GeometricStackMutator<M>
469where
470    S: HasRand,
471    M: ScheduledMutator<I, S>,
472    M::Mutations: MutatorsTuple<I, S>,
473{
474    #[inline]
475    fn mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
476        self.scheduled_mutate(state, input)
477    }
478
479    fn post_exec(&mut self, _state: &mut S, _id: Option<CorpusId>) -> Result<(), Error> {
480        Ok(())
481    }
482}
483
484impl<I, S, M> ScheduledMutator<I, S> for GeometricStackMutator<M>
485where
486    S: HasRand,
487    M: ScheduledMutator<I, S>,
488    M::Mutations: MutatorsTuple<I, S>,
489{
490    fn iterations(&self, state: &mut S, _input: &I) -> u64 {
491        // Integer thresholds over [0,100): [0,40)->1, [40,75)->2, else geometric 3..=16.
492        let r = state.rand_mut().below_or_zero(100);
493        if r < 40 {
494            1
495        } else if r < 75 {
496            2
497        } else {
498            let mut n: u64 = 3;
499            // 0.25 remaining mass spread geometrically (ratio 1/2), capped at 16.
500            while n < 16 && state.rand_mut().below_or_zero(2) == 0 {
501                n += 1;
502            }
503            n
504        }
505    }
506
507    fn schedule(&self, state: &mut S, input: &I) -> MutationId {
508        self.inner.schedule(state, input)
509    }
510}
511
512/// A [`Mutator`] wrapper that, when `enabled`, confines every anchor selection of the inner
513/// (stacking) mutator to a single randomly-chosen step for the duration of one mutational stage.
514///
515/// Rationale: with heavy stacking, a stage's mutations otherwise anchor on *different* steps -- one
516/// can improve coverage at step k while another breaks executability at a later step j, yet the
517/// whole (broken-tailed) trace is still saved to the corpus because coverage improved (the
518/// "coverage hitchhiker" effect). Locking all anchors of a stage to one step makes the coverage
519/// gain and any executability break attributable to the same step.
520///
521/// The lock is applied via [`crate::fuzzer::utils::set_step_lock`], which only affects anchor
522/// selection ([`crate::fuzzer::utils::reservoir_sample`]); Global/Step *fan-out* still spreads a
523/// mutation's effect across the whole trace, so a Global mutation's effect reaches other steps --
524/// only its anchor is confined to the locked step.
525pub struct StepLockedStackMutator<PT, M> {
526    inner: M,
527    enabled: bool,
528    phantom: PhantomData<PT>,
529}
530
531impl<PT, M> StepLockedStackMutator<PT, M> {
532    pub fn new(inner: M, enabled: bool) -> Self {
533        Self {
534            inner,
535            enabled,
536            phantom: PhantomData,
537        }
538    }
539}
540
541impl<PT, M: Named> Named for StepLockedStackMutator<PT, M> {
542    fn name(&self) -> &Cow<'static, str> {
543        self.inner.name()
544    }
545}
546
547impl<PT, M: ComposedByMutations> ComposedByMutations for StepLockedStackMutator<PT, M> {
548    type Mutations = M::Mutations;
549
550    fn mutations(&self) -> &Self::Mutations {
551        self.inner.mutations()
552    }
553
554    fn mutations_mut(&mut self) -> &mut Self::Mutations {
555        self.inner.mutations_mut()
556    }
557}
558
559impl<S, PT, M> Mutator<Trace<PT>, S> for StepLockedStackMutator<PT, M>
560where
561    S: HasRand,
562    PT: ProtocolTypes,
563    M: Mutator<Trace<PT>, S>,
564{
565    #[inline]
566    fn mutate(&mut self, state: &mut S, input: &mut Trace<PT>) -> Result<MutationResult, Error> {
567        let nsteps = input.steps.len();
568        let locked = if self.enabled && nsteps > 0 {
569            Some(state.rand_mut().below_or_zero(nsteps))
570        } else {
571            None
572        };
573        // Set the lock for the whole inner stacking loop, then restore the previous value.
574        let prev = set_step_lock(locked);
575        let r = self.inner.mutate(state, input);
576        set_step_lock(prev);
577        r
578    }
579
580    fn post_exec(&mut self, state: &mut S, id: Option<CorpusId>) -> Result<(), Error> {
581        self.inner.post_exec(state, id)
582    }
583}