json_reader_fuzzer.cc 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright 2015 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. #include "base/json/json_reader.h"
  5. #include "base/json/json_writer.h"
  6. #include "base/values.h"
  7. #include "third_party/abseil-cpp/absl/types/optional.h"
  8. namespace base {
  9. // Entry point for LibFuzzer.
  10. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
  11. if (size < 2)
  12. return 0;
  13. // Create a copy of input buffer, as otherwise we don't catch
  14. // overflow that touches the last byte (which is used in options).
  15. std::unique_ptr<char[]> input(new char[size - 1]);
  16. memcpy(input.get(), data, size - 1);
  17. StringPiece input_string(input.get(), size - 1);
  18. const int options = data[size - 1];
  19. auto json_val =
  20. JSONReader::ReadAndReturnValueWithError(input_string, options);
  21. if (json_val.has_value()) {
  22. // Check that the value can be serialized and deserialized back to an
  23. // equivalent |Value|.
  24. const Value& value = *json_val;
  25. std::string serialized;
  26. CHECK(JSONWriter::Write(value, &serialized));
  27. absl::optional<Value> deserialized =
  28. JSONReader::Read(StringPiece(serialized));
  29. CHECK(deserialized);
  30. CHECK_EQ(value, deserialized.value());
  31. }
  32. return 0;
  33. }
  34. } // namespace base