fuzzer-parse_bson.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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_bson(data)
  9. - vec = to_bson(j1)
  10. - j2 = from_bson(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_bson(vec1);
  28. if (j1.is_discarded())
  29. {
  30. return 0;
  31. }
  32. try
  33. {
  34. // step 2: round trip
  35. std::vector<uint8_t> vec2 = json::to_bson(j1);
  36. // parse serialization
  37. json j2 = json::from_bson(vec2);
  38. // serializations must match
  39. assert(json::to_bson(j2) == vec2);
  40. }
  41. catch (const json::parse_error&)
  42. {
  43. // parsing a BSON serialization must not fail
  44. assert(false);
  45. }
  46. }
  47. catch (const json::parse_error&)
  48. {
  49. // parse errors are ok, because input may be random bytes
  50. }
  51. catch (const json::type_error&)
  52. {
  53. // type errors can occur during parsing, too
  54. }
  55. catch (const json::out_of_range&)
  56. {
  57. // out of range errors can occur during parsing, too
  58. }
  59. // return 0 - non-zero return values are reserved for future use
  60. return 0;
  61. }