1261991Sdim//===- llvm/Support/Windows/Path.inc - Windows Path Impl --------*- C++ -*-===//
2218885Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6218885Sdim//
7218885Sdim//===----------------------------------------------------------------------===//
8218885Sdim//
9261991Sdim// This file implements the Windows specific implementation of the Path API.
10218885Sdim//
11218885Sdim//===----------------------------------------------------------------------===//
12218885Sdim
13218885Sdim//===----------------------------------------------------------------------===//
14261991Sdim//=== WARNING: Implementation here must contain only generic Windows code that
15261991Sdim//===          is guaranteed to work on *all* Windows variants.
16218885Sdim//===----------------------------------------------------------------------===//
17218885Sdim
18261991Sdim#include "llvm/ADT/STLExtras.h"
19341825Sdim#include "llvm/Support/ConvertUTF.h"
20276479Sdim#include "llvm/Support/WindowsError.h"
21261991Sdim#include <fcntl.h>
22261991Sdim#include <io.h>
23261991Sdim#include <sys/stat.h>
24261991Sdim#include <sys/types.h>
25218885Sdim
26276479Sdim// These two headers must be included last, and make sure shlobj is required
27276479Sdim// after Windows.h to make sure it picks up our definition of _WIN32_WINNT
28360784Sdim#include "llvm/Support/Windows/WindowsSupport.h"
29321369Sdim#include <shellapi.h>
30276479Sdim#include <shlobj.h>
31276479Sdim
32261991Sdim#undef max
33218885Sdim
34261991Sdim// MinGW doesn't define this.
35261991Sdim#ifndef _ERRNO_T_DEFINED
36261991Sdim#define _ERRNO_T_DEFINED
37261991Sdimtypedef int errno_t;
38261991Sdim#endif
39218885Sdim
40261991Sdim#ifdef _MSC_VER
41261991Sdim# pragma comment(lib, "advapi32.lib")  // This provides CryptAcquireContextW.
42296417Sdim# pragma comment(lib, "ole32.lib")     // This provides CoTaskMemFree
43261991Sdim#endif
44218885Sdim
45261991Sdimusing namespace llvm;
46218885Sdim
47261991Sdimusing llvm::sys::windows::UTF8ToUTF16;
48341825Sdimusing llvm::sys::windows::CurCPToUTF16;
49261991Sdimusing llvm::sys::windows::UTF16ToUTF8;
50280031Sdimusing llvm::sys::path::widenPath;
51218885Sdim
52276479Sdimstatic bool is_separator(const wchar_t value) {
53276479Sdim  switch (value) {
54276479Sdim  case L'\\':
55276479Sdim  case L'/':
56276479Sdim    return true;
57276479Sdim  default:
58276479Sdim    return false;
59218885Sdim  }
60218885Sdim}
61218885Sdim
62261991Sdimnamespace llvm {
63261991Sdimnamespace sys  {
64280031Sdimnamespace path {
65280031Sdim
66280031Sdim// Convert a UTF-8 path to UTF-16.  Also, if the absolute equivalent of the
67280031Sdim// path is longer than CreateDirectory can tolerate, make it absolute and
68280031Sdim// prefixed by '\\?\'.
69280031Sdimstd::error_code widenPath(const Twine &Path8,
70280031Sdim                          SmallVectorImpl<wchar_t> &Path16) {
71280031Sdim  const size_t MaxDirLen = MAX_PATH - 12; // Must leave room for 8.3 filename.
72280031Sdim
73280031Sdim  // Several operations would convert Path8 to SmallString; more efficient to
74280031Sdim  // do it once up front.
75280031Sdim  SmallString<128> Path8Str;
76280031Sdim  Path8.toVector(Path8Str);
77280031Sdim
78280031Sdim  // If we made this path absolute, how much longer would it get?
79280031Sdim  size_t CurPathLen;
80280031Sdim  if (llvm::sys::path::is_absolute(Twine(Path8Str)))
81280031Sdim    CurPathLen = 0; // No contribution from current_path needed.
82280031Sdim  else {
83280031Sdim    CurPathLen = ::GetCurrentDirectoryW(0, NULL);
84280031Sdim    if (CurPathLen == 0)
85288943Sdim      return mapWindowsError(::GetLastError());
86280031Sdim  }
87280031Sdim
88280031Sdim  // Would the absolute path be longer than our limit?
89280031Sdim  if ((Path8Str.size() + CurPathLen) >= MaxDirLen &&
90280031Sdim      !Path8Str.startswith("\\\\?\\")) {
91280031Sdim    SmallString<2*MAX_PATH> FullPath("\\\\?\\");
92280031Sdim    if (CurPathLen) {
93280031Sdim      SmallString<80> CurPath;
94280031Sdim      if (std::error_code EC = llvm::sys::fs::current_path(CurPath))
95280031Sdim        return EC;
96280031Sdim      FullPath.append(CurPath);
97280031Sdim    }
98327952Sdim    // Traverse the requested path, canonicalizing . and .. (because the \\?\
99327952Sdim    // prefix is documented to treat them as real components).  Ignore
100327952Sdim    // separators, which can be returned from the iterator if the path has a
101327952Sdim    // drive name.  We don't need to call native() on the result since append()
102327952Sdim    // always attaches preferred_separator.
103280031Sdim    for (llvm::sys::path::const_iterator I = llvm::sys::path::begin(Path8Str),
104280031Sdim                                         E = llvm::sys::path::end(Path8Str);
105280031Sdim                                         I != E; ++I) {
106327952Sdim      if (I->size() == 1 && is_separator((*I)[0]))
107327952Sdim        continue;
108280031Sdim      if (I->size() == 1 && *I == ".")
109280031Sdim        continue;
110280031Sdim      if (I->size() == 2 && *I == "..")
111280031Sdim        llvm::sys::path::remove_filename(FullPath);
112280031Sdim      else
113280031Sdim        llvm::sys::path::append(FullPath, *I);
114280031Sdim    }
115280031Sdim    return UTF8ToUTF16(FullPath, Path16);
116280031Sdim  }
117280031Sdim
118280031Sdim  // Just use the caller's original path.
119280031Sdim  return UTF8ToUTF16(Path8Str, Path16);
120280031Sdim}
121280031Sdim} // end namespace path
122280031Sdim
123261991Sdimnamespace fs {
124218885Sdim
125341825Sdimconst file_t kInvalidFile = INVALID_HANDLE_VALUE;
126341825Sdim
127261991Sdimstd::string getMainExecutable(const char *argv0, void *MainExecAddr) {
128261991Sdim  SmallVector<wchar_t, MAX_PATH> PathName;
129261991Sdim  DWORD Size = ::GetModuleFileNameW(NULL, PathName.data(), PathName.capacity());
130218885Sdim
131261991Sdim  // A zero return value indicates a failure other than insufficient space.
132261991Sdim  if (Size == 0)
133261991Sdim    return "";
134218885Sdim
135261991Sdim  // Insufficient space is determined by a return value equal to the size of
136261991Sdim  // the buffer passed in.
137261991Sdim  if (Size == PathName.capacity())
138261991Sdim    return "";
139218885Sdim
140261991Sdim  // On success, GetModuleFileNameW returns the number of characters written to
141261991Sdim  // the buffer not including the NULL terminator.
142261991Sdim  PathName.set_size(Size);
143218885Sdim
144261991Sdim  // Convert the result from UTF-16 to UTF-8.
145261991Sdim  SmallVector<char, MAX_PATH> PathNameUTF8;
146261991Sdim  if (UTF16ToUTF8(PathName.data(), PathName.size(), PathNameUTF8))
147261991Sdim    return "";
148218885Sdim
149261991Sdim  return std::string(PathNameUTF8.data());
150218885Sdim}
151218885Sdim
152261991SdimUniqueID file_status::getUniqueID() const {
153261991Sdim  // The file is uniquely identified by the volume serial number along
154261991Sdim  // with the 64-bit file identifier.
155261991Sdim  uint64_t FileID = (static_cast<uint64_t>(FileIndexHigh) << 32ULL) |
156261991Sdim                    static_cast<uint64_t>(FileIndexLow);
157261991Sdim
158261991Sdim  return UniqueID(VolumeSerialNumber, FileID);
159218885Sdim}
160218885Sdim
161309124SdimErrorOr disk_space(const Twine &Path) {
162309124Sdim  ULARGE_INTEGER Avail, Total, Free;
163309124Sdim  if (!::GetDiskFreeSpaceExA(Path.str().c_str(), &Avail, &Total, &Free))
164309124Sdim    return mapWindowsError(::GetLastError());
165309124Sdim  space_info SpaceInfo;
166309124Sdim  SpaceInfo.capacity =
167309124Sdim      (static_cast<uint64_t>(Total.HighPart) << 32) + Total.LowPart;
168309124Sdim  SpaceInfo.free = (static_cast<uint64_t>(Free.HighPart) << 32) + Free.LowPart;
169309124Sdim  SpaceInfo.available =
170309124Sdim      (static_cast<uint64_t>(Avail.HighPart) << 32) + Avail.LowPart;
171309124Sdim  return SpaceInfo;
172309124Sdim}
173309124Sdim
174327952SdimTimePoint<> basic_file_status::getLastAccessedTime() const {
175314564Sdim  FILETIME Time;
176314564Sdim  Time.dwLowDateTime = LastAccessedTimeLow;
177314564Sdim  Time.dwHighDateTime = LastAccessedTimeHigh;
178314564Sdim  return toTimePoint(Time);
179309124Sdim}
180309124Sdim
181327952SdimTimePoint<> basic_file_status::getLastModificationTime() const {
182314564Sdim  FILETIME Time;
183314564Sdim  Time.dwLowDateTime = LastWriteTimeLow;
184314564Sdim  Time.dwHighDateTime = LastWriteTimeHigh;
185314564Sdim  return toTimePoint(Time);
186218885Sdim}
187218885Sdim
188321369Sdimuint32_t file_status::getLinkCount() const {
189321369Sdim  return NumLinks;
190321369Sdim}
191321369Sdim
192276479Sdimstd::error_code current_path(SmallVectorImpl<char> &result) {
193261991Sdim  SmallVector<wchar_t, MAX_PATH> cur_path;
194261991Sdim  DWORD len = MAX_PATH;
195218885Sdim
196261991Sdim  do {
197261991Sdim    cur_path.reserve(len);
198261991Sdim    len = ::GetCurrentDirectoryW(cur_path.capacity(), cur_path.data());
199218885Sdim
200261991Sdim    // A zero return value indicates a failure other than insufficient space.
201261991Sdim    if (len == 0)
202288943Sdim      return mapWindowsError(::GetLastError());
203218885Sdim
204261991Sdim    // If there's insufficient space, the len returned is larger than the len
205261991Sdim    // given.
206261991Sdim  } while (len > cur_path.capacity());
207261991Sdim
208261991Sdim  // On success, GetCurrentDirectoryW returns the number of characters not
209261991Sdim  // including the null-terminator.
210261991Sdim  cur_path.set_size(len);
211261991Sdim  return UTF16ToUTF8(cur_path.begin(), cur_path.size(), result);
212218885Sdim}
213218885Sdim
214321369Sdimstd::error_code set_current_path(const Twine &path) {
215321369Sdim  // Convert to utf-16.
216321369Sdim  SmallVector<wchar_t, 128> wide_path;
217321369Sdim  if (std::error_code ec = widenPath(path, wide_path))
218321369Sdim    return ec;
219321369Sdim
220321369Sdim  if (!::SetCurrentDirectoryW(wide_path.begin()))
221321369Sdim    return mapWindowsError(::GetLastError());
222321369Sdim
223321369Sdim  return std::error_code();
224321369Sdim}
225321369Sdim
226296417Sdimstd::error_code create_directory(const Twine &path, bool IgnoreExisting,
227296417Sdim                                 perms Perms) {
228261991Sdim  SmallVector<wchar_t, 128> path_utf16;
229218885Sdim
230280031Sdim  if (std::error_code ec = widenPath(path, path_utf16))
231261991Sdim    return ec;
232218885Sdim
233261991Sdim  if (!::CreateDirectoryW(path_utf16.begin(), NULL)) {
234276479Sdim    DWORD LastError = ::GetLastError();
235276479Sdim    if (LastError != ERROR_ALREADY_EXISTS || !IgnoreExisting)
236288943Sdim      return mapWindowsError(LastError);
237276479Sdim  }
238218885Sdim
239276479Sdim  return std::error_code();
240218885Sdim}
241218885Sdim
242276479Sdim// We can't use symbolic links for windows.
243276479Sdimstd::error_code create_link(const Twine &to, const Twine &from) {
244261991Sdim  // Convert to utf-16.
245261991Sdim  SmallVector<wchar_t, 128> wide_from;
246261991Sdim  SmallVector<wchar_t, 128> wide_to;
247280031Sdim  if (std::error_code ec = widenPath(from, wide_from))
248276479Sdim    return ec;
249280031Sdim  if (std::error_code ec = widenPath(to, wide_to))
250276479Sdim    return ec;
251218885Sdim
252276479Sdim  if (!::CreateHardLinkW(wide_from.begin(), wide_to.begin(), NULL))
253288943Sdim    return mapWindowsError(::GetLastError());
254218885Sdim
255276479Sdim  return std::error_code();
256218885Sdim}
257218885Sdim
258314564Sdimstd::error_code create_hard_link(const Twine &to, const Twine &from) {
259327952Sdim  return create_link(to, from);
260314564Sdim}
261314564Sdim
262276479Sdimstd::error_code remove(const Twine &path, bool IgnoreNonExisting) {
263261991Sdim  SmallVector<wchar_t, 128> path_utf16;
264218885Sdim
265280031Sdim  if (std::error_code ec = widenPath(path, path_utf16))
266261991Sdim    return ec;
267261991Sdim
268327952Sdim  // We don't know whether this is a file or a directory, and remove() can
269327952Sdim  // accept both. The usual way to delete a file or directory is to use one of
270327952Sdim  // the DeleteFile or RemoveDirectory functions, but that requires you to know
271327952Sdim  // which one it is. We could stat() the file to determine that, but that would
272327952Sdim  // cost us additional system calls, which can be slow in a directory
273327952Sdim  // containing a large number of files. So instead we call CreateFile directly.
274327952Sdim  // The important part is the FILE_FLAG_DELETE_ON_CLOSE flag, which causes the
275327952Sdim  // file to be deleted once it is closed. We also use the flags
276327952Sdim  // FILE_FLAG_BACKUP_SEMANTICS (which allows us to open directories), and
277327952Sdim  // FILE_FLAG_OPEN_REPARSE_POINT (don't follow symlinks).
278327952Sdim  ScopedFileHandle h(::CreateFileW(
279327952Sdim      c_str(path_utf16), DELETE,
280327952Sdim      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
281327952Sdim      OPEN_EXISTING,
282327952Sdim      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS |
283327952Sdim          FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_DELETE_ON_CLOSE,
284327952Sdim      NULL));
285327952Sdim  if (!h) {
286288943Sdim    std::error_code EC = mapWindowsError(::GetLastError());
287276479Sdim    if (EC != errc::no_such_file_or_directory || !IgnoreNonExisting)
288276479Sdim      return EC;
289276479Sdim  }
290327952Sdim
291276479Sdim  return std::error_code();
292218885Sdim}
293218885Sdim
294321369Sdimstatic std::error_code is_local_internal(SmallVectorImpl<wchar_t> &Path,
295321369Sdim                                         bool &Result) {
296321369Sdim  SmallVector<wchar_t, 128> VolumePath;
297321369Sdim  size_t Len = 128;
298321369Sdim  while (true) {
299321369Sdim    VolumePath.resize(Len);
300321369Sdim    BOOL Success =
301321369Sdim        ::GetVolumePathNameW(Path.data(), VolumePath.data(), VolumePath.size());
302321369Sdim
303321369Sdim    if (Success)
304321369Sdim      break;
305321369Sdim
306321369Sdim    DWORD Err = ::GetLastError();
307321369Sdim    if (Err != ERROR_INSUFFICIENT_BUFFER)
308321369Sdim      return mapWindowsError(Err);
309321369Sdim
310321369Sdim    Len *= 2;
311321369Sdim  }
312321369Sdim  // If the output buffer has exactly enough space for the path name, but not
313321369Sdim  // the null terminator, it will leave the output unterminated.  Push a null
314321369Sdim  // terminator onto the end to ensure that this never happens.
315321369Sdim  VolumePath.push_back(L'\0');
316321369Sdim  VolumePath.set_size(wcslen(VolumePath.data()));
317321369Sdim  const wchar_t *P = VolumePath.data();
318321369Sdim
319321369Sdim  UINT Type = ::GetDriveTypeW(P);
320321369Sdim  switch (Type) {
321321369Sdim  case DRIVE_FIXED:
322321369Sdim    Result = true;
323321369Sdim    return std::error_code();
324321369Sdim  case DRIVE_REMOTE:
325321369Sdim  case DRIVE_CDROM:
326321369Sdim  case DRIVE_RAMDISK:
327321369Sdim  case DRIVE_REMOVABLE:
328321369Sdim    Result = false;
329321369Sdim    return std::error_code();
330321369Sdim  default:
331321369Sdim    return make_error_code(errc::no_such_file_or_directory);
332321369Sdim  }
333321369Sdim  llvm_unreachable("Unreachable!");
334321369Sdim}
335321369Sdim
336321369Sdimstd::error_code is_local(const Twine &path, bool &result) {
337321369Sdim  if (!llvm::sys::fs::exists(path) || !llvm::sys::path::has_root_path(path))
338321369Sdim    return make_error_code(errc::no_such_file_or_directory);
339321369Sdim
340321369Sdim  SmallString<128> Storage;
341321369Sdim  StringRef P = path.toStringRef(Storage);
342321369Sdim
343321369Sdim  // Convert to utf-16.
344321369Sdim  SmallVector<wchar_t, 128> WidePath;
345321369Sdim  if (std::error_code ec = widenPath(P, WidePath))
346321369Sdim    return ec;
347321369Sdim  return is_local_internal(WidePath, result);
348321369Sdim}
349321369Sdim
350327952Sdimstatic std::error_code realPathFromHandle(HANDLE H,
351327952Sdim                                          SmallVectorImpl<wchar_t> &Buffer) {
352327952Sdim  DWORD CountChars = ::GetFinalPathNameByHandleW(
353327952Sdim      H, Buffer.begin(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
354327952Sdim  if (CountChars > Buffer.capacity()) {
355327952Sdim    // The buffer wasn't big enough, try again.  In this case the return value
356327952Sdim    // *does* indicate the size of the null terminator.
357327952Sdim    Buffer.reserve(CountChars);
358327952Sdim    CountChars = ::GetFinalPathNameByHandleW(
359327952Sdim        H, Buffer.data(), Buffer.capacity() - 1, FILE_NAME_NORMALIZED);
360327952Sdim  }
361327952Sdim  if (CountChars == 0)
362327952Sdim    return mapWindowsError(GetLastError());
363327952Sdim  Buffer.set_size(CountChars);
364327952Sdim  return std::error_code();
365327952Sdim}
366327952Sdim
367327952Sdimstatic std::error_code realPathFromHandle(HANDLE H,
368327952Sdim                                          SmallVectorImpl<char> &RealPath) {
369327952Sdim  RealPath.clear();
370327952Sdim  SmallVector<wchar_t, MAX_PATH> Buffer;
371327952Sdim  if (std::error_code EC = realPathFromHandle(H, Buffer))
372327952Sdim    return EC;
373327952Sdim
374360784Sdim  // Strip the \\?\ prefix. We don't want it ending up in output, and such
375360784Sdim  // paths don't get canonicalized by file APIs.
376360784Sdim  wchar_t *Data = Buffer.data();
377327952Sdim  DWORD CountChars = Buffer.size();
378360784Sdim  if (CountChars >= 8 && ::memcmp(Data, L"\\\\?\\UNC\\", 16) == 0) {
379360784Sdim    // Convert \\?\UNC\foo\bar to \\foo\bar
380360784Sdim    CountChars -= 6;
381360784Sdim    Data += 6;
382360784Sdim    Data[0] = '\\';
383360784Sdim  } else if (CountChars >= 4 && ::memcmp(Data, L"\\\\?\\", 8) == 0) {
384360784Sdim    // Convert \\?\c:\foo to c:\foo
385360784Sdim    CountChars -= 4;
386360784Sdim    Data += 4;
387327952Sdim  }
388327952Sdim
389327952Sdim  // Convert the result from UTF-16 to UTF-8.
390327952Sdim  return UTF16ToUTF8(Data, CountChars, RealPath);
391327952Sdim}
392327952Sdim
393321369Sdimstd::error_code is_local(int FD, bool &Result) {
394321369Sdim  SmallVector<wchar_t, 128> FinalPath;
395321369Sdim  HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
396321369Sdim
397327952Sdim  if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
398327952Sdim    return EC;
399321369Sdim
400321369Sdim  return is_local_internal(FinalPath, Result);
401321369Sdim}
402321369Sdim
403327952Sdimstatic std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
404327952Sdim  FILE_DISPOSITION_INFO Disposition;
405327952Sdim  Disposition.DeleteFile = Delete;
406327952Sdim  if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
407327952Sdim                                  sizeof(Disposition)))
408327952Sdim    return mapWindowsError(::GetLastError());
409327952Sdim  return std::error_code();
410327952Sdim}
411261991Sdim
412327952Sdimstatic std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
413327952Sdim                                       bool ReplaceIfExists) {
414327952Sdim  SmallVector<wchar_t, 0> ToWide;
415327952Sdim  if (auto EC = widenPath(To, ToWide))
416327952Sdim    return EC;
417327952Sdim
418327952Sdim  std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
419327952Sdim                                  (ToWide.size() * sizeof(wchar_t)));
420327952Sdim  FILE_RENAME_INFO &RenameInfo =
421327952Sdim      *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
422327952Sdim  RenameInfo.ReplaceIfExists = ReplaceIfExists;
423327952Sdim  RenameInfo.RootDirectory = 0;
424344779Sdim  RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
425327952Sdim  std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
426327952Sdim
427327952Sdim  SetLastError(ERROR_SUCCESS);
428327952Sdim  if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
429327952Sdim                                  RenameInfoBuf.size())) {
430327952Sdim    unsigned Error = GetLastError();
431327952Sdim    if (Error == ERROR_SUCCESS)
432327952Sdim      Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
433327952Sdim    return mapWindowsError(Error);
434327952Sdim  }
435327952Sdim
436327952Sdim  return std::error_code();
437327952Sdim}
438327952Sdim
439327952Sdimstatic std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
440327952Sdim  SmallVector<wchar_t, 128> WideTo;
441327952Sdim  if (std::error_code EC = widenPath(To, WideTo))
442327952Sdim    return EC;
443327952Sdim
444327952Sdim  // We normally expect this loop to succeed after a few iterations. If it
445327952Sdim  // requires more than 200 tries, it's more likely that the failures are due to
446327952Sdim  // a true error, so stop trying.
447327952Sdim  for (unsigned Retry = 0; Retry != 200; ++Retry) {
448327952Sdim    auto EC = rename_internal(FromHandle, To, true);
449327952Sdim
450327952Sdim    if (EC ==
451327952Sdim        std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
452327952Sdim      // Wine doesn't support SetFileInformationByHandle in rename_internal.
453327952Sdim      // Fall back to MoveFileEx.
454327952Sdim      SmallVector<wchar_t, MAX_PATH> WideFrom;
455327952Sdim      if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
456327952Sdim        return EC2;
457327952Sdim      if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
458327952Sdim                        MOVEFILE_REPLACE_EXISTING))
459309124Sdim        return std::error_code();
460327952Sdim      return mapWindowsError(GetLastError());
461327952Sdim    }
462296417Sdim
463327952Sdim    if (!EC || EC != errc::permission_denied)
464327952Sdim      return EC;
465309124Sdim
466327952Sdim    // The destination file probably exists and is currently open in another
467327952Sdim    // process, either because the file was opened without FILE_SHARE_DELETE or
468327952Sdim    // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
469327952Sdim    // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
470327952Sdim    // to arrange for the destination file to be deleted when the other process
471327952Sdim    // closes it.
472327952Sdim    ScopedFileHandle ToHandle(
473327952Sdim        ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
474327952Sdim                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
475327952Sdim                      NULL, OPEN_EXISTING,
476327952Sdim                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
477327952Sdim    if (!ToHandle) {
478327952Sdim      auto EC = mapWindowsError(GetLastError());
479327952Sdim      // Another process might have raced with us and moved the existing file
480327952Sdim      // out of the way before we had a chance to open it. If that happens, try
481327952Sdim      // to rename the source file again.
482327952Sdim      if (EC == errc::no_such_file_or_directory)
483309124Sdim        continue;
484327952Sdim      return EC;
485327952Sdim    }
486327952Sdim
487327952Sdim    BY_HANDLE_FILE_INFORMATION FI;
488327952Sdim    if (!GetFileInformationByHandle(ToHandle, &FI))
489327952Sdim      return mapWindowsError(GetLastError());
490327952Sdim
491327952Sdim    // Try to find a unique new name for the destination file.
492327952Sdim    for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
493327952Sdim      std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
494327952Sdim      if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
495327952Sdim        if (EC == errc::file_exists || EC == errc::permission_denied) {
496327952Sdim          // Again, another process might have raced with us and moved the file
497327952Sdim          // before we could move it. Check whether this is the case, as it
498327952Sdim          // might have caused the permission denied error. If that was the
499327952Sdim          // case, we don't need to move it ourselves.
500327952Sdim          ScopedFileHandle ToHandle2(::CreateFileW(
501327952Sdim              WideTo.begin(), 0,
502327952Sdim              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
503327952Sdim              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
504327952Sdim          if (!ToHandle2) {
505327952Sdim            auto EC = mapWindowsError(GetLastError());
506327952Sdim            if (EC == errc::no_such_file_or_directory)
507327952Sdim              break;
508327952Sdim            return EC;
509327952Sdim          }
510327952Sdim          BY_HANDLE_FILE_INFORMATION FI2;
511327952Sdim          if (!GetFileInformationByHandle(ToHandle2, &FI2))
512327952Sdim            return mapWindowsError(GetLastError());
513327952Sdim          if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
514327952Sdim              FI.nFileIndexLow != FI2.nFileIndexLow ||
515327952Sdim              FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
516327952Sdim            break;
517327952Sdim          continue;
518327952Sdim        }
519327952Sdim        return EC;
520309124Sdim      }
521327952Sdim      break;
522309124Sdim    }
523309124Sdim
524327952Sdim    // Okay, the old destination file has probably been moved out of the way at
525327952Sdim    // this point, so try to rename the source file again. Still, another
526327952Sdim    // process might have raced with us to create and open the destination
527327952Sdim    // file, so we need to keep doing this until we succeed.
528327952Sdim  }
529296417Sdim
530327952Sdim  // The most likely root cause.
531327952Sdim  return errc::permission_denied;
532327952Sdim}
533327952Sdim
534327952Sdimstatic std::error_code rename_fd(int FromFD, const Twine &To) {
535327952Sdim  HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
536327952Sdim  return rename_handle(FromHandle, To);
537327952Sdim}
538327952Sdim
539327952Sdimstd::error_code rename(const Twine &From, const Twine &To) {
540327952Sdim  // Convert to utf-16.
541327952Sdim  SmallVector<wchar_t, 128> WideFrom;
542327952Sdim  if (std::error_code EC = widenPath(From, WideFrom))
543327952Sdim    return EC;
544327952Sdim
545327952Sdim  ScopedFileHandle FromHandle;
546327952Sdim  // Retry this a few times to defeat badly behaved file system scanners.
547327952Sdim  for (unsigned Retry = 0; Retry != 200; ++Retry) {
548327952Sdim    if (Retry != 0)
549327952Sdim      ::Sleep(10);
550327952Sdim    FromHandle =
551327952Sdim        ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
552327952Sdim                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
553327952Sdim                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
554327952Sdim    if (FromHandle)
555327952Sdim      break;
556261991Sdim  }
557327952Sdim  if (!FromHandle)
558327952Sdim    return mapWindowsError(GetLastError());
559261991Sdim
560327952Sdim  return rename_handle(FromHandle, To);
561218885Sdim}
562218885Sdim
563280031Sdimstd::error_code resize_file(int FD, uint64_t Size) {
564261991Sdim#ifdef HAVE__CHSIZE_S
565280031Sdim  errno_t error = ::_chsize_s(FD, Size);
566261991Sdim#else
567280031Sdim  errno_t error = ::_chsize(FD, Size);
568261991Sdim#endif
569276479Sdim  return std::error_code(error, std::generic_category());
570218885Sdim}
571218885Sdim
572280031Sdimstd::error_code access(const Twine &Path, AccessMode Mode) {
573280031Sdim  SmallVector<wchar_t, 128> PathUtf16;
574218885Sdim
575280031Sdim  if (std::error_code EC = widenPath(Path, PathUtf16))
576280031Sdim    return EC;
577218885Sdim
578280031Sdim  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
579218885Sdim
580280031Sdim  if (Attributes == INVALID_FILE_ATTRIBUTES) {
581261991Sdim    // See if the file didn't actually exist.
582276479Sdim    DWORD LastError = ::GetLastError();
583276479Sdim    if (LastError != ERROR_FILE_NOT_FOUND &&
584276479Sdim        LastError != ERROR_PATH_NOT_FOUND)
585288943Sdim      return mapWindowsError(LastError);
586280031Sdim    return errc::no_such_file_or_directory;
587280031Sdim  }
588218885Sdim
589280031Sdim  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
590280031Sdim    return errc::permission_denied;
591218885Sdim
592280031Sdim  return std::error_code();
593261991Sdim}
594218885Sdim
595296417Sdimbool can_execute(const Twine &Path) {
596296417Sdim  return !access(Path, AccessMode::Execute) ||
597296417Sdim         !access(Path + ".exe", AccessMode::Execute);
598296417Sdim}
599296417Sdim
600261991Sdimbool equivalent(file_status A, file_status B) {
601261991Sdim  assert(status_known(A) && status_known(B));
602309124Sdim  return A.FileIndexHigh         == B.FileIndexHigh &&
603309124Sdim         A.FileIndexLow          == B.FileIndexLow &&
604309124Sdim         A.FileSizeHigh          == B.FileSizeHigh &&
605309124Sdim         A.FileSizeLow           == B.FileSizeLow &&
606309124Sdim         A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
607309124Sdim         A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
608309124Sdim         A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
609309124Sdim         A.LastWriteTimeLow      == B.LastWriteTimeLow &&
610309124Sdim         A.VolumeSerialNumber    == B.VolumeSerialNumber;
611218885Sdim}
612218885Sdim
613276479Sdimstd::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
614261991Sdim  file_status fsA, fsB;
615276479Sdim  if (std::error_code ec = status(A, fsA))
616276479Sdim    return ec;
617276479Sdim  if (std::error_code ec = status(B, fsB))
618276479Sdim    return ec;
619261991Sdim  result = equivalent(fsA, fsB);
620276479Sdim  return std::error_code();
621261991Sdim}
622218885Sdim
623261991Sdimstatic bool isReservedName(StringRef path) {
624261991Sdim  // This list of reserved names comes from MSDN, at:
625261991Sdim  // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
626296417Sdim  static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
627296417Sdim                                                "com1", "com2", "com3", "com4",
628296417Sdim                                                "com5", "com6", "com7", "com8",
629296417Sdim                                                "com9", "lpt1", "lpt2", "lpt3",
630296417Sdim                                                "lpt4", "lpt5", "lpt6", "lpt7",
631296417Sdim                                                "lpt8", "lpt9" };
632218885Sdim
633261991Sdim  // First, check to see if this is a device namespace, which always
634261991Sdim  // starts with \\.\, since device namespaces are not legal file paths.
635261991Sdim  if (path.startswith("\\\\.\\"))
636261991Sdim    return true;
637261991Sdim
638309124Sdim  // Then compare against the list of ancient reserved names.
639261991Sdim  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
640261991Sdim    if (path.equals_lower(sReservedNames[i]))
641218885Sdim      return true;
642218885Sdim  }
643218885Sdim
644261991Sdim  // The path isn't what we consider reserved.
645218885Sdim  return false;
646218885Sdim}
647218885Sdim
648327952Sdimstatic file_type file_type_from_attrs(DWORD Attrs) {
649327952Sdim  return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
650327952Sdim                                            : file_type::regular_file;
651327952Sdim}
652327952Sdim
653327952Sdimstatic perms perms_from_attrs(DWORD Attrs) {
654327952Sdim  return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
655327952Sdim}
656327952Sdim
657276479Sdimstatic std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
658261991Sdim  if (FileHandle == INVALID_HANDLE_VALUE)
659261991Sdim    goto handle_status_error;
660261991Sdim
661261991Sdim  switch (::GetFileType(FileHandle)) {
662261991Sdim  default:
663261991Sdim    llvm_unreachable("Don't know anything about this file type");
664261991Sdim  case FILE_TYPE_UNKNOWN: {
665261991Sdim    DWORD Err = ::GetLastError();
666261991Sdim    if (Err != NO_ERROR)
667288943Sdim      return mapWindowsError(Err);
668261991Sdim    Result = file_status(file_type::type_unknown);
669276479Sdim    return std::error_code();
670218885Sdim  }
671261991Sdim  case FILE_TYPE_DISK:
672261991Sdim    break;
673261991Sdim  case FILE_TYPE_CHAR:
674261991Sdim    Result = file_status(file_type::character_file);
675276479Sdim    return std::error_code();
676261991Sdim  case FILE_TYPE_PIPE:
677261991Sdim    Result = file_status(file_type::fifo_file);
678276479Sdim    return std::error_code();
679261991Sdim  }
680218885Sdim
681261991Sdim  BY_HANDLE_FILE_INFORMATION Info;
682261991Sdim  if (!::GetFileInformationByHandle(FileHandle, &Info))
683261991Sdim    goto handle_status_error;
684261991Sdim
685327952Sdim  Result = file_status(
686327952Sdim      file_type_from_attrs(Info.dwFileAttributes),
687327952Sdim      perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
688327952Sdim      Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
689327952Sdim      Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
690327952Sdim      Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
691327952Sdim      Info.nFileIndexHigh, Info.nFileIndexLow);
692327952Sdim  return std::error_code();
693218885Sdim
694261991Sdimhandle_status_error:
695276479Sdim  DWORD LastError = ::GetLastError();
696276479Sdim  if (LastError == ERROR_FILE_NOT_FOUND ||
697276479Sdim      LastError == ERROR_PATH_NOT_FOUND)
698261991Sdim    Result = file_status(file_type::file_not_found);
699276479Sdim  else if (LastError == ERROR_SHARING_VIOLATION)
700261991Sdim    Result = file_status(file_type::type_unknown);
701218885Sdim  else
702261991Sdim    Result = file_status(file_type::status_error);
703288943Sdim  return mapWindowsError(LastError);
704261991Sdim}
705218885Sdim
706321369Sdimstd::error_code status(const Twine &path, file_status &result, bool Follow) {
707261991Sdim  SmallString<128> path_storage;
708261991Sdim  SmallVector<wchar_t, 128> path_utf16;
709261991Sdim
710261991Sdim  StringRef path8 = path.toStringRef(path_storage);
711261991Sdim  if (isReservedName(path8)) {
712261991Sdim    result = file_status(file_type::character_file);
713276479Sdim    return std::error_code();
714218885Sdim  }
715218885Sdim
716280031Sdim  if (std::error_code ec = widenPath(path8, path_utf16))
717261991Sdim    return ec;
718218885Sdim
719261991Sdim  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
720261991Sdim  if (attr == INVALID_FILE_ATTRIBUTES)
721261991Sdim    return getStatus(INVALID_HANDLE_VALUE, result);
722261991Sdim
723321369Sdim  DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
724261991Sdim  // Handle reparse points.
725321369Sdim  if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
726321369Sdim    Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
727261991Sdim
728261991Sdim  ScopedFileHandle h(
729261991Sdim      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
730261991Sdim                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
731321369Sdim                    NULL, OPEN_EXISTING, Flags, 0));
732321369Sdim  if (!h)
733321369Sdim    return getStatus(INVALID_HANDLE_VALUE, result);
734261991Sdim
735321369Sdim  return getStatus(h, result);
736218885Sdim}
737218885Sdim
738276479Sdimstd::error_code status(int FD, file_status &Result) {
739261991Sdim  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
740261991Sdim  return getStatus(FileHandle, Result);
741261991Sdim}
742261991Sdim
743353358Sdimstd::error_code status(file_t FileHandle, file_status &Result) {
744353358Sdim  return getStatus(FileHandle, Result);
745353358Sdim}
746353358Sdim
747353358Sdimunsigned getUmask() {
748353358Sdim  return 0;
749353358Sdim}
750353358Sdim
751321369Sdimstd::error_code setPermissions(const Twine &Path, perms Permissions) {
752321369Sdim  SmallVector<wchar_t, 128> PathUTF16;
753321369Sdim  if (std::error_code EC = widenPath(Path, PathUTF16))
754321369Sdim    return EC;
755321369Sdim
756321369Sdim  DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
757321369Sdim  if (Attributes == INVALID_FILE_ATTRIBUTES)
758321369Sdim    return mapWindowsError(GetLastError());
759321369Sdim
760321369Sdim  // There are many Windows file attributes that are not to do with the file
761321369Sdim  // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
762321369Sdim  // them.
763321369Sdim  if (Permissions & all_write) {
764321369Sdim    Attributes &= ~FILE_ATTRIBUTE_READONLY;
765321369Sdim    if (Attributes == 0)
766321369Sdim      // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
767321369Sdim      Attributes |= FILE_ATTRIBUTE_NORMAL;
768321369Sdim  }
769321369Sdim  else {
770321369Sdim    Attributes |= FILE_ATTRIBUTE_READONLY;
771321369Sdim    // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
772321369Sdim    // remove it, if it is present.
773321369Sdim    Attributes &= ~FILE_ATTRIBUTE_NORMAL;
774321369Sdim  }
775321369Sdim
776321369Sdim  if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
777321369Sdim    return mapWindowsError(GetLastError());
778321369Sdim
779321369Sdim  return std::error_code();
780321369Sdim}
781321369Sdim
782353358Sdimstd::error_code setPermissions(int FD, perms Permissions) {
783353358Sdim  // FIXME Not implemented.
784353358Sdim  return std::make_error_code(std::errc::not_supported);
785353358Sdim}
786353358Sdim
787344779Sdimstd::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
788344779Sdim                                                 TimePoint<> ModificationTime) {
789344779Sdim  FILETIME AccessFT = toFILETIME(AccessTime);
790344779Sdim  FILETIME ModifyFT = toFILETIME(ModificationTime);
791261991Sdim  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
792344779Sdim  if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
793288943Sdim    return mapWindowsError(::GetLastError());
794276479Sdim  return std::error_code();
795261991Sdim}
796261991Sdim
797353358Sdimstd::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
798353358Sdim                                         uint64_t Offset, mapmode Mode) {
799341825Sdim  this->Mode = Mode;
800341825Sdim  if (OrigFileHandle == INVALID_HANDLE_VALUE)
801280031Sdim    return make_error_code(errc::bad_file_descriptor);
802280031Sdim
803261991Sdim  DWORD flprotect;
804261991Sdim  switch (Mode) {
805261991Sdim  case readonly:  flprotect = PAGE_READONLY; break;
806261991Sdim  case readwrite: flprotect = PAGE_READWRITE; break;
807261991Sdim  case priv:      flprotect = PAGE_WRITECOPY; break;
808218885Sdim  }
809218885Sdim
810280031Sdim  HANDLE FileMappingHandle =
811341825Sdim      ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
812327952Sdim                           Hi_32(Size),
813327952Sdim                           Lo_32(Size),
814261991Sdim                           0);
815261991Sdim  if (FileMappingHandle == NULL) {
816288943Sdim    std::error_code ec = mapWindowsError(GetLastError());
817261991Sdim    return ec;
818218885Sdim  }
819218885Sdim
820261991Sdim  DWORD dwDesiredAccess;
821261991Sdim  switch (Mode) {
822261991Sdim  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
823261991Sdim  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
824261991Sdim  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
825261991Sdim  }
826261991Sdim  Mapping = ::MapViewOfFile(FileMappingHandle,
827261991Sdim                            dwDesiredAccess,
828261991Sdim                            Offset >> 32,
829261991Sdim                            Offset & 0xffffffff,
830261991Sdim                            Size);
831261991Sdim  if (Mapping == NULL) {
832288943Sdim    std::error_code ec = mapWindowsError(GetLastError());
833261991Sdim    ::CloseHandle(FileMappingHandle);
834261991Sdim    return ec;
835261991Sdim  }
836261991Sdim
837261991Sdim  if (Size == 0) {
838261991Sdim    MEMORY_BASIC_INFORMATION mbi;
839261991Sdim    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
840261991Sdim    if (Result == 0) {
841288943Sdim      std::error_code ec = mapWindowsError(GetLastError());
842261991Sdim      ::UnmapViewOfFile(Mapping);
843261991Sdim      ::CloseHandle(FileMappingHandle);
844261991Sdim      return ec;
845218885Sdim    }
846261991Sdim    Size = mbi.RegionSize;
847218885Sdim  }
848218885Sdim
849341825Sdim  // Close the file mapping handle, as it's kept alive by the file mapping. But
850341825Sdim  // neither the file mapping nor the file mapping handle keep the file handle
851341825Sdim  // alive, so we need to keep a reference to the file in case all other handles
852341825Sdim  // are closed and the file is deleted, which may cause invalid data to be read
853341825Sdim  // from the file.
854261991Sdim  ::CloseHandle(FileMappingHandle);
855341825Sdim  if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
856341825Sdim                         ::GetCurrentProcess(), &FileHandle, 0, 0,
857341825Sdim                         DUPLICATE_SAME_ACCESS)) {
858341825Sdim    std::error_code ec = mapWindowsError(GetLastError());
859341825Sdim    ::UnmapViewOfFile(Mapping);
860341825Sdim    return ec;
861341825Sdim  }
862341825Sdim
863276479Sdim  return std::error_code();
864218885Sdim}
865218885Sdim
866353358Sdimmapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
867353358Sdim                                       size_t length, uint64_t offset,
868353358Sdim                                       std::error_code &ec)
869280031Sdim    : Size(length), Mapping() {
870280031Sdim  ec = init(fd, offset, mode);
871280031Sdim  if (ec)
872280031Sdim    Mapping = 0;
873261991Sdim}
874218885Sdim
875344779Sdimstatic bool hasFlushBufferKernelBug() {
876344779Sdim  static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
877344779Sdim  return Ret;
878344779Sdim}
879344779Sdim
880344779Sdimstatic bool isEXE(StringRef Magic) {
881344779Sdim  static const char PEMagic[] = {'P', 'E', '\0', '\0'};
882344779Sdim  if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
883344779Sdim    uint32_t off = read32le(Magic.data() + 0x3c);
884344779Sdim    // PE/COFF file, either EXE or DLL.
885344779Sdim    if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
886344779Sdim      return true;
887344779Sdim  }
888344779Sdim  return false;
889344779Sdim}
890344779Sdim
891261991Sdimmapped_file_region::~mapped_file_region() {
892341825Sdim  if (Mapping) {
893344779Sdim
894344779Sdim    bool Exe = isEXE(StringRef((char *)Mapping, Size));
895344779Sdim
896261991Sdim    ::UnmapViewOfFile(Mapping);
897341825Sdim
898344779Sdim    if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
899341825Sdim      // There is a Windows kernel bug, the exact trigger conditions of which
900341825Sdim      // are not well understood.  When triggered, dirty pages are not properly
901341825Sdim      // flushed and subsequent process's attempts to read a file can return
902341825Sdim      // invalid data.  Calling FlushFileBuffers on the write handle is
903341825Sdim      // sufficient to ensure that this bug is not triggered.
904344779Sdim      // The bug only occurs when writing an executable and executing it right
905344779Sdim      // after, under high I/O pressure.
906341825Sdim      ::FlushFileBuffers(FileHandle);
907341825Sdim    }
908341825Sdim
909341825Sdim    ::CloseHandle(FileHandle);
910341825Sdim  }
911261991Sdim}
912218885Sdim
913327952Sdimsize_t mapped_file_region::size() const {
914261991Sdim  assert(Mapping && "Mapping failed but used anyway!");
915261991Sdim  return Size;
916261991Sdim}
917218885Sdim
918261991Sdimchar *mapped_file_region::data() const {
919261991Sdim  assert(Mapping && "Mapping failed but used anyway!");
920261991Sdim  return reinterpret_cast<char*>(Mapping);
921261991Sdim}
922218885Sdim
923261991Sdimconst char *mapped_file_region::const_data() const {
924261991Sdim  assert(Mapping && "Mapping failed but used anyway!");
925261991Sdim  return reinterpret_cast<const char*>(Mapping);
926261991Sdim}
927218885Sdim
928261991Sdimint mapped_file_region::alignment() {
929261991Sdim  SYSTEM_INFO SysInfo;
930261991Sdim  ::GetSystemInfo(&SysInfo);
931261991Sdim  return SysInfo.dwAllocationGranularity;
932261991Sdim}
933218885Sdim
934327952Sdimstatic basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
935327952Sdim  return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
936327952Sdim                           perms_from_attrs(FindData->dwFileAttributes),
937327952Sdim                           FindData->ftLastAccessTime.dwHighDateTime,
938327952Sdim                           FindData->ftLastAccessTime.dwLowDateTime,
939327952Sdim                           FindData->ftLastWriteTime.dwHighDateTime,
940327952Sdim                           FindData->ftLastWriteTime.dwLowDateTime,
941327952Sdim                           FindData->nFileSizeHigh, FindData->nFileSizeLow);
942327952Sdim}
943327952Sdim
944344779Sdimstd::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
945344779Sdim                                                     StringRef Path,
946344779Sdim                                                     bool FollowSymlinks) {
947344779Sdim  SmallVector<wchar_t, 128> PathUTF16;
948218885Sdim
949344779Sdim  if (std::error_code EC = widenPath(Path, PathUTF16))
950344779Sdim    return EC;
951218885Sdim
952261991Sdim  // Convert path to the format that Windows is happy with.
953344779Sdim  if (PathUTF16.size() > 0 &&
954344779Sdim      !is_separator(PathUTF16[Path.size() - 1]) &&
955344779Sdim      PathUTF16[Path.size() - 1] != L':') {
956344779Sdim    PathUTF16.push_back(L'\\');
957344779Sdim    PathUTF16.push_back(L'*');
958261991Sdim  } else {
959344779Sdim    PathUTF16.push_back(L'*');
960261991Sdim  }
961218885Sdim
962261991Sdim  //  Get the first directory entry.
963261991Sdim  WIN32_FIND_DATAW FirstFind;
964327952Sdim  ScopedFindHandle FindHandle(::FindFirstFileExW(
965344779Sdim      c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
966327952Sdim      NULL, FIND_FIRST_EX_LARGE_FETCH));
967261991Sdim  if (!FindHandle)
968288943Sdim    return mapWindowsError(::GetLastError());
969218885Sdim
970261991Sdim  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
971261991Sdim  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
972261991Sdim         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
973261991Sdim                              FirstFind.cFileName[1] == L'.'))
974261991Sdim    if (!::FindNextFileW(FindHandle, &FirstFind)) {
975276479Sdim      DWORD LastError = ::GetLastError();
976261991Sdim      // Check for end.
977276479Sdim      if (LastError == ERROR_NO_MORE_FILES)
978344779Sdim        return detail::directory_iterator_destruct(IT);
979288943Sdim      return mapWindowsError(LastError);
980261991Sdim    } else
981261991Sdim      FilenameLen = ::wcslen(FirstFind.cFileName);
982218885Sdim
983261991Sdim  // Construct the current directory entry.
984344779Sdim  SmallString<128> DirectoryEntryNameUTF8;
985344779Sdim  if (std::error_code EC =
986276479Sdim          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
987344779Sdim                      DirectoryEntryNameUTF8))
988344779Sdim    return EC;
989218885Sdim
990344779Sdim  IT.IterationHandle = intptr_t(FindHandle.take());
991344779Sdim  SmallString<128> DirectoryEntryPath(Path);
992344779Sdim  path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
993344779Sdim  IT.CurrentEntry =
994344779Sdim      directory_entry(DirectoryEntryPath, FollowSymlinks,
995344779Sdim                      file_type_from_attrs(FirstFind.dwFileAttributes),
996344779Sdim                      status_from_find_data(&FirstFind));
997218885Sdim
998276479Sdim  return std::error_code();
999218885Sdim}
1000218885Sdim
1001344779Sdimstd::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
1002344779Sdim  if (IT.IterationHandle != 0)
1003261991Sdim    // Closes the handle if it's valid.
1004344779Sdim    ScopedFindHandle close(HANDLE(IT.IterationHandle));
1005344779Sdim  IT.IterationHandle = 0;
1006344779Sdim  IT.CurrentEntry = directory_entry();
1007276479Sdim  return std::error_code();
1008261991Sdim}
1009218885Sdim
1010344779Sdimstd::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1011261991Sdim  WIN32_FIND_DATAW FindData;
1012344779Sdim  if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1013276479Sdim    DWORD LastError = ::GetLastError();
1014261991Sdim    // Check for end.
1015276479Sdim    if (LastError == ERROR_NO_MORE_FILES)
1016344779Sdim      return detail::directory_iterator_destruct(IT);
1017288943Sdim    return mapWindowsError(LastError);
1018261991Sdim  }
1019218885Sdim
1020261991Sdim  size_t FilenameLen = ::wcslen(FindData.cFileName);
1021261991Sdim  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1022261991Sdim      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1023261991Sdim                           FindData.cFileName[1] == L'.'))
1024344779Sdim    return directory_iterator_increment(IT);
1025218885Sdim
1026344779Sdim  SmallString<128> DirectoryEntryPathUTF8;
1027344779Sdim  if (std::error_code EC =
1028276479Sdim          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1029344779Sdim                      DirectoryEntryPathUTF8))
1030344779Sdim    return EC;
1031218885Sdim
1032344779Sdim  IT.CurrentEntry.replace_filename(
1033344779Sdim      Twine(DirectoryEntryPathUTF8),
1034344779Sdim      file_type_from_attrs(FindData.dwFileAttributes),
1035344779Sdim      status_from_find_data(&FindData));
1036276479Sdim  return std::error_code();
1037218885Sdim}
1038218885Sdim
1039327952SdimErrorOr<basic_file_status> directory_entry::status() const {
1040327952Sdim  return Status;
1041321369Sdim}
1042321369Sdim
1043341825Sdimstatic std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1044341825Sdim                                      OpenFlags Flags) {
1045341825Sdim  int CrtOpenFlags = 0;
1046341825Sdim  if (Flags & OF_Append)
1047341825Sdim    CrtOpenFlags |= _O_APPEND;
1048321369Sdim
1049341825Sdim  if (Flags & OF_Text)
1050341825Sdim    CrtOpenFlags |= _O_TEXT;
1051321369Sdim
1052341825Sdim  ResultFD = -1;
1053341825Sdim  if (!H)
1054341825Sdim    return errorToErrorCode(H.takeError());
1055341825Sdim
1056341825Sdim  ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1057341825Sdim  if (ResultFD == -1) {
1058341825Sdim    ::CloseHandle(*H);
1059341825Sdim    return mapWindowsError(ERROR_INVALID_HANDLE);
1060341825Sdim  }
1061341825Sdim  return std::error_code();
1062321369Sdim}
1063321369Sdim
1064341825Sdimstatic DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1065341825Sdim  // This is a compatibility hack.  Really we should respect the creation
1066341825Sdim  // disposition, but a lot of old code relied on the implicit assumption that
1067341825Sdim  // OF_Append implied it would open an existing file.  Since the disposition is
1068341825Sdim  // now explicit and defaults to CD_CreateAlways, this assumption would cause
1069341825Sdim  // any usage of OF_Append to append to a new file, even if the file already
1070341825Sdim  // existed.  A better solution might have two new creation dispositions:
1071341825Sdim  // CD_AppendAlways and CD_AppendNew.  This would also address the problem of
1072341825Sdim  // OF_Append being used on a read-only descriptor, which doesn't make sense.
1073341825Sdim  if (Flags & OF_Append)
1074341825Sdim    return OPEN_ALWAYS;
1075341825Sdim
1076341825Sdim  switch (Disp) {
1077341825Sdim  case CD_CreateAlways:
1078341825Sdim    return CREATE_ALWAYS;
1079341825Sdim  case CD_CreateNew:
1080341825Sdim    return CREATE_NEW;
1081341825Sdim  case CD_OpenAlways:
1082341825Sdim    return OPEN_ALWAYS;
1083341825Sdim  case CD_OpenExisting:
1084341825Sdim    return OPEN_EXISTING;
1085341825Sdim  }
1086341825Sdim  llvm_unreachable("unreachable!");
1087341825Sdim}
1088341825Sdim
1089341825Sdimstatic DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1090341825Sdim  DWORD Result = 0;
1091341825Sdim  if (Access & FA_Read)
1092341825Sdim    Result |= GENERIC_READ;
1093341825Sdim  if (Access & FA_Write)
1094341825Sdim    Result |= GENERIC_WRITE;
1095341825Sdim  if (Flags & OF_Delete)
1096341825Sdim    Result |= DELETE;
1097341825Sdim  if (Flags & OF_UpdateAtime)
1098341825Sdim    Result |= FILE_WRITE_ATTRIBUTES;
1099341825Sdim  return Result;
1100341825Sdim}
1101341825Sdim
1102341825Sdimstatic std::error_code openNativeFileInternal(const Twine &Name,
1103341825Sdim                                              file_t &ResultFile, DWORD Disp,
1104341825Sdim                                              DWORD Access, DWORD Flags,
1105341825Sdim                                              bool Inherit = false) {
1106261991Sdim  SmallVector<wchar_t, 128> PathUTF16;
1107280031Sdim  if (std::error_code EC = widenPath(Name, PathUTF16))
1108261991Sdim    return EC;
1109218885Sdim
1110341825Sdim  SECURITY_ATTRIBUTES SA;
1111341825Sdim  SA.nLength = sizeof(SA);
1112341825Sdim  SA.lpSecurityDescriptor = nullptr;
1113341825Sdim  SA.bInheritHandle = Inherit;
1114341825Sdim
1115296417Sdim  HANDLE H =
1116341825Sdim      ::CreateFileW(PathUTF16.begin(), Access,
1117341825Sdim                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1118341825Sdim                    Disp, Flags, NULL);
1119261991Sdim  if (H == INVALID_HANDLE_VALUE) {
1120276479Sdim    DWORD LastError = ::GetLastError();
1121288943Sdim    std::error_code EC = mapWindowsError(LastError);
1122261991Sdim    // Provide a better error message when trying to open directories.
1123261991Sdim    // This only runs if we failed to open the file, so there is probably
1124261991Sdim    // no performances issues.
1125276479Sdim    if (LastError != ERROR_ACCESS_DENIED)
1126261991Sdim      return EC;
1127261991Sdim    if (is_directory(Name))
1128276479Sdim      return make_error_code(errc::is_a_directory);
1129261991Sdim    return EC;
1130218885Sdim  }
1131341825Sdim  ResultFile = H;
1132276479Sdim  return std::error_code();
1133218885Sdim}
1134218885Sdim
1135341825SdimExpected openNativeFile(const Twine &Name, CreationDisposition Disp,
1136341825Sdim                                FileAccess Access, OpenFlags Flags,
1137341825Sdim                                unsigned Mode) {
1138261991Sdim  // Verify that we don't have both "append" and "excl".
1139341825Sdim  assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1140341825Sdim         "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1141218885Sdim
1142341825Sdim  DWORD NativeDisp = nativeDisposition(Disp, Flags);
1143341825Sdim  DWORD NativeAccess = nativeAccess(Access, Flags);
1144218885Sdim
1145341825Sdim  bool Inherit = false;
1146341825Sdim  if (Flags & OF_ChildInherit)
1147341825Sdim    Inherit = true;
1148218885Sdim
1149341825Sdim  file_t Result;
1150341825Sdim  std::error_code EC = openNativeFileInternal(
1151341825Sdim      Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1152341825Sdim  if (EC)
1153341825Sdim    return errorCodeToError(EC);
1154261991Sdim
1155341825Sdim  if (Flags & OF_UpdateAtime) {
1156341825Sdim    FILETIME FileTime;
1157341825Sdim    SYSTEMTIME SystemTime;
1158341825Sdim    GetSystemTime(&SystemTime);
1159341825Sdim    if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1160341825Sdim        SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1161341825Sdim      DWORD LastError = ::GetLastError();
1162341825Sdim      ::CloseHandle(Result);
1163341825Sdim      return errorCodeToError(mapWindowsError(LastError));
1164341825Sdim    }
1165327952Sdim  }
1166276479Sdim
1167341825Sdim  if (Flags & OF_Delete) {
1168341825Sdim    if ((EC = setDeleteDisposition(Result, true))) {
1169341825Sdim      ::CloseHandle(Result);
1170341825Sdim      return errorCodeToError(EC);
1171341825Sdim    }
1172341825Sdim  }
1173341825Sdim  return Result;
1174341825Sdim}
1175261991Sdim
1176341825Sdimstd::error_code openFile(const Twine &Name, int &ResultFD,
1177341825Sdim                         CreationDisposition Disp, FileAccess Access,
1178341825Sdim                         OpenFlags Flags, unsigned int Mode) {
1179341825Sdim  Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1180341825Sdim  if (!Result)
1181341825Sdim    return errorToErrorCode(Result.takeError());
1182341825Sdim
1183341825Sdim  return nativeFileToFd(*Result, ResultFD, Flags);
1184341825Sdim}
1185341825Sdim
1186341825Sdimstatic std::error_code directoryRealPath(const Twine &Name,
1187341825Sdim                                         SmallVectorImpl<char> &RealPath) {
1188341825Sdim  file_t File;
1189341825Sdim  std::error_code EC = openNativeFileInternal(
1190341825Sdim      Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1191341825Sdim  if (EC)
1192261991Sdim    return EC;
1193218885Sdim
1194341825Sdim  EC = realPathFromHandle(File, RealPath);
1195341825Sdim  ::CloseHandle(File);
1196341825Sdim  return EC;
1197341825Sdim}
1198218885Sdim
1199341825Sdimstd::error_code openFileForRead(const Twine &Name, int &ResultFD,
1200341825Sdim                                OpenFlags Flags,
1201341825Sdim                                SmallVectorImpl<char> *RealPath) {
1202341825Sdim  Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1203341825Sdim  return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1204341825Sdim}
1205218885Sdim
1206341825SdimExpected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1207341825Sdim                                       SmallVectorImpl<char> *RealPath) {
1208341825Sdim  Expected<file_t> Result =
1209341825Sdim      openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1210218885Sdim
1211341825Sdim  // Fetch the real name of the file, if the user asked
1212341825Sdim  if (Result && RealPath)
1213341825Sdim    realPathFromHandle(*Result, *RealPath);
1214341825Sdim
1215341825Sdim  return Result;
1216218885Sdim}
1217309124Sdim
1218353358Sdimfile_t convertFDToNativeFile(int FD) {
1219353358Sdim  return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1220353358Sdim}
1221353358Sdim
1222353358Sdimfile_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1223353358Sdimfile_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1224353358Sdimfile_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1225353358Sdim
1226360784SdimExpected<size_t> readNativeFileImpl(file_t FileHandle,
1227360784Sdim                                    MutableArrayRef<char> Buf,
1228360784Sdim                                    OVERLAPPED *Overlap) {
1229353358Sdim  // ReadFile can only read 2GB at a time. The caller should check the number of
1230353358Sdim  // bytes and read in a loop until termination.
1231360784Sdim  DWORD BytesToRead =
1232360784Sdim      std::min(size_t(std::numeric_limits<DWORD>::max()), Buf.size());
1233360784Sdim  DWORD BytesRead = 0;
1234360784Sdim  if (::ReadFile(FileHandle, Buf.data(), BytesToRead, &BytesRead, Overlap))
1235360784Sdim    return BytesRead;
1236360784Sdim  DWORD Err = ::GetLastError();
1237360784Sdim  // EOF is not an error.
1238360784Sdim  if (Err == ERROR_BROKEN_PIPE || Err == ERROR_HANDLE_EOF)
1239360784Sdim    return BytesRead;
1240360784Sdim  return errorCodeToError(mapWindowsError(Err));
1241353358Sdim}
1242353358Sdim
1243360784SdimExpected<size_t> readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf) {
1244360784Sdim  return readNativeFileImpl(FileHandle, Buf, /*Overlap=*/nullptr);
1245353358Sdim}
1246353358Sdim
1247360784SdimExpected<size_t> readNativeFileSlice(file_t FileHandle,
1248360784Sdim                                     MutableArrayRef<char> Buf,
1249360784Sdim                                     uint64_t Offset) {
1250360784Sdim  OVERLAPPED Overlapped = {};
1251360784Sdim  Overlapped.Offset = uint32_t(Offset);
1252360784Sdim  Overlapped.OffsetHigh = uint32_t(Offset >> 32);
1253360784Sdim  return readNativeFileImpl(FileHandle, Buf, &Overlapped);
1254353358Sdim}
1255353358Sdim
1256353358Sdimstd::error_code closeFile(file_t &F) {
1257353358Sdim  file_t TmpF = F;
1258341825Sdim  F = kInvalidFile;
1259353358Sdim  if (!::CloseHandle(TmpF))
1260353358Sdim    return mapWindowsError(::GetLastError());
1261353358Sdim  return std::error_code();
1262341825Sdim}
1263341825Sdim
1264321369Sdimstd::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1265321369Sdim  // Convert to utf-16.
1266321369Sdim  SmallVector<wchar_t, 128> Path16;
1267321369Sdim  std::error_code EC = widenPath(path, Path16);
1268321369Sdim  if (EC && !IgnoreErrors)
1269321369Sdim    return EC;
1270321369Sdim
1271321369Sdim  // SHFileOperation() accepts a list of paths, and so must be double null-
1272321369Sdim  // terminated to indicate the end of the list.  The buffer is already null
1273321369Sdim  // terminated, but since that null character is not considered part of the
1274321369Sdim  // vector's size, pushing another one will just consume that byte.  So we
1275321369Sdim  // need to push 2 null terminators.
1276321369Sdim  Path16.push_back(0);
1277321369Sdim  Path16.push_back(0);
1278321369Sdim
1279321369Sdim  SHFILEOPSTRUCTW shfos = {};
1280321369Sdim  shfos.wFunc = FO_DELETE;
1281321369Sdim  shfos.pFrom = Path16.data();
1282321369Sdim  shfos.fFlags = FOF_NO_UI;
1283321369Sdim
1284321369Sdim  int result = ::SHFileOperationW(&shfos);
1285321369Sdim  if (result != 0 && !IgnoreErrors)
1286321369Sdim    return mapWindowsError(result);
1287321369Sdim  return std::error_code();
1288321369Sdim}
1289321369Sdim
1290321369Sdimstatic void expandTildeExpr(SmallVectorImpl<char> &Path) {
1291321369Sdim  // Path does not begin with a tilde expression.
1292321369Sdim  if (Path.empty() || Path[0] != '~')
1293321369Sdim    return;
1294321369Sdim
1295321369Sdim  StringRef PathStr(Path.begin(), Path.size());
1296321369Sdim  PathStr = PathStr.drop_front();
1297321369Sdim  StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1298321369Sdim
1299321369Sdim  if (!Expr.empty()) {
1300321369Sdim    // This is probably a ~username/ expression.  Don't support this on Windows.
1301321369Sdim    return;
1302321369Sdim  }
1303321369Sdim
1304321369Sdim  SmallString<128> HomeDir;
1305321369Sdim  if (!path::home_directory(HomeDir)) {
1306321369Sdim    // For some reason we couldn't get the home directory.  Just exit.
1307321369Sdim    return;
1308321369Sdim  }
1309321369Sdim
1310321369Sdim  // Overwrite the first character and insert the rest.
1311321369Sdim  Path[0] = HomeDir[0];
1312321369Sdim  Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1313321369Sdim}
1314321369Sdim
1315344779Sdimvoid expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1316344779Sdim  dest.clear();
1317344779Sdim  if (path.isTriviallyEmpty())
1318344779Sdim    return;
1319344779Sdim
1320344779Sdim  path.toVector(dest);
1321344779Sdim  expandTildeExpr(dest);
1322344779Sdim
1323344779Sdim  return;
1324344779Sdim}
1325344779Sdim
1326321369Sdimstd::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1327321369Sdim                          bool expand_tilde) {
1328321369Sdim  dest.clear();
1329321369Sdim  if (path.isTriviallyEmpty())
1330321369Sdim    return std::error_code();
1331321369Sdim
1332321369Sdim  if (expand_tilde) {
1333321369Sdim    SmallString<128> Storage;
1334321369Sdim    path.toVector(Storage);
1335321369Sdim    expandTildeExpr(Storage);
1336321369Sdim    return real_path(Storage, dest, false);
1337321369Sdim  }
1338321369Sdim
1339321369Sdim  if (is_directory(path))
1340321369Sdim    return directoryRealPath(path, dest);
1341321369Sdim
1342321369Sdim  int fd;
1343341825Sdim  if (std::error_code EC =
1344341825Sdim          llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1345321369Sdim    return EC;
1346321369Sdim  ::close(fd);
1347321369Sdim  return std::error_code();
1348321369Sdim}
1349321369Sdim
1350261991Sdim} // end namespace fs
1351218885Sdim
1352276479Sdimnamespace path {
1353296417Sdimstatic bool getKnownFolderPath(KNOWNFOLDERID folderId,
1354296417Sdim                               SmallVectorImpl<char> &result) {
1355296417Sdim  wchar_t *path = nullptr;
1356296417Sdim  if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1357276479Sdim    return false;
1358276479Sdim
1359296417Sdim  bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1360296417Sdim  ::CoTaskMemFree(path);
1361296417Sdim  return ok;
1362296417Sdim}
1363276479Sdim
1364296417Sdimbool home_directory(SmallVectorImpl<char> &result) {
1365296417Sdim  return getKnownFolderPath(FOLDERID_Profile, result);
1366296417Sdim}
1367280031Sdim
1368296417Sdimstatic bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1369280031Sdim  SmallVector<wchar_t, 1024> Buf;
1370280031Sdim  size_t Size = 1024;
1371280031Sdim  do {
1372280031Sdim    Buf.reserve(Size);
1373296417Sdim    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1374280031Sdim    if (Size == 0)
1375280031Sdim      return false;
1376280031Sdim
1377280031Sdim    // Try again with larger buffer.
1378280031Sdim  } while (Size > Buf.capacity());
1379280031Sdim  Buf.set_size(Size);
1380280031Sdim
1381296417Sdim  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1382280031Sdim}
1383280031Sdim
1384280031Sdimstatic bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1385296417Sdim  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1386296417Sdim  for (auto *Env : EnvironmentVariables) {
1387280031Sdim    if (getTempDirEnvVar(Env, Res))
1388280031Sdim      return true;
1389280031Sdim  }
1390280031Sdim  return false;
1391280031Sdim}
1392280031Sdim
1393280031Sdimvoid system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1394280031Sdim  (void)ErasedOnReboot;
1395280031Sdim  Result.clear();
1396280031Sdim
1397296417Sdim  // Check whether the temporary directory is specified by an environment var.
1398296417Sdim  // This matches GetTempPath logic to some degree. GetTempPath is not used
1399296417Sdim  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1400296417Sdim  // (fixed on Windows 8).
1401296417Sdim  if (getTempDirEnvVar(Result)) {
1402296417Sdim    assert(!Result.empty() && "Unexpected empty path");
1403296417Sdim    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1404296417Sdim    fs::make_absolute(Result); // Make it absolute if not already.
1405280031Sdim    return;
1406296417Sdim  }
1407280031Sdim
1408280031Sdim  // Fall back to a system default.
1409296417Sdim  const char *DefaultResult = "C:\\Temp";
1410280031Sdim  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1411280031Sdim}
1412276479Sdim} // end namespace path
1413276479Sdim
1414261991Sdimnamespace windows {
1415341825Sdimstd::error_code CodePageToUTF16(unsigned codepage,
1416341825Sdim                                llvm::StringRef original,
1417341825Sdim                                llvm::SmallVectorImpl<wchar_t> &utf16) {
1418341825Sdim  if (!original.empty()) {
1419341825Sdim    int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1420341825Sdim                                    original.size(), utf16.begin(), 0);
1421261991Sdim
1422341825Sdim    if (len == 0) {
1423288943Sdim      return mapWindowsError(::GetLastError());
1424341825Sdim    }
1425261991Sdim
1426276479Sdim    utf16.reserve(len + 1);
1427276479Sdim    utf16.set_size(len);
1428261991Sdim
1429341825Sdim    len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1430341825Sdim                                original.size(), utf16.begin(), utf16.size());
1431261991Sdim
1432341825Sdim    if (len == 0) {
1433288943Sdim      return mapWindowsError(::GetLastError());
1434341825Sdim    }
1435276479Sdim  }
1436261991Sdim
1437261991Sdim  // Make utf16 null terminated.
1438261991Sdim  utf16.push_back(0);
1439261991Sdim  utf16.pop_back();
1440261991Sdim
1441276479Sdim  return std::error_code();
1442218885Sdim}
1443218885Sdim
1444341825Sdimstd::error_code UTF8ToUTF16(llvm::StringRef utf8,
1445341825Sdim                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1446341825Sdim  return CodePageToUTF16(CP_UTF8, utf8, utf16);
1447341825Sdim}
1448341825Sdim
1449341825Sdimstd::error_code CurCPToUTF16(llvm::StringRef curcp,
1450341825Sdim                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1451341825Sdim  return CodePageToUTF16(CP_ACP, curcp, utf16);
1452341825Sdim}
1453341825Sdim
1454280031Sdimstatic
1455280031Sdimstd::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1456280031Sdim                                size_t utf16_len,
1457341825Sdim                                llvm::SmallVectorImpl<char> &converted) {
1458276479Sdim  if (utf16_len) {
1459276479Sdim    // Get length.
1460341825Sdim    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
1461276479Sdim                                    0, NULL, NULL);
1462261991Sdim
1463341825Sdim    if (len == 0) {
1464288943Sdim      return mapWindowsError(::GetLastError());
1465341825Sdim    }
1466261991Sdim
1467341825Sdim    converted.reserve(len);
1468341825Sdim    converted.set_size(len);
1469261991Sdim
1470276479Sdim    // Now do the actual conversion.
1471341825Sdim    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1472341825Sdim                                converted.size(), NULL, NULL);
1473261991Sdim
1474341825Sdim    if (len == 0) {
1475288943Sdim      return mapWindowsError(::GetLastError());
1476341825Sdim    }
1477276479Sdim  }
1478261991Sdim
1479341825Sdim  // Make the new string null terminated.
1480341825Sdim  converted.push_back(0);
1481341825Sdim  converted.pop_back();
1482261991Sdim
1483276479Sdim  return std::error_code();
1484218885Sdim}
1485280031Sdim
1486280031Sdimstd::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1487280031Sdim                            llvm::SmallVectorImpl<char> &utf8) {
1488280031Sdim  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1489280031Sdim}
1490280031Sdim
1491280031Sdimstd::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1492341825Sdim                             llvm::SmallVectorImpl<char> &curcp) {
1493341825Sdim  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1494280031Sdim}
1495309124Sdim
1496261991Sdim} // end namespace windows
1497261991Sdim} // end namespace sys
1498261991Sdim} // end namespace llvm
1499