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
#[cfg(fuzzing_libfuzzer)]
pub mod fuzzer {
    use std::{
        ffi::CString,
        os::raw::{c_char, c_int},
        panic::{self, catch_unwind, AssertUnwindSafe, RefUnwindSafe},
    };

    static mut TESTFN: &dyn Fn(&[u8]) = &uninit as &dyn Fn(&[u8]);

    fn uninit(_input: &[u8]) {
        panic!("uninitialized test");
    }

    extern "C" {
        // entrypoint for libfuzzer
        pub fn LLVMFuzzerStartTest(a: c_int, b: *const *const c_char) -> c_int;
    }

    #[no_mangle]
    pub unsafe extern "C" fn LLVMFuzzerTestOneInput(data: *const u8, size: usize) -> i32 {
        let exec = || {
            let data_slice = std::slice::from_raw_parts(data, size);
            TESTFN(data_slice);
        };

        if catch_unwind(AssertUnwindSafe(exec)).is_err() {
            1
        } else {
            0
        }
    }

    #[no_mangle]
    pub unsafe extern "C" fn LLVMFuzzerInitialize(
        _argc: *const isize,
        _argv: *const *const *const u8,
    ) -> isize {
        panic::set_hook(Box::new(|_| {
            std::process::abort();
        }));

        0
    }

    pub unsafe fn fuzz<F: Fn(&[u8])>(testfn: F)
    where
        F: RefUnwindSafe,
    {
        TESTFN = std::mem::transmute(&testfn as &dyn Fn(&[u8]));

        // create a vector of zero terminated strings
        let args = std::env::args()
            .map(|arg| CString::new(arg).unwrap())
            .collect::<Vec<_>>();

        // convert the strings to raw pointers
        let c_args = args
            .iter()
            .map(|arg| arg.as_ptr())
            .chain(Some(0 as *const _)) // add a null pointer to the end
            .collect::<Vec<_>>();

        LLVMFuzzerStartTest(args.len() as c_int, c_args.as_ptr());
    }
}

#[cfg(fuzzing_libfuzzer)]
pub use fuzzer::*;