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