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