1//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Windows specific implementation of the Path API.
10//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic Windows code that
15//===          is guaranteed to work on *all* Windows variants.
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/Support/ConvertUTF.h"
20#include "llvm/Support/WindowsError.h"
21#include <fcntl.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24
25// These two headers must be included last, and make sure shlobj is required
26// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
27#include "llvm/Support/Windows/WindowsSupport.h"
28#include <shellapi.h>
29#include <shlobj.h>
30
31#undef max
32
33// MinGW doesn't define this.
34#ifndef _ERRNO_T_DEFINED
35#define _ERRNO_T_DEFINED
36typedef int errno_t;
37#endif
38
39#ifdef _MSC_VER
40# pragma comment(lib, "advapi32.lib")  // This provides CryptAcquireContextW.
41# pragma comment(lib, "ole32.lib")     // This provides CoTaskMemFree
42#endif
43
44using namespace llvm;
45
46using llvm::sys::windows::UTF8ToUTF16;
47using llvm::sys::windows::CurCPToUTF16;
48using llvm::sys::windows::UTF16ToUTF8;
49using llvm::sys::windows::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 windows {
64
65// Convert a UTF-8 path to UTF-16. Also, if the absolute equivalent of the path
66// is longer than the limit that the Win32 Unicode File API can tolerate, make
67// it an absolute normalized path prefixed by '\\?\'.
68std::error_code widenPath(const Twine &Path8, SmallVectorImpl<wchar_t> &Path16,
69                          size_t MaxPathLen) {
70  assert(MaxPathLen <= MAX_PATH);
71
72  // Several operations would convert Path8 to SmallString; more efficient to do
73  // it once up front.
74  SmallString<MAX_PATH> Path8Str;
75  Path8.toVector(Path8Str);
76
77  if (std::error_code EC = UTF8ToUTF16(Path8Str, Path16))
78    return EC;
79
80  const bool IsAbsolute = llvm::sys::path::is_absolute(Path8);
81  size_t CurPathLen;
82  if (IsAbsolute)
83    CurPathLen = 0; // No contribution from current_path needed.
84  else {
85    CurPathLen = ::GetCurrentDirectoryW(
86        0, NULL); // Returns the size including the null terminator.
87    if (CurPathLen == 0)
88      return mapWindowsError(::GetLastError());
89  }
90
91  const char *const LongPathPrefix = "\\\\?\\";
92
93  if ((Path16.size() + CurPathLen) < MaxPathLen ||
94      Path8Str.startswith(LongPathPrefix))
95    return std::error_code();
96
97  if (!IsAbsolute) {
98    if (std::error_code EC = llvm::sys::fs::make_absolute(Path8Str))
99      return EC;
100  }
101
102  // Remove '.' and '..' because long paths treat these as real path components.
103  llvm::sys::path::native(Path8Str, path::Style::windows);
104  llvm::sys::path::remove_dots(Path8Str, true);
105
106  const StringRef RootName = llvm::sys::path::root_name(Path8Str);
107  assert(!RootName.empty() &&
108         "Root name cannot be empty for an absolute path!");
109
110  SmallString<2 * MAX_PATH> FullPath(LongPathPrefix);
111  if (RootName[1] != ':') { // Check if UNC.
112    FullPath.append("UNC\\");
113    FullPath.append(Path8Str.begin() + 2, Path8Str.end());
114  } else
115    FullPath.append(Path8Str);
116
117  return UTF8ToUTF16(FullPath, Path16);
118}
119
120} // end namespace windows
121
122namespace fs {
123
124const file_t kInvalidFile = INVALID_HANDLE_VALUE;
125
126std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
127  SmallVector<wchar_t, MAX_PATH> PathName;
128  DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
129
130  // A zero return value indicates a failure other than insufficient space.
131  if (Size == 0)
132    return "";
133
134  // Insufficient space is determined by a return value equal to the size of
135  // the buffer passed in.
136  if (Size == PathName.capacity())
137    return "";
138
139  // On success, GetModuleFileNameW returns the number of characters written to
140  // the buffer not including the NULL terminator.
141  PathName.set_size(Size);
142
143  // Convert the result from UTF-16 to UTF-8.
144  SmallVector<char, MAX_PATH> PathNameUTF8;
145  if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
146    return "";
147
148  return std::string(PathNameUTF8.data());
149}
150
151UniqueID file_status::getUniqueID() const {
152  // The file is uniquely identified by the volume serial number along
153  // with the 64-bit file identifier.
154  uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
155                    static_cast<uint64_t>(FileIndexLow);
156
157  return UniqueID(VolumeSerialNumber, FileID);
158}
159
160ErrorOr<space_info> disk_space(const Twine &Path) {
161  ULARGE_INTEGER Avail, Total, Free;
162  if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
163    return mapWindowsError(::GetLastError());
164  space_info SpaceInfo;
165  SpaceInfo.capacity =
166      (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
167  SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
168  SpaceInfo.available =
169      (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
170  return SpaceInfo;
171}
172
173TimePoint<> basic_file_status::getLastAccessedTime() const {
174  FILETIME Time;
175  Time.dwLowDateTime = LastAccessedTimeLow;
176  Time.dwHighDateTime = LastAccessedTimeHigh;
177  return toTimePoint(Time);
178}
179
180TimePoint<> basic_file_status::getLastModificationTime() const {
181  FILETIME Time;
182  Time.dwLowDateTime = LastWriteTimeLow;
183  Time.dwHighDateTime = LastWriteTimeHigh;
184  return toTimePoint(Time);
185}
186
187uint32_t file_status::getLinkCount() const {
188  return NumLinks;
189}
190
191std::error_code current_path(SmallVectorImpl<char> &result) {
192  SmallVector<wchar_t, MAX_PATH> cur_path;
193  DWORD len = MAX_PATH;
194
195  do {
196    cur_path.reserve(len);
197    len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
198
199    // A zero return value indicates a failure other than insufficient space.
200    if (len == 0)
201      return mapWindowsError(::GetLastError());
202
203    // If there's insufficient space, the len returned is larger than the len
204    // given.
205  } while (len > cur_path.capacity());
206
207  // On success, GetCurrentDirectoryW returns the number of characters not
208  // including the null-terminator.
209  cur_path.set_size(len);
210  return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
211}
212
213std::error_code set_current_path(const Twine &path) {
214  // Convert to utf-16.
215  SmallVector<wchar_t, 128> wide_path;
216  if (std::error_code ec = widenPath(path, wide_path))
217    return ec;
218
219  if (!::SetCurrentDirectoryW(wide_path.begin()))
220    return mapWindowsError(::GetLastError());
221
222  return std::error_code();
223}
224
225std::error_code create_directory(const Twine &path, bool IgnoreExisting,
226                                 perms Perms) {
227  SmallVector<wchar_t, 128> path_utf16;
228
229  // CreateDirectoryW has a lower maximum path length as it must leave room for
230  // an 8.3 filename.
231  if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))
232    return ec;
233
234  if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
235    DWORD LastError = ::GetLastError();
236    if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
237      return mapWindowsError(LastError);
238  }
239
240  return std::error_code();
241}
242
243// We can't use symbolic links for windows.
244std::error_code create_link(const Twine &to, const Twine &from) {
245  // Convert to utf-16.
246  SmallVector<wchar_t, 128> wide_from;
247  SmallVector<wchar_t, 128> wide_to;
248  if (std::error_code ec = widenPath(from, wide_from))
249    return ec;
250  if (std::error_code ec = widenPath(to, wide_to))
251    return ec;
252
253  if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
254    return mapWindowsError(::GetLastError());
255
256  return std::error_code();
257}
258
259std::error_code create_hard_link(const Twine &to, const Twine &from) {
260  return create_link(to, from);
261}
262
263std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
264  SmallVector<wchar_t, 128> path_utf16;
265
266  if (std::error_code ec = widenPath(path, path_utf16))
267    return ec;
268
269  // We don't know whether this is a file or a directory, and remove() can
270  // accept both. The usual way to delete a file or directory is to use one of
271  // the DeleteFile or RemoveDirectory functions, but that requires you to know
272  // which one it is. We could stat() the file to determine that, but that would
273  // cost us additional system calls, which can be slow in a directory
274  // containing a large number of files. So instead we call CreateFile directly.
275  // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
276  // file to be deleted once it is closed. We also use the flags
277  // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
278  // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
279  ScopedFileHandle h(::CreateFileW(
280      c_str(path_utf16), DELETE,
281      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
282      OPEN_EXISTING,
283      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
284          FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
285      NULL));
286  if (!h) {
287    std::error_code EC = mapWindowsError(::GetLastError());
288    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
289      return EC;
290  }
291
292  return std::error_code();
293}
294
295static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
296                                         bool &Result) {
297  SmallVector<wchar_t, 128> VolumePath;
298  size_t Len = 128;
299  while (true) {
300    VolumePath.resize(Len);
301    BOOL Success =
302        ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
303
304    if (Success)
305      break;
306
307    DWORD Err = ::GetLastError();
308    if (Err != ERROR_INSUFFICIENT_BUFFER)
309      return mapWindowsError(Err);
310
311    Len *= 2;
312  }
313  // If the output buffer has exactly enough space for the path name, but not
314  // the null terminator, it will leave the output unterminated.  Push a null
315  // terminator onto the end to ensure that this never happens.
316  VolumePath.push_back(L'\0');
317  VolumePath.set_size(wcslen(VolumePath.data()));
318  const wchar_t *P = VolumePath.data();
319
320  UINT Type = ::GetDriveTypeW(P);
321  switch (Type) {
322  case DRIVE_FIXED:
323    Result = true;
324    return std::error_code();
325  case DRIVE_REMOTE:
326  case DRIVE_CDROM:
327  case DRIVE_RAMDISK:
328  case DRIVE_REMOVABLE:
329    Result = false;
330    return std::error_code();
331  default:
332    return make_error_code(errc::no_such_file_or_directory);
333  }
334  llvm_unreachable("Unreachable!");
335}
336
337std::error_code is_local(const Twine &path, bool &result) {
338  if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
339    return make_error_code(errc::no_such_file_or_directory);
340
341  SmallString<128> Storage;
342  StringRef P = path.toStringRef(Storage);
343
344  // Convert to utf-16.
345  SmallVector<wchar_t, 128> WidePath;
346  if (std::error_code ec = widenPath(P, WidePath))
347    return ec;
348  return is_local_internal(WidePath, result);
349}
350
351static std::error_code realPathFromHandle(HANDLE H,
352                                          SmallVectorImpl<wchar_t> &Buffer) {
353  DWORD CountChars = ::GetFinalPathNameByHandleW(
354      H, Buffer.begin(), Buffer.capacity(), FILE_NAME_NORMALIZED);
355  if (CountChars && CountChars >= Buffer.capacity()) {
356    // The buffer wasn't big enough, try again.  In this case the return value
357    // *does* indicate the size of the null terminator.
358    Buffer.reserve(CountChars);
359    CountChars = ::GetFinalPathNameByHandleW(
360        H, Buffer.begin(), Buffer.capacity(), FILE_NAME_NORMALIZED);
361  }
362  if (CountChars == 0)
363    return mapWindowsError(GetLastError());
364  Buffer.set_size(CountChars);
365  return std::error_code();
366}
367
368static std::error_code realPathFromHandle(HANDLE H,
369                                          SmallVectorImpl<char> &RealPath) {
370  RealPath.clear();
371  SmallVector<wchar_t, MAX_PATH> Buffer;
372  if (std::error_code EC = realPathFromHandle(H, Buffer))
373    return EC;
374
375  // Strip the \\?\ prefix. We don't want it ending up in output, and such
376  // paths don't get canonicalized by file APIs.
377  wchar_t *Data = Buffer.data();
378  DWORD CountChars = Buffer.size();
379  if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
380    // Convert \\?\UNC\foo\bar to \\foo\bar
381    CountChars -= 6;
382    Data += 6;
383    Data[0] = '\\';
384  } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
385    // Convert \\?\c:\foo to c:\foo
386    CountChars -= 4;
387    Data += 4;
388  }
389
390  // Convert the result from UTF-16 to UTF-8.
391  return UTF16ToUTF8(Data, CountChars, RealPath);
392}
393
394std::error_code is_local(int FD, bool &Result) {
395  SmallVector<wchar_t, 128> FinalPath;
396  HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
397
398  if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
399    return EC;
400
401  return is_local_internal(FinalPath, Result);
402}
403
404static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
405  FILE_DISPOSITION_INFO Disposition;
406  Disposition.DeleteFile = Delete;
407  if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
408                                  sizeof(Disposition)))
409    return mapWindowsError(::GetLastError());
410  return std::error_code();
411}
412
413static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
414                                       bool ReplaceIfExists) {
415  SmallVector<wchar_t, 0> ToWide;
416  if (auto EC = widenPath(To, ToWide))
417    return EC;
418
419  std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
420                                  (ToWide.size() * sizeof(wchar_t)));
421  FILE_RENAME_INFO &RenameInfo =
422      *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
423  RenameInfo.ReplaceIfExists = ReplaceIfExists;
424  RenameInfo.RootDirectory = 0;
425  RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
426  std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
427
428  SetLastError(ERROR_SUCCESS);
429  if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
430                                  RenameInfoBuf.size())) {
431    unsigned Error = GetLastError();
432    if (Error == ERROR_SUCCESS)
433      Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
434    return mapWindowsError(Error);
435  }
436
437  return std::error_code();
438}
439
440static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
441  SmallVector<wchar_t, 128> WideTo;
442  if (std::error_code EC = widenPath(To, WideTo))
443    return EC;
444
445  // We normally expect this loop to succeed after a few iterations. If it
446  // requires more than 200 tries, it's more likely that the failures are due to
447  // a true error, so stop trying.
448  for (unsigned Retry = 0; Retry != 200; ++Retry) {
449    auto EC = rename_internal(FromHandle, To, true);
450
451    if (EC ==
452        std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
453      // Wine doesn't support SetFileInformationByHandle in rename_internal.
454      // Fall back to MoveFileEx.
455      SmallVector<wchar_t, MAX_PATH> WideFrom;
456      if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
457        return EC2;
458      if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
459                        MOVEFILE_REPLACE_EXISTING))
460        return std::error_code();
461      return mapWindowsError(GetLastError());
462    }
463
464    if (!EC || EC != errc::permission_denied)
465      return EC;
466
467    // The destination file probably exists and is currently open in another
468    // process, either because the file was opened without FILE_SHARE_DELETE or
469    // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
470    // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
471    // to arrange for the destination file to be deleted when the other process
472    // closes it.
473    ScopedFileHandle ToHandle(
474        ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
475                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
476                      NULL, OPEN_EXISTING,
477                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
478    if (!ToHandle) {
479      auto EC = mapWindowsError(GetLastError());
480      // Another process might have raced with us and moved the existing file
481      // out of the way before we had a chance to open it. If that happens, try
482      // to rename the source file again.
483      if (EC == errc::no_such_file_or_directory)
484        continue;
485      return EC;
486    }
487
488    BY_HANDLE_FILE_INFORMATION FI;
489    if (!GetFileInformationByHandle(ToHandle, &FI))
490      return mapWindowsError(GetLastError());
491
492    // Try to find a unique new name for the destination file.
493    for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
494      std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
495      if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
496        if (EC == errc::file_exists || EC == errc::permission_denied) {
497          // Again, another process might have raced with us and moved the file
498          // before we could move it. Check whether this is the case, as it
499          // might have caused the permission denied error. If that was the
500          // case, we don't need to move it ourselves.
501          ScopedFileHandle ToHandle2(::CreateFileW(
502              WideTo.begin(), 0,
503              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
504              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
505          if (!ToHandle2) {
506            auto EC = mapWindowsError(GetLastError());
507            if (EC == errc::no_such_file_or_directory)
508              break;
509            return EC;
510          }
511          BY_HANDLE_FILE_INFORMATION FI2;
512          if (!GetFileInformationByHandle(ToHandle2, &FI2))
513            return mapWindowsError(GetLastError());
514          if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
515              FI.nFileIndexLow != FI2.nFileIndexLow ||
516              FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
517            break;
518          continue;
519        }
520        return EC;
521      }
522      break;
523    }
524
525    // Okay, the old destination file has probably been moved out of the way at
526    // this point, so try to rename the source file again. Still, another
527    // process might have raced with us to create and open the destination
528    // file, so we need to keep doing this until we succeed.
529  }
530
531  // The most likely root cause.
532  return errc::permission_denied;
533}
534
535static std::error_code rename_fd(int FromFD, const Twine &To) {
536  HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
537  return rename_handle(FromHandle, To);
538}
539
540std::error_code rename(const Twine &From, const Twine &To) {
541  // Convert to utf-16.
542  SmallVector<wchar_t, 128> WideFrom;
543  if (std::error_code EC = widenPath(From, WideFrom))
544    return EC;
545
546  ScopedFileHandle FromHandle;
547  // Retry this a few times to defeat badly behaved file system scanners.
548  for (unsigned Retry = 0; Retry != 200; ++Retry) {
549    if (Retry != 0)
550      ::Sleep(10);
551    FromHandle =
552        ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
553                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
554                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
555    if (FromHandle)
556      break;
557
558    // We don't want to loop if the file doesn't exist.
559    auto EC = mapWindowsError(GetLastError());
560    if (EC == errc::no_such_file_or_directory)
561      return EC;
562  }
563  if (!FromHandle)
564    return mapWindowsError(GetLastError());
565
566  return rename_handle(FromHandle, To);
567}
568
569std::error_code resize_file(int FD, uint64_t Size) {
570#ifdef HAVE__CHSIZE_S
571  errno_t error = ::_chsize_s(FD, Size);
572#else
573  errno_t error = ::_chsize(FD, Size);
574#endif
575  return std::error_code(error, std::generic_category());
576}
577
578std::error_code access(const Twine &Path, AccessMode Mode) {
579  SmallVector<wchar_t, 128> PathUtf16;
580
581  if (std::error_code EC = widenPath(Path, PathUtf16))
582    return EC;
583
584  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
585
586  if (Attributes == INVALID_FILE_ATTRIBUTES) {
587    // See if the file didn't actually exist.
588    DWORD LastError = ::GetLastError();
589    if (LastError != ERROR_FILE_NOT_FOUND &&
590        LastError != ERROR_PATH_NOT_FOUND)
591      return mapWindowsError(LastError);
592    return errc::no_such_file_or_directory;
593  }
594
595  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
596    return errc::permission_denied;
597
598  return std::error_code();
599}
600
601bool can_execute(const Twine &Path) {
602  return !access(Path, AccessMode::Execute) ||
603         !access(Path + ".exe", AccessMode::Execute);
604}
605
606bool equivalent(file_status A, file_status B) {
607  assert(status_known(A) && status_known(B));
608  return A.FileIndexHigh         == B.FileIndexHigh &&
609         A.FileIndexLow          == B.FileIndexLow &&
610         A.FileSizeHigh          == B.FileSizeHigh &&
611         A.FileSizeLow           == B.FileSizeLow &&
612         A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
613         A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
614         A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
615         A.LastWriteTimeLow      == B.LastWriteTimeLow &&
616         A.VolumeSerialNumber    == B.VolumeSerialNumber;
617}
618
619std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
620  file_status fsA, fsB;
621  if (std::error_code ec = status(A, fsA))
622    return ec;
623  if (std::error_code ec = status(B, fsB))
624    return ec;
625  result = equivalent(fsA, fsB);
626  return std::error_code();
627}
628
629static bool isReservedName(StringRef path) {
630  // This list of reserved names comes from MSDN, at:
631  // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
632  static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
633                                                "com1", "com2", "com3", "com4",
634                                                "com5", "com6", "com7", "com8",
635                                                "com9", "lpt1", "lpt2", "lpt3",
636                                                "lpt4", "lpt5", "lpt6", "lpt7",
637                                                "lpt8", "lpt9" };
638
639  // First, check to see if this is a device namespace, which always
640  // starts with \\.\, since device namespaces are not legal file paths.
641  if (path.startswith("\\\\.\\"))
642    return true;
643
644  // Then compare against the list of ancient reserved names.
645  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
646    if (path.equals_lower(sReservedNames[i]))
647      return true;
648  }
649
650  // The path isn't what we consider reserved.
651  return false;
652}
653
654static file_type file_type_from_attrs(DWORD Attrs) {
655  return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
656                                            : file_type::regular_file;
657}
658
659static perms perms_from_attrs(DWORD Attrs) {
660  return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
661}
662
663static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
664  if (FileHandle == INVALID_HANDLE_VALUE)
665    goto handle_status_error;
666
667  switch (::GetFileType(FileHandle)) {
668  default:
669    llvm_unreachable("Don't know anything about this file type");
670  case FILE_TYPE_UNKNOWN: {
671    DWORD Err = ::GetLastError();
672    if (Err != NO_ERROR)
673      return mapWindowsError(Err);
674    Result = file_status(file_type::type_unknown);
675    return std::error_code();
676  }
677  case FILE_TYPE_DISK:
678    break;
679  case FILE_TYPE_CHAR:
680    Result = file_status(file_type::character_file);
681    return std::error_code();
682  case FILE_TYPE_PIPE:
683    Result = file_status(file_type::fifo_file);
684    return std::error_code();
685  }
686
687  BY_HANDLE_FILE_INFORMATION Info;
688  if (!::GetFileInformationByHandle(FileHandle, &Info))
689    goto handle_status_error;
690
691  Result = file_status(
692      file_type_from_attrs(Info.dwFileAttributes),
693      perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
694      Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
695      Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
696      Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
697      Info.nFileIndexHigh, Info.nFileIndexLow);
698  return std::error_code();
699
700handle_status_error:
701  DWORD LastError = ::GetLastError();
702  if (LastError == ERROR_FILE_NOT_FOUND ||
703      LastError == ERROR_PATH_NOT_FOUND)
704    Result = file_status(file_type::file_not_found);
705  else if (LastError == ERROR_SHARING_VIOLATION)
706    Result = file_status(file_type::type_unknown);
707  else
708    Result = file_status(file_type::status_error);
709  return mapWindowsError(LastError);
710}
711
712std::error_code status(const Twine &path, file_status &result, bool Follow) {
713  ++NumStatusCalls;
714  SmallString<128> path_storage;
715  SmallVector<wchar_t, 128> path_utf16;
716
717  StringRef path8 = path.toStringRef(path_storage);
718  if (isReservedName(path8)) {
719    result = file_status(file_type::character_file);
720    return std::error_code();
721  }
722
723  if (std::error_code ec = widenPath(path8, path_utf16))
724    return ec;
725
726  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
727  if (attr == INVALID_FILE_ATTRIBUTES)
728    return getStatus(INVALID_HANDLE_VALUE, result);
729
730  DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
731  // Handle reparse points.
732  if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
733    Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
734
735  ScopedFileHandle h(
736      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
737                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
738                    NULL, OPEN_EXISTING, Flags, 0));
739  if (!h)
740    return getStatus(INVALID_HANDLE_VALUE, result);
741
742  return getStatus(h, result);
743}
744
745std::error_code status(int FD, file_status &Result) {
746  ++NumStatusCalls;
747  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
748  return getStatus(FileHandle, Result);
749}
750
751std::error_code status(file_t FileHandle, file_status &Result) {
752  ++NumStatusCalls;
753  return getStatus(FileHandle, Result);
754}
755
756unsigned getUmask() {
757  return 0;
758}
759
760std::error_code setPermissions(const Twine &Path, perms Permissions) {
761  SmallVector<wchar_t, 128> PathUTF16;
762  if (std::error_code EC = widenPath(Path, PathUTF16))
763    return EC;
764
765  DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
766  if (Attributes == INVALID_FILE_ATTRIBUTES)
767    return mapWindowsError(GetLastError());
768
769  // There are many Windows file attributes that are not to do with the file
770  // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
771  // them.
772  if (Permissions & all_write) {
773    Attributes &= ~FILE_ATTRIBUTE_READONLY;
774    if (Attributes == 0)
775      // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
776      Attributes |= FILE_ATTRIBUTE_NORMAL;
777  }
778  else {
779    Attributes |= FILE_ATTRIBUTE_READONLY;
780    // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
781    // remove it, if it is present.
782    Attributes &= ~FILE_ATTRIBUTE_NORMAL;
783  }
784
785  if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
786    return mapWindowsError(GetLastError());
787
788  return std::error_code();
789}
790
791std::error_code setPermissions(int FD, perms Permissions) {
792  // FIXME Not implemented.
793  return std::make_error_code(std::errc::not_supported);
794}
795
796std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
797                                                 TimePoint<> ModificationTime) {
798  FILETIME AccessFT = toFILETIME(AccessTime);
799  FILETIME ModifyFT = toFILETIME(ModificationTime);
800  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
801  if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
802    return mapWindowsError(::GetLastError());
803  return std::error_code();
804}
805
806std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
807                                         uint64_t Offset, mapmode Mode) {
808  this->Mode = Mode;
809  if (OrigFileHandle == INVALID_HANDLE_VALUE)
810    return make_error_code(errc::bad_file_descriptor);
811
812  DWORD flprotect;
813  switch (Mode) {
814  case readonly:  flprotect = PAGE_READONLY; break;
815  case readwrite: flprotect = PAGE_READWRITE; break;
816  case priv:      flprotect = PAGE_WRITECOPY; break;
817  }
818
819  HANDLE FileMappingHandle =
820      ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
821                           Hi_32(Size),
822                           Lo_32(Size),
823                           0);
824  if (FileMappingHandle == NULL) {
825    std::error_code ec = mapWindowsError(GetLastError());
826    return ec;
827  }
828
829  DWORD dwDesiredAccess;
830  switch (Mode) {
831  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
832  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
833  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
834  }
835  Mapping = ::MapViewOfFile(FileMappingHandle,
836                            dwDesiredAccess,
837                            Offset >> 32,
838                            Offset & 0xffffffff,
839                            Size);
840  if (Mapping == NULL) {
841    std::error_code ec = mapWindowsError(GetLastError());
842    ::CloseHandle(FileMappingHandle);
843    return ec;
844  }
845
846  if (Size == 0) {
847    MEMORY_BASIC_INFORMATION mbi;
848    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
849    if (Result == 0) {
850      std::error_code ec = mapWindowsError(GetLastError());
851      ::UnmapViewOfFile(Mapping);
852      ::CloseHandle(FileMappingHandle);
853      return ec;
854    }
855    Size = mbi.RegionSize;
856  }
857
858  // Close the file mapping handle, as it's kept alive by the file mapping. But
859  // neither the file mapping nor the file mapping handle keep the file handle
860  // alive, so we need to keep a reference to the file in case all other handles
861  // are closed and the file is deleted, which may cause invalid data to be read
862  // from the file.
863  ::CloseHandle(FileMappingHandle);
864  if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
865                         ::GetCurrentProcess(), &FileHandle, 0, 0,
866                         DUPLICATE_SAME_ACCESS)) {
867    std::error_code ec = mapWindowsError(GetLastError());
868    ::UnmapViewOfFile(Mapping);
869    return ec;
870  }
871
872  return std::error_code();
873}
874
875mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
876                                       size_t length, uint64_t offset,
877                                       std::error_code &ec)
878    : Size(length), Mapping() {
879  ec = init(fd, offset, mode);
880  if (ec)
881    Mapping = 0;
882}
883
884static bool hasFlushBufferKernelBug() {
885  static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
886  return Ret;
887}
888
889static bool isEXE(StringRef Magic) {
890  static const char PEMagic[] = {'P', 'E', '\0', '\0'};
891  if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
892    uint32_t off = read32le(Magic.data() + 0x3c);
893    // PE/COFF file, either EXE or DLL.
894    if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
895      return true;
896  }
897  return false;
898}
899
900mapped_file_region::~mapped_file_region() {
901  if (Mapping) {
902
903    bool Exe = isEXE(StringRef((char *)Mapping, Size));
904
905    ::UnmapViewOfFile(Mapping);
906
907    if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
908      // There is a Windows kernel bug, the exact trigger conditions of which
909      // are not well understood.  When triggered, dirty pages are not properly
910      // flushed and subsequent process's attempts to read a file can return
911      // invalid data.  Calling FlushFileBuffers on the write handle is
912      // sufficient to ensure that this bug is not triggered.
913      // The bug only occurs when writing an executable and executing it right
914      // after, under high I/O pressure.
915      ::FlushFileBuffers(FileHandle);
916    }
917
918    ::CloseHandle(FileHandle);
919  }
920}
921
922size_t mapped_file_region::size() const {
923  assert(Mapping && "Mapping failed but used anyway!");
924  return Size;
925}
926
927char *mapped_file_region::data() const {
928  assert(Mapping && "Mapping failed but used anyway!");
929  return reinterpret_cast<char*>(Mapping);
930}
931
932const char *mapped_file_region::const_data() const {
933  assert(Mapping && "Mapping failed but used anyway!");
934  return reinterpret_cast<const char*>(Mapping);
935}
936
937int mapped_file_region::alignment() {
938  SYSTEM_INFO SysInfo;
939  ::GetSystemInfo(&SysInfo);
940  return SysInfo.dwAllocationGranularity;
941}
942
943static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
944  return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
945                           perms_from_attrs(FindData->dwFileAttributes),
946                           FindData->ftLastAccessTime.dwHighDateTime,
947                           FindData->ftLastAccessTime.dwLowDateTime,
948                           FindData->ftLastWriteTime.dwHighDateTime,
949                           FindData->ftLastWriteTime.dwLowDateTime,
950                           FindData->nFileSizeHigh, FindData->nFileSizeLow);
951}
952
953std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
954                                                     StringRef Path,
955                                                     bool FollowSymlinks) {
956  SmallVector<wchar_t, 128> PathUTF16;
957
958  if (std::error_code EC = widenPath(Path, PathUTF16))
959    return EC;
960
961  // Convert path to the format that Windows is happy with.
962  size_t PathUTF16Len = PathUTF16.size();
963  if (PathUTF16Len > 0 && !is_separator(PathUTF16[PathUTF16Len - 1]) &&
964      PathUTF16[PathUTF16Len - 1] != L':') {
965    PathUTF16.push_back(L'\\');
966    PathUTF16.push_back(L'*');
967  } else {
968    PathUTF16.push_back(L'*');
969  }
970
971  //  Get the first directory entry.
972  WIN32_FIND_DATAW FirstFind;
973  ScopedFindHandle FindHandle(::FindFirstFileExW(
974      c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
975      NULL, FIND_FIRST_EX_LARGE_FETCH));
976  if (!FindHandle)
977    return mapWindowsError(::GetLastError());
978
979  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
980  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
981         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
982                              FirstFind.cFileName[1] == L'.'))
983    if (!::FindNextFileW(FindHandle, &FirstFind)) {
984      DWORD LastError = ::GetLastError();
985      // Check for end.
986      if (LastError == ERROR_NO_MORE_FILES)
987        return detail::directory_iterator_destruct(IT);
988      return mapWindowsError(LastError);
989    } else
990      FilenameLen = ::wcslen(FirstFind.cFileName);
991
992  // Construct the current directory entry.
993  SmallString<128> DirectoryEntryNameUTF8;
994  if (std::error_code EC =
995          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
996                      DirectoryEntryNameUTF8))
997    return EC;
998
999  IT.IterationHandle = intptr_t(FindHandle.take());
1000  SmallString<128> DirectoryEntryPath(Path);
1001  path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
1002  IT.CurrentEntry =
1003      directory_entry(DirectoryEntryPath, FollowSymlinks,
1004                      file_type_from_attrs(FirstFind.dwFileAttributes),
1005                      status_from_find_data(&FirstFind));
1006
1007  return std::error_code();
1008}
1009
1010std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1011  if (IT.IterationHandle != 0)
1012    // Closes the handle if it's valid.
1013    ScopedFindHandle close(HANDLE(IT.IterationHandle));
1014  IT.IterationHandle = 0;
1015  IT.CurrentEntry = directory_entry();
1016  return std::error_code();
1017}
1018
1019std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1020  WIN32_FIND_DATAW FindData;
1021  if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1022    DWORD LastError = ::GetLastError();
1023    // Check for end.
1024    if (LastError == ERROR_NO_MORE_FILES)
1025      return detail::directory_iterator_destruct(IT);
1026    return mapWindowsError(LastError);
1027  }
1028
1029  size_t FilenameLen = ::wcslen(FindData.cFileName);
1030  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1031      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1032                           FindData.cFileName[1] == L'.'))
1033    return directory_iterator_increment(IT);
1034
1035  SmallString<128> DirectoryEntryPathUTF8;
1036  if (std::error_code EC =
1037          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1038                      DirectoryEntryPathUTF8))
1039    return EC;
1040
1041  IT.CurrentEntry.replace_filename(
1042      Twine(DirectoryEntryPathUTF8),
1043      file_type_from_attrs(FindData.dwFileAttributes),
1044      status_from_find_data(&FindData));
1045  return std::error_code();
1046}
1047
1048ErrorOr<basic_file_status> directory_entry::status() const {
1049  return Status;
1050}
1051
1052static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1053                                      OpenFlags Flags) {
1054  int CrtOpenFlags = 0;
1055  if (Flags & OF_Append)
1056    CrtOpenFlags |= _O_APPEND;
1057
1058  if (Flags & OF_Text)
1059    CrtOpenFlags |= _O_TEXT;
1060
1061  ResultFD = -1;
1062  if (!H)
1063    return errorToErrorCode(H.takeError());
1064
1065  ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1066  if (ResultFD == -1) {
1067    ::CloseHandle(*H);
1068    return mapWindowsError(ERROR_INVALID_HANDLE);
1069  }
1070  return std::error_code();
1071}
1072
1073static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1074  // This is a compatibility hack.  Really we should respect the creation
1075  // disposition, but a lot of old code relied on the implicit assumption that
1076  // OF_Append implied it would open an existing file.  Since the disposition is
1077  // now explicit and defaults to CD_CreateAlways, this assumption would cause
1078  // any usage of OF_Append to append to a new file, even if the file already
1079  // existed.  A better solution might have two new creation dispositions:
1080  // CD_AppendAlways and CD_AppendNew.  This would also address the problem of
1081  // OF_Append being used on a read-only descriptor, which doesn't make sense.
1082  if (Flags & OF_Append)
1083    return OPEN_ALWAYS;
1084
1085  switch (Disp) {
1086  case CD_CreateAlways:
1087    return CREATE_ALWAYS;
1088  case CD_CreateNew:
1089    return CREATE_NEW;
1090  case CD_OpenAlways:
1091    return OPEN_ALWAYS;
1092  case CD_OpenExisting:
1093    return OPEN_EXISTING;
1094  }
1095  llvm_unreachable("unreachable!");
1096}
1097
1098static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1099  DWORD Result = 0;
1100  if (Access & FA_Read)
1101    Result |= GENERIC_READ;
1102  if (Access & FA_Write)
1103    Result |= GENERIC_WRITE;
1104  if (Flags & OF_Delete)
1105    Result |= DELETE;
1106  if (Flags & OF_UpdateAtime)
1107    Result |= FILE_WRITE_ATTRIBUTES;
1108  return Result;
1109}
1110
1111static std::error_code openNativeFileInternal(const Twine &Name,
1112                                              file_t &ResultFile, DWORD Disp,
1113                                              DWORD Access, DWORD Flags,
1114                                              bool Inherit = false) {
1115  SmallVector<wchar_t, 128> PathUTF16;
1116  if (std::error_code EC = widenPath(Name, PathUTF16))
1117    return EC;
1118
1119  SECURITY_ATTRIBUTES SA;
1120  SA.nLength = sizeof(SA);
1121  SA.lpSecurityDescriptor = nullptr;
1122  SA.bInheritHandle = Inherit;
1123
1124  HANDLE H =
1125      ::CreateFileW(PathUTF16.begin(), Access,
1126                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1127                    Disp, Flags, NULL);
1128  if (H == INVALID_HANDLE_VALUE) {
1129    DWORD LastError = ::GetLastError();
1130    std::error_code EC = mapWindowsError(LastError);
1131    // Provide a better error message when trying to open directories.
1132    // This only runs if we failed to open the file, so there is probably
1133    // no performances issues.
1134    if (LastError != ERROR_ACCESS_DENIED)
1135      return EC;
1136    if (is_directory(Name))
1137      return make_error_code(errc::is_a_directory);
1138    return EC;
1139  }
1140  ResultFile = H;
1141  return std::error_code();
1142}
1143
1144Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1145                                FileAccess Access, OpenFlags Flags,
1146                                unsigned Mode) {
1147  // Verify that we don't have both "append" and "excl".
1148  assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1149         "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1150
1151  DWORD NativeDisp = nativeDisposition(Disp, Flags);
1152  DWORD NativeAccess = nativeAccess(Access, Flags);
1153
1154  bool Inherit = false;
1155  if (Flags & OF_ChildInherit)
1156    Inherit = true;
1157
1158  file_t Result;
1159  std::error_code EC = openNativeFileInternal(
1160      Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1161  if (EC)
1162    return errorCodeToError(EC);
1163
1164  if (Flags & OF_UpdateAtime) {
1165    FILETIME FileTime;
1166    SYSTEMTIME SystemTime;
1167    GetSystemTime(&SystemTime);
1168    if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1169        SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1170      DWORD LastError = ::GetLastError();
1171      ::CloseHandle(Result);
1172      return errorCodeToError(mapWindowsError(LastError));
1173    }
1174  }
1175
1176  if (Flags & OF_Delete) {
1177    if ((EC = setDeleteDisposition(Result, true))) {
1178      ::CloseHandle(Result);
1179      return errorCodeToError(EC);
1180    }
1181  }
1182  return Result;
1183}
1184
1185std::error_code openFile(const Twine &Name, int &ResultFD,
1186                         CreationDisposition Disp, FileAccess Access,
1187                         OpenFlags Flags, unsigned int Mode) {
1188  Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1189  if (!Result)
1190    return errorToErrorCode(Result.takeError());
1191
1192  return nativeFileToFd(*Result, ResultFD, Flags);
1193}
1194
1195static std::error_code directoryRealPath(const Twine &Name,
1196                                         SmallVectorImpl<char> &RealPath) {
1197  file_t File;
1198  std::error_code EC = openNativeFileInternal(
1199      Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1200  if (EC)
1201    return EC;
1202
1203  EC = realPathFromHandle(File, RealPath);
1204  ::CloseHandle(File);
1205  return EC;
1206}
1207
1208std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1209                                OpenFlags Flags,
1210                                SmallVectorImpl<char> *RealPath) {
1211  Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1212  return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1213}
1214
1215Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1216                                       SmallVectorImpl<char> *RealPath) {
1217  Expected<file_t> Result =
1218      openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1219
1220  // Fetch the real name of the file, if the user asked
1221  if (Result && RealPath)
1222    realPathFromHandle(*Result, *RealPath);
1223
1224  return Result;
1225}
1226
1227file_t convertFDToNativeFile(int FD) {
1228  return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1229}
1230
1231file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1232file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1233file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1234
1235Expected<size_t> readNativeFileImpl(file_t FileHandle,
1236                                    MutableArrayRef<char> Buf,
1237                                    OVERLAPPED *Overlap) {
1238  // ReadFile can only read 2GB at a time. The caller should check the number of
1239  // bytes and read in a loop until termination.
1240  DWORD BytesToRead =
1241      std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1242  DWORD BytesRead = 0;
1243  if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))
1244    return BytesRead;
1245  DWORD Err = ::GetLastError();
1246  // EOF is not an error.
1247  if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1248    return BytesRead;
1249  return errorCodeToError(mapWindowsError(Err));
1250}
1251
1252Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
1253  return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1254}
1255
1256Expected<size_t> readNativeFileSlice(file_t FileHandle,
1257                                     MutableArrayRef<char> Buf,
1258                                     uint64_t Offset) {
1259  OVERLAPPED Overlapped = {};
1260  Overlapped.Offset = uint32_t(Offset);
1261  Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1262  return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1263}
1264
1265std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
1266  DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;
1267  OVERLAPPED OV = {};
1268  file_t File = convertFDToNativeFile(FD);
1269  auto Start = std::chrono::steady_clock::now();
1270  auto End = Start + Timeout;
1271  do {
1272    if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1273      return std::error_code();
1274    DWORD Error = ::GetLastError();
1275    if (Error == ERROR_LOCK_VIOLATION) {
1276      ::Sleep(1);
1277      continue;
1278    }
1279    return mapWindowsError(Error);
1280  } while (std::chrono::steady_clock::now() < End);
1281  return mapWindowsError(ERROR_LOCK_VIOLATION);
1282}
1283
1284std::error_code lockFile(int FD) {
1285  DWORD Flags = LOCKFILE_EXCLUSIVE_LOCK;
1286  OVERLAPPED OV = {};
1287  file_t File = convertFDToNativeFile(FD);
1288  if (::LockFileEx(File, Flags, 0, MAXDWORD, MAXDWORD, &OV))
1289    return std::error_code();
1290  DWORD Error = ::GetLastError();
1291  return mapWindowsError(Error);
1292}
1293
1294std::error_code unlockFile(int FD) {
1295  OVERLAPPED OV = {};
1296  file_t File = convertFDToNativeFile(FD);
1297  if (::UnlockFileEx(File, 0, MAXDWORD, MAXDWORD, &OV))
1298    return std::error_code();
1299  return mapWindowsError(::GetLastError());
1300}
1301
1302std::error_code closeFile(file_t &F) {
1303  file_t TmpF = F;
1304  F = kInvalidFile;
1305  if (!::CloseHandle(TmpF))
1306    return mapWindowsError(::GetLastError());
1307  return std::error_code();
1308}
1309
1310std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1311  // Convert to utf-16.
1312  SmallVector<wchar_t, 128> Path16;
1313  std::error_code EC = widenPath(path, Path16);
1314  if (EC && !IgnoreErrors)
1315    return EC;
1316
1317  // SHFileOperation() accepts a list of paths, and so must be double null-
1318  // terminated to indicate the end of the list.  The buffer is already null
1319  // terminated, but since that null character is not considered part of the
1320  // vector's size, pushing another one will just consume that byte.  So we
1321  // need to push 2 null terminators.
1322  Path16.push_back(0);
1323  Path16.push_back(0);
1324
1325  SHFILEOPSTRUCTW shfos = {};
1326  shfos.wFunc = FO_DELETE;
1327  shfos.pFrom = Path16.data();
1328  shfos.fFlags = FOF_NO_UI;
1329
1330  int result = ::SHFileOperationW(&shfos);
1331  if (result != 0 && !IgnoreErrors)
1332    return mapWindowsError(result);
1333  return std::error_code();
1334}
1335
1336static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1337  // Path does not begin with a tilde expression.
1338  if (Path.empty() || Path[0] != '~')
1339    return;
1340
1341  StringRef PathStr(Path.begin(), Path.size());
1342  PathStr = PathStr.drop_front();
1343  StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1344
1345  if (!Expr.empty()) {
1346    // This is probably a ~username/ expression.  Don't support this on Windows.
1347    return;
1348  }
1349
1350  SmallString<128> HomeDir;
1351  if (!path::home_directory(HomeDir)) {
1352    // For some reason we couldn't get the home directory.  Just exit.
1353    return;
1354  }
1355
1356  // Overwrite the first character and insert the rest.
1357  Path[0] = HomeDir[0];
1358  Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1359}
1360
1361void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1362  dest.clear();
1363  if (path.isTriviallyEmpty())
1364    return;
1365
1366  path.toVector(dest);
1367  expandTildeExpr(dest);
1368
1369  return;
1370}
1371
1372std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1373                          bool expand_tilde) {
1374  dest.clear();
1375  if (path.isTriviallyEmpty())
1376    return std::error_code();
1377
1378  if (expand_tilde) {
1379    SmallString<128> Storage;
1380    path.toVector(Storage);
1381    expandTildeExpr(Storage);
1382    return real_path(Storage, dest, false);
1383  }
1384
1385  if (is_directory(path))
1386    return directoryRealPath(path, dest);
1387
1388  int fd;
1389  if (std::error_code EC =
1390          llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1391    return EC;
1392  ::close(fd);
1393  return std::error_code();
1394}
1395
1396} // end namespace fs
1397
1398namespace path {
1399static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1400                               SmallVectorImpl<char> &result) {
1401  wchar_t *path = nullptr;
1402  if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1403    return false;
1404
1405  bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1406  ::CoTaskMemFree(path);
1407  return ok;
1408}
1409
1410bool home_directory(SmallVectorImpl<char> &result) {
1411  return getKnownFolderPath(FOLDERID_Profile, result);
1412}
1413
1414bool user_config_directory(SmallVectorImpl<char> &result) {
1415  // Either local or roaming appdata may be suitable in some cases, depending
1416  // on the data. Local is more conservative, Roaming may not always be correct.
1417  return getKnownFolderPath(FOLDERID_LocalAppData, result);
1418}
1419
1420bool cache_directory(SmallVectorImpl<char> &result) {
1421  return getKnownFolderPath(FOLDERID_LocalAppData, result);
1422}
1423
1424static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1425  SmallVector<wchar_t, 1024> Buf;
1426  size_t Size = 1024;
1427  do {
1428    Buf.reserve(Size);
1429    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1430    if (Size == 0)
1431      return false;
1432
1433    // Try again with larger buffer.
1434  } while (Size > Buf.capacity());
1435  Buf.set_size(Size);
1436
1437  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1438}
1439
1440static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1441  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1442  for (auto *Env : EnvironmentVariables) {
1443    if (getTempDirEnvVar(Env, Res))
1444      return true;
1445  }
1446  return false;
1447}
1448
1449void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1450  (void)ErasedOnReboot;
1451  Result.clear();
1452
1453  // Check whether the temporary directory is specified by an environment var.
1454  // This matches GetTempPath logic to some degree. GetTempPath is not used
1455  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1456  // (fixed on Windows 8).
1457  if (getTempDirEnvVar(Result)) {
1458    assert(!Result.empty() && "Unexpected empty path");
1459    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1460    fs::make_absolute(Result); // Make it absolute if not already.
1461    return;
1462  }
1463
1464  // Fall back to a system default.
1465  const char *DefaultResult = "C:\\Temp";
1466  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1467}
1468} // end namespace path
1469
1470namespace windows {
1471std::error_code CodePageToUTF16(unsigned codepage,
1472                                llvm::StringRef original,
1473                                llvm::SmallVectorImpl<wchar_t> &utf16) {
1474  if (!original.empty()) {
1475    int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1476                                    original.size(), utf16.begin(), 0);
1477
1478    if (len == 0) {
1479      return mapWindowsError(::GetLastError());
1480    }
1481
1482    utf16.reserve(len + 1);
1483    utf16.set_size(len);
1484
1485    len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1486                                original.size(), utf16.begin(), utf16.size());
1487
1488    if (len == 0) {
1489      return mapWindowsError(::GetLastError());
1490    }
1491  }
1492
1493  // Make utf16 null terminated.
1494  utf16.push_back(0);
1495  utf16.pop_back();
1496
1497  return std::error_code();
1498}
1499
1500std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1501                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1502  return CodePageToUTF16(CP_UTF8, utf8, utf16);
1503}
1504
1505std::error_code CurCPToUTF16(llvm::StringRef curcp,
1506                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1507  return CodePageToUTF16(CP_ACP, curcp, utf16);
1508}
1509
1510static
1511std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1512                                size_t utf16_len,
1513                                llvm::SmallVectorImpl<char> &converted) {
1514  if (utf16_len) {
1515    // Get length.
1516    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
1517                                    0, NULL, NULL);
1518
1519    if (len == 0) {
1520      return mapWindowsError(::GetLastError());
1521    }
1522
1523    converted.reserve(len);
1524    converted.set_size(len);
1525
1526    // Now do the actual conversion.
1527    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1528                                converted.size(), NULL, NULL);
1529
1530    if (len == 0) {
1531      return mapWindowsError(::GetLastError());
1532    }
1533  }
1534
1535  // Make the new string null terminated.
1536  converted.push_back(0);
1537  converted.pop_back();
1538
1539  return std::error_code();
1540}
1541
1542std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1543                            llvm::SmallVectorImpl<char> &utf8) {
1544  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1545}
1546
1547std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1548                             llvm::SmallVectorImpl<char> &curcp) {
1549  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1550}
1551
1552} // end namespace windows
1553} // end namespace sys
1554} // end namespace llvm
1555