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  if (!FromHandle)
560    return mapWindowsError(GetLastError());
561
562  return rename_handle(FromHandle, To);
563}
564
565std::error_code resize_file(int FD, uint64_t Size) {
566#ifdef HAVE__CHSIZE_S
567  errno_t error = ::_chsize_s(FD, Size);
568#else
569  errno_t error = ::_chsize(FD, Size);
570#endif
571  return std::error_code(error, std::generic_category());
572}
573
574std::error_code access(const Twine &Path, AccessMode Mode) {
575  SmallVector<wchar_t, 128> PathUtf16;
576
577  if (std::error_code EC = widenPath(Path, PathUtf16))
578    return EC;
579
580  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
581
582  if (Attributes == INVALID_FILE_ATTRIBUTES) {
583    // See if the file didn't actually exist.
584    DWORD LastError = ::GetLastError();
585    if (LastError != ERROR_FILE_NOT_FOUND &&
586        LastError != ERROR_PATH_NOT_FOUND)
587      return mapWindowsError(LastError);
588    return errc::no_such_file_or_directory;
589  }
590
591  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
592    return errc::permission_denied;
593
594  return std::error_code();
595}
596
597bool can_execute(const Twine &Path) {
598  return !access(Path, AccessMode::Execute) ||
599         !access(Path + ".exe", AccessMode::Execute);
600}
601
602bool equivalent(file_status A, file_status B) {
603  assert(status_known(A) && status_known(B));
604  return A.FileIndexHigh         == B.FileIndexHigh &&
605         A.FileIndexLow          == B.FileIndexLow &&
606         A.FileSizeHigh          == B.FileSizeHigh &&
607         A.FileSizeLow           == B.FileSizeLow &&
608         A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
609         A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
610         A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
611         A.LastWriteTimeLow      == B.LastWriteTimeLow &&
612         A.VolumeSerialNumber    == B.VolumeSerialNumber;
613}
614
615std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
616  file_status fsA, fsB;
617  if (std::error_code ec = status(A, fsA))
618    return ec;
619  if (std::error_code ec = status(B, fsB))
620    return ec;
621  result = equivalent(fsA, fsB);
622  return std::error_code();
623}
624
625static bool isReservedName(StringRef path) {
626  // This list of reserved names comes from MSDN, at:
627  // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
628  static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
629                                                "com1", "com2", "com3", "com4",
630                                                "com5", "com6", "com7", "com8",
631                                                "com9", "lpt1", "lpt2", "lpt3",
632                                                "lpt4", "lpt5", "lpt6", "lpt7",
633                                                "lpt8", "lpt9" };
634
635  // First, check to see if this is a device namespace, which always
636  // starts with \\.\, since device namespaces are not legal file paths.
637  if (path.startswith("\\\\.\\"))
638    return true;
639
640  // Then compare against the list of ancient reserved names.
641  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
642    if (path.equals_lower(sReservedNames[i]))
643      return true;
644  }
645
646  // The path isn't what we consider reserved.
647  return false;
648}
649
650static file_type file_type_from_attrs(DWORD Attrs) {
651  return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
652                                            : file_type::regular_file;
653}
654
655static perms perms_from_attrs(DWORD Attrs) {
656  return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
657}
658
659static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
660  if (FileHandle == INVALID_HANDLE_VALUE)
661    goto handle_status_error;
662
663  switch (::GetFileType(FileHandle)) {
664  default:
665    llvm_unreachable("Don't know anything about this file type");
666  case FILE_TYPE_UNKNOWN: {
667    DWORD Err = ::GetLastError();
668    if (Err != NO_ERROR)
669      return mapWindowsError(Err);
670    Result = file_status(file_type::type_unknown);
671    return std::error_code();
672  }
673  case FILE_TYPE_DISK:
674    break;
675  case FILE_TYPE_CHAR:
676    Result = file_status(file_type::character_file);
677    return std::error_code();
678  case FILE_TYPE_PIPE:
679    Result = file_status(file_type::fifo_file);
680    return std::error_code();
681  }
682
683  BY_HANDLE_FILE_INFORMATION Info;
684  if (!::GetFileInformationByHandle(FileHandle, &Info))
685    goto handle_status_error;
686
687  Result = file_status(
688      file_type_from_attrs(Info.dwFileAttributes),
689      perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
690      Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
691      Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
692      Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
693      Info.nFileIndexHigh, Info.nFileIndexLow);
694  return std::error_code();
695
696handle_status_error:
697  DWORD LastError = ::GetLastError();
698  if (LastError == ERROR_FILE_NOT_FOUND ||
699      LastError == ERROR_PATH_NOT_FOUND)
700    Result = file_status(file_type::file_not_found);
701  else if (LastError == ERROR_SHARING_VIOLATION)
702    Result = file_status(file_type::type_unknown);
703  else
704    Result = file_status(file_type::status_error);
705  return mapWindowsError(LastError);
706}
707
708std::error_code status(const Twine &path, file_status &result, bool Follow) {
709  SmallString<128> path_storage;
710  SmallVector<wchar_t, 128> path_utf16;
711
712  StringRef path8 = path.toStringRef(path_storage);
713  if (isReservedName(path8)) {
714    result = file_status(file_type::character_file);
715    return std::error_code();
716  }
717
718  if (std::error_code ec = widenPath(path8, path_utf16))
719    return ec;
720
721  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
722  if (attr == INVALID_FILE_ATTRIBUTES)
723    return getStatus(INVALID_HANDLE_VALUE, result);
724
725  DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
726  // Handle reparse points.
727  if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
728    Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
729
730  ScopedFileHandle h(
731      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
732                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
733                    NULL, OPEN_EXISTING, Flags, 0));
734  if (!h)
735    return getStatus(INVALID_HANDLE_VALUE, result);
736
737  return getStatus(h, result);
738}
739
740std::error_code status(int FD, file_status &Result) {
741  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
742  return getStatus(FileHandle, Result);
743}
744
745std::error_code status(file_t FileHandle, file_status &Result) {
746  return getStatus(FileHandle, Result);
747}
748
749unsigned getUmask() {
750  return 0;
751}
752
753std::error_code setPermissions(const Twine &Path, perms Permissions) {
754  SmallVector<wchar_t, 128> PathUTF16;
755  if (std::error_code EC = widenPath(Path, PathUTF16))
756    return EC;
757
758  DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
759  if (Attributes == INVALID_FILE_ATTRIBUTES)
760    return mapWindowsError(GetLastError());
761
762  // There are many Windows file attributes that are not to do with the file
763  // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
764  // them.
765  if (Permissions & all_write) {
766    Attributes &= ~FILE_ATTRIBUTE_READONLY;
767    if (Attributes == 0)
768      // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
769      Attributes |= FILE_ATTRIBUTE_NORMAL;
770  }
771  else {
772    Attributes |= FILE_ATTRIBUTE_READONLY;
773    // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
774    // remove it, if it is present.
775    Attributes &= ~FILE_ATTRIBUTE_NORMAL;
776  }
777
778  if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
779    return mapWindowsError(GetLastError());
780
781  return std::error_code();
782}
783
784std::error_code setPermissions(int FD, perms Permissions) {
785  // FIXME Not implemented.
786  return std::make_error_code(std::errc::not_supported);
787}
788
789std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
790                                                 TimePoint<> ModificationTime) {
791  FILETIME AccessFT = toFILETIME(AccessTime);
792  FILETIME ModifyFT = toFILETIME(ModificationTime);
793  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
794  if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
795    return mapWindowsError(::GetLastError());
796  return std::error_code();
797}
798
799std::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
800                                         uint64_t Offset, mapmode Mode) {
801  this->Mode = Mode;
802  if (OrigFileHandle == INVALID_HANDLE_VALUE)
803    return make_error_code(errc::bad_file_descriptor);
804
805  DWORD flprotect;
806  switch (Mode) {
807  case readonly:  flprotect = PAGE_READONLY; break;
808  case readwrite: flprotect = PAGE_READWRITE; break;
809  case priv:      flprotect = PAGE_WRITECOPY; break;
810  }
811
812  HANDLE FileMappingHandle =
813      ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
814                           Hi_32(Size),
815                           Lo_32(Size),
816                           0);
817  if (FileMappingHandle == NULL) {
818    std::error_code ec = mapWindowsError(GetLastError());
819    return ec;
820  }
821
822  DWORD dwDesiredAccess;
823  switch (Mode) {
824  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
825  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
826  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
827  }
828  Mapping = ::MapViewOfFile(FileMappingHandle,
829                            dwDesiredAccess,
830                            Offset >> 32,
831                            Offset & 0xffffffff,
832                            Size);
833  if (Mapping == NULL) {
834    std::error_code ec = mapWindowsError(GetLastError());
835    ::CloseHandle(FileMappingHandle);
836    return ec;
837  }
838
839  if (Size == 0) {
840    MEMORY_BASIC_INFORMATION mbi;
841    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
842    if (Result == 0) {
843      std::error_code ec = mapWindowsError(GetLastError());
844      ::UnmapViewOfFile(Mapping);
845      ::CloseHandle(FileMappingHandle);
846      return ec;
847    }
848    Size = mbi.RegionSize;
849  }
850
851  // Close the file mapping handle, as it's kept alive by the file mapping. But
852  // neither the file mapping nor the file mapping handle keep the file handle
853  // alive, so we need to keep a reference to the file in case all other handles
854  // are closed and the file is deleted, which may cause invalid data to be read
855  // from the file.
856  ::CloseHandle(FileMappingHandle);
857  if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
858                         ::GetCurrentProcess(), &FileHandle, 0, 0,
859                         DUPLICATE_SAME_ACCESS)) {
860    std::error_code ec = mapWindowsError(GetLastError());
861    ::UnmapViewOfFile(Mapping);
862    return ec;
863  }
864
865  return std::error_code();
866}
867
868mapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
869                                       size_t length, uint64_t offset,
870                                       std::error_code &ec)
871    : Size(length), Mapping() {
872  ec = init(fd, offset, mode);
873  if (ec)
874    Mapping = 0;
875}
876
877static bool hasFlushBufferKernelBug() {
878  static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
879  return Ret;
880}
881
882static bool isEXE(StringRef Magic) {
883  static const char PEMagic[] = {'P', 'E', '\0', '\0'};
884  if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
885    uint32_t off = read32le(Magic.data() + 0x3c);
886    // PE/COFF file, either EXE or DLL.
887    if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
888      return true;
889  }
890  return false;
891}
892
893mapped_file_region::~mapped_file_region() {
894  if (Mapping) {
895
896    bool Exe = isEXE(StringRef((char *)Mapping, Size));
897
898    ::UnmapViewOfFile(Mapping);
899
900    if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
901      // There is a Windows kernel bug, the exact trigger conditions of which
902      // are not well understood.  When triggered, dirty pages are not properly
903      // flushed and subsequent process's attempts to read a file can return
904      // invalid data.  Calling FlushFileBuffers on the write handle is
905      // sufficient to ensure that this bug is not triggered.
906      // The bug only occurs when writing an executable and executing it right
907      // after, under high I/O pressure.
908      ::FlushFileBuffers(FileHandle);
909    }
910
911    ::CloseHandle(FileHandle);
912  }
913}
914
915size_t mapped_file_region::size() const {
916  assert(Mapping && "Mapping failed but used anyway!");
917  return Size;
918}
919
920char *mapped_file_region::data() const {
921  assert(Mapping && "Mapping failed but used anyway!");
922  return reinterpret_cast<char*>(Mapping);
923}
924
925const char *mapped_file_region::const_data() const {
926  assert(Mapping && "Mapping failed but used anyway!");
927  return reinterpret_cast<const char*>(Mapping);
928}
929
930int mapped_file_region::alignment() {
931  SYSTEM_INFO SysInfo;
932  ::GetSystemInfo(&SysInfo);
933  return SysInfo.dwAllocationGranularity;
934}
935
936static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
937  return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
938                           perms_from_attrs(FindData->dwFileAttributes),
939                           FindData->ftLastAccessTime.dwHighDateTime,
940                           FindData->ftLastAccessTime.dwLowDateTime,
941                           FindData->ftLastWriteTime.dwHighDateTime,
942                           FindData->ftLastWriteTime.dwLowDateTime,
943                           FindData->nFileSizeHigh, FindData->nFileSizeLow);
944}
945
946std::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
947                                                     StringRef Path,
948                                                     bool FollowSymlinks) {
949  SmallVector<wchar_t, 128> PathUTF16;
950
951  if (std::error_code EC = widenPath(Path, PathUTF16))
952    return EC;
953
954  // Convert path to the format that Windows is happy with.
955  if (PathUTF16.size() > 0 &&
956      !is_separator(PathUTF16[Path.size() - 1]) &&
957      PathUTF16[Path.size() - 1] != L':') {
958    PathUTF16.push_back(L'\\');
959    PathUTF16.push_back(L'*');
960  } else {
961    PathUTF16.push_back(L'*');
962  }
963
964  //  Get the first directory entry.
965  WIN32_FIND_DATAW FirstFind;
966  ScopedFindHandle FindHandle(::FindFirstFileExW(
967      c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
968      NULL, FIND_FIRST_EX_LARGE_FETCH));
969  if (!FindHandle)
970    return mapWindowsError(::GetLastError());
971
972  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
973  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
974         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
975                              FirstFind.cFileName[1] == L'.'))
976    if (!::FindNextFileW(FindHandle, &FirstFind)) {
977      DWORD LastError = ::GetLastError();
978      // Check for end.
979      if (LastError == ERROR_NO_MORE_FILES)
980        return detail::directory_iterator_destruct(IT);
981      return mapWindowsError(LastError);
982    } else
983      FilenameLen = ::wcslen(FirstFind.cFileName);
984
985  // Construct the current directory entry.
986  SmallString<128> DirectoryEntryNameUTF8;
987  if (std::error_code EC =
988          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
989                      DirectoryEntryNameUTF8))
990    return EC;
991
992  IT.IterationHandle = intptr_t(FindHandle.take());
993  SmallString<128> DirectoryEntryPath(Path);
994  path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
995  IT.CurrentEntry =
996      directory_entry(DirectoryEntryPath, FollowSymlinks,
997                      file_type_from_attrs(FirstFind.dwFileAttributes),
998                      status_from_find_data(&FirstFind));
999
1000  return std::error_code();
1001}
1002
1003std::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1004  if (IT.IterationHandle != 0)
1005    // Closes the handle if it's valid.
1006    ScopedFindHandle close(HANDLE(IT.IterationHandle));
1007  IT.IterationHandle = 0;
1008  IT.CurrentEntry = directory_entry();
1009  return std::error_code();
1010}
1011
1012std::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1013  WIN32_FIND_DATAW FindData;
1014  if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1015    DWORD LastError = ::GetLastError();
1016    // Check for end.
1017    if (LastError == ERROR_NO_MORE_FILES)
1018      return detail::directory_iterator_destruct(IT);
1019    return mapWindowsError(LastError);
1020  }
1021
1022  size_t FilenameLen = ::wcslen(FindData.cFileName);
1023  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1024      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1025                           FindData.cFileName[1] == L'.'))
1026    return directory_iterator_increment(IT);
1027
1028  SmallString<128> DirectoryEntryPathUTF8;
1029  if (std::error_code EC =
1030          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1031                      DirectoryEntryPathUTF8))
1032    return EC;
1033
1034  IT.CurrentEntry.replace_filename(
1035      Twine(DirectoryEntryPathUTF8),
1036      file_type_from_attrs(FindData.dwFileAttributes),
1037      status_from_find_data(&FindData));
1038  return std::error_code();
1039}
1040
1041ErrorOr<basic_file_status> directory_entry::status() const {
1042  return Status;
1043}
1044
1045static std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1046                                      OpenFlags Flags) {
1047  int CrtOpenFlags = 0;
1048  if (Flags & OF_Append)
1049    CrtOpenFlags |= _O_APPEND;
1050
1051  if (Flags & OF_Text)
1052    CrtOpenFlags |= _O_TEXT;
1053
1054  ResultFD = -1;
1055  if (!H)
1056    return errorToErrorCode(H.takeError());
1057
1058  ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1059  if (ResultFD == -1) {
1060    ::CloseHandle(*H);
1061    return mapWindowsError(ERROR_INVALID_HANDLE);
1062  }
1063  return std::error_code();
1064}
1065
1066static DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1067  // This is a compatibility hack.  Really we should respect the creation
1068  // disposition, but a lot of old code relied on the implicit assumption that
1069  // OF_Append implied it would open an existing file.  Since the disposition is
1070  // now explicit and defaults to CD_CreateAlways, this assumption would cause
1071  // any usage of OF_Append to append to a new file, even if the file already
1072  // existed.  A better solution might have two new creation dispositions:
1073  // CD_AppendAlways and CD_AppendNew.  This would also address the problem of
1074  // OF_Append being used on a read-only descriptor, which doesn't make sense.
1075  if (Flags & OF_Append)
1076    return OPEN_ALWAYS;
1077
1078  switch (Disp) {
1079  case CD_CreateAlways:
1080    return CREATE_ALWAYS;
1081  case CD_CreateNew:
1082    return CREATE_NEW;
1083  case CD_OpenAlways:
1084    return OPEN_ALWAYS;
1085  case CD_OpenExisting:
1086    return OPEN_EXISTING;
1087  }
1088  llvm_unreachable("unreachable!");
1089}
1090
1091static DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1092  DWORD Result = 0;
1093  if (Access & FA_Read)
1094    Result |= GENERIC_READ;
1095  if (Access & FA_Write)
1096    Result |= GENERIC_WRITE;
1097  if (Flags & OF_Delete)
1098    Result |= DELETE;
1099  if (Flags & OF_UpdateAtime)
1100    Result |= FILE_WRITE_ATTRIBUTES;
1101  return Result;
1102}
1103
1104static std::error_code openNativeFileInternal(const Twine &Name,
1105                                              file_t &ResultFile, DWORD Disp,
1106                                              DWORD Access, DWORD Flags,
1107                                              bool Inherit = false) {
1108  SmallVector<wchar_t, 128> PathUTF16;
1109  if (std::error_code EC = widenPath(Name, PathUTF16))
1110    return EC;
1111
1112  SECURITY_ATTRIBUTES SA;
1113  SA.nLength = sizeof(SA);
1114  SA.lpSecurityDescriptor = nullptr;
1115  SA.bInheritHandle = Inherit;
1116
1117  HANDLE H =
1118      ::CreateFileW(PathUTF16.begin(), Access,
1119                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1120                    Disp, Flags, NULL);
1121  if (H == INVALID_HANDLE_VALUE) {
1122    DWORD LastError = ::GetLastError();
1123    std::error_code EC = mapWindowsError(LastError);
1124    // Provide a better error message when trying to open directories.
1125    // This only runs if we failed to open the file, so there is probably
1126    // no performances issues.
1127    if (LastError != ERROR_ACCESS_DENIED)
1128      return EC;
1129    if (is_directory(Name))
1130      return make_error_code(errc::is_a_directory);
1131    return EC;
1132  }
1133  ResultFile = H;
1134  return std::error_code();
1135}
1136
1137Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1138                                FileAccess Access, OpenFlags Flags,
1139                                unsigned Mode) {
1140  // Verify that we don't have both "append" and "excl".
1141  assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1142         "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1143
1144  DWORD NativeDisp = nativeDisposition(Disp, Flags);
1145  DWORD NativeAccess = nativeAccess(Access, Flags);
1146
1147  bool Inherit = false;
1148  if (Flags & OF_ChildInherit)
1149    Inherit = true;
1150
1151  file_t Result;
1152  std::error_code EC = openNativeFileInternal(
1153      Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1154  if (EC)
1155    return errorCodeToError(EC);
1156
1157  if (Flags & OF_UpdateAtime) {
1158    FILETIME FileTime;
1159    SYSTEMTIME SystemTime;
1160    GetSystemTime(&SystemTime);
1161    if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1162        SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1163      DWORD LastError = ::GetLastError();
1164      ::CloseHandle(Result);
1165      return errorCodeToError(mapWindowsError(LastError));
1166    }
1167  }
1168
1169  if (Flags & OF_Delete) {
1170    if ((EC = setDeleteDisposition(Result, true))) {
1171      ::CloseHandle(Result);
1172      return errorCodeToError(EC);
1173    }
1174  }
1175  return Result;
1176}
1177
1178std::error_code openFile(const Twine &Name, int &ResultFD,
1179                         CreationDisposition Disp, FileAccess Access,
1180                         OpenFlags Flags, unsigned int Mode) {
1181  Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1182  if (!Result)
1183    return errorToErrorCode(Result.takeError());
1184
1185  return nativeFileToFd(*Result, ResultFD, Flags);
1186}
1187
1188static std::error_code directoryRealPath(const Twine &Name,
1189                                         SmallVectorImpl<char> &RealPath) {
1190  file_t File;
1191  std::error_code EC = openNativeFileInternal(
1192      Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1193  if (EC)
1194    return EC;
1195
1196  EC = realPathFromHandle(File, RealPath);
1197  ::CloseHandle(File);
1198  return EC;
1199}
1200
1201std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1202                                OpenFlags Flags,
1203                                SmallVectorImpl<char> *RealPath) {
1204  Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1205  return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1206}
1207
1208Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1209                                       SmallVectorImpl<char> *RealPath) {
1210  Expected<file_t> Result =
1211      openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1212
1213  // Fetch the real name of the file, if the user asked
1214  if (Result && RealPath)
1215    realPathFromHandle(*Result, *RealPath);
1216
1217  return Result;
1218}
1219
1220file_t convertFDToNativeFile(int FD) {
1221  return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1222}
1223
1224file_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1225file_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1226file_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1227
1228Expected<size_t> readNativeFileImpl(file_t FileHandle,
1229                                    MutableArrayRef<char> Buf,
1230                                    OVERLAPPED *Overlap) {
1231  // ReadFile can only read 2GB at a time. The caller should check the number of
1232  // bytes and read in a loop until termination.
1233  DWORD BytesToRead =
1234      std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1235  DWORD BytesRead = 0;
1236  if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))
1237    return BytesRead;
1238  DWORD Err = ::GetLastError();
1239  // EOF is not an error.
1240  if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1241    return BytesRead;
1242  return errorCodeToError(mapWindowsError(Err));
1243}
1244
1245Expected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
1246  return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1247}
1248
1249Expected<size_t> readNativeFileSlice(file_t FileHandle,
1250                                     MutableArrayRef<char> Buf,
1251                                     uint64_t Offset) {
1252  OVERLAPPED Overlapped = {};
1253  Overlapped.Offset = uint32_t(Offset);
1254  Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1255  return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1256}
1257
1258std::error_code closeFile(file_t &F) {
1259  file_t TmpF = F;
1260  F = kInvalidFile;
1261  if (!::CloseHandle(TmpF))
1262    return mapWindowsError(::GetLastError());
1263  return std::error_code();
1264}
1265
1266std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1267  // Convert to utf-16.
1268  SmallVector<wchar_t, 128> Path16;
1269  std::error_code EC = widenPath(path, Path16);
1270  if (EC && !IgnoreErrors)
1271    return EC;
1272
1273  // SHFileOperation() accepts a list of paths, and so must be double null-
1274  // terminated to indicate the end of the list.  The buffer is already null
1275  // terminated, but since that null character is not considered part of the
1276  // vector's size, pushing another one will just consume that byte.  So we
1277  // need to push 2 null terminators.
1278  Path16.push_back(0);
1279  Path16.push_back(0);
1280
1281  SHFILEOPSTRUCTW shfos = {};
1282  shfos.wFunc = FO_DELETE;
1283  shfos.pFrom = Path16.data();
1284  shfos.fFlags = FOF_NO_UI;
1285
1286  int result = ::SHFileOperationW(&shfos);
1287  if (result != 0 && !IgnoreErrors)
1288    return mapWindowsError(result);
1289  return std::error_code();
1290}
1291
1292static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1293  // Path does not begin with a tilde expression.
1294  if (Path.empty() || Path[0] != '~')
1295    return;
1296
1297  StringRef PathStr(Path.begin(), Path.size());
1298  PathStr = PathStr.drop_front();
1299  StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1300
1301  if (!Expr.empty()) {
1302    // This is probably a ~username/ expression.  Don't support this on Windows.
1303    return;
1304  }
1305
1306  SmallString<128> HomeDir;
1307  if (!path::home_directory(HomeDir)) {
1308    // For some reason we couldn't get the home directory.  Just exit.
1309    return;
1310  }
1311
1312  // Overwrite the first character and insert the rest.
1313  Path[0] = HomeDir[0];
1314  Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1315}
1316
1317void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1318  dest.clear();
1319  if (path.isTriviallyEmpty())
1320    return;
1321
1322  path.toVector(dest);
1323  expandTildeExpr(dest);
1324
1325  return;
1326}
1327
1328std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1329                          bool expand_tilde) {
1330  dest.clear();
1331  if (path.isTriviallyEmpty())
1332    return std::error_code();
1333
1334  if (expand_tilde) {
1335    SmallString<128> Storage;
1336    path.toVector(Storage);
1337    expandTildeExpr(Storage);
1338    return real_path(Storage, dest, false);
1339  }
1340
1341  if (is_directory(path))
1342    return directoryRealPath(path, dest);
1343
1344  int fd;
1345  if (std::error_code EC =
1346          llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1347    return EC;
1348  ::close(fd);
1349  return std::error_code();
1350}
1351
1352} // end namespace fs
1353
1354namespace path {
1355static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1356                               SmallVectorImpl<char> &result) {
1357  wchar_t *path = nullptr;
1358  if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1359    return false;
1360
1361  bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1362  ::CoTaskMemFree(path);
1363  return ok;
1364}
1365
1366bool home_directory(SmallVectorImpl<char> &result) {
1367  return getKnownFolderPath(FOLDERID_Profile, result);
1368}
1369
1370bool cache_directory(SmallVectorImpl<char> &result) {
1371  return getKnownFolderPath(FOLDERID_LocalAppData, result);
1372}
1373
1374static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1375  SmallVector<wchar_t, 1024> Buf;
1376  size_t Size = 1024;
1377  do {
1378    Buf.reserve(Size);
1379    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1380    if (Size == 0)
1381      return false;
1382
1383    // Try again with larger buffer.
1384  } while (Size > Buf.capacity());
1385  Buf.set_size(Size);
1386
1387  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1388}
1389
1390static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1391  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1392  for (auto *Env : EnvironmentVariables) {
1393    if (getTempDirEnvVar(Env, Res))
1394      return true;
1395  }
1396  return false;
1397}
1398
1399void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1400  (void)ErasedOnReboot;
1401  Result.clear();
1402
1403  // Check whether the temporary directory is specified by an environment var.
1404  // This matches GetTempPath logic to some degree. GetTempPath is not used
1405  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1406  // (fixed on Windows 8).
1407  if (getTempDirEnvVar(Result)) {
1408    assert(!Result.empty() && "Unexpected empty path");
1409    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1410    fs::make_absolute(Result); // Make it absolute if not already.
1411    return;
1412  }
1413
1414  // Fall back to a system default.
1415  const char *DefaultResult = "C:\\Temp";
1416  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1417}
1418} // end namespace path
1419
1420namespace windows {
1421std::error_code CodePageToUTF16(unsigned codepage,
1422                                llvm::StringRef original,
1423                                llvm::SmallVectorImpl<wchar_t> &utf16) {
1424  if (!original.empty()) {
1425    int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1426                                    original.size(), utf16.begin(), 0);
1427
1428    if (len == 0) {
1429      return mapWindowsError(::GetLastError());
1430    }
1431
1432    utf16.reserve(len + 1);
1433    utf16.set_size(len);
1434
1435    len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1436                                original.size(), utf16.begin(), utf16.size());
1437
1438    if (len == 0) {
1439      return mapWindowsError(::GetLastError());
1440    }
1441  }
1442
1443  // Make utf16 null terminated.
1444  utf16.push_back(0);
1445  utf16.pop_back();
1446
1447  return std::error_code();
1448}
1449
1450std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1451                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1452  return CodePageToUTF16(CP_UTF8, utf8, utf16);
1453}
1454
1455std::error_code CurCPToUTF16(llvm::StringRef curcp,
1456                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1457  return CodePageToUTF16(CP_ACP, curcp, utf16);
1458}
1459
1460static
1461std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1462                                size_t utf16_len,
1463                                llvm::SmallVectorImpl<char> &converted) {
1464  if (utf16_len) {
1465    // Get length.
1466    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
1467                                    0, NULL, NULL);
1468
1469    if (len == 0) {
1470      return mapWindowsError(::GetLastError());
1471    }
1472
1473    converted.reserve(len);
1474    converted.set_size(len);
1475
1476    // Now do the actual conversion.
1477    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1478                                converted.size(), NULL, NULL);
1479
1480    if (len == 0) {
1481      return mapWindowsError(::GetLastError());
1482    }
1483  }
1484
1485  // Make the new string null terminated.
1486  converted.push_back(0);
1487  converted.pop_back();
1488
1489  return std::error_code();
1490}
1491
1492std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1493                            llvm::SmallVectorImpl<char> &utf8) {
1494  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1495}
1496
1497std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1498                             llvm::SmallVectorImpl<char> &curcp) {
1499  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1500}
1501
1502} // end namespace windows
1503} // end namespace sys
1504} // end namespace llvm
1505