1 // Copyright 2019 The PDFium 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
5 #include <fuzzer/FuzzedDataProvider.h>
6
7 #include <cstdint>
8 #include <vector>
9
10 #include "core/fpdfapi/page/cpdf_streamparser.h"
11 #include "core/fpdfapi/parser/cpdf_dictionary.h"
12 #include "core/fpdfapi/parser/cpdf_object.h"
13 #include "core/fpdfdoc/cpdf_nametree.h"
14 #include "third_party/base/span.h"
15
16 struct Params {
17 bool delete_backwards;
18 uint8_t count;
19 std::vector<WideString> names;
20 };
21
GetNames(uint8_t count,FuzzedDataProvider * data_provider)22 std::vector<WideString> GetNames(uint8_t count,
23 FuzzedDataProvider* data_provider) {
24 std::vector<WideString> names;
25 names.reserve(count);
26 for (size_t i = 0; i < count; ++i) {
27 // The name is not that interesting here. Keep it short.
28 constexpr size_t kMaxNameLen = 10;
29 std::string str = data_provider->ConsumeRandomLengthString(kMaxNameLen);
30 names.push_back(WideString::FromUTF16LE(
31 reinterpret_cast<const unsigned short*>(str.data()),
32 str.size() / sizeof(unsigned short)));
33 }
34 return names;
35 }
36
GetParams(FuzzedDataProvider * data_provider)37 Params GetParams(FuzzedDataProvider* data_provider) {
38 Params params;
39 params.delete_backwards = data_provider->ConsumeBool();
40 params.count = data_provider->ConsumeIntegralInRange(1, 255);
41 params.names = GetNames(params.count, data_provider);
42 return params;
43 }
44
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)45 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
46 FuzzedDataProvider data_provider(data, size);
47 Params params = GetParams(&data_provider);
48
49 // |remaining| needs to outlive |parser|.
50 std::vector<uint8_t> remaining =
51 data_provider.ConsumeRemainingBytes<uint8_t>();
52 if (remaining.empty())
53 return 0;
54
55 CPDF_StreamParser parser(remaining);
56 auto dict = pdfium::MakeRetain<CPDF_Dictionary>();
57 CPDF_NameTree name_tree(dict.Get());
58 for (const auto& name : params.names) {
59 RetainPtr<CPDF_Object> obj = parser.ReadNextObject(
60 /*bAllowNestedArray*/ true, /*bInArray=*/false, /*dwRecursionLevel=*/0);
61 if (!obj)
62 break;
63
64 name_tree.AddValueAndName(std::move(obj), name);
65 }
66
67 if (params.delete_backwards) {
68 for (size_t i = params.count; i > 0; --i)
69 name_tree.DeleteValueAndName(i);
70 } else {
71 for (size_t i = 0; i < params.count; ++i)
72 name_tree.DeleteValueAndName(0);
73 }
74 return 0;
75 }
76