OSDN Git Service

f55260a288e64309affd88c3e1a0f791b9092227
[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/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 <shlobj.h>
30
31 #undef max
32
33 // MinGW doesn't define this.
34 #ifndef _ERRNO_T_DEFINED
35 #define _ERRNO_T_DEFINED
36 typedef int errno_t;
37 #endif
38
39 #ifdef _MSC_VER
40 # pragma comment(lib, "advapi32.lib")  // This provides CryptAcquireContextW.
41 # pragma comment(lib, "ole32.lib")     // This provides CoTaskMemFree
42 #endif
43
44 using namespace llvm;
45
46 using llvm::sys::windows::UTF8ToUTF16;
47 using llvm::sys::windows::UTF16ToUTF8;
48 using llvm::sys::path::widenPath;
49
50 static bool is_separator(const wchar_t value) {
51   switch (value) {
52   case L'\\':
53   case L'/':
54     return true;
55   default:
56     return false;
57   }
58 }
59
60 namespace llvm {
61 namespace sys  {
62 namespace path {
63
64 // Convert a UTF-8 path to UTF-16.  Also, if the absolute equivalent of the
65 // path is longer than CreateDirectory can tolerate, make it absolute and
66 // prefixed by '\\?\'.
67 std::error_code widenPath(const Twine &Path8,
68                           SmallVectorImpl<wchar_t> &Path16) {
69   const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
70
71   // Several operations would convert Path8 to SmallString; more efficient to
72   // do it once up front.
73   SmallString<128> Path8Str;
74   Path8.toVector(Path8Str);
75
76   // If we made this path absolute, how much longer would it get?
77   size_t CurPathLen;
78   if (llvm::sys::path::is_absolute(Twine(Path8Str)))
79     CurPathLen = 0; // No contribution from current_path needed.
80   else {
81     CurPathLen = ::GetCurrentDirectoryW(0, NULL);
82     if (CurPathLen == 0)
83       return mapWindowsError(::GetLastError());
84   }
85
86   // Would the absolute path be longer than our limit?
87   if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
88       !Path8Str.startswith("\\\\?\\")) {
89     SmallString<2*MAX_PATH> FullPath("\\\\?\\");
90     if (CurPathLen) {
91       SmallString<80> CurPath;
92       if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
93         return EC;
94       FullPath.append(CurPath);
95     }
96     // Traverse the requested path, canonicalizing . and .. as we go (because
97     // the \\?\ prefix is documented to treat them as real components).
98     // The iterators don't report separators and append() always attaches
99     // preferred_separator so we don't need to call native() on the result.
100     for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
101                                          E = llvm::sys::path::end(Path8Str);
102                                          I != E; ++I) {
103       if (I->size() == 1 && *I == ".")
104         continue;
105       if (I->size() == 2 && *I == "..")
106         llvm::sys::path::remove_filename(FullPath);
107       else
108         llvm::sys::path::append(FullPath, *I);
109     }
110     return UTF8ToUTF16(FullPath, Path16);
111   }
112
113   // Just use the caller's original path.
114   return UTF8ToUTF16(Path8Str, Path16);
115 }
116 } // end namespace path
117
118 namespace fs {
119
120 std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
121   SmallVector<wchar_t, MAX_PATH> PathName;
122   DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
123
124   // A zero return value indicates a failure other than insufficient space.
125   if (Size == 0)
126     return "";
127
128   // Insufficient space is determined by a return value equal to the size of
129   // the buffer passed in.
130   if (Size == PathName.capacity())
131     return "";
132
133   // On success, GetModuleFileNameW returns the number of characters written to
134   // the buffer not including the NULL terminator.
135   PathName.set_size(Size);
136
137   // Convert the result from UTF-16 to UTF-8.
138   SmallVector<char, MAX_PATH> PathNameUTF8;
139   if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
140     return "";
141
142   return std::string(PathNameUTF8.data());
143 }
144
145 UniqueID file_status::getUniqueID() const {
146   // The file is uniquely identified by the volume serial number along
147   // with the 64-bit file identifier.
148   uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
149                     static_cast<uint64_t>(FileIndexLow);
150
151   return UniqueID(VolumeSerialNumber, FileID);
152 }
153
154 ErrorOr<space_info> disk_space(const Twine Path) {
155   PULARGE_INTEGER Avail, Total, Free;
156   if (!::GetDiskFreeSpaceExW(Path.str().c_str(), &Avail, &Total, &Free))
157     return mapWindowsError(::GetLastError());
158   space_info SpaceInfo;
159   SpaceInfo.capacity =
160       (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
161   SpaceInfo.Free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
162   SpaceInfo.available =
163       (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
164   return SpaceInfo;
165 }
166
167 TimeValue file_status::getLastAccessedTime() const {
168   ULARGE_INTEGER UI;
169   UI.LowPart = LastAccessedTimeLow;
170   UI.HighPart = LastAccessedTimeHigh;
171
172   TimeValue Ret;
173   Ret.fromWin32Time(UI.QuadPart);
174   return Ret;
175 }
176
177 TimeValue file_status::getLastModificationTime() const {
178   ULARGE_INTEGER UI;
179   UI.LowPart = LastWriteTimeLow;
180   UI.HighPart = LastWriteTimeHigh;
181
182   TimeValue Ret;
183   Ret.fromWin32Time(UI.QuadPart);
184   return Ret;
185 }
186
187 std::error_code current_path(SmallVectorImpl<char> &result) {
188   SmallVector<wchar_t, MAX_PATH> cur_path;
189   DWORD len = MAX_PATH;
190
191   do {
192     cur_path.reserve(len);
193     len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
194
195     // A zero return value indicates a failure other than insufficient space.
196     if (len == 0)
197       return mapWindowsError(::GetLastError());
198
199     // If there's insufficient space, the len returned is larger than the len
200     // given.
201   } while (len > cur_path.capacity());
202
203   // On success, GetCurrentDirectoryW returns the number of characters not
204   // including the null-terminator.
205   cur_path.set_size(len);
206   return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
207 }
208
209 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
210                                  perms Perms) {
211   SmallVector<wchar_t, 128> path_utf16;
212
213   if (std::error_code ec = widenPath(path, path_utf16))
214     return ec;
215
216   if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
217     DWORD LastError = ::GetLastError();
218     if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
219       return mapWindowsError(LastError);
220   }
221
222   return std::error_code();
223 }
224
225 // We can't use symbolic links for windows.
226 std::error_code create_link(const Twine &to, const Twine &from) {
227   // Convert to utf-16.
228   SmallVector<wchar_t, 128> wide_from;
229   SmallVector<wchar_t, 128> wide_to;
230   if (std::error_code ec = widenPath(from, wide_from))
231     return ec;
232   if (std::error_code ec = widenPath(to, wide_to))
233     return ec;
234
235   if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
236     return mapWindowsError(::GetLastError());
237
238   return std::error_code();
239 }
240
241 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
242   SmallVector<wchar_t, 128> path_utf16;
243
244   file_status ST;
245   if (std::error_code EC = status(path, ST)) {
246     if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
247       return EC;
248     return std::error_code();
249   }
250
251   if (std::error_code ec = widenPath(path, path_utf16))
252     return ec;
253
254   if (ST.type() == file_type::directory_file) {
255     if (!::RemoveDirectoryW(c_str(path_utf16))) {
256       std::error_code EC = mapWindowsError(::GetLastError());
257       if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
258         return EC;
259     }
260     return std::error_code();
261   }
262   if (!::DeleteFileW(c_str(path_utf16))) {
263     std::error_code EC = mapWindowsError(::GetLastError());
264     if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
265       return EC;
266   }
267   return std::error_code();
268 }
269
270 std::error_code rename(const Twine &from, const Twine &to) {
271   // Convert to utf-16.
272   SmallVector<wchar_t, 128> wide_from;
273   SmallVector<wchar_t, 128> wide_to;
274   if (std::error_code ec = widenPath(from, wide_from))
275     return ec;
276   if (std::error_code ec = widenPath(to, wide_to))
277     return ec;
278
279   std::error_code ec = std::error_code();
280
281   // Retry while we see recoverable errors.
282   // System scanners (eg. indexer) might open the source file when it is written
283   // and closed.
284
285   bool TryReplace = true;
286
287   for (int i = 0; i < 2000; i++) {
288     if (i > 0)
289       ::Sleep(1);
290
291     if (TryReplace) {
292       // Try ReplaceFile first, as it is able to associate a new data stream
293       // with the destination even if the destination file is currently open.
294       if (::ReplaceFileW(wide_to.data(), wide_from.data(), NULL, 0, NULL, NULL))
295         return std::error_code();
296
297       DWORD ReplaceError = ::GetLastError();
298       ec = mapWindowsError(ReplaceError);
299
300       // If ReplaceFileW returned ERROR_UNABLE_TO_MOVE_REPLACEMENT or
301       // ERROR_UNABLE_TO_MOVE_REPLACEMENT_2, retry but only use MoveFileExW().
302       if (ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT ||
303           ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT_2) {
304         TryReplace = false;
305         continue;
306       }
307       // If ReplaceFileW returned ERROR_UNABLE_TO_REMOVE_REPLACED, retry
308       // using ReplaceFileW().
309       if (ReplaceError == ERROR_UNABLE_TO_REMOVE_REPLACED)
310         continue;
311       // We get ERROR_FILE_NOT_FOUND if the destination file is missing.
312       // MoveFileEx can handle this case.
313       if (ReplaceError != ERROR_ACCESS_DENIED &&
314           ReplaceError != ERROR_FILE_NOT_FOUND &&
315           ReplaceError != ERROR_SHARING_VIOLATION)
316         break;
317     }
318
319     if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
320                       MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
321       return std::error_code();
322
323     DWORD MoveError = ::GetLastError();
324     ec = mapWindowsError(MoveError);
325     if (MoveError != ERROR_ACCESS_DENIED) break;
326   }
327
328   return ec;
329 }
330
331 std::error_code resize_file(int FD, uint64_t Size) {
332 #ifdef HAVE__CHSIZE_S
333   errno_t error = ::_chsize_s(FD, Size);
334 #else
335   errno_t error = ::_chsize(FD, Size);
336 #endif
337   return std::error_code(error, std::generic_category());
338 }
339
340 std::error_code access(const Twine &Path, AccessMode Mode) {
341   SmallVector<wchar_t, 128> PathUtf16;
342
343   if (std::error_code EC = widenPath(Path, PathUtf16))
344     return EC;
345
346   DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
347
348   if (Attributes == INVALID_FILE_ATTRIBUTES) {
349     // See if the file didn't actually exist.
350     DWORD LastError = ::GetLastError();
351     if (LastError != ERROR_FILE_NOT_FOUND &&
352         LastError != ERROR_PATH_NOT_FOUND)
353       return mapWindowsError(LastError);
354     return errc::no_such_file_or_directory;
355   }
356
357   if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
358     return errc::permission_denied;
359
360   return std::error_code();
361 }
362
363 bool can_execute(const Twine &Path) {
364   return !access(Path, AccessMode::Execute) ||
365          !access(Path + ".exe", AccessMode::Execute);
366 }
367
368 bool equivalent(file_status A, file_status B) {
369   assert(status_known(A) && status_known(B));
370   return A.FileIndexHigh         == B.FileIndexHigh &&
371          A.FileIndexLow          == B.FileIndexLow &&
372          A.FileSizeHigh          == B.FileSizeHigh &&
373          A.FileSizeLow           == B.FileSizeLow &&
374          A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
375          A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
376          A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
377          A.LastWriteTimeLow      == B.LastWriteTimeLow &&
378          A.VolumeSerialNumber    == B.VolumeSerialNumber;
379 }
380
381 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
382   file_status fsA, fsB;
383   if (std::error_code ec = status(A, fsA))
384     return ec;
385   if (std::error_code ec = status(B, fsB))
386     return ec;
387   result = equivalent(fsA, fsB);
388   return std::error_code();
389 }
390
391 static bool isReservedName(StringRef path) {
392   // This list of reserved names comes from MSDN, at:
393   // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
394   static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
395                                                 "com1", "com2", "com3", "com4",
396                                                 "com5", "com6", "com7", "com8",
397                                                 "com9", "lpt1", "lpt2", "lpt3",
398                                                 "lpt4", "lpt5", "lpt6", "lpt7",
399                                                 "lpt8", "lpt9" };
400
401   // First, check to see if this is a device namespace, which always
402   // starts with \\.\, since device namespaces are not legal file paths.
403   if (path.startswith("\\\\.\\"))
404     return true;
405
406   // Then compare against the list of ancient reserved names
407   for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
408     if (path.equals_lower(sReservedNames[i]))
409       return true;
410   }
411
412   // The path isn't what we consider reserved.
413   return false;
414 }
415
416 static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
417   if (FileHandle == INVALID_HANDLE_VALUE)
418     goto handle_status_error;
419
420   switch (::GetFileType(FileHandle)) {
421   default:
422     llvm_unreachable("Don't know anything about this file type");
423   case FILE_TYPE_UNKNOWN: {
424     DWORD Err = ::GetLastError();
425     if (Err != NO_ERROR)
426       return mapWindowsError(Err);
427     Result = file_status(file_type::type_unknown);
428     return std::error_code();
429   }
430   case FILE_TYPE_DISK:
431     break;
432   case FILE_TYPE_CHAR:
433     Result = file_status(file_type::character_file);
434     return std::error_code();
435   case FILE_TYPE_PIPE:
436     Result = file_status(file_type::fifo_file);
437     return std::error_code();
438   }
439
440   BY_HANDLE_FILE_INFORMATION Info;
441   if (!::GetFileInformationByHandle(FileHandle, &Info))
442     goto handle_status_error;
443
444   {
445     file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
446                          ? file_type::directory_file
447                          : file_type::regular_file;
448     Result =
449         file_status(Type, Info.ftLastAccessTime.dwHighDateTime,
450                     Info.ftLastAccessTime.dwLowDateTime,
451                     Info.ftLastWriteTime.dwHighDateTime,
452                     Info.ftLastWriteTime.dwLowDateTime,
453                     Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
454                     Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
455     return std::error_code();
456   }
457
458 handle_status_error:
459   DWORD LastError = ::GetLastError();
460   if (LastError == ERROR_FILE_NOT_FOUND ||
461       LastError == ERROR_PATH_NOT_FOUND)
462     Result = file_status(file_type::file_not_found);
463   else if (LastError == ERROR_SHARING_VIOLATION)
464     Result = file_status(file_type::type_unknown);
465   else
466     Result = file_status(file_type::status_error);
467   return mapWindowsError(LastError);
468 }
469
470 std::error_code status(const Twine &path, file_status &result) {
471   SmallString<128> path_storage;
472   SmallVector<wchar_t, 128> path_utf16;
473
474   StringRef path8 = path.toStringRef(path_storage);
475   if (isReservedName(path8)) {
476     result = file_status(file_type::character_file);
477     return std::error_code();
478   }
479
480   if (std::error_code ec = widenPath(path8, path_utf16))
481     return ec;
482
483   DWORD attr = ::GetFileAttributesW(path_utf16.begin());
484   if (attr == INVALID_FILE_ATTRIBUTES)
485     return getStatus(INVALID_HANDLE_VALUE, result);
486
487   // Handle reparse points.
488   if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
489     ScopedFileHandle h(
490       ::CreateFileW(path_utf16.begin(),
491                     0, // Attributes only.
492                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
493                     NULL,
494                     OPEN_EXISTING,
495                     FILE_FLAG_BACKUP_SEMANTICS,
496                     0));
497     if (!h)
498       return getStatus(INVALID_HANDLE_VALUE, result);
499   }
500
501   ScopedFileHandle h(
502       ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
503                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
504                     NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
505     if (!h)
506       return getStatus(INVALID_HANDLE_VALUE, result);
507
508     return getStatus(h, result);
509 }
510
511 std::error_code status(int FD, file_status &Result) {
512   HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
513   return getStatus(FileHandle, Result);
514 }
515
516 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
517   ULARGE_INTEGER UI;
518   UI.QuadPart = Time.toWin32Time();
519   FILETIME FT;
520   FT.dwLowDateTime = UI.LowPart;
521   FT.dwHighDateTime = UI.HighPart;
522   HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
523   if (!SetFileTime(FileHandle, NULL, &FT, &FT))
524     return mapWindowsError(::GetLastError());
525   return std::error_code();
526 }
527
528 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
529                                          mapmode Mode) {
530   // Make sure that the requested size fits within SIZE_T.
531   if (Size > std::numeric_limits<SIZE_T>::max())
532     return make_error_code(errc::invalid_argument);
533
534   HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
535   if (FileHandle == INVALID_HANDLE_VALUE)
536     return make_error_code(errc::bad_file_descriptor);
537
538   DWORD flprotect;
539   switch (Mode) {
540   case readonly:  flprotect = PAGE_READONLY; break;
541   case readwrite: flprotect = PAGE_READWRITE; break;
542   case priv:      flprotect = PAGE_WRITECOPY; break;
543   }
544
545   HANDLE FileMappingHandle =
546       ::CreateFileMappingW(FileHandle, 0, flprotect,
547                            (Offset + Size) >> 32,
548                            (Offset + Size) & 0xffffffff,
549                            0);
550   if (FileMappingHandle == NULL) {
551     std::error_code ec = mapWindowsError(GetLastError());
552     return ec;
553   }
554
555   DWORD dwDesiredAccess;
556   switch (Mode) {
557   case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
558   case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
559   case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
560   }
561   Mapping = ::MapViewOfFile(FileMappingHandle,
562                             dwDesiredAccess,
563                             Offset >> 32,
564                             Offset & 0xffffffff,
565                             Size);
566   if (Mapping == NULL) {
567     std::error_code ec = mapWindowsError(GetLastError());
568     ::CloseHandle(FileMappingHandle);
569     return ec;
570   }
571
572   if (Size == 0) {
573     MEMORY_BASIC_INFORMATION mbi;
574     SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
575     if (Result == 0) {
576       std::error_code ec = mapWindowsError(GetLastError());
577       ::UnmapViewOfFile(Mapping);
578       ::CloseHandle(FileMappingHandle);
579       return ec;
580     }
581     Size = mbi.RegionSize;
582   }
583
584   // Close all the handles except for the view. It will keep the other handles
585   // alive.
586   ::CloseHandle(FileMappingHandle);
587   return std::error_code();
588 }
589
590 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
591                                        uint64_t offset, std::error_code &ec)
592     : Size(length), Mapping() {
593   ec = init(fd, offset, mode);
594   if (ec)
595     Mapping = 0;
596 }
597
598 mapped_file_region::~mapped_file_region() {
599   if (Mapping)
600     ::UnmapViewOfFile(Mapping);
601 }
602
603 uint64_t mapped_file_region::size() const {
604   assert(Mapping && "Mapping failed but used anyway!");
605   return Size;
606 }
607
608 char *mapped_file_region::data() const {
609   assert(Mapping && "Mapping failed but used anyway!");
610   return reinterpret_cast<char*>(Mapping);
611 }
612
613 const char *mapped_file_region::const_data() const {
614   assert(Mapping && "Mapping failed but used anyway!");
615   return reinterpret_cast<const char*>(Mapping);
616 }
617
618 int mapped_file_region::alignment() {
619   SYSTEM_INFO SysInfo;
620   ::GetSystemInfo(&SysInfo);
621   return SysInfo.dwAllocationGranularity;
622 }
623
624 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
625                                                 StringRef path){
626   SmallVector<wchar_t, 128> path_utf16;
627
628   if (std::error_code ec = widenPath(path, path_utf16))
629     return ec;
630
631   // Convert path to the format that Windows is happy with.
632   if (path_utf16.size() > 0 &&
633       !is_separator(path_utf16[path.size() - 1]) &&
634       path_utf16[path.size() - 1] != L':') {
635     path_utf16.push_back(L'\\');
636     path_utf16.push_back(L'*');
637   } else {
638     path_utf16.push_back(L'*');
639   }
640
641   //  Get the first directory entry.
642   WIN32_FIND_DATAW FirstFind;
643   ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
644   if (!FindHandle)
645     return mapWindowsError(::GetLastError());
646
647   size_t FilenameLen = ::wcslen(FirstFind.cFileName);
648   while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
649          (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
650                               FirstFind.cFileName[1] == L'.'))
651     if (!::FindNextFileW(FindHandle, &FirstFind)) {
652       DWORD LastError = ::GetLastError();
653       // Check for end.
654       if (LastError == ERROR_NO_MORE_FILES)
655         return detail::directory_iterator_destruct(it);
656       return mapWindowsError(LastError);
657     } else
658       FilenameLen = ::wcslen(FirstFind.cFileName);
659
660   // Construct the current directory entry.
661   SmallString<128> directory_entry_name_utf8;
662   if (std::error_code ec =
663           UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
664                       directory_entry_name_utf8))
665     return ec;
666
667   it.IterationHandle = intptr_t(FindHandle.take());
668   SmallString<128> directory_entry_path(path);
669   path::append(directory_entry_path, directory_entry_name_utf8);
670   it.CurrentEntry = directory_entry(directory_entry_path);
671
672   return std::error_code();
673 }
674
675 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
676   if (it.IterationHandle != 0)
677     // Closes the handle if it's valid.
678     ScopedFindHandle close(HANDLE(it.IterationHandle));
679   it.IterationHandle = 0;
680   it.CurrentEntry = directory_entry();
681   return std::error_code();
682 }
683
684 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
685   WIN32_FIND_DATAW FindData;
686   if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
687     DWORD LastError = ::GetLastError();
688     // Check for end.
689     if (LastError == ERROR_NO_MORE_FILES)
690       return detail::directory_iterator_destruct(it);
691     return mapWindowsError(LastError);
692   }
693
694   size_t FilenameLen = ::wcslen(FindData.cFileName);
695   if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
696       (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
697                            FindData.cFileName[1] == L'.'))
698     return directory_iterator_increment(it);
699
700   SmallString<128> directory_entry_path_utf8;
701   if (std::error_code ec =
702           UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
703                       directory_entry_path_utf8))
704     return ec;
705
706   it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
707   return std::error_code();
708 }
709
710 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
711   SmallVector<wchar_t, 128> PathUTF16;
712
713   if (std::error_code EC = widenPath(Name, PathUTF16))
714     return EC;
715
716   HANDLE H =
717       ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
718                     FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
719                     NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
720   if (H == INVALID_HANDLE_VALUE) {
721     DWORD LastError = ::GetLastError();
722     std::error_code EC = mapWindowsError(LastError);
723     // Provide a better error message when trying to open directories.
724     // This only runs if we failed to open the file, so there is probably
725     // no performances issues.
726     if (LastError != ERROR_ACCESS_DENIED)
727       return EC;
728     if (is_directory(Name))
729       return make_error_code(errc::is_a_directory);
730     return EC;
731   }
732
733   int FD = ::_open_osfhandle(intptr_t(H), 0);
734   if (FD == -1) {
735     ::CloseHandle(H);
736     return mapWindowsError(ERROR_INVALID_HANDLE);
737   }
738
739   ResultFD = FD;
740   return std::error_code();
741 }
742
743 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
744                             sys::fs::OpenFlags Flags, unsigned Mode) {
745   // Verify that we don't have both "append" and "excl".
746   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
747          "Cannot specify both 'excl' and 'append' file creation flags!");
748
749   SmallVector<wchar_t, 128> PathUTF16;
750
751   if (std::error_code EC = widenPath(Name, PathUTF16))
752     return EC;
753
754   DWORD CreationDisposition;
755   if (Flags & F_Excl)
756     CreationDisposition = CREATE_NEW;
757   else if (Flags & F_Append)
758     CreationDisposition = OPEN_ALWAYS;
759   else
760     CreationDisposition = CREATE_ALWAYS;
761
762   DWORD Access = GENERIC_WRITE;
763   if (Flags & F_RW)
764     Access |= GENERIC_READ;
765
766   HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
767                            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
768                            CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
769
770   if (H == INVALID_HANDLE_VALUE) {
771     DWORD LastError = ::GetLastError();
772     std::error_code EC = mapWindowsError(LastError);
773     // Provide a better error message when trying to open directories.
774     // This only runs if we failed to open the file, so there is probably
775     // no performances issues.
776     if (LastError != ERROR_ACCESS_DENIED)
777       return EC;
778     if (is_directory(Name))
779       return make_error_code(errc::is_a_directory);
780     return EC;
781   }
782
783   int OpenFlags = 0;
784   if (Flags & F_Append)
785     OpenFlags |= _O_APPEND;
786
787   if (Flags & F_Text)
788     OpenFlags |= _O_TEXT;
789
790   int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
791   if (FD == -1) {
792     ::CloseHandle(H);
793     return mapWindowsError(ERROR_INVALID_HANDLE);
794   }
795
796   ResultFD = FD;
797   return std::error_code();
798 }
799 } // end namespace fs
800
801 namespace path {
802 static bool getKnownFolderPath(KNOWNFOLDERID folderId,
803                                SmallVectorImpl<char> &result) {
804   wchar_t *path = nullptr;
805   if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
806     return false;
807
808   bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
809   ::CoTaskMemFree(path);
810   return ok;
811 }
812
813 bool getUserCacheDir(SmallVectorImpl<char> &Result) {
814   return getKnownFolderPath(FOLDERID_LocalAppData, Result);
815 }
816
817 bool home_directory(SmallVectorImpl<char> &result) {
818   return getKnownFolderPath(FOLDERID_Profile, result);
819 }
820
821 static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
822   SmallVector<wchar_t, 1024> Buf;
823   size_t Size = 1024;
824   do {
825     Buf.reserve(Size);
826     Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
827     if (Size == 0)
828       return false;
829
830     // Try again with larger buffer.
831   } while (Size > Buf.capacity());
832   Buf.set_size(Size);
833
834   return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
835 }
836
837 static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
838   const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
839   for (auto *Env : EnvironmentVariables) {
840     if (getTempDirEnvVar(Env, Res))
841       return true;
842   }
843   return false;
844 }
845
846 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
847   (void)ErasedOnReboot;
848   Result.clear();
849
850   // Check whether the temporary directory is specified by an environment var.
851   // This matches GetTempPath logic to some degree. GetTempPath is not used
852   // directly as it cannot handle evn var longer than 130 chars on Windows 7
853   // (fixed on Windows 8).
854   if (getTempDirEnvVar(Result)) {
855     assert(!Result.empty() && "Unexpected empty path");
856     native(Result); // Some Unix-like shells use Unix path separator in $TMP.
857     fs::make_absolute(Result); // Make it absolute if not already.
858     return;
859   }
860
861   // Fall back to a system default.
862   const char *DefaultResult = "C:\\Temp";
863   Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
864 }
865 } // end namespace path
866
867 namespace windows {
868 std::error_code UTF8ToUTF16(llvm::StringRef utf8,
869                             llvm::SmallVectorImpl<wchar_t> &utf16) {
870   if (!utf8.empty()) {
871     int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
872                                     utf8.size(), utf16.begin(), 0);
873
874     if (len == 0)
875       return mapWindowsError(::GetLastError());
876
877     utf16.reserve(len + 1);
878     utf16.set_size(len);
879
880     len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
881                                 utf8.size(), utf16.begin(), utf16.size());
882
883     if (len == 0)
884       return mapWindowsError(::GetLastError());
885   }
886
887   // Make utf16 null terminated.
888   utf16.push_back(0);
889   utf16.pop_back();
890
891   return std::error_code();
892 }
893
894 static
895 std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
896                                 size_t utf16_len,
897                                 llvm::SmallVectorImpl<char> &utf8) {
898   if (utf16_len) {
899     // Get length.
900     int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
901                                     0, NULL, NULL);
902
903     if (len == 0)
904       return mapWindowsError(::GetLastError());
905
906     utf8.reserve(len);
907     utf8.set_size(len);
908
909     // Now do the actual conversion.
910     len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
911                                 utf8.size(), NULL, NULL);
912
913     if (len == 0)
914       return mapWindowsError(::GetLastError());
915   }
916
917   // Make utf8 null terminated.
918   utf8.push_back(0);
919   utf8.pop_back();
920
921   return std::error_code();
922 }
923
924 std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
925                             llvm::SmallVectorImpl<char> &utf8) {
926   return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
927 }
928
929 std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
930                              llvm::SmallVectorImpl<char> &utf8) {
931   return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
932 }
933 } // end namespace windows
934 } // end namespace sys
935 } // end namespace llvm