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