OSDN Git Service

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