1 // Copyright 2018 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <memory>
6 #include <string_view>
7
8 #include "base/json/string_escape.h"
9
10 // Entry point for LibFuzzer.
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)11 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
12 if (size < 2)
13 return 0;
14
15 const bool put_in_quotes = data[size - 1];
16
17 // Create a copy of input buffer, as otherwise we don't catch
18 // overflow that touches the last byte (which is used in put_in_quotes).
19 size_t actual_size_char8 = size - 1;
20 std::unique_ptr<char[]> input(new char[actual_size_char8]);
21 memcpy(input.get(), data, actual_size_char8);
22
23 std::string_view input_string(input.get(), actual_size_char8);
24 std::string escaped_string;
25 base::EscapeJSONString(input_string, put_in_quotes, &escaped_string);
26
27 // Test for wide-strings if available size is even.
28 if (actual_size_char8 & 1)
29 return 0;
30
31 size_t actual_size_char16 = actual_size_char8 / 2;
32 std::u16string_view input_string16(reinterpret_cast<char16_t*>(input.get()),
33 actual_size_char16);
34 escaped_string.clear();
35 base::EscapeJSONString(input_string16, put_in_quotes, &escaped_string);
36
37 return 0;
38 }
39