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