1 // Copyright 2015 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 "base/json/json_reader.h" 6 7 #include <optional> 8 #include <string_view> 9 10 #include "base/containers/heap_array.h" 11 #include "base/json/json_writer.h" 12 #include "base/values.h" 13 14 namespace base { 15 16 // Entry point for LibFuzzer. LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)17extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { 18 if (size < 2) 19 return 0; 20 21 // SAFETY: LibFuzzer provides a valid data/size pair. 22 auto data_span = UNSAFE_BUFFERS(base::span(data, size)); 23 24 // Create a copy of input buffer, as otherwise we don't catch 25 // overflow that touches the last byte (which is used in options). 26 auto input = base::HeapArray<unsigned char>::Uninit(size - 1); 27 input.copy_from(data_span.first(size - 1u)); 28 29 std::string_view input_string = base::as_string_view(input); 30 31 const int options = data_span.back(); 32 33 auto json_val = 34 JSONReader::ReadAndReturnValueWithError(input_string, options); 35 if (json_val.has_value()) { 36 // Check that the value can be serialized and deserialized back to an 37 // equivalent |Value|. 38 const Value& value = *json_val; 39 std::string serialized; 40 CHECK(JSONWriter::Write(value, &serialized)); 41 42 std::optional<Value> deserialized = 43 JSONReader::Read(std::string_view(serialized)); 44 CHECK(deserialized); 45 CHECK_EQ(value, deserialized.value()); 46 } 47 48 return 0; 49 } 50 51 } // namespace base 52