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 = parse(data) 11 - s1 = serialize(j1) 12 - j2 = parse(s1) 13 - s2 = serialize(j2) 14 - assert(s1 == s2) 15 16 The provided function `LLVMFuzzerTestOneInput` can be used in different fuzzer 17 drivers. 18 19 Licensed under the MIT License <http://opensource.org/licenses/MIT>. 20 */ 21 22 #include <iostream> 23 #include <sstream> 24 #include <nlohmann/json.hpp> 25 26 using json = nlohmann::json; 27 28 // see http://llvm.org/docs/LibFuzzer.html LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)29extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) 30 { 31 try 32 { 33 // step 1: parse input 34 json j1 = json::parse(data, data + size); 35 36 try 37 { 38 // step 2: round trip 39 40 // first serialization 41 std::string s1 = j1.dump(); 42 43 // parse serialization 44 json j2 = json::parse(s1); 45 46 // second serialization 47 std::string s2 = j2.dump(); 48 49 // serializations must match 50 assert(s1 == s2); 51 } 52 catch (const json::parse_error&) 53 { 54 // parsing a JSON 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::out_of_range&) 63 { 64 // out of range errors may happen if provided sizes are excessive 65 } 66 67 // return 0 - non-zero return values are reserved for future use 68 return 0; 69 } 70