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