fuzzer-parse_cbor.cpp 1.7 KB

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