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