• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The PDFium 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 <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 "core/fxcrt/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(pdfium::as_byte_span(str)));
31   }
32   return names;
33 }
34 
GetParams(FuzzedDataProvider * data_provider)35 Params GetParams(FuzzedDataProvider* data_provider) {
36   Params params;
37   params.delete_backwards = data_provider->ConsumeBool();
38   params.count = data_provider->ConsumeIntegralInRange(1, 255);
39   params.names = GetNames(params.count, data_provider);
40   return params;
41 }
42 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)43 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
44   FuzzedDataProvider data_provider(data, size);
45   Params params = GetParams(&data_provider);
46 
47   // |remaining| needs to outlive |parser|.
48   std::vector<uint8_t> remaining =
49       data_provider.ConsumeRemainingBytes<uint8_t>();
50   if (remaining.empty())
51     return 0;
52 
53   CPDF_StreamParser parser(remaining);
54   auto dict = pdfium::MakeRetain<CPDF_Dictionary>();
55   std::unique_ptr<CPDF_NameTree> name_tree =
56       CPDF_NameTree::CreateForTesting(dict.Get());
57   for (const auto& name : params.names) {
58     RetainPtr<CPDF_Object> obj = parser.ReadNextObject(
59         /*bAllowNestedArray*/ true, /*bInArray=*/false, /*dwRecursionLevel=*/0);
60     if (!obj)
61       break;
62 
63     name_tree->AddValueAndName(std::move(obj), name);
64   }
65 
66   if (params.delete_backwards) {
67     for (size_t i = params.count; i > 0; --i)
68       name_tree->DeleteValueAndName(i);
69   } else {
70     for (size_t i = 0; i < params.count; ++i)
71       name_tree->DeleteValueAndName(0);
72   }
73   return 0;
74 }
75