brintos

brintos / llvm-project-archived public Read only

0
0
Text · 47.2 KiB · 0d991ea Raw
1561 lines · plain
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-exception6//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 that15//===          is guaranteed to work on *all* UNIX variants.16//===----------------------------------------------------------------------===//17 18#include "Unix.h"19#include <limits.h>20#include <stdio.h>21#include <sys/stat.h>22#include <fcntl.h>23#ifdef HAVE_UNISTD_H24#include <unistd.h>25#endif26#ifdef HAVE_SYS_MMAN_H27#include <sys/mman.h>28#endif29 30#include <dirent.h>31#include <pwd.h>32 33#ifdef __APPLE__34#include <copyfile.h>35#include <mach-o/dyld.h>36#include <sys/attr.h>37#if __has_include(<sys/clonefile.h>)38#include <sys/clonefile.h>39#endif40#elif defined(__FreeBSD__)41#include <osreldate.h>42#if __FreeBSD_version >= 130005743#include <sys/auxv.h>44#else45#include <machine/elf.h>46extern char **environ;47#endif48#elif defined(__DragonFly__)49#include <sys/mount.h>50#elif defined(__MVS__)51#include "llvm/Support/AutoConvert.h"52#include <sys/ps.h>53#endif54 55// Both stdio.h and cstdio are included via different paths and56// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros57// either.58#undef ferror59#undef feof60 61#if !defined(PATH_MAX)62// For GNU Hurd63#if defined(__GNU__)64#define PATH_MAX 409665#elif defined(__MVS__)66#define PATH_MAX _XOPEN_PATH_MAX67#endif68#endif69 70#include <sys/types.h>71#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) &&   \72    !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX) &&   \73    !defined(__managarm__)74#include <sys/statvfs.h>75#define STATVFS statvfs76#define FSTATVFS fstatvfs77#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize78#else79#if defined(__OpenBSD__) || defined(__FreeBSD__)80#include <sys/mount.h>81#include <sys/param.h>82#elif defined(__linux__) || defined(__managarm__)83#if defined(HAVE_LINUX_MAGIC_H)84#include <linux/magic.h>85#else86#if defined(HAVE_LINUX_NFS_FS_H)87#include <linux/nfs_fs.h>88#endif89#if defined(HAVE_LINUX_SMB_H)90#include <linux/smb.h>91#endif92#endif93#include <sys/vfs.h>94#elif defined(_AIX)95#include <sys/statfs.h>96 97// <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to98// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide99// the typedef prior to including <sys/vmount.h> to work around this issue.100typedef uint_t uint;101#include <sys/vmount.h>102#else103#include <sys/mount.h>104#endif105#define STATVFS statfs106#define FSTATVFS fstatfs107#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)108#endif109 110#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) ||       \111    defined(__MVS__)112#define STATVFS_F_FLAG(vfs) (vfs).f_flag113#else114#define STATVFS_F_FLAG(vfs) (vfs).f_flags115#endif116 117using namespace llvm;118 119namespace llvm {120namespace sys {121namespace fs {122 123const file_t kInvalidFile = -1;124 125#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) ||     \126    defined(__FreeBSD_kernel__) || defined(__linux__) ||                       \127    defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) ||          \128    defined(__GNU__) ||                                                        \129    (defined(__sun__) && defined(__svr4__) || defined(__HAIKU__)) ||           \130    defined(__managarm__)131static int test_dir(char ret[PATH_MAX], const char *dir, const char *bin) {132  struct stat sb;133  char fullpath[PATH_MAX];134 135  int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);136  // We cannot write PATH_MAX characters because the string will be terminated137  // with a null character. Fail if truncation happened.138  if (chars >= PATH_MAX)139    return 1;140  if (!realpath(fullpath, ret))141    return 1;142  if (stat(fullpath, &sb) != 0)143    return 1;144 145  return 0;146}147 148static char *getprogpath(char ret[PATH_MAX], const char *bin) {149  if (bin == nullptr)150    return nullptr;151 152  /* First approach: absolute path. */153  if (bin[0] == '/') {154    if (test_dir(ret, "/", bin) == 0)155      return ret;156    return nullptr;157  }158 159  /* Second approach: relative path. */160  if (strchr(bin, '/')) {161    char cwd[PATH_MAX];162    if (!getcwd(cwd, PATH_MAX))163      return nullptr;164    if (test_dir(ret, cwd, bin) == 0)165      return ret;166    return nullptr;167  }168 169  /* Third approach: $PATH */170  char *pv;171  if ((pv = getenv("PATH")) == nullptr)172    return nullptr;173  char *s = strdup(pv);174  if (!s)175    return nullptr;176  char *state;177  for (char *t = strtok_r(s, ":", &state); t != nullptr;178       t = strtok_r(nullptr, ":", &state)) {179    if (test_dir(ret, t, bin) == 0) {180      free(s);181      return ret;182    }183  }184  free(s);185  return nullptr;186}187#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__188 189/// GetMainExecutable - Return the path to the main executable, given the190/// value of argv[0] from program startup.191std::string getMainExecutable(const char *argv0, void *MainAddr) {192#if defined(__APPLE__)193  // On OS X the executable path is saved to the stack by dyld. Reading it194  // from there is much faster than calling dladdr, especially for large195  // binaries with symbols.196  char exe_path[PATH_MAX];197  uint32_t size = sizeof(exe_path);198  if (_NSGetExecutablePath(exe_path, &size) == 0) {199    char link_path[PATH_MAX];200    if (realpath(exe_path, link_path))201      return link_path;202  }203#elif defined(__FreeBSD__)204  // On FreeBSD if the exec path specified in ELF auxiliary vectors is205  // preferred, if available.  /proc/curproc/file and the KERN_PROC_PATHNAME206  // sysctl may not return the desired path if there are multiple hardlinks207  // to the file.208  char exe_path[PATH_MAX];209#if __FreeBSD_version >= 1300057210  if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0) {211    char link_path[PATH_MAX];212    if (realpath(exe_path, link_path))213      return link_path;214  }215#else216  // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,217  // fall back to finding the ELF auxiliary vectors after the process's218  // environment.219  char **p = ::environ;220  while (*p++ != 0)221    ;222  // Iterate through auxiliary vectors for AT_EXECPATH.223  for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {224    if (aux->a_type == AT_EXECPATH) {225      char link_path[PATH_MAX];226      if (realpath((char *)aux->a_un.a_ptr, link_path))227        return link_path;228    }229  }230#endif231  // Fall back to argv[0] if auxiliary vectors are not available.232  if (getprogpath(exe_path, argv0) != NULL)233    return exe_path;234#elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) || \235    defined(__NetBSD__)236  const char *curproc = "/proc/curproc/file";237  char exe_path[PATH_MAX];238  if (sys::fs::exists(curproc)) {239    ssize_t len = readlink(curproc, exe_path, sizeof(exe_path));240    if (len > 0) {241      // Null terminate the string for realpath. readlink never null242      // terminates its output.243      len = std::min(len, ssize_t(sizeof(exe_path) - 1));244      exe_path[len] = '\0';245      return exe_path;246    }247  }248  // If we don't have procfs mounted, fall back to argv[0]249  if (getprogpath(exe_path, argv0) != NULL)250    return exe_path;251#elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__) ||    \252    defined(__managarm__)253  char exe_path[PATH_MAX];254  const char *aPath = "/proc/self/exe";255  if (sys::fs::exists(aPath)) {256    // /proc is not always mounted under Linux (chroot for example).257    ssize_t len = readlink(aPath, exe_path, sizeof(exe_path));258    if (len < 0)259      return "";260 261    // Null terminate the string for realpath. readlink never null262    // terminates its output.263    len = std::min(len, ssize_t(sizeof(exe_path) - 1));264    exe_path[len] = '\0';265 266    // On Linux, /proc/self/exe always looks through symlinks. However, on267    // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start268    // the program, and not the eventual binary file. Therefore, call realpath269    // so this behaves the same on all platforms.270#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)271    if (char *real_path = realpath(exe_path, nullptr)) {272      std::string ret = std::string(real_path);273      free(real_path);274      return ret;275    }276#else277    char real_path[PATH_MAX];278    if (realpath(exe_path, real_path))279      return std::string(real_path);280#endif281  }282  // Fall back to the classical detection.283  if (getprogpath(exe_path, argv0))284    return exe_path;285#elif defined(__OpenBSD__) || defined(__HAIKU__)286  char exe_path[PATH_MAX];287  // argv[0] only288  if (getprogpath(exe_path, argv0) != NULL)289    return exe_path;290#elif defined(__sun__) && defined(__svr4__)291  char exe_path[PATH_MAX];292  const char *aPath = "/proc/self/execname";293  if (sys::fs::exists(aPath)) {294    int fd = open(aPath, O_RDONLY);295    if (fd == -1)296      return "";297    if (read(fd, exe_path, sizeof(exe_path)) < 0)298      return "";299    return exe_path;300  }301  // Fall back to the classical detection.302  if (getprogpath(exe_path, argv0) != NULL)303    return exe_path;304#elif defined(__MVS__)305  int token = 0;306  W_PSPROC buf;307  char exe_path[PS_PATHBLEN];308  pid_t pid = getpid();309 310  memset(&buf, 0, sizeof(buf));311  buf.ps_pathptr = exe_path;312  buf.ps_pathlen = sizeof(exe_path);313 314  while (true) {315    if ((token = w_getpsent(token, &buf, sizeof(buf))) <= 0)316      break;317    if (buf.ps_pid != pid)318      continue;319    char real_path[PATH_MAX];320    if (realpath(exe_path, real_path))321      return std::string(real_path);322    break; // Found entry, but realpath failed.323  }324#elif defined(HAVE_DLOPEN)325  // Use dladdr to get executable path if available.326  Dl_info DLInfo;327  int err = dladdr(MainAddr, &DLInfo);328  if (err == 0)329    return "";330 331  // If the filename is a symlink, we need to resolve and return the location of332  // the actual executable.333  char link_path[PATH_MAX];334  if (realpath(DLInfo.dli_fname, link_path))335    return link_path;336#else337#error GetMainExecutable is not implemented on this host yet.338#endif339  return "";340}341 342TimePoint<> basic_file_status::getLastAccessedTime() const {343  return toTimePoint(fs_st_atime, fs_st_atime_nsec);344}345 346TimePoint<> basic_file_status::getLastModificationTime() const {347  return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);348}349 350UniqueID file_status::getUniqueID() const {351  return UniqueID(fs_st_dev, fs_st_ino);352}353 354uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }355 356ErrorOr<space_info> disk_space(const Twine &Path) {357  struct STATVFS Vfs;358  if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))359    return errnoAsErrorCode();360  auto FrSize = STATVFS_F_FRSIZE(Vfs);361  space_info SpaceInfo;362  SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;363  SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;364  SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;365  return SpaceInfo;366}367 368std::error_code current_path(SmallVectorImpl<char> &result) {369  result.clear();370 371  const char *pwd = ::getenv("PWD");372  llvm::sys::fs::file_status PWDStatus, DotStatus;373  if (pwd && llvm::sys::path::is_absolute(pwd) &&374      !llvm::sys::fs::status(pwd, PWDStatus) &&375      !llvm::sys::fs::status(".", DotStatus) &&376      PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {377    result.append(pwd, pwd + strlen(pwd));378    return std::error_code();379  }380 381  result.resize_for_overwrite(PATH_MAX);382 383  while (true) {384    if (::getcwd(result.data(), result.size()) == nullptr) {385      // See if there was a real error.386      if (errno != ENOMEM) {387        result.clear();388        return errnoAsErrorCode();389      }390      // Otherwise there just wasn't enough space.391      result.resize_for_overwrite(result.capacity() * 2);392    } else {393      break;394    }395  }396 397  result.truncate(strlen(result.data()));398  return std::error_code();399}400 401std::error_code set_current_path(const Twine &path) {402  SmallString<128> path_storage;403  StringRef p = path.toNullTerminatedStringRef(path_storage);404 405  if (::chdir(p.begin()) == -1)406    return errnoAsErrorCode();407 408  return std::error_code();409}410 411std::error_code create_directory(const Twine &path, bool IgnoreExisting,412                                 perms Perms) {413  SmallString<128> path_storage;414  StringRef p = path.toNullTerminatedStringRef(path_storage);415 416  if (::mkdir(p.begin(), Perms) == -1) {417    if (errno != EEXIST || !IgnoreExisting)418      return errnoAsErrorCode();419  }420 421  return std::error_code();422}423 424// Note that we are using symbolic link because hard links are not supported by425// all filesystems (SMB doesn't).426std::error_code create_link(const Twine &to, const Twine &from) {427  // Get arguments.428  SmallString<128> from_storage;429  SmallString<128> to_storage;430  StringRef f = from.toNullTerminatedStringRef(from_storage);431  StringRef t = to.toNullTerminatedStringRef(to_storage);432 433  if (::symlink(t.begin(), f.begin()) == -1)434    return errnoAsErrorCode();435 436  return std::error_code();437}438 439std::error_code create_hard_link(const Twine &to, const Twine &from) {440  // Get arguments.441  SmallString<128> from_storage;442  SmallString<128> to_storage;443  StringRef f = from.toNullTerminatedStringRef(from_storage);444  StringRef t = to.toNullTerminatedStringRef(to_storage);445 446  if (::link(t.begin(), f.begin()) == -1)447    return errnoAsErrorCode();448 449  return std::error_code();450}451 452std::error_code remove(const Twine &path, bool IgnoreNonExisting) {453  SmallString<128> path_storage;454  StringRef p = path.toNullTerminatedStringRef(path_storage);455 456  struct stat buf;457  if (lstat(p.begin(), &buf) != 0) {458    if (errno != ENOENT || !IgnoreNonExisting)459      return errnoAsErrorCode();460    return std::error_code();461  }462 463  // Note: this check catches strange situations. In all cases, LLVM should464  // only be involved in the creation and deletion of regular files.  This465  // check ensures that what we're trying to erase is a regular file. It466  // effectively prevents LLVM from erasing things like /dev/null, any block467  // special file, or other things that aren't "regular" files.468  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))469    return make_error_code(errc::operation_not_permitted);470 471  if (::remove(p.begin()) == -1) {472    if (errno != ENOENT || !IgnoreNonExisting)473      return errnoAsErrorCode();474  }475 476  return std::error_code();477}478 479static bool is_local_impl(struct STATVFS &Vfs) {480#if defined(__linux__) || defined(__GNU__) || defined(__managarm__)481#ifndef NFS_SUPER_MAGIC482#define NFS_SUPER_MAGIC 0x6969483#endif484#ifndef SMB_SUPER_MAGIC485#define SMB_SUPER_MAGIC 0x517B486#endif487#ifndef CIFS_MAGIC_NUMBER488#define CIFS_MAGIC_NUMBER 0xFF534D42489#endif490#if defined(__GNU__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 39)))491  switch ((uint32_t)Vfs.__f_type) {492#else493  switch ((uint32_t)Vfs.f_type) {494#endif495  case NFS_SUPER_MAGIC:496  case SMB_SUPER_MAGIC:497  case CIFS_MAGIC_NUMBER:498    return false;499  default:500    return true;501  }502#elif defined(__CYGWIN__)503  // Cygwin doesn't expose this information; would need to use Win32 API.504  return false;505#elif defined(__Fuchsia__)506  // Fuchsia doesn't yet support remote filesystem mounts.507  return true;508#elif defined(__EMSCRIPTEN__)509  // Emscripten doesn't currently support remote filesystem mounts.510  return true;511#elif defined(__HAIKU__)512  // Haiku doesn't expose this information.513  return false;514#elif defined(__sun)515  // statvfs::f_basetype contains a null-terminated FSType name of the mounted516  // target517  StringRef fstype(Vfs.f_basetype);518  // NFS is the only non-local fstype??519  return fstype != "nfs";520#elif defined(_AIX)521  // Call mntctl; try more than twice in case of timing issues with a concurrent522  // mount.523  int Ret;524  size_t BufSize = 2048u;525  std::unique_ptr<char[]> Buf;526  int Tries = 3;527  while (Tries--) {528    Buf = std::make_unique<char[]>(BufSize);529    Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());530    if (Ret != 0)531      break;532    BufSize = *reinterpret_cast<unsigned int *>(Buf.get());533    Buf.reset();534  }535 536  if (Ret == -1)537    // There was an error; "remote" is the conservative answer.538    return false;539 540  // Look for the correct vmount entry.541  char *CurObjPtr = Buf.get();542  while (Ret--) {543    struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);544    static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),545                  "fsid length mismatch");546    if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)547      return (Vp->vmt_flags & MNT_REMOTE) == 0;548 549    CurObjPtr += Vp->vmt_length;550  }551 552  // vmount entry not found; "remote" is the conservative answer.553  return false;554#elif defined(__MVS__)555  // The file system can have an arbitrary structure on z/OS; must go with the556  // conservative answer.557  return false;558#else559  return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);560#endif561}562 563std::error_code is_local(const Twine &Path, bool &Result) {564  struct STATVFS Vfs;565  if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))566    return errnoAsErrorCode();567 568  Result = is_local_impl(Vfs);569  return std::error_code();570}571 572std::error_code is_local(int FD, bool &Result) {573  struct STATVFS Vfs;574  if (::FSTATVFS(FD, &Vfs))575    return errnoAsErrorCode();576 577  Result = is_local_impl(Vfs);578  return std::error_code();579}580 581std::error_code rename(const Twine &from, const Twine &to) {582  // Get arguments.583  SmallString<128> from_storage;584  SmallString<128> to_storage;585  StringRef f = from.toNullTerminatedStringRef(from_storage);586  StringRef t = to.toNullTerminatedStringRef(to_storage);587 588  if (::rename(f.begin(), t.begin()) == -1)589    return errnoAsErrorCode();590 591  return std::error_code();592}593 594std::error_code resize_file(int FD, uint64_t Size) {595  // Use ftruncate as a fallback. It may or may not allocate space. At least on596  // OS X with HFS+ it does.597  if (::ftruncate(FD, Size) == -1)598    return errnoAsErrorCode();599 600  return std::error_code();601}602 603std::error_code resize_file_sparse(int FD, uint64_t Size) {604  // On Unix, this is the same as `resize_file`.605  return resize_file(FD, Size);606}607 608static int convertAccessMode(AccessMode Mode) {609  switch (Mode) {610  case AccessMode::Exist:611    return F_OK;612  case AccessMode::Write:613    return W_OK;614  case AccessMode::Execute:615    return R_OK | X_OK; // scripts also need R_OK.616  }617  llvm_unreachable("invalid enum");618}619 620std::error_code access(const Twine &Path, AccessMode Mode) {621  SmallString<128> PathStorage;622  StringRef P = Path.toNullTerminatedStringRef(PathStorage);623 624  if (::access(P.begin(), convertAccessMode(Mode)) == -1)625    return errnoAsErrorCode();626 627  if (Mode == AccessMode::Execute) {628    // Don't say that directories are executable.629    struct stat buf;630    if (0 != stat(P.begin(), &buf))631      return errc::permission_denied;632    if (!S_ISREG(buf.st_mode))633      return errc::permission_denied;634  }635 636  return std::error_code();637}638 639bool can_execute(const Twine &Path) {640  return !access(Path, AccessMode::Execute);641}642 643bool equivalent(file_status A, file_status B) {644  assert(status_known(A) && status_known(B));645  return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino;646}647 648std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {649  file_status fsA, fsB;650  if (std::error_code ec = status(A, fsA))651    return ec;652  if (std::error_code ec = status(B, fsB))653    return ec;654  result = equivalent(fsA, fsB);655  return std::error_code();656}657 658static void expandTildeExpr(SmallVectorImpl<char> &Path) {659  StringRef PathStr(Path.begin(), Path.size());660  if (PathStr.empty() || !PathStr.starts_with("~"))661    return;662 663  PathStr = PathStr.drop_front();664  StringRef Expr =665      PathStr.take_until([](char c) { return path::is_separator(c); });666  StringRef Remainder = PathStr.substr(Expr.size() + 1);667  SmallString<128> Storage;668  if (Expr.empty()) {669    // This is just ~/..., resolve it to the current user's home dir.670    if (!path::home_directory(Storage)) {671      // For some reason we couldn't get the home directory.  Just exit.672      return;673    }674 675    // Overwrite the first character and insert the rest.676    Path[0] = Storage[0];677    Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());678    return;679  }680 681  // This is a string of the form ~username/, look up this user's entry in the682  // password database.683  std::unique_ptr<char[]> Buf;684  long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);685  if (BufSize <= 0)686    BufSize = 16384;687  Buf = std::make_unique<char[]>(BufSize);688  struct passwd Pwd;689  std::string User = Expr.str();690  struct passwd *Entry = nullptr;691  getpwnam_r(User.c_str(), &Pwd, Buf.get(), BufSize, &Entry);692 693  if (!Entry || !Entry->pw_dir) {694    // Unable to look up the entry, just return back the original path.695    return;696  }697 698  Storage = Remainder;699  Path.clear();700  Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));701  llvm::sys::path::append(Path, Storage);702}703 704void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {705  dest.clear();706  if (path.isTriviallyEmpty())707    return;708 709  path.toVector(dest);710  expandTildeExpr(dest);711}712 713static file_type typeForMode(mode_t Mode) {714  if (S_ISDIR(Mode))715    return file_type::directory_file;716  else if (S_ISREG(Mode))717    return file_type::regular_file;718  else if (S_ISBLK(Mode))719    return file_type::block_file;720  else if (S_ISCHR(Mode))721    return file_type::character_file;722  else if (S_ISFIFO(Mode))723    return file_type::fifo_file;724  else if (S_ISSOCK(Mode))725    return file_type::socket_file;726  else if (S_ISLNK(Mode))727    return file_type::symlink_file;728  return file_type::type_unknown;729}730 731static std::error_code fillStatus(int StatRet, const struct stat &Status,732                                  file_status &Result) {733  if (StatRet != 0) {734    std::error_code EC = errnoAsErrorCode();735    if (EC == errc::no_such_file_or_directory)736      Result = file_status(file_type::file_not_found);737    else738      Result = file_status(file_type::status_error);739    return EC;740  }741 742  uint32_t atime_nsec, mtime_nsec;743#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)744  atime_nsec = Status.st_atimespec.tv_nsec;745  mtime_nsec = Status.st_mtimespec.tv_nsec;746#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)747  atime_nsec = Status.st_atim.tv_nsec;748  mtime_nsec = Status.st_mtim.tv_nsec;749#else750  atime_nsec = mtime_nsec = 0;751#endif752 753  perms Perms = static_cast<perms>(Status.st_mode) & all_perms;754  Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,755                       Status.st_nlink, Status.st_ino, Status.st_atime,756                       atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,757                       Status.st_gid, Status.st_size);758 759  return std::error_code();760}761 762std::error_code status(const Twine &Path, file_status &Result, bool Follow) {763  SmallString<128> PathStorage;764  StringRef P = Path.toNullTerminatedStringRef(PathStorage);765 766  struct stat Status;767  int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);768  return fillStatus(StatRet, Status, Result);769}770 771std::error_code status(int FD, file_status &Result) {772  struct stat Status;773  int StatRet = ::fstat(FD, &Status);774  return fillStatus(StatRet, Status, Result);775}776 777unsigned getUmask() {778  // Chose arbitary new mask and reset the umask to the old mask.779  // umask(2) never fails so ignore the return of the second call.780  unsigned Mask = ::umask(0);781  (void)::umask(Mask);782  return Mask;783}784 785std::error_code setPermissions(const Twine &Path, perms Permissions) {786  SmallString<128> PathStorage;787  StringRef P = Path.toNullTerminatedStringRef(PathStorage);788 789  if (::chmod(P.begin(), Permissions))790    return errnoAsErrorCode();791  return std::error_code();792}793 794std::error_code setPermissions(int FD, perms Permissions) {795  if (::fchmod(FD, Permissions))796    return errnoAsErrorCode();797  return std::error_code();798}799 800std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,801                                                 TimePoint<> ModificationTime) {802#if defined(HAVE_FUTIMENS)803  timespec Times[2];804  Times[0] = sys::toTimeSpec(AccessTime);805  Times[1] = sys::toTimeSpec(ModificationTime);806  if (::futimens(FD, Times))807    return errnoAsErrorCode();808  return std::error_code();809#elif defined(HAVE_FUTIMES)810  timeval Times[2];811  Times[0] = sys::toTimeVal(812      std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));813  Times[1] =814      sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(815          ModificationTime));816  if (::futimes(FD, Times))817    return errnoAsErrorCode();818  return std::error_code();819#elif defined(__MVS__)820  attrib_t Attr;821  memset(&Attr, 0, sizeof(Attr));822  Attr.att_atimechg = 1;823  Attr.att_atime = sys::toTimeT(AccessTime);824  Attr.att_mtimechg = 1;825  Attr.att_mtime = sys::toTimeT(ModificationTime);826  if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)827    return errnoAsErrorCode();828  return std::error_code();829#else830#warning Missing futimes() and futimens()831  return make_error_code(errc::function_not_supported);832#endif833}834 835std::error_code mapped_file_region::init(int FD, uint64_t Offset,836                                         mapmode Mode) {837  assert(Size != 0);838 839  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;840  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);841#if defined(MAP_NORESERVE)842  flags |= MAP_NORESERVE;843#endif844#if defined(__APPLE__)845  //----------------------------------------------------------------------846  // Newer versions of MacOSX have a flag that will allow us to read from847  // binaries whose code signature is invalid without crashing by using848  // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media849  // is mapped we can avoid crashing and return zeroes to any pages we try850  // to read if the media becomes unavailable by using the851  // MAP_RESILIENT_MEDIA flag.  These flags are only usable when mapping852  // with PROT_READ, so take care not to specify them otherwise.853  //----------------------------------------------------------------------854  if (Mode == readonly) {855#if defined(MAP_RESILIENT_CODESIGN)856    flags |= MAP_RESILIENT_CODESIGN;857#endif858#if defined(MAP_RESILIENT_MEDIA)859    flags |= MAP_RESILIENT_MEDIA;860#endif861  }862#endif // #if defined (__APPLE__)863 864  Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);865  if (Mapping == MAP_FAILED)866    return errnoAsErrorCode();867  return std::error_code();868}869 870mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,871                                       uint64_t offset, std::error_code &ec)872    : Size(length), Mode(mode) {873  (void)Mode;874  ec = init(fd, offset, mode);875  if (ec)876    copyFrom(mapped_file_region());877}878 879void mapped_file_region::unmapImpl() {880  if (Mapping)881    ::munmap(Mapping, Size);882}883 884std::error_code mapped_file_region::sync() const {885  if (int Res = ::msync(Mapping, Size, MS_SYNC))886    return std::error_code(Res, std::generic_category());887  return std::error_code();888}889 890void mapped_file_region::dontNeedImpl() {891  assert(Mode == mapped_file_region::readonly);892  if (!Mapping)893    return;894#if defined(__MVS__) || defined(_AIX)895    // If we don't have madvise, or it isn't beneficial, treat this as a no-op.896#elif defined(POSIX_MADV_DONTNEED)897  ::posix_madvise(Mapping, Size, POSIX_MADV_DONTNEED);898#else899  ::madvise(Mapping, Size, MADV_DONTNEED);900#endif901}902 903int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }904 905std::error_code detail::directory_iterator_construct(detail::DirIterState &it,906                                                     StringRef path,907                                                     bool follow_symlinks) {908  SmallString<128> path_null(path);909  DIR *directory = ::opendir(path_null.c_str());910  if (!directory)911    return errnoAsErrorCode();912 913  it.IterationHandle = reinterpret_cast<intptr_t>(directory);914  // Add something for replace_filename to replace.915  path::append(path_null, ".");916  it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);917  return directory_iterator_increment(it);918}919 920std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {921  if (it.IterationHandle)922    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));923  it.IterationHandle = 0;924  it.CurrentEntry = directory_entry();925  return std::error_code();926}927 928static file_type direntType(dirent *Entry) {929  // Most platforms provide the file type in the dirent: Linux/BSD/Mac.930  // The DTTOIF macro lets us reuse our status -> type conversion.931  // Note that while glibc provides a macro to see if this is supported,932  // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the933  // d_type-to-mode_t conversion macro instead.934#if defined(DTTOIF)935  return typeForMode(DTTOIF(Entry->d_type));936#else937  // Other platforms such as Solaris require a stat() to get the type.938  return file_type::type_unknown;939#endif940}941 942std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {943  errno = 0;944  dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));945  if (CurDir == nullptr && errno != 0) {946    return errnoAsErrorCode();947  } else if (CurDir != nullptr) {948    StringRef Name(CurDir->d_name);949    if ((Name.size() == 1 && Name[0] == '.') ||950        (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))951      return directory_iterator_increment(It);952    It.CurrentEntry.replace_filename(Name, direntType(CurDir));953  } else {954    return directory_iterator_destruct(It);955  }956 957  return std::error_code();958}959 960ErrorOr<basic_file_status> directory_entry::status() const {961  file_status s;962  if (auto EC = fs::status(Path, s, FollowSymlinks))963    return EC;964  return s;965}966 967//968// FreeBSD optionally provides /proc/self/fd, but it is incompatible with969// Linux. The thing to use is realpath.970//971#if !defined(__FreeBSD__) && !defined(__OpenBSD__)972#define TRY_PROC_SELF_FD973#endif974 975#if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)976static bool hasProcSelfFD() {977  // If we have a /proc filesystem mounted, we can quickly establish the978  // real name of the file with readlink979  static const bool Result = (::access("/proc/self/fd", R_OK) == 0);980  return Result;981}982#endif983 984static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,985                           FileAccess Access) {986  int Result = 0;987  if (Access == FA_Read)988    Result |= O_RDONLY;989  else if (Access == FA_Write)990    Result |= O_WRONLY;991  else if (Access == (FA_Read | FA_Write))992    Result |= O_RDWR;993 994  // This is for compatibility with old code that assumed OF_Append implied995  // would open an existing file.  See Windows/Path.inc for a longer comment.996  if (Flags & OF_Append)997    Disp = CD_OpenAlways;998 999  if (Disp == CD_CreateNew) {1000    Result |= O_CREAT; // Create if it doesn't exist.1001    Result |= O_EXCL;  // Fail if it does.1002  } else if (Disp == CD_CreateAlways) {1003    Result |= O_CREAT; // Create if it doesn't exist.1004    Result |= O_TRUNC; // Truncate if it does.1005  } else if (Disp == CD_OpenAlways) {1006    Result |= O_CREAT; // Create if it doesn't exist.1007  } else if (Disp == CD_OpenExisting) {1008    // Nothing special, just don't add O_CREAT and we get these semantics.1009  }1010 1011// Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when1012// calling write(). Instead we need to use lseek() to set offset to EOF after1013// open().1014#ifndef __MVS__1015  if (Flags & OF_Append)1016    Result |= O_APPEND;1017#endif1018 1019#ifdef O_CLOEXEC1020  if (!(Flags & OF_ChildInherit))1021    Result |= O_CLOEXEC;1022#endif1023 1024  return Result;1025}1026 1027std::error_code openFile(const Twine &Name, int &ResultFD,1028                         CreationDisposition Disp, FileAccess Access,1029                         OpenFlags Flags, unsigned Mode) {1030  int OpenFlags = nativeOpenFlags(Disp, Flags, Access);1031 1032  SmallString<128> Storage;1033  StringRef P = Name.toNullTerminatedStringRef(Storage);1034  // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal1035  // when open is overloaded, such as in Bionic.1036  auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };1037  if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)1038    return errnoAsErrorCode();1039#ifndef O_CLOEXEC1040  if (!(Flags & OF_ChildInherit)) {1041    int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);1042    (void)r;1043    assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");1044  }1045#endif1046 1047#ifdef __MVS__1048  /* Reason about auto-conversion and file tags. Setting the file tag only1049   * applies if file is opened in write mode:1050   *1051   * Text file:1052   *                  File exists       File created1053   * CD_CreateNew     n/a               conv: on1054   *                                    tag: set 10471055   * CD_CreateAlways  conv: auto        conv: on1056   *                  tag: auto 1047    tag: set 10471057   * CD_OpenAlways    conv: auto        conv: on1058   *                  tag: auto 1047    tag: set 10471059   * CD_OpenExisting  conv: auto        n/a1060   *                  tag: unchanged1061   *1062   * Binary file:1063   *                  File exists       File created1064   * CD_CreateNew     n/a               conv: off1065   *                                    tag: set binary1066   * CD_CreateAlways  conv: off         conv: off1067   *                  tag: auto binary  tag: set binary1068   * CD_OpenAlways    conv: off         conv: off1069   *                  tag: auto binary  tag: set binary1070   * CD_OpenExisting  conv: off         n/a1071   *                  tag: unchanged1072   *1073   * Actions:1074   *   conv: off        -> auto-conversion is turned off1075   *   conv: on         -> auto-conversion is turned on1076   *   conv: auto       -> auto-conversion is turned on if the file is untagged1077   *   tag: set 1047    -> set the file tag to text encoded in 10471078   *   tag: set binary  -> set the file tag to binary1079   *   tag: auto 1047   -> set file tag to 1047 if not set1080   *   tag: auto binary -> set file tag to binary if not set1081   *   tag: unchanged   -> do not care about the file tag1082   *1083   * It is not possible to distinguish between the cases "file exists" and1084   * "file created". In the latter case, the file tag is not set and the file1085   * size is zero. The decision table boils down to:1086   *1087   * the file tag is set if1088   *   - the file is opened for writing1089   *   - the create disposition is not equal to CD_OpenExisting1090   *   - the file tag is not set1091   *   - the file size is zero1092   *1093   * This only applies if the file is a regular file. E.g. enabling1094   * auto-conversion for reading from /dev/null results in error EINVAL when1095   * calling read().1096   *1097   * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when1098   * calling write(). Instead we need to use lseek() to set offset to EOF after1099   * open().1100   */1101  if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)1102    return errnoAsErrorCode();1103  struct stat Stat;1104  if (fstat(ResultFD, &Stat) == -1)1105    return errnoAsErrorCode();1106  if (S_ISREG(Stat.st_mode)) {1107    bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&1108                    !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&1109                    Stat.st_size == 0;1110    if (Flags & OF_Text) {1111      if (auto EC = llvm::enableAutoConversion(ResultFD))1112        return EC;1113      if (DoSetTag) {1114        if (auto EC = llvm::setzOSFileTag(ResultFD, CCSID_IBM_1047, true))1115          return EC;1116      }1117    } else {1118      if (auto EC = llvm::disableAutoConversion(ResultFD))1119        return EC;1120      if (DoSetTag) {1121        if (auto EC = llvm::setzOSFileTag(ResultFD, FT_BINARY, false))1122          return EC;1123      }1124    }1125  }1126#endif1127 1128  return std::error_code();1129}1130 1131Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,1132                             FileAccess Access, OpenFlags Flags,1133                             unsigned Mode) {1134 1135  int FD;1136  std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);1137  if (EC)1138    return errorCodeToError(EC);1139  return FD;1140}1141 1142std::error_code openFileForRead(const Twine &Name, int &ResultFD,1143                                OpenFlags Flags,1144                                SmallVectorImpl<char> *RealPath) {1145  std::error_code EC =1146      openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);1147  if (EC)1148    return EC;1149 1150  // Attempt to get the real name of the file, if the user asked1151  if (!RealPath)1152    return std::error_code();1153  RealPath->clear();1154#if defined(F_GETPATH)1155  // When F_GETPATH is availble, it is the quickest way to get1156  // the real path name.1157  char Buffer[PATH_MAX];1158  if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)1159    RealPath->append(Buffer, Buffer + strlen(Buffer));1160#else1161  char Buffer[PATH_MAX];1162#if defined(TRY_PROC_SELF_FD)1163  if (hasProcSelfFD()) {1164    char ProcPath[64];1165    snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);1166    ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));1167    if (CharCount > 0)1168      RealPath->append(Buffer, Buffer + CharCount);1169  } else {1170#endif1171    SmallString<128> Storage;1172    StringRef P = Name.toNullTerminatedStringRef(Storage);1173 1174    // Use ::realpath to get the real path name1175    if (::realpath(P.begin(), Buffer) != nullptr)1176      RealPath->append(Buffer, Buffer + strlen(Buffer));1177#if defined(TRY_PROC_SELF_FD)1178  }1179#endif1180#endif1181  return std::error_code();1182}1183 1184Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,1185                                       SmallVectorImpl<char> *RealPath) {1186  file_t ResultFD;1187  std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);1188  if (EC)1189    return errorCodeToError(EC);1190  return ResultFD;1191}1192 1193file_t getStdinHandle() { return 0; }1194file_t getStdoutHandle() { return 1; }1195file_t getStderrHandle() { return 2; }1196 1197Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {1198#if defined(__APPLE__)1199  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);1200#else1201  size_t Size = Buf.size();1202#endif1203  ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);1204  if (NumRead == -1)1205    return errorCodeToError(errnoAsErrorCode());1206// The underlying operation on these platforms allow opening directories1207// for reading in more cases than other platforms.1208#if defined(__MVS__) || defined(_AIX)1209  struct stat Status;1210  if (fstat(FD, &Status) == -1)1211    return errorCodeToError(errnoAsErrorCode());1212  if (S_ISDIR(Status.st_mode))1213    return errorCodeToError(make_error_code(errc::is_a_directory));1214#endif1215  return NumRead;1216}1217 1218Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,1219                                     uint64_t Offset) {1220#if defined(__APPLE__)1221  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);1222#else1223  size_t Size = Buf.size();1224#endif1225#ifdef HAVE_PREAD1226  ssize_t NumRead =1227      sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);1228#else1229  if (lseek(FD, Offset, SEEK_SET) == -1)1230    return errorCodeToError(errnoAsErrorCode());1231  ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);1232#endif1233  if (NumRead == -1)1234    return errorCodeToError(errnoAsErrorCode());1235  return NumRead;1236}1237 1238std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,1239                            LockKind Kind) {1240  auto Start = std::chrono::steady_clock::now();1241  auto End = Start + Timeout;1242  do {1243    struct flock Lock;1244    memset(&Lock, 0, sizeof(Lock));1245    switch (Kind) {1246    case LockKind::Exclusive:1247      Lock.l_type = F_WRLCK;1248      break;1249    case LockKind::Shared:1250      Lock.l_type = F_RDLCK;1251      break;1252    }1253    Lock.l_whence = SEEK_SET;1254    Lock.l_start = 0;1255    Lock.l_len = 0;1256    if (::fcntl(FD, F_SETLK, &Lock) != -1)1257      return std::error_code();1258    int Error = errno;1259    if (Error != EACCES && Error != EAGAIN)1260      return std::error_code(Error, std::generic_category());1261    if (Timeout.count() == 0)1262      break;1263    usleep(1000);1264  } while (std::chrono::steady_clock::now() < End);1265  return make_error_code(errc::no_lock_available);1266}1267 1268std::error_code lockFile(int FD, LockKind Kind) {1269  struct flock Lock;1270  memset(&Lock, 0, sizeof(Lock));1271  switch (Kind) {1272  case LockKind::Exclusive:1273    Lock.l_type = F_WRLCK;1274    break;1275  case LockKind::Shared:1276    Lock.l_type = F_RDLCK;1277    break;1278  }1279  Lock.l_whence = SEEK_SET;1280  Lock.l_start = 0;1281  Lock.l_len = 0;1282  if (::fcntl(FD, F_SETLKW, &Lock) != -1)1283    return std::error_code();1284  return errnoAsErrorCode();1285}1286 1287std::error_code unlockFile(int FD) {1288  struct flock Lock;1289  Lock.l_type = F_UNLCK;1290  Lock.l_whence = SEEK_SET;1291  Lock.l_start = 0;1292  Lock.l_len = 0;1293  if (::fcntl(FD, F_SETLK, &Lock) != -1)1294    return std::error_code();1295  return errnoAsErrorCode();1296}1297 1298std::error_code closeFile(file_t &F) {1299  file_t TmpF = F;1300  F = kInvalidFile;1301  return Process::SafelyCloseFileDescriptor(TmpF);1302}1303 1304template <typename T>1305static std::error_code remove_directories_impl(const T &Entry,1306                                               bool IgnoreErrors) {1307  std::error_code EC;1308  directory_iterator Begin(Entry, EC, false);1309  directory_iterator End;1310  while (Begin != End) {1311    auto &Item = *Begin;1312    ErrorOr<basic_file_status> st = Item.status();1313    if (st) {1314      if (is_directory(*st)) {1315        EC = remove_directories_impl(Item, IgnoreErrors);1316        if (EC && !IgnoreErrors)1317          return EC;1318      }1319 1320      EC = fs::remove(Item.path(), true);1321      if (EC && !IgnoreErrors)1322        return EC;1323    } else if (!IgnoreErrors) {1324      return st.getError();1325    }1326 1327    Begin.increment(EC);1328    if (EC && !IgnoreErrors)1329      return EC;1330  }1331  return std::error_code();1332}1333 1334std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {1335  auto EC = remove_directories_impl(path, IgnoreErrors);1336  if (EC && !IgnoreErrors)1337    return EC;1338  EC = fs::remove(path, true);1339  if (EC && !IgnoreErrors)1340    return EC;1341  return std::error_code();1342}1343 1344std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,1345                          bool expand_tilde) {1346  dest.clear();1347  if (path.isTriviallyEmpty())1348    return std::error_code();1349 1350  if (expand_tilde) {1351    SmallString<128> Storage;1352    path.toVector(Storage);1353    expandTildeExpr(Storage);1354    return real_path(Storage, dest, false);1355  }1356 1357  SmallString<128> Storage;1358  StringRef P = path.toNullTerminatedStringRef(Storage);1359  char Buffer[PATH_MAX];1360  if (::realpath(P.begin(), Buffer) == nullptr)1361    return errnoAsErrorCode();1362  dest.append(Buffer, Buffer + strlen(Buffer));1363  return std::error_code();1364}1365 1366std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {1367  auto FChown = [&]() { return ::fchown(FD, Owner, Group); };1368  // Retry if fchown call fails due to interruption.1369  if ((sys::RetryAfterSignal(-1, FChown)) < 0)1370    return errnoAsErrorCode();1371  return std::error_code();1372}1373 1374} // end namespace fs1375 1376namespace path {1377 1378bool home_directory(SmallVectorImpl<char> &result) {1379  std::unique_ptr<char[]> Buf;1380  char *RequestedDir = getenv("HOME");1381  if (!RequestedDir) {1382    long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);1383    if (BufSize <= 0)1384      BufSize = 16384;1385    Buf = std::make_unique<char[]>(BufSize);1386    struct passwd Pwd;1387    struct passwd *pw = nullptr;1388    getpwuid_r(getuid(), &Pwd, Buf.get(), BufSize, &pw);1389    if (pw && pw->pw_dir)1390      RequestedDir = pw->pw_dir;1391  }1392  if (!RequestedDir)1393    return false;1394 1395  result.clear();1396  result.append(RequestedDir, RequestedDir + strlen(RequestedDir));1397  return true;1398}1399 1400static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {1401#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)1402  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.1403  // macros defined in <unistd.h> on darwin >= 91404  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;1405  size_t ConfLen = confstr(ConfName, nullptr, 0);1406  if (ConfLen > 0) {1407    do {1408      Result.resize(ConfLen);1409      ConfLen = confstr(ConfName, Result.data(), Result.size());1410    } while (ConfLen > 0 && ConfLen != Result.size());1411 1412    if (ConfLen > 0) {1413      assert(Result.back() == 0);1414      Result.pop_back();1415      return true;1416    }1417 1418    Result.clear();1419  }1420#endif1421  return false;1422}1423 1424bool user_config_directory(SmallVectorImpl<char> &result) {1425#ifdef __APPLE__1426  // Mac: ~/Library/Preferences/1427  if (home_directory(result)) {1428    append(result, "Library", "Preferences");1429    return true;1430  }1431#else1432  // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:1433  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html1434  if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {1435    result.clear();1436    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));1437    return true;1438  }1439#endif1440  // Fallback: ~/.config1441  if (!home_directory(result)) {1442    return false;1443  }1444  append(result, ".config");1445  return true;1446}1447 1448bool cache_directory(SmallVectorImpl<char> &result) {1449#ifdef __APPLE__1450  if (getDarwinConfDir(false /*tempDir*/, result)) {1451    return true;1452  }1453#else1454  // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:1455  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html1456  if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {1457    result.clear();1458    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));1459    return true;1460  }1461#endif1462  if (!home_directory(result)) {1463    return false;1464  }1465  append(result, ".cache");1466  return true;1467}1468 1469static const char *getEnvTempDir() {1470  // Check whether the temporary directory is specified by an environment1471  // variable.1472  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};1473  for (const char *Env : EnvironmentVariables) {1474    if (const char *Dir = std::getenv(Env))1475      return Dir;1476  }1477 1478  return nullptr;1479}1480 1481static const char *getDefaultTempDir(bool ErasedOnReboot) {1482#ifdef P_tmpdir1483  if ((bool)P_tmpdir)1484    return P_tmpdir;1485#endif1486 1487  if (ErasedOnReboot)1488    return "/tmp";1489  return "/var/tmp";1490}1491 1492void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {1493  Result.clear();1494 1495  if (ErasedOnReboot) {1496    // There is no env variable for the cache directory.1497    if (const char *RequestedDir = getEnvTempDir()) {1498      Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));1499      return;1500    }1501  }1502 1503  if (getDarwinConfDir(ErasedOnReboot, Result))1504    return;1505 1506  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);1507  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));1508}1509 1510} // end namespace path1511 1512namespace fs {1513 1514#ifdef __APPLE__1515/// This implementation tries to perform an APFS CoW clone of the file,1516/// which can be much faster and uses less space.1517/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the1518/// file descriptor variant of this function still uses the default1519/// implementation.1520std::error_code copy_file(const Twine &From, const Twine &To) {1521  std::string FromS = From.str();1522  std::string ToS = To.str();1523#if __has_builtin(__builtin_available)1524  if (__builtin_available(macos 10.12, *)) {1525    // Optimistically try to use clonefile() and handle errors, rather than1526    // calling stat() to see if it'll work.1527    //1528    // Note: It's okay if From is a symlink. In contrast to the behaviour of1529    // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the1530    // symlink itself) unless the flag CLONE_NOFOLLOW is passed.1531    if (!clonefile(FromS.c_str(), ToS.c_str(), 0))1532      return std::error_code();1533 1534    auto Errno = errno;1535    switch (Errno) {1536    case EEXIST:  // To already exists.1537    case ENOTSUP: // Device does not support cloning.1538    case EXDEV:   // From and To are on different devices.1539      break;1540    default:1541      // Anything else will also break copyfile().1542      return std::error_code(Errno, std::generic_category());1543    }1544 1545    // TODO: For EEXIST, profile calling fs::generateUniqueName() and1546    // clonefile() in a retry loop (then rename() on success) before falling1547    // back to copyfile(). Depending on the size of the file this could be1548    // cheaper.1549  }1550#endif1551  if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))1552    return std::error_code();1553  return errnoAsErrorCode();1554}1555#endif // __APPLE__1556 1557} // end namespace fs1558 1559} // end namespace sys1560} // end namespace llvm1561