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