xref: /aosp_15_r20/external/cronet/base/json/json_reader_fuzzer.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/json/json_reader.h"
6 
7 #include <optional>
8 #include <string_view>
9 
10 #include "base/json/json_writer.h"
11 #include "base/values.h"
12 
13 namespace base {
14 
15 // Entry point for LibFuzzer.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)16 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
17   if (size < 2)
18     return 0;
19 
20   // Create a copy of input buffer, as otherwise we don't catch
21   // overflow that touches the last byte (which is used in options).
22   std::unique_ptr<char[]> input(new char[size - 1]);
23   memcpy(input.get(), data, size - 1);
24 
25   std::string_view input_string(input.get(), size - 1);
26 
27   const int options = data[size - 1];
28 
29   auto json_val =
30       JSONReader::ReadAndReturnValueWithError(input_string, options);
31   if (json_val.has_value()) {
32     // Check that the value can be serialized and deserialized back to an
33     // equivalent |Value|.
34     const Value& value = *json_val;
35     std::string serialized;
36     CHECK(JSONWriter::Write(value, &serialized));
37 
38     std::optional<Value> deserialized =
39         JSONReader::Read(std::string_view(serialized));
40     CHECK(deserialized);
41     CHECK_EQ(value, deserialized.value());
42   }
43 
44   return 0;
45 }
46 
47 }  // namespace base
48