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 <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#endif
42
43using namespace llvm;
44
45using llvm::sys::windows::UTF8ToUTF16;
46using llvm::sys::windows::UTF16ToUTF8;
47
48static std::error_code windows_error(DWORD E) {
49  return mapWindowsError(E);
50}
51
52static bool is_separator(const wchar_t value) {
53  switch (value) {
54  case L'\\':
55  case L'/':
56    return true;
57  default:
58    return false;
59  }
60}
61
62namespace llvm {
63namespace sys  {
64namespace fs {
65
66std::string getMainExecutable(const char *argv0, void *MainExecAddr) {
67  SmallVector<wchar_t, MAX_PATH> PathName;
68  DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
69
70  // A zero return value indicates a failure other than insufficient space.
71  if (Size == 0)
72    return "";
73
74  // Insufficient space is determined by a return value equal to the size of
75  // the buffer passed in.
76  if (Size == PathName.capacity())
77    return "";
78
79  // On success, GetModuleFileNameW returns the number of characters written to
80  // the buffer not including the NULL terminator.
81  PathName.set_size(Size);
82
83  // Convert the result from UTF-16 to UTF-8.
84  SmallVector<char, MAX_PATH> PathNameUTF8;
85  if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
86    return "";
87
88  return std::string(PathNameUTF8.data());
89}
90
91UniqueID file_status::getUniqueID() const {
92  // The file is uniquely identified by the volume serial number along
93  // with the 64-bit file identifier.
94  uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
95                    static_cast<uint64_t>(FileIndexLow);
96
97  return UniqueID(VolumeSerialNumber, FileID);
98}
99
100TimeValue file_status::getLastModificationTime() const {
101  ULARGE_INTEGER UI;
102  UI.LowPart = LastWriteTimeLow;
103  UI.HighPart = LastWriteTimeHigh;
104
105  TimeValue Ret;
106  Ret.fromWin32Time(UI.QuadPart);
107  return Ret;
108}
109
110std::error_code current_path(SmallVectorImpl<char> &result) {
111  SmallVector<wchar_t, MAX_PATH> cur_path;
112  DWORD len = MAX_PATH;
113
114  do {
115    cur_path.reserve(len);
116    len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
117
118    // A zero return value indicates a failure other than insufficient space.
119    if (len == 0)
120      return windows_error(::GetLastError());
121
122    // If there's insufficient space, the len returned is larger than the len
123    // given.
124  } while (len > cur_path.capacity());
125
126  // On success, GetCurrentDirectoryW returns the number of characters not
127  // including the null-terminator.
128  cur_path.set_size(len);
129  return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
130}
131
132std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
133  SmallString<128> path_storage;
134  SmallVector<wchar_t, 128> path_utf16;
135
136  if (std::error_code ec =
137          UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
138    return ec;
139
140  if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
141    DWORD LastError = ::GetLastError();
142    if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
143      return windows_error(LastError);
144  }
145
146  return std::error_code();
147}
148
149// We can't use symbolic links for windows.
150std::error_code create_link(const Twine &to, const Twine &from) {
151  // Get arguments.
152  SmallString<128> from_storage;
153  SmallString<128> to_storage;
154  StringRef f = from.toStringRef(from_storage);
155  StringRef t = to.toStringRef(to_storage);
156
157  // Convert to utf-16.
158  SmallVector<wchar_t, 128> wide_from;
159  SmallVector<wchar_t, 128> wide_to;
160  if (std::error_code ec = UTF8ToUTF16(f, wide_from))
161    return ec;
162  if (std::error_code ec = UTF8ToUTF16(t, wide_to))
163    return ec;
164
165  if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
166    return windows_error(::GetLastError());
167
168  return std::error_code();
169}
170
171std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
172  SmallString<128> path_storage;
173  SmallVector<wchar_t, 128> path_utf16;
174
175  file_status ST;
176  if (std::error_code EC = status(path, ST)) {
177    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
178      return EC;
179    return std::error_code();
180  }
181
182  if (std::error_code ec =
183          UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
184    return ec;
185
186  if (ST.type() == file_type::directory_file) {
187    if (!::RemoveDirectoryW(c_str(path_utf16))) {
188      std::error_code EC = windows_error(::GetLastError());
189      if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
190        return EC;
191    }
192    return std::error_code();
193  }
194  if (!::DeleteFileW(c_str(path_utf16))) {
195    std::error_code EC = windows_error(::GetLastError());
196    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
197      return EC;
198  }
199  return std::error_code();
200}
201
202std::error_code rename(const Twine &from, const Twine &to) {
203  // Get arguments.
204  SmallString<128> from_storage;
205  SmallString<128> to_storage;
206  StringRef f = from.toStringRef(from_storage);
207  StringRef t = to.toStringRef(to_storage);
208
209  // Convert to utf-16.
210  SmallVector<wchar_t, 128> wide_from;
211  SmallVector<wchar_t, 128> wide_to;
212  if (std::error_code ec = UTF8ToUTF16(f, wide_from))
213    return ec;
214  if (std::error_code ec = UTF8ToUTF16(t, wide_to))
215    return ec;
216
217  std::error_code ec = std::error_code();
218  for (int i = 0; i < 2000; i++) {
219    if (::MoveFileExW(wide_from.begin(), wide_to.begin(),
220                      MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING))
221      return std::error_code();
222    DWORD LastError = ::GetLastError();
223    if (LastError != ERROR_ACCESS_DENIED)
224      break;
225    // Retry MoveFile() at ACCESS_DENIED.
226    // System scanners (eg. indexer) might open the source file when
227    // It is written and closed.
228    ::Sleep(1);
229  }
230
231  return ec;
232}
233
234std::error_code resize_file(const Twine &path, uint64_t size) {
235  SmallString<128> path_storage;
236  SmallVector<wchar_t, 128> path_utf16;
237
238  if (std::error_code ec =
239          UTF8ToUTF16(path.toStringRef(path_storage), path_utf16))
240    return ec;
241
242  int fd = ::_wopen(path_utf16.begin(), O_BINARY | _O_RDWR, S_IWRITE);
243  if (fd == -1)
244    return std::error_code(errno, std::generic_category());
245#ifdef HAVE__CHSIZE_S
246  errno_t error = ::_chsize_s(fd, size);
247#else
248  errno_t error = ::_chsize(fd, size);
249#endif
250  ::close(fd);
251  return std::error_code(error, std::generic_category());
252}
253
254std::error_code access(const Twine &Path, AccessMode Mode) {
255  SmallString<128> PathStorage;
256  SmallVector<wchar_t, 128> PathUtf16;
257
258  if (std::error_code EC =
259          UTF8ToUTF16(Path.toStringRef(PathStorage), PathUtf16))
260    return EC;
261
262  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
263
264  if (Attributes == INVALID_FILE_ATTRIBUTES) {
265    // See if the file didn't actually exist.
266    DWORD LastError = ::GetLastError();
267    if (LastError != ERROR_FILE_NOT_FOUND &&
268        LastError != ERROR_PATH_NOT_FOUND)
269      return windows_error(LastError);
270    return errc::no_such_file_or_directory;
271  }
272
273  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
274    return errc::permission_denied;
275
276  return std::error_code();
277}
278
279bool equivalent(file_status A, file_status B) {
280  assert(status_known(A) && status_known(B));
281  return A.FileIndexHigh      == B.FileIndexHigh &&
282         A.FileIndexLow       == B.FileIndexLow &&
283         A.FileSizeHigh       == B.FileSizeHigh &&
284         A.FileSizeLow        == B.FileSizeLow &&
285         A.LastWriteTimeHigh  == B.LastWriteTimeHigh &&
286         A.LastWriteTimeLow   == B.LastWriteTimeLow &&
287         A.VolumeSerialNumber == B.VolumeSerialNumber;
288}
289
290std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
291  file_status fsA, fsB;
292  if (std::error_code ec = status(A, fsA))
293    return ec;
294  if (std::error_code ec = status(B, fsB))
295    return ec;
296  result = equivalent(fsA, fsB);
297  return std::error_code();
298}
299
300static bool isReservedName(StringRef path) {
301  // This list of reserved names comes from MSDN, at:
302  // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
303  static const char *sReservedNames[] = { "nul", "con", "prn", "aux",
304                              "com1", "com2", "com3", "com4", "com5", "com6",
305                              "com7", "com8", "com9", "lpt1", "lpt2", "lpt3",
306                              "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9" };
307
308  // First, check to see if this is a device namespace, which always
309  // starts with \\.\, since device namespaces are not legal file paths.
310  if (path.startswith("\\\\.\\"))
311    return true;
312
313  // Then compare against the list of ancient reserved names
314  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
315    if (path.equals_lower(sReservedNames[i]))
316      return true;
317  }
318
319  // The path isn't what we consider reserved.
320  return false;
321}
322
323static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
324  if (FileHandle == INVALID_HANDLE_VALUE)
325    goto handle_status_error;
326
327  switch (::GetFileType(FileHandle)) {
328  default:
329    llvm_unreachable("Don't know anything about this file type");
330  case FILE_TYPE_UNKNOWN: {
331    DWORD Err = ::GetLastError();
332    if (Err != NO_ERROR)
333      return windows_error(Err);
334    Result = file_status(file_type::type_unknown);
335    return std::error_code();
336  }
337  case FILE_TYPE_DISK:
338    break;
339  case FILE_TYPE_CHAR:
340    Result = file_status(file_type::character_file);
341    return std::error_code();
342  case FILE_TYPE_PIPE:
343    Result = file_status(file_type::fifo_file);
344    return std::error_code();
345  }
346
347  BY_HANDLE_FILE_INFORMATION Info;
348  if (!::GetFileInformationByHandle(FileHandle, &Info))
349    goto handle_status_error;
350
351  {
352    file_type Type = (Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
353                         ? file_type::directory_file
354                         : file_type::regular_file;
355    Result =
356        file_status(Type, Info.ftLastWriteTime.dwHighDateTime,
357                    Info.ftLastWriteTime.dwLowDateTime,
358                    Info.dwVolumeSerialNumber, Info.nFileSizeHigh,
359                    Info.nFileSizeLow, Info.nFileIndexHigh, Info.nFileIndexLow);
360    return std::error_code();
361  }
362
363handle_status_error:
364  DWORD LastError = ::GetLastError();
365  if (LastError == ERROR_FILE_NOT_FOUND ||
366      LastError == ERROR_PATH_NOT_FOUND)
367    Result = file_status(file_type::file_not_found);
368  else if (LastError == ERROR_SHARING_VIOLATION)
369    Result = file_status(file_type::type_unknown);
370  else
371    Result = file_status(file_type::status_error);
372  return windows_error(LastError);
373}
374
375std::error_code status(const Twine &path, file_status &result) {
376  SmallString<128> path_storage;
377  SmallVector<wchar_t, 128> path_utf16;
378
379  StringRef path8 = path.toStringRef(path_storage);
380  if (isReservedName(path8)) {
381    result = file_status(file_type::character_file);
382    return std::error_code();
383  }
384
385  if (std::error_code ec = UTF8ToUTF16(path8, path_utf16))
386    return ec;
387
388  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
389  if (attr == INVALID_FILE_ATTRIBUTES)
390    return getStatus(INVALID_HANDLE_VALUE, result);
391
392  // Handle reparse points.
393  if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
394    ScopedFileHandle h(
395      ::CreateFileW(path_utf16.begin(),
396                    0, // Attributes only.
397                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
398                    NULL,
399                    OPEN_EXISTING,
400                    FILE_FLAG_BACKUP_SEMANTICS,
401                    0));
402    if (!h)
403      return getStatus(INVALID_HANDLE_VALUE, result);
404  }
405
406  ScopedFileHandle h(
407      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
408                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
409                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
410    if (!h)
411      return getStatus(INVALID_HANDLE_VALUE, result);
412
413    return getStatus(h, result);
414}
415
416std::error_code status(int FD, file_status &Result) {
417  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
418  return getStatus(FileHandle, Result);
419}
420
421std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
422  ULARGE_INTEGER UI;
423  UI.QuadPart = Time.toWin32Time();
424  FILETIME FT;
425  FT.dwLowDateTime = UI.LowPart;
426  FT.dwHighDateTime = UI.HighPart;
427  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
428  if (!SetFileTime(FileHandle, NULL, &FT, &FT))
429    return windows_error(::GetLastError());
430  return std::error_code();
431}
432
433std::error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
434  FileDescriptor = FD;
435  // Make sure that the requested size fits within SIZE_T.
436  if (Size > std::numeric_limits<SIZE_T>::max()) {
437    if (FileDescriptor) {
438      if (CloseFD)
439        _close(FileDescriptor);
440    } else
441      ::CloseHandle(FileHandle);
442    return make_error_code(errc::invalid_argument);
443  }
444
445  DWORD flprotect;
446  switch (Mode) {
447  case readonly:  flprotect = PAGE_READONLY; break;
448  case readwrite: flprotect = PAGE_READWRITE; break;
449  case priv:      flprotect = PAGE_WRITECOPY; break;
450  }
451
452  FileMappingHandle =
453      ::CreateFileMappingW(FileHandle, 0, flprotect,
454                           (Offset + Size) >> 32,
455                           (Offset + Size) & 0xffffffff,
456                           0);
457  if (FileMappingHandle == NULL) {
458    std::error_code ec = windows_error(GetLastError());
459    if (FileDescriptor) {
460      if (CloseFD)
461        _close(FileDescriptor);
462    } else
463      ::CloseHandle(FileHandle);
464    return ec;
465  }
466
467  DWORD dwDesiredAccess;
468  switch (Mode) {
469  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
470  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
471  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
472  }
473  Mapping = ::MapViewOfFile(FileMappingHandle,
474                            dwDesiredAccess,
475                            Offset >> 32,
476                            Offset & 0xffffffff,
477                            Size);
478  if (Mapping == NULL) {
479    std::error_code ec = windows_error(GetLastError());
480    ::CloseHandle(FileMappingHandle);
481    if (FileDescriptor) {
482      if (CloseFD)
483        _close(FileDescriptor);
484    } else
485      ::CloseHandle(FileHandle);
486    return ec;
487  }
488
489  if (Size == 0) {
490    MEMORY_BASIC_INFORMATION mbi;
491    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
492    if (Result == 0) {
493      std::error_code ec = windows_error(GetLastError());
494      ::UnmapViewOfFile(Mapping);
495      ::CloseHandle(FileMappingHandle);
496      if (FileDescriptor) {
497        if (CloseFD)
498          _close(FileDescriptor);
499      } else
500        ::CloseHandle(FileHandle);
501      return ec;
502    }
503    Size = mbi.RegionSize;
504  }
505
506  // Close all the handles except for the view. It will keep the other handles
507  // alive.
508  ::CloseHandle(FileMappingHandle);
509  if (FileDescriptor) {
510    if (CloseFD)
511      _close(FileDescriptor); // Also closes FileHandle.
512  } else
513    ::CloseHandle(FileHandle);
514  return std::error_code();
515}
516
517mapped_file_region::mapped_file_region(const Twine &path,
518                                       mapmode mode,
519                                       uint64_t length,
520                                       uint64_t offset,
521                                       std::error_code &ec)
522  : Mode(mode)
523  , Size(length)
524  , Mapping()
525  , FileDescriptor()
526  , FileHandle(INVALID_HANDLE_VALUE)
527  , FileMappingHandle() {
528  SmallString<128> path_storage;
529  SmallVector<wchar_t, 128> path_utf16;
530
531  // Convert path to UTF-16.
532  if ((ec = UTF8ToUTF16(path.toStringRef(path_storage), path_utf16)))
533    return;
534
535  // Get file handle for creating a file mapping.
536  FileHandle = ::CreateFileW(c_str(path_utf16),
537                             Mode == readonly ? GENERIC_READ
538                                              : GENERIC_READ | GENERIC_WRITE,
539                             Mode == readonly ? FILE_SHARE_READ
540                                              : 0,
541                             0,
542                             Mode == readonly ? OPEN_EXISTING
543                                              : OPEN_ALWAYS,
544                             Mode == readonly ? FILE_ATTRIBUTE_READONLY
545                                              : FILE_ATTRIBUTE_NORMAL,
546                             0);
547  if (FileHandle == INVALID_HANDLE_VALUE) {
548    ec = windows_error(::GetLastError());
549    return;
550  }
551
552  FileDescriptor = 0;
553  ec = init(FileDescriptor, true, offset);
554  if (ec) {
555    Mapping = FileMappingHandle = 0;
556    FileHandle = INVALID_HANDLE_VALUE;
557    FileDescriptor = 0;
558  }
559}
560
561mapped_file_region::mapped_file_region(int fd,
562                                       bool closefd,
563                                       mapmode mode,
564                                       uint64_t length,
565                                       uint64_t offset,
566                                       std::error_code &ec)
567  : Mode(mode)
568  , Size(length)
569  , Mapping()
570  , FileDescriptor(fd)
571  , FileHandle(INVALID_HANDLE_VALUE)
572  , FileMappingHandle() {
573  FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
574  if (FileHandle == INVALID_HANDLE_VALUE) {
575    if (closefd)
576      _close(FileDescriptor);
577    FileDescriptor = 0;
578    ec = make_error_code(errc::bad_file_descriptor);
579    return;
580  }
581
582  ec = init(FileDescriptor, closefd, offset);
583  if (ec) {
584    Mapping = FileMappingHandle = 0;
585    FileHandle = INVALID_HANDLE_VALUE;
586    FileDescriptor = 0;
587  }
588}
589
590mapped_file_region::~mapped_file_region() {
591  if (Mapping)
592    ::UnmapViewOfFile(Mapping);
593}
594
595mapped_file_region::mapped_file_region(mapped_file_region &&other)
596  : Mode(other.Mode)
597  , Size(other.Size)
598  , Mapping(other.Mapping)
599  , FileDescriptor(other.FileDescriptor)
600  , FileHandle(other.FileHandle)
601  , FileMappingHandle(other.FileMappingHandle) {
602  other.Mapping = other.FileMappingHandle = 0;
603  other.FileHandle = INVALID_HANDLE_VALUE;
604  other.FileDescriptor = 0;
605}
606
607mapped_file_region::mapmode mapped_file_region::flags() const {
608  assert(Mapping && "Mapping failed but used anyway!");
609  return Mode;
610}
611
612uint64_t mapped_file_region::size() const {
613  assert(Mapping && "Mapping failed but used anyway!");
614  return Size;
615}
616
617char *mapped_file_region::data() const {
618  assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
619  assert(Mapping && "Mapping failed but used anyway!");
620  return reinterpret_cast<char*>(Mapping);
621}
622
623const char *mapped_file_region::const_data() const {
624  assert(Mapping && "Mapping failed but used anyway!");
625  return reinterpret_cast<const char*>(Mapping);
626}
627
628int mapped_file_region::alignment() {
629  SYSTEM_INFO SysInfo;
630  ::GetSystemInfo(&SysInfo);
631  return SysInfo.dwAllocationGranularity;
632}
633
634std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
635                                                StringRef path){
636  SmallVector<wchar_t, 128> path_utf16;
637
638  if (std::error_code ec = UTF8ToUTF16(path, path_utf16))
639    return ec;
640
641  // Convert path to the format that Windows is happy with.
642  if (path_utf16.size() > 0 &&
643      !is_separator(path_utf16[path.size() - 1]) &&
644      path_utf16[path.size() - 1] != L':') {
645    path_utf16.push_back(L'\\');
646    path_utf16.push_back(L'*');
647  } else {
648    path_utf16.push_back(L'*');
649  }
650
651  //  Get the first directory entry.
652  WIN32_FIND_DATAW FirstFind;
653  ScopedFindHandle FindHandle(::FindFirstFileW(c_str(path_utf16), &FirstFind));
654  if (!FindHandle)
655    return windows_error(::GetLastError());
656
657  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
658  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
659         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
660                              FirstFind.cFileName[1] == L'.'))
661    if (!::FindNextFileW(FindHandle, &FirstFind)) {
662      DWORD LastError = ::GetLastError();
663      // Check for end.
664      if (LastError == ERROR_NO_MORE_FILES)
665        return detail::directory_iterator_destruct(it);
666      return windows_error(LastError);
667    } else
668      FilenameLen = ::wcslen(FirstFind.cFileName);
669
670  // Construct the current directory entry.
671  SmallString<128> directory_entry_name_utf8;
672  if (std::error_code ec =
673          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
674                      directory_entry_name_utf8))
675    return ec;
676
677  it.IterationHandle = intptr_t(FindHandle.take());
678  SmallString<128> directory_entry_path(path);
679  path::append(directory_entry_path, directory_entry_name_utf8.str());
680  it.CurrentEntry = directory_entry(directory_entry_path.str());
681
682  return std::error_code();
683}
684
685std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
686  if (it.IterationHandle != 0)
687    // Closes the handle if it's valid.
688    ScopedFindHandle close(HANDLE(it.IterationHandle));
689  it.IterationHandle = 0;
690  it.CurrentEntry = directory_entry();
691  return std::error_code();
692}
693
694std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
695  WIN32_FIND_DATAW FindData;
696  if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
697    DWORD LastError = ::GetLastError();
698    // Check for end.
699    if (LastError == ERROR_NO_MORE_FILES)
700      return detail::directory_iterator_destruct(it);
701    return windows_error(LastError);
702  }
703
704  size_t FilenameLen = ::wcslen(FindData.cFileName);
705  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
706      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
707                           FindData.cFileName[1] == L'.'))
708    return directory_iterator_increment(it);
709
710  SmallString<128> directory_entry_path_utf8;
711  if (std::error_code ec =
712          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
713                      directory_entry_path_utf8))
714    return ec;
715
716  it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8));
717  return std::error_code();
718}
719
720std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
721  SmallString<128> PathStorage;
722  SmallVector<wchar_t, 128> PathUTF16;
723
724  if (std::error_code EC =
725          UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
726    return EC;
727
728  HANDLE H = ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
729                           FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
730                           OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
731  if (H == INVALID_HANDLE_VALUE) {
732    DWORD LastError = ::GetLastError();
733    std::error_code EC = windows_error(LastError);
734    // Provide a better error message when trying to open directories.
735    // This only runs if we failed to open the file, so there is probably
736    // no performances issues.
737    if (LastError != ERROR_ACCESS_DENIED)
738      return EC;
739    if (is_directory(Name))
740      return make_error_code(errc::is_a_directory);
741    return EC;
742  }
743
744  int FD = ::_open_osfhandle(intptr_t(H), 0);
745  if (FD == -1) {
746    ::CloseHandle(H);
747    return windows_error(ERROR_INVALID_HANDLE);
748  }
749
750  ResultFD = FD;
751  return std::error_code();
752}
753
754std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
755                            sys::fs::OpenFlags Flags, unsigned Mode) {
756  // Verify that we don't have both "append" and "excl".
757  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
758         "Cannot specify both 'excl' and 'append' file creation flags!");
759
760  SmallString<128> PathStorage;
761  SmallVector<wchar_t, 128> PathUTF16;
762
763  if (std::error_code EC =
764          UTF8ToUTF16(Name.toStringRef(PathStorage), PathUTF16))
765    return EC;
766
767  DWORD CreationDisposition;
768  if (Flags & F_Excl)
769    CreationDisposition = CREATE_NEW;
770  else if (Flags & F_Append)
771    CreationDisposition = OPEN_ALWAYS;
772  else
773    CreationDisposition = CREATE_ALWAYS;
774
775  DWORD Access = GENERIC_WRITE;
776  if (Flags & F_RW)
777    Access |= GENERIC_READ;
778
779  HANDLE H = ::CreateFileW(PathUTF16.begin(), Access,
780                           FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
781                           CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
782
783  if (H == INVALID_HANDLE_VALUE) {
784    DWORD LastError = ::GetLastError();
785    std::error_code EC = windows_error(LastError);
786    // Provide a better error message when trying to open directories.
787    // This only runs if we failed to open the file, so there is probably
788    // no performances issues.
789    if (LastError != ERROR_ACCESS_DENIED)
790      return EC;
791    if (is_directory(Name))
792      return make_error_code(errc::is_a_directory);
793    return EC;
794  }
795
796  int OpenFlags = 0;
797  if (Flags & F_Append)
798    OpenFlags |= _O_APPEND;
799
800  if (Flags & F_Text)
801    OpenFlags |= _O_TEXT;
802
803  int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
804  if (FD == -1) {
805    ::CloseHandle(H);
806    return windows_error(ERROR_INVALID_HANDLE);
807  }
808
809  ResultFD = FD;
810  return std::error_code();
811}
812} // end namespace fs
813
814namespace path {
815
816bool home_directory(SmallVectorImpl<char> &result) {
817  wchar_t Path[MAX_PATH];
818  if (::SHGetFolderPathW(0, CSIDL_APPDATA | CSIDL_FLAG_CREATE, 0,
819                         /*SHGFP_TYPE_CURRENT*/0, Path) != S_OK)
820    return false;
821
822  if (UTF16ToUTF8(Path, ::wcslen(Path), result))
823    return false;
824
825  return true;
826}
827
828static bool getTempDirEnvVar(const char *Var, SmallVectorImpl<char> &Res) {
829  SmallVector<wchar_t, 128> NameUTF16;
830  if (windows::UTF8ToUTF16(Var, NameUTF16))
831    return false;
832
833  SmallVector<wchar_t, 1024> Buf;
834  size_t Size = 1024;
835  do {
836    Buf.reserve(Size);
837    Size =
838        GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
839    if (Size == 0)
840      return false;
841
842    // Try again with larger buffer.
843  } while (Size > Buf.capacity());
844  Buf.set_size(Size);
845
846  if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
847    return false;
848  return true;
849}
850
851static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
852  const char *EnvironmentVariables[] = {"TMP", "TEMP", "USERPROFILE"};
853  for (const char *Env : EnvironmentVariables) {
854    if (getTempDirEnvVar(Env, Res))
855      return true;
856  }
857  return false;
858}
859
860void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
861  (void)ErasedOnReboot;
862  Result.clear();
863
864  // Check whether the temporary directory is specified by an environment
865  // variable.
866  if (getTempDirEnvVar(Result))
867    return;
868
869  // Fall back to a system default.
870  const char *DefaultResult = "C:\\TEMP";
871  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
872}
873} // end namespace path
874
875namespace windows {
876std::error_code UTF8ToUTF16(llvm::StringRef utf8,
877                            llvm::SmallVectorImpl<wchar_t> &utf16) {
878  if (!utf8.empty()) {
879    int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
880                                    utf8.size(), utf16.begin(), 0);
881
882    if (len == 0)
883      return windows_error(::GetLastError());
884
885    utf16.reserve(len + 1);
886    utf16.set_size(len);
887
888    len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
889                                utf8.size(), utf16.begin(), utf16.size());
890
891    if (len == 0)
892      return windows_error(::GetLastError());
893  }
894
895  // Make utf16 null terminated.
896  utf16.push_back(0);
897  utf16.pop_back();
898
899  return std::error_code();
900}
901
902static
903std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
904                                size_t utf16_len,
905                                llvm::SmallVectorImpl<char> &utf8) {
906  if (utf16_len) {
907    // Get length.
908    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
909                                    0, NULL, NULL);
910
911    if (len == 0)
912      return windows_error(::GetLastError());
913
914    utf8.reserve(len);
915    utf8.set_size(len);
916
917    // Now do the actual conversion.
918    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
919                                utf8.size(), NULL, NULL);
920
921    if (len == 0)
922      return windows_error(::GetLastError());
923  }
924
925  // Make utf8 null terminated.
926  utf8.push_back(0);
927  utf8.pop_back();
928
929  return std::error_code();
930}
931
932std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
933                            llvm::SmallVectorImpl<char> &utf8) {
934  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
935}
936
937std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
938                             llvm::SmallVectorImpl<char> &utf8) {
939  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
940}
941} // end namespace windows
942} // end namespace sys
943} // end namespace llvm
944