xref: /freebsd/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerIOWindows.cpp (revision b4e38a41f584ad4391c04b8cfec81f46176b18b0)
1 //===- FuzzerIOWindows.cpp - IO utils for Windows. ------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 // IO functions implementation for Windows.
9 //===----------------------------------------------------------------------===//
10 #include "FuzzerDefs.h"
11 #if LIBFUZZER_WINDOWS
12 
13 #include "FuzzerExtFunctions.h"
14 #include "FuzzerIO.h"
15 #include <cstdarg>
16 #include <cstdio>
17 #include <fstream>
18 #include <io.h>
19 #include <iterator>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <windows.h>
23 
24 namespace fuzzer {
25 
26 static bool IsFile(const std::string &Path, const DWORD &FileAttributes) {
27 
28   if (FileAttributes & FILE_ATTRIBUTE_NORMAL)
29     return true;
30 
31   if (FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
32     return false;
33 
34   HANDLE FileHandle(
35       CreateFileA(Path.c_str(), 0, FILE_SHARE_READ, NULL, OPEN_EXISTING,
36                   FILE_FLAG_BACKUP_SEMANTICS, 0));
37 
38   if (FileHandle == INVALID_HANDLE_VALUE) {
39     Printf("CreateFileA() failed for \"%s\" (Error code: %lu).\n", Path.c_str(),
40         GetLastError());
41     return false;
42   }
43 
44   DWORD FileType = GetFileType(FileHandle);
45 
46   if (FileType == FILE_TYPE_UNKNOWN) {
47     Printf("GetFileType() failed for \"%s\" (Error code: %lu).\n", Path.c_str(),
48         GetLastError());
49     CloseHandle(FileHandle);
50     return false;
51   }
52 
53   if (FileType != FILE_TYPE_DISK) {
54     CloseHandle(FileHandle);
55     return false;
56   }
57 
58   CloseHandle(FileHandle);
59   return true;
60 }
61 
62 bool IsFile(const std::string &Path) {
63   DWORD Att = GetFileAttributesA(Path.c_str());
64 
65   if (Att == INVALID_FILE_ATTRIBUTES) {
66     Printf("GetFileAttributesA() failed for \"%s\" (Error code: %lu).\n",
67         Path.c_str(), GetLastError());
68     return false;
69   }
70 
71   return IsFile(Path, Att);
72 }
73 
74 static bool IsDir(DWORD FileAttrs) {
75   if (FileAttrs == INVALID_FILE_ATTRIBUTES) return false;
76   return FileAttrs & FILE_ATTRIBUTE_DIRECTORY;
77 }
78 
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);
84 }
85 
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);
93     return 0;
94   }
95   ULARGE_INTEGER size;
96   size.HighPart = attr.nFileSizeHigh;
97   size.LowPart = attr.nFileSizeLow;
98   return size.QuadPart;
99 }
100 
101 void ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
102                              Vector<std::string> *V, bool TopDir) {
103   auto E = GetEpoch(Dir);
104   if (Epoch)
105     if (E && *Epoch >= E) return;
106 
107   std::string Path(Dir);
108   assert(!Path.empty());
109   if (Path.back() != '\\')
110       Path.push_back('\\');
111   Path.push_back('*');
112 
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)
117   {
118     if (GetLastError() == ERROR_FILE_NOT_FOUND)
119       return;
120     Printf("No such file or directory: %s; exiting\n", Dir.c_str());
121     exit(1);
122   }
123 
124   do {
125     std::string FileName = DirPlusFile(Dir, FindInfo.cFileName);
126 
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] == '.'))
132         continue;
133 
134       ListFilesInDirRecursive(FileName, Epoch, V, false);
135     }
136     else if (IsFile(FileName, FindInfo.dwFileAttributes))
137       V->push_back(FileName);
138   } while (FindNextFileA(FindHandle, &FindInfo));
139 
140   DWORD LastError = GetLastError();
141   if (LastError != ERROR_NO_MORE_FILES)
142     Printf("FindNextFileA failed (Error code: %lu).\n", LastError);
143 
144   FindClose(FindHandle);
145 
146   if (Epoch && TopDir)
147     *Epoch = E;
148 }
149 
150 
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.
156   DirPreCallback(Dir);
157 
158   DWORD DirAttrs = GetFileAttributesA(Dir.c_str());
159   if (!IsDir(DirAttrs)) return;
160 
161   std::string TargetDir(Dir);
162   assert(!TargetDir.empty());
163   if (TargetDir.back() != '\\') TargetDir.push_back('\\');
164   TargetDir.push_back('*');
165 
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(),
174              LastError);
175     }
176     return;
177   }
178 
179   do {
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)
186         continue;
187       IterateDirRecursive(Path, DirPreCallback, DirPostCallback, FileCallback);
188     } else if (PathAttrs != INVALID_FILE_ATTRIBUTES) {
189       FileCallback(Path);
190     }
191   } while (FindNextFileA(FindHandle, &FindInfo));
192 
193   DWORD LastError = GetLastError();
194   if (LastError != ERROR_NO_MORE_FILES)
195     Printf("FindNextFileA failed for %s (Error code: %lu).\n", Dir.c_str(),
196            LastError);
197 
198   FindClose(FindHandle);
199   DirPostCallback(Dir);
200 }
201 
202 char GetSeparator() {
203   return '\\';
204 }
205 
206 FILE* OpenFile(int Fd, const char* Mode) {
207   return _fdopen(Fd, Mode);
208 }
209 
210 int CloseFile(int Fd) {
211   return _close(Fd);
212 }
213 
214 int DuplicateFile(int Fd) {
215   return _dup(Fd);
216 }
217 
218 void RemoveFile(const std::string &Path) {
219   _unlink(Path.c_str());
220 }
221 
222 void RenameFile(const std::string &OldPath, const std::string &NewPath) {
223   rename(OldPath.c_str(), NewPath.c_str());
224 }
225 
226 intptr_t GetHandleFromFd(int fd) {
227   return _get_osfhandle(fd);
228 }
229 
230 static bool IsSeparator(char C) {
231   return C == '\\' || C == '/';
232 }
233 
234 // Parse disk designators, like "C:\". If Relative == true, also accepts: "C:".
235 // Returns number of characters considered if successful.
236 static size_t ParseDrive(const std::string &FileName, const size_t Offset,
237                          bool Relative = true) {
238   if (Offset + 1 >= FileName.size() || FileName[Offset + 1] != ':')
239     return 0;
240   if (Offset + 2 >= FileName.size() || !IsSeparator(FileName[Offset + 2])) {
241     if (!Relative) // Accept relative path?
242       return 0;
243     else
244       return 2;
245   }
246   return 3;
247 }
248 
249 // Parse a file name, like: SomeFile.txt
250 // Returns number of characters considered if successful.
251 static size_t ParseFileName(const std::string &FileName, const size_t Offset) {
252   size_t Pos = Offset;
253   const size_t End = FileName.size();
254   for(; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
255     ;
256   return Pos - Offset;
257 }
258 
259 // Parse a directory ending in separator, like: `SomeDir\`
260 // Returns number of characters considered if successful.
261 static size_t ParseDir(const std::string &FileName, const size_t Offset) {
262   size_t Pos = Offset;
263   const size_t End = FileName.size();
264   if (Pos >= End || IsSeparator(FileName[Pos]))
265     return 0;
266   for(; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
267     ;
268   if (Pos >= End)
269     return 0;
270   ++Pos; // Include separator.
271   return Pos - Offset;
272 }
273 
274 // Parse a servername and share, like: `SomeServer\SomeShare\`
275 // Returns number of characters considered if successful.
276 static size_t ParseServerAndShare(const std::string &FileName,
277                                   const size_t Offset) {
278   size_t Pos = Offset, Res;
279   if (!(Res = ParseDir(FileName, Pos)))
280     return 0;
281   Pos += Res;
282   if (!(Res = ParseDir(FileName, Pos)))
283     return 0;
284   Pos += Res;
285   return Pos - Offset;
286 }
287 
288 // Parse the given Ref string from the position Offset, to exactly match the given
289 // string Patt.
290 // Returns number of characters considered if successful.
291 static size_t ParseCustomString(const std::string &Ref, size_t Offset,
292                                 const char *Patt) {
293   size_t Len = strlen(Patt);
294   if (Offset + Len > Ref.size())
295     return 0;
296   return Ref.compare(Offset, Len, Patt) == 0 ? Len : 0;
297 }
298 
299 // Parse a location, like:
300 // \\?\UNC\Server\Share\  \\?\C:\  \\Server\Share\  \  C:\  C:
301 // Returns number of characters considered if successful.
302 static size_t ParseLocation(const std::string &FileName) {
303   size_t Pos = 0, Res;
304 
305   if ((Res = ParseCustomString(FileName, Pos, R"(\\?\)"))) {
306     Pos += Res;
307     if ((Res = ParseCustomString(FileName, Pos, R"(UNC\)"))) {
308       Pos += Res;
309       if ((Res = ParseServerAndShare(FileName, Pos)))
310         return Pos + Res;
311       return 0;
312     }
313     if ((Res = ParseDrive(FileName, Pos, false)))
314       return Pos + Res;
315     return 0;
316   }
317 
318   if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
319     ++Pos;
320     if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
321       ++Pos;
322       if ((Res = ParseServerAndShare(FileName, Pos)))
323         return Pos + Res;
324       return 0;
325     }
326     return Pos;
327   }
328 
329   if ((Res = ParseDrive(FileName, Pos)))
330     return Pos + Res;
331 
332   return Pos;
333 }
334 
335 std::string DirName(const std::string &FileName) {
336   size_t LocationLen = ParseLocation(FileName);
337   size_t DirLen = 0, Res;
338   while ((Res = ParseDir(FileName, LocationLen + DirLen)))
339     DirLen += Res;
340   size_t FileLen = ParseFileName(FileName, LocationLen + DirLen);
341 
342   if (LocationLen + DirLen + FileLen != FileName.size()) {
343     Printf("DirName() failed for \"%s\", invalid path.\n", FileName.c_str());
344     exit(1);
345   }
346 
347   if (DirLen) {
348     --DirLen; // Remove trailing separator.
349     if (!FileLen) { // Path ended in separator.
350       assert(DirLen);
351       // Remove file name from Dir.
352       while (DirLen && !IsSeparator(FileName[LocationLen + DirLen - 1]))
353         --DirLen;
354       if (DirLen) // Remove trailing separator.
355         --DirLen;
356     }
357   }
358 
359   if (!LocationLen) { // Relative path.
360     if (!DirLen)
361       return ".";
362     return std::string(".\\").append(FileName, 0, DirLen);
363   }
364 
365   return FileName.substr(0, LocationLen + DirLen);
366 }
367 
368 std::string TmpDir() {
369   std::string Tmp;
370   Tmp.resize(MAX_PATH + 1);
371   DWORD Size = GetTempPathA(Tmp.size(), &Tmp[0]);
372   if (Size == 0) {
373     Printf("Couldn't get Tmp path.\n");
374     exit(1);
375   }
376   Tmp.resize(Size);
377   return Tmp;
378 }
379 
380 bool IsInterestingCoverageFile(const std::string &FileName) {
381   if (FileName.find("Program Files") != std::string::npos)
382     return false;
383   if (FileName.find("compiler-rt\\lib\\") != std::string::npos)
384     return false; // sanitizer internal.
385   if (FileName == "<null>")
386     return false;
387   return true;
388 }
389 
390 void RawPrint(const char *Str) {
391   _write(2, Str, strlen(Str));
392 }
393 
394 void MkDir(const std::string &Path) {
395   if (CreateDirectoryA(Path.c_str(), nullptr)) return;
396   Printf("CreateDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
397          GetLastError());
398 }
399 
400 void RmDir(const std::string &Path) {
401   if (RemoveDirectoryA(Path.c_str())) return;
402   Printf("RemoveDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
403          GetLastError());
404 }
405 
406 const std::string &getDevNull() {
407   static const std::string devNull = "NUL";
408   return devNull;
409 }
410 
411 }  // namespace fuzzer
412 
413 #endif // LIBFUZZER_WINDOWS
414