summaryrefslogtreecommitdiffstats
path: root/tools/fuzzing/rust/src/lib.rs
blob: 1df45153c10b61d1a4c06cf04dfc2ad4af4e54f3 (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
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#[macro_use]
extern crate lazy_static;
extern crate libc;
extern crate lmdb;
extern crate rkv;
extern crate tempfile;

use rkv::backend::{
    BackendEnvironmentBuilder, SafeMode, SafeModeDatabase, SafeModeEnvironment,
    SafeModeRoTransaction, SafeModeRwTransaction,
};
use std::fs;
use std::fs::File;
use std::io::Write;
use std::iter;
use std::path::Path;
use std::sync::Arc;
use std::thread;
use tempfile::Builder;

type Rkv = rkv::Rkv<SafeModeEnvironment>;
type SingleStore = rkv::SingleStore<SafeModeDatabase>;

fn eat_lmdb_err<T>(value: Result<T, rkv::StoreError>) -> Result<Option<T>, rkv::StoreError> {
    match value {
        Ok(value) => Ok(Some(value)),
        Err(rkv::StoreError::LmdbError(_)) => Ok(None),
        Err(err) => {
            println!("Not a crash, but an error outside LMDB: {}", err);
            println!("A refined fuzzing test, or changes to RKV, might be required.");
            Err(err)
        }
    }
}

fn panic_with_err(err: rkv::StoreError) {
    println!("Got error: {}", err);
    Result::Err(err).unwrap()
}

#[no_mangle]
pub extern "C" fn fuzz_rkv_db_file(raw_data: *const u8, size: libc::size_t) -> libc::c_int {
    let data = unsafe { std::slice::from_raw_parts(raw_data as *const u8, size as usize) };

    // First 8192 bytes are for the lock file.
    if data.len() < 8192 {
        return 0;
    }
    let (lock, db) = data.split_at(8192);
    let mut lock_file = File::create("data.lock").unwrap();
    lock_file.write_all(lock).unwrap();
    let mut db_file = File::create("data.mdb").unwrap();
    db_file.write_all(db).unwrap();

    let env = Rkv::with_capacity::<SafeMode>(Path::new("."), 2).unwrap();
    let store = env
        .open_single("test", rkv::StoreOptions::create())
        .unwrap();

    let reader = env.read().unwrap();
    eat_lmdb_err(store.get(&reader, &[0])).unwrap();

    0
}

#[no_mangle]
pub extern "C" fn fuzz_rkv_db_name(raw_data: *const u8, size: libc::size_t) -> libc::c_int {
    let data = unsafe { std::slice::from_raw_parts(raw_data as *const u8, size as usize) };

    let root = Builder::new().prefix("fuzz_rkv_db_name").tempdir().unwrap();
    fs::create_dir_all(root.path()).unwrap();

    let env = Rkv::new::<SafeMode>(root.path()).unwrap();
    let name = String::from_utf8_lossy(data);
    println!("Checking string: '{:?}'", name);
    // Some strings are invalid database names, and are handled as store errors.
    // Ignore those errors, but not others.
    let store = eat_lmdb_err(env.open_single(name.as_ref(), rkv::StoreOptions::create())).unwrap();

    if let Some(store) = store {
        let reader = env.read().unwrap();
        eat_lmdb_err(store.get(&reader, &[0])).unwrap();
    };

    0
}

#[no_mangle]
pub extern "C" fn fuzz_rkv_key_write(raw_data: *const u8, size: libc::size_t) -> libc::c_int {
    let data = unsafe { std::slice::from_raw_parts(raw_data as *const u8, size as usize) };

    let root = Builder::new()
        .prefix("fuzz_rkv_key_write")
        .tempdir()
        .unwrap();
    fs::create_dir_all(root.path()).unwrap();

    let env = Rkv::new::<SafeMode>(root.path()).unwrap();
    let store = env
        .open_single("test", rkv::StoreOptions::create())
        .unwrap();

    let mut writer = env.write().unwrap();
    // Some data are invalid values, and are handled as store errors.
    // Ignore those errors, but not others.
    eat_lmdb_err(store.put(&mut writer, data, &rkv::Value::Str("val"))).unwrap();

    0
}

#[no_mangle]
pub extern "C" fn fuzz_rkv_val_write(raw_data: *const u8, size: libc::size_t) -> libc::c_int {
    let data = unsafe { std::slice::from_raw_parts(raw_data as *const u8, size as usize) };

    let root = Builder::new()
        .prefix("fuzz_rkv_val_write")
        .tempdir()
        .unwrap();
    fs::create_dir_all(root.path()).unwrap();

    let env = Rkv::new::<SafeMode>(root.path()).unwrap();
    let store = env
        .open_single("test", rkv::StoreOptions::create())
        .unwrap();

    let mut writer = env.write().unwrap();
    let string = String::from_utf8_lossy(data);
    let value = rkv::Value::Str(&string);
    store.put(&mut writer, "key", &value).unwrap();

    0
}

lazy_static! {
    static ref STATIC_DATA: Vec<String> = {
        let sizes = vec![4, 16, 128, 512, 1024];
        let mut data = Vec::new();

        for (i, s) in sizes.into_iter().enumerate() {
            let bytes = iter::repeat('a' as u8 + i as u8).take(s).collect();
            data.push(String::from_utf8(bytes).unwrap());
        }

        data
    };
}

#[no_mangle]
pub extern "C" fn fuzz_rkv_calls(raw_data: *const u8, size: libc::size_t) -> libc::c_int {
    let data = unsafe { std::slice::from_raw_parts(raw_data as *const u8, size as usize) };
    let mut fuzz = data.iter().copied();

    fn maybe_do<I: Iterator<Item = u8>>(fuzz: &mut I, f: impl FnOnce(&mut I) -> ()) -> Option<()> {
        match fuzz.next().map(|byte| byte % 2) {
            Some(0) => Some(f(fuzz)),
            _ => None,
        }
    }

    fn maybe_abort<I: Iterator<Item = u8>>(
        fuzz: &mut I,
        read: rkv::Reader<SafeModeRoTransaction>,
    ) -> Result<(), rkv::StoreError> {
        match fuzz.next().map(|byte| byte % 2) {
            Some(0) => Ok(read.abort()),
            _ => Ok(()),
        }
    };

    fn maybe_commit<I: Iterator<Item = u8>>(
        fuzz: &mut I,
        write: rkv::Writer<SafeModeRwTransaction>,
    ) -> Result<(), rkv::StoreError> {
        match fuzz.next().map(|byte| byte % 3) {
            Some(0) => write.commit(),
            Some(1) => Ok(write.abort()),
            _ => Ok(()),
        }
    };

    fn get_static_data<'a, I: Iterator<Item = u8>>(fuzz: &mut I) -> Option<&'a String> {
        fuzz.next().map(|byte| {
            let data = &*STATIC_DATA;
            let n = byte as usize;
            data.get(n % data.len()).unwrap()
        })
    };

    fn get_fuzz_data<I: Iterator<Item = u8> + Clone>(
        fuzz: &mut I,
        max_len: usize,
    ) -> Option<Vec<u8>> {
        fuzz.next().map(|byte| {
            let n = byte as usize;
            fuzz.clone().take((n * n) % max_len).collect()
        })
    };

    fn get_any_data<I: Iterator<Item = u8> + Clone>(
        fuzz: &mut I,
        max_len: usize,
    ) -> Option<Vec<u8>> {
        match fuzz.next().map(|byte| byte % 2) {
            Some(0) => get_static_data(fuzz).map(|v| v.clone().into_bytes()),
            Some(1) => get_fuzz_data(fuzz, max_len),
            _ => None,
        }
    };

    fn store_put<I: Iterator<Item = u8> + Clone>(fuzz: &mut I, env: &Rkv, store: &SingleStore) {
        let key = match get_any_data(fuzz, 1024) {
            Some(key) => key,
            None => return,
        };
        let value = match get_any_data(fuzz, std::usize::MAX) {
            Some(value) => value,
            None => return,
        };

        let mut writer = env.write().unwrap();
        let mut full = false;

        match store.put(&mut writer, key, &rkv::Value::Blob(&value)) {
            Ok(_) => {}
            Err(rkv::StoreError::LmdbError(lmdb::Error::BadValSize)) => {}
            Err(rkv::StoreError::LmdbError(lmdb::Error::MapFull)) => full = true,
            Err(err) => panic_with_err(err),
        };

        if full {
            writer.abort();
            store_resize(fuzz, env);
        } else {
            maybe_commit(fuzz, writer).unwrap();
        }
    }

    fn store_get<I: Iterator<Item = u8> + Clone>(fuzz: &mut I, env: &Rkv, store: &SingleStore) {
        let key = match get_any_data(fuzz, 1024) {
            Some(key) => key,
            None => return,
        };

        let mut reader = match env.read() {
            Ok(reader) => reader,
            Err(rkv::StoreError::LmdbError(lmdb::Error::ReadersFull)) => return,
            Err(err) => return panic_with_err(err),
        };

        match store.get(&mut reader, key) {
            Ok(_) => {}
            Err(rkv::StoreError::LmdbError(lmdb::Error::BadValSize)) => {}
            Err(err) => panic_with_err(err),
        };

        maybe_abort(fuzz, reader).unwrap();
    }

    fn store_delete<I: Iterator<Item = u8> + Clone>(fuzz: &mut I, env: &Rkv, store: &SingleStore) {
        let key = match get_any_data(fuzz, 1024) {
            Some(key) => key,
            None => return,
        };

        let mut writer = env.write().unwrap();

        match store.delete(&mut writer, key) {
            Ok(_) => {}
            Err(rkv::StoreError::LmdbError(lmdb::Error::BadValSize)) => {}
            Err(rkv::StoreError::LmdbError(lmdb::Error::NotFound)) => {}
            Err(err) => panic_with_err(err),
        };

        maybe_commit(fuzz, writer).unwrap();
    }

    fn store_resize<I: Iterator<Item = u8>>(fuzz: &mut I, env: &Rkv) {
        let n = fuzz.next().unwrap_or(1) as usize;
        env.set_map_size(1_048_576 * (n % 100)).unwrap() // 1,048,576 bytes, i.e. 1MiB.
    };

    let root = Builder::new().prefix("fuzz_rkv_calls").tempdir().unwrap();
    fs::create_dir_all(root.path()).unwrap();

    let mut builder: SafeMode = Rkv::environment_builder();
    builder.set_max_dbs(1); // need at least one db

    maybe_do(&mut fuzz, |fuzz| {
        let n = fuzz.next().unwrap_or(126) as u32; // default
        builder.set_max_readers(1 + n);
    });
    maybe_do(&mut fuzz, |fuzz| {
        let n = fuzz.next().unwrap_or(0) as u32;
        builder.set_max_dbs(1 + n);
    });
    maybe_do(&mut fuzz, |fuzz| {
        let n = fuzz.next().unwrap_or(1) as usize;
        builder.set_map_size(1_048_576 * (n % 100)); // 1,048,576 bytes, i.e. 1MiB.
    });

    let env = Rkv::from_builder(root.path(), builder).unwrap();
    let store = env
        .open_single("test", rkv::StoreOptions::create())
        .unwrap();

    let shared_env = Arc::new(env);
    let shared_store = Arc::new(store);

    let use_threads = fuzz.next().map(|byte| byte % 10 == 0).unwrap_or(false);
    let max_threads = if use_threads { 16 } else { 1 };
    let num_threads = fuzz.next().unwrap_or(0) as usize % max_threads + 1;
    let chunk_size = fuzz.len() / num_threads;

    let threads = (0..num_threads).map(|_| {
        let env = shared_env.clone();
        let store = shared_store.clone();

        let chunk: Vec<_> = fuzz.by_ref().take(chunk_size).collect();
        let mut fuzz = chunk.into_iter();

        thread::spawn(move || loop {
            match fuzz.next().map(|byte| byte % 4) {
                Some(0) => store_put(&mut fuzz, &env, &store),
                Some(1) => store_get(&mut fuzz, &env, &store),
                Some(2) => store_delete(&mut fuzz, &env, &store),
                Some(3) => store_resize(&mut fuzz, &env),
                _ => break,
            }
        })
    });

    for handle in threads {
        handle.join().unwrap()
    }

    0
}