1//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Windows specific implementation of the Path API.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic Windows code that
16//===          is guaranteed to work on *all* Windows variants.
17//===----------------------------------------------------------------------===//
18
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Support/WindowsError.h"
21#include <fcntl.h>
22#include <io.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25
26// These two headers must be included last, and make sure shlobj is required
27// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
28#include "WindowsSupport.h"
29#include <shellapi.h>
30#include <shlobj.h>
31
32#undef max
33
34// MinGW doesn't define this.
35#ifndef _ERRNO_T_DEFINED
36#define _ERRNO_T_DEFINED
37typedef int errno_t;
38#endif
39
40#ifdef _MSC_VER
41# pragma comment(lib, "advapi32.lib")  // This provides CryptAcquireContextW.
42# pragma comment(lib, "ole32.lib")     // This provides CoTaskMemFree
43#endif
44
45using namespace llvm;
46
47using llvm::sys::windows::UTF8ToUTF16;
48using llvm::sys::windows::UTF16ToUTF8;
49using llvm::sys::path::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 path {
64
65// Convert a UTF-8 path to UTF-16.  Also, if the absolute equivalent of the
66// path is longer than CreateDirectory can tolerate, make it absolute and
67// prefixed by '\\?\'.
68std::error_code widenPath(const Twine &Path8,
69                          SmallVectorImpl<wchar_t> &Path16) {
70  const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
71
72  // Several operations would convert Path8 to SmallString; more efficient to
73  // do it once up front.
74  SmallString<128> Path8Str;
75  Path8.toVector(Path8Str);
76
77  // If we made this path absolute, how much longer would it get?
78  size_t CurPathLen;
79  if (llvm::sys::path::is_absolute(Twine(Path8Str)))
80    CurPathLen = 0; // No contribution from current_path needed.
81  else {
82    CurPathLen = ::GetCurrentDirectoryW(0, NULL);
83    if (CurPathLen == 0)
84      return mapWindowsError(::GetLastError());
85  }
86
87  // Would the absolute path be longer than our limit?
88  if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
89      !Path8Str.startswith("\\\\?\\")) {
90    SmallString<2*MAX_PATH> FullPath("\\\\?\\");
91    if (CurPathLen) {
92      SmallString<80> CurPath;
93      if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
94        return EC;
95      FullPath.append(CurPath);
96    }
97    // Traverse the requested path, canonicalizing . and .. (because the \\?\
98    // prefix is documented to treat them as real components).  Ignore
99    // separators, which can be returned from the iterator if the path has a
100    // drive name.  We don't need to call native() on the result since append()
101    // always attaches preferred_separator.
102    for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
103                                         E = llvm::sys::path::end(Path8Str);
104                                         I != E; ++I) {
105      if (I->size() == 1 && is_separator((*I)[0]))
106        continue;
107      if (I->size() == 1 && *I == ".")
108        continue;
109      if (I->size() == 2 && *I == "..")
110        llvm::sys::path::remove_filename(FullPath);
111      else
112        llvm::sys::path::append(FullPath, *I);
113    }
114    return UTF8ToUTF16(FullPath, Path16);
115  }
116
117  // Just use the caller's original path.
118  return UTF8ToUTF16(Path8Str, Path16);
119}
120} // end namespace path
121
122namespace fs {
123
124std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
125  SmallVector<wchar_t, MAX_PATH> PathName;
126  DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
127
128  // A zero return value indicates a failure other than insufficient space.
129  if (Size == 0)
130    return "";
131
132  // Insufficient space is determined by a return value equal to the size of
133  // the buffer passed in.
134  if (Size == PathName.capacity())
135    return "";
136
137  // On success, GetModuleFileNameW returns the number of characters written to
138  // the buffer not including the NULL terminator.
139  PathName.set_size(Size);
140
141  // Convert the result from UTF-16 to UTF-8.
142  SmallVector<char, MAX_PATH> PathNameUTF8;
143  if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
144    return "";
145
146  return std::string(PathNameUTF8.data());
147}
148
149UniqueID file_status::getUniqueID() const {
150  // The file is uniquely identified by the volume serial number along
151  // with the 64-bit file identifier.
152  uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
153                    static_cast<uint64_t>(FileIndexLow);
154
155  return UniqueID(VolumeSerialNumber, FileID);
156}
157
158ErrorOr<space_info> disk_space(const Twine &Path) {
159  ULARGE_INTEGER Avail, Total, Free;
160  if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
161    return mapWindowsError(::GetLastError());
162  space_info SpaceInfo;
163  SpaceInfo.capacity =
164      (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
165  SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
166  SpaceInfo.available =
167      (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
168  return SpaceInfo;
169}
170
171TimePoint<> file_status::getLastAccessedTime() const {
172  FILETIME Time;
173  Time.dwLowDateTime = LastAccessedTimeLow;
174  Time.dwHighDateTime = LastAccessedTimeHigh;
175  return toTimePoint(Time);
176}
177
178TimePoint<> file_status::getLastModificationTime() const {
179  FILETIME Time;
180  Time.dwLowDateTime = LastWriteTimeLow;
181  Time.dwHighDateTime = LastWriteTimeHigh;
182  return toTimePoint(Time);
183}
184
185uint32_t file_status::getLinkCount() const {
186  return NumLinks;
187}
188
189std::error_code current_path(SmallVectorImpl<char> &result) {
190  SmallVector<wchar_t, MAX_PATH> cur_path;
191  DWORD len = MAX_PATH;
192
193  do {
194    cur_path.reserve(len);
195    len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
196
197    // A zero return value indicates a failure other than insufficient space.
198    if (len == 0)
199      return mapWindowsError(::GetLastError());
200
201    // If there's insufficient space, the len returned is larger than the len
202    // given.
203  } while (len > cur_path.capacity());
204
205  // On success, GetCurrentDirectoryW returns the number of characters not
206  // including the null-terminator.
207  cur_path.set_size(len);
208  return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
209}
210
211std::error_code set_current_path(const Twine &path) {
212  // Convert to utf-16.
213  SmallVector<wchar_t, 128> wide_path;
214  if (std::error_code ec = widenPath(path, wide_path))
215    return ec;
216
217  if (!::SetCurrentDirectoryW(wide_path.begin()))
218    return mapWindowsError(::GetLastError());
219
220  return std::error_code();
221}
222
223std::error_code create_directory(const Twine &path, bool IgnoreExisting,
224                                 perms Perms) {
225  SmallVector<wchar_t, 128> path_utf16;
226
227  if (std::error_code ec = widenPath(path, path_utf16))
228    return ec;
229
230  if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
231    DWORD LastError = ::GetLastError();
232    if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
233      return mapWindowsError(LastError);
234  }
235
236  return std::error_code();
237}
238
239// We can't use symbolic links for windows.
240std::error_code create_link(const Twine &to, const Twine &from) {
241  // Convert to utf-16.
242  SmallVector<wchar_t, 128> wide_from;
243  SmallVector<wchar_t, 128> wide_to;
244  if (std::error_code ec = widenPath(from, wide_from))
245    return ec;
246  if (std::error_code ec = widenPath(to, wide_to))
247    return ec;
248
249  if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
250    return mapWindowsError(::GetLastError());
251
252  return std::error_code();
253}
254
255std::error_code create_hard_link(const Twine &to, const Twine &from) {
256  return create_link(to, from);
257}
258
259std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
260  SmallVector<wchar_t, 128> path_utf16;
261
262  file_status ST;
263  if (std::error_code EC = status(path, ST)) {
264    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
265      return EC;
266    return std::error_code();
267  }
268
269  if (std::error_code ec = widenPath(path, path_utf16))
270    return ec;
271
272  if (ST.type() == file_type::directory_file) {
273    if (!::RemoveDirectoryW(c_str(path_utf16))) {
274      std::error_code EC = mapWindowsError(::GetLastError());
275      if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
276        return EC;
277    }
278    return std::error_code();
279  }
280  if (!::DeleteFileW(c_str(path_utf16))) {
281    std::error_code EC = mapWindowsError(::GetLastError());
282    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
283      return EC;
284  }
285  return std::error_code();
286}
287
288static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
289                                         bool &Result) {
290  SmallVector<wchar_t, 128> VolumePath;
291  size_t Len = 128;
292  while (true) {
293    VolumePath.resize(Len);
294    BOOL Success =
295        ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
296
297    if (Success)
298      break;
299
300    DWORD Err = ::GetLastError();
301    if (Err != ERROR_INSUFFICIENT_BUFFER)
302      return mapWindowsError(Err);
303
304    Len *= 2;
305  }
306  // If the output buffer has exactly enough space for the path name, but not
307  // the null terminator, it will leave the output unterminated.  Push a null
308  // terminator onto the end to ensure that this never happens.
309  VolumePath.push_back(L'\0');
310  VolumePath.set_size(wcslen(VolumePath.data()));
311  const wchar_t *P = VolumePath.data();
312
313  UINT Type = ::GetDriveTypeW(P);
314  switch (Type) {
315  case DRIVE_FIXED:
316    Result = true;
317    return std::error_code();
318  case DRIVE_REMOTE:
319  case DRIVE_CDROM:
320  case DRIVE_RAMDISK:
321  case DRIVE_REMOVABLE:
322    Result = false;
323    return std::error_code();
324  default:
325    return make_error_code(errc::no_such_file_or_directory);
326  }
327  llvm_unreachable("Unreachable!");
328}
329
330std::error_code is_local(const Twine &path, bool &result) {
331  if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
332    return make_error_code(errc::no_such_file_or_directory);
333
334  SmallString<128> Storage;
335  StringRef P = path.toStringRef(Storage);
336
337  // Convert to utf-16.
338  SmallVector<wchar_t, 128> WidePath;
339  if (std::error_code ec = widenPath(P, WidePath))
340    return ec;
341  return is_local_internal(WidePath, result);
342}
343
344std::error_code is_local(int FD, bool &Result) {
345  SmallVector<wchar_t, 128> FinalPath;
346  HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
347
348  size_t Len = 128;
349  do {
350    FinalPath.reserve(Len);
351    Len = ::GetFinalPathNameByHandleW(Handle, FinalPath.data(),
352                                      FinalPath.capacity() - 1, VOLUME_NAME_NT);
353    if (Len == 0)
354      return mapWindowsError(::GetLastError());
355  } while (Len > FinalPath.capacity());
356
357  FinalPath.set_size(Len);
358
359  return is_local_internal(FinalPath, Result);
360}
361
362static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
363                                       bool ReplaceIfExists) {
364  SmallVector<wchar_t, 0> ToWide;
365  if (auto EC = widenPath(To, ToWide))
366    return EC;
367
368  std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
369                                  (ToWide.size() * sizeof(wchar_t)));
370  FILE_RENAME_INFO &RenameInfo =
371      *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
372  RenameInfo.ReplaceIfExists = ReplaceIfExists;
373  RenameInfo.RootDirectory = 0;
374  RenameInfo.FileNameLength = ToWide.size();
375  std::copy(ToWide.begin(), ToWide.end(), RenameInfo.FileName);
376
377  if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
378                                  RenameInfoBuf.size()))
379    return mapWindowsError(GetLastError());
380
381  return std::error_code();
382}
383
384std::error_code rename(const Twine &From, const Twine &To) {
385  // Convert to utf-16.
386  SmallVector<wchar_t, 128> WideFrom;
387  SmallVector<wchar_t, 128> WideTo;
388  if (std::error_code EC = widenPath(From, WideFrom))
389    return EC;
390  if (std::error_code EC = widenPath(To, WideTo))
391    return EC;
392
393  ScopedFileHandle FromHandle;
394  // Retry this a few times to defeat badly behaved file system scanners.
395  for (unsigned Retry = 0; Retry != 200; ++Retry) {
396    if (Retry != 0)
397      ::Sleep(10);
398    FromHandle =
399        ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
400                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
401                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
402    if (FromHandle)
403      break;
404  }
405  if (!FromHandle)
406    return mapWindowsError(GetLastError());
407
408  // We normally expect this loop to succeed after a few iterations. If it
409  // requires more than 200 tries, it's more likely that the failures are due to
410  // a true error, so stop trying.
411  for (unsigned Retry = 0; Retry != 200; ++Retry) {
412    auto EC = rename_internal(FromHandle, To, true);
413    if (!EC || EC != errc::permission_denied)
414      return EC;
415
416    // The destination file probably exists and is currently open in another
417    // process, either because the file was opened without FILE_SHARE_DELETE or
418    // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
419    // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
420    // to arrange for the destination file to be deleted when the other process
421    // closes it.
422    ScopedFileHandle ToHandle(
423        ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
424                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
425                      NULL, OPEN_EXISTING,
426                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
427    if (!ToHandle) {
428      auto EC = mapWindowsError(GetLastError());
429      // Another process might have raced with us and moved the existing file
430      // out of the way before we had a chance to open it. If that happens, try
431      // to rename the source file again.
432      if (EC == errc::no_such_file_or_directory)
433        continue;
434      return EC;
435    }
436
437    BY_HANDLE_FILE_INFORMATION FI;
438    if (!GetFileInformationByHandle(ToHandle, &FI))
439      return mapWindowsError(GetLastError());
440
441    // Try to find a unique new name for the destination file.
442    for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
443      std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
444      if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
445        if (EC == errc::file_exists || EC == errc::permission_denied) {
446          // Again, another process might have raced with us and moved the file
447          // before we could move it. Check whether this is the case, as it
448          // might have caused the permission denied error. If that was the
449          // case, we don't need to move it ourselves.
450          ScopedFileHandle ToHandle2(::CreateFileW(
451              WideTo.begin(), 0,
452              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
453              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
454          if (!ToHandle2) {
455            auto EC = mapWindowsError(GetLastError());
456            if (EC == errc::no_such_file_or_directory)
457              break;
458            return EC;
459          }
460          BY_HANDLE_FILE_INFORMATION FI2;
461          if (!GetFileInformationByHandle(ToHandle2, &FI2))
462            return mapWindowsError(GetLastError());
463          if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
464              FI.nFileIndexLow != FI2.nFileIndexLow ||
465              FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
466            break;
467          continue;
468        }
469        return EC;
470      }
471      break;
472    }
473
474    // Okay, the old destination file has probably been moved out of the way at
475    // this point, so try to rename the source file again. Still, another
476    // process might have raced with us to create and open the destination
477    // file, so we need to keep doing this until we succeed.
478  }
479
480  // The most likely root cause.
481  return errc::permission_denied;
482}
483
484std::error_code resize_file(int FD, uint64_t Size) {
485#ifdef HAVE__CHSIZE_S
486  errno_t error = ::_chsize_s(FD, Size);
487#else
488  errno_t error = ::_chsize(FD, Size);
489#endif
490  return std::error_code(error, std::generic_category());
491}
492
493std::error_code access(const Twine &Path, AccessMode Mode) {
494  SmallVector<wchar_t, 128> PathUtf16;
495
496  if (std::error_code EC = widenPath(Path, PathUtf16))
497    return EC;
498
499  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
500
501  if (Attributes == INVALID_FILE_ATTRIBUTES) {
502    // See if the file didn't actually exist.
503    DWORD LastError = ::GetLastError();
504    if (LastError != ERROR_FILE_NOT_FOUND &&
505        LastError != ERROR_PATH_NOT_FOUND)
506      return mapWindowsError(LastError);
507    return errc::no_such_file_or_directory;
508  }
509
510  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
511    return errc::permission_denied;
512
513  return std::error_code();
514}
515
516bool can_execute(const Twine &Path) {
517  return !access(Path, AccessMode::Execute) ||
518         !access(Path + ".exe", AccessMode::Execute);
519}
520
521bool equivalent(file_status A, file_status B) {
522  assert(status_known(A) && status_known(B));
523  return A.FileIndexHigh         == B.FileIndexHigh &&
524         A.FileIndexLow          == B.FileIndexLow &&
525         A.FileSizeHigh          == B.FileSizeHigh &&
526         A.FileSizeLow           == B.FileSizeLow &&
527         A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
528         A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
529         A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
530         A.LastWriteTimeLow      == B.LastWriteTimeLow &&
531         A.VolumeSerialNumber    == B.VolumeSerialNumber;
532}
533
534std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
535  file_status fsA, fsB;
536  if (std::error_code ec = status(A, fsA))
537    return ec;
538  if (std::error_code ec = status(B, fsB))
539    return ec;
540  result = equivalent(fsA, fsB);
541  return std::error_code();
542}
543
544static bool isReservedName(StringRef path) {
545  // This list of reserved names comes from MSDN, at:
546  // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
547  static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
548                                                "com1", "com2", "com3", "com4",
549                                                "com5", "com6", "com7", "com8",
550                                                "com9", "lpt1", "lpt2", "lpt3",
551                                                "lpt4", "lpt5", "lpt6", "lpt7",
552                                                "lpt8", "lpt9" };
553
554  // First, check to see if this is a device namespace, which always
555  // starts with \\.\, since device namespaces are not legal file paths.
556  if (path.startswith("\\\\.\\"))
557    return true;
558
559  // Then compare against the list of ancient reserved names.
560  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
561    if (path.equals_lower(sReservedNames[i]))
562      return true;
563  }
564
565  // The path isn't what we consider reserved.
566  return false;
567}
568
569static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
570  if (FileHandle == INVALID_HANDLE_VALUE)
571    goto handle_status_error;
572
573  switch (::GetFileType(FileHandle)) {
574  default:
575    llvm_unreachable("Don't know anything about this file type");
576  case FILE_TYPE_UNKNOWN: {
577    DWORD Err = ::GetLastError();
578    if (Err != NO_ERROR)
579      return mapWindowsError(Err);
580    Result = file_status(file_type::type_unknown);
581    return std::error_code();
582  }
583  case FILE_TYPE_DISK:
584    break;
585  case FILE_TYPE_CHAR:
586    Result = file_status(file_type::character_file);
587    return std::error_code();
588  case FILE_TYPE_PIPE:
589    Result = file_status(file_type::fifo_file);
590    return std::error_code();
591  }
592
593  BY_HANDLE_FILE_INFORMATION Info;
594  if (!::GetFileInformationByHandle(FileHandle, &Info))
595    goto handle_status_error;
596
597  {
598    file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
599                         ? file_type::directory_file
600                         : file_type::regular_file;
601    perms Permissions = (Info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
602                            ? (all_read | all_exe)
603                            : all_all;
604    Result = file_status(
605        Type, Permissions, Info.nNumberOfLinks,
606        Info.ftLastAccessTime.dwHighDateTime,
607        Info.ftLastAccessTime.dwLowDateTime,
608        Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
609        Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
610        Info.nFileIndexHigh, Info.nFileIndexLow);
611    return std::error_code();
612  }
613
614handle_status_error:
615  DWORD LastError = ::GetLastError();
616  if (LastError == ERROR_FILE_NOT_FOUND ||
617      LastError == ERROR_PATH_NOT_FOUND)
618    Result = file_status(file_type::file_not_found);
619  else if (LastError == ERROR_SHARING_VIOLATION)
620    Result = file_status(file_type::type_unknown);
621  else
622    Result = file_status(file_type::status_error);
623  return mapWindowsError(LastError);
624}
625
626std::error_code status(const Twine &path, file_status &result, bool Follow) {
627  SmallString<128> path_storage;
628  SmallVector<wchar_t, 128> path_utf16;
629
630  StringRef path8 = path.toStringRef(path_storage);
631  if (isReservedName(path8)) {
632    result = file_status(file_type::character_file);
633    return std::error_code();
634  }
635
636  if (std::error_code ec = widenPath(path8, path_utf16))
637    return ec;
638
639  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
640  if (attr == INVALID_FILE_ATTRIBUTES)
641    return getStatus(INVALID_HANDLE_VALUE, result);
642
643  DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
644  // Handle reparse points.
645  if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
646    Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
647
648  ScopedFileHandle h(
649      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
650                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
651                    NULL, OPEN_EXISTING, Flags, 0));
652  if (!h)
653    return getStatus(INVALID_HANDLE_VALUE, result);
654
655  return getStatus(h, result);
656}
657
658std::error_code status(int FD, file_status &Result) {
659  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
660  return getStatus(FileHandle, Result);
661}
662
663std::error_code setPermissions(const Twine &Path, perms Permissions) {
664  SmallVector<wchar_t, 128> PathUTF16;
665  if (std::error_code EC = widenPath(Path, PathUTF16))
666    return EC;
667
668  DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
669  if (Attributes == INVALID_FILE_ATTRIBUTES)
670    return mapWindowsError(GetLastError());
671
672  // There are many Windows file attributes that are not to do with the file
673  // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
674  // them.
675  if (Permissions & all_write) {
676    Attributes &= ~FILE_ATTRIBUTE_READONLY;
677    if (Attributes == 0)
678      // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
679      Attributes |= FILE_ATTRIBUTE_NORMAL;
680  }
681  else {
682    Attributes |= FILE_ATTRIBUTE_READONLY;
683    // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
684    // remove it, if it is present.
685    Attributes &= ~FILE_ATTRIBUTE_NORMAL;
686  }
687
688  if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
689    return mapWindowsError(GetLastError());
690
691  return std::error_code();
692}
693
694std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
695  FILETIME FT = toFILETIME(Time);
696  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
697  if (!SetFileTime(FileHandle, NULL, &FT, &FT))
698    return mapWindowsError(::GetLastError());
699  return std::error_code();
700}
701
702std::error_code mapped_file_region::init(int FD, uint64_t Offset,
703                                         mapmode Mode) {
704  // Make sure that the requested size fits within SIZE_T.
705  if (Size > std::numeric_limits<SIZE_T>::max())
706    return make_error_code(errc::invalid_argument);
707
708  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
709  if (FileHandle == INVALID_HANDLE_VALUE)
710    return make_error_code(errc::bad_file_descriptor);
711
712  DWORD flprotect;
713  switch (Mode) {
714  case readonly:  flprotect = PAGE_READONLY; break;
715  case readwrite: flprotect = PAGE_READWRITE; break;
716  case priv:      flprotect = PAGE_WRITECOPY; break;
717  }
718
719  HANDLE FileMappingHandle =
720      ::CreateFileMappingW(FileHandle, 0, flprotect,
721                           (Offset + Size) >> 32,
722                           (Offset + Size) & 0xffffffff,
723                           0);
724  if (FileMappingHandle == NULL) {
725    std::error_code ec = mapWindowsError(GetLastError());
726    return ec;
727  }
728
729  DWORD dwDesiredAccess;
730  switch (Mode) {
731  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
732  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
733  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
734  }
735  Mapping = ::MapViewOfFile(FileMappingHandle,
736                            dwDesiredAccess,
737                            Offset >> 32,
738                            Offset & 0xffffffff,
739                            Size);
740  if (Mapping == NULL) {
741    std::error_code ec = mapWindowsError(GetLastError());
742    ::CloseHandle(FileMappingHandle);
743    return ec;
744  }
745
746  if (Size == 0) {
747    MEMORY_BASIC_INFORMATION mbi;
748    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
749    if (Result == 0) {
750      std::error_code ec = mapWindowsError(GetLastError());
751      ::UnmapViewOfFile(Mapping);
752      ::CloseHandle(FileMappingHandle);
753      return ec;
754    }
755    Size = mbi.RegionSize;
756  }
757
758  // Close all the handles except for the view. It will keep the other handles
759  // alive.
760  ::CloseHandle(FileMappingHandle);
761  return std::error_code();
762}
763
764mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
765                                       uint64_t offset, std::error_code &ec)
766    : Size(length), Mapping() {
767  ec = init(fd, offset, mode);
768  if (ec)
769    Mapping = 0;
770}
771
772mapped_file_region::~mapped_file_region() {
773  if (Mapping)
774    ::UnmapViewOfFile(Mapping);
775}
776
777size_t mapped_file_region::size() const {
778  assert(Mapping && "Mapping failed but used anyway!");
779  return Size;
780}
781
782char *mapped_file_region::data() const {
783  assert(Mapping && "Mapping failed but used anyway!");
784  return reinterpret_cast<char*>(Mapping);
785}
786
787const char *mapped_file_region::const_data() const {
788  assert(Mapping && "Mapping failed but used anyway!");
789  return reinterpret_cast<const char*>(Mapping);
790}
791
792int mapped_file_region::alignment() {
793  SYSTEM_INFO SysInfo;
794  ::GetSystemInfo(&SysInfo);
795  return SysInfo.dwAllocationGranularity;
796}
797
798std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
799                                                     StringRef path,
800                                                     bool follow_symlinks) {
801  SmallVector<wchar_t, 128> path_utf16;
802
803  if (std::error_code ec = widenPath(path, path_utf16))
804    return ec;
805
806  // Convert path to the format that Windows is happy with.
807  if (path_utf16.size() > 0 &&
808      !is_separator(path_utf16[path.size() - 1]) &&
809      path_utf16[path.size() - 1] != L':') {
810    path_utf16.push_back(L'\\');
811    path_utf16.push_back(L'*');
812  } else {
813    path_utf16.push_back(L'*');
814  }
815
816  //  Get the first directory entry.
817  WIN32_FIND_DATAW FirstFind;
818  ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
819  if (!FindHandle)
820    return mapWindowsError(::GetLastError());
821
822  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
823  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
824         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
825                              FirstFind.cFileName[1] == L'.'))
826    if (!::FindNextFileW(FindHandle, &FirstFind)) {
827      DWORD LastError = ::GetLastError();
828      // Check for end.
829      if (LastError == ERROR_NO_MORE_FILES)
830        return detail::directory_iterator_destruct(it);
831      return mapWindowsError(LastError);
832    } else
833      FilenameLen = ::wcslen(FirstFind.cFileName);
834
835  // Construct the current directory entry.
836  SmallString<128> directory_entry_name_utf8;
837  if (std::error_code ec =
838          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
839                      directory_entry_name_utf8))
840    return ec;
841
842  it.IterationHandle = intptr_t(FindHandle.take());
843  SmallString<128> directory_entry_path(path);
844  path::append(directory_entry_path, directory_entry_name_utf8);
845  it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks);
846
847  return std::error_code();
848}
849
850std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
851  if (it.IterationHandle != 0)
852    // Closes the handle if it's valid.
853    ScopedFindHandle close(HANDLE(it.IterationHandle));
854  it.IterationHandle = 0;
855  it.CurrentEntry = directory_entry();
856  return std::error_code();
857}
858
859std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
860  WIN32_FIND_DATAW FindData;
861  if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
862    DWORD LastError = ::GetLastError();
863    // Check for end.
864    if (LastError == ERROR_NO_MORE_FILES)
865      return detail::directory_iterator_destruct(it);
866    return mapWindowsError(LastError);
867  }
868
869  size_t FilenameLen = ::wcslen(FindData.cFileName);
870  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
871      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
872                           FindData.cFileName[1] == L'.'))
873    return directory_iterator_increment(it);
874
875  SmallString<128> directory_entry_path_utf8;
876  if (std::error_code ec =
877          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
878                      directory_entry_path_utf8))
879    return ec;
880
881  it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
882  return std::error_code();
883}
884
885static std::error_code realPathFromHandle(HANDLE H,
886                                          SmallVectorImpl<char> &RealPath) {
887  RealPath.clear();
888  llvm::SmallVector<wchar_t, MAX_PATH> Buffer;
889  DWORD CountChars = ::GetFinalPathNameByHandleW(
890      H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
891  if (CountChars > Buffer.capacity()) {
892    // The buffer wasn't big enough, try again.  In this case the return value
893    // *does* indicate the size of the null terminator.
894    Buffer.reserve(CountChars);
895    CountChars = ::GetFinalPathNameByHandleW(
896        H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
897  }
898  if (CountChars == 0)
899    return mapWindowsError(GetLastError());
900
901  const wchar_t *Data = Buffer.data();
902  if (CountChars >= 4) {
903    if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
904      CountChars -= 4;
905      Data += 4;
906    }
907  }
908
909  // Convert the result from UTF-16 to UTF-8.
910  return UTF16ToUTF8(Data, CountChars, RealPath);
911}
912
913static std::error_code directoryRealPath(const Twine &Name,
914                                         SmallVectorImpl<char> &RealPath) {
915  SmallVector<wchar_t, 128> PathUTF16;
916
917  if (std::error_code EC = widenPath(Name, PathUTF16))
918    return EC;
919
920  HANDLE H =
921      ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
922                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
923                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
924  if (H == INVALID_HANDLE_VALUE)
925    return mapWindowsError(GetLastError());
926  std::error_code EC = realPathFromHandle(H, RealPath);
927  ::CloseHandle(H);
928  return EC;
929}
930
931std::error_code openFileForRead(const Twine &Name, int &ResultFD,
932                                SmallVectorImpl<char> *RealPath) {
933  SmallVector<wchar_t, 128> PathUTF16;
934
935  if (std::error_code EC = widenPath(Name, PathUTF16))
936    return EC;
937
938  HANDLE H =
939      ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
940                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
941                    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
942  if (H == INVALID_HANDLE_VALUE) {
943    DWORD LastError = ::GetLastError();
944    std::error_code EC = mapWindowsError(LastError);
945    // Provide a better error message when trying to open directories.
946    // This only runs if we failed to open the file, so there is probably
947    // no performances issues.
948    if (LastError != ERROR_ACCESS_DENIED)
949      return EC;
950    if (is_directory(Name))
951      return make_error_code(errc::is_a_directory);
952    return EC;
953  }
954
955  int FD = ::_open_osfhandle(intptr_t(H), 0);
956  if (FD == -1) {
957    ::CloseHandle(H);
958    return mapWindowsError(ERROR_INVALID_HANDLE);
959  }
960
961  // Fetch the real name of the file, if the user asked
962  if (RealPath)
963    realPathFromHandle(H, *RealPath);
964
965  ResultFD = FD;
966  return std::error_code();
967}
968
969std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
970                            sys::fs::OpenFlags Flags, unsigned Mode) {
971  // Verify that we don't have both "append" and "excl".
972  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
973         "Cannot specify both 'excl' and 'append' file creation flags!");
974
975  SmallVector<wchar_t, 128> PathUTF16;
976
977  if (std::error_code EC = widenPath(Name, PathUTF16))
978    return EC;
979
980  DWORD CreationDisposition;
981  if (Flags & F_Excl)
982    CreationDisposition = CREATE_NEW;
983  else if (Flags & F_Append)
984    CreationDisposition = OPEN_ALWAYS;
985  else
986    CreationDisposition = CREATE_ALWAYS;
987
988  DWORD Access = GENERIC_WRITE;
989  if (Flags & F_RW)
990    Access |= GENERIC_READ;
991
992  HANDLE H =
993      ::CreateFileW(PathUTF16.begin(), Access,
994                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
995                    NULL, CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
996
997  if (H == INVALID_HANDLE_VALUE) {
998    DWORD LastError = ::GetLastError();
999    std::error_code EC = mapWindowsError(LastError);
1000    // Provide a better error message when trying to open directories.
1001    // This only runs if we failed to open the file, so there is probably
1002    // no performances issues.
1003    if (LastError != ERROR_ACCESS_DENIED)
1004      return EC;
1005    if (is_directory(Name))
1006      return make_error_code(errc::is_a_directory);
1007    return EC;
1008  }
1009
1010  int OpenFlags = 0;
1011  if (Flags & F_Append)
1012    OpenFlags |= _O_APPEND;
1013
1014  if (Flags & F_Text)
1015    OpenFlags |= _O_TEXT;
1016
1017  int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1018  if (FD == -1) {
1019    ::CloseHandle(H);
1020    return mapWindowsError(ERROR_INVALID_HANDLE);
1021  }
1022
1023  ResultFD = FD;
1024  return std::error_code();
1025}
1026
1027std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1028  // Convert to utf-16.
1029  SmallVector<wchar_t, 128> Path16;
1030  std::error_code EC = widenPath(path, Path16);
1031  if (EC && !IgnoreErrors)
1032    return EC;
1033
1034  // SHFileOperation() accepts a list of paths, and so must be double null-
1035  // terminated to indicate the end of the list.  The buffer is already null
1036  // terminated, but since that null character is not considered part of the
1037  // vector's size, pushing another one will just consume that byte.  So we
1038  // need to push 2 null terminators.
1039  Path16.push_back(0);
1040  Path16.push_back(0);
1041
1042  SHFILEOPSTRUCTW shfos = {};
1043  shfos.wFunc = FO_DELETE;
1044  shfos.pFrom = Path16.data();
1045  shfos.fFlags = FOF_NO_UI;
1046
1047  int result = ::SHFileOperationW(&shfos);
1048  if (result != 0 && !IgnoreErrors)
1049    return mapWindowsError(result);
1050  return std::error_code();
1051}
1052
1053static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1054  // Path does not begin with a tilde expression.
1055  if (Path.empty() || Path[0] != '~')
1056    return;
1057
1058  StringRef PathStr(Path.begin(), Path.size());
1059  PathStr = PathStr.drop_front();
1060  StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1061
1062  if (!Expr.empty()) {
1063    // This is probably a ~username/ expression.  Don't support this on Windows.
1064    return;
1065  }
1066
1067  SmallString<128> HomeDir;
1068  if (!path::home_directory(HomeDir)) {
1069    // For some reason we couldn't get the home directory.  Just exit.
1070    return;
1071  }
1072
1073  // Overwrite the first character and insert the rest.
1074  Path[0] = HomeDir[0];
1075  Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1076}
1077
1078std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1079                          bool expand_tilde) {
1080  dest.clear();
1081  if (path.isTriviallyEmpty())
1082    return std::error_code();
1083
1084  if (expand_tilde) {
1085    SmallString<128> Storage;
1086    path.toVector(Storage);
1087    expandTildeExpr(Storage);
1088    return real_path(Storage, dest, false);
1089  }
1090
1091  if (is_directory(path))
1092    return directoryRealPath(path, dest);
1093
1094  int fd;
1095  if (std::error_code EC = llvm::sys::fs::openFileForRead(path, fd, &dest))
1096    return EC;
1097  ::close(fd);
1098  return std::error_code();
1099}
1100
1101} // end namespace fs
1102
1103namespace path {
1104static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1105                               SmallVectorImpl<char> &result) {
1106  wchar_t *path = nullptr;
1107  if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1108    return false;
1109
1110  bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1111  ::CoTaskMemFree(path);
1112  return ok;
1113}
1114
1115bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1116  return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1117}
1118
1119bool home_directory(SmallVectorImpl<char> &result) {
1120  return getKnownFolderPath(FOLDERID_Profile, result);
1121}
1122
1123static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1124  SmallVector<wchar_t, 1024> Buf;
1125  size_t Size = 1024;
1126  do {
1127    Buf.reserve(Size);
1128    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1129    if (Size == 0)
1130      return false;
1131
1132    // Try again with larger buffer.
1133  } while (Size > Buf.capacity());
1134  Buf.set_size(Size);
1135
1136  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1137}
1138
1139static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1140  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1141  for (auto *Env : EnvironmentVariables) {
1142    if (getTempDirEnvVar(Env, Res))
1143      return true;
1144  }
1145  return false;
1146}
1147
1148void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1149  (void)ErasedOnReboot;
1150  Result.clear();
1151
1152  // Check whether the temporary directory is specified by an environment var.
1153  // This matches GetTempPath logic to some degree. GetTempPath is not used
1154  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1155  // (fixed on Windows 8).
1156  if (getTempDirEnvVar(Result)) {
1157    assert(!Result.empty() && "Unexpected empty path");
1158    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1159    fs::make_absolute(Result); // Make it absolute if not already.
1160    return;
1161  }
1162
1163  // Fall back to a system default.
1164  const char *DefaultResult = "C:\\Temp";
1165  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1166}
1167} // end namespace path
1168
1169namespace windows {
1170std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1171                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1172  if (!utf8.empty()) {
1173    int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1174                                    utf8.size(), utf16.begin(), 0);
1175
1176    if (len == 0)
1177      return mapWindowsError(::GetLastError());
1178
1179    utf16.reserve(len + 1);
1180    utf16.set_size(len);
1181
1182    len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1183                                utf8.size(), utf16.begin(), utf16.size());
1184
1185    if (len == 0)
1186      return mapWindowsError(::GetLastError());
1187  }
1188
1189  // Make utf16 null terminated.
1190  utf16.push_back(0);
1191  utf16.pop_back();
1192
1193  return std::error_code();
1194}
1195
1196static
1197std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1198                                size_t utf16_len,
1199                                llvm::SmallVectorImpl<char> &utf8) {
1200  if (utf16_len) {
1201    // Get length.
1202    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
1203                                    0, NULL, NULL);
1204
1205    if (len == 0)
1206      return mapWindowsError(::GetLastError());
1207
1208    utf8.reserve(len);
1209    utf8.set_size(len);
1210
1211    // Now do the actual conversion.
1212    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
1213                                utf8.size(), NULL, NULL);
1214
1215    if (len == 0)
1216      return mapWindowsError(::GetLastError());
1217  }
1218
1219  // Make utf8 null terminated.
1220  utf8.push_back(0);
1221  utf8.pop_back();
1222
1223  return std::error_code();
1224}
1225
1226std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1227                            llvm::SmallVectorImpl<char> &utf8) {
1228  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1229}
1230
1231std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1232                             llvm::SmallVectorImpl<char> &utf8) {
1233  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
1234}
1235
1236} // end namespace windows
1237} // end namespace sys
1238} // end namespace llvm
1239