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