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 Printf("Can not stat: %s; exiting\n", Path.c_str());
31 static std::vector<std::string> ListFilesInDir(const std::string &Dir,
33 std::vector<std::string> V;
35 auto E = GetEpoch(Dir);
36 if (*Epoch >= E) return V;
39 DIR *D = opendir(Dir.c_str());
41 Printf("No such directory: %s; exiting\n", Dir.c_str());
44 while (auto E = readdir(D)) {
45 if (E->d_type == DT_REG || E->d_type == DT_LNK)
46 V.push_back(E->d_name);
52 Unit FileToVector(const std::string &Path) {
53 std::ifstream T(Path);
54 return Unit((std::istreambuf_iterator<char>(T)),
55 std::istreambuf_iterator<char>());
58 std::string FileToString(const std::string &Path) {
59 std::ifstream T(Path);
60 return std::string((std::istreambuf_iterator<char>(T)),
61 std::istreambuf_iterator<char>());
64 void CopyFileToErr(const std::string &Path) {
65 Printf("%s", FileToString(Path).c_str());
68 void WriteToFile(const Unit &U, const std::string &Path) {
69 // Use raw C interface because this function may be called from a sig handler.
70 FILE *Out = fopen(Path.c_str(), "w");
72 fwrite(U.data(), sizeof(U[0]), U.size(), Out);
76 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
78 long E = Epoch ? *Epoch : 0;
79 for (auto &X : ListFilesInDir(Path, Epoch)) {
80 auto FilePath = DirPlusFile(Path, X);
81 if (Epoch && GetEpoch(FilePath) < E) continue;
82 V->push_back(FileToVector(FilePath));
86 std::string DirPlusFile(const std::string &DirPath,
87 const std::string &FileName) {
88 return DirPath + "/" + FileName;
91 void PrintFileAsBase64(const std::string &Path) {
92 std::string Cmd = "base64 -w 0 < " + Path + "; echo";
96 void Printf(const char *Fmt, ...) {
99 vfprintf(stderr, Fmt, ap);
103 } // namespace fuzzer