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