aboutsummaryrefslogtreecommitdiff
path: root/test/core/util/fuzzer_corpus_test.cc
blob: f1e831765ef40e1b09c7324b7df52ce4f52eb4fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
//
//
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//

#include <dirent.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <algorithm>
#include <string>
#include <vector>

#include "absl/flags/flag.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "gtest/gtest.h"

#include <grpc/slice.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>

#include "src/core/lib/gprpp/env.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/load_file.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/test_config.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
extern bool squelch;

ABSL_FLAG(std::string, file, "", "Use this file as test data");
ABSL_FLAG(std::string, directory, "", "Use this directory as test data");

class FuzzerCorpusTest : public ::testing::TestWithParam<std::string> {};

TEST_P(FuzzerCorpusTest, RunOneExample) {
  // Need to call grpc_init() here to use a slice, but need to shut it
  // down before calling LLVMFuzzerTestOneInput(), because most
  // implementations of that function will initialize and shutdown gRPC
  // internally.
  gpr_log(GPR_INFO, "Example file: %s", GetParam().c_str());
  grpc_slice buffer;
  squelch = false;
  GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file",
                               grpc_load_file(GetParam().c_str(), 0, &buffer)));
  size_t length = GRPC_SLICE_LENGTH(buffer);
  void* data = gpr_malloc(length);
  if (length > 0) {
    memcpy(data, GRPC_SLICE_START_PTR(buffer), length);
  }
  grpc_slice_unref(buffer);
  LLVMFuzzerTestOneInput(static_cast<uint8_t*>(data), length);
  gpr_free(data);
}

class ExampleGenerator
    : public ::testing::internal::ParamGeneratorInterface<std::string> {
 public:
  ::testing::internal::ParamIteratorInterface<std::string>* Begin()
      const override;
  ::testing::internal::ParamIteratorInterface<std::string>* End()
      const override;

 private:
  void Materialize() const {
    if (examples_.empty()) {
      if (!absl::GetFlag(FLAGS_file).empty()) {
        examples_.push_back(absl::GetFlag(FLAGS_file));
      }
      if (!absl::GetFlag(FLAGS_directory).empty()) {
        auto test_srcdir = grpc_core::GetEnv("TEST_SRCDIR");
        gpr_log(GPR_DEBUG, "test_srcdir=\"%s\"",
                test_srcdir.has_value() ? test_srcdir->c_str() : "(null)");
        std::string directory = absl::GetFlag(FLAGS_directory);
        if (test_srcdir.has_value()) {
          directory =
              *test_srcdir + std::string("/com_github_grpc_grpc/") + directory;
        }
        gpr_log(GPR_DEBUG, "Using corpus directory: %s", directory.c_str());
        DIR* dp;
        struct dirent* ep;
        dp = opendir(directory.c_str());

        if (dp != nullptr) {
          while ((ep = readdir(dp)) != nullptr) {
            if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0) {
              examples_.push_back(directory + "/" + ep->d_name);
            }
          }

          (void)closedir(dp);
        } else {
          perror("Couldn't open the directory");
          abort();
        }
      }
    }
    // Make sure we don't succeed without doing anything, which caused
    // us to be blind to our fuzzers not running for 9 months.
    GPR_ASSERT(!examples_.empty());
    // Get a consistent ordering of examples so problems don't just show up on
    // CI
    std::sort(examples_.begin(), examples_.end());
  }

  mutable std::vector<std::string> examples_;
};

class ExampleIterator
    : public ::testing::internal::ParamIteratorInterface<std::string> {
 public:
  ExampleIterator(const ExampleGenerator& base_,
                  std::vector<std::string>::const_iterator begin)
      : base_(base_), begin_(begin), current_(begin) {}

  const ExampleGenerator* BaseGenerator() const override { return &base_; }

  void Advance() override { current_++; }
  ExampleIterator* Clone() const override { return new ExampleIterator(*this); }
  const std::string* Current() const override { return &*current_; }

  bool Equals(const ParamIteratorInterface<std::string>& other) const override {
    return &base_ == other.BaseGenerator() &&
           current_ == dynamic_cast<const ExampleIterator*>(&other)->current_;
  }

 private:
  ExampleIterator(const ExampleIterator& other)
      : base_(other.base_), begin_(other.begin_), current_(other.current_) {}

  const ExampleGenerator& base_;
  const std::vector<std::string>::const_iterator begin_;
  std::vector<std::string>::const_iterator current_;
};

::testing::internal::ParamIteratorInterface<std::string>*
ExampleGenerator::Begin() const {
  Materialize();
  return new ExampleIterator(*this, examples_.begin());
}

::testing::internal::ParamIteratorInterface<std::string>*
ExampleGenerator::End() const {
  Materialize();
  return new ExampleIterator(*this, examples_.end());
}

INSTANTIATE_TEST_SUITE_P(
    CorpusExamples, FuzzerCorpusTest,
    ::testing::internal::ParamGenerator<std::string>(new ExampleGenerator));

int main(int argc, char** argv) {
  grpc::testing::TestEnvironment env(&argc, argv);
  grpc::testing::InitTest(&argc, &argv, true);
  ::testing::InitGoogleTest(&argc, argv);

  return RUN_ALL_TESTS();
}