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
//! The [`DumpToDiskStage`] is a stage that dumps the corpus and the solutions to disk to e.g. allow AFL to sync

use alloc::vec::Vec;
use core::{clone::Clone, marker::PhantomData};
use std::{fs, fs::File, io::Write, path::PathBuf};

use serde::{Deserialize, Serialize};

use crate::{
    corpus::{Corpus, CorpusId},
    inputs::UsesInput,
    stages::Stage,
    state::{HasCorpus, HasMetadata, HasRand, HasSolutions, UsesState},
    Error,
};

/// Metadata used to store information about disk dump indexes for names
#[derive(Default, Serialize, Deserialize, Clone, Debug)]
pub struct DumpToDiskMetadata {
    last_corpus: Option<CorpusId>,
    last_solution: Option<CorpusId>,
}

crate::impl_serdeany!(DumpToDiskMetadata);

/// The [`DumpToDiskStage`] is a stage that dumps the corpus and the solutions to disk
#[derive(Debug)]
pub struct DumpToDiskStage<CB, EM, Z> {
    solutions_dir: PathBuf,
    corpus_dir: PathBuf,
    to_bytes: CB,
    phantom: PhantomData<(EM, Z)>,
}

impl<CB, EM, Z> UsesState for DumpToDiskStage<CB, EM, Z>
where
    EM: UsesState,
{
    type State = EM::State;
}

impl<CB, E, EM, Z> Stage<E, EM, Z> for DumpToDiskStage<CB, EM, Z>
where
    CB: FnMut(&<Z::State as UsesInput>::Input) -> Vec<u8>,
    EM: UsesState<State = Z::State>,
    E: UsesState<State = Z::State>,
    Z: UsesState,
    Z::State: HasCorpus + HasSolutions + HasRand + HasMetadata,
{
    #[inline]
    fn perform(
        &mut self,
        _fuzzer: &mut Z,
        _executor: &mut E,
        state: &mut Z::State,
        _manager: &mut EM,
        _corpus_idx: CorpusId,
    ) -> Result<(), Error> {
        let (mut corpus_idx, mut solutions_idx) =
            if let Some(meta) = state.metadata().get::<DumpToDiskMetadata>() {
                (
                    meta.last_corpus.and_then(|x| state.corpus().next(x)),
                    meta.last_solution.and_then(|x| state.solutions().next(x)),
                )
            } else {
                (state.corpus().first(), state.solutions().first())
            };

        while let Some(i) = corpus_idx {
            let mut testcase = state.corpus().get(i)?.borrow_mut();
            let input = testcase.load_input()?;
            let bytes = (self.to_bytes)(input);

            let fname = self.corpus_dir.join(format!("id_{i}"));
            let mut f = File::create(fname)?;
            drop(f.write_all(&bytes));

            corpus_idx = state.corpus().next(i);
        }

        while let Some(i) = solutions_idx {
            let mut testcase = state.solutions().get(i)?.borrow_mut();
            let input = testcase.load_input()?;
            let bytes = (self.to_bytes)(input);

            let fname = self.solutions_dir.join(format!("id_{i}"));
            let mut f = File::create(fname)?;
            drop(f.write_all(&bytes));

            solutions_idx = state.solutions().next(i);
        }

        state.add_metadata(DumpToDiskMetadata {
            last_corpus: state.corpus().last(),
            last_solution: state.solutions().last(),
        });

        Ok(())
    }
}

impl<CB, EM, Z> DumpToDiskStage<CB, EM, Z>
where
    CB: FnMut(&<Z::State as UsesInput>::Input) -> Vec<u8>,
    EM: UsesState<State = Z::State>,
    Z: UsesState,
    Z::State: HasCorpus + HasSolutions + HasRand + HasMetadata,
{
    /// Create a new [`DumpToDiskStage`]
    pub fn new<A, B>(to_bytes: CB, corpus_dir: A, solutions_dir: B) -> Result<Self, Error>
    where
        A: Into<PathBuf>,
        B: Into<PathBuf>,
    {
        let corpus_dir = corpus_dir.into();
        if let Err(e) = fs::create_dir(&corpus_dir) {
            if !corpus_dir.is_dir() {
                return Err(Error::file(e));
            }
        }
        let solutions_dir = solutions_dir.into();
        if let Err(e) = fs::create_dir(&solutions_dir) {
            if !corpus_dir.is_dir() {
                return Err(Error::file(e));
            }
        }
        Ok(Self {
            to_bytes,
            solutions_dir,
            corpus_dir,
            phantom: PhantomData,
        })
    }
}