1 //===- FuzzerIOWindows.cpp - IO utils for Windows. ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
8 // IO functions implementation for Windows.
9 //===----------------------------------------------------------------------===//
10 #include "FuzzerDefs.h"
13 #include "FuzzerExtFunctions.h"
21 #include <sys/types.h>
26 static bool IsFile(const std::string &Path, const DWORD &FileAttributes) {
28 if (FileAttributes & FILE_ATTRIBUTE_NORMAL)
31 if (FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
35 CreateFileA(Path.c_str(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
36 FILE_FLAG_BACKUP_SEMANTICS, 0));
38 if (FileHandle == INVALID_HANDLE_VALUE) {
39 Printf("CreateFileA() failed for \"%s\" (Error code: %lu).\n", Path.c_str(),
44 DWORD FileType = GetFileType(FileHandle);
46 if (FileType == FILE_TYPE_UNKNOWN) {
47 Printf("GetFileType() failed for \"%s\" (Error code: %lu).\n", Path.c_str(),
49 CloseHandle(FileHandle);
53 if (FileType != FILE_TYPE_DISK) {
54 CloseHandle(FileHandle);
58 CloseHandle(FileHandle);
62 bool IsFile(const std::string &Path) {
63 DWORD Att = GetFileAttributesA(Path.c_str());
65 if (Att == INVALID_FILE_ATTRIBUTES) {
66 Printf("GetFileAttributesA() failed for \"%s\" (Error code: %lu).\n",
67 Path.c_str(), GetLastError());
71 return IsFile(Path, Att);
74 static bool IsDir(DWORD FileAttrs) {
75 if (FileAttrs == INVALID_FILE_ATTRIBUTES) return false;
76 return FileAttrs & FILE_ATTRIBUTE_DIRECTORY;
79 std::string Basename(const std::string &Path) {
80 size_t Pos = Path.find_last_of("/\\");
81 if (Pos == std::string::npos) return Path;
82 assert(Pos < Path.size());
83 return Path.substr(Pos + 1);
86 size_t FileSize(const std::string &Path) {
87 WIN32_FILE_ATTRIBUTE_DATA attr;
88 if (!GetFileAttributesExA(Path.c_str(), GetFileExInfoStandard, &attr)) {
89 DWORD LastError = GetLastError();
90 if (LastError != ERROR_FILE_NOT_FOUND)
91 Printf("GetFileAttributesExA() failed for \"%s\" (Error code: %lu).\n",
92 Path.c_str(), LastError);
96 size.HighPart = attr.nFileSizeHigh;
97 size.LowPart = attr.nFileSizeLow;
101 void ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
102 Vector<std::string> *V, bool TopDir) {
103 auto E = GetEpoch(Dir);
105 if (E && *Epoch >= E) return;
107 std::string Path(Dir);
108 assert(!Path.empty());
109 if (Path.back() != '\\')
110 Path.push_back('\\');
113 // Get the first directory entry.
114 WIN32_FIND_DATAA FindInfo;
115 HANDLE FindHandle(FindFirstFileA(Path.c_str(), &FindInfo));
116 if (FindHandle == INVALID_HANDLE_VALUE)
118 if (GetLastError() == ERROR_FILE_NOT_FOUND)
120 Printf("No such file or directory: %s; exiting\n", Dir.c_str());
125 std::string FileName = DirPlusFile(Dir, FindInfo.cFileName);
127 if (FindInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
128 size_t FilenameLen = strlen(FindInfo.cFileName);
129 if ((FilenameLen == 1 && FindInfo.cFileName[0] == '.') ||
130 (FilenameLen == 2 && FindInfo.cFileName[0] == '.' &&
131 FindInfo.cFileName[1] == '.'))
134 ListFilesInDirRecursive(FileName, Epoch, V, false);
136 else if (IsFile(FileName, FindInfo.dwFileAttributes))
137 V->push_back(FileName);
138 } while (FindNextFileA(FindHandle, &FindInfo));
140 DWORD LastError = GetLastError();
141 if (LastError != ERROR_NO_MORE_FILES)
142 Printf("FindNextFileA failed (Error code: %lu).\n", LastError);
144 FindClose(FindHandle);
151 void IterateDirRecursive(const std::string &Dir,
152 void (*DirPreCallback)(const std::string &Dir),
153 void (*DirPostCallback)(const std::string &Dir),
154 void (*FileCallback)(const std::string &Dir)) {
155 // TODO(metzman): Implement ListFilesInDirRecursive via this function.
158 DWORD DirAttrs = GetFileAttributesA(Dir.c_str());
159 if (!IsDir(DirAttrs)) return;
161 std::string TargetDir(Dir);
162 assert(!TargetDir.empty());
163 if (TargetDir.back() != '\\') TargetDir.push_back('\\');
164 TargetDir.push_back('*');
166 WIN32_FIND_DATAA FindInfo;
167 // Find the directory's first file.
168 HANDLE FindHandle = FindFirstFileA(TargetDir.c_str(), &FindInfo);
169 if (FindHandle == INVALID_HANDLE_VALUE) {
170 DWORD LastError = GetLastError();
171 if (LastError != ERROR_FILE_NOT_FOUND) {
172 // If the directory isn't empty, then something abnormal is going on.
173 Printf("FindFirstFileA failed for %s (Error code: %lu).\n", Dir.c_str(),
180 std::string Path = DirPlusFile(Dir, FindInfo.cFileName);
181 DWORD PathAttrs = FindInfo.dwFileAttributes;
182 if (IsDir(PathAttrs)) {
183 // Is Path the current directory (".") or the parent ("..")?
184 if (strcmp(FindInfo.cFileName, ".") == 0 ||
185 strcmp(FindInfo.cFileName, "..") == 0)
187 IterateDirRecursive(Path, DirPreCallback, DirPostCallback, FileCallback);
188 } else if (PathAttrs != INVALID_FILE_ATTRIBUTES) {
191 } while (FindNextFileA(FindHandle, &FindInfo));
193 DWORD LastError = GetLastError();
194 if (LastError != ERROR_NO_MORE_FILES)
195 Printf("FindNextFileA failed for %s (Error code: %lu).\n", Dir.c_str(),
198 FindClose(FindHandle);
199 DirPostCallback(Dir);
202 char GetSeparator() {
206 FILE* OpenFile(int Fd, const char* Mode) {
207 return _fdopen(Fd, Mode);
210 int CloseFile(int Fd) {
214 int DuplicateFile(int Fd) {
218 void RemoveFile(const std::string &Path) {
219 _unlink(Path.c_str());
222 void RenameFile(const std::string &OldPath, const std::string &NewPath) {
223 rename(OldPath.c_str(), NewPath.c_str());
226 void DiscardOutput(int Fd) {
227 FILE* Temp = fopen("nul", "w");
230 _dup2(_fileno(Temp), Fd);
234 intptr_t GetHandleFromFd(int fd) {
235 return _get_osfhandle(fd);
238 static bool IsSeparator(char C) {
239 return C == '\\' || C == '/';
242 // Parse disk designators, like "C:\". If Relative == true, also accepts: "C:".
243 // Returns number of characters considered if successful.
244 static size_t ParseDrive(const std::string &FileName, const size_t Offset,
245 bool Relative = true) {
246 if (Offset + 1 >= FileName.size() || FileName[Offset + 1] != ':')
248 if (Offset + 2 >= FileName.size() || !IsSeparator(FileName[Offset + 2])) {
249 if (!Relative) // Accept relative path?
257 // Parse a file name, like: SomeFile.txt
258 // Returns number of characters considered if successful.
259 static size_t ParseFileName(const std::string &FileName, const size_t Offset) {
261 const size_t End = FileName.size();
262 for(; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
267 // Parse a directory ending in separator, like: `SomeDir\`
268 // Returns number of characters considered if successful.
269 static size_t ParseDir(const std::string &FileName, const size_t Offset) {
271 const size_t End = FileName.size();
272 if (Pos >= End || IsSeparator(FileName[Pos]))
274 for(; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
278 ++Pos; // Include separator.
282 // Parse a servername and share, like: `SomeServer\SomeShare\`
283 // Returns number of characters considered if successful.
284 static size_t ParseServerAndShare(const std::string &FileName,
285 const size_t Offset) {
286 size_t Pos = Offset, Res;
287 if (!(Res = ParseDir(FileName, Pos)))
290 if (!(Res = ParseDir(FileName, Pos)))
296 // Parse the given Ref string from the position Offset, to exactly match the given
298 // Returns number of characters considered if successful.
299 static size_t ParseCustomString(const std::string &Ref, size_t Offset,
301 size_t Len = strlen(Patt);
302 if (Offset + Len > Ref.size())
304 return Ref.compare(Offset, Len, Patt) == 0 ? Len : 0;
307 // Parse a location, like:
308 // \\?\UNC\Server\Share\ \\?\C:\ \\Server\Share\ \ C:\ C:
309 // Returns number of characters considered if successful.
310 static size_t ParseLocation(const std::string &FileName) {
313 if ((Res = ParseCustomString(FileName, Pos, R"(\\?\)"))) {
315 if ((Res = ParseCustomString(FileName, Pos, R"(UNC\)"))) {
317 if ((Res = ParseServerAndShare(FileName, Pos)))
321 if ((Res = ParseDrive(FileName, Pos, false)))
326 if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
328 if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
330 if ((Res = ParseServerAndShare(FileName, Pos)))
337 if ((Res = ParseDrive(FileName, Pos)))
343 std::string DirName(const std::string &FileName) {
344 size_t LocationLen = ParseLocation(FileName);
345 size_t DirLen = 0, Res;
346 while ((Res = ParseDir(FileName, LocationLen + DirLen)))
348 size_t FileLen = ParseFileName(FileName, LocationLen + DirLen);
350 if (LocationLen + DirLen + FileLen != FileName.size()) {
351 Printf("DirName() failed for \"%s\", invalid path.\n", FileName.c_str());
356 --DirLen; // Remove trailing separator.
357 if (!FileLen) { // Path ended in separator.
359 // Remove file name from Dir.
360 while (DirLen && !IsSeparator(FileName[LocationLen + DirLen - 1]))
362 if (DirLen) // Remove trailing separator.
367 if (!LocationLen) { // Relative path.
370 return std::string(".\\").append(FileName, 0, DirLen);
373 return FileName.substr(0, LocationLen + DirLen);
376 std::string TmpDir() {
378 Tmp.resize(MAX_PATH + 1);
379 DWORD Size = GetTempPathA(Tmp.size(), &Tmp[0]);
381 Printf("Couldn't get Tmp path.\n");
388 bool IsInterestingCoverageFile(const std::string &FileName) {
389 if (FileName.find("Program Files") != std::string::npos)
391 if (FileName.find("compiler-rt\\lib\\") != std::string::npos)
392 return false; // sanitizer internal.
393 if (FileName == "<null>")
398 void RawPrint(const char *Str) {
399 _write(2, Str, strlen(Str));
402 void MkDir(const std::string &Path) {
403 if (CreateDirectoryA(Path.c_str(), nullptr)) return;
404 Printf("CreateDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
408 void RmDir(const std::string &Path) {
409 if (RemoveDirectoryA(Path.c_str())) return;
410 Printf("RemoveDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
414 const std::string &getDevNull() {
415 static const std::string devNull = "NUL";
419 } // namespace fuzzer
421 #endif // LIBFUZZER_WINDOWS