• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
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.
8 
9 #include <stddef.h>
10 #include <stdint.h>
11 
12 #include <string>
13 
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"
19 
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.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)23 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
24   if (size < 2)
25     return 0;
26 
27   int error_code, error_line, error_column;
28   std::string error_message;
29 
30   // Create a copy of input buffer, as otherwise we don't catch
31   // overflow that touches the last byte (which is used in options).
32   std::unique_ptr<char[]> input(new char[size - 1]);
33   memcpy(input.get(), data, size - 1);
34 
35   base::StringPiece input_string(input.get(), size - 1);
36 
37   const int options = data[size - 1];
38   auto parsed_value = base::JSONReader::ReadAndReturnError(
39       input_string, options, &error_code, &error_message, &error_line,
40       &error_column);
41   if (!parsed_value)
42     return 0;
43 
44   std::string parsed_output;
45   bool b = base::JSONWriter::Write(*parsed_value, &parsed_output);
46   LOG_ASSERT(b);
47 
48   auto double_parsed_value = base::JSONReader::ReadAndReturnError(
49       parsed_output, options, &error_code, &error_message, &error_line,
50       &error_column);
51   LOG_ASSERT(double_parsed_value);
52   std::string double_parsed_output;
53   bool b2 =
54       base::JSONWriter::Write(*double_parsed_value, &double_parsed_output);
55   LOG_ASSERT(b2);
56 
57   LOG_ASSERT(parsed_output == double_parsed_output)
58       << "Parser/Writer mismatch."
59       << "\nInput=" << base::GetQuotedJSONString(parsed_output)
60       << "\nOutput=" << base::GetQuotedJSONString(double_parsed_output);
61 
62   return 0;
63 }
64