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