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