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 //===----------------------------------------------------------------------===//
13 #include "FuzzerDefs.h"
14 #include "FuzzerExtFunctions.h"
20 #include <sys/types.h>
24 static FILE *OutputFile = stderr;
26 long GetEpoch(const std::string &Path) {
28 if (stat(Path.c_str(), &St))
29 return 0; // Can't stat, be conservative.
33 Unit FileToVector(const std::string &Path, size_t MaxSize, bool ExitOnError) {
34 std::ifstream T(Path, std::ios::binary);
35 if (ExitOnError && !T) {
36 Printf("No such directory: %s; exiting\n", Path.c_str());
41 auto EndPos = T.tellg();
42 if (EndPos < 0) return {};
43 size_t FileLen = EndPos;
45 FileLen = std::min(FileLen, MaxSize);
49 T.read(reinterpret_cast<char *>(Res.data()), FileLen);
53 std::string FileToString(const std::string &Path) {
54 std::ifstream T(Path, std::ios::binary);
55 return std::string((std::istreambuf_iterator<char>(T)),
56 std::istreambuf_iterator<char>());
59 void CopyFileToErr(const std::string &Path) {
60 Printf("%s", FileToString(Path).c_str());
63 void WriteToFile(const Unit &U, const std::string &Path) {
64 // Use raw C interface because this function may be called from a sig handler.
65 FILE *Out = fopen(Path.c_str(), "w");
67 fwrite(U.data(), sizeof(U[0]), U.size(), Out);
71 void ReadDirToVectorOfUnits(const char *Path, Vector<Unit> *V,
72 long *Epoch, size_t MaxSize, bool ExitOnError) {
73 long E = Epoch ? *Epoch : 0;
74 Vector<std::string> Files;
75 ListFilesInDirRecursive(Path, Epoch, &Files, /*TopDir*/true);
77 for (size_t i = 0; i < Files.size(); i++) {
79 if (Epoch && GetEpoch(X) < E) continue;
81 if ((NumLoaded & (NumLoaded - 1)) == 0 && NumLoaded >= 1024)
82 Printf("Loaded %zd/%zd files from %s\n", NumLoaded, Files.size(), Path);
83 auto S = FileToVector(X, MaxSize, ExitOnError);
90 void GetSizedFilesFromDir(const std::string &Dir, Vector<SizedFile> *V) {
91 Vector<std::string> Files;
92 ListFilesInDirRecursive(Dir, 0, &Files, /*TopDir*/true);
93 for (auto &File : Files)
94 if (size_t Size = FileSize(File))
95 V->push_back({File, Size});
98 std::string DirPlusFile(const std::string &DirPath,
99 const std::string &FileName) {
100 return DirPath + GetSeparator() + FileName;
103 void DupAndCloseStderr() {
104 int OutputFd = DuplicateFile(2);
106 FILE *NewOutputFile = OpenFile(OutputFd, "w");
108 OutputFile = NewOutputFile;
109 if (EF->__sanitizer_set_report_fd)
110 EF->__sanitizer_set_report_fd(
111 reinterpret_cast<void *>(GetHandleFromFd(OutputFd)));
121 void Printf(const char *Fmt, ...) {
124 vfprintf(OutputFile, Fmt, ap);
129 } // namespace fuzzer