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