fuzzer-parse_json.cpp 1.7 KB

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