]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/lib/Support/Windows/Path.inc
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / lib / Support / Windows / Path.inc
1 //===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
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 //
9 // This file implements the Windows specific implementation of the Path API.
10 //
11 //===----------------------------------------------------------------------===//
12
13 //===----------------------------------------------------------------------===//
14 //=== WARNING: Implementation here must contain only generic Windows code that
15 //===          is guaranteed to work on *all* Windows variants.
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/ConvertUTF.h"
20 #include "llvm/Support/WindowsError.h"
21 #include <fcntl.h>
22 #include <io.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25
26 // These two headers must be included last, and make sure shlobj is required
27 // after Windows.h to make sure it picks up our definition of _WIN32_WINNT
28 #include "WindowsSupport.h"
29 #include <shellapi.h>
30 #include <shlobj.h>
31
32 #undef max
33
34 // MinGW doesn't define this.
35 #ifndef _ERRNO_T_DEFINED
36 #define _ERRNO_T_DEFINED
37 typedef int errno_t;
38 #endif
39
40 #ifdef _MSC_VER
41 # pragma comment(lib, "advapi32.lib")  // This provides CryptAcquireContextW.
42 # pragma comment(lib, "ole32.lib")     // This provides CoTaskMemFree
43 #endif
44
45 using namespace llvm;
46
47 using llvm::sys::windows::UTF8ToUTF16;
48 using llvm::sys::windows::CurCPToUTF16;
49 using llvm::sys::windows::UTF16ToUTF8;
50 using llvm::sys::path::widenPath;
51
52 static bool is_separator(const wchar_t value) {
53   switch (value) {
54   case L'\\':
55   case L'/':
56     return true;
57   default:
58     return false;
59   }
60 }
61
62 namespace llvm {
63 namespace sys  {
64 namespace path {
65
66 // Convert a UTF-8 path to UTF-16.  Also, if the absolute equivalent of the
67 // path is longer than CreateDirectory can tolerate, make it absolute and
68 // prefixed by '\\?\'.
69 std::error_code widenPath(const Twine &Path8,
70                           SmallVectorImpl<wchar_t> &Path16) {
71   const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
72
73   // Several operations would convert Path8 to SmallString; more efficient to
74   // do it once up front.
75   SmallString<128> Path8Str;
76   Path8.toVector(Path8Str);
77
78   // If we made this path absolute, how much longer would it get?
79   size_t CurPathLen;
80   if (llvm::sys::path::is_absolute(Twine(Path8Str)))
81     CurPathLen = 0; // No contribution from current_path needed.
82   else {
83     CurPathLen = ::GetCurrentDirectoryW(0, NULL);
84     if (CurPathLen == 0)
85       return mapWindowsError(::GetLastError());
86   }
87
88   // Would the absolute path be longer than our limit?
89   if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
90       !Path8Str.startswith("\\\\?\\")) {
91     SmallString<2*MAX_PATH> FullPath("\\\\?\\");
92     if (CurPathLen) {
93       SmallString<80> CurPath;
94       if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
95         return EC;
96       FullPath.append(CurPath);
97     }
98     // Traverse the requested path, canonicalizing . and .. (because the \\?\
99     // prefix is documented to treat them as real components).  Ignore
100     // separators, which can be returned from the iterator if the path has a
101     // drive name.  We don't need to call native() on the result since append()
102     // always attaches preferred_separator.
103     for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
104                                          E = llvm::sys::path::end(Path8Str);
105                                          I != E; ++I) {
106       if (I->size() == 1 && is_separator((*I)[0]))
107         continue;
108       if (I->size() == 1 && *I == ".")
109         continue;
110       if (I->size() == 2 && *I == "..")
111         llvm::sys::path::remove_filename(FullPath);
112       else
113         llvm::sys::path::append(FullPath, *I);
114     }
115     return UTF8ToUTF16(FullPath, Path16);
116   }
117
118   // Just use the caller's original path.
119   return UTF8ToUTF16(Path8Str, Path16);
120 }
121 } // end namespace path
122
123 namespace fs {
124
125 const file_t kInvalidFile = INVALID_HANDLE_VALUE;
126
127 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
128   SmallVector<wchar_t, MAX_PATH> PathName;
129   DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
130
131   // A zero return value indicates a failure other than insufficient space.
132   if (Size == 0)
133     return "";
134
135   // Insufficient space is determined by a return value equal to the size of
136   // the buffer passed in.
137   if (Size == PathName.capacity())
138     return "";
139
140   // On success, GetModuleFileNameW returns the number of characters written to
141   // the buffer not including the NULL terminator.
142   PathName.set_size(Size);
143
144   // Convert the result from UTF-16 to UTF-8.
145   SmallVector<char, MAX_PATH> PathNameUTF8;
146   if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
147     return "";
148
149   return std::string(PathNameUTF8.data());
150 }
151
152 UniqueID file_status::getUniqueID() const {
153   // The file is uniquely identified by the volume serial number along
154   // with the 64-bit file identifier.
155   uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
156                     static_cast<uint64_t>(FileIndexLow);
157
158   return UniqueID(VolumeSerialNumber, FileID);
159 }
160
161 ErrorOr<space_info> disk_space(const Twine &Path) {
162   ULARGE_INTEGER Avail, Total, Free;
163   if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
164     return mapWindowsError(::GetLastError());
165   space_info SpaceInfo;
166   SpaceInfo.capacity =
167       (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
168   SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
169   SpaceInfo.available =
170       (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
171   return SpaceInfo;
172 }
173
174 TimePoint<> basic_file_status::getLastAccessedTime() const {
175   FILETIME Time;
176   Time.dwLowDateTime = LastAccessedTimeLow;
177   Time.dwHighDateTime = LastAccessedTimeHigh;
178   return toTimePoint(Time);
179 }
180
181 TimePoint<> basic_file_status::getLastModificationTime() const {
182   FILETIME Time;
183   Time.dwLowDateTime = LastWriteTimeLow;
184   Time.dwHighDateTime = LastWriteTimeHigh;
185   return toTimePoint(Time);
186 }
187
188 uint32_t file_status::getLinkCount() const {
189   return NumLinks;
190 }
191
192 std::error_code current_path(SmallVectorImpl<char> &result) {
193   SmallVector<wchar_t, MAX_PATH> cur_path;
194   DWORD len = MAX_PATH;
195
196   do {
197     cur_path.reserve(len);
198     len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
199
200     // A zero return value indicates a failure other than insufficient space.
201     if (len == 0)
202       return mapWindowsError(::GetLastError());
203
204     // If there's insufficient space, the len returned is larger than the len
205     // given.
206   } while (len > cur_path.capacity());
207
208   // On success, GetCurrentDirectoryW returns the number of characters not
209   // including the null-terminator.
210   cur_path.set_size(len);
211   return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
212 }
213
214 std::error_code set_current_path(const Twine &path) {
215   // Convert to utf-16.
216   SmallVector<wchar_t, 128> wide_path;
217   if (std::error_code ec = widenPath(path, wide_path))
218     return ec;
219
220   if (!::SetCurrentDirectoryW(wide_path.begin()))
221     return mapWindowsError(::GetLastError());
222
223   return std::error_code();
224 }
225
226 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
227                                  perms Perms) {
228   SmallVector<wchar_t, 128> path_utf16;
229
230   if (std::error_code ec = widenPath(path, path_utf16))
231     return ec;
232
233   if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
234     DWORD LastError = ::GetLastError();
235     if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
236       return mapWindowsError(LastError);
237   }
238
239   return std::error_code();
240 }
241
242 // We can't use symbolic links for windows.
243 std::error_code create_link(const Twine &to, const Twine &from) {
244   // Convert to utf-16.
245   SmallVector<wchar_t, 128> wide_from;
246   SmallVector<wchar_t, 128> wide_to;
247   if (std::error_code ec = widenPath(from, wide_from))
248     return ec;
249   if (std::error_code ec = widenPath(to, wide_to))
250     return ec;
251
252   if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
253     return mapWindowsError(::GetLastError());
254
255   return std::error_code();
256 }
257
258 std::error_code create_hard_link(const Twine &to, const Twine &from) {
259   return create_link(to, from);
260 }
261
262 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
263   SmallVector<wchar_t, 128> path_utf16;
264
265   if (std::error_code ec = widenPath(path, path_utf16))
266     return ec;
267
268   // We don't know whether this is a file or a directory, and remove() can
269   // accept both. The usual way to delete a file or directory is to use one of
270   // the DeleteFile or RemoveDirectory functions, but that requires you to know
271   // which one it is. We could stat() the file to determine that, but that would
272   // cost us additional system calls, which can be slow in a directory
273   // containing a large number of files. So instead we call CreateFile directly.
274   // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
275   // file to be deleted once it is closed. We also use the flags
276   // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
277   // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
278   ScopedFileHandle h(::CreateFileW(
279       c_str(path_utf16), DELETE,
280       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
281       OPEN_EXISTING,
282       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
283           FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
284       NULL));
285   if (!h) {
286     std::error_code EC = mapWindowsError(::GetLastError());
287     if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
288       return EC;
289   }
290
291   return std::error_code();
292 }
293
294 static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
295                                          bool &Result) {
296   SmallVector<wchar_t, 128> VolumePath;
297   size_t Len = 128;
298   while (true) {
299     VolumePath.resize(Len);
300     BOOL Success =
301         ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
302
303     if (Success)
304       break;
305
306     DWORD Err = ::GetLastError();
307     if (Err != ERROR_INSUFFICIENT_BUFFER)
308       return mapWindowsError(Err);
309
310     Len *= 2;
311   }
312   // If the output buffer has exactly enough space for the path name, but not
313   // the null terminator, it will leave the output unterminated.  Push a null
314   // terminator onto the end to ensure that this never happens.
315   VolumePath.push_back(L'\0');
316   VolumePath.set_size(wcslen(VolumePath.data()));
317   const wchar_t *P = VolumePath.data();
318
319   UINT Type = ::GetDriveTypeW(P);
320   switch (Type) {
321   case DRIVE_FIXED:
322     Result = true;
323     return std::error_code();
324   case DRIVE_REMOTE:
325   case DRIVE_CDROM:
326   case DRIVE_RAMDISK:
327   case DRIVE_REMOVABLE:
328     Result = false;
329     return std::error_code();
330   default:
331     return make_error_code(errc::no_such_file_or_directory);
332   }
333   llvm_unreachable("Unreachable!");
334 }
335
336 std::error_code is_local(const Twine &path, bool &result) {
337   if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
338     return make_error_code(errc::no_such_file_or_directory);
339
340   SmallString<128> Storage;
341   StringRef P = path.toStringRef(Storage);
342
343   // Convert to utf-16.
344   SmallVector<wchar_t, 128> WidePath;
345   if (std::error_code ec = widenPath(P, WidePath))
346     return ec;
347   return is_local_internal(WidePath, result);
348 }
349
350 static std::error_code realPathFromHandle(HANDLE H,
351                                           SmallVectorImpl<wchar_t> &Buffer) {
352   DWORD CountChars = ::GetFinalPathNameByHandleW(
353       H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
354   if (CountChars > Buffer.capacity()) {
355     // The buffer wasn't big enough, try again.  In this case the return value
356     // *does* indicate the size of the null terminator.
357     Buffer.reserve(CountChars);
358     CountChars = ::GetFinalPathNameByHandleW(
359         H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
360   }
361   if (CountChars == 0)
362     return mapWindowsError(GetLastError());
363   Buffer.set_size(CountChars);
364   return std::error_code();
365 }
366
367 static std::error_code realPathFromHandle(HANDLE H,
368                                           SmallVectorImpl<char> &RealPath) {
369   RealPath.clear();
370   SmallVector<wchar_t, MAX_PATH> Buffer;
371   if (std::error_code EC = realPathFromHandle(H, Buffer))
372     return EC;
373
374   const wchar_t *Data = Buffer.data();
375   DWORD CountChars = Buffer.size();
376   if (CountChars >= 4) {
377     if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
378       CountChars -= 4;
379       Data += 4;
380     }
381   }
382
383   // Convert the result from UTF-16 to UTF-8.
384   return UTF16ToUTF8(Data, CountChars, RealPath);
385 }
386
387 std::error_code is_local(int FD, bool &Result) {
388   SmallVector<wchar_t, 128> FinalPath;
389   HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
390
391   if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
392     return EC;
393
394   return is_local_internal(FinalPath, Result);
395 }
396
397 static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
398   FILE_DISPOSITION_INFO Disposition;
399   Disposition.DeleteFile = Delete;
400   if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
401                                   sizeof(Disposition)))
402     return mapWindowsError(::GetLastError());
403   return std::error_code();
404 }
405
406 static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
407                                        bool ReplaceIfExists) {
408   SmallVector<wchar_t, 0> ToWide;
409   if (auto EC = widenPath(To, ToWide))
410     return EC;
411
412   std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
413                                   (ToWide.size() * sizeof(wchar_t)));
414   FILE_RENAME_INFO &RenameInfo =
415       *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
416   RenameInfo.ReplaceIfExists = ReplaceIfExists;
417   RenameInfo.RootDirectory = 0;
418   RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
419   std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
420
421   SetLastError(ERROR_SUCCESS);
422   if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
423                                   RenameInfoBuf.size())) {
424     unsigned Error = GetLastError();
425     if (Error == ERROR_SUCCESS)
426       Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
427     return mapWindowsError(Error);
428   }
429
430   return std::error_code();
431 }
432
433 static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
434   SmallVector<wchar_t, 128> WideTo;
435   if (std::error_code EC = widenPath(To, WideTo))
436     return EC;
437
438   // We normally expect this loop to succeed after a few iterations. If it
439   // requires more than 200 tries, it's more likely that the failures are due to
440   // a true error, so stop trying.
441   for (unsigned Retry = 0; Retry != 200; ++Retry) {
442     auto EC = rename_internal(FromHandle, To, true);
443
444     if (EC ==
445         std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
446       // Wine doesn't support SetFileInformationByHandle in rename_internal.
447       // Fall back to MoveFileEx.
448       SmallVector<wchar_t, MAX_PATH> WideFrom;
449       if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
450         return EC2;
451       if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
452                         MOVEFILE_REPLACE_EXISTING))
453         return std::error_code();
454       return mapWindowsError(GetLastError());
455     }
456
457     if (!EC || EC != errc::permission_denied)
458       return EC;
459
460     // The destination file probably exists and is currently open in another
461     // process, either because the file was opened without FILE_SHARE_DELETE or
462     // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
463     // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
464     // to arrange for the destination file to be deleted when the other process
465     // closes it.
466     ScopedFileHandle ToHandle(
467         ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
468                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
469                       NULL, OPEN_EXISTING,
470                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
471     if (!ToHandle) {
472       auto EC = mapWindowsError(GetLastError());
473       // Another process might have raced with us and moved the existing file
474       // out of the way before we had a chance to open it. If that happens, try
475       // to rename the source file again.
476       if (EC == errc::no_such_file_or_directory)
477         continue;
478       return EC;
479     }
480
481     BY_HANDLE_FILE_INFORMATION FI;
482     if (!GetFileInformationByHandle(ToHandle, &FI))
483       return mapWindowsError(GetLastError());
484
485     // Try to find a unique new name for the destination file.
486     for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
487       std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
488       if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
489         if (EC == errc::file_exists || EC == errc::permission_denied) {
490           // Again, another process might have raced with us and moved the file
491           // before we could move it. Check whether this is the case, as it
492           // might have caused the permission denied error. If that was the
493           // case, we don't need to move it ourselves.
494           ScopedFileHandle ToHandle2(::CreateFileW(
495               WideTo.begin(), 0,
496               FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
497               OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
498           if (!ToHandle2) {
499             auto EC = mapWindowsError(GetLastError());
500             if (EC == errc::no_such_file_or_directory)
501               break;
502             return EC;
503           }
504           BY_HANDLE_FILE_INFORMATION FI2;
505           if (!GetFileInformationByHandle(ToHandle2, &FI2))
506             return mapWindowsError(GetLastError());
507           if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
508               FI.nFileIndexLow != FI2.nFileIndexLow ||
509               FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
510             break;
511           continue;
512         }
513         return EC;
514       }
515       break;
516     }
517
518     // Okay, the old destination file has probably been moved out of the way at
519     // this point, so try to rename the source file again. Still, another
520     // process might have raced with us to create and open the destination
521     // file, so we need to keep doing this until we succeed.
522   }
523
524   // The most likely root cause.
525   return errc::permission_denied;
526 }
527
528 static std::error_code rename_fd(int FromFD, const Twine &To) {
529   HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
530   return rename_handle(FromHandle, To);
531 }
532
533 std::error_code rename(const Twine &From, const Twine &To) {
534   // Convert to utf-16.
535   SmallVector<wchar_t, 128> WideFrom;
536   if (std::error_code EC = widenPath(From, WideFrom))
537     return EC;
538
539   ScopedFileHandle FromHandle;
540   // Retry this a few times to defeat badly behaved file system scanners.
541   for (unsigned Retry = 0; Retry != 200; ++Retry) {
542     if (Retry != 0)
543       ::Sleep(10);
544     FromHandle =
545         ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
546                       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
547                       NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
548     if (FromHandle)
549       break;
550   }
551   if (!FromHandle)
552     return mapWindowsError(GetLastError());
553
554   return rename_handle(FromHandle, To);
555 }
556
557 std::error_code resize_file(int FD, uint64_t Size) {
558 #ifdef HAVE__CHSIZE_S
559   errno_t error = ::_chsize_s(FD, Size);
560 #else
561   errno_t error = ::_chsize(FD, Size);
562 #endif
563   return std::error_code(error, std::generic_category());
564 }
565
566 std::error_code access(const Twine &Path, AccessMode Mode) {
567   SmallVector<wchar_t, 128> PathUtf16;
568
569   if (std::error_code EC = widenPath(Path, PathUtf16))
570     return EC;
571
572   DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
573
574   if (Attributes == INVALID_FILE_ATTRIBUTES) {
575     // See if the file didn't actually exist.
576     DWORD LastError = ::GetLastError();
577     if (LastError != ERROR_FILE_NOT_FOUND &&
578         LastError != ERROR_PATH_NOT_FOUND)
579       return mapWindowsError(LastError);
580     return errc::no_such_file_or_directory;
581   }
582
583   if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
584     return errc::permission_denied;
585
586   return std::error_code();
587 }
588
589 bool can_execute(const Twine &Path) {
590   return !access(Path, AccessMode::Execute) ||
591          !access(Path + ".exe", AccessMode::Execute);
592 }
593
594 bool equivalent(file_status A, file_status B) {
595   assert(status_known(A) && status_known(B));
596   return A.FileIndexHigh         == B.FileIndexHigh &&
597          A.FileIndexLow          == B.FileIndexLow &&
598          A.FileSizeHigh          == B.FileSizeHigh &&
599          A.FileSizeLow           == B.FileSizeLow &&
600          A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
601          A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
602          A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
603          A.LastWriteTimeLow      == B.LastWriteTimeLow &&
604          A.VolumeSerialNumber    == B.VolumeSerialNumber;
605 }
606
607 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
608   file_status fsA, fsB;
609   if (std::error_code ec = status(A, fsA))
610     return ec;
611   if (std::error_code ec = status(B, fsB))
612     return ec;
613   result = equivalent(fsA, fsB);
614   return std::error_code();
615 }
616
617 static bool isReservedName(StringRef path) {
618   // This list of reserved names comes from MSDN, at:
619   // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
620   static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
621                                                 "com1", "com2", "com3", "com4",
622                                                 "com5", "com6", "com7", "com8",
623                                                 "com9", "lpt1", "lpt2", "lpt3",
624                                                 "lpt4", "lpt5", "lpt6", "lpt7",
625                                                 "lpt8", "lpt9" };
626
627   // First, check to see if this is a device namespace, which always
628   // starts with \\.\, since device namespaces are not legal file paths.
629   if (path.startswith("\\\\.\\"))
630     return true;
631
632   // Then compare against the list of ancient reserved names.
633   for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
634     if (path.equals_lower(sReservedNames[i]))
635       return true;
636   }
637
638   // The path isn't what we consider reserved.
639   return false;
640 }
641
642 static file_type file_type_from_attrs(DWORD Attrs) {
643   return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
644                                             : file_type::regular_file;
645 }
646
647 static perms perms_from_attrs(DWORD Attrs) {
648   return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
649 }
650
651 static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
652   if (FileHandle == INVALID_HANDLE_VALUE)
653     goto handle_status_error;
654
655   switch (::GetFileType(FileHandle)) {
656   default:
657     llvm_unreachable("Don't know anything about this file type");
658   case FILE_TYPE_UNKNOWN: {
659     DWORD Err = ::GetLastError();
660     if (Err != NO_ERROR)
661       return mapWindowsError(Err);
662     Result = file_status(file_type::type_unknown);
663     return std::error_code();
664   }
665   case FILE_TYPE_DISK:
666     break;
667   case FILE_TYPE_CHAR:
668     Result = file_status(file_type::character_file);
669     return std::error_code();
670   case FILE_TYPE_PIPE:
671     Result = file_status(file_type::fifo_file);
672     return std::error_code();
673   }
674
675   BY_HANDLE_FILE_INFORMATION Info;
676   if (!::GetFileInformationByHandle(FileHandle, &Info))
677     goto handle_status_error;
678
679   Result = file_status(
680       file_type_from_attrs(Info.dwFileAttributes),
681       perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
682       Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
683       Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
684       Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
685       Info.nFileIndexHigh, Info.nFileIndexLow);
686   return std::error_code();
687
688 handle_status_error:
689   DWORD LastError = ::GetLastError();
690   if (LastError == ERROR_FILE_NOT_FOUND ||
691       LastError == ERROR_PATH_NOT_FOUND)
692     Result = file_status(file_type::file_not_found);
693   else if (LastError == ERROR_SHARING_VIOLATION)
694     Result = file_status(file_type::type_unknown);
695   else
696     Result = file_status(file_type::status_error);
697   return mapWindowsError(LastError);
698 }
699
700 std::error_code status(const Twine &path, file_status &result, bool Follow) {
701   SmallString<128> path_storage;
702   SmallVector<wchar_t, 128> path_utf16;
703
704   StringRef path8 = path.toStringRef(path_storage);
705   if (isReservedName(path8)) {
706     result = file_status(file_type::character_file);
707     return std::error_code();
708   }
709
710   if (std::error_code ec = widenPath(path8, path_utf16))
711     return ec;
712
713   DWORD attr = ::GetFileAttributesW(path_utf16.begin());
714   if (attr == INVALID_FILE_ATTRIBUTES)
715     return getStatus(INVALID_HANDLE_VALUE, result);
716
717   DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
718   // Handle reparse points.
719   if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
720     Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
721
722   ScopedFileHandle h(
723       ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
724                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
725                     NULL, OPEN_EXISTING, Flags, 0));
726   if (!h)
727     return getStatus(INVALID_HANDLE_VALUE, result);
728
729   return getStatus(h, result);
730 }
731
732 std::error_code status(int FD, file_status &Result) {
733   HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
734   return getStatus(FileHandle, Result);
735 }
736
737 std::error_code status(file_t FileHandle, file_status &Result) {
738   return getStatus(FileHandle, Result);
739 }
740
741 unsigned getUmask() {
742   return 0;
743 }
744
745 std::error_code setPermissions(const Twine &Path, perms Permissions) {
746   SmallVector<wchar_t, 128> PathUTF16;
747   if (std::error_code EC = widenPath(Path, PathUTF16))
748     return EC;
749
750   DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
751   if (Attributes == INVALID_FILE_ATTRIBUTES)
752     return mapWindowsError(GetLastError());
753
754   // There are many Windows file attributes that are not to do with the file
755   // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
756   // them.
757   if (Permissions & all_write) {
758     Attributes &= ~FILE_ATTRIBUTE_READONLY;
759     if (Attributes == 0)
760       // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
761       Attributes |= FILE_ATTRIBUTE_NORMAL;
762   }
763   else {
764     Attributes |= FILE_ATTRIBUTE_READONLY;
765     // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
766     // remove it, if it is present.
767     Attributes &= ~FILE_ATTRIBUTE_NORMAL;
768   }
769
770   if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
771     return mapWindowsError(GetLastError());
772
773   return std::error_code();
774 }
775
776 std::error_code setPermissions(int FD, perms Permissions) {
777   // FIXME Not implemented.
778   return std::make_error_code(std::errc::not_supported);
779 }
780
781 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
782                                                  TimePoint<> ModificationTime) {
783   FILETIME AccessFT = toFILETIME(AccessTime);
784   FILETIME ModifyFT = toFILETIME(ModificationTime);
785   HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
786   if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
787     return mapWindowsError(::GetLastError());
788   return std::error_code();
789 }
790
791 std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
792                                          uint64_t Offset, mapmode Mode) {
793   this->Mode = Mode;
794   if (OrigFileHandle == INVALID_HANDLE_VALUE)
795     return make_error_code(errc::bad_file_descriptor);
796
797   DWORD flprotect;
798   switch (Mode) {
799   case readonly:  flprotect = PAGE_READONLY; break;
800   case readwrite: flprotect = PAGE_READWRITE; break;
801   case priv:      flprotect = PAGE_WRITECOPY; break;
802   }
803
804   HANDLE FileMappingHandle =
805       ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
806                            Hi_32(Size),
807                            Lo_32(Size),
808                            0);
809   if (FileMappingHandle == NULL) {
810     std::error_code ec = mapWindowsError(GetLastError());
811     return ec;
812   }
813
814   DWORD dwDesiredAccess;
815   switch (Mode) {
816   case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
817   case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
818   case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
819   }
820   Mapping = ::MapViewOfFile(FileMappingHandle,
821                             dwDesiredAccess,
822                             Offset >> 32,
823                             Offset & 0xffffffff,
824                             Size);
825   if (Mapping == NULL) {
826     std::error_code ec = mapWindowsError(GetLastError());
827     ::CloseHandle(FileMappingHandle);
828     return ec;
829   }
830
831   if (Size == 0) {
832     MEMORY_BASIC_INFORMATION mbi;
833     SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
834     if (Result == 0) {
835       std::error_code ec = mapWindowsError(GetLastError());
836       ::UnmapViewOfFile(Mapping);
837       ::CloseHandle(FileMappingHandle);
838       return ec;
839     }
840     Size = mbi.RegionSize;
841   }
842
843   // Close the file mapping handle, as it's kept alive by the file mapping. But
844   // neither the file mapping nor the file mapping handle keep the file handle
845   // alive, so we need to keep a reference to the file in case all other handles
846   // are closed and the file is deleted, which may cause invalid data to be read
847   // from the file.
848   ::CloseHandle(FileMappingHandle);
849   if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
850                          ::GetCurrentProcess(), &FileHandle, 0, 0,
851                          DUPLICATE_SAME_ACCESS)) {
852     std::error_code ec = mapWindowsError(GetLastError());
853     ::UnmapViewOfFile(Mapping);
854     return ec;
855   }
856
857   return std::error_code();
858 }
859
860 mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
861                                        size_t length, uint64_t offset,
862                                        std::error_code &ec)
863     : Size(length), Mapping() {
864   ec = init(fd, offset, mode);
865   if (ec)
866     Mapping = 0;
867 }
868
869 static bool hasFlushBufferKernelBug() {
870   static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
871   return Ret;
872 }
873
874 static bool isEXE(StringRef Magic) {
875   static const char PEMagic[] = {'P', 'E', '\0', '\0'};
876   if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
877     uint32_t off = read32le(Magic.data() + 0x3c);
878     // PE/COFF file, either EXE or DLL.
879     if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
880       return true;
881   }
882   return false;
883 }
884
885 mapped_file_region::~mapped_file_region() {
886   if (Mapping) {
887
888     bool Exe = isEXE(StringRef((char *)Mapping, Size));
889
890     ::UnmapViewOfFile(Mapping);
891
892     if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
893       // There is a Windows kernel bug, the exact trigger conditions of which
894       // are not well understood.  When triggered, dirty pages are not properly
895       // flushed and subsequent process's attempts to read a file can return
896       // invalid data.  Calling FlushFileBuffers on the write handle is
897       // sufficient to ensure that this bug is not triggered.
898       // The bug only occurs when writing an executable and executing it right
899       // after, under high I/O pressure.
900       ::FlushFileBuffers(FileHandle);
901     }
902
903     ::CloseHandle(FileHandle);
904   }
905 }
906
907 size_t mapped_file_region::size() const {
908   assert(Mapping && "Mapping failed but used anyway!");
909   return Size;
910 }
911
912 char *mapped_file_region::data() const {
913   assert(Mapping && "Mapping failed but used anyway!");
914   return reinterpret_cast<char*>(Mapping);
915 }
916
917 const char *mapped_file_region::const_data() const {
918   assert(Mapping && "Mapping failed but used anyway!");
919   return reinterpret_cast<const char*>(Mapping);
920 }
921
922 int mapped_file_region::alignment() {
923   SYSTEM_INFO SysInfo;
924   ::GetSystemInfo(&SysInfo);
925   return SysInfo.dwAllocationGranularity;
926 }
927
928 static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
929   return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
930                            perms_from_attrs(FindData->dwFileAttributes),
931                            FindData->ftLastAccessTime.dwHighDateTime,
932                            FindData->ftLastAccessTime.dwLowDateTime,
933                            FindData->ftLastWriteTime.dwHighDateTime,
934                            FindData->ftLastWriteTime.dwLowDateTime,
935                            FindData->nFileSizeHigh, FindData->nFileSizeLow);
936 }
937
938 std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
939                                                      StringRef Path,
940                                                      bool FollowSymlinks) {
941   SmallVector<wchar_t, 128> PathUTF16;
942
943   if (std::error_code EC = widenPath(Path, PathUTF16))
944     return EC;
945
946   // Convert path to the format that Windows is happy with.
947   if (PathUTF16.size() > 0 &&
948       !is_separator(PathUTF16[Path.size() - 1]) &&
949       PathUTF16[Path.size() - 1] != L':') {
950     PathUTF16.push_back(L'\\');
951     PathUTF16.push_back(L'*');
952   } else {
953     PathUTF16.push_back(L'*');
954   }
955
956   //  Get the first directory entry.
957   WIN32_FIND_DATAW FirstFind;
958   ScopedFindHandle FindHandle(::FindFirstFileExW(
959       c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
960       NULL, FIND_FIRST_EX_LARGE_FETCH));
961   if (!FindHandle)
962     return mapWindowsError(::GetLastError());
963
964   size_t FilenameLen = ::wcslen(FirstFind.cFileName);
965   while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
966          (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
967                               FirstFind.cFileName[1] == L'.'))
968     if (!::FindNextFileW(FindHandle, &FirstFind)) {
969       DWORD LastError = ::GetLastError();
970       // Check for end.
971       if (LastError == ERROR_NO_MORE_FILES)
972         return detail::directory_iterator_destruct(IT);
973       return mapWindowsError(LastError);
974     } else
975       FilenameLen = ::wcslen(FirstFind.cFileName);
976
977   // Construct the current directory entry.
978   SmallString<128> DirectoryEntryNameUTF8;
979   if (std::error_code EC =
980           UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
981                       DirectoryEntryNameUTF8))
982     return EC;
983
984   IT.IterationHandle = intptr_t(FindHandle.take());
985   SmallString<128> DirectoryEntryPath(Path);
986   path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
987   IT.CurrentEntry =
988       directory_entry(DirectoryEntryPath, FollowSymlinks,
989                       file_type_from_attrs(FirstFind.dwFileAttributes),
990                       status_from_find_data(&FirstFind));
991
992   return std::error_code();
993 }
994
995 std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
996   if (IT.IterationHandle != 0)
997     // Closes the handle if it's valid.
998     ScopedFindHandle close(HANDLE(IT.IterationHandle));
999   IT.IterationHandle = 0;
1000   IT.CurrentEntry = directory_entry();
1001   return std::error_code();
1002 }
1003
1004 std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1005   WIN32_FIND_DATAW FindData;
1006   if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1007     DWORD LastError = ::GetLastError();
1008     // Check for end.
1009     if (LastError == ERROR_NO_MORE_FILES)
1010       return detail::directory_iterator_destruct(IT);
1011     return mapWindowsError(LastError);
1012   }
1013
1014   size_t FilenameLen = ::wcslen(FindData.cFileName);
1015   if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1016       (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1017                            FindData.cFileName[1] == L'.'))
1018     return directory_iterator_increment(IT);
1019
1020   SmallString<128> DirectoryEntryPathUTF8;
1021   if (std::error_code EC =
1022           UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1023                       DirectoryEntryPathUTF8))
1024     return EC;
1025
1026   IT.CurrentEntry.replace_filename(
1027       Twine(DirectoryEntryPathUTF8),
1028       file_type_from_attrs(FindData.dwFileAttributes),
1029       status_from_find_data(&FindData));
1030   return std::error_code();
1031 }
1032
1033 ErrorOr<basic_file_status> directory_entry::status() const {
1034   return Status;
1035 }
1036
1037 static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1038                                       OpenFlags Flags) {
1039   int CrtOpenFlags = 0;
1040   if (Flags & OF_Append)
1041     CrtOpenFlags |= _O_APPEND;
1042
1043   if (Flags & OF_Text)
1044     CrtOpenFlags |= _O_TEXT;
1045
1046   ResultFD = -1;
1047   if (!H)
1048     return errorToErrorCode(H.takeError());
1049
1050   ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1051   if (ResultFD == -1) {
1052     ::CloseHandle(*H);
1053     return mapWindowsError(ERROR_INVALID_HANDLE);
1054   }
1055   return std::error_code();
1056 }
1057
1058 static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1059   // This is a compatibility hack.  Really we should respect the creation
1060   // disposition, but a lot of old code relied on the implicit assumption that
1061   // OF_Append implied it would open an existing file.  Since the disposition is
1062   // now explicit and defaults to CD_CreateAlways, this assumption would cause
1063   // any usage of OF_Append to append to a new file, even if the file already
1064   // existed.  A better solution might have two new creation dispositions:
1065   // CD_AppendAlways and CD_AppendNew.  This would also address the problem of
1066   // OF_Append being used on a read-only descriptor, which doesn't make sense.
1067   if (Flags & OF_Append)
1068     return OPEN_ALWAYS;
1069
1070   switch (Disp) {
1071   case CD_CreateAlways:
1072     return CREATE_ALWAYS;
1073   case CD_CreateNew:
1074     return CREATE_NEW;
1075   case CD_OpenAlways:
1076     return OPEN_ALWAYS;
1077   case CD_OpenExisting:
1078     return OPEN_EXISTING;
1079   }
1080   llvm_unreachable("unreachable!");
1081 }
1082
1083 static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1084   DWORD Result = 0;
1085   if (Access & FA_Read)
1086     Result |= GENERIC_READ;
1087   if (Access & FA_Write)
1088     Result |= GENERIC_WRITE;
1089   if (Flags & OF_Delete)
1090     Result |= DELETE;
1091   if (Flags & OF_UpdateAtime)
1092     Result |= FILE_WRITE_ATTRIBUTES;
1093   return Result;
1094 }
1095
1096 static std::error_code openNativeFileInternal(const Twine &Name,
1097                                               file_t &ResultFile, DWORD Disp,
1098                                               DWORD Access, DWORD Flags,
1099                                               bool Inherit = false) {
1100   SmallVector<wchar_t, 128> PathUTF16;
1101   if (std::error_code EC = widenPath(Name, PathUTF16))
1102     return EC;
1103
1104   SECURITY_ATTRIBUTES SA;
1105   SA.nLength = sizeof(SA);
1106   SA.lpSecurityDescriptor = nullptr;
1107   SA.bInheritHandle = Inherit;
1108
1109   HANDLE H =
1110       ::CreateFileW(PathUTF16.begin(), Access,
1111                     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1112                     Disp, Flags, NULL);
1113   if (H == INVALID_HANDLE_VALUE) {
1114     DWORD LastError = ::GetLastError();
1115     std::error_code EC = mapWindowsError(LastError);
1116     // Provide a better error message when trying to open directories.
1117     // This only runs if we failed to open the file, so there is probably
1118     // no performances issues.
1119     if (LastError != ERROR_ACCESS_DENIED)
1120       return EC;
1121     if (is_directory(Name))
1122       return make_error_code(errc::is_a_directory);
1123     return EC;
1124   }
1125   ResultFile = H;
1126   return std::error_code();
1127 }
1128
1129 Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1130                                 FileAccess Access, OpenFlags Flags,
1131                                 unsigned Mode) {
1132   // Verify that we don't have both "append" and "excl".
1133   assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1134          "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1135
1136   DWORD NativeDisp = nativeDisposition(Disp, Flags);
1137   DWORD NativeAccess = nativeAccess(Access, Flags);
1138
1139   bool Inherit = false;
1140   if (Flags & OF_ChildInherit)
1141     Inherit = true;
1142
1143   file_t Result;
1144   std::error_code EC = openNativeFileInternal(
1145       Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1146   if (EC)
1147     return errorCodeToError(EC);
1148
1149   if (Flags & OF_UpdateAtime) {
1150     FILETIME FileTime;
1151     SYSTEMTIME SystemTime;
1152     GetSystemTime(&SystemTime);
1153     if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1154         SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1155       DWORD LastError = ::GetLastError();
1156       ::CloseHandle(Result);
1157       return errorCodeToError(mapWindowsError(LastError));
1158     }
1159   }
1160
1161   if (Flags & OF_Delete) {
1162     if ((EC = setDeleteDisposition(Result, true))) {
1163       ::CloseHandle(Result);
1164       return errorCodeToError(EC);
1165     }
1166   }
1167   return Result;
1168 }
1169
1170 std::error_code openFile(const Twine &Name, int &ResultFD,
1171                          CreationDisposition Disp, FileAccess Access,
1172                          OpenFlags Flags, unsigned int Mode) {
1173   Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1174   if (!Result)
1175     return errorToErrorCode(Result.takeError());
1176
1177   return nativeFileToFd(*Result, ResultFD, Flags);
1178 }
1179
1180 static std::error_code directoryRealPath(const Twine &Name,
1181                                          SmallVectorImpl<char> &RealPath) {
1182   file_t File;
1183   std::error_code EC = openNativeFileInternal(
1184       Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1185   if (EC)
1186     return EC;
1187
1188   EC = realPathFromHandle(File, RealPath);
1189   ::CloseHandle(File);
1190   return EC;
1191 }
1192
1193 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1194                                 OpenFlags Flags,
1195                                 SmallVectorImpl<char> *RealPath) {
1196   Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1197   return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1198 }
1199
1200 Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1201                                        SmallVectorImpl<char> *RealPath) {
1202   Expected<file_t> Result =
1203       openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1204
1205   // Fetch the real name of the file, if the user asked
1206   if (Result && RealPath)
1207     realPathFromHandle(*Result, *RealPath);
1208
1209   return Result;
1210 }
1211
1212 file_t convertFDToNativeFile(int FD) {
1213   return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1214 }
1215
1216 file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1217 file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1218 file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1219
1220 std::error_code readNativeFileImpl(file_t FileHandle, char *BufPtr, size_t BytesToRead,
1221                                    size_t *BytesRead, OVERLAPPED *Overlap) {
1222   // ReadFile can only read 2GB at a time. The caller should check the number of
1223   // bytes and read in a loop until termination.
1224   DWORD BytesToRead32 =
1225       std::min(size_t(std::numeric_limits<DWORD>::max()), BytesToRead);
1226   DWORD BytesRead32 = 0;
1227   bool Success =
1228       ::ReadFile(FileHandle, BufPtr, BytesToRead32, &BytesRead32, Overlap);
1229   *BytesRead = BytesRead32;
1230   if (!Success) {
1231     DWORD Err = ::GetLastError();
1232     // Pipe EOF is not an error.
1233     if (Err == ERROR_BROKEN_PIPE)
1234       return std::error_code();
1235     return mapWindowsError(Err);
1236   }
1237   return std::error_code();
1238 }
1239
1240 std::error_code readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf,
1241                                size_t *BytesRead) {
1242   return readNativeFileImpl(FileHandle, Buf.data(), Buf.size(), BytesRead,
1243                             /*Overlap=*/nullptr);
1244 }
1245
1246 std::error_code readNativeFileSlice(file_t FileHandle,
1247                                     MutableArrayRef<char> Buf, size_t Offset) {
1248   char *BufPtr = Buf.data();
1249   size_t BytesLeft = Buf.size();
1250
1251   while (BytesLeft) {
1252     uint64_t CurOff = Buf.size() - BytesLeft + Offset;
1253     OVERLAPPED Overlapped = {};
1254     Overlapped.Offset = uint32_t(CurOff);
1255     Overlapped.OffsetHigh = uint32_t(uint64_t(CurOff) >> 32);
1256
1257     size_t BytesRead = 0;
1258     if (auto EC = readNativeFileImpl(FileHandle, BufPtr, BytesLeft, &BytesRead,
1259                                      &Overlapped))
1260       return EC;
1261
1262     // Once we reach EOF, zero the remaining bytes in the buffer.
1263     if (BytesRead == 0) {
1264       memset(BufPtr, 0, BytesLeft);
1265       break;
1266     }
1267     BytesLeft -= BytesRead;
1268     BufPtr += BytesRead;
1269   }
1270   return std::error_code();
1271 }
1272
1273 std::error_code closeFile(file_t &F) {
1274   file_t TmpF = F;
1275   F = kInvalidFile;
1276   if (!::CloseHandle(TmpF))
1277     return mapWindowsError(::GetLastError());
1278   return std::error_code();
1279 }
1280
1281 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1282   // Convert to utf-16.
1283   SmallVector<wchar_t, 128> Path16;
1284   std::error_code EC = widenPath(path, Path16);
1285   if (EC && !IgnoreErrors)
1286     return EC;
1287
1288   // SHFileOperation() accepts a list of paths, and so must be double null-
1289   // terminated to indicate the end of the list.  The buffer is already null
1290   // terminated, but since that null character is not considered part of the
1291   // vector's size, pushing another one will just consume that byte.  So we
1292   // need to push 2 null terminators.
1293   Path16.push_back(0);
1294   Path16.push_back(0);
1295
1296   SHFILEOPSTRUCTW shfos = {};
1297   shfos.wFunc = FO_DELETE;
1298   shfos.pFrom = Path16.data();
1299   shfos.fFlags = FOF_NO_UI;
1300
1301   int result = ::SHFileOperationW(&shfos);
1302   if (result != 0 && !IgnoreErrors)
1303     return mapWindowsError(result);
1304   return std::error_code();
1305 }
1306
1307 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1308   // Path does not begin with a tilde expression.
1309   if (Path.empty() || Path[0] != '~')
1310     return;
1311
1312   StringRef PathStr(Path.begin(), Path.size());
1313   PathStr = PathStr.drop_front();
1314   StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1315
1316   if (!Expr.empty()) {
1317     // This is probably a ~username/ expression.  Don't support this on Windows.
1318     return;
1319   }
1320
1321   SmallString<128> HomeDir;
1322   if (!path::home_directory(HomeDir)) {
1323     // For some reason we couldn't get the home directory.  Just exit.
1324     return;
1325   }
1326
1327   // Overwrite the first character and insert the rest.
1328   Path[0] = HomeDir[0];
1329   Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1330 }
1331
1332 void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1333   dest.clear();
1334   if (path.isTriviallyEmpty())
1335     return;
1336
1337   path.toVector(dest);
1338   expandTildeExpr(dest);
1339
1340   return;
1341 }
1342
1343 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1344                           bool expand_tilde) {
1345   dest.clear();
1346   if (path.isTriviallyEmpty())
1347     return std::error_code();
1348
1349   if (expand_tilde) {
1350     SmallString<128> Storage;
1351     path.toVector(Storage);
1352     expandTildeExpr(Storage);
1353     return real_path(Storage, dest, false);
1354   }
1355
1356   if (is_directory(path))
1357     return directoryRealPath(path, dest);
1358
1359   int fd;
1360   if (std::error_code EC =
1361           llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1362     return EC;
1363   ::close(fd);
1364   return std::error_code();
1365 }
1366
1367 } // end namespace fs
1368
1369 namespace path {
1370 static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1371                                SmallVectorImpl<char> &result) {
1372   wchar_t *path = nullptr;
1373   if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1374     return false;
1375
1376   bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1377   ::CoTaskMemFree(path);
1378   return ok;
1379 }
1380
1381 bool home_directory(SmallVectorImpl<char> &result) {
1382   return getKnownFolderPath(FOLDERID_Profile, result);
1383 }
1384
1385 static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1386   SmallVector<wchar_t, 1024> Buf;
1387   size_t Size = 1024;
1388   do {
1389     Buf.reserve(Size);
1390     Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1391     if (Size == 0)
1392       return false;
1393
1394     // Try again with larger buffer.
1395   } while (Size > Buf.capacity());
1396   Buf.set_size(Size);
1397
1398   return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1399 }
1400
1401 static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1402   const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1403   for (auto *Env : EnvironmentVariables) {
1404     if (getTempDirEnvVar(Env, Res))
1405       return true;
1406   }
1407   return false;
1408 }
1409
1410 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1411   (void)ErasedOnReboot;
1412   Result.clear();
1413
1414   // Check whether the temporary directory is specified by an environment var.
1415   // This matches GetTempPath logic to some degree. GetTempPath is not used
1416   // directly as it cannot handle evn var longer than 130 chars on Windows 7
1417   // (fixed on Windows 8).
1418   if (getTempDirEnvVar(Result)) {
1419     assert(!Result.empty() && "Unexpected empty path");
1420     native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1421     fs::make_absolute(Result); // Make it absolute if not already.
1422     return;
1423   }
1424
1425   // Fall back to a system default.
1426   const char *DefaultResult = "C:\\Temp";
1427   Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1428 }
1429 } // end namespace path
1430
1431 namespace windows {
1432 std::error_code CodePageToUTF16(unsigned codepage,
1433                                 llvm::StringRef original,
1434                                 llvm::SmallVectorImpl<wchar_t> &utf16) {
1435   if (!original.empty()) {
1436     int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1437                                     original.size(), utf16.begin(), 0);
1438
1439     if (len == 0) {
1440       return mapWindowsError(::GetLastError());
1441     }
1442
1443     utf16.reserve(len + 1);
1444     utf16.set_size(len);
1445
1446     len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1447                                 original.size(), utf16.begin(), utf16.size());
1448
1449     if (len == 0) {
1450       return mapWindowsError(::GetLastError());
1451     }
1452   }
1453
1454   // Make utf16 null terminated.
1455   utf16.push_back(0);
1456   utf16.pop_back();
1457
1458   return std::error_code();
1459 }
1460
1461 std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1462                             llvm::SmallVectorImpl<wchar_t> &utf16) {
1463   return CodePageToUTF16(CP_UTF8, utf8, utf16);
1464 }
1465
1466 std::error_code CurCPToUTF16(llvm::StringRef curcp,
1467                             llvm::SmallVectorImpl<wchar_t> &utf16) {
1468   return CodePageToUTF16(CP_ACP, curcp, utf16);
1469 }
1470
1471 static
1472 std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1473                                 size_t utf16_len,
1474                                 llvm::SmallVectorImpl<char> &converted) {
1475   if (utf16_len) {
1476     // Get length.
1477     int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
1478                                     0, NULL, NULL);
1479
1480     if (len == 0) {
1481       return mapWindowsError(::GetLastError());
1482     }
1483
1484     converted.reserve(len);
1485     converted.set_size(len);
1486
1487     // Now do the actual conversion.
1488     len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1489                                 converted.size(), NULL, NULL);
1490
1491     if (len == 0) {
1492       return mapWindowsError(::GetLastError());
1493     }
1494   }
1495
1496   // Make the new string null terminated.
1497   converted.push_back(0);
1498   converted.pop_back();
1499
1500   return std::error_code();
1501 }
1502
1503 std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1504                             llvm::SmallVectorImpl<char> &utf8) {
1505   return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1506 }
1507
1508 std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1509                              llvm::SmallVectorImpl<char> &curcp) {
1510   return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1511 }
1512
1513 } // end namespace windows
1514 } // end namespace sys
1515 } // end namespace llvm