/src/flatbuffers/tests/fuzzer/flatbuffers_scalar_fuzzer.cc
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright 2014 Google Inc. All rights reserved. |
3 | | * |
4 | | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | | * you may not use this file except in compliance with the License. |
6 | | * You may obtain a copy of the License at |
7 | | * |
8 | | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | | * |
10 | | * Unless required by applicable law or agreed to in writing, software |
11 | | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | | * See the License for the specific language governing permissions and |
14 | | * limitations under the License. |
15 | | */ |
16 | | |
17 | | #include <assert.h> |
18 | | #include <stddef.h> |
19 | | #include <stdint.h> |
20 | | |
21 | | #include <algorithm> |
22 | | #include <clocale> |
23 | | #include <memory> |
24 | | #include <regex> |
25 | | #include <string> |
26 | | |
27 | | #include "flatbuffers/idl.h" |
28 | | #include "test_init.h" |
29 | | |
30 | | static constexpr size_t kMinInputLength = 1; |
31 | | static constexpr size_t kMaxInputLength = 3000; |
32 | | |
33 | | static constexpr uint8_t flags_scalar_type = 0x0F; // type of scalar value |
34 | | static constexpr uint8_t flags_quotes_kind = 0x10; // quote " or ' |
35 | | // reserved for future: json {named} or [unnamed] |
36 | | // static constexpr uint8_t flags_json_bracer = 0x20; |
37 | | |
38 | | // Find all 'subj' sub-strings and replace first character of sub-string. |
39 | | // BreakSequence("testest","tes", 'X') -> "XesXest". |
40 | | // BreakSequence("xxx","xx", 'Y') -> "YYx". |
41 | 51.9k | static void BreakSequence(std::string &s, const char *subj, char repl) { |
42 | 51.9k | size_t pos = 0; |
43 | 56.9k | while (pos = s.find(subj, pos), pos != std::string::npos) { |
44 | 4.97k | s.at(pos) = repl; |
45 | 4.97k | pos++; |
46 | 4.97k | } |
47 | 51.9k | } |
48 | | |
49 | | // Remove all leading and trailing symbols matched with pattern set. |
50 | | // StripString("xy{xy}y", "xy") -> "{xy}" |
51 | | static std::string StripString(const std::string &s, const char *pattern, |
52 | 8.90k | size_t *pos = nullptr) { |
53 | 8.90k | if (pos) *pos = 0; |
54 | | // leading |
55 | 8.90k | auto first = s.find_first_not_of(pattern); |
56 | 8.90k | if (std::string::npos == first) return ""; |
57 | 8.83k | if (pos) *pos = first; |
58 | | // trailing |
59 | 8.83k | auto last = s.find_last_not_of(pattern); |
60 | 8.83k | assert(last < s.length()); |
61 | 0 | assert(first <= last); |
62 | 0 | return s.substr(first, last - first + 1); |
63 | 8.90k | } |
64 | | |
65 | | class RegexMatcher { |
66 | | protected: |
67 | | virtual bool MatchNumber(const std::string &input) const = 0; |
68 | | |
69 | | public: |
70 | 4.72k | virtual ~RegexMatcher() = default; |
71 | | |
72 | | struct MatchResult { |
73 | | size_t pos{ 0 }; |
74 | | size_t len{ 0 }; |
75 | | bool res{ false }; |
76 | | bool quoted{ false }; |
77 | | }; |
78 | | |
79 | 4.72k | MatchResult Match(const std::string &input) const { |
80 | 4.72k | MatchResult r; |
81 | | // strip leading and trailing "spaces" accepted by flatbuffer |
82 | 4.72k | auto test = StripString(input, "\t\r\n ", &r.pos); |
83 | 4.72k | r.len = test.size(); |
84 | | // check quotes |
85 | 4.72k | if (test.size() >= 2) { |
86 | 4.09k | auto fch = test.front(); |
87 | 4.09k | auto lch = test.back(); |
88 | 4.09k | r.quoted = (fch == lch) && (fch == '\'' || fch == '\"'); |
89 | 4.09k | if (r.quoted) { |
90 | | // remove quotes for regex test |
91 | 63 | test = test.substr(1, test.size() - 2); |
92 | 63 | } |
93 | 4.09k | } |
94 | | // Fast check: |
95 | 4.72k | if (test.empty()) return r; |
96 | | // A string with a valid scalar shouldn't have non-ascii or non-printable |
97 | | // symbols. |
98 | 357k | for (auto c : test) { |
99 | 357k | if ((c < ' ') || (c > '~')) return r; |
100 | 357k | } |
101 | | // Check with regex |
102 | 4.19k | r.res = MatchNumber(test); |
103 | 4.19k | return r; |
104 | 4.65k | } |
105 | | |
106 | | bool MatchRegexList(const std::string &input, |
107 | 4.18k | const std::vector<std::regex> &re_list) const { |
108 | 4.18k | auto str = StripString(input, " "); |
109 | 4.18k | if (str.empty()) return false; |
110 | 8.75k | for (auto &re : re_list) { |
111 | 8.75k | std::smatch match; |
112 | 8.75k | if (std::regex_match(str, match, re)) return true; |
113 | 8.75k | } |
114 | 2.21k | return false; |
115 | 4.17k | } |
116 | | }; |
117 | | |
118 | | class IntegerRegex : public RegexMatcher { |
119 | | protected: |
120 | 1.73k | bool MatchNumber(const std::string &input) const override { |
121 | 1.73k | static const std::vector<std::regex> re_list = { |
122 | 1.73k | std::regex{ R"(^[-+]?[0-9]+$)", std::regex_constants::optimize }, |
123 | | |
124 | 1.73k | std::regex{ R"(^[-+]?0[xX][0-9a-fA-F]+$)", |
125 | 1.73k | std::regex_constants::optimize } |
126 | 1.73k | }; |
127 | 1.73k | return MatchRegexList(input, re_list); |
128 | 1.73k | } |
129 | | |
130 | | public: |
131 | 1.91k | IntegerRegex() = default; |
132 | | virtual ~IntegerRegex() = default; |
133 | | }; |
134 | | |
135 | | class UIntegerRegex : public RegexMatcher { |
136 | | protected: |
137 | 1.40k | bool MatchNumber(const std::string &input) const override { |
138 | 1.40k | static const std::vector<std::regex> re_list = { |
139 | 1.40k | std::regex{ R"(^[+]?[0-9]+$)", std::regex_constants::optimize }, |
140 | 1.40k | std::regex{ R"(^[+]?0[xX][0-9a-fA-F]+$)", |
141 | 1.40k | std::regex_constants::optimize }, |
142 | | // accept -0 number |
143 | 1.40k | std::regex{ R"(^[-](?:0[xX])?0+$)", std::regex_constants::optimize } |
144 | 1.40k | }; |
145 | 1.40k | return MatchRegexList(input, re_list); |
146 | 1.40k | } |
147 | | |
148 | | public: |
149 | 1.51k | UIntegerRegex() = default; |
150 | | virtual ~UIntegerRegex() = default; |
151 | | }; |
152 | | |
153 | | class BooleanRegex : public IntegerRegex { |
154 | | protected: |
155 | 273 | bool MatchNumber(const std::string &input) const override { |
156 | 273 | if (input == "true" || input == "false") return true; |
157 | 259 | return IntegerRegex::MatchNumber(input); |
158 | 273 | } |
159 | | |
160 | | public: |
161 | 312 | BooleanRegex() = default; |
162 | | virtual ~BooleanRegex() = default; |
163 | | }; |
164 | | |
165 | | class FloatRegex : public RegexMatcher { |
166 | | protected: |
167 | 1.04k | bool MatchNumber(const std::string &input) const override { |
168 | 1.04k | static const std::vector<std::regex> re_list = { |
169 | | // hex-float |
170 | 1.04k | std::regex{ |
171 | 1.04k | R"(^[-+]?0[xX](?:(?:[.][0-9a-fA-F]+)|(?:[0-9a-fA-F]+[.][0-9a-fA-F]*)|(?:[0-9a-fA-F]+))[pP][-+]?[0-9]+$)", |
172 | 1.04k | std::regex_constants::optimize }, |
173 | | // dec-float |
174 | 1.04k | std::regex{ |
175 | 1.04k | R"(^[-+]?(?:(?:[.][0-9]+)|(?:[0-9]+[.][0-9]*)|(?:[0-9]+))(?:[eE][-+]?[0-9]+)?$)", |
176 | 1.04k | std::regex_constants::optimize }, |
177 | | |
178 | 1.04k | std::regex{ R"(^[-+]?(?:nan|inf|infinity)$)", |
179 | 1.04k | std::regex_constants::optimize | std::regex_constants::icase } |
180 | 1.04k | }; |
181 | 1.04k | return MatchRegexList(input, re_list); |
182 | 1.04k | } |
183 | | |
184 | | public: |
185 | 1.29k | FloatRegex() = default; |
186 | | virtual ~FloatRegex() = default; |
187 | | }; |
188 | | |
189 | | class ScalarReferenceResult { |
190 | | private: |
191 | | ScalarReferenceResult(const char *_type, RegexMatcher::MatchResult _matched) |
192 | 4.72k | : type(_type), matched(_matched) {} |
193 | | |
194 | | public: |
195 | | // Decode scalar type and check if the input string satisfies the scalar type. |
196 | 4.72k | static ScalarReferenceResult Check(uint8_t code, const std::string &input) { |
197 | 4.72k | switch (code) { |
198 | 455 | case 0x0: return { "double", FloatRegex().Match(input) }; |
199 | 211 | case 0x1: return { "float", FloatRegex().Match(input) }; |
200 | 398 | case 0x2: return { "int8", IntegerRegex().Match(input) }; |
201 | 398 | case 0x3: return { "int16", IntegerRegex().Match(input) }; |
202 | 418 | case 0x4: return { "int32", IntegerRegex().Match(input) }; |
203 | 392 | case 0x5: return { "int64", IntegerRegex().Match(input) }; |
204 | 238 | case 0x6: return { "uint8", UIntegerRegex().Match(input) }; |
205 | 389 | case 0x7: return { "uint16", UIntegerRegex().Match(input) }; |
206 | 414 | case 0x8: return { "uint32", UIntegerRegex().Match(input) }; |
207 | 469 | case 0x9: return { "uint64", UIntegerRegex().Match(input) }; |
208 | 312 | case 0xA: return { "bool", BooleanRegex().Match(input) }; |
209 | 628 | default: return { "float", FloatRegex().Match(input) }; |
210 | 4.72k | }; |
211 | 0 | } |
212 | | |
213 | | const char *type; |
214 | | const RegexMatcher::MatchResult matched; |
215 | | }; |
216 | | |
217 | | bool Parse(flatbuffers::Parser &parser, const std::string &json, |
218 | 674k | std::string *_text) { |
219 | 674k | auto done = parser.ParseJson(json.c_str()); |
220 | 674k | if (done) { |
221 | 190k | TEST_NULL(GenText(parser, parser.builder_.GetBufferPointer(), _text)); |
222 | 484k | } else { |
223 | 484k | *_text = parser.error_; |
224 | 484k | } |
225 | 674k | return done; |
226 | 674k | } |
227 | | |
228 | | // Utility for test run. |
229 | | OneTimeTestInit OneTimeTestInit::one_time_init_; |
230 | | |
231 | | // llvm std::regex have problem with stack overflow, limit maximum length. |
232 | | // ./scalar_fuzzer -max_len=3000 |
233 | 4.77k | extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { |
234 | | // Reserve one byte for Parser flags and one byte for repetition counter. |
235 | 4.77k | if (size < 3) return 0; |
236 | 4.76k | const uint8_t flags = data[0]; |
237 | | // normalize to ascii alphabet |
238 | 4.76k | const int extra_rep_number = |
239 | 4.76k | std::max(5, (data[1] > '0' ? (data[1] - '0') : 0)); |
240 | 4.76k | data += 2; |
241 | 4.76k | size -= 2; // bypass |
242 | | |
243 | | // Guarantee 0-termination. |
244 | 4.76k | const std::string original(reinterpret_cast<const char *>(data), size); |
245 | 4.76k | auto input = std::string(original.c_str()); // until '\0' |
246 | 4.76k | if (input.size() < kMinInputLength || input.size() > kMaxInputLength) |
247 | 47 | return 0; |
248 | | |
249 | | // Break comments in json to avoid complexity with regex matcher. |
250 | | // The string " 12345 /* text */" will be accepted if insert it to string |
251 | | // expression: "table X { Y: " + " 12345 /* text */" + "; }. |
252 | | // But strings like this will complicate regex matcher. |
253 | | // We reject this by transform "/* text */ 12345" to "@* text */ 12345". |
254 | 4.72k | BreakSequence(input, "//", '@'); // "//" -> "@/" |
255 | 4.72k | BreakSequence(input, "/*", '@'); // "/*" -> "@*" |
256 | | // { "$schema: "text" } is exceptional case. |
257 | | // This key:value ignored by the parser. Numbers can not have $. |
258 | 4.72k | BreakSequence(input, "$schema", '@'); // "$schema" -> "@schema" |
259 | | // Break all known scalar functions (todo: add them to regex?): |
260 | 37.7k | for (auto f : { "deg", "rad", "sin", "cos", "tan", "asin", "acos", "atan" }) { |
261 | 37.7k | BreakSequence(input, f, '_'); // ident -> ident |
262 | 37.7k | } |
263 | | |
264 | | // Extract type of scalar from 'flags' and check if the input string satisfies |
265 | | // the scalar type. |
266 | 4.72k | const auto ref_res = |
267 | 4.72k | ScalarReferenceResult::Check(flags & flags_scalar_type, input); |
268 | 4.72k | auto &recheck = ref_res.matched; |
269 | | |
270 | | // Create parser |
271 | 4.72k | flatbuffers::IDLOptions opts; |
272 | 4.72k | opts.force_defaults = true; |
273 | 4.72k | opts.output_default_scalars_in_json = true; |
274 | 4.72k | opts.indent_step = -1; |
275 | 4.72k | opts.strict_json = true; |
276 | | |
277 | 4.72k | flatbuffers::Parser parser(opts); |
278 | 4.72k | auto schema = |
279 | 4.72k | "table X { Y: " + std::string(ref_res.type) + "; } root_type X;"; |
280 | 4.72k | TEST_EQ_FUNC(parser.Parse(schema.c_str()), true); |
281 | | |
282 | | // The fuzzer can adjust the number repetition if a side-effects have found. |
283 | | // Each test should pass at least two times to ensure that the parser doesn't |
284 | | // have any hidden-states or locale-depended effects. |
285 | 345k | for (auto cnt = 0; cnt < (extra_rep_number + 2); cnt++) { |
286 | | // Each even run (0,2,4..) will test locale independed code. |
287 | 341k | auto use_locale = !!OneTimeTestInit::test_locale() && (0 == (cnt % 2)); |
288 | | // Set new locale. |
289 | 341k | if (use_locale) { |
290 | 172k | FLATBUFFERS_ASSERT(setlocale(LC_ALL, OneTimeTestInit::test_locale())); |
291 | 172k | } |
292 | | |
293 | | // Parse original input as-is. |
294 | 0 | auto orig_scalar = "{\"Y\" : " + input + "}"; |
295 | 341k | std::string orig_back; |
296 | 341k | auto orig_done = Parse(parser, orig_scalar, &orig_back); |
297 | | |
298 | 341k | if (recheck.res != orig_done) { |
299 | | // look for "does not fit" or "doesn't fit" or "out of range" |
300 | 51.6k | auto not_fit = |
301 | 51.6k | (true == recheck.res) |
302 | 51.6k | ? ((orig_back.find("does not fit") != std::string::npos) || |
303 | 51.6k | (orig_back.find("out of range") != std::string::npos)) |
304 | 51.6k | : false; |
305 | | |
306 | 51.6k | if (false == not_fit) { |
307 | 0 | TEST_OUTPUT_LINE("Stage 1 failed: Parser(%d) != Regex(%d)", orig_done, |
308 | 0 | recheck.res); |
309 | 0 | TEST_EQ_STR(orig_back.c_str(), |
310 | 0 | input.substr(recheck.pos, recheck.len).c_str()); |
311 | 0 | TEST_EQ_FUNC(orig_done, recheck.res); |
312 | 0 | } |
313 | 51.6k | } |
314 | | |
315 | | // Try to make quoted string and test it. |
316 | 341k | std::string qouted_input; |
317 | 341k | if (true == recheck.quoted) { |
318 | | // we can't simply remove quotes, they may be nested "'12'". |
319 | | // Original string "\'12\'" converted to "'12'". |
320 | | // The string can be an invalid string by JSON rules, but after quotes |
321 | | // removed can transform to valid. |
322 | 7.28k | assert(recheck.len >= 2); |
323 | 333k | } else { |
324 | 333k | const auto quote = (flags & flags_quotes_kind) ? '\"' : '\''; |
325 | 333k | qouted_input = input; // copy |
326 | 333k | qouted_input.insert(recheck.pos + recheck.len, 1, quote); |
327 | 333k | qouted_input.insert(recheck.pos, 1, quote); |
328 | 333k | } |
329 | | |
330 | | // Test quoted version of the string |
331 | 341k | if (!qouted_input.empty()) { |
332 | 333k | auto fix_scalar = "{\"Y\" : " + qouted_input + "}"; |
333 | 333k | std::string fix_back; |
334 | 333k | auto fix_done = Parse(parser, fix_scalar, &fix_back); |
335 | | |
336 | 333k | if (orig_done != fix_done) { |
337 | 0 | TEST_OUTPUT_LINE("Stage 2 failed: Parser(%d) != Regex(%d)", fix_done, |
338 | 0 | orig_done); |
339 | 0 | TEST_EQ_STR(fix_back.c_str(), orig_back.c_str()); |
340 | 0 | } |
341 | 333k | if (orig_done) { TEST_EQ_STR(fix_back.c_str(), orig_back.c_str()); } |
342 | 333k | TEST_EQ_FUNC(fix_done, orig_done); |
343 | 333k | } |
344 | | |
345 | | // Create new parser and test default value |
346 | 341k | if (true == orig_done) { |
347 | 98.2k | flatbuffers::Parser def_parser(opts); // re-use options |
348 | 98.2k | auto def_schema = "table X { Y: " + std::string(ref_res.type) + " = " + |
349 | 98.2k | input + "; } root_type X;" + |
350 | 98.2k | "{}"; // <- with empty json {}! |
351 | | |
352 | 98.2k | auto def_done = def_parser.Parse(def_schema.c_str()); |
353 | 98.2k | if (false == def_done) { |
354 | 0 | TEST_OUTPUT_LINE("Stage 3.1 failed with _error = %s", |
355 | 0 | def_parser.error_.c_str()); |
356 | 0 | FLATBUFFERS_ASSERT(false); |
357 | 0 | } |
358 | | // Compare with print. |
359 | 0 | std::string ref_string, def_string; |
360 | 98.2k | FLATBUFFERS_ASSERT(!GenText( |
361 | 98.2k | parser, parser.builder_.GetBufferPointer(), &ref_string)); |
362 | 0 | FLATBUFFERS_ASSERT(!GenText( |
363 | 98.2k | def_parser, def_parser.builder_.GetBufferPointer(), &def_string)); |
364 | 98.2k | if (ref_string != def_string) { |
365 | 0 | TEST_OUTPUT_LINE("Stage 3.2 failed: '%s' != '%s'", def_string.c_str(), |
366 | 0 | ref_string.c_str()); |
367 | 0 | FLATBUFFERS_ASSERT(false); |
368 | 0 | } |
369 | 98.2k | } |
370 | | |
371 | | // Restore locale. |
372 | 341k | if (use_locale) { FLATBUFFERS_ASSERT(setlocale(LC_ALL, "C")); } |
373 | 341k | } |
374 | 4.72k | return 0; |
375 | 4.76k | } |