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