1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use bolero_engine::{rng::RngEngine, ByteSliceTestInput, Engine, Never, TargetLocation, Test};
use bolero_generator::driver::DriverMode;
use core::iter::empty;
use libtest_mimic::{run_tests, Arguments, FormatSetting, Outcome, Test as LibTest};
use std::path::PathBuf;

mod input;
use input::*;

/// Engine implementation which mimics Rust's default test
/// harness. By default, the test inputs will include any present
/// `corpus` and `crashes` files, as well as generating
#[derive(Debug)]
pub struct TestEngine {
    location: TargetLocation,
    driver_mode: Option<DriverMode>,
}

impl TestEngine {
    #[allow(dead_code)]
    pub fn new(location: TargetLocation) -> Self {
        Self {
            location,
            driver_mode: None,
        }
    }

    fn sub_dir<'a, D: Iterator<Item = &'a str>>(&self, dirs: D) -> PathBuf {
        let mut fuzz_target_path = self
            .location
            .work_dir()
            .expect("could not resolve target work dir");

        fuzz_target_path.extend(dirs);

        fuzz_target_path
    }

    fn file_tests<'a, D: Iterator<Item = &'a str>>(
        &self,
        sub_dirs: D,
    ) -> impl Iterator<Item = LibTest<TestInput>> {
        std::fs::read_dir(self.sub_dir(sub_dirs))
            .ok()
            .into_iter()
            .map(move |dir| {
                dir.filter_map(Result::ok)
                    .map(|item| item.path())
                    .filter(|path| path.is_file())
                    .filter(|path| !path.file_name().unwrap().to_str().unwrap().starts_with('.'))
                    .map(move |path| LibTest {
                        name: format!("{}", path.display()),
                        kind: "".into(),
                        is_ignored: false,
                        is_bench: false,
                        data: TestInput::FileTest(FileTest { path }),
                    })
            })
            .flatten()
    }

    #[cfg(feature = "rand")]
    fn rng_tests(&self) -> impl Iterator<Item = LibTest<TestInput>> {
        use rand::{rngs::StdRng, RngCore, SeedableRng};

        let rng_info = RngEngine::default();
        let mut seed_rng = StdRng::seed_from_u64(rng_info.seed);

        let test_name = self.location.module_path;

        (0..rng_info.iterations)
            .scan(rng_info.seed, move |state, _index| {
                let seed = *state;
                *state = seed_rng.next_u64();
                Some(seed)
            })
            .map(move |seed| LibTest {
                name: format!("{} [seed={}]", test_name, seed),
                kind: "".into(),
                is_ignored: false,
                is_bench: false,
                data: TestInput::RngTest(RngTest {
                    seed,
                    max_len: rng_info.max_len,
                }),
            })
    }

    #[cfg(not(feature = "rand"))]
    fn rng_tests(&self) -> impl Iterator<Item = LibTest<TestInput>> {
        empty()
    }

    fn tests(&self) -> Vec<LibTest<TestInput>> {
        empty()
            .chain(self.file_tests(["corpus"].iter().cloned()))
            .chain(self.file_tests(["crashes"].iter().cloned()))
            .chain(self.file_tests(["afl_state", "hangs"].iter().cloned()))
            .chain(self.file_tests(["afl_state", "queue"].iter().cloned()))
            .chain(self.file_tests(["afl_state", "crashes"].iter().cloned()))
            .chain(self.rng_tests())
            .collect()
    }

    /// Use the libtest_mimic harness
    fn libtest_mimic(self, testfn: &mut dyn FnMut(&TestInput) -> Result<bool, String>) -> Never {
        // `run_tests` only accepts `Fn` instead of `FnMut`
        // convert the function to a dynamic FnMut and drop the lifetime
        static mut TESTFN: Option<&mut dyn FnMut(&TestInput) -> Result<bool, String>> = None;

        unsafe {
            TESTFN = Some(std::mem::transmute(
                testfn as &mut dyn FnMut(&TestInput) -> Result<bool, String>,
            ));
        }

        let mut arguments = Arguments::from_args();

        if arguments.format.is_none() {
            arguments.format = Some(FormatSetting::Terse);
        }

        let tests = self.tests();

        bolero_engine::panic::set_hook();
        bolero_engine::panic::forward_panic(true);

        let result = run_tests(&arguments, tests, |config| {
            let testfn = unsafe { TESTFN.as_mut().expect("uninitialized test function") };
            if let Err(err) = testfn(&config.data) {
                Outcome::Failed { msg: Some(err) }
            } else {
                Outcome::Passed
            }
        });

        result.exit();
    }

    /// Use the libtest harness
    fn libtest(self, testfn: &mut dyn FnMut(&TestInput) -> Result<bool, String>) -> Never {
        let tests = self.tests();

        bolero_engine::panic::set_hook();
        bolero_engine::panic::forward_panic(false);

        for test in tests {
            if let Err(err) = testfn(&test.data) {
                bolero_engine::panic::forward_panic(true);
                eprintln!("{}", err);
                panic!();
            }
        }
    }
}

impl<T: Test> Engine<T> for TestEngine
where
    T::Value: core::fmt::Debug,
{
    type Output = Never;

    fn set_driver_mode(&mut self, mode: DriverMode) {
        self.driver_mode = Some(mode);
    }

    fn run(self, mut test: T) -> Self::Output {
        let driver_mode = self.driver_mode;
        let mut input = vec![];
        let mut testfn = &mut |data: &TestInput| {
            input.clear();
            data.read_into(&mut input);

            test.test(&mut ByteSliceTestInput::new(&input, driver_mode))
                .map_err(|_| {
                    let failure = test
                        .shrink(input.clone(), data.seed(), driver_mode)
                        .expect("test should fail");

                    format!("{:#}", failure)
                })
        };

        if self.location.is_harnessed() {
            self.libtest(&mut testfn)
        } else {
            self.libtest_mimic(&mut testfn)
        }
    }
}