LCOV - code coverage report
Current view: top level - lib/Support/Unix - Path.inc (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 287 363 79.1 %
Date: 2018-07-13 00:08:38 Functions: 47 54 87.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the Unix specific implementation of the Path API.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : //===----------------------------------------------------------------------===//
      15             : //=== WARNING: Implementation here must contain only generic UNIX code that
      16             : //===          is guaranteed to work on *all* UNIX variants.
      17             : //===----------------------------------------------------------------------===//
      18             : 
      19             : #include "Unix.h"
      20             : #include <limits.h>
      21             : #include <stdio.h>
      22             : #if HAVE_SYS_STAT_H
      23             : #include <sys/stat.h>
      24             : #endif
      25             : #if HAVE_FCNTL_H
      26             : #include <fcntl.h>
      27             : #endif
      28             : #ifdef HAVE_UNISTD_H
      29             : #include <unistd.h>
      30             : #endif
      31             : #ifdef HAVE_SYS_MMAN_H
      32             : #include <sys/mman.h>
      33             : #endif
      34             : 
      35             : #include <dirent.h>
      36             : #include <pwd.h>
      37             : 
      38             : #ifdef __APPLE__
      39             : #include <mach-o/dyld.h>
      40             : #include <sys/attr.h>
      41             : #endif
      42             : 
      43             : // Both stdio.h and cstdio are included via different paths and
      44             : // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
      45             : // either.
      46             : #undef ferror
      47             : #undef feof
      48             : 
      49             : // For GNU Hurd
      50             : #if defined(__GNU__) && !defined(PATH_MAX)
      51             : # define PATH_MAX 4096
      52             : # define MAXPATHLEN 4096
      53             : #endif
      54             : 
      55             : #include <sys/types.h>
      56             : #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) &&   \
      57             :     !defined(__linux__)
      58             : #include <sys/statvfs.h>
      59             : #define STATVFS statvfs
      60             : #define FSTATVFS fstatvfs
      61             : #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
      62             : #else
      63             : #if defined(__OpenBSD__) || defined(__FreeBSD__)
      64             : #include <sys/mount.h>
      65             : #include <sys/param.h>
      66             : #elif defined(__linux__)
      67             : #if defined(HAVE_LINUX_MAGIC_H)
      68             : #include <linux/magic.h>
      69             : #else
      70             : #if defined(HAVE_LINUX_NFS_FS_H)
      71             : #include <linux/nfs_fs.h>
      72             : #endif
      73             : #if defined(HAVE_LINUX_SMB_H)
      74             : #include <linux/smb.h>
      75             : #endif
      76             : #endif
      77             : #include <sys/vfs.h>
      78             : #else
      79             : #include <sys/mount.h>
      80             : #endif
      81             : #define STATVFS statfs
      82             : #define FSTATVFS fstatfs
      83             : #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
      84             : #endif
      85             : 
      86             : #if defined(__NetBSD__)
      87             : #define STATVFS_F_FLAG(vfs) (vfs).f_flag
      88             : #else
      89             : #define STATVFS_F_FLAG(vfs) (vfs).f_flags
      90             : #endif
      91             : 
      92             : using namespace llvm;
      93             : 
      94             : namespace llvm {
      95             : namespace sys  {
      96             : namespace fs {
      97             : 
      98             : const file_t kInvalidFile = -1;
      99             : 
     100             : #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) ||     \
     101             :     defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) ||   \
     102             :     defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX)
     103             : static int
     104           0 : test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
     105             : {
     106             :   struct stat sb;
     107             :   char fullpath[PATH_MAX];
     108             : 
     109           0 :   snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
     110           0 :   if (!realpath(fullpath, ret))
     111             :     return 1;
     112           0 :   if (stat(fullpath, &sb) != 0)
     113             :     return 1;
     114             : 
     115           0 :   return 0;
     116             : }
     117             : 
     118             : static char *
     119           0 : getprogpath(char ret[PATH_MAX], const char *bin)
     120             : {
     121             :   char *pv, *s, *t;
     122             : 
     123             :   /* First approach: absolute path. */
     124           0 :   if (bin[0] == '/') {
     125           0 :     if (test_dir(ret, "/", bin) == 0)
     126             :       return ret;
     127           0 :     return nullptr;
     128             :   }
     129             : 
     130             :   /* Second approach: relative path. */
     131           0 :   if (strchr(bin, '/')) {
     132             :     char cwd[PATH_MAX];
     133           0 :     if (!getcwd(cwd, PATH_MAX))
     134             :       return nullptr;
     135           0 :     if (test_dir(ret, cwd, bin) == 0)
     136             :       return ret;
     137           0 :     return nullptr;
     138             :   }
     139             : 
     140             :   /* Third approach: $PATH */
     141           0 :   if ((pv = getenv("PATH")) == nullptr)
     142             :     return nullptr;
     143           0 :   s = pv = strdup(pv);
     144           0 :   if (!pv)
     145             :     return nullptr;
     146           0 :   while ((t = strsep(&s, ":")) != nullptr) {
     147           0 :     if (test_dir(ret, t, bin) == 0) {
     148           0 :       free(pv);
     149           0 :       return ret;
     150             :     }
     151             :   }
     152           0 :   free(pv);
     153           0 :   return nullptr;
     154             : }
     155             : #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
     156             : 
     157             : /// GetMainExecutable - Return the path to the main executable, given the
     158             : /// value of argv[0] from program startup.
     159       31827 : std::string getMainExecutable(const char *argv0, void *MainAddr) {
     160             : #if defined(__APPLE__)
     161             :   // On OS X the executable path is saved to the stack by dyld. Reading it
     162             :   // from there is much faster than calling dladdr, especially for large
     163             :   // binaries with symbols.
     164             :   char exe_path[MAXPATHLEN];
     165             :   uint32_t size = sizeof(exe_path);
     166             :   if (_NSGetExecutablePath(exe_path, &size) == 0) {
     167             :     char link_path[MAXPATHLEN];
     168             :     if (realpath(exe_path, link_path))
     169             :       return link_path;
     170             :   }
     171             : #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) ||   \
     172             :     defined(__minix) || defined(__DragonFly__) ||                              \
     173             :     defined(__FreeBSD_kernel__) || defined(_AIX)
     174             :   char exe_path[PATH_MAX];
     175             : 
     176             :   if (getprogpath(exe_path, argv0) != NULL)
     177             :     return exe_path;
     178             : #elif defined(__linux__) || defined(__CYGWIN__) || defined(__GNU__)
     179             :   char exe_path[MAXPATHLEN];
     180             :   StringRef aPath("/proc/self/exe");
     181       31827 :   if (sys::fs::exists(aPath)) {
     182             :       // /proc is not always mounted under Linux (chroot for example).
     183       63654 :       ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
     184       31827 :       if (len >= 0)
     185       31827 :           return std::string(exe_path, len);
     186             :   } else {
     187             :       // Fall back to the classical detection.
     188           0 :       if (getprogpath(exe_path, argv0))
     189           0 :         return exe_path;
     190             :   }
     191             : #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
     192             :   // Use dladdr to get executable path if available.
     193             :   Dl_info DLInfo;
     194             :   int err = dladdr(MainAddr, &DLInfo);
     195             :   if (err == 0)
     196             :     return "";
     197             : 
     198             :   // If the filename is a symlink, we need to resolve and return the location of
     199             :   // the actual executable.
     200             :   char link_path[MAXPATHLEN];
     201             :   if (realpath(DLInfo.dli_fname, link_path))
     202             :     return link_path;
     203             : #else
     204             : #error GetMainExecutable is not implemented on this host yet.
     205             : #endif
     206           0 :   return "";
     207             : }
     208             : 
     209          67 : TimePoint<> basic_file_status::getLastAccessedTime() const {
     210         134 :   return toTimePoint(fs_st_atime);
     211             : }
     212             : 
     213     1119308 : TimePoint<> basic_file_status::getLastModificationTime() const {
     214     2238616 :   return toTimePoint(fs_st_mtime);
     215             : }
     216             : 
     217     1196673 : UniqueID file_status::getUniqueID() const {
     218     1196673 :   return UniqueID(fs_st_dev, fs_st_ino);
     219             : }
     220             : 
     221           0 : uint32_t file_status::getLinkCount() const {
     222           0 :   return fs_st_nlinks;
     223             : }
     224             : 
     225          24 : ErrorOr<space_info> disk_space(const Twine &Path) {
     226             :   struct STATVFS Vfs;
     227          72 :   if (::STATVFS(Path.str().c_str(), &Vfs))
     228           0 :     return std::error_code(errno, std::generic_category());
     229          24 :   auto FrSize = STATVFS_F_FRSIZE(Vfs);
     230             :   space_info SpaceInfo;
     231          24 :   SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
     232          24 :   SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
     233          24 :   SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
     234             :   return SpaceInfo;
     235             : }
     236             : 
     237       50252 : std::error_code current_path(SmallVectorImpl<char> &result) {
     238             :   result.clear();
     239             : 
     240       50252 :   const char *pwd = ::getenv("PWD");
     241       50253 :   llvm::sys::fs::file_status PWDStatus, DotStatus;
     242      120477 :   if (pwd && llvm::sys::path::is_absolute(pwd) &&
     243      120477 :       !llvm::sys::fs::status(pwd, PWDStatus) &&
     244      135618 :       !llvm::sys::fs::status(".", DotStatus) &&
     245       85365 :       PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
     246       35065 :     result.append(pwd, pwd + strlen(pwd));
     247       35065 :     return std::error_code();
     248             :   }
     249             : 
     250             : #ifdef MAXPATHLEN
     251             :   result.reserve(MAXPATHLEN);
     252             : #else
     253             : // For GNU Hurd
     254             :   result.reserve(1024);
     255             : #endif
     256             : 
     257             :   while (true) {
     258       15188 :     if (::getcwd(result.data(), result.capacity()) == nullptr) {
     259             :       // See if there was a real error.
     260           0 :       if (errno != ENOMEM)
     261           0 :         return std::error_code(errno, std::generic_category());
     262             :       // Otherwise there just wasn't enough space.
     263           0 :       result.reserve(result.capacity() * 2);
     264             :     } else
     265             :       break;
     266             :   }
     267             : 
     268       15188 :   result.set_size(strlen(result.data()));
     269       15188 :   return std::error_code();
     270             : }
     271             : 
     272       10196 : std::error_code set_current_path(const Twine &path) {
     273             :   SmallString<128> path_storage;
     274       10196 :   StringRef p = path.toNullTerminatedStringRef(path_storage);
     275             : 
     276       10196 :   if (::chdir(p.begin()) == -1)
     277          99 :     return std::error_code(errno, std::generic_category());
     278             : 
     279       10097 :   return std::error_code();
     280             : }
     281             : 
     282        3039 : std::error_code create_directory(const Twine &path, bool IgnoreExisting,
     283             :                                  perms Perms) {
     284             :   SmallString<128> path_storage;
     285        3039 :   StringRef p = path.toNullTerminatedStringRef(path_storage);
     286             : 
     287        3039 :   if (::mkdir(p.begin(), Perms) == -1) {
     288        1644 :     if (errno != EEXIST || !IgnoreExisting)
     289         526 :       return std::error_code(errno, std::generic_category());
     290             :   }
     291             : 
     292        2513 :   return std::error_code();
     293             : }
     294             : 
     295             : // Note that we are using symbolic link because hard links are not supported by
     296             : // all filesystems (SMB doesn't).
     297        1731 : std::error_code create_link(const Twine &to, const Twine &from) {
     298             :   // Get arguments.
     299             :   SmallString<128> from_storage;
     300             :   SmallString<128> to_storage;
     301        1731 :   StringRef f = from.toNullTerminatedStringRef(from_storage);
     302        1731 :   StringRef t = to.toNullTerminatedStringRef(to_storage);
     303             : 
     304        1731 :   if (::symlink(t.begin(), f.begin()) == -1)
     305           0 :     return std::error_code(errno, std::generic_category());
     306             : 
     307        1731 :   return std::error_code();
     308             : }
     309             : 
     310           7 : std::error_code create_hard_link(const Twine &to, const Twine &from) {
     311             :   // Get arguments.
     312             :   SmallString<128> from_storage;
     313             :   SmallString<128> to_storage;
     314           7 :   StringRef f = from.toNullTerminatedStringRef(from_storage);
     315           7 :   StringRef t = to.toNullTerminatedStringRef(to_storage);
     316             : 
     317           7 :   if (::link(t.begin(), f.begin()) == -1)
     318           0 :     return std::error_code(errno, std::generic_category());
     319             : 
     320           7 :   return std::error_code();
     321             : }
     322             : 
     323       14730 : std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
     324             :   SmallString<128> path_storage;
     325       14730 :   StringRef p = path.toNullTerminatedStringRef(path_storage);
     326             : 
     327             :   struct stat buf;
     328       14730 :   if (lstat(p.begin(), &buf) != 0) {
     329        2337 :     if (errno != ENOENT || !IgnoreNonExisting)
     330           1 :       return std::error_code(errno, std::generic_category());
     331        2336 :     return std::error_code();
     332             :   }
     333             : 
     334             :   // Note: this check catches strange situations. In all cases, LLVM should
     335             :   // only be involved in the creation and deletion of regular files.  This
     336             :   // check ensures that what we're trying to erase is a regular file. It
     337             :   // effectively prevents LLVM from erasing things like /dev/null, any block
     338             :   // special file, or other things that aren't "regular" files.
     339       12393 :   if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
     340             :     return make_error_code(errc::operation_not_permitted);
     341             : 
     342       12090 :   if (::remove(p.begin()) == -1) {
     343           2 :     if (errno != ENOENT || !IgnoreNonExisting)
     344           2 :       return std::error_code(errno, std::generic_category());
     345             :   }
     346             : 
     347       12088 :   return std::error_code();
     348             : }
     349             : 
     350             : static bool is_local_impl(struct STATVFS &Vfs) {
     351             : #if defined(__linux__)
     352             : #ifndef NFS_SUPER_MAGIC
     353             : #define NFS_SUPER_MAGIC 0x6969
     354             : #endif
     355             : #ifndef SMB_SUPER_MAGIC
     356             : #define SMB_SUPER_MAGIC 0x517B
     357             : #endif
     358             : #ifndef CIFS_MAGIC_NUMBER
     359             : #define CIFS_MAGIC_NUMBER 0xFF534D42
     360             : #endif
     361        9097 :   switch ((uint32_t)Vfs.f_type) {
     362             :   case NFS_SUPER_MAGIC:
     363             :   case SMB_SUPER_MAGIC:
     364             :   case CIFS_MAGIC_NUMBER:
     365             :     return false;
     366        9097 :   default:
     367             :     return true;
     368             :   }
     369             : #elif defined(__CYGWIN__)
     370             :   // Cygwin doesn't expose this information; would need to use Win32 API.
     371             :   return false;
     372             : #elif defined(__Fuchsia__)
     373             :   // Fuchsia doesn't yet support remote filesystem mounts.
     374             :   return true;
     375             : #elif defined(__sun)
     376             :   // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
     377             :   StringRef fstype(Vfs.f_basetype);
     378             :   // NFS is the only non-local fstype??
     379             :   return !fstype.equals("nfs");
     380             : #else
     381             :   return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
     382             : #endif
     383             : }
     384             : 
     385       18500 : std::error_code is_local(const Twine &Path, bool &Result) {
     386             :   struct STATVFS Vfs;
     387       55500 :   if (::STATVFS(Path.str().c_str(), &Vfs))
     388        9403 :     return std::error_code(errno, std::generic_category());
     389             : 
     390       18194 :   Result = is_local_impl(Vfs);
     391        9097 :   return std::error_code();
     392             : }
     393             : 
     394           0 : std::error_code is_local(int FD, bool &Result) {
     395             :   struct STATVFS Vfs;
     396           0 :   if (::FSTATVFS(FD, &Vfs))
     397           0 :     return std::error_code(errno, std::generic_category());
     398             : 
     399           0 :   Result = is_local_impl(Vfs);
     400           0 :   return std::error_code();
     401             : }
     402             : 
     403       10060 : std::error_code rename(const Twine &from, const Twine &to) {
     404             :   // Get arguments.
     405             :   SmallString<128> from_storage;
     406             :   SmallString<128> to_storage;
     407       10060 :   StringRef f = from.toNullTerminatedStringRef(from_storage);
     408       10060 :   StringRef t = to.toNullTerminatedStringRef(to_storage);
     409             : 
     410       10060 :   if (::rename(f.begin(), t.begin()) == -1)
     411           0 :     return std::error_code(errno, std::generic_category());
     412             : 
     413       10060 :   return std::error_code();
     414             : }
     415             : 
     416        4870 : std::error_code resize_file(int FD, uint64_t Size) {
     417             : #if defined(HAVE_POSIX_FALLOCATE)
     418             :   // If we have posix_fallocate use it. Unlike ftruncate it always allocates
     419             :   // space, so we get an error if the disk is full.
     420        4870 :   if (int Err = ::posix_fallocate(FD, 0, Size)) {
     421           0 :     if (Err != EINVAL && Err != EOPNOTSUPP)
     422           0 :       return std::error_code(Err, std::generic_category());
     423             :   }
     424             : #endif
     425             :   // Use ftruncate as a fallback. It may or may not allocate space. At least on
     426             :   // OS X with HFS+ it does.
     427        4870 :   if (::ftruncate(FD, Size) == -1)
     428           0 :     return std::error_code(errno, std::generic_category());
     429             : 
     430        4870 :   return std::error_code();
     431             : }
     432             : 
     433             : static int convertAccessMode(AccessMode Mode) {
     434      376000 :   switch (Mode) {
     435             :   case AccessMode::Exist:
     436             :     return F_OK;
     437        5921 :   case AccessMode::Write:
     438             :     return W_OK;
     439      161001 :   case AccessMode::Execute:
     440             :     return R_OK | X_OK; // scripts also need R_OK.
     441             :   }
     442           0 :   llvm_unreachable("invalid enum");
     443             : }
     444             : 
     445      375999 : std::error_code access(const Twine &Path, AccessMode Mode) {
     446             :   SmallString<128> PathStorage;
     447      375999 :   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
     448             : 
     449      376000 :   if (::access(P.begin(), convertAccessMode(Mode)) == -1)
     450      261787 :     return std::error_code(errno, std::generic_category());
     451             : 
     452      114212 :   if (Mode == AccessMode::Execute) {
     453             :     // Don't say that directories are executable.
     454             :     struct stat buf;
     455        4913 :     if (0 != stat(P.begin(), &buf))
     456           0 :       return errc::permission_denied;
     457        4913 :     if (!S_ISREG(buf.st_mode))
     458           1 :       return errc::permission_denied;
     459             :   }
     460             : 
     461      114211 :   return std::error_code();
     462             : }
     463             : 
     464      161001 : bool can_execute(const Twine &Path) {
     465      161001 :   return !access(Path, AccessMode::Execute);
     466             : }
     467             : 
     468         409 : bool equivalent(file_status A, file_status B) {
     469             :   assert(status_known(A) && status_known(B));
     470         818 :   return A.fs_st_dev == B.fs_st_dev &&
     471         818 :          A.fs_st_ino == B.fs_st_ino;
     472             : }
     473             : 
     474        3526 : std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
     475        3526 :   file_status fsA, fsB;
     476        3526 :   if (std::error_code ec = status(A, fsA))
     477        3114 :     return ec;
     478         412 :   if (std::error_code ec = status(B, fsB))
     479           5 :     return ec;
     480         407 :   result = equivalent(fsA, fsB);
     481         407 :   return std::error_code();
     482             : }
     483             : 
     484          34 : static void expandTildeExpr(SmallVectorImpl<char> &Path) {
     485             :   StringRef PathStr(Path.begin(), Path.size());
     486          34 :   if (PathStr.empty() || !PathStr.startswith("~"))
     487          34 :     return;
     488             : 
     489          34 :   PathStr = PathStr.drop_front();
     490             :   StringRef Expr =
     491          34 :       PathStr.take_until([](char c) { return path::is_separator(c); });
     492          34 :   StringRef Remainder = PathStr.substr(Expr.size() + 1);
     493             :   SmallString<128> Storage;
     494          34 :   if (Expr.empty()) {
     495             :     // This is just ~/..., resolve it to the current user's home dir.
     496          34 :     if (!path::home_directory(Storage)) {
     497             :       // For some reason we couldn't get the home directory.  Just exit.
     498             :       return;
     499             :     }
     500             : 
     501             :     // Overwrite the first character and insert the rest.
     502          34 :     Path[0] = Storage[0];
     503          68 :     Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
     504          34 :     return;
     505             :   }
     506             : 
     507             :   // This is a string of the form ~username/, look up this user's entry in the
     508             :   // password database.
     509             :   struct passwd *Entry = nullptr;
     510             :   std::string User = Expr.str();
     511           0 :   Entry = ::getpwnam(User.c_str());
     512             : 
     513           0 :   if (!Entry) {
     514             :     // Unable to look up the entry, just return back the original path.
     515             :     return;
     516             :   }
     517             : 
     518             :   Storage = Remainder;
     519             :   Path.clear();
     520           0 :   Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
     521           0 :   llvm::sys::path::append(Path, Storage);
     522             : }
     523             : 
     524     2318607 : static std::error_code fillStatus(int StatRet, const struct stat &Status,
     525             :                                   file_status &Result) {
     526     2318607 :   if (StatRet != 0) {
     527      672477 :     std::error_code ec(errno, std::generic_category());
     528             :     if (ec == errc::no_such_file_or_directory)
     529      672396 :       Result = file_status(file_type::file_not_found);
     530             :     else
     531          81 :       Result = file_status(file_type::status_error);
     532      672477 :     return ec;
     533             :   }
     534             : 
     535             :   file_type Type = file_type::type_unknown;
     536             : 
     537     1646130 :   if (S_ISDIR(Status.st_mode))
     538             :     Type = file_type::directory_file;
     539      589922 :   else if (S_ISREG(Status.st_mode))
     540             :     Type = file_type::regular_file;
     541         836 :   else if (S_ISBLK(Status.st_mode))
     542             :     Type = file_type::block_file;
     543         836 :   else if (S_ISCHR(Status.st_mode))
     544             :     Type = file_type::character_file;
     545          36 :   else if (S_ISFIFO(Status.st_mode))
     546             :     Type = file_type::fifo_file;
     547          33 :   else if (S_ISSOCK(Status.st_mode))
     548             :     Type = file_type::socket_file;
     549          32 :   else if (S_ISLNK(Status.st_mode))
     550             :     Type = file_type::symlink_file;
     551             : 
     552             :   perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
     553     1646130 :   Result = file_status(Type, Perms, Status.st_dev, Status.st_nlink,
     554     1646130 :                        Status.st_ino, Status.st_atime, Status.st_mtime,
     555     1646130 :                        Status.st_uid, Status.st_gid, Status.st_size);
     556             : 
     557     1646130 :   return std::error_code();
     558             : }
     559             : 
     560     1919582 : std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
     561             :   SmallString<128> PathStorage;
     562     1919582 :   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
     563             : 
     564             :   struct stat Status;
     565     1919580 :   int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
     566     3839166 :   return fillStatus(StatRet, Status, Result);
     567             : }
     568             : 
     569      399021 : std::error_code status(int FD, file_status &Result) {
     570             :   struct stat Status;
     571             :   int StatRet = ::fstat(FD, &Status);
     572      399022 :   return fillStatus(StatRet, Status, Result);
     573             : }
     574             : 
     575          27 : std::error_code setPermissions(const Twine &Path, perms Permissions) {
     576             :   SmallString<128> PathStorage;
     577          27 :   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
     578             : 
     579          27 :   if (::chmod(P.begin(), Permissions))
     580           0 :     return std::error_code(errno, std::generic_category());
     581          27 :   return std::error_code();
     582             : }
     583             : 
     584           1 : std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
     585             : #if defined(HAVE_FUTIMENS)
     586             :   timespec Times[2];
     587           1 :   Times[0] = Times[1] = sys::toTimeSpec(Time);
     588           1 :   if (::futimens(FD, Times))
     589           0 :     return std::error_code(errno, std::generic_category());
     590           1 :   return std::error_code();
     591             : #elif defined(HAVE_FUTIMES)
     592             :   timeval Times[2];
     593             :   Times[0] = Times[1] = sys::toTimeVal(
     594             :       std::chrono::time_point_cast<std::chrono::microseconds>(Time));
     595             :   if (::futimes(FD, Times))
     596             :     return std::error_code(errno, std::generic_category());
     597             :   return std::error_code();
     598             : #else
     599             : #warning Missing futimes() and futimens()
     600             :   return make_error_code(errc::function_not_supported);
     601             : #endif
     602             : }
     603             : 
     604       65149 : std::error_code mapped_file_region::init(int FD, uint64_t Offset,
     605             :                                          mapmode Mode) {
     606             :   assert(Size != 0);
     607             : 
     608       65149 :   int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
     609       65149 :   int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
     610             : #if defined(__APPLE__)
     611             :   //----------------------------------------------------------------------
     612             :   // Newer versions of MacOSX have a flag that will allow us to read from
     613             :   // binaries whose code signature is invalid without crashing by using
     614             :   // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
     615             :   // is mapped we can avoid crashing and return zeroes to any pages we try
     616             :   // to read if the media becomes unavailable by using the
     617             :   // MAP_RESILIENT_MEDIA flag.  These flags are only usable when mapping
     618             :   // with PROT_READ, so take care not to specify them otherwise.
     619             :   //----------------------------------------------------------------------
     620             :   if (Mode == readonly) {
     621             : #if defined(MAP_RESILIENT_CODESIGN)
     622             :     flags |= MAP_RESILIENT_CODESIGN;
     623             : #endif
     624             : #if defined(MAP_RESILIENT_MEDIA)
     625             :     flags |= MAP_RESILIENT_MEDIA;
     626             : #endif
     627             :   }
     628             : #endif // #if defined (__APPLE__)
     629             : 
     630       65149 :   Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
     631       65149 :   if (Mapping == MAP_FAILED)
     632           0 :     return std::error_code(errno, std::generic_category());
     633       65149 :   return std::error_code();
     634             : }
     635             : 
     636       65149 : mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
     637       65149 :                                        uint64_t offset, std::error_code &ec)
     638       65149 :     : Size(length), Mapping(), Mode(mode) {
     639             :   (void)Mode;
     640       65149 :   ec = init(fd, offset, mode);
     641       65149 :   if (ec)
     642           0 :     Mapping = nullptr;
     643       65149 : }
     644             : 
     645       74162 : mapped_file_region::~mapped_file_region() {
     646       37081 :   if (Mapping)
     647       37081 :     ::munmap(Mapping, Size);
     648       37081 : }
     649             : 
     650         582 : size_t mapped_file_region::size() const {
     651             :   assert(Mapping && "Mapping failed but used anyway!");
     652         582 :   return Size;
     653             : }
     654             : 
     655        9541 : char *mapped_file_region::data() const {
     656             :   assert(Mapping && "Mapping failed but used anyway!");
     657        9541 :   return reinterpret_cast<char*>(Mapping);
     658             : }
     659             : 
     660       60178 : const char *mapped_file_region::const_data() const {
     661             :   assert(Mapping && "Mapping failed but used anyway!");
     662       60178 :   return reinterpret_cast<const char*>(Mapping);
     663             : }
     664             : 
     665      180531 : int mapped_file_region::alignment() {
     666      180531 :   return Process::getPageSize();
     667             : }
     668             : 
     669     2452783 : std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
     670             :                                                      StringRef path,
     671             :                                                      bool follow_symlinks) {
     672             :   SmallString<128> path_null(path);
     673     2452784 :   DIR *directory = ::opendir(path_null.c_str());
     674     2452786 :   if (!directory)
     675     2429142 :     return std::error_code(errno, std::generic_category());
     676             : 
     677       23644 :   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
     678             :   // Add something for replace_filename to replace.
     679       23644 :   path::append(path_null, ".");
     680       47288 :   it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
     681       23644 :   return directory_iterator_increment(it);
     682             : }
     683             : 
     684     2476384 : std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
     685     2476384 :   if (it.IterationHandle)
     686       23644 :     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
     687     2476384 :   it.IterationHandle = 0;
     688     4952868 :   it.CurrentEntry = directory_entry();
     689     2476484 :   return std::error_code();
     690             : }
     691             : 
     692      355865 : std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
     693      355865 :   errno = 0;
     694      355865 :   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
     695      355864 :   if (cur_dir == nullptr && errno != 0) {
     696           0 :     return std::error_code(errno, std::generic_category());
     697      355864 :   } else if (cur_dir != nullptr) {
     698      332236 :     StringRef name(cur_dir->d_name);
     699      440764 :     if ((name.size() == 1 && name[0] == '.') ||
     700       47294 :         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
     701       47254 :       return directory_iterator_increment(it);
     702      569964 :     it.CurrentEntry.replace_filename(name);
     703             :   } else
     704       23628 :     return directory_iterator_destruct(it);
     705             : 
     706      284981 :   return std::error_code();
     707             : }
     708             : 
     709      285511 : ErrorOr<basic_file_status> directory_entry::status() const {
     710      285511 :   file_status s;
     711      571022 :   if (auto EC = fs::status(Path, s, FollowSymlinks))
     712          20 :     return EC;
     713             :   return s;
     714             : }
     715             : 
     716             : #if !defined(F_GETPATH)
     717      304745 : static bool hasProcSelfFD() {
     718             :   // If we have a /proc filesystem mounted, we can quickly establish the
     719             :   // real name of the file with readlink
     720      304745 :   static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
     721      304745 :   return Result;
     722             : }
     723             : #endif
     724             : 
     725     1241792 : static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
     726             :                            FileAccess Access) {
     727             :   int Result = 0;
     728     1241792 :   if (Access == FA_Read)
     729             :     Result |= O_RDONLY;
     730       30779 :   else if (Access == FA_Write)
     731             :     Result |= O_WRONLY;
     732       20157 :   else if (Access == (FA_Read | FA_Write))
     733             :     Result |= O_RDWR;
     734             : 
     735             :   // This is for compatibility with old code that assumed F_Append implied
     736             :   // would open an existing file.  See Windows/Path.inc for a longer comment.
     737     1241792 :   if (Flags & F_Append)
     738             :     Disp = CD_OpenAlways;
     739             : 
     740     1241784 :   if (Disp == CD_CreateNew) {
     741             :     Result |= O_CREAT; // Create if it doesn't exist.
     742       20019 :     Result |= O_EXCL;  // Fail if it does.
     743     1221773 :   } else if (Disp == CD_CreateAlways) {
     744             :     Result |= O_CREAT; // Create if it doesn't exist.
     745       10744 :     Result |= O_TRUNC; // Truncate if it does.
     746     1211029 :   } else if (Disp == CD_OpenAlways) {
     747          10 :     Result |= O_CREAT; // Create if it doesn't exist.
     748             :   } else if (Disp == CD_OpenExisting) {
     749             :     // Nothing special, just don't add O_CREAT and we get these semantics.
     750             :   }
     751             : 
     752     1241792 :   if (Flags & F_Append)
     753           8 :     Result |= O_APPEND;
     754             : 
     755             : #ifdef O_CLOEXEC
     756     1241792 :   if (!(Flags & OF_ChildInherit))
     757     1241792 :     Result |= O_CLOEXEC;
     758             : #endif
     759             : 
     760     1241792 :   return Result;
     761             : }
     762             : 
     763     1241792 : std::error_code openFile(const Twine &Name, int &ResultFD,
     764             :                          CreationDisposition Disp, FileAccess Access,
     765             :                          OpenFlags Flags, unsigned Mode) {
     766     1241792 :   int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
     767             : 
     768             :   SmallString<128> Storage;
     769     1241792 :   StringRef P = Name.toNullTerminatedStringRef(Storage);
     770     1241793 :   if ((ResultFD = sys::RetryAfterSignal(-1, ::open, P.begin(), OpenFlags, Mode)) <
     771             :       0)
     772      701054 :     return std::error_code(errno, std::generic_category());
     773             : #ifndef O_CLOEXEC
     774             :   if (!(Flags & OF_ChildInherit)) {
     775             :     int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
     776             :     (void)r;
     777             :     assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
     778             :   }
     779             : #endif
     780      540740 :   return std::error_code();
     781             : }
     782             : 
     783           0 : Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
     784             :                              FileAccess Access, OpenFlags Flags,
     785             :                              unsigned Mode) {
     786             : 
     787             :   int FD;
     788           0 :   std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
     789           0 :   if (EC)
     790           0 :     return errorCodeToError(EC);
     791             :   return FD;
     792             : }
     793             : 
     794     1211014 : std::error_code openFileForRead(const Twine &Name, int &ResultFD,
     795             :                                 OpenFlags Flags,
     796             :                                 SmallVectorImpl<char> *RealPath) {
     797             :   std::error_code EC =
     798     1211014 :       openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
     799     1211015 :   if (EC)
     800      700630 :     return EC;
     801             : 
     802             :   // Attempt to get the real name of the file, if the user asked
     803      510385 :   if(!RealPath)
     804      205640 :     return std::error_code();
     805             :   RealPath->clear();
     806             : #if defined(F_GETPATH)
     807             :   // When F_GETPATH is availble, it is the quickest way to get
     808             :   // the real path name.
     809             :   char Buffer[MAXPATHLEN];
     810             :   if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
     811             :     RealPath->append(Buffer, Buffer + strlen(Buffer));
     812             : #else
     813             :   char Buffer[PATH_MAX];
     814      304745 :   if (hasProcSelfFD()) {
     815             :     char ProcPath[64];
     816      304745 :     snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
     817      304745 :     ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
     818      304745 :     if (CharCount > 0)
     819      304745 :       RealPath->append(Buffer, Buffer + CharCount);
     820             :   } else {
     821             :     SmallString<128> Storage;
     822           0 :     StringRef P = Name.toNullTerminatedStringRef(Storage);
     823             : 
     824             :     // Use ::realpath to get the real path name
     825           0 :     if (::realpath(P.begin(), Buffer) != nullptr)
     826           0 :       RealPath->append(Buffer, Buffer + strlen(Buffer));
     827             :   }
     828             : #endif
     829      304745 :   return std::error_code();
     830             : }
     831             : 
     832           0 : Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
     833             :                                        SmallVectorImpl<char> *RealPath) {
     834             :   file_t ResultFD;
     835           0 :   std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
     836           0 :   if (EC)
     837           0 :     return errorCodeToError(EC);
     838             :   return ResultFD;
     839             : }
     840             : 
     841           0 : void closeFile(file_t &F) {
     842           0 :   ::close(F);
     843           0 :   F = kInvalidFile;
     844           0 : }
     845             : 
     846             : template <typename T>
     847          68 : static std::error_code remove_directories_impl(const T &Entry,
     848             :                                                bool IgnoreErrors) {
     849             :   std::error_code EC;
     850          68 :   directory_iterator Begin(Entry, EC, false);
     851          68 :   directory_iterator End;
     852         158 :   while (Begin != End) {
     853             :     auto &Item = *Begin;
     854          90 :     ErrorOr<basic_file_status> st = Item.status();
     855          90 :     if (!st && !IgnoreErrors)
     856             :       return st.getError();
     857             : 
     858          90 :     if (is_directory(*st)) {
     859          53 :       EC = remove_directories_impl(Item, IgnoreErrors);
     860          53 :       if (EC && !IgnoreErrors)
     861           0 :         return EC;
     862             :     }
     863             : 
     864          90 :     EC = fs::remove(Item.path(), true);
     865          90 :     if (EC && !IgnoreErrors)
     866           0 :       return EC;
     867             : 
     868             :     Begin.increment(EC);
     869          90 :     if (EC && !IgnoreErrors)
     870           0 :       return EC;
     871             :   }
     872          68 :   return std::error_code();
     873             : }
     874             : 
     875          15 : std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
     876          15 :   auto EC = remove_directories_impl(path, IgnoreErrors);
     877          15 :   if (EC && !IgnoreErrors)
     878           0 :     return EC;
     879          15 :   EC = fs::remove(path, true);
     880          15 :   if (EC && !IgnoreErrors)
     881           0 :     return EC;
     882          15 :   return std::error_code();
     883             : }
     884             : 
     885        1390 : std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
     886             :                           bool expand_tilde) {
     887             :   dest.clear();
     888             :   if (path.isTriviallyEmpty())
     889           0 :     return std::error_code();
     890             : 
     891        1390 :   if (expand_tilde) {
     892             :     SmallString<128> Storage;
     893          34 :     path.toVector(Storage);
     894          34 :     expandTildeExpr(Storage);
     895          34 :     return real_path(Storage, dest, false);
     896             :   }
     897             : 
     898             :   SmallString<128> Storage;
     899        1356 :   StringRef P = path.toNullTerminatedStringRef(Storage);
     900             :   char Buffer[PATH_MAX];
     901        1356 :   if (::realpath(P.begin(), Buffer) == nullptr)
     902          37 :     return std::error_code(errno, std::generic_category());
     903        1319 :   dest.append(Buffer, Buffer + strlen(Buffer));
     904        1319 :   return std::error_code();
     905             : }
     906             : 
     907             : } // end namespace fs
     908             : 
     909             : namespace path {
     910             : 
     911        3442 : bool home_directory(SmallVectorImpl<char> &result) {
     912        3442 :   char *RequestedDir = getenv("HOME");
     913        3442 :   if (!RequestedDir) {
     914        3442 :     struct passwd *pw = getpwuid(getuid());
     915        3442 :     if (pw && pw->pw_dir)
     916             :       RequestedDir = pw->pw_dir;
     917             :   }
     918        3442 :   if (!RequestedDir)
     919             :     return false;
     920             : 
     921             :   result.clear();
     922        3442 :   result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
     923        3442 :   return true;
     924             : }
     925             : 
     926             : static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
     927             :   #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
     928             :   // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
     929             :   // macros defined in <unistd.h> on darwin >= 9
     930             :   int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
     931             :                          : _CS_DARWIN_USER_CACHE_DIR;
     932             :   size_t ConfLen = confstr(ConfName, nullptr, 0);
     933             :   if (ConfLen > 0) {
     934             :     do {
     935             :       Result.resize(ConfLen);
     936             :       ConfLen = confstr(ConfName, Result.data(), Result.size());
     937             :     } while (ConfLen > 0 && ConfLen != Result.size());
     938             : 
     939             :     if (ConfLen > 0) {
     940             :       assert(Result.back() == 0);
     941             :       Result.pop_back();
     942             :       return true;
     943             :     }
     944             : 
     945             :     Result.clear();
     946             :   }
     947             :   #endif
     948             :   return false;
     949             : }
     950             : 
     951           4 : static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
     952             :   // First try using XDG_CACHE_HOME env variable,
     953             :   // as specified in XDG Base Directory Specification at
     954             :   // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
     955           4 :   if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
     956             :     Result.clear();
     957           0 :     Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
     958           0 :     return true;
     959             :   }
     960             : 
     961             :   // Try Darwin configuration query
     962             :   if (getDarwinConfDir(false, Result))
     963             :     return true;
     964             : 
     965             :   // Use "$HOME/.cache" if $HOME is available
     966           4 :   if (home_directory(Result)) {
     967           4 :     append(Result, ".cache");
     968           4 :     return true;
     969             :   }
     970             : 
     971             :   return false;
     972             : }
     973             : 
     974        5636 : static const char *getEnvTempDir() {
     975             :   // Check whether the temporary directory is specified by an environment
     976             :   // variable.
     977        5636 :   const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
     978        5652 :   for (const char *Env : EnvironmentVariables) {
     979        5642 :     if (const char *Dir = std::getenv(Env))
     980             :       return Dir;
     981             :   }
     982             : 
     983             :   return nullptr;
     984             : }
     985             : 
     986             : static const char *getDefaultTempDir(bool ErasedOnReboot) {
     987             : #ifdef P_tmpdir
     988             :   if ((bool)P_tmpdir)
     989             :     return P_tmpdir;
     990             : #endif
     991             : 
     992             :   if (ErasedOnReboot)
     993             :     return "/tmp";
     994             :   return "/var/tmp";
     995             : }
     996             : 
     997        7782 : void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
     998             :   Result.clear();
     999             : 
    1000        7782 :   if (ErasedOnReboot) {
    1001             :     // There is no env variable for the cache directory.
    1002        5636 :     if (const char *RequestedDir = getEnvTempDir()) {
    1003        5634 :       Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
    1004        5634 :       return;
    1005             :     }
    1006             :   }
    1007             : 
    1008             :   if (getDarwinConfDir(ErasedOnReboot, Result))
    1009             :     return;
    1010             : 
    1011             :   const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
    1012        2148 :   Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
    1013             : }
    1014             : 
    1015             : } // end namespace path
    1016             : 
    1017             : } // end namespace sys
    1018             : } // end namespace llvm

Generated by: LCOV version 1.13