Debian Codegraph @

tools/fuzzing/libfuzzer/FuzzerIOWindows.cpp

raw
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 "FuzzerPlatform.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 int ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
102 Vector<std::string> *V, bool TopDir) {
103 int Res;
104 auto E = GetEpoch(Dir);
105 if (Epoch)
106 if (E && *Epoch >= E) return 0;
107
108 std::string Path(Dir);
109 assert(!Path.empty());
110 if (Path.back() != '\\')
111 Path.push_back('\\');
112 Path.push_back('*');
113
114 // Get the first directory entry.
115 WIN32_FIND_DATAA FindInfo;
116 HANDLE FindHandle(FindFirstFileA(Path.c_str(), &FindInfo));
117 if (FindHandle == INVALID_HANDLE_VALUE)
118 {
119 if (GetLastError() == ERROR_FILE_NOT_FOUND)
120 return 0;
121 Printf("No such file or directory: %s; exiting\n", Dir.c_str());
122 return 1;
123 }
124
125 do {
126 std::string FileName = DirPlusFile(Dir, FindInfo.cFileName);
127
128 if (FindInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
129 size_t FilenameLen = strlen(FindInfo.cFileName);
130 if ((FilenameLen == 1 && FindInfo.cFileName[0] == '.') ||
131 (FilenameLen == 2 && FindInfo.cFileName[0] == '.' &&
132 FindInfo.cFileName[1] == '.'))
133 continue;
134
135 int Res = ListFilesInDirRecursive(FileName, Epoch, V, false);
136 if (Res != 0)
137 return Res;
138 }
139 else if (IsFile(FileName, FindInfo.dwFileAttributes))
140 V->push_back(FileName);
141 } while (FindNextFileA(FindHandle, &FindInfo));
142
143 DWORD LastError = GetLastError();
144 if (LastError != ERROR_NO_MORE_FILES)
145 Printf("FindNextFileA failed (Error code: %lu).\n", LastError);
146
147 FindClose(FindHandle);
148
149 if (Epoch && TopDir)
150 *Epoch = E;
151 return 0;
152 }
153
154
155 void IterateDirRecursive(const std::string &Dir,
156 void (*DirPreCallback)(const std::string &Dir),
157 void (*DirPostCallback)(const std::string &Dir),
158 void (*FileCallback)(const std::string &Dir)) {
159 // TODO(metzman): Implement ListFilesInDirRecursive via this function.
160 DirPreCallback(Dir);
161
162 DWORD DirAttrs = GetFileAttributesA(Dir.c_str());
163 if (!IsDir(DirAttrs)) return;
164
165 std::string TargetDir(Dir);
166 assert(!TargetDir.empty());
167 if (TargetDir.back() != '\\') TargetDir.push_back('\\');
168 TargetDir.push_back('*');
169
170 WIN32_FIND_DATAA FindInfo;
171 // Find the directory's first file.
172 HANDLE FindHandle = FindFirstFileA(TargetDir.c_str(), &FindInfo);
173 if (FindHandle == INVALID_HANDLE_VALUE) {
174 DWORD LastError = GetLastError();
175 if (LastError != ERROR_FILE_NOT_FOUND) {
176 // If the directory isn't empty, then something abnormal is going on.
177 Printf("FindFirstFileA failed for %s (Error code: %lu).\n", Dir.c_str(),
178 LastError);
179 }
180 return;
181 }
182
183 do {
184 std::string Path = DirPlusFile(Dir, FindInfo.cFileName);
185 DWORD PathAttrs = FindInfo.dwFileAttributes;
186 if (IsDir(PathAttrs)) {
187 // Is Path the current directory (".") or the parent ("..")?
188 if (strcmp(FindInfo.cFileName, ".") == 0 ||
189 strcmp(FindInfo.cFileName, "..") == 0)
190 continue;
191 IterateDirRecursive(Path, DirPreCallback, DirPostCallback, FileCallback);
192 } else if (PathAttrs != INVALID_FILE_ATTRIBUTES) {
193 FileCallback(Path);
194 }
195 } while (FindNextFileA(FindHandle, &FindInfo));
196
197 DWORD LastError = GetLastError();
198 if (LastError != ERROR_NO_MORE_FILES)
199 Printf("FindNextFileA failed for %s (Error code: %lu).\n", Dir.c_str(),
200 LastError);
201
202 FindClose(FindHandle);
203 DirPostCallback(Dir);
204 }
205
206 char GetSeparator() {
207 return '\\';
208 }
209
210 FILE* OpenFile(int Fd, const char* Mode) {
211 return _fdopen(Fd, Mode);
212 }
213
214 int CloseFile(int Fd) {
215 return _close(Fd);
216 }
217
218 int DuplicateFile(int Fd) {
219 return _dup(Fd);
220 }
221
222 void RemoveFile(const std::string &Path) {
223 _unlink(Path.c_str());
224 }
225
226 void RenameFile(const std::string &OldPath, const std::string &NewPath) {
227 rename(OldPath.c_str(), NewPath.c_str());
228 }
229
230 intptr_t GetHandleFromFd(int fd) {
231 return _get_osfhandle(fd);
232 }
233
234 static bool IsSeparator(char C) {
235 return C == '\\' || C == '/';
236 }
237
238 // Parse disk designators, like "C:\". If Relative == true, also accepts: "C:".
239 // Returns number of characters considered if successful.
240 static size_t ParseDrive(const std::string &FileName, const size_t Offset,
241 bool Relative = true) {
242 if (Offset + 1 >= FileName.size() || FileName[Offset + 1] != ':')
243 return 0;
244 if (Offset + 2 >= FileName.size() || !IsSeparator(FileName[Offset + 2])) {
245 if (!Relative) // Accept relative path?
246 return 0;
247 else
248 return 2;
249 }
250 return 3;
251 }
252
253 // Parse a file name, like: SomeFile.txt
254 // Returns number of characters considered if successful.
255 static size_t ParseFileName(const std::string &FileName, const size_t Offset) {
256 size_t Pos = Offset;
257 const size_t End = FileName.size();
258 for(; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
259 ;
260 return Pos - Offset;
261 }
262
263 // Parse a directory ending in separator, like: `SomeDir\`
264 // Returns number of characters considered if successful.
265 static size_t ParseDir(const std::string &FileName, const size_t Offset) {
266 size_t Pos = Offset;
267 const size_t End = FileName.size();
268 if (Pos >= End || IsSeparator(FileName[Pos]))
269 return 0;
270 for(; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
271 ;
272 if (Pos >= End)
273 return 0;
274 ++Pos; // Include separator.
275 return Pos - Offset;
276 }
277
278 // Parse a servername and share, like: `SomeServer\SomeShare\`
279 // Returns number of characters considered if successful.
280 static size_t ParseServerAndShare(const std::string &FileName,
281 const size_t Offset) {
282 size_t Pos = Offset, Res;
283 if (!(Res = ParseDir(FileName, Pos)))
284 return 0;
285 Pos += Res;
286 if (!(Res = ParseDir(FileName, Pos)))
287 return 0;
288 Pos += Res;
289 return Pos - Offset;
290 }
291
292 // Parse the given Ref string from the position Offset, to exactly match the given
293 // string Patt.
294 // Returns number of characters considered if successful.
295 static size_t ParseCustomString(const std::string &Ref, size_t Offset,
296 const char *Patt) {
297 size_t Len = strlen(Patt);
298 if (Offset + Len > Ref.size())
299 return 0;
300 return Ref.compare(Offset, Len, Patt) == 0 ? Len : 0;
301 }
302
303 // Parse a location, like:
304 // \\?\UNC\Server\Share\ \\?\C:\ \\Server\Share\ \ C:\ C:
305 // Returns number of characters considered if successful.
306 static size_t ParseLocation(const std::string &FileName) {
307 size_t Pos = 0, Res;
308
309 if ((Res = ParseCustomString(FileName, Pos, R"(\\?\)"))) {
310 Pos += Res;
311 if ((Res = ParseCustomString(FileName, Pos, R"(UNC\)"))) {
312 Pos += Res;
313 if ((Res = ParseServerAndShare(FileName, Pos)))
314 return Pos + Res;
315 return 0;
316 }
317 if ((Res = ParseDrive(FileName, Pos, false)))
318 return Pos + Res;
319 return 0;
320 }
321
322 if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
323 ++Pos;
324 if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
325 ++Pos;
326 if ((Res = ParseServerAndShare(FileName, Pos)))
327 return Pos + Res;
328 return 0;
329 }
330 return Pos;
331 }
332
333 if ((Res = ParseDrive(FileName, Pos)))
334 return Pos + Res;
335
336 return Pos;
337 }
338
339 std::string DirName(const std::string &FileName) {
340 size_t LocationLen = ParseLocation(FileName);
341 size_t DirLen = 0, Res;
342 while ((Res = ParseDir(FileName, LocationLen + DirLen)))
343 DirLen += Res;
344 size_t FileLen = ParseFileName(FileName, LocationLen + DirLen);
345
346 if (LocationLen + DirLen + FileLen != FileName.size()) {
347 Printf("DirName() failed for \"%s\", invalid path.\n", FileName.c_str());
348 exit(1);
349 }
350
351 if (DirLen) {
352 --DirLen; // Remove trailing separator.
353 if (!FileLen) { // Path ended in separator.
354 assert(DirLen);
355 // Remove file name from Dir.
356 while (DirLen && !IsSeparator(FileName[LocationLen + DirLen - 1]))
357 --DirLen;
358 if (DirLen) // Remove trailing separator.
359 --DirLen;
360 }
361 }
362
363 if (!LocationLen) { // Relative path.
364 if (!DirLen)
365 return ".";
366 return std::string(".\\").append(FileName, 0, DirLen);
367 }
368
369 return FileName.substr(0, LocationLen + DirLen);
370 }
371
372 std::string TmpDir() {
373 std::string Tmp;
374 Tmp.resize(MAX_PATH + 1);
375 DWORD Size = GetTempPathA(Tmp.size(), &Tmp[0]);
376 if (Size == 0) {
377 Printf("Couldn't get Tmp path.\n");
378 exit(1);
379 }
380 Tmp.resize(Size);
381 return Tmp;
382 }
383
384 bool IsInterestingCoverageFile(const std::string &FileName) {
385 if (FileName.find("Program Files") != std::string::npos)
386 return false;
387 if (FileName.find("compiler-rt\\lib\\") != std::string::npos)
388 return false; // sanitizer internal.
389 if (FileName == "<null>")
390 return false;
391 return true;
392 }
393
394 void RawPrint(const char *Str) {
395 _write(2, Str, strlen(Str));
396 }
397
398 void MkDir(const std::string &Path) {
399 if (CreateDirectoryA(Path.c_str(), nullptr)) return;
400 Printf("CreateDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
401 GetLastError());
402 }
403
404 void RmDir(const std::string &Path) {
405 if (RemoveDirectoryA(Path.c_str())) return;
406 Printf("RemoveDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
407 GetLastError());
408 }
409
410 const std::string &getDevNull() {
411 static const std::string devNull = "NUL";
412 return devNull;
413 }
414
415 } // namespace fuzzer
416
417 #endif // LIBFUZZER_WINDOWS