1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
cfg_if::cfg_if! {
    if #[cfg(fuzzing_libfuzzer)] {
        /// The default engine used when defining a test target
        pub use bolero_libfuzzer::LibFuzzerEngine as DefaultEngine;
    } else if #[cfg(fuzzing_afl)] {
        /// The default engine used when defining a test target
        pub use bolero_afl::AflEngine as DefaultEngine;
    } else if #[cfg(fuzzing_honggfuzz)] {
        /// The default engine used when defining a test target
        pub use bolero_honggfuzz::HonggfuzzEngine as DefaultEngine;
    } else {
        mod test;

        /// The default engine used when defining a test target
        pub use crate::test::TestEngine as DefaultEngine;
    }
}

/// Re-export of [`bolero_generator`]
pub mod generator {
    pub use bolero_generator::{self, prelude::*};
}

#[doc(hidden)]
pub use bolero_engine::{self, TargetLocation, __item_path__};

pub use bolero_engine::{rng::RngEngine, Driver, DriverMode, Engine, Test};

use bolero_generator::{
    combinator::{AndThenGenerator, FilterGenerator, FilterMapGenerator, MapGenerator},
    TypeValueGenerator,
};
use core::{fmt::Debug, marker::PhantomData};

/// Execute fuzz tests for a given target
///
/// This should be executed in a separate test target, for example
/// `tests/my_fuzz_target/main.rs`.
///
/// # Examples
///
/// By default, `input` is a `&[u8]`.
///
/// This mode is generally used when testing an implementation that
/// handles raw bytes, e.g. a parser.
///
/// ```rust
/// use bolero::fuzz;
///
/// fn main() {
///     fuzz!().for_each(|input| {
///         // implement checks here
///     });
/// }
/// ```
///
/// Calling `with_type::<Type>()` will generate random values of `Type`
/// to be tested. `Type` is required to implement [`generator::TypeGenerator`]
/// in order to use this method.
///
/// This mode is used for testing an implementation that requires
/// structured input.
///
/// ```rust
/// use bolero::fuzz;
///
/// fn main() {
///     fuzz!()
///         .with_type::<(u8, u16)>()
///         .for_each(|(a, b)| {
///             // implement checks here
///         });
/// }
/// ```
///
/// The function `with_generator::<Generator>(generator)` will use the provided `Generator`,
/// which implements [`generator::ValueGenerator`], to generate input
/// values of type `Generator::Output`.
///
/// This mode is used for testing an implementation that requires
/// structured input with specific constraints applied to the type.
/// In the following example, we are only interested in generating
/// two values, one being between 0 and 100, the other: 10 and 50.
///
/// ```rust
/// use bolero::fuzz;
///
/// fn main() {
///     fuzz!()
///         .with_generator((0..100, 10..50))
///         .for_each(|(a, b)| {
///             // implement checks here
///         });
/// }
/// ```
///
/// For compatibility purposes, `bolero` also supports the same interface as
/// [rust-fuzz/afl.rs](https://github.com/rust-fuzz/afl.rs). This usage
/// has a few downsides:
///
/// * The test cannot be configured
/// * The test code will be contained inside a macro which can trip up
///   some editors and IDEs.
///
/// ```rust
/// use bolero::fuzz;
///
/// fn main() {
///     fuzz!(|input| {
///         // implement checks here
///     });
/// }
/// ```

#[macro_export]
macro_rules! fuzz {
    () => {{
        let item_path = $crate::__item_path__!();
        $crate::fuzz!(name = item_path)
    }};
    ($fun:path) => {
        $crate::fuzz!(|input| { $fun(input) })
    };
    (| $input:ident $(: &[u8])? | $impl:expr) => {
        $crate::fuzz!().for_each(|$input: &[u8]| $impl)
    };
    (| $input:ident : $ty:ty | $impl:expr) => {
        $crate::fuzz!().with_type().for_each(|$input: $ty| $impl)
    };
    (name = $target_name:expr) => {{
        let location = $crate::TargetLocation {
            package_name: env!("CARGO_PKG_NAME"),
            manifest_dir: env!("CARGO_MANIFEST_DIR"),
            module_path: module_path!(),
            file: file!(),
            line: line!(),
            item_path: format!("{}", $target_name),
        };

        if !location.should_run() {
            return;
        }

        $crate::fuzz(location)
    }};
}

