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 "llvm/Support/WindowsError.h"
21#include <fcntl.h>
22#include <io.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25
26// These two headers must be included last, and make sure shlobj is required
27// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
28#include "WindowsSupport.h"
29#include <shellapi.h>
30#include <shlobj.h>
31
32#undef max
33
34// MinGW doesn't define this.
35#ifndef _ERRNO_T_DEFINED
36#define _ERRNO_T_DEFINED
37typedef int errno_t;
38#endif
39
40#ifdef _MSC_VER
41# pragma comment(lib, "advapi32.lib")  // This provides CryptAcquireContextW.
42# pragma comment(lib, "ole32.lib")     // This provides CoTaskMemFree
43#endif
44
45using namespace llvm;
46
47using llvm::sys::windows::UTF8ToUTF16;
48using llvm::sys::windows::UTF16ToUTF8;
49using llvm::sys::path::widenPath;
50
51static bool is_separator(const wchar_t value) {
52  switch (value) {
53  case L'\\':
54  case L'/':
55    return true;
56  default:
57    return false;
58  }
59}
60
61namespace llvm {
62namespace sys  {
63namespace path {
64
65// Convert a UTF-8 path to UTF-16.  Also, if the absolute equivalent of the
66// path is longer than CreateDirectory can tolerate, make it absolute and
67// prefixed by '\\?\'.
68std::error_code widenPath(const Twine &Path8,
69                          SmallVectorImpl<wchar_t> &Path16) {
70  const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
71
72  // Several operations would convert Path8 to SmallString; more efficient to
73  // do it once up front.
74  SmallString<128> Path8Str;
75  Path8.toVector(Path8Str);
76
77  // If we made this path absolute, how much longer would it get?
78  size_t CurPathLen;
79  if (llvm::sys::path::is_absolute(Twine(Path8Str)))
80    CurPathLen = 0; // No contribution from current_path needed.
81  else {
82    CurPathLen = ::GetCurrentDirectoryW(0, NULL);
83    if (CurPathLen == 0)
84      return mapWindowsError(::GetLastError());
85  }
86
87  // Would the absolute path be longer than our limit?
88  if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
89      !Path8Str.startswith("\\\\?\\")) {
90    SmallString<2*MAX_PATH> FullPath("\\\\?\\");
91    if (CurPathLen) {
92      SmallString<80> CurPath;
93      if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
94        return EC;
95      FullPath.append(CurPath);
96    }
97    // Traverse the requested path, canonicalizing . and .. as we go (because
98    // the \\?\ prefix is documented to treat them as real components).
99    // The iterators don't report separators and append() always attaches
100    // preferred_separator so we don't need to call native() on the result.
101    for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
102                                         E = llvm::sys::path::end(Path8Str);
103                                         I != E; ++I) {
104      if (I->size() == 1 && *I == ".")
105        continue;
106      if (I->size() == 2 && *I == "..")
107        llvm::sys::path::remove_filename(FullPath);
108      else
109        llvm::sys::path::append(FullPath, *I);
110    }
111    return UTF8ToUTF16(FullPath, Path16);
112  }
113
114  // Just use the caller's original path.
115  return UTF8ToUTF16(Path8Str, Path16);
116}
117} // end namespace path
118
119namespace fs {
120
121std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
122  SmallVector<wchar_t, MAX_PATH> PathName;
123  DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
124
125  // A zero return value indicates a failure other than insufficient space.
126  if (Size == 0)
127    return "";
128
129  // Insufficient space is determined by a return value equal to the size of
130  // the buffer passed in.
131  if (Size == PathName.capacity())
132    return "";
133
134  // On success, GetModuleFileNameW returns the number of characters written to
135  // the buffer not including the NULL terminator.
136  PathName.set_size(Size);
137
138  // Convert the result from UTF-16 to UTF-8.
139  SmallVector<char, MAX_PATH> PathNameUTF8;
140  if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
141    return "";
142
143  return std::string(PathNameUTF8.data());
144}
145
146UniqueID file_status::getUniqueID() const {
147  // The file is uniquely identified by the volume serial number along
148  // with the 64-bit file identifier.
149  uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
150                    static_cast<uint64_t>(FileIndexLow);
151
152  return UniqueID(VolumeSerialNumber, FileID);
153}
154
155ErrorOr<space_info> disk_space(const Twine &Path) {
156  ULARGE_INTEGER Avail, Total, Free;
157  if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
158    return mapWindowsError(::GetLastError());
159  space_info SpaceInfo;
160  SpaceInfo.capacity =
161      (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
162  SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
163  SpaceInfo.available =
164      (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
165  return SpaceInfo;
166}
167
168TimePoint<> file_status::getLastAccessedTime() const {
169  FILETIME Time;
170  Time.dwLowDateTime = LastAccessedTimeLow;
171  Time.dwHighDateTime = LastAccessedTimeHigh;
172  return toTimePoint(Time);
173}
174
175TimePoint<> file_status::getLastModificationTime() const {
176  FILETIME Time;
177  Time.dwLowDateTime = LastWriteTimeLow;
178  Time.dwHighDateTime = LastWriteTimeHigh;
179  return toTimePoint(Time);
180}
181
182uint32_t file_status::getLinkCount() const {
183  return NumLinks;
184}
185
186std::error_code current_path(SmallVectorImpl<char> &result) {
187  SmallVector<wchar_t, MAX_PATH> cur_path;
188  DWORD len = MAX_PATH;
189
190  do {
191    cur_path.reserve(len);
192    len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
193
194    // A zero return value indicates a failure other than insufficient space.
195    if (len == 0)
196      return mapWindowsError(::GetLastError());
197
198    // If there's insufficient space, the len returned is larger than the len
199    // given.
200  } while (len > cur_path.capacity());
201
202  // On success, GetCurrentDirectoryW returns the number of characters not
203  // including the null-terminator.
204  cur_path.set_size(len);
205  return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
206}
207
208std::error_code set_current_path(const Twine &path) {
209  // Convert to utf-16.
210  SmallVector<wchar_t, 128> wide_path;
211  if (std::error_code ec = widenPath(path, wide_path))
212    return ec;
213
214  if (!::SetCurrentDirectoryW(wide_path.begin()))
215    return mapWindowsError(::GetLastError());
216
217  return std::error_code();
218}
219
220std::error_code create_directory(const Twine &path, bool IgnoreExisting,
221                                 perms Perms) {
222  SmallVector<wchar_t, 128> path_utf16;
223
224  if (std::error_code ec = widenPath(path, path_utf16))
225    return ec;
226
227  if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
228    DWORD LastError = ::GetLastError();
229    if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
230      return mapWindowsError(LastError);
231  }
232
233  return std::error_code();
234}
235
236// We can't use symbolic links for windows.
237std::error_code create_link(const Twine &to, const Twine &from) {
238  // Convert to utf-16.
239  SmallVector<wchar_t, 128> wide_from;
240  SmallVector<wchar_t, 128> wide_to;
241  if (std::error_code ec = widenPath(from, wide_from))
242    return ec;
243  if (std::error_code ec = widenPath(to, wide_to))
244    return ec;
245
246  if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
247    return mapWindowsError(::GetLastError());
248
249  return std::error_code();
250}
251
252std::error_code create_hard_link(const Twine &to, const Twine &from) {
253	return create_link(to, from);
254}
255
256std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
257  SmallVector<wchar_t, 128> path_utf16;
258
259  file_status ST;
260  if (std::error_code EC = status(path, ST)) {
261    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
262      return EC;
263    return std::error_code();
264  }
265
266  if (std::error_code ec = widenPath(path, path_utf16))
267    return ec;
268
269  if (ST.type() == file_type::directory_file) {
270    if (!::RemoveDirectoryW(c_str(path_utf16))) {
271      std::error_code EC = mapWindowsError(::GetLastError());
272      if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
273        return EC;
274    }
275    return std::error_code();
276  }
277  if (!::DeleteFileW(c_str(path_utf16))) {
278    std::error_code EC = mapWindowsError(::GetLastError());
279    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
280      return EC;
281  }
282  return std::error_code();
283}
284
285static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
286                                         bool &Result) {
287  SmallVector<wchar_t, 128> VolumePath;
288  size_t Len = 128;
289  while (true) {
290    VolumePath.resize(Len);
291    BOOL Success =
292        ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
293
294    if (Success)
295      break;
296
297    DWORD Err = ::GetLastError();
298    if (Err != ERROR_INSUFFICIENT_BUFFER)
299      return mapWindowsError(Err);
300
301    Len *= 2;
302  }
303  // If the output buffer has exactly enough space for the path name, but not
304  // the null terminator, it will leave the output unterminated.  Push a null
305  // terminator onto the end to ensure that this never happens.
306  VolumePath.push_back(L'\0');
307  VolumePath.set_size(wcslen(VolumePath.data()));
308  const wchar_t *P = VolumePath.data();
309
310  UINT Type = ::GetDriveTypeW(P);
311  switch (Type) {
312  case DRIVE_FIXED:
313    Result = true;
314    return std::error_code();
315  case DRIVE_REMOTE:
316  case DRIVE_CDROM:
317  case DRIVE_RAMDISK:
318  case DRIVE_REMOVABLE:
319    Result = false;
320    return std::error_code();
321  default:
322    return make_error_code(errc::no_such_file_or_directory);
323  }
324  llvm_unreachable("Unreachable!");
325}
326
327std::error_code is_local(const Twine &path, bool &result) {
328  if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
329    return make_error_code(errc::no_such_file_or_directory);
330
331  SmallString<128> Storage;
332  StringRef P = path.toStringRef(Storage);
333
334  // Convert to utf-16.
335  SmallVector<wchar_t, 128> WidePath;
336  if (std::error_code ec = widenPath(P, WidePath))
337    return ec;
338  return is_local_internal(WidePath, result);
339}
340
341std::error_code is_local(int FD, bool &Result) {
342  SmallVector<wchar_t, 128> FinalPath;
343  HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
344
345  size_t Len = 128;
346  do {
347    FinalPath.reserve(Len);
348    Len = ::GetFinalPathNameByHandleW(Handle, FinalPath.data(),
349                                      FinalPath.capacity() - 1, VOLUME_NAME_NT);
350    if (Len == 0)
351      return mapWindowsError(::GetLastError());
352  } while (Len > FinalPath.capacity());
353
354  FinalPath.set_size(Len);
355
356  return is_local_internal(FinalPath, Result);
357}
358
359std::error_code rename(const Twine &from, const Twine &to) {
360  // Convert to utf-16.
361  SmallVector<wchar_t, 128> wide_from;
362  SmallVector<wchar_t, 128> wide_to;
363  if (std::error_code ec = widenPath(from, wide_from))
364    return ec;
365  if (std::error_code ec = widenPath(to, wide_to))
366    return ec;
367
368  std::error_code ec = std::error_code();
369
370  // Retry while we see recoverable errors.
371  // System scanners (eg. indexer) might open the source file when it is written
372  // and closed.
373
374  bool TryReplace = true;
375
376  for (int i = 0; i < 2000; i++) {
377    if (i > 0)
378      ::Sleep(1);
379
380    if (TryReplace) {
381      // Try ReplaceFile first, as it is able to associate a new data stream
382      // with the destination even if the destination file is currently open.
383      if (::ReplaceFileW(wide_to.data(), wide_from.data(), NULL, 0, NULL, NULL))
384        return std::error_code();
385
386      DWORD ReplaceError = ::GetLastError();
387      ec = mapWindowsError(ReplaceError);
388
389      // If ReplaceFileW returned ERROR_UNABLE_TO_MOVE_REPLACEMENT or
390      // ERROR_UNABLE_TO_MOVE_REPLACEMENT_2, retry but only use MoveFileExW().
391      if (ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT ||
392          ReplaceError == ERROR_UNABLE_TO_MOVE_REPLACEMENT_2) {
393        TryReplace = false;
394        continue;
395      }
396      // If ReplaceFileW returned ERROR_UNABLE_TO_REMOVE_REPLACED, retry
397      // using ReplaceFileW().
398      if (ReplaceError == ERROR_UNABLE_TO_REMOVE_REPLACED)
399        continue;
400      // We get ERROR_FILE_NOT_FOUND if the destination file is missing.
401      // MoveFileEx can handle this case.
402      if (ReplaceError != ERROR_ACCESS_DENIED &&
403          ReplaceError != ERROR_FILE_NOT_FOUND &&
404          ReplaceError != ERROR_SHARING_VIOLATION)
405        break;
406    }
407
408    if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
409                      MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
410      return std::error_code();
411
412    DWORD MoveError = ::GetLastError();
413    ec = mapWindowsError(MoveError);
414    if (MoveError != ERROR_ACCESS_DENIED) break;
415  }
416
417  return ec;
418}
419
420std::error_code resize_file(int FD, uint64_t Size) {
421#ifdef HAVE__CHSIZE_S
422  errno_t error = ::_chsize_s(FD, Size);
423#else
424  errno_t error = ::_chsize(FD, Size);
425#endif
426  return std::error_code(error, std::generic_category());
427}
428
429std::error_code access(const Twine &Path, AccessMode Mode) {
430  SmallVector<wchar_t, 128> PathUtf16;
431
432  if (std::error_code EC = widenPath(Path, PathUtf16))
433    return EC;
434
435  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
436
437  if (Attributes == INVALID_FILE_ATTRIBUTES) {
438    // See if the file didn't actually exist.
439    DWORD LastError = ::GetLastError();
440    if (LastError != ERROR_FILE_NOT_FOUND &&
441        LastError != ERROR_PATH_NOT_FOUND)
442      return mapWindowsError(LastError);
443    return errc::no_such_file_or_directory;
444  }
445
446  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
447    return errc::permission_denied;
448
449  return std::error_code();
450}
451
452bool can_execute(const Twine &Path) {
453  return !access(Path, AccessMode::Execute) ||
454         !access(Path + ".exe", AccessMode::Execute);
455}
456
457bool equivalent(file_status A, file_status B) {
458  assert(status_known(A) && status_known(B));
459  return A.FileIndexHigh         == B.FileIndexHigh &&
460         A.FileIndexLow          == B.FileIndexLow &&
461         A.FileSizeHigh          == B.FileSizeHigh &&
462         A.FileSizeLow           == B.FileSizeLow &&
463         A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
464         A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
465         A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
466         A.LastWriteTimeLow      == B.LastWriteTimeLow &&
467         A.VolumeSerialNumber    == B.VolumeSerialNumber;
468}
469
470std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
471  file_status fsA, fsB;
472  if (std::error_code ec = status(A, fsA))
473    return ec;
474  if (std::error_code ec = status(B, fsB))
475    return ec;
476  result = equivalent(fsA, fsB);
477  return std::error_code();
478}
479
480static 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 *const sReservedNames[] = { "nul", "con", "prn", "aux",
484                                                "com1", "com2", "com3", "com4",
485                                                "com5", "com6", "com7", "com8",
486                                                "com9", "lpt1", "lpt2", "lpt3",
487                                                "lpt4", "lpt5", "lpt6", "lpt7",
488                                                "lpt8", "lpt9" };
489
490  // First, check to see if this is a device namespace, which always
491  // starts with \\.\, since device namespaces are not legal file paths.
492  if (path.startswith("\\\\.\\"))
493    return true;
494
495  // Then compare against the list of ancient reserved names.
496  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
497    if (path.equals_lower(sReservedNames[i]))
498      return true;
499  }
500
501  // The path isn't what we consider reserved.
502  return false;
503}
504
505static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
506  if (FileHandle == INVALID_HANDLE_VALUE)
507    goto handle_status_error;
508
509  switch (::GetFileType(FileHandle)) {
510  default:
511    llvm_unreachable("Don't know anything about this file type");
512  case FILE_TYPE_UNKNOWN: {
513    DWORD Err = ::GetLastError();
514    if (Err != NO_ERROR)
515      return mapWindowsError(Err);
516    Result = file_status(file_type::type_unknown);
517    return std::error_code();
518  }
519  case FILE_TYPE_DISK:
520    break;
521  case FILE_TYPE_CHAR:
522    Result = file_status(file_type::character_file);
523    return std::error_code();
524  case FILE_TYPE_PIPE:
525    Result = file_status(file_type::fifo_file);
526    return std::error_code();
527  }
528
529  BY_HANDLE_FILE_INFORMATION Info;
530  if (!::GetFileInformationByHandle(FileHandle, &Info))
531    goto handle_status_error;
532
533  {
534    file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
535                         ? file_type::directory_file
536                         : file_type::regular_file;
537    perms Permissions = (Info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
538                            ? (all_read | all_exe)
539                            : all_all;
540    Result = file_status(
541        Type, Permissions, Info.nNumberOfLinks,
542        Info.ftLastAccessTime.dwHighDateTime,
543        Info.ftLastAccessTime.dwLowDateTime,
544        Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
545        Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
546        Info.nFileIndexHigh, Info.nFileIndexLow);
547    return std::error_code();
548  }
549
550handle_status_error:
551  DWORD LastError = ::GetLastError();
552  if (LastError == ERROR_FILE_NOT_FOUND ||
553      LastError == ERROR_PATH_NOT_FOUND)
554    Result = file_status(file_type::file_not_found);
555  else if (LastError == ERROR_SHARING_VIOLATION)
556    Result = file_status(file_type::type_unknown);
557  else
558    Result = file_status(file_type::status_error);
559  return mapWindowsError(LastError);
560}
561
562std::error_code status(const Twine &path, file_status &result, bool Follow) {
563  SmallString<128> path_storage;
564  SmallVector<wchar_t, 128> path_utf16;
565
566  StringRef path8 = path.toStringRef(path_storage);
567  if (isReservedName(path8)) {
568    result = file_status(file_type::character_file);
569    return std::error_code();
570  }
571
572  if (std::error_code ec = widenPath(path8, path_utf16))
573    return ec;
574
575  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
576  if (attr == INVALID_FILE_ATTRIBUTES)
577    return getStatus(INVALID_HANDLE_VALUE, result);
578
579  DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
580  // Handle reparse points.
581  if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
582    Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
583
584  ScopedFileHandle h(
585      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
586                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
587                    NULL, OPEN_EXISTING, Flags, 0));
588  if (!h)
589    return getStatus(INVALID_HANDLE_VALUE, result);
590
591  return getStatus(h, result);
592}
593
594std::error_code status(int FD, file_status &Result) {
595  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
596  return getStatus(FileHandle, Result);
597}
598
599std::error_code setPermissions(const Twine &Path, perms Permissions) {
600  SmallVector<wchar_t, 128> PathUTF16;
601  if (std::error_code EC = widenPath(Path, PathUTF16))
602    return EC;
603
604  DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
605  if (Attributes == INVALID_FILE_ATTRIBUTES)
606    return mapWindowsError(GetLastError());
607
608  // There are many Windows file attributes that are not to do with the file
609  // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
610  // them.
611  if (Permissions & all_write) {
612    Attributes &= ~FILE_ATTRIBUTE_READONLY;
613    if (Attributes == 0)
614      // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
615      Attributes |= FILE_ATTRIBUTE_NORMAL;
616  }
617  else {
618    Attributes |= FILE_ATTRIBUTE_READONLY;
619    // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
620    // remove it, if it is present.
621    Attributes &= ~FILE_ATTRIBUTE_NORMAL;
622  }
623
624  if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
625    return mapWindowsError(GetLastError());
626
627  return std::error_code();
628}
629
630std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
631  FILETIME FT = toFILETIME(Time);
632  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
633  if (!SetFileTime(FileHandle, NULL, &FT, &FT))
634    return mapWindowsError(::GetLastError());
635  return std::error_code();
636}
637
638std::error_code mapped_file_region::init(int FD, uint64_t Offset,
639                                         mapmode Mode) {
640  // Make sure that the requested size fits within SIZE_T.
641  if (Size > std::numeric_limits<SIZE_T>::max())
642    return make_error_code(errc::invalid_argument);
643
644  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
645  if (FileHandle == INVALID_HANDLE_VALUE)
646    return make_error_code(errc::bad_file_descriptor);
647
648  DWORD flprotect;
649  switch (Mode) {
650  case readonly:  flprotect = PAGE_READONLY; break;
651  case readwrite: flprotect = PAGE_READWRITE; break;
652  case priv:      flprotect = PAGE_WRITECOPY; break;
653  }
654
655  HANDLE FileMappingHandle =
656      ::CreateFileMappingW(FileHandle, 0, flprotect,
657                           (Offset + Size) >> 32,
658                           (Offset + Size) & 0xffffffff,
659                           0);
660  if (FileMappingHandle == NULL) {
661    std::error_code ec = mapWindowsError(GetLastError());
662    return ec;
663  }
664
665  DWORD dwDesiredAccess;
666  switch (Mode) {
667  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
668  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
669  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
670  }
671  Mapping = ::MapViewOfFile(FileMappingHandle,
672                            dwDesiredAccess,
673                            Offset >> 32,
674                            Offset & 0xffffffff,
675                            Size);
676  if (Mapping == NULL) {
677    std::error_code ec = mapWindowsError(GetLastError());
678    ::CloseHandle(FileMappingHandle);
679    return ec;
680  }
681
682  if (Size == 0) {
683    MEMORY_BASIC_INFORMATION mbi;
684    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
685    if (Result == 0) {
686      std::error_code ec = mapWindowsError(GetLastError());
687      ::UnmapViewOfFile(Mapping);
688      ::CloseHandle(FileMappingHandle);
689      return ec;
690    }
691    Size = mbi.RegionSize;
692  }
693
694  // Close all the handles except for the view. It will keep the other handles
695  // alive.
696  ::CloseHandle(FileMappingHandle);
697  return std::error_code();
698}
699
700mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
701                                       uint64_t offset, std::error_code &ec)
702    : Size(length), Mapping() {
703  ec = init(fd, offset, mode);
704  if (ec)
705    Mapping = 0;
706}
707
708mapped_file_region::~mapped_file_region() {
709  if (Mapping)
710    ::UnmapViewOfFile(Mapping);
711}
712
713uint64_t mapped_file_region::size() const {
714  assert(Mapping && "Mapping failed but used anyway!");
715  return Size;
716}
717
718char *mapped_file_region::data() const {
719  assert(Mapping && "Mapping failed but used anyway!");
720  return reinterpret_cast<char*>(Mapping);
721}
722
723const char *mapped_file_region::const_data() const {
724  assert(Mapping && "Mapping failed but used anyway!");
725  return reinterpret_cast<const char*>(Mapping);
726}
727
728int mapped_file_region::alignment() {
729  SYSTEM_INFO SysInfo;
730  ::GetSystemInfo(&SysInfo);
731  return SysInfo.dwAllocationGranularity;
732}
733
734std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
735                                                     StringRef path,
736                                                     bool follow_symlinks) {
737  SmallVector<wchar_t, 128> path_utf16;
738
739  if (std::error_code ec = widenPath(path, path_utf16))
740    return ec;
741
742  // Convert path to the format that Windows is happy with.
743  if (path_utf16.size() > 0 &&
744      !is_separator(path_utf16[path.size() - 1]) &&
745      path_utf16[path.size() - 1] != L':') {
746    path_utf16.push_back(L'\\');
747    path_utf16.push_back(L'*');
748  } else {
749    path_utf16.push_back(L'*');
750  }
751
752  //  Get the first directory entry.
753  WIN32_FIND_DATAW FirstFind;
754  ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
755  if (!FindHandle)
756    return mapWindowsError(::GetLastError());
757
758  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
759  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
760         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
761                              FirstFind.cFileName[1] == L'.'))
762    if (!::FindNextFileW(FindHandle, &FirstFind)) {
763      DWORD LastError = ::GetLastError();
764      // Check for end.
765      if (LastError == ERROR_NO_MORE_FILES)
766        return detail::directory_iterator_destruct(it);
767      return mapWindowsError(LastError);
768    } else
769      FilenameLen = ::wcslen(FirstFind.cFileName);
770
771  // Construct the current directory entry.
772  SmallString<128> directory_entry_name_utf8;
773  if (std::error_code ec =
774          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
775                      directory_entry_name_utf8))
776    return ec;
777
778  it.IterationHandle = intptr_t(FindHandle.take());
779  SmallString<128> directory_entry_path(path);
780  path::append(directory_entry_path, directory_entry_name_utf8);
781  it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks);
782
783  return std::error_code();
784}
785
786std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
787  if (it.IterationHandle != 0)
788    // Closes the handle if it's valid.
789    ScopedFindHandle close(HANDLE(it.IterationHandle));
790  it.IterationHandle = 0;
791  it.CurrentEntry = directory_entry();
792  return std::error_code();
793}
794
795std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
796  WIN32_FIND_DATAW FindData;
797  if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
798    DWORD LastError = ::GetLastError();
799    // Check for end.
800    if (LastError == ERROR_NO_MORE_FILES)
801      return detail::directory_iterator_destruct(it);
802    return mapWindowsError(LastError);
803  }
804
805  size_t FilenameLen = ::wcslen(FindData.cFileName);
806  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
807      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
808                           FindData.cFileName[1] == L'.'))
809    return directory_iterator_increment(it);
810
811  SmallString<128> directory_entry_path_utf8;
812  if (std::error_code ec =
813          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
814                      directory_entry_path_utf8))
815    return ec;
816
817  it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
818  return std::error_code();
819}
820
821static std::error_code realPathFromHandle(HANDLE H,
822                                          SmallVectorImpl<char> &RealPath) {
823  RealPath.clear();
824  llvm::SmallVector<wchar_t, MAX_PATH> Buffer;
825  DWORD CountChars = ::GetFinalPathNameByHandleW(
826      H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
827  if (CountChars > Buffer.capacity()) {
828    // The buffer wasn't big enough, try again.  In this case the return value
829    // *does* indicate the size of the null terminator.
830    Buffer.reserve(CountChars);
831    CountChars = ::GetFinalPathNameByHandleW(
832        H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
833  }
834  if (CountChars == 0)
835    return mapWindowsError(GetLastError());
836
837  const wchar_t *Data = Buffer.data();
838  if (CountChars >= 4) {
839    if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
840      CountChars -= 4;
841      Data += 4;
842    }
843  }
844
845  // Convert the result from UTF-16 to UTF-8.
846  return UTF16ToUTF8(Data, CountChars, RealPath);
847}
848
849static std::error_code directoryRealPath(const Twine &Name,
850                                         SmallVectorImpl<char> &RealPath) {
851  SmallVector<wchar_t, 128> PathUTF16;
852
853  if (std::error_code EC = widenPath(Name, PathUTF16))
854    return EC;
855
856  HANDLE H =
857      ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
858                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
859                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
860  if (H == INVALID_HANDLE_VALUE)
861    return mapWindowsError(GetLastError());
862  std::error_code EC = realPathFromHandle(H, RealPath);
863  ::CloseHandle(H);
864  return EC;
865}
866
867std::error_code openFileForRead(const Twine &Name, int &ResultFD,
868                                SmallVectorImpl<char> *RealPath) {
869  SmallVector<wchar_t, 128> PathUTF16;
870
871  if (std::error_code EC = widenPath(Name, PathUTF16))
872    return EC;
873
874  HANDLE H =
875      ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
876                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
877                    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
878  if (H == INVALID_HANDLE_VALUE) {
879    DWORD LastError = ::GetLastError();
880    std::error_code EC = mapWindowsError(LastError);
881    // Provide a better error message when trying to open directories.
882    // This only runs if we failed to open the file, so there is probably
883    // no performances issues.
884    if (LastError != ERROR_ACCESS_DENIED)
885      return EC;
886    if (is_directory(Name))
887      return make_error_code(errc::is_a_directory);
888    return EC;
889  }
890
891  int FD = ::_open_osfhandle(intptr_t(H), 0);
892  if (FD == -1) {
893    ::CloseHandle(H);
894    return mapWindowsError(ERROR_INVALID_HANDLE);
895  }
896
897  // Fetch the real name of the file, if the user asked
898  if (RealPath)
899    realPathFromHandle(H, *RealPath);
900
901  ResultFD = FD;
902  return std::error_code();
903}
904
905std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
906                            sys::fs::OpenFlags Flags, unsigned Mode) {
907  // Verify that we don't have both "append" and "excl".
908  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
909         "Cannot specify both 'excl' and 'append' file creation flags!");
910
911  SmallVector<wchar_t, 128> PathUTF16;
912
913  if (std::error_code EC = widenPath(Name, PathUTF16))
914    return EC;
915
916  DWORD CreationDisposition;
917  if (Flags & F_Excl)
918    CreationDisposition = CREATE_NEW;
919  else if (Flags & F_Append)
920    CreationDisposition = OPEN_ALWAYS;
921  else
922    CreationDisposition = CREATE_ALWAYS;
923
924  DWORD Access = GENERIC_WRITE;
925  if (Flags & F_RW)
926    Access |= GENERIC_READ;
927
928  HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
929                           FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
930                           CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
931
932  if (H == INVALID_HANDLE_VALUE) {
933    DWORD LastError = ::GetLastError();
934    std::error_code EC = mapWindowsError(LastError);
935    // Provide a better error message when trying to open directories.
936    // This only runs if we failed to open the file, so there is probably
937    // no performances issues.
938    if (LastError != ERROR_ACCESS_DENIED)
939      return EC;
940    if (is_directory(Name))
941      return make_error_code(errc::is_a_directory);
942    return EC;
943  }
944
945  int OpenFlags = 0;
946  if (Flags & F_Append)
947    OpenFlags |= _O_APPEND;
948
949  if (Flags & F_Text)
950    OpenFlags |= _O_TEXT;
951
952  int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
953  if (FD == -1) {
954    ::CloseHandle(H);
955    return mapWindowsError(ERROR_INVALID_HANDLE);
956  }
957
958  ResultFD = FD;
959  return std::error_code();
960}
961
962std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
963  HANDLE FileHandle = reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
964  if (FileHandle == INVALID_HANDLE_VALUE)
965    return make_error_code(errc::bad_file_descriptor);
966
967  DWORD CharCount;
968  SmallVector<wchar_t, 1024> TempPath;
969  do {
970    CharCount = ::GetFinalPathNameByHandleW(FileHandle, TempPath.begin(),
971                                            TempPath.capacity(),
972                                            FILE_NAME_NORMALIZED);
973    if (CharCount < TempPath.capacity())
974      break;
975
976    // Reserve sufficient space for the path as well as the null character. Even
977    // though the API does not document that it is required, if we reserve just
978    // CharCount space, the function call will not store the resulting path and
979    // still report success.
980    TempPath.reserve(CharCount + 1);
981  } while (true);
982
983  if (CharCount == 0)
984    return mapWindowsError(::GetLastError());
985
986  TempPath.set_size(CharCount);
987
988  // On earlier Windows releases, the character count includes the terminating
989  // null.
990  if (TempPath.back() == L'\0') {
991    --CharCount;
992    TempPath.pop_back();
993  }
994
995  return windows::UTF16ToUTF8(TempPath.data(), CharCount, ResultPath);
996}
997
998std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
999  // Convert to utf-16.
1000  SmallVector<wchar_t, 128> Path16;
1001  std::error_code EC = widenPath(path, Path16);
1002  if (EC && !IgnoreErrors)
1003    return EC;
1004
1005  // SHFileOperation() accepts a list of paths, and so must be double null-
1006  // terminated to indicate the end of the list.  The buffer is already null
1007  // terminated, but since that null character is not considered part of the
1008  // vector's size, pushing another one will just consume that byte.  So we
1009  // need to push 2 null terminators.
1010  Path16.push_back(0);
1011  Path16.push_back(0);
1012
1013  SHFILEOPSTRUCTW shfos = {};
1014  shfos.wFunc = FO_DELETE;
1015  shfos.pFrom = Path16.data();
1016  shfos.fFlags = FOF_NO_UI;
1017
1018  int result = ::SHFileOperationW(&shfos);
1019  if (result != 0 && !IgnoreErrors)
1020    return mapWindowsError(result);
1021  return std::error_code();
1022}
1023
1024static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1025  // Path does not begin with a tilde expression.
1026  if (Path.empty() || Path[0] != '~')
1027    return;
1028
1029  StringRef PathStr(Path.begin(), Path.size());
1030  PathStr = PathStr.drop_front();
1031  StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1032
1033  if (!Expr.empty()) {
1034    // This is probably a ~username/ expression.  Don't support this on Windows.
1035    return;
1036  }
1037
1038  SmallString<128> HomeDir;
1039  if (!path::home_directory(HomeDir)) {
1040    // For some reason we couldn't get the home directory.  Just exit.
1041    return;
1042  }
1043
1044  // Overwrite the first character and insert the rest.
1045  Path[0] = HomeDir[0];
1046  Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1047}
1048
1049std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1050                          bool expand_tilde) {
1051  dest.clear();
1052  if (path.isTriviallyEmpty())
1053    return std::error_code();
1054
1055  if (expand_tilde) {
1056    SmallString<128> Storage;
1057    path.toVector(Storage);
1058    expandTildeExpr(Storage);
1059    return real_path(Storage, dest, false);
1060  }
1061
1062  if (is_directory(path))
1063    return directoryRealPath(path, dest);
1064
1065  int fd;
1066  if (std::error_code EC = llvm::sys::fs::openFileForRead(path, fd, &dest))
1067    return EC;
1068  ::close(fd);
1069  return std::error_code();
1070}
1071
1072} // end namespace fs
1073
1074namespace path {
1075static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1076                               SmallVectorImpl<char> &result) {
1077  wchar_t *path = nullptr;
1078  if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1079    return false;
1080
1081  bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1082  ::CoTaskMemFree(path);
1083  return ok;
1084}
1085
1086bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1087  return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1088}
1089
1090bool home_directory(SmallVectorImpl<char> &result) {
1091  return getKnownFolderPath(FOLDERID_Profile, result);
1092}
1093
1094static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1095  SmallVector<wchar_t, 1024> Buf;
1096  size_t Size = 1024;
1097  do {
1098    Buf.reserve(Size);
1099    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1100    if (Size == 0)
1101      return false;
1102
1103    // Try again with larger buffer.
1104  } while (Size > Buf.capacity());
1105  Buf.set_size(Size);
1106
1107  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1108}
1109
1110static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1111  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1112  for (auto *Env : EnvironmentVariables) {
1113    if (getTempDirEnvVar(Env, Res))
1114      return true;
1115  }
1116  return false;
1117}
1118
1119void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1120  (void)ErasedOnReboot;
1121  Result.clear();
1122
1123  // Check whether the temporary directory is specified by an environment var.
1124  // This matches GetTempPath logic to some degree. GetTempPath is not used
1125  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1126  // (fixed on Windows 8).
1127  if (getTempDirEnvVar(Result)) {
1128    assert(!Result.empty() && "Unexpected empty path");
1129    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1130    fs::make_absolute(Result); // Make it absolute if not already.
1131    return;
1132  }
1133
1134  // Fall back to a system default.
1135  const char *DefaultResult = "C:\\Temp";
1136  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1137}
1138} // end namespace path
1139
1140namespace windows {
1141std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1142                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1143  if (!utf8.empty()) {
1144    int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1145                                    utf8.size(), utf16.begin(), 0);
1146
1147    if (len == 0)
1148      return mapWindowsError(::GetLastError());
1149
1150    utf16.reserve(len + 1);
1151    utf16.set_size(len);
1152
1153    len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1154                                utf8.size(), utf16.begin(), utf16.size());
1155
1156    if (len == 0)
1157      return mapWindowsError(::GetLastError());
1158  }
1159
1160  // Make utf16 null terminated.
1161  utf16.push_back(0);
1162  utf16.pop_back();
1163
1164  return std::error_code();
1165}
1166
1167static
1168std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1169                                size_t utf16_len,
1170                                llvm::SmallVectorImpl<char> &utf8) {
1171  if (utf16_len) {
1172    // Get length.
1173    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
1174                                    0, NULL, NULL);
1175
1176    if (len == 0)
1177      return mapWindowsError(::GetLastError());
1178
1179    utf8.reserve(len);
1180    utf8.set_size(len);
1181
1182    // Now do the actual conversion.
1183    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
1184                                utf8.size(), NULL, NULL);
1185
1186    if (len == 0)
1187      return mapWindowsError(::GetLastError());
1188  }
1189
1190  // Make utf8 null terminated.
1191  utf8.push_back(0);
1192  utf8.pop_back();
1193
1194  return std::error_code();
1195}
1196
1197std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1198                            llvm::SmallVectorImpl<char> &utf8) {
1199  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1200}
1201
1202std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1203                             llvm::SmallVectorImpl<char> &utf8) {
1204  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
1205}
1206
1207} // end namespace windows
1208} // end namespace sys
1209} // end namespace llvm
1210