Share a createUniqueEntity implementation between unix and windows.
[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 #if LLVM_HAS_RVALUE_REFERENCES
663 mapped_file_region::mapped_file_region(mapped_file_region &&other)
664   : Mode(other.Mode)
665   , Size(other.Size)
666   , Mapping(other.Mapping)
667   , FileDescriptor(other.FileDescriptor)
668   , FileHandle(other.FileHandle)
669   , FileMappingHandle(other.FileMappingHandle) {
670   other.Mapping = other.FileMappingHandle = 0;
671   other.FileHandle = INVALID_HANDLE_VALUE;
672   other.FileDescriptor = 0;
673 }
674 #endif
675
676 mapped_file_region::mapmode mapped_file_region::flags() const {
677   assert(Mapping && "Mapping failed but used anyway!");
678   return Mode;
679 }
680
681 uint64_t mapped_file_region::size() const {
682   assert(Mapping && "Mapping failed but used anyway!");
683   return Size;
684 }
685
686 char *mapped_file_region::data() const {
687   assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
688   assert(Mapping && "Mapping failed but used anyway!");
689   return reinterpret_cast<char*>(Mapping);
690 }
691
692 const char *mapped_file_region::const_data() const {
693   assert(Mapping && "Mapping failed but used anyway!");
694   return reinterpret_cast<const char*>(Mapping);
695 }
696
697 int mapped_file_region::alignment() {
698   SYSTEM_INFO SysInfo;
699   ::GetSystemInfo(&SysInfo);
700   return SysInfo.dwAllocationGranularity;
701 }
702
703 error_code detail::directory_iterator_construct(detail::DirIterState &it,
704                                                 StringRef path){
705   SmallVector<wchar_t, 128> path_utf16;
706
707   if (error_code ec = UTF8ToUTF16(path,
708                                   path_utf16))
709     return ec;
710
711   // Convert path to the format that Windows is happy with.
712   if (path_utf16.size() > 0 &&
713       !is_separator(path_utf16[path.size() - 1]) &&
714       path_utf16[path.size() - 1] != L':') {
715     path_utf16.push_back(L'\\');
716     path_utf16.push_back(L'*');
717   } else {
718     path_utf16.push_back(L'*');
719   }
720
721   //  Get the first directory entry.
722   WIN32_FIND_DATAW FirstFind;
723   ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
724   if (!FindHandle)
725     return windows_error(::GetLastError());
726
727   size_t FilenameLen = ::wcslen(FirstFind.cFileName);
728   while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
729          (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
730                               FirstFind.cFileName[1] == L'.'))
731     if (!::FindNextFileW(FindHandle, &FirstFind)) {
732       error_code ec = windows_error(::GetLastError());
733       // Check for end.
734       if (ec == windows_error::no_more_files)
735         return detail::directory_iterator_destruct(it);
736       return ec;
737     } else
738       FilenameLen = ::wcslen(FirstFind.cFileName);
739
740   // Construct the current directory entry.
741   SmallString<128> directory_entry_name_utf8;
742   if (error_code ec = UTF16ToUTF8(FirstFind.cFileName,
743                                   ::wcslen(FirstFind.cFileName),
744                                   directory_entry_name_utf8))
745     return ec;
746
747   it.IterationHandle = intptr_t(FindHandle.take());
748   SmallString<128> directory_entry_path(path);
749   path::append(directory_entry_path, directory_entry_name_utf8.str());
750   it.CurrentEntry = directory_entry(directory_entry_path.str());
751
752   return error_code::success();
753 }
754
755 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
756   if (it.IterationHandle != 0)
757     // Closes the handle if it's valid.
758     ScopedFindHandle close(HANDLE(it.IterationHandle));
759   it.IterationHandle = 0;
760   it.CurrentEntry = directory_entry();
761   return error_code::success();
762 }
763
764 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
765   WIN32_FIND_DATAW FindData;
766   if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
767     error_code ec = windows_error(::GetLastError());
768     // Check for end.
769     if (ec == windows_error::no_more_files)
770       return detail::directory_iterator_destruct(it);
771     return ec;
772   }
773
774   size_t FilenameLen = ::wcslen(FindData.cFileName);
775   if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
776       (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
777                            FindData.cFileName[1] == L'.'))
778     return directory_iterator_increment(it);
779
780   SmallString<128> directory_entry_path_utf8;
781   if (error_code ec = UTF16ToUTF8(FindData.cFileName,
782                                   ::wcslen(FindData.cFileName),
783                                   directory_entry_path_utf8))
784     return ec;
785
786   it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
787   return error_code::success();
788 }
789
790 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
791                                             bool map_writable, void *&result) {
792   assert(0 && "NOT IMPLEMENTED");
793   return windows_error::invalid_function;
794 }
795
796 error_code unmap_file_pages(void *base, size_t size) {
797   assert(0 && "NOT IMPLEMENTED");
798   return windows_error::invalid_function;
799 }
800
801 error_code openFileForRead(const Twine &Name, int &ResultFD) {
802   SmallString<128> PathStorage;
803   SmallVector<wchar_t, 128> PathUTF16;
804
805   if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
806                                   PathUTF16))
807     return EC;
808
809   HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
810                            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
811                            OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
812   if (H == INVALID_HANDLE_VALUE) {
813     error_code EC = windows_error(::GetLastError());
814     // Provide a better error message when trying to open directories.
815     // This only runs if we failed to open the file, so there is probably
816     // no performances issues.
817     if (EC != windows_error::access_denied)
818       return EC;
819     if (is_directory(Name))
820       return error_code(errc::is_a_directory, posix_category());
821     return EC;
822   }
823
824   int FD = ::_open_osfhandle(intptr_t(H), 0);
825   if (FD == -1) {
826     ::CloseHandle(H);
827     return windows_error::invalid_handle;
828   }
829
830   ResultFD = FD;
831   return error_code::success();
832 }
833
834 error_code openFileForWrite(const Twine &Name, int &ResultFD,
835                             sys::fs::OpenFlags Flags, unsigned Mode) {
836   // Verify that we don't have both "append" and "excl".
837   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
838          "Cannot specify both 'excl' and 'append' file creation flags!");
839
840   SmallString<128> PathStorage;
841   SmallVector<wchar_t, 128> PathUTF16;
842
843   if (error_code EC = UTF8ToUTF16(Name.toStringRef(PathStorage),
844                                   PathUTF16))
845     return EC;
846
847   DWORD CreationDisposition;
848   if (Flags & F_Excl)
849     CreationDisposition = CREATE_NEW;
850   else if (Flags & F_Append)
851     CreationDisposition = OPEN_ALWAYS;
852   else
853     CreationDisposition = CREATE_ALWAYS;
854
855   DWORD Access = GENERIC_WRITE;
856   if (Flags & F_RW)
857     Access |= GENERIC_READ;
858
859   HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
860                            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
861                            CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
862
863   if (H == INVALID_HANDLE_VALUE) {
864     error_code EC = windows_error(::GetLastError());
865     // Provide a better error message when trying to open directories.
866     // This only runs if we failed to open the file, so there is probably
867     // no performances issues.
868     if (EC != windows_error::access_denied)
869       return EC;
870     if (is_directory(Name))
871       return error_code(errc::is_a_directory, posix_category());
872     return EC;
873   }
874
875   int OpenFlags = 0;
876   if (Flags & F_Append)
877     OpenFlags |= _O_APPEND;
878
879   if (!(Flags & F_Binary))
880     OpenFlags |= _O_TEXT;
881
882   int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
883   if (FD == -1) {
884     ::CloseHandle(H);
885     return windows_error::invalid_handle;
886   }
887
888   ResultFD = FD;
889   return error_code::success();
890 }
891 } // end namespace fs
892
893 namespace path {
894
895 bool home_directory(SmallVectorImpl<char> &result) {
896   wchar_t Path[MAX_PATH];
897   if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
898                          /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
899     return false;
900
901   if (UTF16ToUTF8(Path, ::wcslen(Path), result))
902     return false;
903
904   return true;
905 }
906
907 } // end namespace path
908
909 namespace windows {
910 llvm::error_code UTF8ToUTF16(llvm::StringRef utf8,
911                              llvm::SmallVectorImpl<wchar_t> &utf16) {
912   if (!utf8.empty()) {
913     int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
914                                     utf8.size(), utf16.begin(), 0);
915
916     if (len == 0)
917       return llvm::windows_error(::GetLastError());
918
919     utf16.reserve(len + 1);
920     utf16.set_size(len);
921
922     len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
923                                 utf8.size(), utf16.begin(), utf16.size());
924
925     if (len == 0)
926       return llvm::windows_error(::GetLastError());
927   }
928
929   // Make utf16 null terminated.
930   utf16.push_back(0);
931   utf16.pop_back();
932
933   return llvm::error_code::success();
934 }
935
936 llvm::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
937                              llvm::SmallVectorImpl<char> &utf8) {
938   if (utf16_len) {
939     // Get length.
940     int len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.begin(),
941                                     0, NULL, NULL);
942
943     if (len == 0)
944       return llvm::windows_error(::GetLastError());
945
946     utf8.reserve(len);
947     utf8.set_size(len);
948
949     // Now do the actual conversion.
950     len = ::WideCharToMultiByte(CP_UTF8, 0, utf16, utf16_len, utf8.data(),
951                                 utf8.size(), NULL, NULL);
952
953     if (len == 0)
954       return llvm::windows_error(::GetLastError());
955   }
956
957   // Make utf8 null terminated.
958   utf8.push_back(0);
959   utf8.pop_back();
960
961   return llvm::error_code::success();
962 }
963 } // end namespace windows
964 } // end namespace sys
965 } // end namespace llvm