1 // Copyright 2020 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ////////////////////////////////////////////////////////////////////////////////
16 
17 #include "json.pb.h"
18 #include "json_proto_converter.h"
19 #include "libprotobuf-mutator/src/libfuzzer/libfuzzer_macro.h"
20 
21 #include <cstdint>
22 #include <json/config.h>
23 #include <json/json.h>
24 #include <memory>
25 #include <string>
26 #include <iostream>
27 #include <cstddef>
28 #include <stdint.h>
29 #include <cstring>
30 #include <iostream>
31 
32 namespace Json {
33 class Exception;
34 }
35 
FuzzJson(std::string data_str,int32_t hash_settings)36 void FuzzJson(std::string data_str, int32_t hash_settings) {
37   Json::CharReaderBuilder builder;
38 
39   builder.settings_["failIfExtra"] = hash_settings & (1 << 0);
40   builder.settings_["allowComments_"] = hash_settings & (1 << 1);
41   builder.settings_["strictRoot_"] = hash_settings & (1 << 2);
42   builder.settings_["allowDroppedNullPlaceholders_"] = hash_settings & (1 << 3);
43   builder.settings_["allowNumericKeys_"] = hash_settings & (1 << 4);
44   builder.settings_["allowSingleQuotes_"] = hash_settings & (1 << 5);
45   builder.settings_["failIfExtra_"] = hash_settings & (1 << 6);
46   builder.settings_["rejectDupKeys_"] = hash_settings & (1 << 7);
47   builder.settings_["allowSpecialFloats_"] = hash_settings & (1 << 8);
48   builder.settings_["collectComments"] = hash_settings & (1 << 9);
49   builder.settings_["allowTrailingCommas_"] = hash_settings & (1 << 10);
50 
51   std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
52 
53   const char* begin = data_str.c_str();
54   const char* end = begin + data_str.length();
55 
56   Json::Value root;
57   try {
58     reader->parse(begin, end, &root, nullptr);
59   } catch (Json::Exception const&) {
60   }
61 }
62 
DEFINE_PROTO_FUZZER(const json_proto::JsonParseAPI & json_proto)63 DEFINE_PROTO_FUZZER(const json_proto::JsonParseAPI &json_proto) {
64   json_proto::JsonProtoConverter converter;
65   std::string data_str = converter.Convert(json_proto.object_value());
66   int32_t hash_settings = json_proto.settings();
67   FuzzJson(data_str, hash_settings);
68 }
69