json_correctness_fuzzer.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2016 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. // A fuzzer that checks correctness of json parser/writer.
  5. // The fuzzer input is passed through parsing twice,
  6. // so that presumably valid json is parsed/written again.
  7. #include <stddef.h>
  8. #include <stdint.h>
  9. #include <string>
  10. #include "base/json/json_reader.h"
  11. #include "base/json/json_writer.h"
  12. #include "base/json/string_escape.h"
  13. #include "base/logging.h"
  14. #include "base/values.h"
  15. // Entry point for libFuzzer.
  16. // We will use the last byte of data as parsing options.
  17. // The rest will be used as text input to the parser.
  18. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  19. if (size < 2)
  20. return 0;
  21. // Create a copy of input buffer, as otherwise we don't catch
  22. // overflow that touches the last byte (which is used in options).
  23. std::unique_ptr<char[]> input(new char[size - 1]);
  24. memcpy(input.get(), data, size - 1);
  25. base::StringPiece input_string(input.get(), size - 1);
  26. const int options = data[size - 1];
  27. auto result =
  28. base::JSONReader::ReadAndReturnValueWithError(input_string, options);
  29. if (!result.has_value())
  30. return 0;
  31. std::string parsed_output;
  32. bool b = base::JSONWriter::Write(*result, &parsed_output);
  33. LOG_ASSERT(b);
  34. auto double_result =
  35. base::JSONReader::ReadAndReturnValueWithError(parsed_output, options);
  36. LOG_ASSERT(double_result.has_value());
  37. std::string double_parsed_output;
  38. bool b2 = base::JSONWriter::Write(*double_result, &double_parsed_output);
  39. LOG_ASSERT(b2);
  40. LOG_ASSERT(parsed_output == double_parsed_output)
  41. << "Parser/Writer mismatch."
  42. << "\nInput=" << base::GetQuotedJSONString(parsed_output)
  43. << "\nOutput=" << base::GetQuotedJSONString(double_parsed_output);
  44. return 0;
  45. }