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