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