puffin/fuzzer/
bit_mutations.rs

1use std::any::Any;
2use std::borrow::Cow;
3use std::cmp::min;
4use std::ops::Not;
5
6use libafl::mutators::mutations::{
7    BitFlipMutator, ByteAddMutator, ByteDecMutator, ByteFlipMutator, ByteIncMutator,
8    ByteInterestingMutator, ByteNegMutator, ByteRandMutator, BytesCopyMutator, BytesDeleteMutator,
9    BytesExpandMutator, BytesInsertCopyMutator, BytesInsertMutator, BytesRandInsertMutator,
10    BytesRandSetMutator, BytesSetMutator, BytesSwapMutator, DwordAddMutator,
11    DwordInterestingMutator, QwordAddMutator, WordAddMutator, WordInterestingMutator,
12};
13use libafl::prelude::*;
14use libafl_bolts::bolts_prelude::Merge;
15use libafl_bolts::prelude::{tuple_list, tuple_list_type};
16use libafl_bolts::rands::Rand;
17use libafl_bolts::Named;
18
19use super::utils::{
20    choose_filtered, choose_term_path_filtered, find_term, find_term_mut, TermConstraints,
21    TracePath,
22};
23use crate::algebra::{Term, TermType};
24use crate::fuzzer::utils::choose_term_filtered_mut;
25use crate::protocol::{ProtocolBehavior, ProtocolTypes};
26use crate::trace::{ConfigTrace, Spawner, Trace, TraceContext};
27
28/* List from: https://docs.rs/libafl/latest/src/libafl/mutators/havoc_mutations.rs.html#60
29    BitFlipMutator,
30    ByteFlipMutator,
31    ByteIncMutator,
32    ByteDecMutator,
33    ByteNegMutator,
34    ByteRandMutator,
35    ByteAddMutator,
36    WordAddMutator,
37    DwordAddMutator,
38    QwordAddMutator,
39    ByteInterestingMutator,
40    WordInterestingMutator,
41    DwordInterestingMutator,
42    BytesDeleteMutator,
43    BytesDeleteMutator,
44    BytesDeleteMutator,
45    BytesDeleteMutator,
46    BytesExpandMutator,
47    BytesInsertMutator,
48    BytesRandInsertMutator,
49    BytesSetMutator,
50    BytesRandSetMutator,
51    BytesCopyMutator,
52    BytesInsertCopyMutator,
53    BytesSwapMutator,
54    CrossoverInsertMutator,
55    CrossoverReplaceMutator,
56*/
57
58pub type HavocMutationsTypeDY<S, PT> = tuple_list_type!(
59    BitFlipMutatorDY<S, PT>,
60    ByteFlipMutatorDY<S, PT>,
61    ByteIncMutatorDY<S, PT>,
62    ByteDecMutatorDY<S, PT>,
63    ByteNegMutatorDY<S, PT>,
64    ByteRandMutatorDY<S, PT>,
65    ByteAddMutatorDY<S, PT>,
66    WordAddMutatorDY<S, PT>,
67    DwordAddMutatorDY<S, PT>,
68    QwordAddMutatorDY<S, PT>,
69    ByteInterestingMutatorDY<S, PT>,
70    WordInterestingMutatorDY<S, PT>,
71    DwordInterestingMutatorDY<S, PT>,
72    BytesDeleteMutatorDY<S, PT>,
73    BytesDeleteMutatorDY<S, PT>,
74    BytesDeleteMutatorDY<S, PT>,
75    BytesDeleteMutatorDY<S, PT>,
76    BytesExpandMutatorDY<S, PT>,
77    BytesLargeExpandMutatorDY<S, PT>, // NEW! Different from classical havoc!!
78    BytesInsertMutatorDY<S, PT>,
79    BytesRandInsertMutatorDY<S, PT>,
80    BytesSetMutatorDY<S, PT>,
81    BytesRandSetMutatorDY<S, PT>,
82    BytesCopyMutatorDY<S, PT>,
83    BytesInsertCopyMutatorDY<S>,
84    BytesSwapMutatorDY<S>,
85    CrossoverInsertMutatorDY<S, PT>,
86    CrossoverReplaceMutatorDY<S, PT>,
87    SpliceMutatorDY<S, PT>,
88);
89
90pub type BitMutations<'harness, PB, PT, S> = tuple_list_type!(
91    MakeMessage<'harness, PB>,
92    ReadMessage<'harness, PB>,
93    BitFlipMutatorDY<S, PT>,
94    ByteFlipMutatorDY<S, PT>,
95    ByteIncMutatorDY<S, PT>,
96    ByteDecMutatorDY<S, PT>,
97    ByteNegMutatorDY<S, PT>,
98    ByteRandMutatorDY<S, PT>,
99    ByteAddMutatorDY<S, PT>,
100    WordAddMutatorDY<S, PT>,
101    DwordAddMutatorDY<S, PT>,
102    QwordAddMutatorDY<S, PT>,
103    ByteInterestingMutatorDY<S, PT>,
104    WordInterestingMutatorDY<S, PT>,
105    DwordInterestingMutatorDY<S, PT>,
106    BytesDeleteMutatorDY<S, PT>,
107    BytesDeleteMutatorDY<S, PT>,
108    BytesDeleteMutatorDY<S, PT>,
109    BytesDeleteMutatorDY<S, PT>,
110    BytesExpandMutatorDY<S, PT>,
111    BytesLargeExpandMutatorDY<S, PT>,
112    BytesInsertMutatorDY<S, PT>,
113    BytesRandInsertMutatorDY<S, PT>,
114    BytesSetMutatorDY<S, PT>,
115    BytesRandSetMutatorDY<S, PT>,
116    BytesCopyMutatorDY<S, PT>,
117    BytesInsertCopyMutatorDY<S>,
118    BytesSwapMutatorDY<S>,
119    CrossoverInsertMutatorDY<S, PT>,
120    CrossoverReplaceMutatorDY<S, PT>,
121    SpliceMutatorDY<S, PT>,
122);
123
124pub type AllMutations<'harness, PT, PB, S> = tuple_list_type!(
125    RepeatMutator<S>,
126    SkipMutator<S>,
127    ReplaceReuseMutator<S>,
128    ReplaceMatchMutator<S, PT>,
129    RemoveAndLiftMutator<S>,
130    GenerateMutator<'harness, S, PB>,
131    SwapMutator<S>,
132    MakeMessage<'harness, PB>,
133    ReadMessage<'harness, PB>,
134    BitFlipMutatorDY<S, PT>,
135    ByteFlipMutatorDY<S, PT>,
136    ByteIncMutatorDY<S, PT>,
137    ByteDecMutatorDY<S, PT>,
138    ByteNegMutatorDY<S, PT>,
139    ByteRandMutatorDY<S, PT>,
140    ByteAddMutatorDY<S, PT>,
141    WordAddMutatorDY<S, PT>,
142    DwordAddMutatorDY<S, PT>,
143    QwordAddMutatorDY<S, PT>,
144    ByteInterestingMutatorDY<S, PT>,
145    WordInterestingMutatorDY<S, PT>,
146    DwordInterestingMutatorDY<S, PT>,
147    BytesDeleteMutatorDY<S, PT>,
148    BytesDeleteMutatorDY<S, PT>,
149    BytesDeleteMutatorDY<S, PT>,
150    BytesDeleteMutatorDY<S, PT>,
151    BytesExpandMutatorDY<S, PT>,
152    BytesLargeExpandMutatorDY<S, PT>,
153    BytesInsertMutatorDY<S, PT>,
154    BytesRandInsertMutatorDY<S, PT>,
155    BytesSetMutatorDY<S, PT>,
156    BytesRandSetMutatorDY<S, PT>,
157    BytesCopyMutatorDY<S, PT>,
158    BytesInsertCopyMutatorDY<S>,
159    BytesSwapMutatorDY<S>,
160    CrossoverInsertMutatorDY<S, PT>,
161    CrossoverReplaceMutatorDY<S, PT>,
162    SpliceMutatorDY<S, PT>,
163);
164
165#[must_use]
166pub fn havoc_mutations_dy<S: HasRand + HasMaxSize + HasCorpus<Trace<PT>>, PT: ProtocolTypes>(
167    mutation_config: MutationConfig,
168) -> HavocMutationsTypeDY<S, PT> {
169    tuple_list!(
170        BitFlipMutatorDY::new(mutation_config),
171        ByteFlipMutatorDY::new(mutation_config),
172        ByteIncMutatorDY::new(mutation_config),
173        ByteDecMutatorDY::new(mutation_config),
174        ByteNegMutatorDY::new(mutation_config),
175        ByteRandMutatorDY::new(mutation_config),
176        ByteAddMutatorDY::new(mutation_config),
177        WordAddMutatorDY::new(mutation_config),
178        DwordAddMutatorDY::new(mutation_config),
179        QwordAddMutatorDY::new(mutation_config),
180        ByteInterestingMutatorDY::new(mutation_config),
181        WordInterestingMutatorDY::new(mutation_config),
182        DwordInterestingMutatorDY::new(mutation_config),
183        BytesDeleteMutatorDY::new(mutation_config),
184        BytesDeleteMutatorDY::new(mutation_config),
185        BytesDeleteMutatorDY::new(mutation_config),
186        BytesDeleteMutatorDY::new(mutation_config),
187        BytesExpandMutatorDY::new(mutation_config),
188        BytesLargeExpandMutatorDY::new(mutation_config),
189        BytesInsertMutatorDY::new(mutation_config),
190        BytesRandInsertMutatorDY::new(mutation_config),
191        BytesSetMutatorDY::new(mutation_config),
192        BytesRandSetMutatorDY::new(mutation_config),
193        BytesCopyMutatorDY::new(mutation_config),
194        BytesInsertCopyMutatorDY::new(mutation_config),
195        BytesSwapMutatorDY::new(mutation_config),
196        CrossoverInsertMutatorDY::new(mutation_config),
197        CrossoverReplaceMutatorDY::new(mutation_config),
198        SpliceMutatorDY::new(mutation_config),
199    )
200}
201
202#[must_use]
203pub fn bit_mutations_dy<S: HasRand + HasMaxSize + HasCorpus<Trace<PT>>, PT: ProtocolTypes, PB>(
204    mutation_config: MutationConfig,
205    put_registry: &PutRegistry<PB>,
206) -> BitMutations<'_, PB, PT, S>
207where
208    PB: ProtocolBehavior,
209{
210    tuple_list!(
211        MakeMessage::new(mutation_config, put_registry),
212        ReadMessage::new(mutation_config, put_registry)
213    )
214    .merge(havoc_mutations_dy(mutation_config))
215}
216
217pub fn all_mutations<'harness, S, PT: ProtocolTypes, PB>(
218    mutation_config: MutationConfig,
219    signature: &'static Signature<PT>,
220    put_registry: &'harness PutRegistry<PB>,
221) -> AllMutations<'harness, PT, PB, S>
222where
223    S: HasCorpus<Trace<PT>> + HasMetadata + HasMaxSize + HasRand,
224    PB: ProtocolBehavior<ProtocolTypes = PT>,
225{
226    dy_mutations(mutation_config, signature, put_registry)
227        .merge(bit_mutations_dy(mutation_config, put_registry))
228}
229
230// --------------------------------------------------------------------------------------------------
231// MakeMessage mutation
232// --------------------------------------------------------------------------------------------------
233
234/// MAKE MESSAGE: transforms a sub term into a message which can then be mutated using havoc
235pub struct MakeMessage<'a, PB> {
236    put_registry: &'a PutRegistry<PB>,
237    config: MutationConfig,
238}
239
240impl<'a, PB> MakeMessage<'a, PB> {
241    #[must_use]
242    pub const fn new(config: MutationConfig, put_registry: &'a PutRegistry<PB>) -> Self {
243        Self {
244            config,
245            put_registry,
246        }
247    }
248}
249
250/// `MakeMessage` on the term at path `path` in `tr`.
251fn make_message_term<PT: ProtocolTypes, PB: ProtocolBehavior<ProtocolTypes = PT>>(
252    tr: &mut Trace<PT>,
253    path: &TracePath,
254    ctx: &mut TraceContext<PB>,
255) -> Result<(), crate::error::Error> {
256    log::debug!("make_message_term: executing until path.0: {}", path.0);
257    // Only execute shorter trace: trace[0..step_index])
258    // execute the PUT on the first step_index steps and store the resulting trace context
259    tr.execute_until_step(ctx, path.0, &mut 0, true).map_err(|e| {
260        // 20% to 50% MakeMessage mutations fail, so this is a bit costly :(
261        // TODO: we could memoize the term evaluation in a Option<ConcreteMessage> and use that here
262        log::debug!("mutation::MakeMessage trace is not executable until step {},\
263            could only happen if this mutation is scheduled with other mutations that create a non-executable trace.\
264            Error: {e}. Skipped MakeMessage...", path.0);
265        log::trace!("{}", &tr);
266        e
267    })?;
268
269    let t = find_term_mut(tr, path).expect("make_message_term - Should never happen.");
270    t.make_payload(ctx)?;
271    Ok(())
272}
273
274impl<'a, S, PT: ProtocolTypes, PB: ProtocolBehavior<ProtocolTypes = PT>> Mutator<Trace<PT>, S>
275    for MakeMessage<'a, PB>
276where
277    S: HasRand,
278    PB: ProtocolBehavior<ProtocolTypes = PT>,
279{
280    fn mutate(&mut self, state: &mut S, trace: &mut Trace<PT>) -> Result<MutationResult, Error> {
281        log::debug!("[Bit] Start mutate with {}", self.name());
282        if !self.config.with_bit_level {
283            log::debug!("[Mutation-bit] Mutate MakeMessage skipped because bit-level mutations are disabled");
284            return Ok(MutationResult::Skipped);
285        }
286        let nb_payloads = trace.all_payloads().len();
287        let nb_payloads_no_readable = trace
288            .all_payloads()
289            .iter()
290            .filter(|p| !p.metadata.readable)
291            .count();
292        let nb_terms = trace.steps.len();
293        let payloads_term_ratio = nb_payloads / std::cmp::max(1, nb_terms);
294        let no_more_new_payloads =
295            payloads_term_ratio > self.config.term_constraints.threshold_max_payloads_per_term;
296        if no_more_new_payloads {
297            log::debug!("[MakeMessage] on a trace with too many payloads: {trace}")
298        } else {
299            log::debug!("[MakeMessage] Do a regular MakeMessage")
300        }
301        let rand = state.rand_mut();
302        let mut constraints_make_message = TermConstraints {
303            must_be_symbolic: true, /* we exclude non-symbolic terms, which were already mutated
304                                     * with MakeMessage */
305            no_payload_in_subterm: false, /* change to true to exclude picking a term with a
306                                           * payload in a sub-term */
307            // TODO: we may want to set no_payload_subterm to true
308            // pros of adding: less mutations on sub-terms that could be subsumed by mutations on a
309            // larger term done in the first place cons: might be useful to first
310            // shotgun small mutations on a small term to make the trace progress with possibly more
311            // actions and then do larger mutations on a larger term from there
312            // (might have an impact later). TODO: balance out this trade-off
313            must_payload_in_subterm: no_more_new_payloads, /* change to true when there are too
314                                                            * many payloads already */
315            not_inside_list: true, /* true means we are not picking terms inside list (like
316                                    * fn_append in the middle) */
317            // we set it to true since it would otherwise be redundant with picking each of the item
318            // as mutated term
319            weighted_depth: false, /* true means we select a sub-term by giving higher-priority
320                                    * to deeper sub-terms */
321            // Set two lasts to false now as this allows to find more case for now.
322            // TODO: fix reservoir sampling and set this to true (as well as in
323            // integration_test/term_zoo.rs)
324            not_readable: true,
325            ..self.config.term_constraints
326        };
327        if !self.config.with_dy {
328            constraints_make_message.must_be_root = true;
329        }
330
331        // If debug mode, test that trace has no focus and panic otherwise
332        #[cfg(any(debug_assertions, feature = "debug"))]
333        if trace.get_focus().is_some() {
334            log::error!(
335                "[MakeMessage] with_focus is set but trace has a focus already: {:?}. Trace:\n{trace}",
336                trace.get_focus().unwrap()
337            );
338            return Ok(MutationResult::Skipped);
339        }
340
341        // choose a random sub term
342        if let Some(trace_path) = if self.config.with_focus {
343            if nb_payloads > 0 && payloads_term_ratio > 1 {
344                if nb_payloads_no_readable == 0 {
345                    log::debug!("[MakeMessage] With focus and enough existing payloads but all are readable. Skipping...");
346                    return Ok(MutationResult::Skipped);
347                }
348                log::debug!(
349                    "[MakeMessage] With focus and enough existing payloads: randomly picking one"
350                );
351                constraints_make_message.must_be_symbolic = false;
352                constraints_make_message.must_payload_in_subterm = false;
353                if let Some((_, trace_path)) = choose_filtered(
354                    trace,
355                    &constraints_make_message,
356                    |t| !t.is_symbolic(),
357                    state.rand_mut(),
358                ) {
359                    log::debug!("[MakeMessage] Picked existing payload and focus set to it: {trace_path:?}. Mutated.");
360                    trace.set_focus(trace_path.clone());
361                    Some(trace_path)
362                } else {
363                    log::error!("[MakeMessage] Skipped as we failed selecting a term with existing payloads while there is at least one payload. Trace: {trace}. Constraints: {:?}.", constraints_make_message);
364                    return Ok(MutationResult::Skipped);
365                }
366            } else {
367                log::debug!("[MakeMessage] With focus and no enough existing payloads, picking a random term");
368                choose_filtered(trace, &constraints_make_message, |t| !t.is_no_bit(), rand)
369                    .map(|(_, p)| p)
370            }
371        } else {
372            log::debug!("[MakeMessage] Without focus, picking a random term");
373            choose_filtered(trace, &constraints_make_message, |t| !t.is_no_bit(), rand)
374                .map(|(_, p)| p)
375        } {
376            log::debug!(
377                "[Mutation-bit] Mutate MakeMessage on term\n{}",
378                find_term(trace, &trace_path).expect("make_message_term - Should never happen.")
379            );
380            let spawner = Spawner::new(self.put_registry.clone());
381            // log::trace!("Using self.put_registry {:?} to compute ctx",
382            // self.put_registry.default().name());
383            let mut ctx = TraceContext::new_config(
384                spawner,
385                ConfigTrace {
386                    with_bit_level: self.config.with_bit_level,
387                    ..Default::default()
388                },
389            );
390            if self.config.with_focus {
391                MM_EXEC.increment();
392            }
393            BIT_EXEC.increment();
394            match make_message_term(trace, &trace_path, &mut ctx) {
395                // TODO: possibly we would need to make sure the mutated trace can be executed (if
396                // not directly dropped by the feedback loop once executed).
397                // TODO: maybe add a consistency check: same encoding by reading/encoding
398                Ok(()) => {
399                    log::debug!("mutation::MakeMessage successful!");
400                    if self.config.with_focus {
401                        MM_EXEC_SUCCESS.increment();
402                        log::debug!("mutation::MakeMessage set focus on {trace_path:?}");
403                        trace.set_focus(trace_path);
404                    }
405                    BIT_EXEC_SUCCESS.increment();
406                    Ok(MutationResult::Mutated)
407                }
408                Err(e) => {
409                    log::warn!(
410                        "mutation::MakeMessage failed (with_focus: {}) due to {e}",
411                        self.config.with_focus
412                    );
413                    log::debug!("mutation::MakeMessage failed due to {e}");
414                    log::debug!("       Skipped {}", self.name());
415                    Ok(MutationResult::Skipped)
416                }
417            }
418        } else {
419            log::debug!(
420                "mutation::MakeMessage failed to choose term in trace:\n {}",
421                &trace
422            );
423            log::debug!("       Skipped {}", self.name());
424            Ok(MutationResult::Skipped)
425        }
426    }
427
428    #[inline]
429    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
430        Ok(())
431    }
432}
433
434impl<'a, PB> Named for MakeMessage<'a, PB>
435where
436    PB: ProtocolBehavior,
437{
438    fn name(&self) -> &Cow<'static, str> {
439        &Cow::Borrowed("MakeMessage")
440    }
441}
442
443// --------------------------------------------------------------------------------------------------
444// ReadMessage mutation
445// --------------------------------------------------------------------------------------------------
446
447/// READ MESSAGE: picks a sub-term having itself a sub-term with payload, evaluate, read and
448/// performs an in-place replacement
449pub struct ReadMessage<'a, PB> {
450    config: MutationConfig,
451    put_registry: &'a PutRegistry<PB>,
452}
453
454impl<'a, PB> ReadMessage<'a, PB> {
455    #[must_use]
456    pub const fn new(config: MutationConfig, put_registry: &'a PutRegistry<PB>) -> Self {
457        Self {
458            config,
459            put_registry,
460        }
461    }
462}
463
464/// `ReadMessage` on the term at path `path` in `tr`.
465fn read_message_term<PT: ProtocolTypes, PB: ProtocolBehavior<ProtocolTypes = PT>>(
466    tr: &mut Trace<PT>,
467    path: &TracePath,
468    ctx: &mut TraceContext<PB>,
469) -> Result<(), crate::error::Error> {
470    // Only execute shorter trace: trace[0..step_index])
471    // execute the PUT on the first step_index steps and store the resulting trace context
472    log::debug!("Try eval until path.0: {}", path.0);
473    tr.execute_until_step(ctx, path.0, &mut 0, true).map_err(|e| {
474        log::debug!("mutation::ReadMessage trace is not executable until step {}, \
475            could only happen if this mutation is scheduled with other mutations that create a non-executable trace. Skipped ReadMessage\
476            Error: {e}. Skipping ReadMessage...", path.0);
477        log::trace!("{}", &tr);
478        e
479    })?;
480
481    let t = find_term_mut(tr, path).expect("read_message_term - Should never happen.");
482    log::debug!(
483        "[mutation::ReadMessage] [read_message_term] Mutate ReadMessage on term\n{}\n Trying read for type shape: {} and type id : {:?}",
484        t, t.get_type_shape(), t.term.type_id()
485    );
486    // Evaluate the term and try to read it into the term type
487    let eval = t.evaluate(ctx)?; // We do not measure failure or not for this specific eval (less costly than trace execution)
488    let read_term = PB::try_read_bytes(&eval, t.get_type_shape().clone().into())?; // skip if try_read fails
489
490    // The evaluation of this readable term eval_read is likely NOT the original evaluation itself
491    // eval. What we keep here is eval_read since we aim to store the re-interpretation of the
492    // payload. Note that when eval != eval_read, it likely means that `t` is length-prefixed or has
493    // some headers and that havoc mutations have messed up with those or the payload length. We
494    // will loose part of this. However, it is likely that we could have ReadMessage a
495    // strict-subterm instead to avoid this.
496    let eval_read = read_term.get_encoding();
497
498    #[cfg(any(debug_assertions, feature = "debug"))]
499    if PB::try_read_bytes(&eval_read, t.get_type_shape().clone().into()).is_err() {
500        log::error!("[mutation::ReadMessage] [read_message_term] Failed to read eval_read\n - t: {t}\n - eval: {eval:?}\n - read_term: {read_term:?}\n - eval_read: {eval_read:?}\n - type shape: {:?} and type id : {:?}",
501            t.get_type_shape(), t.term.type_id());
502    }
503
504    t.add_payload_readable(eval_read);
505    Ok(())
506}
507
508impl<'a, S, PT: ProtocolTypes, PB: ProtocolBehavior<ProtocolTypes = PT>> Mutator<Trace<PT>, S>
509    for ReadMessage<'a, PB>
510where
511    S: HasRand,
512    PB: ProtocolBehavior<ProtocolTypes = PT>,
513{
514    fn mutate(&mut self, state: &mut S, trace: &mut Trace<PT>) -> Result<MutationResult, Error> {
515        log::debug!("[Bit] Start mutate with {}", self.name());
516        let focus = trace.get_focus().cloned();
517        if self.config.with_focus {
518            trace.clear_focus(); // to save a bit of memory (no need to serialize focus in the
519                                 // corpus!)
520        }
521        if !self.config.with_bit_level {
522            log::debug!("[Mutation-bit] Mutate ReadMessage skipped because bit-level mutations are disabled");
523            return Ok(MutationResult::Skipped);
524        }
525        let rand = state.rand_mut();
526        let mut constraints_read_message = TermConstraints {
527            no_payload_in_subterm: false, /* change to true to exclude picking a term with a
528                                           * payload in a sub-term */
529            not_inside_list: true, /* true means we are not picking terms inside list (like
530                                    * fn_append in the middle) */
531            weighted_depth: false, /* true means we select a sub-term by giving higher-priority
532                                    * to deeper sub-terms */
533            not_readable: true,
534            must_be_det: true, // do not make read on a non det term !
535            ..self.config.term_constraints
536        };
537        if !self.config.with_dy {
538            constraints_read_message.must_be_root = true;
539        }
540        let chosen_path = if self.config.with_focus {
541            if let Some(trace_path) = focus {
542                // We skip ReadMessage with proba 1/4 in focus mode!
543                let proba = 1.0 / 4.0;
544                let max_range = (1_000_000_000.0 * proba) as usize;
545                if !rand.between(0, 1_000_000_000 - 1) < max_range {
546                    log::debug!("read_message_term: skipping as we do in 3/4 of times");
547                    return Ok(MutationResult::Skipped);
548                }
549                // If focus was already set, we use it as is!
550                // TODO: investigate whether we still want to explore application on parents
551                log::debug!("read_message_term::mutate - Using focus {trace_path:?}");
552                trace_path.clone()
553            } else {
554                log::debug!("read_message_term::mutate - No focus set and yet with_focus config. Should only happen when initial MakeMessage failed! Skipping...");
555                return Ok(MutationResult::Skipped); // First MakeMessage failed, we won't apply
556                                                    // further mutations then
557            }
558        } else {
559            // Randomly choose a random sub term
560            // Specifically for ReadMessage, we should prioritize terms close to a sub-term with
561            // payloads. We first randomly pick a term with payload. With proba p:=1/2 we pick
562            // that one. With proba. p:=p/2 we pick the parent term, etc.
563            if let Some(mut chosen_path) = choose_term_path_filtered(
564                trace,
565                |x| x.is_symbolic().not(),
566                &constraints_read_message,
567                rand,
568            ) {
569                log::debug!("[ReadMessage] Initially picked term at {chosen_path:?}");
570                let term = find_term_mut(trace, &chosen_path)
571                    .expect("mutation::ReadMessage::mutate - Should never happen!");
572                let payloads = term.payloads.as_ref().expect(
573                    "mutation::ReadMessage::mutate - Should never happen, we should have filtered out symbolic terms",
574                );
575                if !payloads.has_changed() {
576                    // Extremely likely that payload.payload == payload.payload0 then!
577                    log::debug!("       Skipped {} because payload unchanged", self.name());
578                    return Ok(MutationResult::Skipped);
579                }
580                let mut proba = 1.0 / 2.0;
581                while !chosen_path.1.is_empty() {
582                    let max_range = (1_000_000_000.0 * proba) as usize;
583                    if rand.between(0, 1_000_000_000 - 1) < max_range {
584                        log::trace!("[ReadMessage] Going up, proba was {proba}");
585                        proba /= 2.0;
586                        chosen_path.1.pop();
587                    } else {
588                        break;
589                    }
590                }
591                log::debug!("[ReadMessage] Finally picked term at {chosen_path:?}");
592                chosen_path
593            } else {
594                log::trace!(
595                    "[mutation::ReadMessage] Failed to choose term with payload in trace:\n {}",
596                    &trace
597                );
598                log::warn!(
599                    "       Skipped {} as we failed to choose a term with payload in the trace.",
600                    self.name()
601                );
602                return Ok(MutationResult::Skipped);
603            }
604        };
605        let term =
606            find_term_mut(trace, &chosen_path).expect("read_message_term - Should never happen.");
607        if term.is_list() || term.is_readable() || term.has_no_det() {
608            log::debug!(
609                "[ReadMessage] Skipping ReadMessage on term\n{term:?}, because it is a list or already readable or has no det"
610            );
611            return Ok(MutationResult::Skipped);
612        }
613
614        let spawner = Spawner::new(self.put_registry.clone());
615        // log::trace!("Using self.put_registry {:?} to compute ctx",
616        // self.put_registry.default().name());
617        let mut ctx = TraceContext::new_config(
618            spawner,
619            ConfigTrace {
620                with_bit_level: self.config.with_bit_level,
621                ..Default::default()
622            },
623        );
624        if self.config.with_focus {
625            MM_EXEC.increment();
626        }
627        BIT_EXEC.increment();
628        match read_message_term(trace, &chosen_path, &mut ctx) {
629            Ok(_) => {
630                if self.config.with_focus {
631                    MM_EXEC_SUCCESS.increment();
632                }
633                BIT_EXEC_SUCCESS.increment();
634                log::debug!("[ReadMessage] Path chosen: {chosen_path:?}");
635                log::debug!("[mutation::ReadMessage] successful!");
636                Ok(MutationResult::Mutated)
637            }
638            Err(e) => {
639                log::debug!("[mutation::ReadMessage] failed due to {e}");
640                log::debug!("       Skipped {}", self.name());
641                Ok(MutationResult::Skipped)
642            }
643        }
644    }
645
646    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
647        Ok(())
648    }
649}
650
651impl<'a, PB> Named for ReadMessage<'a, PB>
652where
653    PB: ProtocolBehavior,
654{
655    fn name(&self) -> &Cow<'static, str> {
656        &Cow::Borrowed("ReadMessage")
657    }
658}
659
660// --------------------------------------------------------------------------------------------------
661// Term-level bit-level mutations
662// --------------------------------------------------------------------------------------------------
663
664use paste::paste;
665
666use crate::algebra::bitstrings::PayloadMetadata;
667use crate::algebra::signature::Signature;
668use crate::fuzzer::mutations::{
669    dy_mutations, GenerateMutator, MutationConfig, RemoveAndLiftMutator, RepeatMutator,
670    ReplaceMatchMutator, ReplaceReuseMutator, SkipMutator, SwapMutator,
671};
672use crate::fuzzer::stats_stage::{BIT_EXEC, BIT_EXEC_SUCCESS, MM_EXEC, MM_EXEC_SUCCESS};
673use crate::put_registry::PutRegistry;
674
675macro_rules! expand_mutation {
676    ($mutation:ident) => {
677paste!{
678        /// mutation definition
679pub struct [<$mutation  DY>]<S, PT>
680    where
681        S: HasRand + HasMaxSize,
682        PT: ProtocolTypes,
683{
684    config: MutationConfig,
685    phantom_s: std::marker::PhantomData<(S, PT)>,
686}
687
688impl<S, PT> [<$mutation  DY>]<S, PT>
689    where
690        S: HasRand + HasMaxSize,
691        PT: ProtocolTypes,
692{
693    #[must_use]
694    pub const fn new(config: MutationConfig) -> Self {
695        Self {
696            config: MutationConfig {
697                term_constraints: TermConstraints {
698                    not_readable: true,
699                    ..config.term_constraints
700                },
701                ..config
702            },
703            phantom_s: std::marker::PhantomData,
704        }
705    }
706}
707
708impl<S, PT> Mutator<Trace<PT>, S> for [<$mutation  DY>]<S, PT>
709    where
710        S: HasRand + HasMaxSize,
711        PT: ProtocolTypes,
712{
713    fn mutate(
714        &mut self,
715        state: &mut S,
716        trace: &mut Trace<PT>,
717    ) -> Result<MutationResult, Error> {
718        log::debug!("[Bit] Start mutate with {}", self.name());
719
720        if !self.config.with_bit_level {
721            log::debug!("[Mutation-bit] Mutate {} skipped because bit-level mutations are disabled", self.name());
722            return Ok(MutationResult::Skipped)
723        }
724        match choose_term_with_payload_mut(
725            trace,
726            state,
727            &self.config.term_constraints,
728            self.config.with_focus,
729        ) {
730            Some(to_mutate) => {
731                log::debug!("[Mutation-bit] Mutate {} on term\n{to_mutate}", self.name(),);
732                if let Some(payloads) = &mut to_mutate.payloads {
733                    $mutation.mutate(state, &mut payloads.payload)
734                              .and_then(|r| {
735                               payloads.set_changed();
736                               Ok(r)
737                          })
738                } else {
739                    panic!("mutation::{}::this shouldn't happen since we filtered out terms that are symbolic!", self.name());
740                }
741            }
742            None => {
743                log::debug!("       Skipped {}", self.name());
744                Ok(MutationResult::Skipped)
745            }
746        }
747    }
748
749    #[inline]
750    fn post_exec(
751        &mut self,
752        _state: &mut S,
753        _new_corpus_id: Option<CorpusId>,
754    ) -> Result<(), Error> {
755        Ok(())
756    }
757}
758
759impl<S, PT> Named for [<$mutation  DY>]<S, PT>
760    where
761        S: HasRand + HasMaxSize,
762        PT: ProtocolTypes,
763{
764    fn name(&self) -> &Cow<'static, str> {
765        &Cow::Borrowed(stringify!($mutation))
766    }
767}
768}};
769}
770
771#[macro_export]
772macro_rules! expand_mutations {
773    () => {};
774    ($mutation:ident) => {
775          expand_mutation!($mutation);
776    };
777    ($mutation:ident,) => {
778          expand_mutation!($mutation);
779    };
780    ($mutation:ident, $($MS:ident),*) => {
781          expand_mutation!($mutation);
782          $crate::expand_mutations!($($MS),*);
783    };
784}
785// Use of `expand_mutations` is below
786expand_mutations!(
787    BitFlipMutator,
788    ByteFlipMutator,
789    ByteIncMutator,
790    ByteDecMutator,
791    ByteNegMutator,
792    ByteRandMutator,
793    ByteAddMutator,
794    WordAddMutator,
795    DwordAddMutator,
796    QwordAddMutator,
797    ByteInterestingMutator,
798    WordInterestingMutator,
799    DwordInterestingMutator,
800    BytesDeleteMutator,
801    BytesExpandMutator,
802    BytesLargeExpandMutator,
803    BytesInsertMutator,
804    BytesRandInsertMutator,
805    BytesSetMutator,
806    BytesRandSetMutator,
807    BytesCopyMutator /* The next 2 require custom implementations:
808                      *   BytesInsertCopyMutator,
809                      *   BytesSwapMutator,
810                      * The three next require to pick up another test-case (cross-over), see
811                      * dedicated implementations:
812                      *   CrossoverInsertMutator
813                      *   CrossoverReplaceMutator
814                      *   SpliceMutator */
815);
816
817// We could write another macro for the two following mutations
818// BytesSwapMutatorDY
819pub struct BytesSwapMutatorDY<S>
820where
821    S: HasRand + HasMaxSize,
822{
823    config: MutationConfig,
824    tmp_buf: BytesSwapMutator,
825    phantom_s: std::marker::PhantomData<S>,
826}
827
828impl<S> BytesSwapMutatorDY<S>
829where
830    S: HasRand + HasMaxSize,
831{
832    #[must_use]
833    pub fn new(config: MutationConfig) -> Self {
834        Self {
835            config: MutationConfig {
836                term_constraints: TermConstraints {
837                    not_readable: true,
838                    ..config.term_constraints
839                },
840                ..config
841            },
842            tmp_buf: BytesSwapMutator::new(),
843            phantom_s: std::marker::PhantomData,
844        }
845    }
846}
847
848impl<S, PT> Mutator<Trace<PT>, S> for BytesSwapMutatorDY<S>
849where
850    S: HasRand + HasMaxSize,
851    PT: ProtocolTypes,
852{
853    fn mutate(&mut self, state: &mut S, trace: &mut Trace<PT>) -> Result<MutationResult, Error> {
854        log::debug!("[Bit] Start mutate with {}", self.name());
855
856        if !self.config.with_bit_level {
857            log::debug!("[Mutation-bit] Mutate BytesSwapMutatorDY skipped because bit-level mutations are disabled");
858            return Ok(MutationResult::Skipped);
859        }
860        match choose_term_with_payload_mut(
861            trace,
862            state,
863            &self.config.term_constraints,
864            self.config.with_focus,
865        ) {
866            Some(to_mutate) => {
867                log::debug!("[Mutation-bit] Mutate {} on term\n{to_mutate}", self.name(),);
868                if let Some(payloads) = &mut to_mutate.payloads {
869                    BytesSwapMutator::mutate(&mut self.tmp_buf, state, &mut payloads.payload).map(
870                        |r| {
871                            payloads.set_changed();
872                            r
873                        },
874                    )
875                } else {
876                    panic!("mutation::{}::this shouldn't happen since we filtered out terms that are symbolic!", self.name());
877                }
878            }
879            None => {
880                log::debug!("       Skipped {}", self.name());
881                Ok(MutationResult::Skipped)
882            }
883        }
884    }
885
886    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
887        Ok(())
888    }
889}
890
891impl<S> Named for BytesSwapMutatorDY<S>
892where
893    S: HasRand + HasMaxSize,
894{
895    fn name(&self) -> &Cow<'static, str> {
896        &Cow::Borrowed("BytesSwapMutatorDY")
897    }
898}
899
900// BytesInsertCopyMutatorDY
901pub struct BytesInsertCopyMutatorDY<S>
902where
903    S: HasRand + HasMaxSize,
904{
905    config: MutationConfig,
906    tmp_buf: BytesInsertCopyMutator,
907    phantom_s: std::marker::PhantomData<S>,
908}
909
910impl<S> BytesInsertCopyMutatorDY<S>
911where
912    S: HasRand + HasMaxSize,
913{
914    #[must_use]
915    pub fn new(config: MutationConfig) -> Self {
916        Self {
917            config: MutationConfig {
918                term_constraints: TermConstraints {
919                    not_readable: true,
920                    ..config.term_constraints
921                },
922                ..config
923            },
924            tmp_buf: BytesInsertCopyMutator::new(),
925            phantom_s: std::marker::PhantomData,
926        }
927    }
928}
929
930impl<S, PT> Mutator<Trace<PT>, S> for BytesInsertCopyMutatorDY<S>
931where
932    S: HasRand + HasMaxSize,
933    PT: ProtocolTypes,
934{
935    fn mutate(&mut self, state: &mut S, trace: &mut Trace<PT>) -> Result<MutationResult, Error> {
936        log::debug!("[Bit] Start mutate with {}", self.name());
937
938        if !self.config.with_bit_level {
939            log::debug!("[Mutation-bit] Mutate BytesInsertCopyMutatorDY skipped because bit-level mutations are disabled");
940            return Ok(MutationResult::Skipped);
941        }
942        match choose_term_with_payload_mut(
943            trace,
944            state,
945            &self.config.term_constraints,
946            self.config.with_focus,
947        ) {
948            Some(to_mutate) => {
949                log::debug!("[Mutation-bit] Mutate {} on term\n{to_mutate}", self.name(),);
950                if let Some(payloads) = &mut to_mutate.payloads {
951                    BytesInsertCopyMutator::mutate(&mut self.tmp_buf, state, &mut payloads.payload)
952                        .map(|r| {
953                            payloads.set_changed();
954                            r
955                        })
956                } else {
957                    panic!("mutation::{}::this shouldn't happen since we filtered out terms that are symbolic!", self.name());
958                }
959            }
960            None => {
961                log::debug!("       Skipped {}", self.name());
962                Ok(MutationResult::Skipped)
963            }
964        }
965    }
966
967    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
968        Ok(())
969    }
970}
971
972impl<S> Named for BytesInsertCopyMutatorDY<S>
973where
974    S: HasRand + HasMaxSize,
975{
976    fn name(&self) -> &Cow<'static, str> {
977        &Cow::Borrowed("BytesInsertCopyMutatorDY")
978    }
979}
980
981// --------------------------------------------------------------------------------------------------
982// Trace-level bit-level mutations --> Cross-over need to consider traces with the HasBytesVec
983// trait!
984// --------------------------------------------------------------------------------------------------
985
986/// Returns the focused payload or randomly choose a non-symbolic payload in a trace (mutable
987/// reference).
988pub fn choose_term_with_payload_mut<'a, PT, S>(
989    trace: &'a mut Trace<PT>,
990    state: &mut S,
991    term_constraints: &TermConstraints,
992    with_focus: bool,
993) -> Option<&'a mut Term<PT>>
994where
995    S: HasRand + HasMaxSize,
996    PT: ProtocolTypes,
997{
998    if with_focus {
999        if let Some(path_trace) = trace.get_focus() {
1000            log::debug!("choose_term_with_payload_mut -- Focused path: {path_trace:?}");
1001            let term = find_term_mut(trace, &path_trace.clone())
1002                .expect("choose_term_with_payload_mut -- should never happen");
1003            Some(term)
1004        } else {
1005            log::debug!("choose_term_with_payload_mut -- No focus set and yet with_focus config. Skipping...");
1006            None // First MakeMessage failed, we won't apply further mutations then
1007        }
1008    } else {
1009        let res = choose_term_filtered_mut(
1010            trace,
1011            |x| x.is_symbolic().not(),
1012            term_constraints,
1013            state.rand_mut(),
1014        );
1015        log::debug!("choose_term_with_payload_mut -- Chosen term, not focus");
1016        res
1017    }
1018}
1019
1020/* When !with_focus, possibly randomly choose a payload among the all_payloads vec instead. The distribution won't be the same. Investigate what's best.
1021
1022/// Randomly choose a payload and its index (nth) in a trace (mutable reference), if there is any
1023/// and if it has at least 2 bytes. Also returns a mutable ref to the payload metadata.
1024pub fn choose_payload_mut<'a, PT, S>(
1025    trace: &'a mut Trace<PT>,
1026    state: &mut S,
1027) -> Option<(&'a mut Vec<u8>, usize, &'a mut PayloadMetadata)>
1028where
1029    S: HasCorpus + HasRand + HasMaxSize,
1030    PT: ProtocolTypes,
1031{
1032    let mut all_payloads: Vec<&'a mut Payloads> = trace.all_payloads_mut();
1033    if all_payloads.is_empty() {
1034        return None;
1035    }
1036    let idx = state.rand_mut().between(0, (all_payloads.len() - 1) as u64) as usize;
1037    let input = all_payloads.remove(idx);
1038    let metada = &mut input.metadata;
1039    let input = input.payload.bytes_mut();
1040    if input.len() < 2 {
1041        return None;
1042    }
1043    Some((input, idx, metada))
1044}
1045*/
1046
1047pub fn choose_payload_mut<'a, PT, S>(
1048    trace: &'a mut Trace<PT>,
1049    state: &mut S,
1050    config: &MutationConfig,
1051) -> Option<(&'a mut Vec<u8>, &'a mut PayloadMetadata)>
1052where
1053    S: HasRand + HasMaxSize,
1054    PT: ProtocolTypes,
1055{
1056    match choose_term_with_payload_mut(trace, state, &config.term_constraints, config.with_focus) {
1057        Some(term) => {
1058            let payloads = term
1059                .payloads
1060                .as_mut()
1061                .expect("[choose_payload_mut] should never happen");
1062            let input = payloads.payload.as_mut();
1063            if input.len() < 2 {
1064                log::debug!(
1065                    "[choose_payload_mut] Skipped because payload is too small: {} bytes",
1066                    input.len()
1067                );
1068                None
1069            } else {
1070                Some((input, &mut payloads.metadata))
1071            }
1072        }
1073        None => None,
1074    }
1075}
1076
1077// /// Returns the focused payload or randomly choose over a vector of all payloads a payload in a
1078// /// trace (mutable reference), if there is any and if it has at least 2 bytes. Also returns a
1079// /// mutable ref to the payload metadata.
1080// pub fn choose_payload_mut_<'a, PT, S>(
1081//     trace: &'a mut Trace<PT>,
1082//     state: &mut S,
1083//     config: &MutationConfig,
1084// ) -> Option<(&'a mut Vec<u8>, &'a mut PayloadMetadata)>
1085// where
1086//     S: HasRand + HasMaxSize,
1087//     PT: ProtocolTypes,
1088// {
1089//     if let (true, Some(path_trace)) = (config.with_focus, trace.get_focus()) {
1090//         let term = find_term_mut(trace, &path_trace.clone())
1091//             .expect("[choose_payload_mut] should never happen");
1092//         let payloads = term
1093//             .payloads
1094//             .as_mut()
1095//             .expect("[choose_payload_mut] should never happen");
1096//         let input = payloads.payload.bytes_mut();
1097//         if input.len() < 2 {
1098//             return None;
1099//         }
1100//         Some((input, &mut payloads.metadata))
1101//     } else {
1102//         let mut all_payloads: Vec<&'a mut Payloads> = trace.all_payloads_mut();
1103//         if all_payloads.is_empty() {
1104//             return None;
1105//         }
1106//         let idx = state.rand_mut().between(0, (all_payloads.len() - 1) as u64) as usize;
1107//         let input = all_payloads.remove(idx);
1108//         let metada = &mut input.metadata;
1109//         let input = input.payload.bytes_mut();
1110//         if input.len() < 2 {
1111//             return None;
1112//         }
1113//         Some((input, metada))
1114//     }
1115// }
1116
1117// Randomly choose a payload and its index (n-th) in a trace, if there is any and if it has at
1118// least 2 bytes
1119// fn choose_payload<'a, PT, S>(trace: &'a Trace<PT>, state: &mut S) -> Option<(&'a [u8], usize)>
1120// where
1121//     S: HasCorpus + HasRand + HasMaxSize,
1122//     PT: ProtocolTypes,
1123// {
1124//     let all_payloads = trace.all_payloads();
1125//     if all_payloads.is_empty() {
1126//         return None;
1127//     }
1128//     let idx = state.rand_mut().between(0, (all_payloads.len() - 1) as u64) as usize;
1129//     let input = all_payloads[idx].payload.bytes();
1130//     if input.len() < 2 {
1131//         return None;
1132//     }
1133//     Some((input, idx))
1134// }
1135
1136// Access the n-th payload of a trace, if it exists
1137// fn get_payload<PT>(trace: &Trace<PT>, idx: usize) -> Option<&[u8]>
1138// where
1139//     PT: ProtocolTypes,
1140// {
1141//     let all_payloads = trace.all_payloads();
1142//     if all_payloads.len() <= idx {
1143//         return None;
1144//     }
1145//     let input = all_payloads[idx].payload.bytes();
1146//     if input.len() < 2 {
1147//         return None;
1148//     }
1149//     Some(input)
1150// }
1151
1152/// Copied from `libafl::mutators::mutations`
1153/// Returns the first and last diff position between the given vectors, stopping at the min len
1154fn locate_diffs(this: &[u8], other: &[u8]) -> (i64, i64) {
1155    let mut first_diff: i64 = -1;
1156    let mut last_diff: i64 = -1;
1157    for (i, (this_el, other_el)) in this.iter().zip(other.iter()).enumerate() {
1158        if this_el != other_el {
1159            if first_diff < 0 {
1160                first_diff = i as i64;
1161            }
1162            last_diff = i as i64;
1163        }
1164    }
1165
1166    (first_diff, last_diff)
1167}
1168
1169/// Copied from `libafl::mutators::mutations`
1170/// Mem move in the own vec
1171#[inline]
1172pub(crate) unsafe fn buffer_self_copy<T>(data: &mut [T], from: usize, to: usize, len: usize) {
1173    debug_assert!(!data.is_empty());
1174    debug_assert!(from + len <= data.len());
1175    debug_assert!(to + len <= data.len());
1176    if len != 0 && from != to {
1177        let ptr = data.as_mut_ptr();
1178        unsafe {
1179            core::ptr::copy(ptr.add(from), ptr.add(to), len);
1180        }
1181    }
1182}
1183
1184/// Mem move between vecs
1185#[inline]
1186pub(crate) unsafe fn buffer_copy<T>(dst: &mut [T], src: &[T], from: usize, to: usize, len: usize) {
1187    debug_assert!(!dst.is_empty());
1188    debug_assert!(!src.is_empty());
1189    debug_assert!(from + len <= src.len());
1190    debug_assert!(to + len <= dst.len());
1191    let dst_ptr = dst.as_mut_ptr();
1192    let src_ptr = src.as_ptr();
1193    if len != 0 {
1194        unsafe {
1195            core::ptr::copy(src_ptr.add(from), dst_ptr.add(to), len);
1196        }
1197    }
1198}
1199
1200// CrossoverInsertMutatorDY
1201pub struct CrossoverInsertMutatorDY<S, PT>
1202where
1203    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1204    PT: ProtocolTypes,
1205{
1206    config: MutationConfig,
1207    phantom_s: std::marker::PhantomData<(S, PT)>,
1208}
1209
1210impl<S, PT> CrossoverInsertMutatorDY<S, PT>
1211where
1212    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1213    PT: ProtocolTypes,
1214{
1215    #[must_use]
1216    pub fn new(config: MutationConfig) -> Self {
1217        Self {
1218            config: MutationConfig {
1219                term_constraints: TermConstraints {
1220                    not_readable: true,
1221                    ..config.term_constraints
1222                },
1223                ..config
1224            },
1225            phantom_s: std::marker::PhantomData,
1226        }
1227    }
1228}
1229
1230impl<S, PT> Mutator<Trace<PT>, S> for CrossoverInsertMutatorDY<S, PT>
1231where
1232    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1233    PT: ProtocolTypes,
1234{
1235    fn mutate(&mut self, state: &mut S, trace: &mut Trace<PT>) -> Result<MutationResult, Error> {
1236        log::debug!("[Bit] Start mutate with {}", self.name());
1237
1238        if !self.config.with_bit_level {
1239            log::debug!("[Mutation-bit] Mutate CrossoverInsertMutatorDY skipped because bit-level mutations are disabled");
1240            return Ok(MutationResult::Skipped);
1241        }
1242
1243        let Some((input, metadata)) = choose_payload_mut(trace, state, &self.config) else {
1244            log::debug!("       Skipped {}", self.name());
1245            return Ok(MutationResult::Skipped);
1246        };
1247
1248        // Inlined from libafl::mutators::mutations pub struct CrossoverInsertMutator
1249        let size = input.len();
1250        let max_size = state.max_size();
1251        if size >= max_size {
1252            log::debug!("       Skipped {}", self.name());
1253            return Ok(MutationResult::Skipped);
1254        }
1255
1256        // We don't want to use the testcase we're already using for splicing
1257        let idx = random_corpus_id!(state.corpus(), state.rand_mut());
1258
1259        if let Some(cur) = state.corpus().current() {
1260            if idx == *cur {
1261                log::debug!("       Skipped {}", self.name());
1262                return Ok(MutationResult::Skipped);
1263            }
1264        }
1265
1266        // let other_size = {
1267        //     let mut other_testcase = state.corpus().get(idx)?.borrow_mut();
1268        //     other_testcase.load_input(state.corpus())?.bytes().len()
1269        // };
1270        let size_vec_payloads = {
1271            let mut other_testcase = state.corpus().get(idx)?.borrow_mut();
1272            let other_input_trace = other_testcase.load_input(state.corpus())?;
1273            other_input_trace.all_payloads().len()
1274        };
1275        if size_vec_payloads < 1 {
1276            log::debug!("       Skipped {}", self.name());
1277            return Ok(MutationResult::Skipped);
1278        }
1279        let payload_idx = state // we need to split the choice of other_input int two steps to
1280            // avoid borrow checker issues (state need sto be immutably borrowed to access the
1281            // corpus and mutably borrowed to pick a random payload in the chosen trace)
1282            .rand_mut()
1283            .between(0, size_vec_payloads - 1);
1284        let other_size = {
1285            let other_testcase = state.corpus().get(idx)?.borrow_mut();
1286            // Input will already be loaded.
1287            let other_input = other_testcase.input().as_ref().unwrap().all_payloads()[payload_idx]
1288                .payload
1289                .mutator_bytes();
1290            other_input.len()
1291        };
1292        //
1293
1294        if other_size < 2 {
1295            log::debug!("       Skipped {}", self.name());
1296            return Ok(MutationResult::Skipped);
1297        }
1298
1299        let range = rand_range(
1300            state,
1301            other_size,
1302            min(other_size, max_size - size).try_into()?,
1303        );
1304        let target = state.rand_mut().below_or_zero(size);
1305
1306        input.resize(size + range.len(), 0);
1307        unsafe {
1308            buffer_self_copy(input, target, target + range.len(), size - target);
1309        }
1310
1311        // let other_testcase = state.corpus().get(idx)?.borrow_mut();
1312        // // No need to load the input again, it'll still be cached.
1313        // let other = other_testcase.input().as_ref().unwrap();
1314        let other_testcase = state.corpus().get(idx)?.borrow_mut();
1315        // Input will already be loaded.
1316        let other_input = other_testcase.input().as_ref().unwrap().all_payloads()[payload_idx]
1317            .payload
1318            .mutator_bytes();
1319        let _other_size = other_input.len();
1320
1321        unsafe {
1322            buffer_copy(input, other_input, range.start, target, range.len());
1323        }
1324        metadata.has_changed = true;
1325
1326        log::debug!("[Mutation-bit] Mutate {} on trace {trace:?} crossing over with corpus id {idx} and payload id {payload_idx}", self.name());
1327        log::trace!("Trace: {trace}");
1328        Ok(MutationResult::Mutated)
1329    }
1330
1331    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
1332        Ok(())
1333    }
1334}
1335
1336impl<S, PT> Named for CrossoverInsertMutatorDY<S, PT>
1337where
1338    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1339    PT: ProtocolTypes,
1340{
1341    fn name(&self) -> &Cow<'static, str> {
1342        &Cow::Borrowed("CrossoverInsertMutatorDY")
1343    }
1344}
1345
1346pub struct CrossoverReplaceMutatorDY<S, PT>
1347where
1348    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1349    PT: ProtocolTypes,
1350{
1351    config: MutationConfig,
1352    phantom_s: std::marker::PhantomData<(S, PT)>,
1353}
1354
1355impl<S, PT> CrossoverReplaceMutatorDY<S, PT>
1356where
1357    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1358    PT: ProtocolTypes,
1359{
1360    #[must_use]
1361    pub fn new(config: MutationConfig) -> Self {
1362        Self {
1363            config: MutationConfig {
1364                term_constraints: TermConstraints {
1365                    not_readable: true,
1366                    ..config.term_constraints
1367                },
1368                ..config
1369            },
1370            phantom_s: std::marker::PhantomData,
1371        }
1372    }
1373}
1374
1375impl<S, PT> Named for CrossoverReplaceMutatorDY<S, PT>
1376where
1377    PT: ProtocolTypes,
1378    S: HasCorpus<Trace<PT>> + HasMaxSize + HasRand,
1379{
1380    fn name(&self) -> &Cow<'static, str> {
1381        &Cow::Borrowed("CrossoverReplaceMutatorDY")
1382    }
1383}
1384
1385impl<S, PT> Mutator<Trace<PT>, S> for CrossoverReplaceMutatorDY<S, PT>
1386where
1387    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1388    PT: ProtocolTypes,
1389{
1390    fn mutate(&mut self, state: &mut S, trace: &mut Trace<PT>) -> Result<MutationResult, Error> {
1391        log::debug!("[Bit] Start mutate with {}", self.name());
1392
1393        if !self.config.with_bit_level {
1394            log::debug!("[Mutation-bit] Mutate CrossoverReplaceMutatorDY skipped because bit-level mutations are disabled");
1395            return Ok(MutationResult::Skipped);
1396        }
1397
1398        let Some((input, metadata)) = choose_payload_mut(trace, state, &self.config) else {
1399            log::debug!("       Skipped {}", self.name());
1400            return Ok(MutationResult::Skipped);
1401        };
1402
1403        // Inlined from libafl::mutators::mutations pub struct CrossoverReplaceMutator
1404        let size = input.len();
1405        if size == 0 {
1406            log::debug!("       Skipped {}", self.name());
1407            return Ok(MutationResult::Skipped);
1408        }
1409
1410        // We don't want to use the testcase we're already using for splicing
1411        let idx = random_corpus_id!(state.corpus(), state.rand_mut());
1412        if let Some(cur) = state.corpus().current() {
1413            if idx == *cur {
1414                log::debug!("       Skipped {}", self.name());
1415                return Ok(MutationResult::Skipped);
1416            }
1417        }
1418
1419        // let other_size = {
1420        //     let mut other_testcase = state.corpus().get(idx)?.borrow_mut();
1421        //     other_testcase.load_input(state.corpus())?.bytes().len()
1422        // };
1423        let size_vec_payloads = {
1424            let mut other_testcase = state.corpus().get(idx)?.borrow_mut();
1425            let other_input_trace = other_testcase.load_input(state.corpus())?;
1426            other_input_trace.all_payloads().len()
1427        };
1428        if size_vec_payloads < 1 {
1429            log::debug!("       Skipped {}", self.name());
1430            return Ok(MutationResult::Skipped);
1431        }
1432        let payload_idx = state // we need to split the choice of other_input int two steps to
1433            // avoid borrow checker issues (state need sto be immutably borrowed to access the
1434            // corpus and mutably borrowed to pick a random payload in the chosen trace)
1435            .rand_mut()
1436            .between(0, size_vec_payloads - 1);
1437        let other_size = {
1438            let other_testcase = state.corpus().get(idx)?.borrow_mut();
1439            // Input will already be loaded.
1440            let other_input = other_testcase.input().as_ref().unwrap().all_payloads()[payload_idx]
1441                .payload
1442                .mutator_bytes();
1443            other_input.len()
1444        };
1445        //
1446
1447        if other_size < 2 {
1448            log::debug!("       Skipped {}", self.name());
1449            return Ok(MutationResult::Skipped);
1450        }
1451
1452        let target = state.rand_mut().below_or_zero(size);
1453        let range = rand_range(
1454            state,
1455            other_size,
1456            min(other_size, size - target).try_into()?,
1457        );
1458
1459        // let other_testcase = state.corpus().get(idx)?.borrow_mut();
1460        // // No need to load the input again, it'll still be cached.
1461        // let other = other_testcase.input().as_ref().unwrap();
1462        let other_testcase = state.corpus().get(idx)?.borrow_mut();
1463        // Input will already be loaded.
1464        let other_input = other_testcase.input().as_ref().unwrap().all_payloads()[payload_idx]
1465            .payload
1466            .mutator_bytes();
1467
1468        unsafe {
1469            buffer_copy(input, other_input, range.start, target, range.len());
1470        }
1471        metadata.has_changed = true;
1472
1473        log::debug!("[Mutation-bit] Mutate {} on trace {trace:?} crossing over with corpus id {idx} and payload id {payload_idx}", self.name());
1474        log::trace!("Trace: {trace}");
1475        Ok(MutationResult::Mutated)
1476    }
1477
1478    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
1479        Ok(())
1480    }
1481}
1482
1483pub struct SpliceMutatorDY<S, PT>
1484where
1485    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1486    PT: ProtocolTypes,
1487{
1488    config: MutationConfig,
1489    phantom_s: std::marker::PhantomData<(S, PT)>,
1490}
1491
1492impl<S, PT> SpliceMutatorDY<S, PT>
1493where
1494    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1495    PT: ProtocolTypes,
1496{
1497    #[must_use]
1498    pub fn new(config: MutationConfig) -> Self {
1499        Self {
1500            config: MutationConfig {
1501                term_constraints: TermConstraints {
1502                    not_readable: true,
1503                    ..config.term_constraints
1504                },
1505                ..config
1506            },
1507            phantom_s: std::marker::PhantomData,
1508        }
1509    }
1510}
1511
1512impl<S, PT> Named for SpliceMutatorDY<S, PT>
1513where
1514    PT: ProtocolTypes,
1515    S: HasCorpus<Trace<PT>> + HasMaxSize + HasRand,
1516{
1517    fn name(&self) -> &Cow<'static, str> {
1518        &Cow::Borrowed("SpliceMutatorDY")
1519    }
1520}
1521
1522impl<S, PT> Mutator<Trace<PT>, S> for SpliceMutatorDY<S, PT>
1523where
1524    S: HasCorpus<Trace<PT>> + HasRand + HasMaxSize,
1525    PT: ProtocolTypes,
1526{
1527    fn mutate(&mut self, state: &mut S, trace: &mut Trace<PT>) -> Result<MutationResult, Error> {
1528        log::debug!("[Bit] Start mutate with {}", self.name());
1529
1530        if !self.config.with_bit_level {
1531            log::debug!("[Mutation-bit] Mutate SpliceMutatorDY skipped because bit-level mutations are disabled");
1532            return Ok(MutationResult::Skipped);
1533        }
1534
1535        let Some((input, metadata)) = choose_payload_mut(trace, state, &self.config) else {
1536            log::trace!("choose_payload_mut failed");
1537            log::debug!("       Skipped {}", self.name());
1538            return Ok(MutationResult::Skipped);
1539        };
1540
1541        // Inlined from libafl::mutators::mutations pub struct SpliceMutator
1542        // We don't want to use the testcase we're already using for splicing
1543        let idx = random_corpus_id!(state.corpus(), state.rand_mut());
1544        if let Some(cur) = state.corpus().current() {
1545            if idx == *cur {
1546                log::trace!("Same other testcase");
1547                log::debug!("       Skipped {}", self.name());
1548                return Ok(MutationResult::Skipped);
1549            }
1550        }
1551
1552        // Picking up other payload
1553        let size_vec_payloads = {
1554            let mut other_testcase = state.corpus().get(idx)?.borrow_mut();
1555            let other_input_trace = other_testcase.load_input(state.corpus())?;
1556            other_input_trace.all_payloads().len()
1557        };
1558        if size_vec_payloads < 1 {
1559            log::trace!("other payload is too short: {size_vec_payloads}");
1560            log::debug!("       Skipped {}", self.name());
1561            return Ok(MutationResult::Skipped);
1562        }
1563        let payload_idx = state // we need to split the choice of other_input int two steps to
1564            // avoid borrow checker issues (state need sto be immutably borrowed to access the
1565            // corpus and mutably borrowed to pick a random payload in the chosen trace)
1566            .rand_mut()
1567            .between(0, size_vec_payloads - 1);
1568        let _other_size = {
1569            let other_testcase = state.corpus().get(idx)?.borrow_mut();
1570            // Input will already be loaded.
1571            let other_input = other_testcase.input().as_ref().unwrap().all_payloads()[payload_idx]
1572                .payload
1573                .mutator_bytes();
1574            other_input.len()
1575        };
1576        //
1577
1578        let (first_diff, last_diff) = {
1579            let other_testcase = state.corpus().get(idx)?.borrow_mut();
1580            // Input will already be loaded.
1581            let other_input = other_testcase.input().as_ref().unwrap().all_payloads()[payload_idx]
1582                .payload
1583                .mutator_bytes();
1584
1585            let mut counter: u32 = 0;
1586            loop {
1587                let (f, l) = locate_diffs(input, other_input);
1588
1589                if f != l && f >= 0 && l >= 2 {
1590                    break (f as usize, l as usize);
1591                }
1592                if counter == 3 {
1593                    log::trace!("counter is 3");
1594                    log::debug!("       Skipped {}", self.name());
1595                    return Ok(MutationResult::Skipped);
1596                }
1597                counter += 1;
1598            }
1599        };
1600
1601        let split_at = state.rand_mut().between(first_diff, last_diff);
1602
1603        let other_testcase = state.corpus().get(idx)?.borrow_mut();
1604        // Input will already be loaded.
1605        let other_input = other_testcase.input().as_ref().unwrap().all_payloads()[payload_idx]
1606            .payload
1607            .mutator_bytes();
1608
1609        input.splice(split_at.., other_input[split_at..].iter().copied());
1610        metadata.has_changed = true;
1611
1612        log::debug!("[Mutation-bit] Mutate {} on trace {trace:?} crossing over with corpus id {idx} and payload id {payload_idx}", self.name());
1613        log::trace!("Trace: {trace}");
1614        Ok(MutationResult::Mutated)
1615    }
1616
1617    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
1618        Ok(())
1619    }
1620}
1621
1622/***************************************************************************************************
1623                      New BytesLargeExpandMutator mutation
1624***************************************************************************************************/
1625
1626/// Large number of bytes expand mutation for inputs with a bytes vector (expand range: from 2^5 to
1627/// 2^12)
1628#[derive(Default, Debug)]
1629pub struct BytesLargeExpandMutator;
1630
1631impl<I, S> Mutator<I, S> for BytesLargeExpandMutator
1632where
1633    S: HasRand + HasMaxSize,
1634    I: HasMutatorBytes + ResizableMutator<u8>,
1635{
1636    fn mutate(&mut self, state: &mut S, input: &mut I) -> Result<MutationResult, Error> {
1637        let min_length_log = 5;
1638        let max_length_log = 12;
1639
1640        let max_size = state.max_size();
1641        let size = input.mutator_bytes().len();
1642        if size == 0 || size >= max_size {
1643            return Ok(MutationResult::Skipped);
1644        }
1645        if size < 1 << min_length_log {
1646            return Ok(MutationResult::Skipped);
1647        }
1648        let len_log = state.rand_mut().between(min_length_log, max_length_log);
1649        let len = min(1 << len_log, max_size - size);
1650        let start = state.rand_mut().between(0, size);
1651        let range = start..(start + len);
1652        log::trace!("[BytesLargeExpandMutator] len: {len}, range: {range:?}, size: {size}");
1653        input.resize(size + range.len(), 0);
1654        unsafe {
1655            buffer_self_copy(
1656                input.mutator_bytes_mut(),
1657                range.start,
1658                range.start + range.len(),
1659                size - range.start,
1660            );
1661        }
1662        log::trace!("After mutation, length is: {}", input.mutator_bytes().len());
1663
1664        Ok(MutationResult::Mutated)
1665    }
1666
1667    fn post_exec(&mut self, _state: &mut S, _new_corpus_id: Option<CorpusId>) -> Result<(), Error> {
1668        Ok(())
1669    }
1670}
1671
1672impl Named for BytesLargeExpandMutator {
1673    fn name(&self) -> &Cow<'static, str> {
1674        &Cow::Borrowed("BytesLargexpandMutator")
1675    }
1676}
1677
1678impl BytesLargeExpandMutator {
1679    /// Creates a new [`BytesLargeExpandMutator`].
1680    #[must_use]
1681    pub fn new() -> Self {
1682        Self
1683    }
1684}