1 //===- FuzzerIOPosix.cpp - IO utils for Posix. ----------------------------===//
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 //===----------------------------------------------------------------------===//
9 // IO functions implementation using Posix API.
10 //===----------------------------------------------------------------------===//
11 #include "FuzzerDefs.h"
12 #if LIBFUZZER_POSIX || LIBFUZZER_FUCHSIA
14 #include "FuzzerExtFunctions.h"
23 #include <sys/types.h>
28 bool IsFile(const std::string &Path) {
30 if (stat(Path.c_str(), &St))
32 return S_ISREG(St.st_mode);
35 static bool IsDirectory(const std::string &Path) {
37 if (stat(Path.c_str(), &St))
39 return S_ISDIR(St.st_mode);
42 size_t FileSize(const std::string &Path) {
44 if (stat(Path.c_str(), &St))
49 void ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
50 Vector<std::string> *V, bool TopDir) {
51 auto E = GetEpoch(Dir);
53 if (E && *Epoch >= E) return;
55 DIR *D = opendir(Dir.c_str());
57 Printf("%s: %s; exiting\n", strerror(errno), Dir.c_str());
60 while (auto E = readdir(D)) {
61 std::string Path = DirPlusFile(Dir, E->d_name);
62 if (E->d_type == DT_REG || E->d_type == DT_LNK ||
63 (E->d_type == DT_UNKNOWN && IsFile(Path)))
65 else if ((E->d_type == DT_DIR ||
66 (E->d_type == DT_UNKNOWN && IsDirectory(Path))) &&
68 ListFilesInDirRecursive(Path, Epoch, V, false);
79 FILE* OpenFile(int Fd, const char* Mode) {
80 return fdopen(Fd, Mode);
83 int CloseFile(int fd) {
87 int DuplicateFile(int Fd) {
91 void RemoveFile(const std::string &Path) {
95 void DiscardOutput(int Fd) {
96 FILE* Temp = fopen("/dev/null", "w");
99 dup2(fileno(Temp), Fd);
103 intptr_t GetHandleFromFd(int fd) {
104 return static_cast<intptr_t>(fd);
107 std::string DirName(const std::string &FileName) {
108 char *Tmp = new char[FileName.size() + 1];
109 memcpy(Tmp, FileName.c_str(), FileName.size() + 1);
110 std::string Res = dirname(Tmp);
115 std::string TmpDir() {
116 if (auto Env = getenv("TMPDIR"))
121 bool IsInterestingCoverageFile(const std::string &FileName) {
122 if (FileName.find("compiler-rt/lib/") != std::string::npos)
123 return false; // sanitizer internal.
124 if (FileName.find("/usr/lib/") != std::string::npos)
126 if (FileName.find("/usr/include/") != std::string::npos)
128 if (FileName == "<null>")
134 void RawPrint(const char *Str) {
135 write(2, Str, strlen(Str));
138 } // namespace fuzzer
140 #endif // LIBFUZZER_POSIX