• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2     __ _____ _____ _____
3  __|  |   __|     |   | |  JSON for Modern C++ (fuzz test support)
4 |  |  |__   |  |  | | | |  version 3.9.1
5 |_____|_____|_____|_|___|  https://github.com/nlohmann/json
6 
7 This file implements a parser test suitable for fuzz testing. Given a byte
8 array data, it performs the following steps:
9 
10 - j1 = from_bson(data)
11 - vec = to_bson(j1)
12 - j2 = from_bson(vec)
13 - assert(j1 == j2)
14 
15 The provided function `LLVMFuzzerTestOneInput` can be used in different fuzzer
16 drivers.
17 
18 Licensed under the MIT License <http://opensource.org/licenses/MIT>.
19 */
20 
21 #include <iostream>
22 #include <sstream>
23 #include <nlohmann/json.hpp>
24 
25 using json = nlohmann::json;
26 
27 // see http://llvm.org/docs/LibFuzzer.html
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)28 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
29 {
30     try
31     {
32         // step 1: parse input
33         std::vector<uint8_t> vec1(data, data + size);
34         json j1 = json::from_bson(vec1);
35 
36         if (j1.is_discarded())
37         {
38             return 0;
39         }
40 
41         try
42         {
43             // step 2: round trip
44             std::vector<uint8_t> vec2 = json::to_bson(j1);
45 
46             // parse serialization
47             json j2 = json::from_bson(vec2);
48 
49             // serializations must match
50             assert(json::to_bson(j2) == vec2);
51         }
52         catch (const json::parse_error&)
53         {
54             // parsing a BSON serialization must not fail
55             assert(false);
56         }
57     }
58     catch (const json::parse_error&)
59     {
60         // parse errors are ok, because input may be random bytes
61     }
62     catch (const json::type_error&)
63     {
64         // type errors can occur during parsing, too
65     }
66     catch (const json::out_of_range&)
67     {
68         // out of range errors can occur during parsing, too
69     }
70 
71     // return 0 - non-zero return values are reserved for future use
72     return 0;
73 }
74