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<> basic_file_status::getLastAccessedTime() const {
172  FILETIME Time;
173  Time.dwLowDateTime = LastAccessedTimeLow;
174  Time.dwHighDateTime = LastAccessedTimeHigh;
175  return toTimePoint(Time);
176}
177
178TimePoint<> basic_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  if (std::error_code ec = widenPath(path, path_utf16))
263    return ec;
264
265  // We don't know whether this is a file or a directory, and remove() can
266  // accept both. The usual way to delete a file or directory is to use one of
267  // the DeleteFile or RemoveDirectory functions, but that requires you to know
268  // which one it is. We could stat() the file to determine that, but that would
269  // cost us additional system calls, which can be slow in a directory
270  // containing a large number of files. So instead we call CreateFile directly.
271  // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
272  // file to be deleted once it is closed. We also use the flags
273  // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
274  // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
275  ScopedFileHandle h(::CreateFileW(
276      c_str(path_utf16), DELETE,
277      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
278      OPEN_EXISTING,
279      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
280          FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
281      NULL));
282  if (!h) {
283    std::error_code EC = mapWindowsError(::GetLastError());
284    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
285      return EC;
286  }
287
288  return std::error_code();
289}
290
291static std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
292                                         bool &Result) {
293  SmallVector<wchar_t, 128> VolumePath;
294  size_t Len = 128;
295  while (true) {
296    VolumePath.resize(Len);
297    BOOL Success =
298        ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
299
300    if (Success)
301      break;
302
303    DWORD Err = ::GetLastError();
304    if (Err != ERROR_INSUFFICIENT_BUFFER)
305      return mapWindowsError(Err);
306
307    Len *= 2;
308  }
309  // If the output buffer has exactly enough space for the path name, but not
310  // the null terminator, it will leave the output unterminated.  Push a null
311  // terminator onto the end to ensure that this never happens.
312  VolumePath.push_back(L'\0');
313  VolumePath.set_size(wcslen(VolumePath.data()));
314  const wchar_t *P = VolumePath.data();
315
316  UINT Type = ::GetDriveTypeW(P);
317  switch (Type) {
318  case DRIVE_FIXED:
319    Result = true;
320    return std::error_code();
321  case DRIVE_REMOTE:
322  case DRIVE_CDROM:
323  case DRIVE_RAMDISK:
324  case DRIVE_REMOVABLE:
325    Result = false;
326    return std::error_code();
327  default:
328    return make_error_code(errc::no_such_file_or_directory);
329  }
330  llvm_unreachable("Unreachable!");
331}
332
333std::error_code is_local(const Twine &path, bool &result) {
334  if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
335    return make_error_code(errc::no_such_file_or_directory);
336
337  SmallString<128> Storage;
338  StringRef P = path.toStringRef(Storage);
339
340  // Convert to utf-16.
341  SmallVector<wchar_t, 128> WidePath;
342  if (std::error_code ec = widenPath(P, WidePath))
343    return ec;
344  return is_local_internal(WidePath, result);
345}
346
347std::error_code is_local(int FD, bool &Result) {
348  SmallVector<wchar_t, 128> FinalPath;
349  HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
350
351  size_t Len = 128;
352  do {
353    FinalPath.reserve(Len);
354    Len = ::GetFinalPathNameByHandleW(Handle, FinalPath.data(),
355                                      FinalPath.capacity() - 1, VOLUME_NAME_NT);
356    if (Len == 0)
357      return mapWindowsError(::GetLastError());
358  } while (Len > FinalPath.capacity());
359
360  FinalPath.set_size(Len);
361
362  return is_local_internal(FinalPath, Result);
363}
364
365static std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
366                                       bool ReplaceIfExists) {
367  SmallVector<wchar_t, 0> ToWide;
368  if (auto EC = widenPath(To, ToWide))
369    return EC;
370
371  std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
372                                  (ToWide.size() * sizeof(wchar_t)));
373  FILE_RENAME_INFO &RenameInfo =
374      *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
375  RenameInfo.ReplaceIfExists = ReplaceIfExists;
376  RenameInfo.RootDirectory = 0;
377  RenameInfo.FileNameLength = ToWide.size();
378  std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
379
380  SetLastError(ERROR_SUCCESS);
381  if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
382                                  RenameInfoBuf.size())) {
383    unsigned Error = GetLastError();
384    if (Error == ERROR_SUCCESS)
385      Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
386    return mapWindowsError(Error);
387  }
388
389  return std::error_code();
390}
391
392std::error_code rename(const Twine &From, const Twine &To) {
393  // Convert to utf-16.
394  SmallVector<wchar_t, 128> WideFrom;
395  SmallVector<wchar_t, 128> WideTo;
396  if (std::error_code EC = widenPath(From, WideFrom))
397    return EC;
398  if (std::error_code EC = widenPath(To, WideTo))
399    return EC;
400
401  ScopedFileHandle FromHandle;
402  // Retry this a few times to defeat badly behaved file system scanners.
403  for (unsigned Retry = 0; Retry != 200; ++Retry) {
404    if (Retry != 0)
405      ::Sleep(10);
406    FromHandle =
407        ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
408                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
409                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
410    if (FromHandle)
411      break;
412  }
413  if (!FromHandle)
414    return mapWindowsError(GetLastError());
415
416  // We normally expect this loop to succeed after a few iterations. If it
417  // requires more than 200 tries, it's more likely that the failures are due to
418  // a true error, so stop trying.
419  for (unsigned Retry = 0; Retry != 200; ++Retry) {
420    auto EC = rename_internal(FromHandle, To, true);
421
422    if (EC ==
423        std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
424      // Wine doesn't support SetFileInformationByHandle in rename_internal.
425      // Fall back to MoveFileEx.
426      if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
427                        MOVEFILE_REPLACE_EXISTING))
428        return std::error_code();
429      return mapWindowsError(GetLastError());
430    }
431
432    if (!EC || EC != errc::permission_denied)
433      return EC;
434
435    // The destination file probably exists and is currently open in another
436    // process, either because the file was opened without FILE_SHARE_DELETE or
437    // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
438    // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
439    // to arrange for the destination file to be deleted when the other process
440    // closes it.
441    ScopedFileHandle ToHandle(
442        ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
443                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
444                      NULL, OPEN_EXISTING,
445                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
446    if (!ToHandle) {
447      auto EC = mapWindowsError(GetLastError());
448      // Another process might have raced with us and moved the existing file
449      // out of the way before we had a chance to open it. If that happens, try
450      // to rename the source file again.
451      if (EC == errc::no_such_file_or_directory)
452        continue;
453      return EC;
454    }
455
456    BY_HANDLE_FILE_INFORMATION FI;
457    if (!GetFileInformationByHandle(ToHandle, &FI))
458      return mapWindowsError(GetLastError());
459
460    // Try to find a unique new name for the destination file.
461    for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
462      std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
463      if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
464        if (EC == errc::file_exists || EC == errc::permission_denied) {
465          // Again, another process might have raced with us and moved the file
466          // before we could move it. Check whether this is the case, as it
467          // might have caused the permission denied error. If that was the
468          // case, we don't need to move it ourselves.
469          ScopedFileHandle ToHandle2(::CreateFileW(
470              WideTo.begin(), 0,
471              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
472              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
473          if (!ToHandle2) {
474            auto EC = mapWindowsError(GetLastError());
475            if (EC == errc::no_such_file_or_directory)
476              break;
477            return EC;
478          }
479          BY_HANDLE_FILE_INFORMATION FI2;
480          if (!GetFileInformationByHandle(ToHandle2, &FI2))
481            return mapWindowsError(GetLastError());
482          if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
483              FI.nFileIndexLow != FI2.nFileIndexLow ||
484              FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
485            break;
486          continue;
487        }
488        return EC;
489      }
490      break;
491    }
492
493    // Okay, the old destination file has probably been moved out of the way at
494    // this point, so try to rename the source file again. Still, another
495    // process might have raced with us to create and open the destination
496    // file, so we need to keep doing this until we succeed.
497  }
498
499  // The most likely root cause.
500  return errc::permission_denied;
501}
502
503std::error_code resize_file(int FD, uint64_t Size) {
504#ifdef HAVE__CHSIZE_S
505  errno_t error = ::_chsize_s(FD, Size);
506#else
507  errno_t error = ::_chsize(FD, Size);
508#endif
509  return std::error_code(error, std::generic_category());
510}
511
512std::error_code access(const Twine &Path, AccessMode Mode) {
513  SmallVector<wchar_t, 128> PathUtf16;
514
515  if (std::error_code EC = widenPath(Path, PathUtf16))
516    return EC;
517
518  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
519
520  if (Attributes == INVALID_FILE_ATTRIBUTES) {
521    // See if the file didn't actually exist.
522    DWORD LastError = ::GetLastError();
523    if (LastError != ERROR_FILE_NOT_FOUND &&
524        LastError != ERROR_PATH_NOT_FOUND)
525      return mapWindowsError(LastError);
526    return errc::no_such_file_or_directory;
527  }
528
529  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
530    return errc::permission_denied;
531
532  return std::error_code();
533}
534
535bool can_execute(const Twine &Path) {
536  return !access(Path, AccessMode::Execute) ||
537         !access(Path + ".exe", AccessMode::Execute);
538}
539
540bool equivalent(file_status A, file_status B) {
541  assert(status_known(A) && status_known(B));
542  return A.FileIndexHigh         == B.FileIndexHigh &&
543         A.FileIndexLow          == B.FileIndexLow &&
544         A.FileSizeHigh          == B.FileSizeHigh &&
545         A.FileSizeLow           == B.FileSizeLow &&
546         A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
547         A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
548         A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
549         A.LastWriteTimeLow      == B.LastWriteTimeLow &&
550         A.VolumeSerialNumber    == B.VolumeSerialNumber;
551}
552
553std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
554  file_status fsA, fsB;
555  if (std::error_code ec = status(A, fsA))
556    return ec;
557  if (std::error_code ec = status(B, fsB))
558    return ec;
559  result = equivalent(fsA, fsB);
560  return std::error_code();
561}
562
563static bool isReservedName(StringRef path) {
564  // This list of reserved names comes from MSDN, at:
565  // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
566  static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
567                                                "com1", "com2", "com3", "com4",
568                                                "com5", "com6", "com7", "com8",
569                                                "com9", "lpt1", "lpt2", "lpt3",
570                                                "lpt4", "lpt5", "lpt6", "lpt7",
571                                                "lpt8", "lpt9" };
572
573  // First, check to see if this is a device namespace, which always
574  // starts with \\.\, since device namespaces are not legal file paths.
575  if (path.startswith("\\\\.\\"))
576    return true;
577
578  // Then compare against the list of ancient reserved names.
579  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
580    if (path.equals_lower(sReservedNames[i]))
581      return true;
582  }
583
584  // The path isn't what we consider reserved.
585  return false;
586}
587
588static file_type file_type_from_attrs(DWORD Attrs) {
589  return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
590                                            : file_type::regular_file;
591}
592
593static perms perms_from_attrs(DWORD Attrs) {
594  return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
595}
596
597static std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
598  if (FileHandle == INVALID_HANDLE_VALUE)
599    goto handle_status_error;
600
601  switch (::GetFileType(FileHandle)) {
602  default:
603    llvm_unreachable("Don't know anything about this file type");
604  case FILE_TYPE_UNKNOWN: {
605    DWORD Err = ::GetLastError();
606    if (Err != NO_ERROR)
607      return mapWindowsError(Err);
608    Result = file_status(file_type::type_unknown);
609    return std::error_code();
610  }
611  case FILE_TYPE_DISK:
612    break;
613  case FILE_TYPE_CHAR:
614    Result = file_status(file_type::character_file);
615    return std::error_code();
616  case FILE_TYPE_PIPE:
617    Result = file_status(file_type::fifo_file);
618    return std::error_code();
619  }
620
621  BY_HANDLE_FILE_INFORMATION Info;
622  if (!::GetFileInformationByHandle(FileHandle, &Info))
623    goto handle_status_error;
624
625  Result = file_status(
626      file_type_from_attrs(Info.dwFileAttributes),
627      perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
628      Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
629      Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
630      Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
631      Info.nFileIndexHigh, Info.nFileIndexLow);
632  return std::error_code();
633
634handle_status_error:
635  DWORD LastError = ::GetLastError();
636  if (LastError == ERROR_FILE_NOT_FOUND ||
637      LastError == ERROR_PATH_NOT_FOUND)
638    Result = file_status(file_type::file_not_found);
639  else if (LastError == ERROR_SHARING_VIOLATION)
640    Result = file_status(file_type::type_unknown);
641  else
642    Result = file_status(file_type::status_error);
643  return mapWindowsError(LastError);
644}
645
646std::error_code status(const Twine &path, file_status &result, bool Follow) {
647  SmallString<128> path_storage;
648  SmallVector<wchar_t, 128> path_utf16;
649
650  StringRef path8 = path.toStringRef(path_storage);
651  if (isReservedName(path8)) {
652    result = file_status(file_type::character_file);
653    return std::error_code();
654  }
655
656  if (std::error_code ec = widenPath(path8, path_utf16))
657    return ec;
658
659  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
660  if (attr == INVALID_FILE_ATTRIBUTES)
661    return getStatus(INVALID_HANDLE_VALUE, result);
662
663  DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
664  // Handle reparse points.
665  if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
666    Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
667
668  ScopedFileHandle h(
669      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
670                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
671                    NULL, OPEN_EXISTING, Flags, 0));
672  if (!h)
673    return getStatus(INVALID_HANDLE_VALUE, result);
674
675  return getStatus(h, result);
676}
677
678std::error_code status(int FD, file_status &Result) {
679  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
680  return getStatus(FileHandle, Result);
681}
682
683std::error_code setPermissions(const Twine &Path, perms Permissions) {
684  SmallVector<wchar_t, 128> PathUTF16;
685  if (std::error_code EC = widenPath(Path, PathUTF16))
686    return EC;
687
688  DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
689  if (Attributes == INVALID_FILE_ATTRIBUTES)
690    return mapWindowsError(GetLastError());
691
692  // There are many Windows file attributes that are not to do with the file
693  // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
694  // them.
695  if (Permissions & all_write) {
696    Attributes &= ~FILE_ATTRIBUTE_READONLY;
697    if (Attributes == 0)
698      // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
699      Attributes |= FILE_ATTRIBUTE_NORMAL;
700  }
701  else {
702    Attributes |= FILE_ATTRIBUTE_READONLY;
703    // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
704    // remove it, if it is present.
705    Attributes &= ~FILE_ATTRIBUTE_NORMAL;
706  }
707
708  if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
709    return mapWindowsError(GetLastError());
710
711  return std::error_code();
712}
713
714std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
715  FILETIME FT = toFILETIME(Time);
716  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
717  if (!SetFileTime(FileHandle, NULL, &FT, &FT))
718    return mapWindowsError(::GetLastError());
719  return std::error_code();
720}
721
722std::error_code mapped_file_region::init(int FD, uint64_t Offset,
723                                         mapmode Mode) {
724  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
725  if (FileHandle == INVALID_HANDLE_VALUE)
726    return make_error_code(errc::bad_file_descriptor);
727
728  DWORD flprotect;
729  switch (Mode) {
730  case readonly:  flprotect = PAGE_READONLY; break;
731  case readwrite: flprotect = PAGE_READWRITE; break;
732  case priv:      flprotect = PAGE_WRITECOPY; break;
733  }
734
735  HANDLE FileMappingHandle =
736      ::CreateFileMappingW(FileHandle, 0, flprotect,
737                           (Offset + Size) >> 32,
738                           (Offset + Size) & 0xffffffff,
739                           0);
740  if (FileMappingHandle == NULL) {
741    std::error_code ec = mapWindowsError(GetLastError());
742    return ec;
743  }
744
745  DWORD dwDesiredAccess;
746  switch (Mode) {
747  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
748  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
749  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
750  }
751  Mapping = ::MapViewOfFile(FileMappingHandle,
752                            dwDesiredAccess,
753                            Offset >> 32,
754                            Offset & 0xffffffff,
755                            Size);
756  if (Mapping == NULL) {
757    std::error_code ec = mapWindowsError(GetLastError());
758    ::CloseHandle(FileMappingHandle);
759    return ec;
760  }
761
762  if (Size == 0) {
763    MEMORY_BASIC_INFORMATION mbi;
764    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
765    if (Result == 0) {
766      std::error_code ec = mapWindowsError(GetLastError());
767      ::UnmapViewOfFile(Mapping);
768      ::CloseHandle(FileMappingHandle);
769      return ec;
770    }
771    Size = mbi.RegionSize;
772  }
773
774  // Close all the handles except for the view. It will keep the other handles
775  // alive.
776  ::CloseHandle(FileMappingHandle);
777  return std::error_code();
778}
779
780mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
781                                       uint64_t offset, std::error_code &ec)
782    : Size(length), Mapping() {
783  ec = init(fd, offset, mode);
784  if (ec)
785    Mapping = 0;
786}
787
788mapped_file_region::~mapped_file_region() {
789  if (Mapping)
790    ::UnmapViewOfFile(Mapping);
791}
792
793size_t mapped_file_region::size() const {
794  assert(Mapping && "Mapping failed but used anyway!");
795  return Size;
796}
797
798char *mapped_file_region::data() const {
799  assert(Mapping && "Mapping failed but used anyway!");
800  return reinterpret_cast<char*>(Mapping);
801}
802
803const char *mapped_file_region::const_data() const {
804  assert(Mapping && "Mapping failed but used anyway!");
805  return reinterpret_cast<const char*>(Mapping);
806}
807
808int mapped_file_region::alignment() {
809  SYSTEM_INFO SysInfo;
810  ::GetSystemInfo(&SysInfo);
811  return SysInfo.dwAllocationGranularity;
812}
813
814static basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
815  return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
816                           perms_from_attrs(FindData->dwFileAttributes),
817                           FindData->ftLastAccessTime.dwHighDateTime,
818                           FindData->ftLastAccessTime.dwLowDateTime,
819                           FindData->ftLastWriteTime.dwHighDateTime,
820                           FindData->ftLastWriteTime.dwLowDateTime,
821                           FindData->nFileSizeHigh, FindData->nFileSizeLow);
822}
823
824std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
825                                                     StringRef path,
826                                                     bool follow_symlinks) {
827  SmallVector<wchar_t, 128> path_utf16;
828
829  if (std::error_code ec = widenPath(path, path_utf16))
830    return ec;
831
832  // Convert path to the format that Windows is happy with.
833  if (path_utf16.size() > 0 &&
834      !is_separator(path_utf16[path.size() - 1]) &&
835      path_utf16[path.size() - 1] != L':') {
836    path_utf16.push_back(L'\\');
837    path_utf16.push_back(L'*');
838  } else {
839    path_utf16.push_back(L'*');
840  }
841
842  //  Get the first directory entry.
843  WIN32_FIND_DATAW FirstFind;
844  ScopedFindHandle FindHandle(::FindFirstFileExW(
845      c_str(path_utf16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
846      NULL, FIND_FIRST_EX_LARGE_FETCH));
847  if (!FindHandle)
848    return mapWindowsError(::GetLastError());
849
850  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
851  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
852         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
853                              FirstFind.cFileName[1] == L'.'))
854    if (!::FindNextFileW(FindHandle, &FirstFind)) {
855      DWORD LastError = ::GetLastError();
856      // Check for end.
857      if (LastError == ERROR_NO_MORE_FILES)
858        return detail::directory_iterator_destruct(it);
859      return mapWindowsError(LastError);
860    } else
861      FilenameLen = ::wcslen(FirstFind.cFileName);
862
863  // Construct the current directory entry.
864  SmallString<128> directory_entry_name_utf8;
865  if (std::error_code ec =
866          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
867                      directory_entry_name_utf8))
868    return ec;
869
870  it.IterationHandle = intptr_t(FindHandle.take());
871  SmallString<128> directory_entry_path(path);
872  path::append(directory_entry_path, directory_entry_name_utf8);
873  it.CurrentEntry = directory_entry(directory_entry_path, follow_symlinks,
874                                    status_from_find_data(&FirstFind));
875
876  return std::error_code();
877}
878
879std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
880  if (it.IterationHandle != 0)
881    // Closes the handle if it's valid.
882    ScopedFindHandle close(HANDLE(it.IterationHandle));
883  it.IterationHandle = 0;
884  it.CurrentEntry = directory_entry();
885  return std::error_code();
886}
887
888std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
889  WIN32_FIND_DATAW FindData;
890  if (!::FindNextFileW(HANDLE(it.IterationHandle), &FindData)) {
891    DWORD LastError = ::GetLastError();
892    // Check for end.
893    if (LastError == ERROR_NO_MORE_FILES)
894      return detail::directory_iterator_destruct(it);
895    return mapWindowsError(LastError);
896  }
897
898  size_t FilenameLen = ::wcslen(FindData.cFileName);
899  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
900      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
901                           FindData.cFileName[1] == L'.'))
902    return directory_iterator_increment(it);
903
904  SmallString<128> directory_entry_path_utf8;
905  if (std::error_code ec =
906          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
907                      directory_entry_path_utf8))
908    return ec;
909
910  it.CurrentEntry.replace_filename(Twine(directory_entry_path_utf8),
911                                   status_from_find_data(&FindData));
912  return std::error_code();
913}
914
915ErrorOr<basic_file_status> directory_entry::status() const {
916  return Status;
917}
918
919static std::error_code realPathFromHandle(HANDLE H,
920                                          SmallVectorImpl<char> &RealPath) {
921  RealPath.clear();
922  llvm::SmallVector<wchar_t, MAX_PATH> Buffer;
923  DWORD CountChars = ::GetFinalPathNameByHandleW(
924      H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
925  if (CountChars > Buffer.capacity()) {
926    // The buffer wasn't big enough, try again.  In this case the return value
927    // *does* indicate the size of the null terminator.
928    Buffer.reserve(CountChars);
929    CountChars = ::GetFinalPathNameByHandleW(
930        H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
931  }
932  if (CountChars == 0)
933    return mapWindowsError(GetLastError());
934
935  const wchar_t *Data = Buffer.data();
936  if (CountChars >= 4) {
937    if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
938      CountChars -= 4;
939      Data += 4;
940    }
941  }
942
943  // Convert the result from UTF-16 to UTF-8.
944  return UTF16ToUTF8(Data, CountChars, RealPath);
945}
946
947static std::error_code directoryRealPath(const Twine &Name,
948                                         SmallVectorImpl<char> &RealPath) {
949  SmallVector<wchar_t, 128> PathUTF16;
950
951  if (std::error_code EC = widenPath(Name, PathUTF16))
952    return EC;
953
954  HANDLE H =
955      ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
956                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
957                    NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
958  if (H == INVALID_HANDLE_VALUE)
959    return mapWindowsError(GetLastError());
960  std::error_code EC = realPathFromHandle(H, RealPath);
961  ::CloseHandle(H);
962  return EC;
963}
964
965std::error_code openFileForRead(const Twine &Name, int &ResultFD,
966                                SmallVectorImpl<char> *RealPath) {
967  SmallVector<wchar_t, 128> PathUTF16;
968
969  if (std::error_code EC = widenPath(Name, PathUTF16))
970    return EC;
971
972  HANDLE H =
973      ::CreateFileW(PathUTF16.begin(), GENERIC_READ,
974                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
975                    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
976  if (H == INVALID_HANDLE_VALUE) {
977    DWORD LastError = ::GetLastError();
978    std::error_code EC = mapWindowsError(LastError);
979    // Provide a better error message when trying to open directories.
980    // This only runs if we failed to open the file, so there is probably
981    // no performances issues.
982    if (LastError != ERROR_ACCESS_DENIED)
983      return EC;
984    if (is_directory(Name))
985      return make_error_code(errc::is_a_directory);
986    return EC;
987  }
988
989  int FD = ::_open_osfhandle(intptr_t(H), 0);
990  if (FD == -1) {
991    ::CloseHandle(H);
992    return mapWindowsError(ERROR_INVALID_HANDLE);
993  }
994
995  // Fetch the real name of the file, if the user asked
996  if (RealPath)
997    realPathFromHandle(H, *RealPath);
998
999  ResultFD = FD;
1000  return std::error_code();
1001}
1002
1003std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
1004                            sys::fs::OpenFlags Flags, unsigned Mode) {
1005  // Verify that we don't have both "append" and "excl".
1006  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
1007         "Cannot specify both 'excl' and 'append' file creation flags!");
1008
1009  SmallVector<wchar_t, 128> PathUTF16;
1010
1011  if (std::error_code EC = widenPath(Name, PathUTF16))
1012    return EC;
1013
1014  DWORD CreationDisposition;
1015  if (Flags & F_Excl)
1016    CreationDisposition = CREATE_NEW;
1017  else if (Flags & F_Append)
1018    CreationDisposition = OPEN_ALWAYS;
1019  else
1020    CreationDisposition = CREATE_ALWAYS;
1021
1022  DWORD Access = GENERIC_WRITE;
1023  if (Flags & F_RW)
1024    Access |= GENERIC_READ;
1025
1026  HANDLE H =
1027      ::CreateFileW(PathUTF16.begin(), Access,
1028                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1029                    NULL, CreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1030
1031  if (H == INVALID_HANDLE_VALUE) {
1032    DWORD LastError = ::GetLastError();
1033    std::error_code EC = mapWindowsError(LastError);
1034    // Provide a better error message when trying to open directories.
1035    // This only runs if we failed to open the file, so there is probably
1036    // no performances issues.
1037    if (LastError != ERROR_ACCESS_DENIED)
1038      return EC;
1039    if (is_directory(Name))
1040      return make_error_code(errc::is_a_directory);
1041    return EC;
1042  }
1043
1044  int OpenFlags = 0;
1045  if (Flags & F_Append)
1046    OpenFlags |= _O_APPEND;
1047
1048  if (Flags & F_Text)
1049    OpenFlags |= _O_TEXT;
1050
1051  int FD = ::_open_osfhandle(intptr_t(H), OpenFlags);
1052  if (FD == -1) {
1053    ::CloseHandle(H);
1054    return mapWindowsError(ERROR_INVALID_HANDLE);
1055  }
1056
1057  ResultFD = FD;
1058  return std::error_code();
1059}
1060
1061std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1062  // Convert to utf-16.
1063  SmallVector<wchar_t, 128> Path16;
1064  std::error_code EC = widenPath(path, Path16);
1065  if (EC && !IgnoreErrors)
1066    return EC;
1067
1068  // SHFileOperation() accepts a list of paths, and so must be double null-
1069  // terminated to indicate the end of the list.  The buffer is already null
1070  // terminated, but since that null character is not considered part of the
1071  // vector's size, pushing another one will just consume that byte.  So we
1072  // need to push 2 null terminators.
1073  Path16.push_back(0);
1074  Path16.push_back(0);
1075
1076  SHFILEOPSTRUCTW shfos = {};
1077  shfos.wFunc = FO_DELETE;
1078  shfos.pFrom = Path16.data();
1079  shfos.fFlags = FOF_NO_UI;
1080
1081  int result = ::SHFileOperationW(&shfos);
1082  if (result != 0 && !IgnoreErrors)
1083    return mapWindowsError(result);
1084  return std::error_code();
1085}
1086
1087static void expandTildeExpr(SmallVectorImpl<char> &Path) {
1088  // Path does not begin with a tilde expression.
1089  if (Path.empty() || Path[0] != '~')
1090    return;
1091
1092  StringRef PathStr(Path.begin(), Path.size());
1093  PathStr = PathStr.drop_front();
1094  StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1095
1096  if (!Expr.empty()) {
1097    // This is probably a ~username/ expression.  Don't support this on Windows.
1098    return;
1099  }
1100
1101  SmallString<128> HomeDir;
1102  if (!path::home_directory(HomeDir)) {
1103    // For some reason we couldn't get the home directory.  Just exit.
1104    return;
1105  }
1106
1107  // Overwrite the first character and insert the rest.
1108  Path[0] = HomeDir[0];
1109  Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1110}
1111
1112std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1113                          bool expand_tilde) {
1114  dest.clear();
1115  if (path.isTriviallyEmpty())
1116    return std::error_code();
1117
1118  if (expand_tilde) {
1119    SmallString<128> Storage;
1120    path.toVector(Storage);
1121    expandTildeExpr(Storage);
1122    return real_path(Storage, dest, false);
1123  }
1124
1125  if (is_directory(path))
1126    return directoryRealPath(path, dest);
1127
1128  int fd;
1129  if (std::error_code EC = llvm::sys::fs::openFileForRead(path, fd, &dest))
1130    return EC;
1131  ::close(fd);
1132  return std::error_code();
1133}
1134
1135} // end namespace fs
1136
1137namespace path {
1138static bool getKnownFolderPath(KNOWNFOLDERID folderId,
1139                               SmallVectorImpl<char> &result) {
1140  wchar_t *path = nullptr;
1141  if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1142    return false;
1143
1144  bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1145  ::CoTaskMemFree(path);
1146  return ok;
1147}
1148
1149bool getUserCacheDir(SmallVectorImpl<char> &Result) {
1150  return getKnownFolderPath(FOLDERID_LocalAppData, Result);
1151}
1152
1153bool home_directory(SmallVectorImpl<char> &result) {
1154  return getKnownFolderPath(FOLDERID_Profile, result);
1155}
1156
1157static bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1158  SmallVector<wchar_t, 1024> Buf;
1159  size_t Size = 1024;
1160  do {
1161    Buf.reserve(Size);
1162    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1163    if (Size == 0)
1164      return false;
1165
1166    // Try again with larger buffer.
1167  } while (Size > Buf.capacity());
1168  Buf.set_size(Size);
1169
1170  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1171}
1172
1173static bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1174  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1175  for (auto *Env : EnvironmentVariables) {
1176    if (getTempDirEnvVar(Env, Res))
1177      return true;
1178  }
1179  return false;
1180}
1181
1182void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1183  (void)ErasedOnReboot;
1184  Result.clear();
1185
1186  // Check whether the temporary directory is specified by an environment var.
1187  // This matches GetTempPath logic to some degree. GetTempPath is not used
1188  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1189  // (fixed on Windows 8).
1190  if (getTempDirEnvVar(Result)) {
1191    assert(!Result.empty() && "Unexpected empty path");
1192    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1193    fs::make_absolute(Result); // Make it absolute if not already.
1194    return;
1195  }
1196
1197  // Fall back to a system default.
1198  const char *DefaultResult = "C:\\Temp";
1199  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1200}
1201} // end namespace path
1202
1203namespace windows {
1204std::error_code UTF8ToUTF16(llvm::StringRef utf8,
1205                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1206  if (!utf8.empty()) {
1207    int len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1208                                    utf8.size(), utf16.begin(), 0);
1209
1210    if (len == 0)
1211      return mapWindowsError(::GetLastError());
1212
1213    utf16.reserve(len + 1);
1214    utf16.set_size(len);
1215
1216    len = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.begin(),
1217                                utf8.size(), utf16.begin(), utf16.size());
1218
1219    if (len == 0)
1220      return mapWindowsError(::GetLastError());
1221  }
1222
1223  // Make utf16 null terminated.
1224  utf16.push_back(0);
1225  utf16.pop_back();
1226
1227  return std::error_code();
1228}
1229
1230static
1231std::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1232                                size_t utf16_len,
1233                                llvm::SmallVectorImpl<char> &utf8) {
1234  if (utf16_len) {
1235    // Get length.
1236    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.begin(),
1237                                    0, NULL, NULL);
1238
1239    if (len == 0)
1240      return mapWindowsError(::GetLastError());
1241
1242    utf8.reserve(len);
1243    utf8.set_size(len);
1244
1245    // Now do the actual conversion.
1246    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, utf8.data(),
1247                                utf8.size(), NULL, NULL);
1248
1249    if (len == 0)
1250      return mapWindowsError(::GetLastError());
1251  }
1252
1253  // Make utf8 null terminated.
1254  utf8.push_back(0);
1255  utf8.pop_back();
1256
1257  return std::error_code();
1258}
1259
1260std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1261                            llvm::SmallVectorImpl<char> &utf8) {
1262  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1263}
1264
1265std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1266                             llvm::SmallVectorImpl<char> &utf8) {
1267  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, utf8);
1268}
1269
1270} // end namespace windows
1271} // end namespace sys
1272} // end namespace llvm
1273