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::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  // llvm::sys::path::remove_dots, used above, can leave a '/' after the root
111  // name and long paths must use '\' as the separator.
112  const size_t RootNameSize = RootName.size();
113  if (RootNameSize < Path8Str.size() && Path8Str[RootNameSize] == '/')
114    Path8Str[RootNameSize] = '\\';
115
116  SmallString<2 * MAX_PATH> FullPath(LongPathPrefix);
117  if (RootName[1] != ':') { // Check if UNC.
118    FullPath.append("UNC\\");
119    FullPath.append(Path8Str.begin() + 2, Path8Str.end());
120  } else
121    FullPath.append(Path8Str);
122
123  return UTF8ToUTF16(FullPath, Path16);
124}
125
126} // end namespace windows
127
128namespace fs {
129
130const file_t kInvalidFile = INVALID_HANDLE_VALUE;
131
132std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
133  SmallVector<wchar_t, MAX_PATH> PathName;
134  DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
135
136  // A zero return value indicates a failure other than insufficient space.
137  if (Size == 0)
138    return "";
139
140  // Insufficient space is determined by a return value equal to the size of
141  // the buffer passed in.
142  if (Size == PathName.capacity())
143    return "";
144
145  // On success, GetModuleFileNameW returns the number of characters written to
146  // the buffer not including the NULL terminator.
147  PathName.set_size(Size);
148
149  // Convert the result from UTF-16 to UTF-8.
150  SmallVector<char, MAX_PATH> PathNameUTF8;
151  if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
152    return "";
153
154  return std::string(PathNameUTF8.data());
155}
156
157UniqueID file_status::getUniqueID() const {
158  // The file is uniquely identified by the volume serial number along
159  // with the 64-bit file identifier.
160  uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
161                    static_cast<uint64_t>(FileIndexLow);
162
163  return UniqueID(VolumeSerialNumber, FileID);
164}
165
166ErrorOr<space_info> disk_space(const Twine &Path) {
167  ULARGE_INTEGER Avail, Total, Free;
168  if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
169    return mapWindowsError(::GetLastError());
170  space_info SpaceInfo;
171  SpaceInfo.capacity =
172      (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
173  SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
174  SpaceInfo.available =
175      (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
176  return SpaceInfo;
177}
178
179TimePoint<> basic_file_status::getLastAccessedTime() const {
180  FILETIME Time;
181  Time.dwLowDateTime = LastAccessedTimeLow;
182  Time.dwHighDateTime = LastAccessedTimeHigh;
183  return toTimePoint(Time);
184}
185
186TimePoint<> basic_file_status::getLastModificationTime() const {
187  FILETIME Time;
188  Time.dwLowDateTime = LastWriteTimeLow;
189  Time.dwHighDateTime = LastWriteTimeHigh;
190  return toTimePoint(Time);
191}
192
193uint32_t file_status::getLinkCount() const {
194  return NumLinks;
195}
196
197std::error_code current_path(SmallVectorImpl<char> &result) {
198  SmallVector<wchar_t, MAX_PATH> cur_path;
199  DWORD len = MAX_PATH;
200
201  do {
202    cur_path.reserve(len);
203    len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
204
205    // A zero return value indicates a failure other than insufficient space.
206    if (len == 0)
207      return mapWindowsError(::GetLastError());
208
209    // If there's insufficient space, the len returned is larger than the len
210    // given.
211  } while (len > cur_path.capacity());
212
213  // On success, GetCurrentDirectoryW returns the number of characters not
214  // including the null-terminator.
215  cur_path.set_size(len);
216  return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
217}
218
219std::error_code set_current_path(const Twine &path) {
220  // Convert to utf-16.
221  SmallVector<wchar_t, 128> wide_path;
222  if (std::error_code ec = widenPath(path, wide_path))
223    return ec;
224
225  if (!::SetCurrentDirectoryW(wide_path.begin()))
226    return mapWindowsError(::GetLastError());
227
228  return std::error_code();
229}
230
231std::error_code create_directory(const Twine &path, bool IgnoreExisting,
232                                 perms Perms) {
233  SmallVector<wchar_t, 128> path_utf16;
234
235  // CreateDirectoryW has a lower maximum path length as it must leave room for
236  // an 8.3 filename.
237  if (std::error_code ec = widenPath(path, path_utf16, MAX_PATH - 12))
238    return ec;
239
240  if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
241    DWORD LastError = ::GetLastError();
242    if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
243      return mapWindowsError(LastError);
244  }
245
246  return std::error_code();
247}
248
249// We can't use symbolic links for windows.
250std::error_code create_link(const Twine &to, const Twine &from) {
251  // Convert to utf-16.
252  SmallVector<wchar_t, 128> wide_from;
253  SmallVector<wchar_t, 128> wide_to;
254  if (std::error_code ec = widenPath(from, wide_from))
255    return ec;
256  if (std::error_code ec = widenPath(to, wide_to))
257    return ec;
258
259  if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
260    return mapWindowsError(::GetLastError());
261
262  return std::error_code();
263}
264
265std::error_code create_hard_link(const Twine &to, const Twine &from) {
266  return create_link(to, from);
267}
268
269std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
270  SmallVector<wchar_t, 128> path_utf16;
271
272  if (std::error_code ec = widenPath(path, path_utf16))
273    return ec;
274
275  // We don't know whether this is a file or a directory, and remove() can
276  // accept both. The usual way to delete a file or directory is to use one of
277  // the DeleteFile or RemoveDirectory functions, but that requires you to know
278  // which one it is. We could stat() the file to determine that, but that would
279  // cost us additional system calls, which can be slow in a directory
280  // containing a large number of files. So instead we call CreateFile directly.
281  // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
282  // file to be deleted once it is closed. We also use the flags
283  // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
284  // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
285  ScopedFileHandle h(::CreateFileW(
286      c_str(path_utf16), DELETE,
287      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
288      OPEN_EXISTING,
289      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
290          FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
291      NULL));
292  if (!h) {
293    std::error_code EC = mapWindowsError(::GetLastError());
294    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
295      return EC;
296  }
297
298  return std::error_code();
299}
300
301static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
302                                         bool &Result) {
303  SmallVector<wchar_t, 128> VolumePath;
304  size_t Len = 128;
305  while (true) {
306    VolumePath.resize(Len);
307    BOOL Success =
308        ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
309
310    if (Success)
311      break;
312
313    DWORD Err = ::GetLastError();
314    if (Err != ERROR_INSUFFICIENT_BUFFER)
315      return mapWindowsError(Err);
316
317    Len *= 2;
318  }
319  // If the output buffer has exactly enough space for the path name, but not
320  // the null terminator, it will leave the output unterminated.  Push a null
321  // terminator onto the end to ensure that this never happens.
322  VolumePath.push_back(L'\0');
323  VolumePath.set_size(wcslen(VolumePath.data()));
324  const wchar_t *P = VolumePath.data();
325
326  UINT Type = ::GetDriveTypeW(P);
327  switch (Type) {
328  case DRIVE_FIXED:
329    Result = true;
330    return std::error_code();
331  case DRIVE_REMOTE:
332  case DRIVE_CDROM:
333  case DRIVE_RAMDISK:
334  case DRIVE_REMOVABLE:
335    Result = false;
336    return std::error_code();
337  default:
338    return make_error_code(errc::no_such_file_or_directory);
339  }
340  llvm_unreachable("Unreachable!");
341}
342
343std::error_code is_local(const Twine &path, bool &result) {
344  if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
345    return make_error_code(errc::no_such_file_or_directory);
346
347  SmallString<128> Storage;
348  StringRef P = path.toStringRef(Storage);
349
350  // Convert to utf-16.
351  SmallVector<wchar_t, 128> WidePath;
352  if (std::error_code ec = widenPath(P, WidePath))
353    return ec;
354  return is_local_internal(WidePath, result);
355}
356
357static std::error_code realPathFromHandle(HANDLE H,
358                                          SmallVectorImpl<wchar_t> &Buffer) {
359  DWORD CountChars = ::GetFinalPathNameByHandleW(
360      H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
361  if (CountChars > Buffer.capacity()) {
362    // The buffer wasn't big enough, try again.  In this case the return value
363    // *does* indicate the size of the null terminator.
364    Buffer.reserve(CountChars);
365    CountChars = ::GetFinalPathNameByHandleW(
366        H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
367  }
368  if (CountChars == 0)
369    return mapWindowsError(GetLastError());
370  Buffer.set_size(CountChars);
371  return std::error_code();
372}
373
374static std::error_code realPathFromHandle(HANDLE H,
375                                          SmallVectorImpl<char> &RealPath) {
376  RealPath.clear();
377  SmallVector<wchar_t, MAX_PATH> Buffer;
378  if (std::error_code EC = realPathFromHandle(H, Buffer))
379    return EC;
380
381  // Strip the \\?\ prefix. We don't want it ending up in output, and such
382  // paths don't get canonicalized by file APIs.
383  wchar_t *Data = Buffer.data();
384  DWORD CountChars = Buffer.size();
385  if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
386    // Convert \\?\UNC\foo\bar to \\foo\bar
387    CountChars -= 6;
388    Data += 6;
389    Data[0] = '\\';
390  } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
391    // Convert \\?\c:\foo to c:\foo
392    CountChars -= 4;
393    Data += 4;
394  }
395
396  // Convert the result from UTF-16 to UTF-8.
397  return UTF16ToUTF8(Data, CountChars, RealPath);
398}
399
400std::error_code is_local(int FD, bool &Result) {
401  SmallVector<wchar_t, 128> FinalPath;
402  HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
403
404  if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
405    return EC;
406
407  return is_local_internal(FinalPath, Result);
408}
409
410static std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
411  FILE_DISPOSITION_INFO Disposition;
412  Disposition.DeleteFile = Delete;
413  if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
414                                  sizeof(Disposition)))
415    return mapWindowsError(::GetLastError());
416  return std::error_code();
417}
418
419static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
420                                       bool ReplaceIfExists) {
421  SmallVector<wchar_t, 0> ToWide;
422  if (auto EC = widenPath(To, ToWide))
423    return EC;
424
425  std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
426                                  (ToWide.size() * sizeof(wchar_t)));
427  FILE_RENAME_INFO &RenameInfo =
428      *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
429  RenameInfo.ReplaceIfExists = ReplaceIfExists;
430  RenameInfo.RootDirectory = 0;
431  RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
432  std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
433
434  SetLastError(ERROR_SUCCESS);
435  if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
436                                  RenameInfoBuf.size())) {
437    unsigned Error = GetLastError();
438    if (Error == ERROR_SUCCESS)
439      Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
440    return mapWindowsError(Error);
441  }
442
443  return std::error_code();
444}
445
446static std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
447  SmallVector<wchar_t, 128> WideTo;
448  if (std::error_code EC = widenPath(To, WideTo))
449    return EC;
450
451  // We normally expect this loop to succeed after a few iterations. If it
452  // requires more than 200 tries, it's more likely that the failures are due to
453  // a true error, so stop trying.
454  for (unsigned Retry = 0; Retry != 200; ++Retry) {
455    auto EC = rename_internal(FromHandle, To, true);
456
457    if (EC ==
458        std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
459      // Wine doesn't support SetFileInformationByHandle in rename_internal.
460      // Fall back to MoveFileEx.
461      SmallVector<wchar_t, MAX_PATH> WideFrom;
462      if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
463        return EC2;
464      if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
465                        MOVEFILE_REPLACE_EXISTING))
466        return std::error_code();
467      return mapWindowsError(GetLastError());
468    }
469
470    if (!EC || EC != errc::permission_denied)
471      return EC;
472
473    // The destination file probably exists and is currently open in another
474    // process, either because the file was opened without FILE_SHARE_DELETE or
475    // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
476    // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
477    // to arrange for the destination file to be deleted when the other process
478    // closes it.
479    ScopedFileHandle ToHandle(
480        ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
481                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
482                      NULL, OPEN_EXISTING,
483                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
484    if (!ToHandle) {
485      auto EC = mapWindowsError(GetLastError());
486      // Another process might have raced with us and moved the existing file
487      // out of the way before we had a chance to open it. If that happens, try
488      // to rename the source file again.
489      if (EC == errc::no_such_file_or_directory)
490        continue;
491      return EC;
492    }
493
494    BY_HANDLE_FILE_INFORMATION FI;
495    if (!GetFileInformationByHandle(ToHandle, &FI))
496      return mapWindowsError(GetLastError());
497
498    // Try to find a unique new name for the destination file.
499    for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
500      std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
501      if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
502        if (EC == errc::file_exists || EC == errc::permission_denied) {
503          // Again, another process might have raced with us and moved the file
504          // before we could move it. Check whether this is the case, as it
505          // might have caused the permission denied error. If that was the
506          // case, we don't need to move it ourselves.
507          ScopedFileHandle ToHandle2(::CreateFileW(
508              WideTo.begin(), 0,
509              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
510              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
511          if (!ToHandle2) {
512            auto EC = mapWindowsError(GetLastError());
513            if (EC == errc::no_such_file_or_directory)
514              break;
515            return EC;
516          }
517          BY_HANDLE_FILE_INFORMATION FI2;
518          if (!GetFileInformationByHandle(ToHandle2, &FI2))
519            return mapWindowsError(GetLastError());
520          if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
521              FI.nFileIndexLow != FI2.nFileIndexLow ||
522              FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
523            break;
524          continue;
525        }
526        return EC;
527      }
528      break;
529    }
530
531    // Okay, the old destination file has probably been moved out of the way at
532    // this point, so try to rename the source file again. Still, another
533    // process might have raced with us to create and open the destination
534    // file, so we need to keep doing this until we succeed.
535  }
536
537  // The most likely root cause.
538  return errc::permission_denied;
539}
540
541static std::error_code rename_fd(int FromFD, const Twine &To) {
542  HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
543  return rename_handle(FromHandle, To);
544}
545
546std::error_code rename(const Twine &From, const Twine &To) {
547  // Convert to utf-16.
548  SmallVector<wchar_t, 128> WideFrom;
549  if (std::error_code EC = widenPath(From, WideFrom))
550    return EC;
551
552  ScopedFileHandle FromHandle;
553  // Retry this a few times to defeat badly behaved file system scanners.
554  for (unsigned Retry = 0; Retry != 200; ++Retry) {
555    if (Retry != 0)
556      ::Sleep(10);
557    FromHandle =
558        ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
559                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
560                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
561    if (FromHandle)
562      break;
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  if (PathUTF16.size() > 0 &&
961      !is_separator(PathUTF16[Path.size() - 1]) &&
962      PathUTF16[Path.size() - 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
1375static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1376  SmallVector<wchar_t, 1024> Buf;
1377  size_t Size = 1024;
1378  do {
1379    Buf.reserve(Size);
1380    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1381    if (Size == 0)
1382      return false;
1383
1384    // Try again with larger buffer.
1385  } while (Size > Buf.capacity());
1386  Buf.set_size(Size);
1387
1388  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1389}
1390
1391static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1392  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1393  for (auto *Env : EnvironmentVariables) {
1394    if (getTempDirEnvVar(Env, Res))
1395      return true;
1396  }
1397  return false;
1398}
1399
1400void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1401  (void)ErasedOnReboot;
1402  Result.clear();
1403
1404  // Check whether the temporary directory is specified by an environment var.
1405  // This matches GetTempPath logic to some degree. GetTempPath is not used
1406  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1407  // (fixed on Windows 8).
1408  if (getTempDirEnvVar(Result)) {
1409    assert(!Result.empty() && "Unexpected empty path");
1410    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1411    fs::make_absolute(Result); // Make it absolute if not already.
1412    return;
1413  }
1414
1415  // Fall back to a system default.
1416  const char *DefaultResult = "C:\\Temp";
1417  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1418}
1419} // end namespace path
1420
1421namespace windows {
1422std::error_code CodePageToUTF16(unsigned codepage,
1423                                llvm::StringRef original,
1424                                llvm::SmallVectorImpl<wchar_t> &utf16) {
1425  if (!original.empty()) {
1426    int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1427                                    original.size(), utf16.begin(), 0);
1428
1429    if (len == 0) {
1430      return mapWindowsError(::GetLastError());
1431    }
1432
1433    utf16.reserve(len + 1);
1434    utf16.set_size(len);
1435
1436    len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1437                                original.size(), utf16.begin(), utf16.size());
1438
1439    if (len == 0) {
1440      return mapWindowsError(::GetLastError());
1441    }
1442  }
1443
1444  // Make utf16 null terminated.
1445  utf16.push_back(0);
1446  utf16.pop_back();
1447
1448  return std::error_code();
1449}
1450
1451std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1452                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1453  return CodePageToUTF16(CP_UTF8, utf8, utf16);
1454}
1455
1456std::error_code CurCPToUTF16(llvm::StringRef curcp,
1457                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1458  return CodePageToUTF16(CP_ACP, curcp, utf16);
1459}
1460
1461static
1462std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1463                                size_t utf16_len,
1464                                llvm::SmallVectorImpl<char> &converted) {
1465  if (utf16_len) {
1466    // Get length.
1467    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
1468                                    0, NULL, NULL);
1469
1470    if (len == 0) {
1471      return mapWindowsError(::GetLastError());
1472    }
1473
1474    converted.reserve(len);
1475    converted.set_size(len);
1476
1477    // Now do the actual conversion.
1478    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1479                                converted.size(), NULL, NULL);
1480
1481    if (len == 0) {
1482      return mapWindowsError(::GetLastError());
1483    }
1484  }
1485
1486  // Make the new string null terminated.
1487  converted.push_back(0);
1488  converted.pop_back();
1489
1490  return std::error_code();
1491}
1492
1493std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1494                            llvm::SmallVectorImpl<char> &utf8) {
1495  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1496}
1497
1498std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1499                             llvm::SmallVectorImpl<char> &curcp) {
1500  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1501}
1502
1503} // end namespace windows
1504} // end namespace sys
1505} // end namespace llvm
1506