/// Configuration for a test target
pub struct TestTarget<Generator, Engine, InputOwnership> {
    generator: Generator,
    driver_mode: Option<DriverMode>,
    engine: Engine,
    input_ownership: PhantomData<InputOwnership>,
}

#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BorrowedInput;

#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ClonedInput;

#[doc(hidden)]
pub fn fuzz(
    location: TargetLocation,
) -> TestTarget<ByteSliceGenerator, DefaultEngine, BorrowedInput> {
    TestTarget::new(DefaultEngine::new(location))
}

/// Default generator for byte slices
#[derive(Copy, Clone, Default, PartialEq)]
pub struct ByteSliceGenerator;

impl<Engine> TestTarget<ByteSliceGenerator, Engine, BorrowedInput> {
    /// Create a `TestTarget` with the given `Engine`
    pub fn new(engine: Engine) -> TestTarget<ByteSliceGenerator, Engine, BorrowedInput> {
        Self {
            driver_mode: None,
            generator: ByteSliceGenerator,
            engine,
            input_ownership: PhantomData,
        }
    }
}

impl<G, Engine, InputOwnership> TestTarget<G, Engine, InputOwnership> {
    /// Set the value generator for the `TestTarget`
    ///
    /// The function `with_generator::<Generator>(generator)` will use the provided `Generator`,
    /// which implements [`generator::ValueGenerator`], to generate input
    /// values of type `Generator::Output`.
    ///
    /// This mode is used for testing an implementation that requires
    /// structured input with specific constraints applied to the type.
    pub fn with_generator<Generator: generator::ValueGenerator>(
        self,
        generator: Generator,
    ) -> TestTarget<Generator, Engine, InputOwnership>
    where
        Generator::Output: Debug,
    {
        TestTarget {
            driver_mode: self.driver_mode,
            generator,
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }

    /// Set the type generator for the `TestTarget`
    ///
    /// Calling `with_type::<Type>()` will generate random values of `Type`
    /// to be tested. `Type` is required to implement [`generator::TypeGenerator`]
    /// in order to use this method.
    ///
    /// This mode is used for testing an implementation that requires
    /// structured input.
    pub fn with_type<T: Debug + generator::TypeGenerator>(
        self,
    ) -> TestTarget<TypeValueGenerator<T>, Engine, InputOwnership> {
        TestTarget {
            driver_mode: self.driver_mode,
            generator: generator::gen(),
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }
}

impl<G: generator::ValueGenerator, Engine, InputOwnership> TestTarget<G, Engine, InputOwnership> {
    /// Map the value of the generator
    pub fn map<F: Fn(G::Output) -> T, T: Debug>(
        self,
        map: F,
    ) -> TestTarget<MapGenerator<G, F>, Engine, InputOwnership> {
        TestTarget {
            driver_mode: self.driver_mode,
            generator: self.generator.map(map),
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }

    /// Map the value of the generator with a new generator
    pub fn and_then<F: Fn(G::Output) -> T, T: generator::ValueGenerator>(
        self,
        map: F,
    ) -> TestTarget<AndThenGenerator<G, F>, Engine, InputOwnership>
    where
        T::Output: Debug,
    {
        TestTarget {
            driver_mode: self.driver_mode,
            generator: self.generator.and_then(map),
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }

    /// Filter the value of the generator
    pub fn filter<F: Fn(&G::Output) -> bool>(
        self,
        filter: F,
    ) -> TestTarget<FilterGenerator<G, F>, Engine, InputOwnership> {
        TestTarget {
            driver_mode: self.driver_mode,
            generator: self.generator.filter(filter),
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }

    /// Filter the value of the generator and map it to something else
    pub fn filter_map<F: Fn(G::Output) -> Option<T>, T>(
        self,
        filter_map: F,
    ) -> TestTarget<FilterMapGenerator<G, F>, Engine, InputOwnership> {
        TestTarget {
            driver_mode: self.driver_mode,
            generator: self.generator.filter_map(filter_map),
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }

    /// Set the driver mode for the fuzz target
    pub fn with_driver_mode(self, mode: DriverMode) -> Self {
        TestTarget {
            driver_mode: Some(mode),
            generator: self.generator,
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }
}

impl<G, InputOwnership> TestTarget<G, RngEngine, InputOwnership> {
    /// Set the number of iterations executed
    pub fn with_iterations(mut self, iterations: usize) -> Self {
        self.engine.iterations = iterations;
        TestTarget {
            driver_mode: self.driver_mode,
            generator: self.generator,
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }

    /// Set the maximum length of the generated bytes
    pub fn with_max_len(mut self, max_len: usize) -> Self {
        self.engine.max_len = max_len;
        TestTarget {
            driver_mode: self.driver_mode,
            generator: self.generator,
            engine: self.engine,
            input_ownership: self.input_ownership,
        }
    }
}

impl<G, Engine> TestTarget<G, Engine, BorrowedInput> {
    /// Use a cloned value for the test input
    ///
    /// Cloning the test inputs will force a call to [`Clone::clone`]
    /// on each input value, and therefore, will be less
    /// efficient than using a reference.
    pub fn cloned(self) -> TestTarget<G, Engine, ClonedInput> {
        TestTarget {
            driver_mode: self.driver_mode,
            generator: self.generator,
            engine: self.engine,
            input_ownership: PhantomData,
        }
    }
}

impl<G, E> TestTarget<G, E, BorrowedInput>
where
    G: generator::ValueGenerator,
{
    /// Iterate over all of the inputs and check the `TestTarget`
    pub fn for_each<F>(mut self, test: F) -> E::Output
    where
        E: Engine<bolero_engine::BorrowedGeneratorTest<F, G, G::Output>>,
        bolero_engine::BorrowedGeneratorTest<F, G, G::Output>: Test,
    {
        let test = bolero_engine::BorrowedGeneratorTest::new(test, self.generator);
        if let Some(mode) = self.driver_mode {
            self.engine.set_driver_mode(mode);
        }
        self.engine.run(test)
    }
}

impl<G, E> TestTarget<G, E, ClonedInput>
where
    G: generator::ValueGenerator,
{
    /// Iterate over all of the inputs and check the `TestTarget`
    pub fn for_each<F>(mut self, test: F) -> E::Output
    where
        E: Engine<bolero_engine::ClonedGeneratorTest<F, G, G::Output>>,
        bolero_engine::ClonedGeneratorTest<F, G, G::Output>: Test,
    {
        let test = bolero_engine::ClonedGeneratorTest::new(test, self.generator);
        if let Some(mode) = self.driver_mode {
            self.engine.set_driver_mode(mode);
        }
        self.engine.run(test)
    }
}

impl<E> TestTarget<ByteSliceGenerator, E, BorrowedInput> {
    /// Iterate over all of the inputs and check the `TestTarget`
    pub fn for_each<T>(mut self, test: T) -> E::Output
    where
        E: Engine<bolero_engine::BorrowedSliceTest<T>>,
        bolero_engine::BorrowedSliceTest<T>: Test,
    {
        let test = bolero_engine::BorrowedSliceTest::new(test);
        if let Some(mode) = self.driver_mode {
            self.engine.set_driver_mode(mode);
        }
        self.engine.run(test)
    }
}

impl<E> TestTarget<ByteSliceGenerator, E, ClonedInput> {
    /// Iterate over all of the inputs and check the `TestTarget`
    pub fn for_each<T>(mut self, test: T) -> E::Output
    where
        E: Engine<bolero_engine::ClonedSliceTest<T>>,
        bolero_engine::ClonedSliceTest<T>: Test,
    {
        let test = bolero_engine::ClonedSliceTest::new(test);
        if let Some(mode) = self.driver_mode {
            self.engine.set_driver_mode(mode);
        }
        self.engine.run(test)
    }
}

#[test]
#[should_panic]
fn slice_generator_test() {
    fuzz!().for_each(|input| {
        assert!(input.len() > 1000);
    });
}

#[test]
#[should_panic]
fn type_generator_test() {
    fuzz!().with_type().for_each(|input: &u8| {
        assert!(input < &128);
    });
}

#[test]
#[should_panic]
fn type_generator_cloned_test() {
    fuzz!().with_type().cloned().for_each(|input: u8| {
        assert!(input < 128);
    });
}

#[test]
fn range_generator_test() {
    fuzz!().with_generator(0..=5).for_each(|_input: &u8| {
        // println!("{:?}", input);
    });
}

#[test]
fn range_generator_cloned_test() {
    fuzz!()
        .with_generator(0..=5)
        .cloned()
        .for_each(|_input: u8| {
            // println!("{:?}", input);
        });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn nested_test() {
        fuzz!().with_generator(0..=5).for_each(|_input: &u8| {
            // println!("{:?}", input);
        });
    }
}