1 //===- FuzzerIO.cpp - IO utils. -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 //===----------------------------------------------------------------------===//
11 #include "FuzzerInternal.h"
15 #include <sys/types.h>
23 static long GetEpoch(const std::string &Path) {
25 if (stat(Path.c_str(), &St))
26 return 0; // Can't stat, be conservative.
30 static std::vector<std::string> ListFilesInDir(const std::string &Dir,
32 std::vector<std::string> V;
34 auto E = GetEpoch(Dir);
35 if (*Epoch >= E) return V;
38 DIR *D = opendir(Dir.c_str());
40 Printf("No such directory: %s; exiting\n", Dir.c_str());
43 while (auto E = readdir(D)) {
44 if (E->d_type == DT_REG || E->d_type == DT_LNK)
45 V.push_back(E->d_name);
51 Unit FileToVector(const std::string &Path) {
52 std::ifstream T(Path);
54 Printf("No such directory: %s; exiting\n", Path.c_str());
57 return Unit((std::istreambuf_iterator<char>(T)),
58 std::istreambuf_iterator<char>());
61 std::string FileToString(const std::string &Path) {
62 std::ifstream T(Path);
63 return std::string((std::istreambuf_iterator<char>(T)),
64 std::istreambuf_iterator<char>());
67 void CopyFileToErr(const std::string &Path) {
68 Printf("%s", FileToString(Path).c_str());
71 void WriteToFile(const Unit &U, const std::string &Path) {
72 // Use raw C interface because this function may be called from a sig handler.
73 FILE *Out = fopen(Path.c_str(), "w");
75 fwrite(U.data(), sizeof(U[0]), U.size(), Out);
79 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
81 long E = Epoch ? *Epoch : 0;
82 for (auto &X : ListFilesInDir(Path, Epoch)) {
83 auto FilePath = DirPlusFile(Path, X);
84 if (Epoch && GetEpoch(FilePath) < E) continue;
85 V->push_back(FileToVector(FilePath));
89 std::string DirPlusFile(const std::string &DirPath,
90 const std::string &FileName) {
91 return DirPath + "/" + FileName;
94 void Printf(const char *Fmt, ...) {
97 vfprintf(stderr, Fmt, ap);
101 } // namespace fuzzer