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