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