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