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