libfuzzer_sys/
lib.rs

1//! Bindings to [libFuzzer](http://llvm.org/docs/LibFuzzer.html): a runtime for
2//! coverage-guided fuzzing.
3//!
4//! See [the `cargo-fuzz`
5//! guide](https://rust-fuzz.github.io/book/cargo-fuzz.html) for a usage
6//! tutorial.
7//!
8//! The main export of this crate is [the `fuzz_target!`
9//! macro](./macro.fuzz_target.html), which allows you to define targets for
10//! libFuzzer to exercise.
11
12#![deny(missing_docs, missing_debug_implementations)]
13
14pub use arbitrary;
15use std::sync::OnceLock;
16
17/// Indicates whether the input should be kept in the corpus or rejected. This
18/// should be returned by your fuzz target. If your fuzz target does not return
19/// a value (i.e., returns `()`), then the input will be kept in the corpus.
20#[derive(Debug)]
21pub enum Corpus {
22    /// Keep the input in the corpus.
23    Keep,
24
25    /// Reject the input and do not keep it in the corpus.
26    Reject,
27}
28
29impl From<()> for Corpus {
30    fn from(_: ()) -> Self {
31        Self::Keep
32    }
33}
34
35impl Corpus {
36    #[doc(hidden)]
37    /// Convert this Corpus result into the [integer codes used by
38    /// `libFuzzer`](https://llvm.org/docs/LibFuzzer.html#rejecting-unwanted-inputs).
39    /// This is -1 for reject, 0 for keep.
40    pub fn to_libfuzzer_code(self) -> i32 {
41        match self {
42            Corpus::Keep => 0,
43            Corpus::Reject => -1,
44        }
45    }
46}
47
48extern "C" {
49    // We do not actually cross the FFI bound here.
50    #[allow(improper_ctypes)]
51    fn rust_fuzzer_test_input(input: &[u8]) -> i32;
52
53    fn LLVMFuzzerMutate(data: *mut u8, size: usize, max_size: usize) -> usize;
54}
55
56/// Do not use; only for LibFuzzer's consumption.
57#[doc(hidden)]
58#[export_name = "LLVMFuzzerTestOneInput"]
59pub unsafe fn test_input_wrap(data: *const u8, size: usize) -> i32 {
60    let test_input = ::std::panic::catch_unwind(|| {
61        let data_slice = ::std::slice::from_raw_parts(data, size);
62        rust_fuzzer_test_input(data_slice)
63    });
64
65    match test_input {
66        Ok(i) => i,
67        Err(_) => {
68            // hopefully the custom panic hook will be called before and abort the
69            // process before the stack frames are unwinded.
70            ::std::process::abort();
71        }
72    }
73}
74
75#[doc(hidden)]
76pub fn rust_libfuzzer_debug_path() -> &'static Option<String> {
77    static RUST_LIBFUZZER_DEBUG_PATH: OnceLock<Option<String>> = OnceLock::new();
78    RUST_LIBFUZZER_DEBUG_PATH.get_or_init(|| std::env::var("RUST_LIBFUZZER_DEBUG_PATH").ok())
79}
80
81#[doc(hidden)]
82pub fn initialize(_argc: *const isize, _argv: *const *const *const u8) -> isize {
83    // Registers a panic hook that aborts the process before unwinding.
84    // It is useful to abort before unwinding so that the fuzzer will then be
85    // able to analyse the process stack frames to tell different bugs appart.
86    //
87    // HACK / FIXME: it would be better to use `-C panic=abort` but it's currently
88    // impossible to build code using compiler plugins with this flag.
89    // We will be able to remove this code when
90    // https://github.com/rust-lang/cargo/issues/5423 is fixed.
91    let default_hook = std::panic::take_hook();
92    std::panic::set_hook(Box::new(move |panic_info| {
93        default_hook(panic_info);
94        std::process::abort();
95    }));
96    0
97}
98
99/// Define a fuzz target.
100///
101/// ## Example
102///
103/// This example takes a `&[u8]` slice and attempts to parse it. The parsing
104/// might fail and return an `Err`, but it shouldn't ever panic or segfault.
105///
106/// ```no_run
107/// #![no_main]
108///
109/// use libfuzzer_sys::fuzz_target;
110///
111/// // Note: `|input|` is short for `|input: &[u8]|`.
112/// fuzz_target!(|input| {
113///     let _result: Result<_, _> = my_crate::parse(input);
114/// });
115/// # mod my_crate { pub fn parse(_: &[u8]) -> Result<(), ()> { unimplemented!() } }
116/// ```
117///
118/// ## Rejecting Inputs
119///
120/// It may be desirable to reject some inputs, i.e. to not add them to the
121/// corpus.
122///
123/// For example, when fuzzing an API consisting of parsing and other logic,
124/// one may want to allow only those inputs into the corpus that parse
125/// successfully. To indicate whether an input should be kept in or rejected
126/// from the corpus, return either [Corpus::Keep] or [Corpus::Reject] from your
127/// fuzz target. The default behavior (e.g. if `()` is returned) is to keep the
128/// input in the corpus.
129///
130/// For example:
131///
132/// ```no_run
133/// #![no_main]
134///
135/// use libfuzzer_sys::{Corpus, fuzz_target};
136///
137/// fuzz_target!(|input: String| -> Corpus {
138///     let parts: Vec<&str> = input.splitn(2, '=').collect();
139///     if parts.len() != 2 {
140///         return Corpus::Reject;
141///     }
142///
143///     let key = parts[0];
144///     let value = parts[1];
145///     let _result: Result<_, _> = my_crate::parse(key, value);
146///     Corpus::Keep
147/// });
148/// # mod my_crate { pub fn parse(_key: &str, _value: &str) -> Result<(), ()> { unimplemented!() } }
149/// ```
150///
151/// ## Arbitrary Input Types
152///
153/// The input is a `&[u8]` slice by default, but you can take arbitrary input
154/// types, as long as the type implements [the `arbitrary` crate's `Arbitrary`
155/// trait](https://docs.rs/arbitrary/*/arbitrary/trait.Arbitrary.html) (which is
156/// also re-exported as `libfuzzer_sys::arbitrary::Arbitrary` for convenience).
157///
158/// For example, if you wanted to take an arbitrary RGB color, you could do the
159/// following:
160///
161/// ```no_run
162/// #![no_main]
163/// # mod foo {
164///
165/// use libfuzzer_sys::{arbitrary::{Arbitrary, Error, Unstructured}, fuzz_target};
166///
167/// #[derive(Debug)]
168/// pub struct Rgb {
169///     r: u8,
170///     g: u8,
171///     b: u8,
172/// }
173///
174/// impl<'a> Arbitrary<'a> for Rgb {
175///     fn arbitrary(raw: &mut Unstructured<'a>) -> Result<Self, Error> {
176///         let mut buf = [0; 3];
177///         raw.fill_buffer(&mut buf)?;
178///         let r = buf[0];
179///         let g = buf[1];
180///         let b = buf[2];
181///         Ok(Rgb { r, g, b })
182///     }
183/// }
184///
185/// // Write a fuzz target that works with RGB colors instead of raw bytes.
186/// fuzz_target!(|color: Rgb| {
187///     my_crate::convert_color(color);
188/// });
189/// # mod my_crate {
190/// #     use super::Rgb;
191/// #     pub fn convert_color(_: Rgb) {}
192/// # }
193/// # }
194/// ```
195///
196/// You can also enable the `arbitrary` crate's custom derive via this crate's
197/// `"arbitrary-derive"` cargo feature.
198///
199/// ## Init Code
200///
201/// Init code to the fuzz target by using the `init` keyword. This is called once before the fuzzer starts.
202/// Supports short |input| or |input: <type>| syntax.
203///
204/// ```no_run
205/// #![no_main]
206///
207/// use libfuzzer_sys::fuzz_target;
208/// use std::collections::HashSet;
209/// use std::sync::OnceLock;
210///
211/// static DICTIONARY: OnceLock<HashSet<String>> = OnceLock::new();
212///
213/// fuzz_target!(
214///     init: {
215///         let read_dictionary = |_| unimplemented!();
216///         let dictionary = read_dictionary("/usr/share/dict/words");
217///         DICTIONARY.set(dictionary).unwrap();
218///     },
219///     |input| {
220///         // Use the initialized `DICTIONARY` here...
221///     }
222/// );
223/// ```
224///
225#[macro_export]
226macro_rules! fuzz_target {
227    (init: $init:expr, |$bytes:ident| $body:expr) => {
228        const _: () = {
229            /// Auto-generated functions
230            /// LLVMFuzzerInitialize is called once before the fuzzer starts.
231            #[no_mangle]
232            pub extern "C" fn LLVMFuzzerInitialize(_argc: *const isize, _argv: *const *const *const u8) -> isize {
233                $crate::initialize(_argc, _argv);
234
235                // Supplied init code
236                $init;
237                0
238            }
239
240            #[no_mangle]
241            pub extern "C" fn rust_fuzzer_test_input(bytes: &[u8]) -> i32 {
242                // When `RUST_LIBFUZZER_DEBUG_PATH` is set, write the debug
243                // formatting of the input to that file. This is only intended for
244                // `cargo fuzz`'s use!
245
246                // `RUST_LIBFUZZER_DEBUG_PATH` is set in initialization.
247                if let Some(path) = $crate::rust_libfuzzer_debug_path() {
248                    use std::io::Write;
249                    let mut file = std::fs::File::create(path)
250                        .expect("failed to create `RUST_LIBFUZZER_DEBUG_PATH` file");
251                    writeln!(&mut file, "{:?}", bytes)
252                        .expect("failed to write to `RUST_LIBFUZZER_DEBUG_PATH` file");
253                    return 0;
254                }
255
256                __libfuzzer_sys_run(bytes);
257                0
258            }
259
260            // Split out the actual fuzzer into a separate function which is
261            // tagged as never being inlined. This ensures that if the fuzzer
262            // panics there's at least one stack frame which is named uniquely
263            // according to this specific fuzzer that this is embedded within.
264            //
265            // Systems like oss-fuzz try to deduplicate crashes and without this
266            // panics in separate fuzzers can accidentally appear the same
267            // because each fuzzer will have a function called
268            // `rust_fuzzer_test_input`. By using a normal Rust function here
269            // it's named something like `the_fuzzer_name::_::__libfuzzer_sys_run` which should
270            // ideally help prevent oss-fuzz from deduplicate fuzz bugs across
271            // distinct targets accidentally.
272            #[inline(never)]
273            fn __libfuzzer_sys_run($bytes: &[u8]) {
274                $body
275            }
276        };
277    };
278
279    (|$bytes:ident| $body:expr) => {
280        $crate::fuzz_target!(|$bytes: &[u8]| $body);
281    };
282
283    (|$data:ident: &[u8]| $body:expr) => {
284        $crate::fuzz_target!(init: (), |$data| $body);
285    };
286
287    (|$data:ident: $dty:ty| $body:expr) => {
288        $crate::fuzz_target!(init: (), |$data: $dty| -> () { $body });
289    };
290
291    (|$data:ident: $dty:ty| -> $rty:ty $body:block) => {
292        $crate::fuzz_target!(init: (), |$data: $dty| -> $rty { $body });
293    };
294
295    (init: $init:expr, |$data:ident: &[u8]| $body:expr) => {
296        $crate::fuzz_target!(init: $init, |$data| $body);
297    };
298
299    (init: $init:expr, |$bytes:ident| $body:expr) => {
300        $crate::fuzz_target!(init: $init, |$bytes: &[u8]| $body);
301    };
302
303    (init: $init:expr, |$data:ident: $dty:ty| $body:expr) => {
304        $crate::fuzz_target!(init: $init, |$data: $dty| -> () { $body });
305    };
306
307    (init: $init:expr, |$data:ident: $dty:ty| -> $rty:ty $body:block) => {
308        const _: () = {
309            /// Auto-generated functions
310            /// LLVMFuzzerInitialize is called once before the fuzzer starts.
311            #[no_mangle]
312            pub extern "C" fn LLVMFuzzerInitialize(_argc: *const isize, _argv: *const *const *const u8) -> isize {
313                $crate::initialize(_argc, _argv);
314
315                // Supplied init code
316                $init;
317                0
318            }
319
320            #[no_mangle]
321            pub extern "C" fn rust_fuzzer_test_input(bytes: &[u8]) -> i32 {
322                use $crate::arbitrary::{Arbitrary, Unstructured};
323
324                // Early exit if we don't have enough bytes for the `Arbitrary`
325                // implementation. This helps the fuzzer avoid exploring all the
326                // different not-enough-input-bytes paths inside the `Arbitrary`
327                // implementation. Additionally, it exits faster, letting the fuzzer
328                // get to longer inputs that actually lead to interesting executions
329                // quicker.
330                if bytes.len() < <$dty as Arbitrary>::size_hint(0).0 {
331                    return -1;
332                }
333
334                let mut u = Unstructured::new(bytes);
335                let data = <$dty as Arbitrary>::arbitrary_take_rest(u);
336
337                // When `RUST_LIBFUZZER_DEBUG_PATH` is set, write the debug
338                // formatting of the input to that file. This is only intended for
339                // `cargo fuzz`'s use!
340
341                // `RUST_LIBFUZZER_DEBUG_PATH` is set in initialization.
342                if let Some(path) = $crate::rust_libfuzzer_debug_path() {
343                    use std::io::Write;
344                    let mut file = std::fs::File::create(path)
345                        .expect("failed to create `RUST_LIBFUZZER_DEBUG_PATH` file");
346                    (match data {
347                        Ok(data) => writeln!(&mut file, "{:#?}", data),
348                        Err(err) => writeln!(&mut file, "Arbitrary Error: {}", err),
349                    })
350                    .expect("failed to write to `RUST_LIBFUZZER_DEBUG_PATH` file");
351                    return -1;
352                }
353
354                let data = match data {
355                    Ok(d) => d,
356                    Err(_) => return -1,
357                };
358
359                let result = ::libfuzzer_sys::Corpus::from(__libfuzzer_sys_run(data));
360                result.to_libfuzzer_code()
361            }
362            // See above for why this is split to a separate function.
363            #[inline(never)]
364            fn __libfuzzer_sys_run($data: $dty) -> $rty {
365                $body
366            }
367        };
368    };
369}
370
371/// Define a custom mutator.
372///
373/// This is optional, and libFuzzer will use its own, default mutation strategy
374/// if this is not provided.
375///
376/// You might consider using a custom mutator when your fuzz target is very
377/// particular about the shape of its input:
378///
379/// * You want to fuzz "deeper" than just the parser.
380/// * The input contains checksums that have to match the hash of some subset of
381///   the data or else the whole thing is invalid, and therefore mutating any of
382///   that subset means you need to recompute the checksums.
383/// * Small random changes to the input buffer make it invalid.
384///
385/// That is, a custom mutator is useful in similar situations where [a `T:
386/// Arbitrary` input type](macro.fuzz_target.html#arbitrary-input-types) is
387/// useful. Note that the two approaches are not mutually exclusive; you can use
388/// whichever is easier for your problem domain or both!
389///
390/// ## Implementation Contract
391///
392/// The original, unmodified input is given in `data[..size]`.
393///
394/// You must modify the data in place and return the new size.
395///
396/// The new size should not be greater than `max_size`. If this is not the case,
397/// then the `data` will be truncated to fit within `max_size`. Note that
398/// `max_size < size` is possible when shrinking test cases.
399///
400/// You must produce the same mutation given the same `seed`. Generally, when
401/// choosing what kind of mutation to make or where to mutate, you should start
402/// by creating a random number generator (RNG) that is seeded with the given
403/// `seed` and then consult the RNG whenever making a decision:
404///
405/// ```no_run
406/// #![no_main]
407///
408/// use rand::{rngs::StdRng, Rng, SeedableRng};
409///
410/// libfuzzer_sys::fuzz_mutator!(|data: &mut [u8], size: usize, max_size: usize, seed: u32| {
411///     let mut rng = StdRng::seed_from_u64(seed as u64);
412///
413/// #   let first_mutation = |_, _, _, _| todo!();
414/// #   let second_mutation = |_, _, _, _| todo!();
415/// #   let third_mutation = |_, _, _, _| todo!();
416/// #   let fourth_mutation = |_, _, _, _| todo!();
417///     // Choose which of our four supported kinds of mutations we want to make.
418///     match rng.gen_range(0..4) {
419///         0 => first_mutation(rng, data, size, max_size),
420///         1 => second_mutation(rng, data, size, max_size),
421///         2 => third_mutation(rng, data, size, max_size),
422///         3 => fourth_mutation(rng, data, size, max_size),
423///         _ => unreachable!()
424///     }
425/// });
426/// ```
427///
428/// ## Example: Compression
429///
430/// Consider a simple fuzz target that takes compressed data as input,
431/// decompresses it, and then asserts that the decompressed data doesn't begin
432/// with "boom". It is difficult for `libFuzzer` (or any other fuzzer) to crash
433/// this fuzz target because nearly all mutations it makes will invalidate the
434/// compression format. Therefore, we use a custom mutator that decompresses the
435/// raw input, mutates the decompressed data, and then recompresses it. This
436/// allows `libFuzzer` to quickly discover crashing inputs.
437///
438/// ```no_run
439/// #![no_main]
440///
441/// use flate2::{read::GzDecoder, write::GzEncoder, Compression};
442/// use libfuzzer_sys::{fuzz_mutator, fuzz_target};
443/// use std::io::{Read, Write};
444///
445/// fuzz_target!(|data: &[u8]| {
446///     // Decompress the input data and crash if it starts with "boom".
447///     if let Some(data) = decompress(data) {
448///         if data.starts_with(b"boom") {
449///             panic!();
450///         }
451///     }
452/// });
453///
454/// fuzz_mutator!(
455///     |data: &mut [u8], size: usize, max_size: usize, _seed: u32| {
456///         // Decompress the input data. If that fails, use a dummy value.
457///         let mut decompressed = decompress(&data[..size]).unwrap_or_else(|| b"hi".to_vec());
458///
459///         // Mutate the decompressed data with `libFuzzer`'s default mutator. Make
460///         // the `decompressed` vec's extra capacity available for insertion
461///         // mutations via `resize`.
462///         let len = decompressed.len();
463///         let cap = decompressed.capacity();
464///         decompressed.resize(cap, 0);
465///         let new_decompressed_size = libfuzzer_sys::fuzzer_mutate(&mut decompressed, len, cap);
466///
467///         // Recompress the mutated data.
468///         let compressed = compress(&decompressed[..new_decompressed_size]);
469///
470///         // Copy the recompressed mutated data into `data` and return the new size.
471///         let new_size = std::cmp::min(max_size, compressed.len());
472///         data[..new_size].copy_from_slice(&compressed[..new_size]);
473///         new_size
474///     }
475/// );
476///
477/// fn decompress(compressed_data: &[u8]) -> Option<Vec<u8>> {
478///     let mut decoder = GzDecoder::new(compressed_data);
479///     let mut decompressed = Vec::new();
480///     if decoder.read_to_end(&mut decompressed).is_ok() {
481///         Some(decompressed)
482///     } else {
483///         None
484///     }
485/// }
486///
487/// fn compress(data: &[u8]) -> Vec<u8> {
488///     let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
489///     encoder
490///         .write_all(data)
491///         .expect("writing into a vec is infallible");
492///     encoder.finish().expect("writing into a vec is infallible")
493/// }
494/// ```
495///
496/// This example is inspired by [a similar example from the official `libFuzzer`
497/// docs](https://github.com/google/fuzzing/blob/master/docs/structure-aware-fuzzing.md#example-compression).
498///
499/// ## More Example Ideas
500///
501/// * A PNG custom mutator that decodes a PNG, mutates the image, and then
502/// re-encodes the mutated image as a new PNG.
503///
504/// * A [`serde`](https://serde.rs/) custom mutator that deserializes your
505///   structure, mutates it, and then reserializes it.
506///
507/// * A Wasm binary custom mutator that inserts, replaces, and removes a
508///   bytecode instruction in a function's body.
509///
510/// * An HTTP request custom mutator that inserts, replaces, and removes a
511///   header from an HTTP request.
512#[macro_export]
513macro_rules! fuzz_mutator {
514    (
515        |
516        $data:ident : &mut [u8] ,
517        $size:ident : usize ,
518        $max_size:ident : usize ,
519        $seed:ident : u32 $(,)*
520        |
521        $body:block
522    ) => {
523        /// Auto-generated function. Do not use; only for LibFuzzer's
524        /// consumption.
525        #[export_name = "LLVMFuzzerCustomMutator"]
526        #[doc(hidden)]
527        pub unsafe fn rust_fuzzer_custom_mutator(
528            $data: *mut u8,
529            $size: usize,
530            $max_size: usize,
531            $seed: std::os::raw::c_uint,
532        ) -> usize {
533            // Depending on if we are growing or shrinking the test case, `size`
534            // might be larger or smaller than `max_size`. The `data`'s capacity
535            // is the maximum of the two.
536            let len = std::cmp::max($max_size, $size);
537            let $data: &mut [u8] = std::slice::from_raw_parts_mut($data, len);
538
539            // `unsigned int` is generally a `u32`, but not on all targets. Do
540            // an infallible (and potentially lossy, but that's okay because it
541            // preserves determinism) conversion.
542            let $seed = $seed as u32;
543
544            // Define and invoke a new, safe function so that the body doesn't
545            // inherit `unsafe`.
546            fn custom_mutator(
547                $data: &mut [u8],
548                $size: usize,
549                $max_size: usize,
550                $seed: u32,
551            ) -> usize {
552                $body
553            }
554            let new_size = custom_mutator($data, $size, $max_size, $seed);
555
556            // Truncate the new size if it is larger than the max.
557            std::cmp::min(new_size, $max_size)
558        }
559    };
560}
561
562/// The default `libFuzzer` mutator.
563///
564/// You generally don't have to use this at all unless you're defining a
565/// custom mutator with [the `fuzz_mutator!` macro][crate::fuzz_mutator].
566///
567/// Mutates `data[..size]` in place such that the mutated data is no larger than
568/// `max_size` and returns the new size of the mutated data.
569///
570/// To only allow shrinking mutations, make `max_size < size`.
571///
572/// To additionally allow mutations that grow the size of the data, make
573/// `max_size > size`.
574///
575/// Both `size` and `max_size` must be less than or equal to `data.len()`.
576///
577/// # Example
578///
579/// ```no_run
580/// // Create some data in a buffer.
581/// let mut data = vec![0; 128];
582/// data[..b"hello".len()].copy_from_slice(b"hello");
583///
584/// // Ask `libFuzzer` to mutate the data. By setting `max_size` to our buffer's
585/// // full length, we are allowing `libFuzzer` to perform mutations that grow
586/// // the size of the data, such as insertions.
587/// let size = b"hello".len();
588/// let max_size = data.len();
589/// let new_size = libfuzzer_sys::fuzzer_mutate(&mut data, size, max_size);
590///
591/// // Get the mutated data out of the buffer.
592/// let mutated_data = &data[..new_size];
593/// ```
594pub fn fuzzer_mutate(data: &mut [u8], size: usize, max_size: usize) -> usize {
595    assert!(size <= data.len());
596    assert!(max_size <= data.len());
597    let new_size = unsafe { LLVMFuzzerMutate(data.as_mut_ptr(), size, max_size) };
598    assert!(new_size <= data.len());
599    new_size
600}
601
602/// Define a custom cross-over function to combine test cases.
603///
604/// This is optional, and libFuzzer will use its own, default cross-over strategy
605/// if this is not provided. (As of the time of writing, this default strategy
606/// takes alternating byte sequences from the two test cases, to construct the
607/// new one) (see `FuzzerCrossOver.cpp`)
608///
609/// This could potentially be useful if your input is, for instance, a
610/// sequence of fixed sized, multi-byte values and the crossover could then
611/// merge discrete values rather than joining parts of a value.
612///
613/// ## Implementation Contract
614///
615/// The original, read-only inputs are given in the full slices of `data1`, and
616/// `data2` (as opposed to the, potentially, partial slice of `data` in
617/// [the `fuzz_mutator!` macro][crate::fuzz_mutator]).
618///
619/// You must place the new input merged from the two existing inputs' data
620/// into `out` and return the size of the relevant data written to that slice.
621///
622/// The deterministic requirements from [the `fuzz_mutator!` macro][crate::fuzz_mutator]
623/// apply as well to the `seed` parameter
624///
625/// ## Example: Floating-Point Sum NaN
626///
627/// ```no_run
628/// #![no_main]
629///
630/// use libfuzzer_sys::{fuzz_crossover, fuzz_mutator, fuzz_target, fuzzer_mutate};
631/// use rand::{rngs::StdRng, Rng, SeedableRng};
632/// use std::mem::size_of;
633///
634/// fuzz_target!(|data: &[u8]| {
635///     let (_, floats, _) = unsafe { data.align_to::<f64>() };
636///
637///     let res = floats
638///         .iter()
639///         .fold(0.0, |a, b| if b.is_nan() { a } else { a + b });
640///
641///     assert!(
642///         !res.is_nan(),
643///         "The sum of the following floats resulted in a NaN: {floats:?}"
644///     );
645/// });
646///
647/// // Inject some ...potentially problematic values to make the example close
648/// // more quickly.
649/// fuzz_mutator!(|data: &mut [u8], size: usize, max_size: usize, seed: u32| {
650///     let mut gen = StdRng::seed_from_u64(seed.into());
651///
652///     let (_, floats, _) = unsafe { data[..size].align_to_mut::<f64>() };
653///
654///     let x = gen.gen_range(0..=1000);
655///     if x == 0 && !floats.is_empty() {
656///         floats[0] = f64::INFINITY;
657///     } else if x == 1000 && floats.len() > 1 {
658///         floats[1] = f64::NEG_INFINITY;
659///     } else {
660///         return fuzzer_mutate(data, size, max_size);
661///     }
662///
663///     size
664/// });
665///
666/// fuzz_crossover!(|data1: &[u8], data2: &[u8], out: &mut [u8], _seed: u32| {
667///     // Decode each source to see how many floats we can pull with proper
668///     // alignment, and destination as to how many will fit with proper alignment
669///     //
670///     // Keep track of the unaligned prefix to `out`, as we will need to remember
671///     // that those bytes will remain prepended to the actual floats that we
672///     // write into the out buffer.
673///     let (out_pref, out_floats, _) = unsafe { out.align_to_mut::<f64>() };
674///     let (_, d1_floats, _) = unsafe { data1.align_to::<f64>() };
675///     let (_, d2_floats, _) = unsafe { data2.align_to::<f64>() };
676///
677///     // Put into the destination, floats first from data1 then from data2, ...if
678///     // possible given the size of `out`
679///     let mut i: usize = 0;
680///     for float in d1_floats.iter().chain(d2_floats).take(out_floats.len()) {
681///         out_floats[i] = *float;
682///         i += 1;
683///     }
684///
685///     // Now that we have written the true floats, report back to the fuzzing
686///     // engine that we left the unaligned `out` prefix bytes at the beginning of
687///     // `out` and also then the floats that we wrote into the aligned float
688///     // section.
689///     out_pref.len() * size_of::<u8>() + i * size_of::<f64>()
690/// });
691/// ```
692///
693/// This example is a minimized version of [Erik Rigtorp's floating point
694/// summation fuzzing example][1]. A more detailed version of this experiment
695/// can be found in the `example_crossover` directory.
696///
697/// [1]: https://rigtorp.se/fuzzing-floating-point-code/
698#[macro_export]
699macro_rules! fuzz_crossover {
700    (
701        |
702        $data1:ident : &[u8] ,
703        $data2:ident : &[u8] ,
704        $out:ident : &mut [u8] ,
705        $seed:ident : u32 $(,)*
706        |
707        $body:block
708    ) => {
709        /// Auto-generated function. Do not use; only for LibFuzzer's
710        /// consumption.
711        #[export_name = "LLVMFuzzerCustomCrossOver"]
712        #[doc(hidden)]
713        pub unsafe fn rust_fuzzer_custom_crossover(
714            $data1: *const u8,
715            size1: usize,
716            $data2: *const u8,
717            size2: usize,
718            $out: *mut u8,
719            max_out_size: usize,
720            $seed: std::os::raw::c_uint,
721        ) -> usize {
722            let $data1: &[u8] = std::slice::from_raw_parts($data1, size1);
723            let $data2: &[u8] = std::slice::from_raw_parts($data2, size2);
724            let $out: &mut [u8] = std::slice::from_raw_parts_mut($out, max_out_size);
725
726            // `unsigned int` is generally a `u32`, but not on all targets. Do
727            // an infallible (and potentially lossy, but that's okay because it
728            // preserves determinism) conversion.
729            let $seed = $seed as u32;
730
731            // Define and invoke a new, safe function so that the body doesn't
732            // inherit `unsafe`.
733            fn custom_crossover(
734                $data1: &[u8],
735                $data2: &[u8],
736                $out: &mut [u8],
737                $seed: u32,
738            ) -> usize {
739                $body
740            }
741
742            custom_crossover($data1, $data2, $out, $seed)
743        }
744    };
745}