/src/flatbuffers/tests/fuzzer/flatbuffers_parser_fuzzer.cc
Line | Count | Source |
1 | | // Copyright 2015 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 | | #include <stddef.h> |
5 | | #include <stdint.h> |
6 | | |
7 | | #include <clocale> |
8 | | #include <string> |
9 | | |
10 | | #include "flatbuffers/idl.h" |
11 | | #include "test_init.h" |
12 | | |
13 | | static constexpr size_t kMinInputLength = 1; |
14 | | static constexpr size_t kMaxInputLength = 16384; |
15 | | |
16 | | static constexpr uint8_t flags_strict_json = 0x80; |
17 | | static constexpr uint8_t flags_skip_unexpected_fields_in_json = 0x40; |
18 | | static constexpr uint8_t flags_allow_non_utf8 = 0x20; |
19 | | |
20 | | // Utility for test run. |
21 | | OneTimeTestInit OneTimeTestInit::one_time_init_; |
22 | | |
23 | 29.3k | extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { |
24 | | // Reserve one byte for Parser flags and one byte for repetition counter. |
25 | 29.3k | if (size < 3) return 0; |
26 | 29.3k | const uint8_t flags = data[0]; |
27 | 29.3k | (void)data[1]; // reserved |
28 | 29.3k | data += 2; |
29 | 29.3k | size -= 2; // bypass |
30 | | |
31 | 29.3k | const std::string original(reinterpret_cast<const char*>(data), size); |
32 | 29.3k | auto input = std::string(original.c_str()); // until '\0' |
33 | 29.3k | if (input.size() < kMinInputLength || input.size() > kMaxInputLength) |
34 | 26 | return 0; |
35 | | |
36 | 29.2k | flatbuffers::IDLOptions opts; |
37 | 29.2k | opts.strict_json = (flags & flags_strict_json); |
38 | 29.2k | opts.skip_unexpected_fields_in_json = |
39 | 29.2k | (flags & flags_skip_unexpected_fields_in_json); |
40 | 29.2k | opts.allow_non_utf8 = (flags & flags_allow_non_utf8); |
41 | | |
42 | 29.2k | flatbuffers::Parser parser(opts); |
43 | | |
44 | | // Guarantee 0-termination in the input. |
45 | 29.2k | auto parse_input = input.c_str(); |
46 | | |
47 | | // Check Parser. |
48 | 29.2k | parser.Parse(parse_input); |
49 | | // TODO: |
50 | | // Need to add additional checks for inputs passed Parse(parse_input) |
51 | | // successfully: |
52 | | // 1. Serialization to bfbs. |
53 | | // 2. Generation of a default object. |
54 | | // 3. Verification of the object using reflection. |
55 | | // 3. Printing to json. |
56 | 29.2k | return 0; |
57 | 29.3k | } |