• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #![allow(missing_docs)]
16 #![no_main]
17 
18 use hashbrown::HashMap;
19 use libfuzzer_sys::arbitrary::Arbitrary;
20 use libfuzzer_sys::fuzz_target;
21 
22 const MAX_RESERVE: usize = 1024;
23 
24 #[derive(Arbitrary, Debug, Eq, Hash, PartialEq)]
25 enum Data {
26     A,
27     B,
28     Int { val: u8 },
29 }
30 
31 #[derive(Arbitrary, Debug)]
32 enum HashMapMethods {
33     Insert { key: Data, value: Data },
34     Remove { key: Data },
35     ContainsKey { key: Data },
36     Get { key: Data },
37     EntryOrInsert { key: Data, value: Data },
38     Iter,
39     Drain,
40     Clear,
41     Reserve { additional: usize },
42     ShrinkToFit,
43     ShrinkTo { min_capacity: usize },
44 }
45 
46 fuzz_target!(|commands: Vec<HashMapMethods>| {
47     let mut map = HashMap::new();
48     for command in commands {
49         match command {
50             HashMapMethods::Insert { key, value } => {
51                 map.insert(key, value);
52             }
53             HashMapMethods::Remove { key } => {
54                 map.remove(&key);
55             }
56             HashMapMethods::ContainsKey { key } => {
57                 map.contains_key(&key);
58             }
59             HashMapMethods::Get { key } => {
60                 map.get(&key);
61             }
62             HashMapMethods::EntryOrInsert { key, value } => {
63                 map.entry(key).or_insert(value);
64             }
65             HashMapMethods::Iter => {
66                 std::hint::black_box(map.iter().count());
67             }
68             HashMapMethods::Drain => {
69                 std::hint::black_box(map.drain().count());
70             }
71             HashMapMethods::Clear => {
72                 map.clear();
73             }
74             HashMapMethods::Reserve { additional } => {
75                 // Avoid allocating too much memory and crashing the fuzzer.
76                 map.reserve(additional % MAX_RESERVE);
77             }
78             HashMapMethods::ShrinkToFit => {
79                 map.shrink_to_fit();
80             }
81             HashMapMethods::ShrinkTo { min_capacity } => {
82                 map.shrink_to(min_capacity % MAX_RESERVE);
83             }
84         }
85     }
86 });
87