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