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