blob: a7483a5706b8958a5c7c56c93270e2d928ed1f01 [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001// 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#include <clocale>
7#include <string>
8
9#include "flatbuffers/idl.h"
10#include "test_init.h"
11
Austin Schuh58b9b472020-11-25 19:12:44 -080012static constexpr uint8_t flags_strict_json = 0x80;
13static constexpr uint8_t flags_skip_unexpected_fields_in_json = 0x40;
14static constexpr uint8_t flags_allow_non_utf8 = 0x20;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070015
16// Utility for test run.
17OneTimeTestInit OneTimeTestInit::one_time_init_;
18
19extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
20 // Reserve one byte for Parser flags and one byte for repetition counter.
21 if (size < 3) return 0;
22 const uint8_t flags = data[0];
23 // normalize to ascii alphabet
Austin Schuh272c6132020-11-14 16:37:52 -080024 const int extra_rep_number =
25 std::max(5, (data[1] < '0' ? (data[1] - '0') : 0));
Austin Schuhe89fa2d2019-08-14 20:24:23 -070026 data += 2;
27 size -= 2; // bypass
28
29 const std::string original(reinterpret_cast<const char *>(data), size);
30 auto input = std::string(original.c_str()); // until '\0'
31 if (input.empty()) return 0;
32
33 flatbuffers::IDLOptions opts;
34 opts.strict_json = (flags & flags_strict_json);
35 opts.skip_unexpected_fields_in_json =
36 (flags & flags_skip_unexpected_fields_in_json);
37 opts.allow_non_utf8 = (flags & flags_allow_non_utf8);
38
39 flatbuffers::Parser parser(opts);
40
41 // Guarantee 0-termination in the input.
42 auto parse_input = input.c_str();
43
44 // The fuzzer can adjust the number repetition if a side-effects have found.
45 // Each test should pass at least two times to ensure that the parser doesn't
46 // have any hidden-states or locale-depended effects.
47 for (auto cnt = 0; cnt < (extra_rep_number + 2); cnt++) {
48 // Each even run (0,2,4..) will test locale independed code.
49 auto use_locale = !!OneTimeTestInit::test_locale() && (0 == (cnt % 2));
50 // Set new locale.
51 if (use_locale) {
52 FLATBUFFERS_ASSERT(setlocale(LC_ALL, OneTimeTestInit::test_locale()));
53 }
54
55 // Check Parser.
56 parser.Parse(parse_input);
57
58 // Restore locale.
59 if (use_locale) { FLATBUFFERS_ASSERT(setlocale(LC_ALL, "C")); }
60 }
61
62 return 0;
63}