1 // Copyright 2017 Google Inc. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef EXAMPLES_FUZZER_TEST_H_ 16 #define EXAMPLES_FUZZER_TEST_H_ 17 18 #include <dirent.h> 19 #include <memory> 20 #include <string> 21 22 #include "port/gtest.h" 23 24 using testing::Test; 25 26 class FuzzerTest : public testing::Test { 27 protected: SetUp()28 void SetUp() override { 29 char dir_template[] = "/tmp/libxml2_example_test_XXXXXX"; 30 auto dir = mkdtemp(dir_template); 31 ASSERT_TRUE(dir); 32 dir_ = std::string(dir) + "/"; 33 EXPECT_EQ(0, CountFilesInDir()); 34 } 35 TearDown()36 void TearDown() override { 37 EXPECT_EQ(0, std::system((std::string("rm -rf ") + dir_).c_str())); 38 } 39 RunFuzzer(const std::string & name,int max_len,int runs)40 int RunFuzzer(const std::string& name, int max_len, int runs) { 41 std::string cmd = "ASAN_OPTIONS=detect_leaks=0 ./" + name; 42 cmd += " -detect_leaks=0"; 43 cmd += " -len_control=0"; 44 cmd += " -max_len=" + std::to_string(max_len); 45 cmd += " -runs=" + std::to_string(runs); 46 cmd += " -artifact_prefix=" + dir_; 47 cmd += " " + dir_; 48 fprintf(stderr, "%s \n", cmd.c_str()); 49 return std::system(cmd.c_str()); 50 } 51 CountFilesInDir()52 size_t CountFilesInDir() const { 53 size_t res = 0; 54 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dir_.c_str()), 55 &closedir); 56 if (!dir) return 0; 57 while (readdir(dir.get())) { 58 ++res; 59 } 60 if (res <= 2) return 0; 61 res -= 2; // . and .. 62 return res; 63 } 64 65 std::string dir_; 66 }; 67 68 #endif // EXAMPLES_FUZZER_TEST_H_ 69