| 1 | // __ _____ _____ _____ |
| 2 | // __| | __| | | | JSON for Modern C++ (supporting code) |
| 3 | // | | |__ | | | | | | version 3.12.0 |
| 4 | // |_____|_____|_____|_|___| https://github.com/nlohmann/json |
| 5 | // |
| 6 | // SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann <https://nlohmann.me> |
| 7 | // SPDX-License-Identifier: MIT |
| 8 | |
| 9 | /* |
| 10 | This file implements a parser test suitable for fuzz testing. Given a byte |
| 11 | array data, it performs the following steps: |
| 12 | |
| 13 | - j1 = from_cbor(data) |
| 14 | - vec = to_cbor(j1) |
| 15 | - j2 = from_cbor(vec) |
| 16 | - assert(j1 == j2) |
| 17 | |
| 18 | The provided function `LLVMFuzzerTestOneInput` can be used in different fuzzer |
| 19 | drivers. |
| 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 |
| 29 | extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) |
| 30 | { |
| 31 | try |
| 32 | { |
| 33 | // step 1: parse input |
| 34 | std::vector<uint8_t> const vec1(data, data + size); |
| 35 | json const j1 = json::from_cbor(vec1); |
| 36 | |
| 37 | try |
| 38 | { |
| 39 | // step 2: round trip |
| 40 | std::vector<uint8_t> const vec2 = json::to_cbor(j1); |
| 41 | |
| 42 | // parse serialization |
| 43 | json const j2 = json::from_cbor(vec2); |
| 44 | |
| 45 | // serializations must match |
| 46 | assert(json::to_cbor(j2) == vec2); |
| 47 | } |
| 48 | catch (const json::parse_error&) |
| 49 | { |
| 50 | // parsing a CBOR 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 can occur during parsing, too |
| 65 | } |
| 66 | |
| 67 | // return 0 - non-zero return values are reserved for future use |
| 68 | return 0; |
| 69 | } |