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