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>
22 static long GetEpoch(const std::string &Path) {
24 if (stat(Path.c_str(), &St))
25 return 0; // Can't stat, be conservative.
29 static std::vector<std::string> ListFilesInDir(const std::string &Dir,
31 std::vector<std::string> V;
33 auto E = GetEpoch(Dir);
34 if (*Epoch >= E) return V;
37 DIR *D = opendir(Dir.c_str());
39 Printf("No such directory: %s; exiting\n", Dir.c_str());
42 while (auto E = readdir(D)) {
43 if (E->d_type == DT_REG || E->d_type == DT_LNK)
44 V.push_back(E->d_name);
50 Unit FileToVector(const std::string &Path) {
51 std::ifstream T(Path);
52 return Unit((std::istreambuf_iterator<char>(T)),
53 std::istreambuf_iterator<char>());
56 std::string FileToString(const std::string &Path) {
57 std::ifstream T(Path);
58 return std::string((std::istreambuf_iterator<char>(T)),
59 std::istreambuf_iterator<char>());
62 void CopyFileToErr(const std::string &Path) {
63 Printf("%s", FileToString(Path).c_str());
66 void WriteToFile(const Unit &U, const std::string &Path) {
67 // Use raw C interface because this function may be called from a sig handler.
68 FILE *Out = fopen(Path.c_str(), "w");
70 fwrite(U.data(), sizeof(U[0]), U.size(), Out);
74 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
76 long E = Epoch ? *Epoch : 0;
77 for (auto &X : ListFilesInDir(Path, Epoch)) {
78 auto FilePath = DirPlusFile(Path, X);
79 if (Epoch && GetEpoch(FilePath) < E) continue;
80 V->push_back(FileToVector(FilePath));
84 std::string DirPlusFile(const std::string &DirPath,
85 const std::string &FileName) {
86 return DirPath + "/" + FileName;
89 void PrintFileAsBase64(const std::string &Path) {
90 std::string Cmd = "base64 -w 0 < " + Path + "; echo";
94 void Printf(const char *Fmt, ...) {
97 vfprintf(stderr, Fmt, ap);
101 } // namespace fuzzer