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