Path.inc revision 353358
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
28276479Sdim#include "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
374327952Sdim  const wchar_t *Data = Buffer.data();
375327952Sdim  DWORD CountChars = Buffer.size();
376327952Sdim  if (CountChars >= 4) {
377327952Sdim    if (0 == ::memcmp(Data, L"\\\\?\\", 8)) {
378327952Sdim      CountChars -= 4;
379327952Sdim      Data += 4;
380327952Sdim    }
381327952Sdim  }
382327952Sdim
383327952Sdim  // Convert the result from UTF-16 to UTF-8.
384327952Sdim  return UTF16ToUTF8(Data, CountChars, RealPath);
385327952Sdim}
386327952Sdim
387321369Sdimstd::error_code is_local(int FD, bool &Result) {
388321369Sdim  SmallVector<wchar_t, 128> FinalPath;
389321369Sdim  HANDLE Handle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
390321369Sdim
391327952Sdim  if (std::error_code EC = realPathFromHandle(Handle, FinalPath))
392327952Sdim    return EC;
393321369Sdim
394321369Sdim  return is_local_internal(FinalPath, Result);
395321369Sdim}
396321369Sdim
397327952Sdimstatic std::error_code setDeleteDisposition(HANDLE Handle, bool Delete) {
398327952Sdim  FILE_DISPOSITION_INFO Disposition;
399327952Sdim  Disposition.DeleteFile = Delete;
400327952Sdim  if (!SetFileInformationByHandle(Handle, FileDispositionInfo, &Disposition,
401327952Sdim                                  sizeof(Disposition)))
402327952Sdim    return mapWindowsError(::GetLastError());
403327952Sdim  return std::error_code();
404327952Sdim}
405261991Sdim
406327952Sdimstatic std::error_code rename_internal(HANDLE FromHandle, const Twine &To,
407327952Sdim                                       bool ReplaceIfExists) {
408327952Sdim  SmallVector<wchar_t, 0> ToWide;
409327952Sdim  if (auto EC = widenPath(To, ToWide))
410327952Sdim    return EC;
411327952Sdim
412327952Sdim  std::vector<char> RenameInfoBuf(sizeof(FILE_RENAME_INFO) - sizeof(wchar_t) +
413327952Sdim                                  (ToWide.size() * sizeof(wchar_t)));
414327952Sdim  FILE_RENAME_INFO &RenameInfo =
415327952Sdim      *reinterpret_cast<FILE_RENAME_INFO *>(RenameInfoBuf.data());
416327952Sdim  RenameInfo.ReplaceIfExists = ReplaceIfExists;
417327952Sdim  RenameInfo.RootDirectory = 0;
418344779Sdim  RenameInfo.FileNameLength = ToWide.size() * sizeof(wchar_t);
419327952Sdim  std::copy(ToWide.begin(), ToWide.end(), &RenameInfo.FileName[0]);
420327952Sdim
421327952Sdim  SetLastError(ERROR_SUCCESS);
422327952Sdim  if (!SetFileInformationByHandle(FromHandle, FileRenameInfo, &RenameInfo,
423327952Sdim                                  RenameInfoBuf.size())) {
424327952Sdim    unsigned Error = GetLastError();
425327952Sdim    if (Error == ERROR_SUCCESS)
426327952Sdim      Error = ERROR_CALL_NOT_IMPLEMENTED; // Wine doesn't always set error code.
427327952Sdim    return mapWindowsError(Error);
428327952Sdim  }
429327952Sdim
430327952Sdim  return std::error_code();
431327952Sdim}
432327952Sdim
433327952Sdimstatic std::error_code rename_handle(HANDLE FromHandle, const Twine &To) {
434327952Sdim  SmallVector<wchar_t, 128> WideTo;
435327952Sdim  if (std::error_code EC = widenPath(To, WideTo))
436327952Sdim    return EC;
437327952Sdim
438327952Sdim  // We normally expect this loop to succeed after a few iterations. If it
439327952Sdim  // requires more than 200 tries, it's more likely that the failures are due to
440327952Sdim  // a true error, so stop trying.
441327952Sdim  for (unsigned Retry = 0; Retry != 200; ++Retry) {
442327952Sdim    auto EC = rename_internal(FromHandle, To, true);
443327952Sdim
444327952Sdim    if (EC ==
445327952Sdim        std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category())) {
446327952Sdim      // Wine doesn't support SetFileInformationByHandle in rename_internal.
447327952Sdim      // Fall back to MoveFileEx.
448327952Sdim      SmallVector<wchar_t, MAX_PATH> WideFrom;
449327952Sdim      if (std::error_code EC2 = realPathFromHandle(FromHandle, WideFrom))
450327952Sdim        return EC2;
451327952Sdim      if (::MoveFileExW(WideFrom.begin(), WideTo.begin(),
452327952Sdim                        MOVEFILE_REPLACE_EXISTING))
453309124Sdim        return std::error_code();
454327952Sdim      return mapWindowsError(GetLastError());
455327952Sdim    }
456296417Sdim
457327952Sdim    if (!EC || EC != errc::permission_denied)
458327952Sdim      return EC;
459309124Sdim
460327952Sdim    // The destination file probably exists and is currently open in another
461327952Sdim    // process, either because the file was opened without FILE_SHARE_DELETE or
462327952Sdim    // it is mapped into memory (e.g. using MemoryBuffer). Rename it in order to
463327952Sdim    // move it out of the way of the source file. Use FILE_FLAG_DELETE_ON_CLOSE
464327952Sdim    // to arrange for the destination file to be deleted when the other process
465327952Sdim    // closes it.
466327952Sdim    ScopedFileHandle ToHandle(
467327952Sdim        ::CreateFileW(WideTo.begin(), GENERIC_READ | DELETE,
468327952Sdim                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
469327952Sdim                      NULL, OPEN_EXISTING,
470327952Sdim                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL));
471327952Sdim    if (!ToHandle) {
472327952Sdim      auto EC = mapWindowsError(GetLastError());
473327952Sdim      // Another process might have raced with us and moved the existing file
474327952Sdim      // out of the way before we had a chance to open it. If that happens, try
475327952Sdim      // to rename the source file again.
476327952Sdim      if (EC == errc::no_such_file_or_directory)
477309124Sdim        continue;
478327952Sdim      return EC;
479327952Sdim    }
480327952Sdim
481327952Sdim    BY_HANDLE_FILE_INFORMATION FI;
482327952Sdim    if (!GetFileInformationByHandle(ToHandle, &FI))
483327952Sdim      return mapWindowsError(GetLastError());
484327952Sdim
485327952Sdim    // Try to find a unique new name for the destination file.
486327952Sdim    for (unsigned UniqueId = 0; UniqueId != 200; ++UniqueId) {
487327952Sdim      std::string TmpFilename = (To + ".tmp" + utostr(UniqueId)).str();
488327952Sdim      if (auto EC = rename_internal(ToHandle, TmpFilename, false)) {
489327952Sdim        if (EC == errc::file_exists || EC == errc::permission_denied) {
490327952Sdim          // Again, another process might have raced with us and moved the file
491327952Sdim          // before we could move it. Check whether this is the case, as it
492327952Sdim          // might have caused the permission denied error. If that was the
493327952Sdim          // case, we don't need to move it ourselves.
494327952Sdim          ScopedFileHandle ToHandle2(::CreateFileW(
495327952Sdim              WideTo.begin(), 0,
496327952Sdim              FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
497327952Sdim              OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
498327952Sdim          if (!ToHandle2) {
499327952Sdim            auto EC = mapWindowsError(GetLastError());
500327952Sdim            if (EC == errc::no_such_file_or_directory)
501327952Sdim              break;
502327952Sdim            return EC;
503327952Sdim          }
504327952Sdim          BY_HANDLE_FILE_INFORMATION FI2;
505327952Sdim          if (!GetFileInformationByHandle(ToHandle2, &FI2))
506327952Sdim            return mapWindowsError(GetLastError());
507327952Sdim          if (FI.nFileIndexHigh != FI2.nFileIndexHigh ||
508327952Sdim              FI.nFileIndexLow != FI2.nFileIndexLow ||
509327952Sdim              FI.dwVolumeSerialNumber != FI2.dwVolumeSerialNumber)
510327952Sdim            break;
511327952Sdim          continue;
512327952Sdim        }
513327952Sdim        return EC;
514309124Sdim      }
515327952Sdim      break;
516309124Sdim    }
517309124Sdim
518327952Sdim    // Okay, the old destination file has probably been moved out of the way at
519327952Sdim    // this point, so try to rename the source file again. Still, another
520327952Sdim    // process might have raced with us to create and open the destination
521327952Sdim    // file, so we need to keep doing this until we succeed.
522327952Sdim  }
523296417Sdim
524327952Sdim  // The most likely root cause.
525327952Sdim  return errc::permission_denied;
526327952Sdim}
527327952Sdim
528327952Sdimstatic std::error_code rename_fd(int FromFD, const Twine &To) {
529327952Sdim  HANDLE FromHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FromFD));
530327952Sdim  return rename_handle(FromHandle, To);
531327952Sdim}
532327952Sdim
533327952Sdimstd::error_code rename(const Twine &From, const Twine &To) {
534327952Sdim  // Convert to utf-16.
535327952Sdim  SmallVector<wchar_t, 128> WideFrom;
536327952Sdim  if (std::error_code EC = widenPath(From, WideFrom))
537327952Sdim    return EC;
538327952Sdim
539327952Sdim  ScopedFileHandle FromHandle;
540327952Sdim  // Retry this a few times to defeat badly behaved file system scanners.
541327952Sdim  for (unsigned Retry = 0; Retry != 200; ++Retry) {
542327952Sdim    if (Retry != 0)
543327952Sdim      ::Sleep(10);
544327952Sdim    FromHandle =
545327952Sdim        ::CreateFileW(WideFrom.begin(), GENERIC_READ | DELETE,
546327952Sdim                      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
547327952Sdim                      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
548327952Sdim    if (FromHandle)
549327952Sdim      break;
550261991Sdim  }
551327952Sdim  if (!FromHandle)
552327952Sdim    return mapWindowsError(GetLastError());
553261991Sdim
554327952Sdim  return rename_handle(FromHandle, To);
555218885Sdim}
556218885Sdim
557280031Sdimstd::error_code resize_file(int FD, uint64_t Size) {
558261991Sdim#ifdef HAVE__CHSIZE_S
559280031Sdim  errno_t error = ::_chsize_s(FD, Size);
560261991Sdim#else
561280031Sdim  errno_t error = ::_chsize(FD, Size);
562261991Sdim#endif
563276479Sdim  return std::error_code(error, std::generic_category());
564218885Sdim}
565218885Sdim
566280031Sdimstd::error_code access(const Twine &Path, AccessMode Mode) {
567280031Sdim  SmallVector<wchar_t, 128> PathUtf16;
568218885Sdim
569280031Sdim  if (std::error_code EC = widenPath(Path, PathUtf16))
570280031Sdim    return EC;
571218885Sdim
572280031Sdim  DWORD Attributes = ::GetFileAttributesW(PathUtf16.begin());
573218885Sdim
574280031Sdim  if (Attributes == INVALID_FILE_ATTRIBUTES) {
575261991Sdim    // See if the file didn't actually exist.
576276479Sdim    DWORD LastError = ::GetLastError();
577276479Sdim    if (LastError != ERROR_FILE_NOT_FOUND &&
578276479Sdim        LastError != ERROR_PATH_NOT_FOUND)
579288943Sdim      return mapWindowsError(LastError);
580280031Sdim    return errc::no_such_file_or_directory;
581280031Sdim  }
582218885Sdim
583280031Sdim  if (Mode == AccessMode::Write && (Attributes & FILE_ATTRIBUTE_READONLY))
584280031Sdim    return errc::permission_denied;
585218885Sdim
586280031Sdim  return std::error_code();
587261991Sdim}
588218885Sdim
589296417Sdimbool can_execute(const Twine &Path) {
590296417Sdim  return !access(Path, AccessMode::Execute) ||
591296417Sdim         !access(Path + ".exe", AccessMode::Execute);
592296417Sdim}
593296417Sdim
594261991Sdimbool equivalent(file_status A, file_status B) {
595261991Sdim  assert(status_known(A) && status_known(B));
596309124Sdim  return A.FileIndexHigh         == B.FileIndexHigh &&
597309124Sdim         A.FileIndexLow          == B.FileIndexLow &&
598309124Sdim         A.FileSizeHigh          == B.FileSizeHigh &&
599309124Sdim         A.FileSizeLow           == B.FileSizeLow &&
600309124Sdim         A.LastAccessedTimeHigh  == B.LastAccessedTimeHigh &&
601309124Sdim         A.LastAccessedTimeLow   == B.LastAccessedTimeLow &&
602309124Sdim         A.LastWriteTimeHigh     == B.LastWriteTimeHigh &&
603309124Sdim         A.LastWriteTimeLow      == B.LastWriteTimeLow &&
604309124Sdim         A.VolumeSerialNumber    == B.VolumeSerialNumber;
605218885Sdim}
606218885Sdim
607276479Sdimstd::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
608261991Sdim  file_status fsA, fsB;
609276479Sdim  if (std::error_code ec = status(A, fsA))
610276479Sdim    return ec;
611276479Sdim  if (std::error_code ec = status(B, fsB))
612276479Sdim    return ec;
613261991Sdim  result = equivalent(fsA, fsB);
614276479Sdim  return std::error_code();
615261991Sdim}
616218885Sdim
617261991Sdimstatic bool isReservedName(StringRef path) {
618261991Sdim  // This list of reserved names comes from MSDN, at:
619261991Sdim  // http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
620296417Sdim  static const char *const sReservedNames[] = { "nul", "con", "prn", "aux",
621296417Sdim                                                "com1", "com2", "com3", "com4",
622296417Sdim                                                "com5", "com6", "com7", "com8",
623296417Sdim                                                "com9", "lpt1", "lpt2", "lpt3",
624296417Sdim                                                "lpt4", "lpt5", "lpt6", "lpt7",
625296417Sdim                                                "lpt8", "lpt9" };
626218885Sdim
627261991Sdim  // First, check to see if this is a device namespace, which always
628261991Sdim  // starts with \\.\, since device namespaces are not legal file paths.
629261991Sdim  if (path.startswith("\\\\.\\"))
630261991Sdim    return true;
631261991Sdim
632309124Sdim  // Then compare against the list of ancient reserved names.
633261991Sdim  for (size_t i = 0; i < array_lengthof(sReservedNames); ++i) {
634261991Sdim    if (path.equals_lower(sReservedNames[i]))
635218885Sdim      return true;
636218885Sdim  }
637218885Sdim
638261991Sdim  // The path isn't what we consider reserved.
639218885Sdim  return false;
640218885Sdim}
641218885Sdim
642327952Sdimstatic file_type file_type_from_attrs(DWORD Attrs) {
643327952Sdim  return (Attrs & FILE_ATTRIBUTE_DIRECTORY) ? file_type::directory_file
644327952Sdim                                            : file_type::regular_file;
645327952Sdim}
646327952Sdim
647327952Sdimstatic perms perms_from_attrs(DWORD Attrs) {
648327952Sdim  return (Attrs & FILE_ATTRIBUTE_READONLY) ? (all_read | all_exe) : all_all;
649327952Sdim}
650327952Sdim
651276479Sdimstatic std::error_code getStatus(HANDLE FileHandle, file_status &Result) {
652261991Sdim  if (FileHandle == INVALID_HANDLE_VALUE)
653261991Sdim    goto handle_status_error;
654261991Sdim
655261991Sdim  switch (::GetFileType(FileHandle)) {
656261991Sdim  default:
657261991Sdim    llvm_unreachable("Don't know anything about this file type");
658261991Sdim  case FILE_TYPE_UNKNOWN: {
659261991Sdim    DWORD Err = ::GetLastError();
660261991Sdim    if (Err != NO_ERROR)
661288943Sdim      return mapWindowsError(Err);
662261991Sdim    Result = file_status(file_type::type_unknown);
663276479Sdim    return std::error_code();
664218885Sdim  }
665261991Sdim  case FILE_TYPE_DISK:
666261991Sdim    break;
667261991Sdim  case FILE_TYPE_CHAR:
668261991Sdim    Result = file_status(file_type::character_file);
669276479Sdim    return std::error_code();
670261991Sdim  case FILE_TYPE_PIPE:
671261991Sdim    Result = file_status(file_type::fifo_file);
672276479Sdim    return std::error_code();
673261991Sdim  }
674218885Sdim
675261991Sdim  BY_HANDLE_FILE_INFORMATION Info;
676261991Sdim  if (!::GetFileInformationByHandle(FileHandle, &Info))
677261991Sdim    goto handle_status_error;
678261991Sdim
679327952Sdim  Result = file_status(
680327952Sdim      file_type_from_attrs(Info.dwFileAttributes),
681327952Sdim      perms_from_attrs(Info.dwFileAttributes), Info.nNumberOfLinks,
682327952Sdim      Info.ftLastAccessTime.dwHighDateTime, Info.ftLastAccessTime.dwLowDateTime,
683327952Sdim      Info.ftLastWriteTime.dwHighDateTime, Info.ftLastWriteTime.dwLowDateTime,
684327952Sdim      Info.dwVolumeSerialNumber, Info.nFileSizeHigh, Info.nFileSizeLow,
685327952Sdim      Info.nFileIndexHigh, Info.nFileIndexLow);
686327952Sdim  return std::error_code();
687218885Sdim
688261991Sdimhandle_status_error:
689276479Sdim  DWORD LastError = ::GetLastError();
690276479Sdim  if (LastError == ERROR_FILE_NOT_FOUND ||
691276479Sdim      LastError == ERROR_PATH_NOT_FOUND)
692261991Sdim    Result = file_status(file_type::file_not_found);
693276479Sdim  else if (LastError == ERROR_SHARING_VIOLATION)
694261991Sdim    Result = file_status(file_type::type_unknown);
695218885Sdim  else
696261991Sdim    Result = file_status(file_type::status_error);
697288943Sdim  return mapWindowsError(LastError);
698261991Sdim}
699218885Sdim
700321369Sdimstd::error_code status(const Twine &path, file_status &result, bool Follow) {
701261991Sdim  SmallString<128> path_storage;
702261991Sdim  SmallVector<wchar_t, 128> path_utf16;
703261991Sdim
704261991Sdim  StringRef path8 = path.toStringRef(path_storage);
705261991Sdim  if (isReservedName(path8)) {
706261991Sdim    result = file_status(file_type::character_file);
707276479Sdim    return std::error_code();
708218885Sdim  }
709218885Sdim
710280031Sdim  if (std::error_code ec = widenPath(path8, path_utf16))
711261991Sdim    return ec;
712218885Sdim
713261991Sdim  DWORD attr = ::GetFileAttributesW(path_utf16.begin());
714261991Sdim  if (attr == INVALID_FILE_ATTRIBUTES)
715261991Sdim    return getStatus(INVALID_HANDLE_VALUE, result);
716261991Sdim
717321369Sdim  DWORD Flags = FILE_FLAG_BACKUP_SEMANTICS;
718261991Sdim  // Handle reparse points.
719321369Sdim  if (!Follow && (attr & FILE_ATTRIBUTE_REPARSE_POINT))
720321369Sdim    Flags |= FILE_FLAG_OPEN_REPARSE_POINT;
721261991Sdim
722261991Sdim  ScopedFileHandle h(
723261991Sdim      ::CreateFileW(path_utf16.begin(), 0, // Attributes only.
724261991Sdim                    FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
725321369Sdim                    NULL, OPEN_EXISTING, Flags, 0));
726321369Sdim  if (!h)
727321369Sdim    return getStatus(INVALID_HANDLE_VALUE, result);
728261991Sdim
729321369Sdim  return getStatus(h, result);
730218885Sdim}
731218885Sdim
732276479Sdimstd::error_code status(int FD, file_status &Result) {
733261991Sdim  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
734261991Sdim  return getStatus(FileHandle, Result);
735261991Sdim}
736261991Sdim
737353358Sdimstd::error_code status(file_t FileHandle, file_status &Result) {
738353358Sdim  return getStatus(FileHandle, Result);
739353358Sdim}
740353358Sdim
741353358Sdimunsigned getUmask() {
742353358Sdim  return 0;
743353358Sdim}
744353358Sdim
745321369Sdimstd::error_code setPermissions(const Twine &Path, perms Permissions) {
746321369Sdim  SmallVector<wchar_t, 128> PathUTF16;
747321369Sdim  if (std::error_code EC = widenPath(Path, PathUTF16))
748321369Sdim    return EC;
749321369Sdim
750321369Sdim  DWORD Attributes = ::GetFileAttributesW(PathUTF16.begin());
751321369Sdim  if (Attributes == INVALID_FILE_ATTRIBUTES)
752321369Sdim    return mapWindowsError(GetLastError());
753321369Sdim
754321369Sdim  // There are many Windows file attributes that are not to do with the file
755321369Sdim  // permissions (e.g. FILE_ATTRIBUTE_HIDDEN). We need to be careful to preserve
756321369Sdim  // them.
757321369Sdim  if (Permissions & all_write) {
758321369Sdim    Attributes &= ~FILE_ATTRIBUTE_READONLY;
759321369Sdim    if (Attributes == 0)
760321369Sdim      // FILE_ATTRIBUTE_NORMAL indicates no other attributes are set.
761321369Sdim      Attributes |= FILE_ATTRIBUTE_NORMAL;
762321369Sdim  }
763321369Sdim  else {
764321369Sdim    Attributes |= FILE_ATTRIBUTE_READONLY;
765321369Sdim    // FILE_ATTRIBUTE_NORMAL is not compatible with any other attributes, so
766321369Sdim    // remove it, if it is present.
767321369Sdim    Attributes &= ~FILE_ATTRIBUTE_NORMAL;
768321369Sdim  }
769321369Sdim
770321369Sdim  if (!::SetFileAttributesW(PathUTF16.begin(), Attributes))
771321369Sdim    return mapWindowsError(GetLastError());
772321369Sdim
773321369Sdim  return std::error_code();
774321369Sdim}
775321369Sdim
776353358Sdimstd::error_code setPermissions(int FD, perms Permissions) {
777353358Sdim  // FIXME Not implemented.
778353358Sdim  return std::make_error_code(std::errc::not_supported);
779353358Sdim}
780353358Sdim
781344779Sdimstd::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
782344779Sdim                                                 TimePoint<> ModificationTime) {
783344779Sdim  FILETIME AccessFT = toFILETIME(AccessTime);
784344779Sdim  FILETIME ModifyFT = toFILETIME(ModificationTime);
785261991Sdim  HANDLE FileHandle = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
786344779Sdim  if (!SetFileTime(FileHandle, NULL, &AccessFT, &ModifyFT))
787288943Sdim    return mapWindowsError(::GetLastError());
788276479Sdim  return std::error_code();
789261991Sdim}
790261991Sdim
791353358Sdimstd::error_code mapped_file_region::init(sys::fs::file_t OrigFileHandle,
792353358Sdim                                         uint64_t Offset, mapmode Mode) {
793341825Sdim  this->Mode = Mode;
794341825Sdim  if (OrigFileHandle == INVALID_HANDLE_VALUE)
795280031Sdim    return make_error_code(errc::bad_file_descriptor);
796280031Sdim
797261991Sdim  DWORD flprotect;
798261991Sdim  switch (Mode) {
799261991Sdim  case readonly:  flprotect = PAGE_READONLY; break;
800261991Sdim  case readwrite: flprotect = PAGE_READWRITE; break;
801261991Sdim  case priv:      flprotect = PAGE_WRITECOPY; break;
802218885Sdim  }
803218885Sdim
804280031Sdim  HANDLE FileMappingHandle =
805341825Sdim      ::CreateFileMappingW(OrigFileHandle, 0, flprotect,
806327952Sdim                           Hi_32(Size),
807327952Sdim                           Lo_32(Size),
808261991Sdim                           0);
809261991Sdim  if (FileMappingHandle == NULL) {
810288943Sdim    std::error_code ec = mapWindowsError(GetLastError());
811261991Sdim    return ec;
812218885Sdim  }
813218885Sdim
814261991Sdim  DWORD dwDesiredAccess;
815261991Sdim  switch (Mode) {
816261991Sdim  case readonly:  dwDesiredAccess = FILE_MAP_READ; break;
817261991Sdim  case readwrite: dwDesiredAccess = FILE_MAP_WRITE; break;
818261991Sdim  case priv:      dwDesiredAccess = FILE_MAP_COPY; break;
819261991Sdim  }
820261991Sdim  Mapping = ::MapViewOfFile(FileMappingHandle,
821261991Sdim                            dwDesiredAccess,
822261991Sdim                            Offset >> 32,
823261991Sdim                            Offset & 0xffffffff,
824261991Sdim                            Size);
825261991Sdim  if (Mapping == NULL) {
826288943Sdim    std::error_code ec = mapWindowsError(GetLastError());
827261991Sdim    ::CloseHandle(FileMappingHandle);
828261991Sdim    return ec;
829261991Sdim  }
830261991Sdim
831261991Sdim  if (Size == 0) {
832261991Sdim    MEMORY_BASIC_INFORMATION mbi;
833261991Sdim    SIZE_T Result = VirtualQuery(Mapping, &mbi, sizeof(mbi));
834261991Sdim    if (Result == 0) {
835288943Sdim      std::error_code ec = mapWindowsError(GetLastError());
836261991Sdim      ::UnmapViewOfFile(Mapping);
837261991Sdim      ::CloseHandle(FileMappingHandle);
838261991Sdim      return ec;
839218885Sdim    }
840261991Sdim    Size = mbi.RegionSize;
841218885Sdim  }
842218885Sdim
843341825Sdim  // Close the file mapping handle, as it's kept alive by the file mapping. But
844341825Sdim  // neither the file mapping nor the file mapping handle keep the file handle
845341825Sdim  // alive, so we need to keep a reference to the file in case all other handles
846341825Sdim  // are closed and the file is deleted, which may cause invalid data to be read
847341825Sdim  // from the file.
848261991Sdim  ::CloseHandle(FileMappingHandle);
849341825Sdim  if (!::DuplicateHandle(::GetCurrentProcess(), OrigFileHandle,
850341825Sdim                         ::GetCurrentProcess(), &FileHandle, 0, 0,
851341825Sdim                         DUPLICATE_SAME_ACCESS)) {
852341825Sdim    std::error_code ec = mapWindowsError(GetLastError());
853341825Sdim    ::UnmapViewOfFile(Mapping);
854341825Sdim    return ec;
855341825Sdim  }
856341825Sdim
857276479Sdim  return std::error_code();
858218885Sdim}
859218885Sdim
860353358Sdimmapped_file_region::mapped_file_region(sys::fs::file_t fd, mapmode mode,
861353358Sdim                                       size_t length, uint64_t offset,
862353358Sdim                                       std::error_code &ec)
863280031Sdim    : Size(length), Mapping() {
864280031Sdim  ec = init(fd, offset, mode);
865280031Sdim  if (ec)
866280031Sdim    Mapping = 0;
867261991Sdim}
868218885Sdim
869344779Sdimstatic bool hasFlushBufferKernelBug() {
870344779Sdim  static bool Ret{GetWindowsOSVersion() < llvm::VersionTuple(10, 0, 0, 17763)};
871344779Sdim  return Ret;
872344779Sdim}
873344779Sdim
874344779Sdimstatic bool isEXE(StringRef Magic) {
875344779Sdim  static const char PEMagic[] = {'P', 'E', '\0', '\0'};
876344779Sdim  if (Magic.startswith(StringRef("MZ")) && Magic.size() >= 0x3c + 4) {
877344779Sdim    uint32_t off = read32le(Magic.data() + 0x3c);
878344779Sdim    // PE/COFF file, either EXE or DLL.
879344779Sdim    if (Magic.substr(off).startswith(StringRef(PEMagic, sizeof(PEMagic))))
880344779Sdim      return true;
881344779Sdim  }
882344779Sdim  return false;
883344779Sdim}
884344779Sdim
885261991Sdimmapped_file_region::~mapped_file_region() {
886341825Sdim  if (Mapping) {
887344779Sdim
888344779Sdim    bool Exe = isEXE(StringRef((char *)Mapping, Size));
889344779Sdim
890261991Sdim    ::UnmapViewOfFile(Mapping);
891341825Sdim
892344779Sdim    if (Mode == mapmode::readwrite && Exe && hasFlushBufferKernelBug()) {
893341825Sdim      // There is a Windows kernel bug, the exact trigger conditions of which
894341825Sdim      // are not well understood.  When triggered, dirty pages are not properly
895341825Sdim      // flushed and subsequent process's attempts to read a file can return
896341825Sdim      // invalid data.  Calling FlushFileBuffers on the write handle is
897341825Sdim      // sufficient to ensure that this bug is not triggered.
898344779Sdim      // The bug only occurs when writing an executable and executing it right
899344779Sdim      // after, under high I/O pressure.
900341825Sdim      ::FlushFileBuffers(FileHandle);
901341825Sdim    }
902341825Sdim
903341825Sdim    ::CloseHandle(FileHandle);
904341825Sdim  }
905261991Sdim}
906218885Sdim
907327952Sdimsize_t mapped_file_region::size() const {
908261991Sdim  assert(Mapping && "Mapping failed but used anyway!");
909261991Sdim  return Size;
910261991Sdim}
911218885Sdim
912261991Sdimchar *mapped_file_region::data() const {
913261991Sdim  assert(Mapping && "Mapping failed but used anyway!");
914261991Sdim  return reinterpret_cast<char*>(Mapping);
915261991Sdim}
916218885Sdim
917261991Sdimconst char *mapped_file_region::const_data() const {
918261991Sdim  assert(Mapping && "Mapping failed but used anyway!");
919261991Sdim  return reinterpret_cast<const char*>(Mapping);
920261991Sdim}
921218885Sdim
922261991Sdimint mapped_file_region::alignment() {
923261991Sdim  SYSTEM_INFO SysInfo;
924261991Sdim  ::GetSystemInfo(&SysInfo);
925261991Sdim  return SysInfo.dwAllocationGranularity;
926261991Sdim}
927218885Sdim
928327952Sdimstatic basic_file_status status_from_find_data(WIN32_FIND_DATAW *FindData) {
929327952Sdim  return basic_file_status(file_type_from_attrs(FindData->dwFileAttributes),
930327952Sdim                           perms_from_attrs(FindData->dwFileAttributes),
931327952Sdim                           FindData->ftLastAccessTime.dwHighDateTime,
932327952Sdim                           FindData->ftLastAccessTime.dwLowDateTime,
933327952Sdim                           FindData->ftLastWriteTime.dwHighDateTime,
934327952Sdim                           FindData->ftLastWriteTime.dwLowDateTime,
935327952Sdim                           FindData->nFileSizeHigh, FindData->nFileSizeLow);
936327952Sdim}
937327952Sdim
938344779Sdimstd::error_code detail::directory_iterator_construct(detail::DirIterState &IT,
939344779Sdim                                                     StringRef Path,
940344779Sdim                                                     bool FollowSymlinks) {
941344779Sdim  SmallVector<wchar_t, 128> PathUTF16;
942218885Sdim
943344779Sdim  if (std::error_code EC = widenPath(Path, PathUTF16))
944344779Sdim    return EC;
945218885Sdim
946261991Sdim  // Convert path to the format that Windows is happy with.
947344779Sdim  if (PathUTF16.size() > 0 &&
948344779Sdim      !is_separator(PathUTF16[Path.size() - 1]) &&
949344779Sdim      PathUTF16[Path.size() - 1] != L':') {
950344779Sdim    PathUTF16.push_back(L'\\');
951344779Sdim    PathUTF16.push_back(L'*');
952261991Sdim  } else {
953344779Sdim    PathUTF16.push_back(L'*');
954261991Sdim  }
955218885Sdim
956261991Sdim  //  Get the first directory entry.
957261991Sdim  WIN32_FIND_DATAW FirstFind;
958327952Sdim  ScopedFindHandle FindHandle(::FindFirstFileExW(
959344779Sdim      c_str(PathUTF16), FindExInfoBasic, &FirstFind, FindExSearchNameMatch,
960327952Sdim      NULL, FIND_FIRST_EX_LARGE_FETCH));
961261991Sdim  if (!FindHandle)
962288943Sdim    return mapWindowsError(::GetLastError());
963218885Sdim
964261991Sdim  size_t FilenameLen = ::wcslen(FirstFind.cFileName);
965261991Sdim  while ((FilenameLen == 1 && FirstFind.cFileName[0] == L'.') ||
966261991Sdim         (FilenameLen == 2 && FirstFind.cFileName[0] == L'.' &&
967261991Sdim                              FirstFind.cFileName[1] == L'.'))
968261991Sdim    if (!::FindNextFileW(FindHandle, &FirstFind)) {
969276479Sdim      DWORD LastError = ::GetLastError();
970261991Sdim      // Check for end.
971276479Sdim      if (LastError == ERROR_NO_MORE_FILES)
972344779Sdim        return detail::directory_iterator_destruct(IT);
973288943Sdim      return mapWindowsError(LastError);
974261991Sdim    } else
975261991Sdim      FilenameLen = ::wcslen(FirstFind.cFileName);
976218885Sdim
977261991Sdim  // Construct the current directory entry.
978344779Sdim  SmallString<128> DirectoryEntryNameUTF8;
979344779Sdim  if (std::error_code EC =
980276479Sdim          UTF16ToUTF8(FirstFind.cFileName, ::wcslen(FirstFind.cFileName),
981344779Sdim                      DirectoryEntryNameUTF8))
982344779Sdim    return EC;
983218885Sdim
984344779Sdim  IT.IterationHandle = intptr_t(FindHandle.take());
985344779Sdim  SmallString<128> DirectoryEntryPath(Path);
986344779Sdim  path::append(DirectoryEntryPath, DirectoryEntryNameUTF8);
987344779Sdim  IT.CurrentEntry =
988344779Sdim      directory_entry(DirectoryEntryPath, FollowSymlinks,
989344779Sdim                      file_type_from_attrs(FirstFind.dwFileAttributes),
990344779Sdim                      status_from_find_data(&FirstFind));
991218885Sdim
992276479Sdim  return std::error_code();
993218885Sdim}
994218885Sdim
995344779Sdimstd::error_code detail::directory_iterator_destruct(detail::DirIterState &IT) {
996344779Sdim  if (IT.IterationHandle != 0)
997261991Sdim    // Closes the handle if it's valid.
998344779Sdim    ScopedFindHandle close(HANDLE(IT.IterationHandle));
999344779Sdim  IT.IterationHandle = 0;
1000344779Sdim  IT.CurrentEntry = directory_entry();
1001276479Sdim  return std::error_code();
1002261991Sdim}
1003218885Sdim
1004344779Sdimstd::error_code detail::directory_iterator_increment(detail::DirIterState &IT) {
1005261991Sdim  WIN32_FIND_DATAW FindData;
1006344779Sdim  if (!::FindNextFileW(HANDLE(IT.IterationHandle), &FindData)) {
1007276479Sdim    DWORD LastError = ::GetLastError();
1008261991Sdim    // Check for end.
1009276479Sdim    if (LastError == ERROR_NO_MORE_FILES)
1010344779Sdim      return detail::directory_iterator_destruct(IT);
1011288943Sdim    return mapWindowsError(LastError);
1012261991Sdim  }
1013218885Sdim
1014261991Sdim  size_t FilenameLen = ::wcslen(FindData.cFileName);
1015261991Sdim  if ((FilenameLen == 1 && FindData.cFileName[0] == L'.') ||
1016261991Sdim      (FilenameLen == 2 && FindData.cFileName[0] == L'.' &&
1017261991Sdim                           FindData.cFileName[1] == L'.'))
1018344779Sdim    return directory_iterator_increment(IT);
1019218885Sdim
1020344779Sdim  SmallString<128> DirectoryEntryPathUTF8;
1021344779Sdim  if (std::error_code EC =
1022276479Sdim          UTF16ToUTF8(FindData.cFileName, ::wcslen(FindData.cFileName),
1023344779Sdim                      DirectoryEntryPathUTF8))
1024344779Sdim    return EC;
1025218885Sdim
1026344779Sdim  IT.CurrentEntry.replace_filename(
1027344779Sdim      Twine(DirectoryEntryPathUTF8),
1028344779Sdim      file_type_from_attrs(FindData.dwFileAttributes),
1029344779Sdim      status_from_find_data(&FindData));
1030276479Sdim  return std::error_code();
1031218885Sdim}
1032218885Sdim
1033327952SdimErrorOr<basic_file_status> directory_entry::status() const {
1034327952Sdim  return Status;
1035321369Sdim}
1036321369Sdim
1037341825Sdimstatic std::error_code nativeFileToFd(Expected<HANDLE> H, int &ResultFD,
1038341825Sdim                                      OpenFlags Flags) {
1039341825Sdim  int CrtOpenFlags = 0;
1040341825Sdim  if (Flags & OF_Append)
1041341825Sdim    CrtOpenFlags |= _O_APPEND;
1042321369Sdim
1043341825Sdim  if (Flags & OF_Text)
1044341825Sdim    CrtOpenFlags |= _O_TEXT;
1045321369Sdim
1046341825Sdim  ResultFD = -1;
1047341825Sdim  if (!H)
1048341825Sdim    return errorToErrorCode(H.takeError());
1049341825Sdim
1050341825Sdim  ResultFD = ::_open_osfhandle(intptr_t(*H), CrtOpenFlags);
1051341825Sdim  if (ResultFD == -1) {
1052341825Sdim    ::CloseHandle(*H);
1053341825Sdim    return mapWindowsError(ERROR_INVALID_HANDLE);
1054341825Sdim  }
1055341825Sdim  return std::error_code();
1056321369Sdim}
1057321369Sdim
1058341825Sdimstatic DWORD nativeDisposition(CreationDisposition Disp, OpenFlags Flags) {
1059341825Sdim  // This is a compatibility hack.  Really we should respect the creation
1060341825Sdim  // disposition, but a lot of old code relied on the implicit assumption that
1061341825Sdim  // OF_Append implied it would open an existing file.  Since the disposition is
1062341825Sdim  // now explicit and defaults to CD_CreateAlways, this assumption would cause
1063341825Sdim  // any usage of OF_Append to append to a new file, even if the file already
1064341825Sdim  // existed.  A better solution might have two new creation dispositions:
1065341825Sdim  // CD_AppendAlways and CD_AppendNew.  This would also address the problem of
1066341825Sdim  // OF_Append being used on a read-only descriptor, which doesn't make sense.
1067341825Sdim  if (Flags & OF_Append)
1068341825Sdim    return OPEN_ALWAYS;
1069341825Sdim
1070341825Sdim  switch (Disp) {
1071341825Sdim  case CD_CreateAlways:
1072341825Sdim    return CREATE_ALWAYS;
1073341825Sdim  case CD_CreateNew:
1074341825Sdim    return CREATE_NEW;
1075341825Sdim  case CD_OpenAlways:
1076341825Sdim    return OPEN_ALWAYS;
1077341825Sdim  case CD_OpenExisting:
1078341825Sdim    return OPEN_EXISTING;
1079341825Sdim  }
1080341825Sdim  llvm_unreachable("unreachable!");
1081341825Sdim}
1082341825Sdim
1083341825Sdimstatic DWORD nativeAccess(FileAccess Access, OpenFlags Flags) {
1084341825Sdim  DWORD Result = 0;
1085341825Sdim  if (Access & FA_Read)
1086341825Sdim    Result |= GENERIC_READ;
1087341825Sdim  if (Access & FA_Write)
1088341825Sdim    Result |= GENERIC_WRITE;
1089341825Sdim  if (Flags & OF_Delete)
1090341825Sdim    Result |= DELETE;
1091341825Sdim  if (Flags & OF_UpdateAtime)
1092341825Sdim    Result |= FILE_WRITE_ATTRIBUTES;
1093341825Sdim  return Result;
1094341825Sdim}
1095341825Sdim
1096341825Sdimstatic std::error_code openNativeFileInternal(const Twine &Name,
1097341825Sdim                                              file_t &ResultFile, DWORD Disp,
1098341825Sdim                                              DWORD Access, DWORD Flags,
1099341825Sdim                                              bool Inherit = false) {
1100261991Sdim  SmallVector<wchar_t, 128> PathUTF16;
1101280031Sdim  if (std::error_code EC = widenPath(Name, PathUTF16))
1102261991Sdim    return EC;
1103218885Sdim
1104341825Sdim  SECURITY_ATTRIBUTES SA;
1105341825Sdim  SA.nLength = sizeof(SA);
1106341825Sdim  SA.lpSecurityDescriptor = nullptr;
1107341825Sdim  SA.bInheritHandle = Inherit;
1108341825Sdim
1109296417Sdim  HANDLE H =
1110341825Sdim      ::CreateFileW(PathUTF16.begin(), Access,
1111341825Sdim                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SA,
1112341825Sdim                    Disp, Flags, NULL);
1113261991Sdim  if (H == INVALID_HANDLE_VALUE) {
1114276479Sdim    DWORD LastError = ::GetLastError();
1115288943Sdim    std::error_code EC = mapWindowsError(LastError);
1116261991Sdim    // Provide a better error message when trying to open directories.
1117261991Sdim    // This only runs if we failed to open the file, so there is probably
1118261991Sdim    // no performances issues.
1119276479Sdim    if (LastError != ERROR_ACCESS_DENIED)
1120261991Sdim      return EC;
1121261991Sdim    if (is_directory(Name))
1122276479Sdim      return make_error_code(errc::is_a_directory);
1123261991Sdim    return EC;
1124218885Sdim  }
1125341825Sdim  ResultFile = H;
1126276479Sdim  return std::error_code();
1127218885Sdim}
1128218885Sdim
1129341825SdimExpected openNativeFile(const Twine &Name, CreationDisposition Disp,
1130341825Sdim                                FileAccess Access, OpenFlags Flags,
1131341825Sdim                                unsigned Mode) {
1132261991Sdim  // Verify that we don't have both "append" and "excl".
1133341825Sdim  assert((!(Disp == CD_CreateNew) || !(Flags & OF_Append)) &&
1134341825Sdim         "Cannot specify both 'CreateNew' and 'Append' file creation flags!");
1135218885Sdim
1136341825Sdim  DWORD NativeDisp = nativeDisposition(Disp, Flags);
1137341825Sdim  DWORD NativeAccess = nativeAccess(Access, Flags);
1138218885Sdim
1139341825Sdim  bool Inherit = false;
1140341825Sdim  if (Flags & OF_ChildInherit)
1141341825Sdim    Inherit = true;
1142218885Sdim
1143341825Sdim  file_t Result;
1144341825Sdim  std::error_code EC = openNativeFileInternal(
1145341825Sdim      Name, Result, NativeDisp, NativeAccess, FILE_ATTRIBUTE_NORMAL, Inherit);
1146341825Sdim  if (EC)
1147341825Sdim    return errorCodeToError(EC);
1148261991Sdim
1149341825Sdim  if (Flags & OF_UpdateAtime) {
1150341825Sdim    FILETIME FileTime;
1151341825Sdim    SYSTEMTIME SystemTime;
1152341825Sdim    GetSystemTime(&SystemTime);
1153341825Sdim    if (SystemTimeToFileTime(&SystemTime, &FileTime) == 0 ||
1154341825Sdim        SetFileTime(Result, NULL, &FileTime, NULL) == 0) {
1155341825Sdim      DWORD LastError = ::GetLastError();
1156341825Sdim      ::CloseHandle(Result);
1157341825Sdim      return errorCodeToError(mapWindowsError(LastError));
1158341825Sdim    }
1159327952Sdim  }
1160276479Sdim
1161341825Sdim  if (Flags & OF_Delete) {
1162341825Sdim    if ((EC = setDeleteDisposition(Result, true))) {
1163341825Sdim      ::CloseHandle(Result);
1164341825Sdim      return errorCodeToError(EC);
1165341825Sdim    }
1166341825Sdim  }
1167341825Sdim  return Result;
1168341825Sdim}
1169261991Sdim
1170341825Sdimstd::error_code openFile(const Twine &Name, int &ResultFD,
1171341825Sdim                         CreationDisposition Disp, FileAccess Access,
1172341825Sdim                         OpenFlags Flags, unsigned int Mode) {
1173341825Sdim  Expected<file_t> Result = openNativeFile(Name, Disp, Access, Flags);
1174341825Sdim  if (!Result)
1175341825Sdim    return errorToErrorCode(Result.takeError());
1176341825Sdim
1177341825Sdim  return nativeFileToFd(*Result, ResultFD, Flags);
1178341825Sdim}
1179341825Sdim
1180341825Sdimstatic std::error_code directoryRealPath(const Twine &Name,
1181341825Sdim                                         SmallVectorImpl<char> &RealPath) {
1182341825Sdim  file_t File;
1183341825Sdim  std::error_code EC = openNativeFileInternal(
1184341825Sdim      Name, File, OPEN_EXISTING, GENERIC_READ, FILE_FLAG_BACKUP_SEMANTICS);
1185341825Sdim  if (EC)
1186261991Sdim    return EC;
1187218885Sdim
1188341825Sdim  EC = realPathFromHandle(File, RealPath);
1189341825Sdim  ::CloseHandle(File);
1190341825Sdim  return EC;
1191341825Sdim}
1192218885Sdim
1193341825Sdimstd::error_code openFileForRead(const Twine &Name, int &ResultFD,
1194341825Sdim                                OpenFlags Flags,
1195341825Sdim                                SmallVectorImpl<char> *RealPath) {
1196341825Sdim  Expected<HANDLE> NativeFile = openNativeFileForRead(Name, Flags, RealPath);
1197341825Sdim  return nativeFileToFd(std::move(NativeFile), ResultFD, OF_None);
1198341825Sdim}
1199218885Sdim
1200341825SdimExpected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1201341825Sdim                                       SmallVectorImpl<char> *RealPath) {
1202341825Sdim  Expected<file_t> Result =
1203341825Sdim      openNativeFile(Name, CD_OpenExisting, FA_Read, Flags);
1204218885Sdim
1205341825Sdim  // Fetch the real name of the file, if the user asked
1206341825Sdim  if (Result && RealPath)
1207341825Sdim    realPathFromHandle(*Result, *RealPath);
1208341825Sdim
1209341825Sdim  return Result;
1210218885Sdim}
1211309124Sdim
1212353358Sdimfile_t convertFDToNativeFile(int FD) {
1213353358Sdim  return reinterpret_cast<HANDLE>(::_get_osfhandle(FD));
1214353358Sdim}
1215353358Sdim
1216353358Sdimfile_t getStdinHandle() { return ::GetStdHandle(STD_INPUT_HANDLE); }
1217353358Sdimfile_t getStdoutHandle() { return ::GetStdHandle(STD_OUTPUT_HANDLE); }
1218353358Sdimfile_t getStderrHandle() { return ::GetStdHandle(STD_ERROR_HANDLE); }
1219353358Sdim
1220353358Sdimstd::error_code readNativeFileImpl(file_t FileHandle, char *BufPtr, size_t BytesToRead,
1221353358Sdim                                   size_t *BytesRead, OVERLAPPED *Overlap) {
1222353358Sdim  // ReadFile can only read 2GB at a time. The caller should check the number of
1223353358Sdim  // bytes and read in a loop until termination.
1224353358Sdim  DWORD BytesToRead32 =
1225353358Sdim      std::min(size_t(std::numeric_limits<DWORD>::max()), BytesToRead);
1226353358Sdim  DWORD BytesRead32 = 0;
1227353358Sdim  bool Success =
1228353358Sdim      ::ReadFile(FileHandle, BufPtr, BytesToRead32, &BytesRead32, Overlap);
1229353358Sdim  *BytesRead = BytesRead32;
1230353358Sdim  if (!Success) {
1231353358Sdim    DWORD Err = ::GetLastError();
1232353358Sdim    // Pipe EOF is not an error.
1233353358Sdim    if (Err == ERROR_BROKEN_PIPE)
1234353358Sdim      return std::error_code();
1235353358Sdim    return mapWindowsError(Err);
1236353358Sdim  }
1237353358Sdim  return std::error_code();
1238353358Sdim}
1239353358Sdim
1240353358Sdimstd::error_code readNativeFile(file_t FileHandle, MutableArrayRef<char> Buf,
1241353358Sdim                               size_t *BytesRead) {
1242353358Sdim  return readNativeFileImpl(FileHandle, Buf.data(), Buf.size(), BytesRead,
1243353358Sdim                            /*Overlap=*/nullptr);
1244353358Sdim}
1245353358Sdim
1246353358Sdimstd::error_code readNativeFileSlice(file_t FileHandle,
1247353358Sdim                                    MutableArrayRef<char> Buf, size_t Offset) {
1248353358Sdim  char *BufPtr = Buf.data();
1249353358Sdim  size_t BytesLeft = Buf.size();
1250353358Sdim
1251353358Sdim  while (BytesLeft) {
1252353358Sdim    uint64_t CurOff = Buf.size() - BytesLeft + Offset;
1253353358Sdim    OVERLAPPED Overlapped = {};
1254353358Sdim    Overlapped.Offset = uint32_t(CurOff);
1255353358Sdim    Overlapped.OffsetHigh = uint32_t(uint64_t(CurOff) >> 32);
1256353358Sdim
1257353358Sdim    size_t BytesRead = 0;
1258353358Sdim    if (auto EC = readNativeFileImpl(FileHandle, BufPtr, BytesLeft, &BytesRead,
1259353358Sdim                                     &Overlapped))
1260353358Sdim      return EC;
1261353358Sdim
1262353358Sdim    // Once we reach EOF, zero the remaining bytes in the buffer.
1263353358Sdim    if (BytesRead == 0) {
1264353358Sdim      memset(BufPtr, 0, BytesLeft);
1265353358Sdim      break;
1266353358Sdim    }
1267353358Sdim    BytesLeft -= BytesRead;
1268353358Sdim    BufPtr += BytesRead;
1269353358Sdim  }
1270353358Sdim  return std::error_code();
1271353358Sdim}
1272353358Sdim
1273353358Sdimstd::error_code closeFile(file_t &F) {
1274353358Sdim  file_t TmpF = F;
1275341825Sdim  F = kInvalidFile;
1276353358Sdim  if (!::CloseHandle(TmpF))
1277353358Sdim    return mapWindowsError(::GetLastError());
1278353358Sdim  return std::error_code();
1279341825Sdim}
1280341825Sdim
1281321369Sdimstd::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1282321369Sdim  // Convert to utf-16.
1283321369Sdim  SmallVector<wchar_t, 128> Path16;
1284321369Sdim  std::error_code EC = widenPath(path, Path16);
1285321369Sdim  if (EC && !IgnoreErrors)
1286321369Sdim    return EC;
1287321369Sdim
1288321369Sdim  // SHFileOperation() accepts a list of paths, and so must be double null-
1289321369Sdim  // terminated to indicate the end of the list.  The buffer is already null
1290321369Sdim  // terminated, but since that null character is not considered part of the
1291321369Sdim  // vector's size, pushing another one will just consume that byte.  So we
1292321369Sdim  // need to push 2 null terminators.
1293321369Sdim  Path16.push_back(0);
1294321369Sdim  Path16.push_back(0);
1295321369Sdim
1296321369Sdim  SHFILEOPSTRUCTW shfos = {};
1297321369Sdim  shfos.wFunc = FO_DELETE;
1298321369Sdim  shfos.pFrom = Path16.data();
1299321369Sdim  shfos.fFlags = FOF_NO_UI;
1300321369Sdim
1301321369Sdim  int result = ::SHFileOperationW(&shfos);
1302321369Sdim  if (result != 0 && !IgnoreErrors)
1303321369Sdim    return mapWindowsError(result);
1304321369Sdim  return std::error_code();
1305321369Sdim}
1306321369Sdim
1307321369Sdimstatic void expandTildeExpr(SmallVectorImpl<char> &Path) {
1308321369Sdim  // Path does not begin with a tilde expression.
1309321369Sdim  if (Path.empty() || Path[0] != '~')
1310321369Sdim    return;
1311321369Sdim
1312321369Sdim  StringRef PathStr(Path.begin(), Path.size());
1313321369Sdim  PathStr = PathStr.drop_front();
1314321369Sdim  StringRef Expr = PathStr.take_until([](char c) { return path::is_separator(c); });
1315321369Sdim
1316321369Sdim  if (!Expr.empty()) {
1317321369Sdim    // This is probably a ~username/ expression.  Don't support this on Windows.
1318321369Sdim    return;
1319321369Sdim  }
1320321369Sdim
1321321369Sdim  SmallString<128> HomeDir;
1322321369Sdim  if (!path::home_directory(HomeDir)) {
1323321369Sdim    // For some reason we couldn't get the home directory.  Just exit.
1324321369Sdim    return;
1325321369Sdim  }
1326321369Sdim
1327321369Sdim  // Overwrite the first character and insert the rest.
1328321369Sdim  Path[0] = HomeDir[0];
1329321369Sdim  Path.insert(Path.begin() + 1, HomeDir.begin() + 1, HomeDir.end());
1330321369Sdim}
1331321369Sdim
1332344779Sdimvoid expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
1333344779Sdim  dest.clear();
1334344779Sdim  if (path.isTriviallyEmpty())
1335344779Sdim    return;
1336344779Sdim
1337344779Sdim  path.toVector(dest);
1338344779Sdim  expandTildeExpr(dest);
1339344779Sdim
1340344779Sdim  return;
1341344779Sdim}
1342344779Sdim
1343321369Sdimstd::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1344321369Sdim                          bool expand_tilde) {
1345321369Sdim  dest.clear();
1346321369Sdim  if (path.isTriviallyEmpty())
1347321369Sdim    return std::error_code();
1348321369Sdim
1349321369Sdim  if (expand_tilde) {
1350321369Sdim    SmallString<128> Storage;
1351321369Sdim    path.toVector(Storage);
1352321369Sdim    expandTildeExpr(Storage);
1353321369Sdim    return real_path(Storage, dest, false);
1354321369Sdim  }
1355321369Sdim
1356321369Sdim  if (is_directory(path))
1357321369Sdim    return directoryRealPath(path, dest);
1358321369Sdim
1359321369Sdim  int fd;
1360341825Sdim  if (std::error_code EC =
1361341825Sdim          llvm::sys::fs::openFileForRead(path, fd, OF_None, &dest))
1362321369Sdim    return EC;
1363321369Sdim  ::close(fd);
1364321369Sdim  return std::error_code();
1365321369Sdim}
1366321369Sdim
1367261991Sdim} // end namespace fs
1368218885Sdim
1369276479Sdimnamespace path {
1370296417Sdimstatic bool getKnownFolderPath(KNOWNFOLDERID folderId,
1371296417Sdim                               SmallVectorImpl<char> &result) {
1372296417Sdim  wchar_t *path = nullptr;
1373296417Sdim  if (::SHGetKnownFolderPath(folderId, KF_FLAG_CREATE, nullptr, &path) != S_OK)
1374276479Sdim    return false;
1375276479Sdim
1376296417Sdim  bool ok = !UTF16ToUTF8(path, ::wcslen(path), result);
1377296417Sdim  ::CoTaskMemFree(path);
1378296417Sdim  return ok;
1379296417Sdim}
1380276479Sdim
1381296417Sdimbool home_directory(SmallVectorImpl<char> &result) {
1382296417Sdim  return getKnownFolderPath(FOLDERID_Profile, result);
1383296417Sdim}
1384280031Sdim
1385296417Sdimstatic bool getTempDirEnvVar(const wchar_t *Var, SmallVectorImpl<char> &Res) {
1386280031Sdim  SmallVector<wchar_t, 1024> Buf;
1387280031Sdim  size_t Size = 1024;
1388280031Sdim  do {
1389280031Sdim    Buf.reserve(Size);
1390296417Sdim    Size = GetEnvironmentVariableW(Var, Buf.data(), Buf.capacity());
1391280031Sdim    if (Size == 0)
1392280031Sdim      return false;
1393280031Sdim
1394280031Sdim    // Try again with larger buffer.
1395280031Sdim  } while (Size > Buf.capacity());
1396280031Sdim  Buf.set_size(Size);
1397280031Sdim
1398296417Sdim  return !windows::UTF16ToUTF8(Buf.data(), Size, Res);
1399280031Sdim}
1400280031Sdim
1401280031Sdimstatic bool getTempDirEnvVar(SmallVectorImpl<char> &Res) {
1402296417Sdim  const wchar_t *EnvironmentVariables[] = {L"TMP", L"TEMP", L"USERPROFILE"};
1403296417Sdim  for (auto *Env : EnvironmentVariables) {
1404280031Sdim    if (getTempDirEnvVar(Env, Res))
1405280031Sdim      return true;
1406280031Sdim  }
1407280031Sdim  return false;
1408280031Sdim}
1409280031Sdim
1410280031Sdimvoid system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1411280031Sdim  (void)ErasedOnReboot;
1412280031Sdim  Result.clear();
1413280031Sdim
1414296417Sdim  // Check whether the temporary directory is specified by an environment var.
1415296417Sdim  // This matches GetTempPath logic to some degree. GetTempPath is not used
1416296417Sdim  // directly as it cannot handle evn var longer than 130 chars on Windows 7
1417296417Sdim  // (fixed on Windows 8).
1418296417Sdim  if (getTempDirEnvVar(Result)) {
1419296417Sdim    assert(!Result.empty() && "Unexpected empty path");
1420296417Sdim    native(Result); // Some Unix-like shells use Unix path separator in $TMP.
1421296417Sdim    fs::make_absolute(Result); // Make it absolute if not already.
1422280031Sdim    return;
1423296417Sdim  }
1424280031Sdim
1425280031Sdim  // Fall back to a system default.
1426296417Sdim  const char *DefaultResult = "C:\\Temp";
1427280031Sdim  Result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
1428280031Sdim}
1429276479Sdim} // end namespace path
1430276479Sdim
1431261991Sdimnamespace windows {
1432341825Sdimstd::error_code CodePageToUTF16(unsigned codepage,
1433341825Sdim                                llvm::StringRef original,
1434341825Sdim                                llvm::SmallVectorImpl<wchar_t> &utf16) {
1435341825Sdim  if (!original.empty()) {
1436341825Sdim    int len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1437341825Sdim                                    original.size(), utf16.begin(), 0);
1438261991Sdim
1439341825Sdim    if (len == 0) {
1440288943Sdim      return mapWindowsError(::GetLastError());
1441341825Sdim    }
1442261991Sdim
1443276479Sdim    utf16.reserve(len + 1);
1444276479Sdim    utf16.set_size(len);
1445261991Sdim
1446341825Sdim    len = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, original.begin(),
1447341825Sdim                                original.size(), utf16.begin(), utf16.size());
1448261991Sdim
1449341825Sdim    if (len == 0) {
1450288943Sdim      return mapWindowsError(::GetLastError());
1451341825Sdim    }
1452276479Sdim  }
1453261991Sdim
1454261991Sdim  // Make utf16 null terminated.
1455261991Sdim  utf16.push_back(0);
1456261991Sdim  utf16.pop_back();
1457261991Sdim
1458276479Sdim  return std::error_code();
1459218885Sdim}
1460218885Sdim
1461341825Sdimstd::error_code UTF8ToUTF16(llvm::StringRef utf8,
1462341825Sdim                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1463341825Sdim  return CodePageToUTF16(CP_UTF8, utf8, utf16);
1464341825Sdim}
1465341825Sdim
1466341825Sdimstd::error_code CurCPToUTF16(llvm::StringRef curcp,
1467341825Sdim                            llvm::SmallVectorImpl<wchar_t> &utf16) {
1468341825Sdim  return CodePageToUTF16(CP_ACP, curcp, utf16);
1469341825Sdim}
1470341825Sdim
1471280031Sdimstatic
1472280031Sdimstd::error_code UTF16ToCodePage(unsigned codepage, const wchar_t *utf16,
1473280031Sdim                                size_t utf16_len,
1474341825Sdim                                llvm::SmallVectorImpl<char> &converted) {
1475276479Sdim  if (utf16_len) {
1476276479Sdim    // Get length.
1477341825Sdim    int len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.begin(),
1478276479Sdim                                    0, NULL, NULL);
1479261991Sdim
1480341825Sdim    if (len == 0) {
1481288943Sdim      return mapWindowsError(::GetLastError());
1482341825Sdim    }
1483261991Sdim
1484341825Sdim    converted.reserve(len);
1485341825Sdim    converted.set_size(len);
1486261991Sdim
1487276479Sdim    // Now do the actual conversion.
1488341825Sdim    len = ::WideCharToMultiByte(codepage, 0, utf16, utf16_len, converted.data(),
1489341825Sdim                                converted.size(), NULL, NULL);
1490261991Sdim
1491341825Sdim    if (len == 0) {
1492288943Sdim      return mapWindowsError(::GetLastError());
1493341825Sdim    }
1494276479Sdim  }
1495261991Sdim
1496341825Sdim  // Make the new string null terminated.
1497341825Sdim  converted.push_back(0);
1498341825Sdim  converted.pop_back();
1499261991Sdim
1500276479Sdim  return std::error_code();
1501218885Sdim}
1502280031Sdim
1503280031Sdimstd::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len,
1504280031Sdim                            llvm::SmallVectorImpl<char> &utf8) {
1505280031Sdim  return UTF16ToCodePage(CP_UTF8, utf16, utf16_len, utf8);
1506280031Sdim}
1507280031Sdim
1508280031Sdimstd::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len,
1509341825Sdim                             llvm::SmallVectorImpl<char> &curcp) {
1510341825Sdim  return UTF16ToCodePage(CP_ACP, utf16, utf16_len, curcp);
1511280031Sdim}
1512309124Sdim
1513261991Sdim} // end namespace windows
1514261991Sdim} // end namespace sys
1515261991Sdim} // end namespace llvm
1516