LLVM  10.0.0svn
Path.inc
Go to the documentation of this file.
1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Unix specific implementation of the Path API.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 //===----------------------------------------------------------------------===//
14 //=== WARNING: Implementation here must contain only generic UNIX code that
15 //=== is guaranteed to work on *all* UNIX variants.
16 //===----------------------------------------------------------------------===//
17 
18 #include "Unix.h"
19 #include <limits.h>
20 #include <stdio.h>
21 #if HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #if HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #ifdef HAVE_SYS_MMAN_H
31 #include <sys/mman.h>
32 #endif
33 
34 #include <dirent.h>
35 #include <pwd.h>
36 
37 #ifdef __APPLE__
38 #include <mach-o/dyld.h>
39 #include <sys/attr.h>
40 #include <copyfile.h>
41 #elif defined(__DragonFly__)
42 #include <sys/mount.h>
43 #endif
44 
45 // Both stdio.h and cstdio are included via different paths and
46 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
47 // either.
48 #undef ferror
49 #undef feof
50 
51 // For GNU Hurd
52 #if defined(__GNU__) && !defined(PATH_MAX)
53 # define PATH_MAX 4096
54 # define MAXPATHLEN 4096
55 #endif
56 
57 #include <sys/types.h>
58 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
59  !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX)
60 #include <sys/statvfs.h>
61 #define STATVFS statvfs
62 #define FSTATVFS fstatvfs
63 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
64 #else
65 #if defined(__OpenBSD__) || defined(__FreeBSD__)
66 #include <sys/mount.h>
67 #include <sys/param.h>
68 #elif defined(__linux__)
69 #if defined(HAVE_LINUX_MAGIC_H)
70 #include <linux/magic.h>
71 #else
72 #if defined(HAVE_LINUX_NFS_FS_H)
73 #include <linux/nfs_fs.h>
74 #endif
75 #if defined(HAVE_LINUX_SMB_H)
76 #include <linux/smb.h>
77 #endif
78 #endif
79 #include <sys/vfs.h>
80 #elif defined(_AIX)
81 #include <sys/statfs.h>
82 
83 // <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
84 // `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
85 // the typedef prior to including <sys/vmount.h> to work around this issue.
86 typedef uint_t uint;
87 #include <sys/vmount.h>
88 #else
89 #include <sys/mount.h>
90 #endif
91 #define STATVFS statfs
92 #define FSTATVFS fstatfs
93 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
94 #endif
95 
96 #if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
97 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
98 #else
99 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
100 #endif
101 
102 using namespace llvm;
103 
104 namespace llvm {
105 namespace sys {
106 namespace fs {
107 
108 const file_t kInvalidFile = -1;
109 
110 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
111  defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
112  defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__)
113 static int
114 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
115 {
116  struct stat sb;
117  char fullpath[PATH_MAX];
118 
119  int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
120  // We cannot write PATH_MAX characters because the string will be terminated
121  // with a null character. Fail if truncation happened.
122  if (chars >= PATH_MAX)
123  return 1;
124  if (!realpath(fullpath, ret))
125  return 1;
126  if (stat(fullpath, &sb) != 0)
127  return 1;
128 
129  return 0;
130 }
131 
132 static char *
133 getprogpath(char ret[PATH_MAX], const char *bin)
134 {
135  /* First approach: absolute path. */
136  if (bin[0] == '/') {
137  if (test_dir(ret, "/", bin) == 0)
138  return ret;
139  return nullptr;
140  }
141 
142  /* Second approach: relative path. */
143  if (strchr(bin, '/')) {
144  char cwd[PATH_MAX];
145  if (!getcwd(cwd, PATH_MAX))
146  return nullptr;
147  if (test_dir(ret, cwd, bin) == 0)
148  return ret;
149  return nullptr;
150  }
151 
152  /* Third approach: $PATH */
153  char *pv;
154  if ((pv = getenv("PATH")) == nullptr)
155  return nullptr;
156  char *s = strdup(pv);
157  if (!s)
158  return nullptr;
159  char *state;
160  for (char *t = strtok_r(s, ":", &state); t != nullptr;
161  t = strtok_r(nullptr, ":", &state)) {
162  if (test_dir(ret, t, bin) == 0) {
163  free(s);
164  return ret;
165  }
166  }
167  free(s);
168  return nullptr;
169 }
170 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
171 
172 /// GetMainExecutable - Return the path to the main executable, given the
173 /// value of argv[0] from program startup.
174 std::string getMainExecutable(const char *argv0, void *MainAddr) {
175 #if defined(__APPLE__)
176  // On OS X the executable path is saved to the stack by dyld. Reading it
177  // from there is much faster than calling dladdr, especially for large
178  // binaries with symbols.
179  char exe_path[MAXPATHLEN];
180  uint32_t size = sizeof(exe_path);
181  if (_NSGetExecutablePath(exe_path, &size) == 0) {
182  char link_path[MAXPATHLEN];
183  if (realpath(exe_path, link_path))
184  return link_path;
185  }
186 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
187  defined(__minix) || defined(__DragonFly__) || \
188  defined(__FreeBSD_kernel__) || defined(_AIX)
189  const char *curproc = "/proc/curproc/file";
190  char exe_path[PATH_MAX];
191  // /proc is not mounted by default under FreeBSD, but gives more accurate
192  // information than argv[0] when it is.
193  if (sys::fs::exists(curproc)) {
194  ssize_t len = readlink(curproc, exe_path, sizeof(exe_path));
195  if (len > 0) {
196  // Null terminate the string for realpath. readlink never null
197  // terminates its output.
198  len = std::min(len, ssize_t(sizeof(exe_path) - 1));
199  exe_path[len] = '\0';
200  return exe_path;
201  }
202  }
203  // If we don't have procfs mounted, fall back to argv[0]
204  if (getprogpath(exe_path, argv0) != NULL)
205  return exe_path;
206 #elif defined(__linux__) || defined(__CYGWIN__)
207  char exe_path[MAXPATHLEN];
208  const char *aPath = "/proc/self/exe";
209  if (sys::fs::exists(aPath)) {
210  // /proc is not always mounted under Linux (chroot for example).
211  ssize_t len = readlink(aPath, exe_path, sizeof(exe_path));
212  if (len < 0)
213  return "";
214 
215  // Null terminate the string for realpath. readlink never null
216  // terminates its output.
217  len = std::min(len, ssize_t(sizeof(exe_path) - 1));
218  exe_path[len] = '\0';
219 
220  // On Linux, /proc/self/exe always looks through symlinks. However, on
221  // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
222  // the program, and not the eventual binary file. Therefore, call realpath
223  // so this behaves the same on all platforms.
224 #if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
225  if (char *real_path = realpath(exe_path, NULL)) {
226  std::string ret = std::string(real_path);
227  free(real_path);
228  return ret;
229  }
230 #else
231  char real_path[MAXPATHLEN];
232  if (realpath(exe_path, real_path))
233  return std::string(real_path);
234 #endif
235  }
236  // Fall back to the classical detection.
237  if (getprogpath(exe_path, argv0))
238  return exe_path;
239 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
240  // Use dladdr to get executable path if available.
241  Dl_info DLInfo;
242  int err = dladdr(MainAddr, &DLInfo);
243  if (err == 0)
244  return "";
245 
246  // If the filename is a symlink, we need to resolve and return the location of
247  // the actual executable.
248  char link_path[MAXPATHLEN];
249  if (realpath(DLInfo.dli_fname, link_path))
250  return link_path;
251 #else
252 #error GetMainExecutable is not implemented on this host yet.
253 #endif
254  return "";
255 }
256 
257 TimePoint<> basic_file_status::getLastAccessedTime() const {
259 }
260 
261 TimePoint<> basic_file_status::getLastModificationTime() const {
263 }
264 
265 UniqueID file_status::getUniqueID() const {
266  return UniqueID(fs_st_dev, fs_st_ino);
267 }
268 
270  return fs_st_nlinks;
271 }
272 
273 ErrorOr<space_info> disk_space(const Twine &Path) {
274  struct STATVFS Vfs;
275  if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
276  return std::error_code(errno, std::generic_category());
277  auto FrSize = STATVFS_F_FRSIZE(Vfs);
278  space_info SpaceInfo;
279  SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
280  SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
281  SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
282  return SpaceInfo;
283 }
284 
285 std::error_code current_path(SmallVectorImpl<char> &result) {
286  result.clear();
287 
288  const char *pwd = ::getenv("PWD");
289  llvm::sys::fs::file_status PWDStatus, DotStatus;
290  if (pwd && llvm::sys::path::is_absolute(pwd) &&
291  !llvm::sys::fs::status(pwd, PWDStatus) &&
292  !llvm::sys::fs::status(".", DotStatus) &&
293  PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
294  result.append(pwd, pwd + strlen(pwd));
295  return std::error_code();
296  }
297 
298 #ifdef MAXPATHLEN
299  result.reserve(MAXPATHLEN);
300 #else
301 // For GNU Hurd
302  result.reserve(1024);
303 #endif
304 
305  while (true) {
306  if (::getcwd(result.data(), result.capacity()) == nullptr) {
307  // See if there was a real error.
308  if (errno != ENOMEM)
309  return std::error_code(errno, std::generic_category());
310  // Otherwise there just wasn't enough space.
311  result.reserve(result.capacity() * 2);
312  } else
313  break;
314  }
315 
316  result.set_size(strlen(result.data()));
317  return std::error_code();
318 }
319 
320 std::error_code set_current_path(const Twine &path) {
321  SmallString<128> path_storage;
322  StringRef p = path.toNullTerminatedStringRef(path_storage);
323 
324  if (::chdir(p.begin()) == -1)
325  return std::error_code(errno, std::generic_category());
326 
327  return std::error_code();
328 }
329 
330 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
331  perms Perms) {
332  SmallString<128> path_storage;
333  StringRef p = path.toNullTerminatedStringRef(path_storage);
334 
335  if (::mkdir(p.begin(), Perms) == -1) {
336  if (errno != EEXIST || !IgnoreExisting)
337  return std::error_code(errno, std::generic_category());
338  }
339 
340  return std::error_code();
341 }
342 
343 // Note that we are using symbolic link because hard links are not supported by
344 // all filesystems (SMB doesn't).
345 std::error_code create_link(const Twine &to, const Twine &from) {
346  // Get arguments.
347  SmallString<128> from_storage;
348  SmallString<128> to_storage;
349  StringRef f = from.toNullTerminatedStringRef(from_storage);
350  StringRef t = to.toNullTerminatedStringRef(to_storage);
351 
352  if (::symlink(t.begin(), f.begin()) == -1)
353  return std::error_code(errno, std::generic_category());
354 
355  return std::error_code();
356 }
357 
358 std::error_code create_hard_link(const Twine &to, const Twine &from) {
359  // Get arguments.
360  SmallString<128> from_storage;
361  SmallString<128> to_storage;
362  StringRef f = from.toNullTerminatedStringRef(from_storage);
363  StringRef t = to.toNullTerminatedStringRef(to_storage);
364 
365  if (::link(t.begin(), f.begin()) == -1)
366  return std::error_code(errno, std::generic_category());
367 
368  return std::error_code();
369 }
370 
371 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
372  SmallString<128> path_storage;
373  StringRef p = path.toNullTerminatedStringRef(path_storage);
374 
375  struct stat buf;
376  if (lstat(p.begin(), &buf) != 0) {
377  if (errno != ENOENT || !IgnoreNonExisting)
378  return std::error_code(errno, std::generic_category());
379  return std::error_code();
380  }
381 
382  // Note: this check catches strange situations. In all cases, LLVM should
383  // only be involved in the creation and deletion of regular files. This
384  // check ensures that what we're trying to erase is a regular file. It
385  // effectively prevents LLVM from erasing things like /dev/null, any block
386  // special file, or other things that aren't "regular" files.
387  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
389 
390  if (::remove(p.begin()) == -1) {
391  if (errno != ENOENT || !IgnoreNonExisting)
392  return std::error_code(errno, std::generic_category());
393  }
394 
395  return std::error_code();
396 }
397 
398 static bool is_local_impl(struct STATVFS &Vfs) {
399 #if defined(__linux__) || defined(__GNU__)
400 #ifndef NFS_SUPER_MAGIC
401 #define NFS_SUPER_MAGIC 0x6969
402 #endif
403 #ifndef SMB_SUPER_MAGIC
404 #define SMB_SUPER_MAGIC 0x517B
405 #endif
406 #ifndef CIFS_MAGIC_NUMBER
407 #define CIFS_MAGIC_NUMBER 0xFF534D42
408 #endif
409 #ifdef __GNU__
410  switch ((uint32_t)Vfs.__f_type) {
411 #else
412  switch ((uint32_t)Vfs.f_type) {
413 #endif
414  case NFS_SUPER_MAGIC:
415  case SMB_SUPER_MAGIC:
416  case CIFS_MAGIC_NUMBER:
417  return false;
418  default:
419  return true;
420  }
421 #elif defined(__CYGWIN__)
422  // Cygwin doesn't expose this information; would need to use Win32 API.
423  return false;
424 #elif defined(__Fuchsia__)
425  // Fuchsia doesn't yet support remote filesystem mounts.
426  return true;
427 #elif defined(__EMSCRIPTEN__)
428  // Emscripten doesn't currently support remote filesystem mounts.
429  return true;
430 #elif defined(__HAIKU__)
431  // Haiku doesn't expose this information.
432  return false;
433 #elif defined(__sun)
434  // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
435  StringRef fstype(Vfs.f_basetype);
436  // NFS is the only non-local fstype??
437  return !fstype.equals("nfs");
438 #elif defined(_AIX)
439  // Call mntctl; try more than twice in case of timing issues with a concurrent
440  // mount.
441  int Ret;
442  size_t BufSize = 2048u;
443  std::unique_ptr<char[]> Buf;
444  int Tries = 3;
445  while (Tries--) {
446  Buf = std::make_unique<char[]>(BufSize);
447  Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
448  if (Ret != 0)
449  break;
450  BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
451  Buf.reset();
452  }
453 
454  if (Ret == -1)
455  // There was an error; "remote" is the conservative answer.
456  return false;
457 
458  // Look for the correct vmount entry.
459  char *CurObjPtr = Buf.get();
460  while (Ret--) {
461  struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
462  static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
463  "fsid length mismatch");
464  if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
465  return (Vp->vmt_flags & MNT_REMOTE) == 0;
466 
467  CurObjPtr += Vp->vmt_length;
468  }
469 
470  // vmount entry not found; "remote" is the conservative answer.
471  return false;
472 #else
473  return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
474 #endif
475 }
476 
477 std::error_code is_local(const Twine &Path, bool &Result) {
478  struct STATVFS Vfs;
479  if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
480  return std::error_code(errno, std::generic_category());
481 
482  Result = is_local_impl(Vfs);
483  return std::error_code();
484 }
485 
486 std::error_code is_local(int FD, bool &Result) {
487  struct STATVFS Vfs;
488  if (::FSTATVFS(FD, &Vfs))
489  return std::error_code(errno, std::generic_category());
490 
491  Result = is_local_impl(Vfs);
492  return std::error_code();
493 }
494 
495 std::error_code rename(const Twine &from, const Twine &to) {
496  // Get arguments.
497  SmallString<128> from_storage;
498  SmallString<128> to_storage;
499  StringRef f = from.toNullTerminatedStringRef(from_storage);
500  StringRef t = to.toNullTerminatedStringRef(to_storage);
501 
502  if (::rename(f.begin(), t.begin()) == -1)
503  return std::error_code(errno, std::generic_category());
504 
505  return std::error_code();
506 }
507 
508 std::error_code resize_file(int FD, uint64_t Size) {
509 #if defined(HAVE_POSIX_FALLOCATE)
510  // If we have posix_fallocate use it. Unlike ftruncate it always allocates
511  // space, so we get an error if the disk is full.
512  if (int Err = ::posix_fallocate(FD, 0, Size)) {
513 #ifdef _AIX
514  constexpr int NotSupportedError = ENOTSUP;
515 #else
516  constexpr int NotSupportedError = EOPNOTSUPP;
517 #endif
518  if (Err != EINVAL && Err != NotSupportedError)
519  return std::error_code(Err, std::generic_category());
520  }
521 #endif
522  // Use ftruncate as a fallback. It may or may not allocate space. At least on
523  // OS X with HFS+ it does.
524  if (::ftruncate(FD, Size) == -1)
525  return std::error_code(errno, std::generic_category());
526 
527  return std::error_code();
528 }
529 
530 static int convertAccessMode(AccessMode Mode) {
531  switch (Mode) {
532  case AccessMode::Exist:
533  return F_OK;
534  case AccessMode::Write:
535  return W_OK;
536  case AccessMode::Execute:
537  return R_OK | X_OK; // scripts also need R_OK.
538  }
539  llvm_unreachable("invalid enum");
540 }
541 
542 std::error_code access(const Twine &Path, AccessMode Mode) {
543  SmallString<128> PathStorage;
544  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
545 
546  if (::access(P.begin(), convertAccessMode(Mode)) == -1)
547  return std::error_code(errno, std::generic_category());
548 
549  if (Mode == AccessMode::Execute) {
550  // Don't say that directories are executable.
551  struct stat buf;
552  if (0 != stat(P.begin(), &buf))
554  if (!S_ISREG(buf.st_mode))
556  }
557 
558  return std::error_code();
559 }
560 
561 bool can_execute(const Twine &Path) {
562  return !access(Path, AccessMode::Execute);
563 }
564 
565 bool equivalent(file_status A, file_status B) {
566  assert(status_known(A) && status_known(B));
567  return A.fs_st_dev == B.fs_st_dev &&
568  A.fs_st_ino == B.fs_st_ino;
569 }
570 
571 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
572  file_status fsA, fsB;
573  if (std::error_code ec = status(A, fsA))
574  return ec;
575  if (std::error_code ec = status(B, fsB))
576  return ec;
577  result = equivalent(fsA, fsB);
578  return std::error_code();
579 }
580 
581 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
582  StringRef PathStr(Path.begin(), Path.size());
583  if (PathStr.empty() || !PathStr.startswith("~"))
584  return;
585 
586  PathStr = PathStr.drop_front();
587  StringRef Expr =
588  PathStr.take_until([](char c) { return path::is_separator(c); });
589  StringRef Remainder = PathStr.substr(Expr.size() + 1);
590  SmallString<128> Storage;
591  if (Expr.empty()) {
592  // This is just ~/..., resolve it to the current user's home dir.
593  if (!path::home_directory(Storage)) {
594  // For some reason we couldn't get the home directory. Just exit.
595  return;
596  }
597 
598  // Overwrite the first character and insert the rest.
599  Path[0] = Storage[0];
600  Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
601  return;
602  }
603 
604  // This is a string of the form ~username/, look up this user's entry in the
605  // password database.
606  struct passwd *Entry = nullptr;
607  std::string User = Expr.str();
608  Entry = ::getpwnam(User.c_str());
609 
610  if (!Entry) {
611  // Unable to look up the entry, just return back the original path.
612  return;
613  }
614 
615  Storage = Remainder;
616  Path.clear();
617  Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
618  llvm::sys::path::append(Path, Storage);
619 }
620 
621 
622 void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
623  dest.clear();
624  if (path.isTriviallyEmpty())
625  return;
626 
627  path.toVector(dest);
628  expandTildeExpr(dest);
629 
630  return;
631 }
632 
633 static file_type typeForMode(mode_t Mode) {
634  if (S_ISDIR(Mode))
636  else if (S_ISREG(Mode))
638  else if (S_ISBLK(Mode))
639  return file_type::block_file;
640  else if (S_ISCHR(Mode))
642  else if (S_ISFIFO(Mode))
643  return file_type::fifo_file;
644  else if (S_ISSOCK(Mode))
645  return file_type::socket_file;
646  else if (S_ISLNK(Mode))
649 }
650 
651 static std::error_code fillStatus(int StatRet, const struct stat &Status,
652  file_status &Result) {
653  if (StatRet != 0) {
654  std::error_code EC(errno, std::generic_category());
656  Result = file_status(file_type::file_not_found);
657  else
658  Result = file_status(file_type::status_error);
659  return EC;
660  }
661 
662  uint32_t atime_nsec, mtime_nsec;
663 #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
664  atime_nsec = Status.st_atimespec.tv_nsec;
665  mtime_nsec = Status.st_mtimespec.tv_nsec;
666 #elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
667  atime_nsec = Status.st_atim.tv_nsec;
668  mtime_nsec = Status.st_mtim.tv_nsec;
669 #else
670  atime_nsec = mtime_nsec = 0;
671 #endif
672 
673  perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
674  Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
675  Status.st_nlink, Status.st_ino,
676  Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
677  Status.st_uid, Status.st_gid, Status.st_size);
678 
679  return std::error_code();
680 }
681 
682 std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
683  SmallString<128> PathStorage;
684  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
685 
686  struct stat Status;
687  int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
688  return fillStatus(StatRet, Status, Result);
689 }
690 
691 std::error_code status(int FD, file_status &Result) {
692  struct stat Status;
693  int StatRet = ::fstat(FD, &Status);
694  return fillStatus(StatRet, Status, Result);
695 }
696 
697 unsigned getUmask() {
698  // Chose arbitary new mask and reset the umask to the old mask.
699  // umask(2) never fails so ignore the return of the second call.
700  unsigned Mask = ::umask(0);
701  (void) ::umask(Mask);
702  return Mask;
703 }
704 
705 std::error_code setPermissions(const Twine &Path, perms Permissions) {
706  SmallString<128> PathStorage;
707  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
708 
709  if (::chmod(P.begin(), Permissions))
710  return std::error_code(errno, std::generic_category());
711  return std::error_code();
712 }
713 
714 std::error_code setPermissions(int FD, perms Permissions) {
715  if (::fchmod(FD, Permissions))
716  return std::error_code(errno, std::generic_category());
717  return std::error_code();
718 }
719 
720 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
721  TimePoint<> ModificationTime) {
722 #if defined(HAVE_FUTIMENS)
723  timespec Times[2];
724  Times[0] = sys::toTimeSpec(AccessTime);
725  Times[1] = sys::toTimeSpec(ModificationTime);
726  if (::futimens(FD, Times))
727  return std::error_code(errno, std::generic_category());
728  return std::error_code();
729 #elif defined(HAVE_FUTIMES)
730  timeval Times[2];
731  Times[0] = sys::toTimeVal(
732  std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
733  Times[1] =
734  sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
735  ModificationTime));
736  if (::futimes(FD, Times))
737  return std::error_code(errno, std::generic_category());
738  return std::error_code();
739 #else
740 #warning Missing futimes() and futimens()
742 #endif
743 }
744 
745 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
746  mapmode Mode) {
747  assert(Size != 0);
748 
749  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
750  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
751 #if defined(__APPLE__)
752  //----------------------------------------------------------------------
753  // Newer versions of MacOSX have a flag that will allow us to read from
754  // binaries whose code signature is invalid without crashing by using
755  // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
756  // is mapped we can avoid crashing and return zeroes to any pages we try
757  // to read if the media becomes unavailable by using the
758  // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
759  // with PROT_READ, so take care not to specify them otherwise.
760  //----------------------------------------------------------------------
761  if (Mode == readonly) {
762 #if defined(MAP_RESILIENT_CODESIGN)
763  flags |= MAP_RESILIENT_CODESIGN;
764 #endif
765 #if defined(MAP_RESILIENT_MEDIA)
766  flags |= MAP_RESILIENT_MEDIA;
767 #endif
768  }
769 #endif // #if defined (__APPLE__)
770 
771  Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
772  if (Mapping == MAP_FAILED)
773  return std::error_code(errno, std::generic_category());
774  return std::error_code();
775 }
776 
777 mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
778  uint64_t offset, std::error_code &ec)
779  : Size(length), Mapping(), Mode(mode) {
780  (void)Mode;
781  ec = init(fd, offset, mode);
782  if (ec)
783  Mapping = nullptr;
784 }
785 
786 mapped_file_region::~mapped_file_region() {
787  if (Mapping)
788  ::munmap(Mapping, Size);
789 }
790 
791 size_t mapped_file_region::size() const {
792  assert(Mapping && "Mapping failed but used anyway!");
793  return Size;
794 }
795 
796 char *mapped_file_region::data() const {
797  assert(Mapping && "Mapping failed but used anyway!");
798  return reinterpret_cast<char*>(Mapping);
799 }
800 
801 const char *mapped_file_region::const_data() const {
802  assert(Mapping && "Mapping failed but used anyway!");
803  return reinterpret_cast<const char*>(Mapping);
804 }
805 
806 int mapped_file_region::alignment() {
808 }
809 
810 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
811  StringRef path,
812  bool follow_symlinks) {
813  SmallString<128> path_null(path);
814  DIR *directory = ::opendir(path_null.c_str());
815  if (!directory)
816  return std::error_code(errno, std::generic_category());
817 
818  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
819  // Add something for replace_filename to replace.
820  path::append(path_null, ".");
821  it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
822  return directory_iterator_increment(it);
823 }
824 
825 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
826  if (it.IterationHandle)
827  ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
828  it.IterationHandle = 0;
829  it.CurrentEntry = directory_entry();
830  return std::error_code();
831 }
832 
833 static file_type direntType(dirent* Entry) {
834  // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
835  // The DTTOIF macro lets us reuse our status -> type conversion.
836  // Note that while glibc provides a macro to see if this is supported,
837  // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
838  // d_type-to-mode_t conversion macro instead.
839 #if defined(DTTOIF)
840  return typeForMode(DTTOIF(Entry->d_type));
841 #else
842  // Other platforms such as Solaris require a stat() to get the type.
843  return file_type::type_unknown;
844 #endif
845 }
846 
847 std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
848  errno = 0;
849  dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
850  if (CurDir == nullptr && errno != 0) {
851  return std::error_code(errno, std::generic_category());
852  } else if (CurDir != nullptr) {
853  StringRef Name(CurDir->d_name);
854  if ((Name.size() == 1 && Name[0] == '.') ||
855  (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
856  return directory_iterator_increment(It);
857  It.CurrentEntry.replace_filename(Name, direntType(CurDir));
858  } else
859  return directory_iterator_destruct(It);
860 
861  return std::error_code();
862 }
863 
865  file_status s;
866  if (auto EC = fs::status(Path, s, FollowSymlinks))
867  return EC;
868  return s;
869 }
870 
871 #if !defined(F_GETPATH)
872 static bool hasProcSelfFD() {
873  // If we have a /proc filesystem mounted, we can quickly establish the
874  // real name of the file with readlink
875  static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
876  return Result;
877 }
878 #endif
879 
880 static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
881  FileAccess Access) {
882  int Result = 0;
883  if (Access == FA_Read)
884  Result |= O_RDONLY;
885  else if (Access == FA_Write)
886  Result |= O_WRONLY;
887  else if (Access == (FA_Read | FA_Write))
888  Result |= O_RDWR;
889 
890  // This is for compatibility with old code that assumed OF_Append implied
891  // would open an existing file. See Windows/Path.inc for a longer comment.
892  if (Flags & OF_Append)
893  Disp = CD_OpenAlways;
894 
895  if (Disp == CD_CreateNew) {
896  Result |= O_CREAT; // Create if it doesn't exist.
897  Result |= O_EXCL; // Fail if it does.
898  } else if (Disp == CD_CreateAlways) {
899  Result |= O_CREAT; // Create if it doesn't exist.
900  Result |= O_TRUNC; // Truncate if it does.
901  } else if (Disp == CD_OpenAlways) {
902  Result |= O_CREAT; // Create if it doesn't exist.
903  } else if (Disp == CD_OpenExisting) {
904  // Nothing special, just don't add O_CREAT and we get these semantics.
905  }
906 
907  if (Flags & OF_Append)
908  Result |= O_APPEND;
909 
910 #ifdef O_CLOEXEC
911  if (!(Flags & OF_ChildInherit))
912  Result |= O_CLOEXEC;
913 #endif
914 
915  return Result;
916 }
917 
918 std::error_code openFile(const Twine &Name, int &ResultFD,
919  CreationDisposition Disp, FileAccess Access,
920  OpenFlags Flags, unsigned Mode) {
921  int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
922 
923  SmallString<128> Storage;
924  StringRef P = Name.toNullTerminatedStringRef(Storage);
925  // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
926  // when open is overloaded, such as in Bionic.
927  auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
928  if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
929  return std::error_code(errno, std::generic_category());
930 #ifndef O_CLOEXEC
931  if (!(Flags & OF_ChildInherit)) {
932  int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
933  (void)r;
934  assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
935  }
936 #endif
937  return std::error_code();
938 }
939 
941  FileAccess Access, OpenFlags Flags,
942  unsigned Mode) {
943 
944  int FD;
945  std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
946  if (EC)
947  return errorCodeToError(EC);
948  return FD;
949 }
950 
951 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
952  OpenFlags Flags,
953  SmallVectorImpl<char> *RealPath) {
954  std::error_code EC =
955  openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
956  if (EC)
957  return EC;
958 
959  // Attempt to get the real name of the file, if the user asked
960  if(!RealPath)
961  return std::error_code();
962  RealPath->clear();
963 #if defined(F_GETPATH)
964  // When F_GETPATH is availble, it is the quickest way to get
965  // the real path name.
966  char Buffer[MAXPATHLEN];
967  if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
968  RealPath->append(Buffer, Buffer + strlen(Buffer));
969 #else
970  char Buffer[PATH_MAX];
971  if (hasProcSelfFD()) {
972  char ProcPath[64];
973  snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
974  ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
975  if (CharCount > 0)
976  RealPath->append(Buffer, Buffer + CharCount);
977  } else {
978  SmallString<128> Storage;
979  StringRef P = Name.toNullTerminatedStringRef(Storage);
980 
981  // Use ::realpath to get the real path name
982  if (::realpath(P.begin(), Buffer) != nullptr)
983  RealPath->append(Buffer, Buffer + strlen(Buffer));
984  }
985 #endif
986  return std::error_code();
987 }
988 
989 Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
990  SmallVectorImpl<char> *RealPath) {
991  file_t ResultFD;
992  std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
993  if (EC)
994  return errorCodeToError(EC);
995  return ResultFD;
996 }
997 
998 file_t getStdinHandle() { return 0; }
999 file_t getStdoutHandle() { return 1; }
1000 file_t getStderrHandle() { return 2; }
1001 
1003  ssize_t NumRead =
1004  sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Buf.size());
1005  if (ssize_t(NumRead) == -1)
1006  return errorCodeToError(std::error_code(errno, std::generic_category()));
1007  return NumRead;
1008 }
1009 
1011  uint64_t Offset) {
1012 #ifdef HAVE_PREAD
1013  ssize_t NumRead =
1014  sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Buf.size(), Offset);
1015 #else
1016  if (lseek(FD, Offset, SEEK_SET) == -1)
1017  return errorCodeToError(std::error_code(errno, std::generic_category()));
1018  ssize_t NumRead =
1019  sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Buf.size());
1020 #endif
1021  if (NumRead == -1)
1022  return errorCodeToError(std::error_code(errno, std::generic_category()));
1023  return NumRead;
1024 }
1025 
1026 std::error_code closeFile(file_t &F) {
1027  file_t TmpF = F;
1028  F = kInvalidFile;
1030 }
1031 
1032 template <typename T>
1033 static std::error_code remove_directories_impl(const T &Entry,
1034  bool IgnoreErrors) {
1035  std::error_code EC;
1036  directory_iterator Begin(Entry, EC, false);
1037  directory_iterator End;
1038  while (Begin != End) {
1039  auto &Item = *Begin;
1040  ErrorOr<basic_file_status> st = Item.status();
1041  if (!st && !IgnoreErrors)
1042  return st.getError();
1043 
1044  if (is_directory(*st)) {
1045  EC = remove_directories_impl(Item, IgnoreErrors);
1046  if (EC && !IgnoreErrors)
1047  return EC;
1048  }
1049 
1050  EC = fs::remove(Item.path(), true);
1051  if (EC && !IgnoreErrors)
1052  return EC;
1053 
1054  Begin.increment(EC);
1055  if (EC && !IgnoreErrors)
1056  return EC;
1057  }
1058  return std::error_code();
1059 }
1060 
1061 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1062  auto EC = remove_directories_impl(path, IgnoreErrors);
1063  if (EC && !IgnoreErrors)
1064  return EC;
1065  EC = fs::remove(path, true);
1066  if (EC && !IgnoreErrors)
1067  return EC;
1068  return std::error_code();
1069 }
1070 
1071 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1072  bool expand_tilde) {
1073  dest.clear();
1074  if (path.isTriviallyEmpty())
1075  return std::error_code();
1076 
1077  if (expand_tilde) {
1078  SmallString<128> Storage;
1079  path.toVector(Storage);
1080  expandTildeExpr(Storage);
1081  return real_path(Storage, dest, false);
1082  }
1083 
1084  SmallString<128> Storage;
1085  StringRef P = path.toNullTerminatedStringRef(Storage);
1086  char Buffer[PATH_MAX];
1087  if (::realpath(P.begin(), Buffer) == nullptr)
1088  return std::error_code(errno, std::generic_category());
1089  dest.append(Buffer, Buffer + strlen(Buffer));
1090  return std::error_code();
1091 }
1092 
1093 } // end namespace fs
1094 
1095 namespace path {
1096 
1097 bool home_directory(SmallVectorImpl<char> &result) {
1098  char *RequestedDir = getenv("HOME");
1099  if (!RequestedDir) {
1100  struct passwd *pw = getpwuid(getuid());
1101  if (pw && pw->pw_dir)
1102  RequestedDir = pw->pw_dir;
1103  }
1104  if (!RequestedDir)
1105  return false;
1106 
1107  result.clear();
1108  result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1109  return true;
1110 }
1111 
1112 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1113  #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1114  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1115  // macros defined in <unistd.h> on darwin >= 9
1116  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1117  : _CS_DARWIN_USER_CACHE_DIR;
1118  size_t ConfLen = confstr(ConfName, nullptr, 0);
1119  if (ConfLen > 0) {
1120  do {
1121  Result.resize(ConfLen);
1122  ConfLen = confstr(ConfName, Result.data(), Result.size());
1123  } while (ConfLen > 0 && ConfLen != Result.size());
1124 
1125  if (ConfLen > 0) {
1126  assert(Result.back() == 0);
1127  Result.pop_back();
1128  return true;
1129  }
1130 
1131  Result.clear();
1132  }
1133  #endif
1134  return false;
1135 }
1136 
1137 static const char *getEnvTempDir() {
1138  // Check whether the temporary directory is specified by an environment
1139  // variable.
1140  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1141  for (const char *Env : EnvironmentVariables) {
1142  if (const char *Dir = std::getenv(Env))
1143  return Dir;
1144  }
1145 
1146  return nullptr;
1147 }
1148 
1149 static const char *getDefaultTempDir(bool ErasedOnReboot) {
1150 #ifdef P_tmpdir
1151  if ((bool)P_tmpdir)
1152  return P_tmpdir;
1153 #endif
1154 
1155  if (ErasedOnReboot)
1156  return "/tmp";
1157  return "/var/tmp";
1158 }
1159 
1160 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1161  Result.clear();
1162 
1163  if (ErasedOnReboot) {
1164  // There is no env variable for the cache directory.
1165  if (const char *RequestedDir = getEnvTempDir()) {
1166  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1167  return;
1168  }
1169  }
1170 
1171  if (getDarwinConfDir(ErasedOnReboot, Result))
1172  return;
1173 
1174  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1175  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1176 }
1177 
1178 } // end namespace path
1179 
1180 namespace fs {
1181 
1182 #ifdef __APPLE__
1183 /// This implementation tries to perform an APFS CoW clone of the file,
1184 /// which can be much faster and uses less space.
1185 /// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1186 /// file descriptor variant of this function still uses the default
1187 /// implementation.
1188 std::error_code copy_file(const Twine &From, const Twine &To) {
1189  uint32_t Flag = COPYFILE_DATA;
1190 #if __has_builtin(__builtin_available) && defined(COPYFILE_CLONE)
1191  if (__builtin_available(macos 10.12, *)) {
1192  bool IsSymlink;
1193  if (std::error_code Error = is_symlink_file(From, IsSymlink))
1194  return Error;
1195  // COPYFILE_CLONE clones the symlink instead of following it
1196  // and returns EEXISTS if the target file already exists.
1197  if (!IsSymlink && !exists(To))
1198  Flag = COPYFILE_CLONE;
1199  }
1200 #endif
1201  int Status =
1202  copyfile(From.str().c_str(), To.str().c_str(), /* State */ NULL, Flag);
1203 
1204  if (Status == 0)
1205  return std::error_code();
1206  return std::error_code(errno, std::generic_category());
1207 }
1208 #endif // __APPLE__
1209 
1210 } // end namespace fs
1211 
1212 } // end namespace sys
1213 } // end namespace llvm
const file_t kInvalidFile
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:593
bool can_execute(const Twine &Path)
Can we execute this file?
Represents either an error or a value T.
Definition: ErrorOr.h:56
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:232
SI Whole Quad Mode
bool status_known(const basic_file_status &s)
Is status available?
Definition: Path.cpp:1029
This class represents lattice values for constants.
Definition: AllocatorList.h:23
std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_NODISCARD StringRef take_until(function_ref< bool(char)> F) const
Return the longest prefix of &#39;this&#39; such that no character in the prefix satisfies the given predicat...
Definition: StringRef.h:627
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
file_t getStderrHandle()
Return an open handle to standard error.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
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:400
std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition: Path.cpp:1040
Expected< file_t > openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a platform-s...
F(f)
void reserve(size_type N)
Definition: SmallVector.h:369
std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
Represents the result of a call to sys::fs::status().
Definition: FileSystem.h:246
CD_OpenExisting - When opening a file:
Definition: FileSystem.h:748
Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
struct timespec toTimeSpec(TimePoint<> TP)
Convert a time point to struct timespec.
Definition: Unix.h:83
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:455
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:634
std::error_code make_error_code(BitcodeError E)
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition: Path.cpp:663
Tagged union holding either a T or a Error.
Definition: yaml2obj.h:21
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:592
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:140
When a child process is launched, this file should remain open in the child process.
Definition: FileSystem.h:779
unsigned getUmask()
Get file creation mode mask of the process.
CD_CreateNew - When opening a file:
Definition: FileSystem.h:743
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.
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:144
static unsigned getPageSizeEstimate()
Get the process&#39;s estimated page size.
Definition: Process.h:56
file_t getStdinHandle()
Return an open handle to standard in.
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...
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:131
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:964
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:290
void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user&#39;s home directory.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
UniqueID getUniqueID() const
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
void set_size(size_t N)
Set the array size to N, which the current array must have enough capacity for.
Definition: SmallVector.h:66
std::error_code getError() const
Definition: ErrorOr.h:159
uint32_t getLinkCount() const
TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single null terminated StringRef if it can be represented as such...
Definition: Twine.cpp:37
std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
auto RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As) -> decltype(F(As...))
Definition: Errno.h:33
struct timeval toTimeVal(TimePoint< std::chrono::microseconds > TP)
Convert a time point to struct timeval.
Definition: Unix.h:93
Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
size_t capacity() const
Definition: SmallVector.h:53
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition: Twine.cpp:32
size_t size() const
Definition: SmallVector.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1146
std::error_code directory_iterator_construct(DirIterState &, StringRef, bool)
BlockVerifier::State From
The file should be opened in append mode.
Definition: FileSystem.h:771
Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
std::error_code closeFile(file_t &F)
Close the file object.
std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
iterator insert(iterator I, T &&Elt)
Definition: SmallVector.h:467
std::error_code set_current_path(const Twine &path)
Set the current path.
iterator begin() const
Definition: StringRef.h:115
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:387
ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
std::error_code directory_iterator_destruct(DirIterState &)
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:927
file_type
An enumeration for the file system&#39;s view of the type.
Definition: FileSystem.h:66
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition: Endian.h:65
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
uint32_t Size
Definition: Profile.cpp:46
T * data() const
Definition: ArrayRef.h:328
static std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
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&#39;s represent the same thing?
CD_CreateAlways - When opening a file:
Definition: FileSystem.h:738
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
static std::error_code SafelyCloseFileDescriptor(int FD)
bool home_directory(SmallVectorImpl< char > &result)
Get the user&#39;s home directory.
file_t getStdoutHandle()
Return an open handle to standard out.
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:48
CD_OpenAlways - When opening a file:
Definition: FileSystem.h:753
TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
bool is_symlink_file(const basic_file_status &status)
Does status represent a symlink file?
Definition: Path.cpp:1064
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1025
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
Definition: Chrono.h:44
void resize(size_type N)
Definition: SmallVector.h:344