summaryrefslogtreecommitdiffstats
path: root/vendor/ciborium/tests/fuzz.rs
blob: 2b9d0ecd974042cf28ac865b44e121fff8299a08 (plain)
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
// SPDX-License-Identifier: Apache-2.0

use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::os::raw::c_int;
use std::os::unix::io::{FromRawFd, RawFd};

use ciborium::{de::from_reader, value::Value};
use rand::Rng;

const ITERATIONS: usize = 128 * 1024;

#[allow(non_camel_case_types)]
type pid_t = i32;

extern "C" {
    fn close(fd: RawFd) -> c_int;
    fn fork() -> pid_t;
    fn pipe(pipefd: &mut [RawFd; 2]) -> c_int;
    fn waitpid(pid: pid_t, wstatus: *mut c_int, options: c_int) -> pid_t;
}

#[test]
fn fuzz() {
    let mut fds: [RawFd; 2] = [0; 2];
    assert_eq!(unsafe { pipe(&mut fds) }, 0);

    let pid = unsafe { fork() };
    assert!(pid >= 0);

    match pid {
        0 => {
            let mut child = unsafe { File::from_raw_fd(fds[1]) };
            unsafe { close(fds[0]) };

            let mut rng = rand::thread_rng();
            let mut buffer = [0u8; 32];

            for _ in 0..ITERATIONS {
                let len = rng.gen_range(0..buffer.len());
                rng.fill(&mut buffer[..len]);

                writeln!(child, "{}", hex::encode(&buffer[..len])).unwrap();
                writeln!(child, "{:?}", from_reader::<Value, _>(&buffer[..len])).unwrap();
            }
        }

        pid => {
            let mut parent = unsafe { File::from_raw_fd(fds[0]) };
            unsafe { close(fds[1]) };

            let mut string = String::new();
            parent.read_to_string(&mut string).unwrap();
            eprint!("{}", string);

            let mut status = 0;
            assert_eq!(pid, unsafe { waitpid(pid, &mut status, 0) });

            eprintln!("exit status: {:?}", status);
            assert_eq!(0, status);
        }
    }
}