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_msgpack(data)
14- vec = to_msgpack(j1)
15- j2 = from_msgpack(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_msgpack(vec1);
36
37        try
38        {
39            // step 2: round trip
40            std::vector<uint8_t> vec2 = json::to_msgpack(j1);
41
42            // parse serialization
43            json j2 = json::from_msgpack(vec2);
44
45            // serializations must match
46            assert(json::to_msgpack(j2) == vec2);
47        }
48        catch (const json::parse_error&)
49        {
50            // parsing a MessagePack serialization must not fail
51            assert(false);
52        }
53    }
54    catch (const json::parse_error&)
55    {
56        // parse errors are ok, because input may be random bytes
57    }
58    catch (const json::type_error&)
59    {
60        // type errors can occur during parsing, too
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