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