json_fuzzer.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. //
  5. // JsonCpp fuzzing wrapper to help with automated fuzz testing.
  6. #include <stdint.h>
  7. #include <array>
  8. #include <climits>
  9. #include <cstdio>
  10. #include <iostream>
  11. #include <memory>
  12. #include "third_party/jsoncpp/source/include/json/json.h"
  13. namespace {
  14. // JsonCpp has a few different parsing options. The code below makes sure that
  15. // the most intersting variants are tested.
  16. enum { kBuilderConfigDefault = 0, kBuilderConfigStrict, kNumBuilderConfig };
  17. } // namespace
  18. static const std::array<Json::CharReaderBuilder, kNumBuilderConfig>&
  19. Initialize() {
  20. static std::array<Json::CharReaderBuilder, kNumBuilderConfig> builders{};
  21. Json::CharReaderBuilder::strictMode(
  22. &builders[kBuilderConfigStrict].settings_);
  23. return builders;
  24. }
  25. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  26. const auto& reader_builders = Initialize();
  27. for (const auto& reader_builder : reader_builders) {
  28. // Parse Json.
  29. auto reader =
  30. std::unique_ptr<Json::CharReader>(reader_builder.newCharReader());
  31. Json::Value root;
  32. bool res = reader->parse(reinterpret_cast<const char*>(data),
  33. reinterpret_cast<const char*>(data + size), &root,
  34. nullptr /* errs */);
  35. if (!res) {
  36. continue;
  37. }
  38. // Write and re-read json.
  39. const Json::StreamWriterBuilder writer_builder;
  40. auto writer =
  41. std::unique_ptr<Json::StreamWriter>(writer_builder.newStreamWriter());
  42. std::stringstream out_stream;
  43. writer->write(root, &out_stream);
  44. std::string output_json = out_stream.str();
  45. Json::Value root_again;
  46. res = reader->parse(output_json.data(),
  47. output_json.data() + output_json.length(), &root_again,
  48. nullptr /* errs */);
  49. if (!res) {
  50. continue;
  51. }
  52. // Run equality test.
  53. // Note: This actually causes the Json::Value tree to be traversed and all
  54. // the values to be dereferenced (until two of them are found not equal),
  55. // which is great for detecting memory corruption bugs when compiled with
  56. // AddressSanitizer. The result of the comparison is ignored, as it is
  57. // expected that both the original and the re-read version will differ from
  58. // time to time (e.g. due to floating point accuracy loss).
  59. (void)(root == root_again);
  60. }
  61. return 0;
  62. }